diff --git a/.claude/skills/orca-mcp/SKILL.md b/.claude/skills/orca-mcp/SKILL.md index 4da8350dd9..258cdbd5bf 100644 --- a/.claude/skills/orca-mcp/SKILL.md +++ b/.claude/skills/orca-mcp/SKILL.md @@ -1,6 +1,6 @@ --- name: orca-mcp -description: "Drive a running OrcaSlicer through its MCP server - reproduce a GitHub issue, capture before/after screenshots, script deterministic GUI steps. Use when you need to run the app and see or interact with it." +description: "Drive a running OrcaSlicer through its MCP server - reproduce a GitHub issue, capture before/after screenshots, script deterministic GUI steps, build parts in the Design (CAD) tab. Use when you need to run the app and see or interact with it." --- # Driving OrcaSlicer through its MCP server @@ -39,6 +39,8 @@ Other launch options: presets stay identical. - `--port N` sets the port, needed when 13619 is taken, for example by your own OrcaSlicer with MCP enabled. +- `--cad` turns the Design (CAD) tab on, which `cad_call` needs. The app reads that setting only at + startup, so pass it on the launch, also when you reuse a datadir. - Arguments after `--` go to the app. - `tools/mcp/orca_mcp.py stop` ends the app and its Xvfb. @@ -71,24 +73,72 @@ You can talk to the app in two ways: with `select_preset {"type": "printer", "name": ""}`; filaments take `filament_slot`. Find setting keys with `get_settings {"query": "seam"}`, then change them with `set_settings {"scope": "print", "values": {"wall_loops": 3, "sparse_infill_density": "15%"}}`. - For per-object overrides, use `"scope": "object", "object": 0`. + For per-object overrides, use `"scope": "object", "object": 0`. "Settings, presets and + calibration" below covers object filaments, saving and comparing presets, the project's and the + plates' own settings, preferences and calibration tests. 5. Do the steps, in this order of preference: typed tools, then `list_actions {"query": "arrange"}` with `run_action {"id": "..."}`, then the GUI tools. A Speed Dial command with a path param skips its file dialog: `run_action {"id": "orca_command:export_stl:orca", "param": "{\"path\": \"/abs/x.stl\", \"overwrite\": true}"}`. -6. Slice with `slice {}`. Look at `status` and at `plates[].outcome`: `ok` (with print time and - filament), `error`, `cancelled`, `empty` or `skipped`. + A shape takes its size the same way, with nothing selected: + `run_action {"id": "orca_command:add_primitive_cube:orca", "param": "40 40 10"}`. Place it with + `transform`: `translate`, `rotate`, `scale`, `size` (`[80, null, null]` keeps the proportions), + `plate` to move it to another plate, or `volume` to move one part instead of the object. The + object stays on the bed and on the plate it lands on, as after a move in the 3D view. + Add a part, negative part, modifier or support blocker/enforcer to an object with `add_part + {"object": 0, "type": "negative", "shape": "cylinder", "size": [6.2, 3.2], "position": [128, 128, + 1.6]}` (`position` is the part's centre on the bed), or `"path"` for a model file. Add parts before + instances: an object with several is refused. + The object list's menu commands act on what `select` picked: `obj_type_modifier` (and `_part`, + `_negative`, `_support_blocker`, `_support_enforcer`, `_precise_seam`) after `select {"volumes": + [[0, 1]]}`; `obj_rename` with the name as param; `obj_set_instances` with the total count; + `obj_instances_to_objects`, `obj_assemble` (two or more objects); `obj_order_by_height` (param + `all` for every plate). Choosing the order objects already have reverses it, so read the reply's + `order` and `descending`. Indices change after these; list objects again. + Arrange with `arrange {}` (every unlocked plate), `arrange {"plates": 1, "spacing": 10, + "rotate": false}` (one plate; the options stay saved, as in the Arrange options panel) or + `arrange {"fill": 0}` (fill object 0's plate with instances of it). It waits for the job; list + objects again afterwards, since an arrange may reorder them. Check placement with + `list_objects`: per instance `bbox` and `mirrored`, per part `position`, `bbox` and + `scaled_volume` on the bed (instance 0) and the `filament` it prints with. + Height range modifiers: `set_layer_ranges {"object": 0, "layer_config_ranges": [{"min_z": 0, + "max_z": 15, "values": {"layer_height": 0.28}}, {"min_z": 15, "max_z": 60, "values": + {"sparse_infill_density": "25%", "extruder": 2}}]}` replaces all of them (`[]` removes them); + ranges may touch but not overlap. `list_objects` shows them as `layer_config_ranges`. + Variable layer height: `set_layer_height_profile {"object": 0, "action": "adaptive", "quality": + 0.5}`, then `"smooth"` (`radius`, `keep_min`) or `"reset"`; `list_objects` shows the result as + `layer_height_profile` (point count and extreme heights). Inside a height range Adaptive keeps the + range's `layer_height`, and once an object has a profile it decides the layer heights. +6. Slice with `slice {}`. Look at `status` and at `plates[].outcome`: `ok`, `error`, `cancelled`, + `empty` or `skipped`. An `ok` plate carries the print time, `filament_g`/`filament_m` with the + flush, `layers`, `max_z`, `filament_changes`, and `filaments[i]` (slot i + 1) with its + `model_g`, `support_g`, `flush_g` and `tower_g`, so grams per colour or the purge waste need no + G-code or legend. Read the legend's numbers with `get_preview {"include": ["features", "layers", + "objects", "view"]}`: time and grams per feature type, per-layer Z, height and time (paged), + grams per object, and the colour ranges (highest volumetric flow, shortest layer time). + Layer G-codes go on the sliced layers, as the Preview layer slider's menu places them: + `set_layer_gcode {"add": [{"layer": 26, "type": "pause"}, {"z": 10.2, "type": "custom", "gcode": + "M104 S215"}, {"layer": 60, "type": "change_filament", "filament": 2}]}` (also `remove` by layer or + z, and `clear`). `layer` is 1-based as the slider numbers it, `z` the layer whose top is at or above + it; the reply lists the plate's codes with both. Slice again before exporting. 7. Point the view: `set_view {"tab": "preview", "camera": "iso", "layer": 40, "view_type": "feature_type"}`. - Use `"camera": "fit_objects"` to frame the model. + Use `"camera": "fit_objects"` to frame the model. `"layer_z": 3.2` shows up to the layer that + covers that height (where a custom G-code at 3.2 mm goes); `"legend": {"Sparse infill": false, + "travel": true}` hides or shows legend rows, named as `get_preview` lists them. A `view_type` is + picked as in the legend's combo, so Line Type shows every feature type again: give `legend` in + the same call to hide some. `get_state.preview` reads back the view type and the layer range + with its Z. 8. Take a screenshot: `screenshot {"target": "canvas", "save_path": "/abs/work/before.png", "overwrite": true}`. Use `"target": "window"` for the whole UI, `"dialog"` for the topmost modal, and a widget's ref or locator (`{"label": "Slice plate"}`) for one widget or a window that is not modal. The reply carries a scaled-down image; open the full-size PNG with Read to look closer. 9. Save the session as a script with `export_script {"path": "/abs/work/repro.json"}`. Failed calls - are left out; `export_script {"clear": true}` at the start drops the calls made while you - explored. Now edit the script: + are left out, a job that failed after its reply included. A call whose job is still running is + left out too and named in the reply's `left_out_running`; wait for it and export again. + `export_script {"clear": true}` at the start drops the calls made while you explored. Now edit + the script: - add `expect`s that hold when the bug is fixed, so the script fails before the fix and passes after it; - change the screenshot step's file to `after.png`; @@ -113,9 +163,12 @@ You can talk to the app in two ways: a typed tool that needs no dialog. In a script, put `dialog_auto_answer` first. A file picker's text is its prompt, such as "Choose one or more files", not the name of the menu item that opened it. - "A modal dialog is open; answer it first" means `get_state.dialogs` lists what is in the way. -- While a slice or G-code export runs, other changes are refused. `wait` for it, or `cancel` it. -- Before a screenshot after arrange, orient or anything else that runs in the background, call - `wait {"for": "idle"}`. +- While an operation runs (a slice, an export, or a background job such as an arrange that a call + started, however it started), other changes are refused. `wait` for its job, or `cancel` it. A + background job a person started (typing in the Text gizmo) refuses changes too; `wait {"for": + "idle"}`. Reads still answer. +- A Speed Dial command that did nothing (no object selected) is an error, with the reason. +- Before a screenshot after anything else that runs in the background, call `wait {"for": "idle"}`. - Prefer typed tools, then `run_action`, then clicks. Clicks are the most fragile path. - GUI tools act on a `target`: a ref from the latest `ui_snapshot` (`"w12"`), or a locator such as `{"option": "layer_height"}` (a setting field), `{"label": "Slice plate"}`, @@ -126,11 +179,44 @@ You can talk to the app in two ways: `ui_input {"target": {"option": "layer_height"}, "value": "0.16"}`, `ui_key {"keys": "Ctrl+Z"}` (to the topmost dialog when one is open), `dialog_respond {"button": "ok"}`. A target is scrolled into view first, as a person would, so a following screenshot shows it. +- Menus a click or key opens (right-click menus, a button's menu) are never shown: the reply lists + them as `popup_menu`. Run an item with the same call plus `"popup_item": "Add Modifier>Cylinder"`, + for instance `ui_mouse {"action": "click", "button": "right", "at": {"object": 0, "spot": "top"}, + "popup_item": "Add Modifier>Cylinder"}`; the reply says `ran`. A repeated label takes `#2`. A menu + that opened with no input call to list it is in `get_state.closed_menus`. +- Rows of lists, trees and tables are `row` nodes in `ui_snapshot`: the object list (shown while the + sidebar's Process switch is on Objects, `ui_input {"target": {"class": "SwitchButton", "label": + "Process"}, "value": true}`), Compare presets, the object settings table, drop-down lists. Target + one by its last labels: `ui_click {"target": {"row": "Cube>Generic-Cylinder"}}` selects it as a + click does (`"modifiers": ["ctrl"]` adds it), `"column": "Printable"` acts on that cell, `"button": + "right"` with `popup_item` runs its menu, `ui_input ... "value": true` ticks its checkbox. Shown + popups (the print button's menu, an open drop-down list) follow their window in `ui_snapshot`; + `"root": "popup"` lists only them. +- Plate icons in the Prepare view are targets too: `ui_click {"target": {"plate_icon": "lock", + "plate": 1}}` (`plate`, `delete`, `orient`, `arrange`, `lock`, `settings`, `name`, + `move_to_front`, `filament_map`, `imex_mode`; plates count from 0). Lock replies `locked`, arrange + and orient wait for their job (`done`), settings replies the Plate Settings dialog it opened, and + `"button": "right"` on `"plate"` lists the plate menu (`popup_item` runs one of its items). +- `webview_eval` runs in a modal dialog's page only for the setup wizard and the preset bundle + dialogs (`run_action` ids `orca_command:help_setup_wizard:orca`, `orca_command:preset_bundle:orca`, + with `"await": false` in a script); without a target it uses that dialog's + web view. Commit such a page by clicking its own button from the script: `dialog_respond` only + closes the dialog, and the reply says `closed: true` when the script closed it. - Refs go stale when the UI changes, and after a language change. Take a new snapshot (narrowed with `"query"`) before each GUI action. Scripts store locators, not refs. - `dialog_auto_answer {"rules": [{"match": "", "button": "no"}]}` replaces the rules your - session set before, and an empty list clears them. Inside a script, the rules last until the - script ends. `get_state.auto_answer_rules` lists the rules in force, with how often each answered. + session set before, and an empty list clears them. It presses a wx dialog's button as + `dialog_respond` does (Transfer keeps the edits), and answers a native one unseen. Inside a + script, the rules last until the script ends. `get_state.auto_answer_rules` lists the rules in + force, with how often each answered. +- To upload to a print host (OctoPrint, Moonraker, PrusaLink…), set `host_type` and `print_host` with + `set_settings {"scope": "printer"}` (and `"bbl_use_printhost": true` on a Bambu printer), then + `run_action {"id": "orca_command:send_gcode:orca"}` opens the Send dialog: set the name with + `ui_input {"target": {"class": "wxTextCtrl", "within": "Send G-code to printer host"}, "value": + "part.gcode", "submit": false}`, keeping the suffix it proposes (`.gcode.3mf` when the printer's + `use_3mf` is on, or it asks to confirm), and press `dialog_respond {"button": "Upload"}` (or + "Upload and Print"). The upload runs in the background: poll `get_state.uploads` until its row reads + `completed` or `error`; an error also opens a dialog to close with `dialog_respond`. - Paths are absolute. Output directories must exist, and an existing file is replaced only with `"overwrite": true`. In a `run_action` param, pass the JSON string `{"path": …, "overwrite": true}`. @@ -138,6 +224,55 @@ You can talk to the app in two ways: `/mcp-launch.log`. - Never point `--datadir` at your real OrcaSlicer profile. +## Settings, presets and calibration + +`tools/mcp/tests/presets.json`, `multicolor.json`, `plates.json` and `calibration.json` use each of +these; copy their steps. + +- Object and part overrides take only the keys the object list's Add Settings menu offers there + (region keys for a part or modifier); others, such as `print_sequence`, are refused. `"extruder": 2` + sets the object's filament (`"scope": "volume"` a part's) and leaves the selection alone. + `get_settings` gives each override's `effective` value and its `source`. +- A value whose meta lists `variants` (one entry per nozzle variant, as most X1C speeds and + temperatures have) takes a single number for the entries in use (`meta.active`), as the tab does; + `{"index": i, "value": 250}` sets another entry and an array sets them all. + `set_settings` replies with every key it `changed`, including the app's own adjustments. +- `get_settings {"compare": ":saved"}` lists the unsaved edits (`":parent"` or a preset name compares + with that preset), and `"preset"` reads a preset that is not selected. A `null` value takes a + preset key back to its saved value (`"reset_to": "parent"`: the parent's). +- Save tuned settings with `save_preset {"type": "filament", "name": "My PLA"}` (`"overwrite": true` + replaces a preset that exists, as on a rerun); to keep only some edits, first + `set_settings {"scope": "filament", "reset_all": true, "values": {...}}`. Remove presets you made + with `delete_preset {"type": "filament", "name": "My PLA"}` (a printer must be selected first). +- With unsaved edits, `select_preset` opens the Transfer-or-discard prompt unless you pass + `"changes": "transfer"` or `"discard"` (with several filament slots a slot's switch asks nothing, and + the edits stay on the preset the filament tab edits); `new_project {"discard_changes": true, + "changes": "discard"}` also drops modified presets, which it otherwise keeps. +- The project's own settings (plate type, slot colours, flushing volumes and multiplier, prime tower + position per plate, which slots are mixed) use `"scope": "project"`: + `set_settings {"scope": "project", "values": {"filament_colour": {"index": 1, "value": "#000000"}, "curr_bed_type": "Textured PEI Plate"}}`. + Set `flush_volumes_matrix` last: a colour change recalculates it. +- A plate's own settings use `"scope": "plate"` with `plate`: + `set_settings {"scope": "plate", "plate": 1, "values": {"curr_bed_type": "Textured PEI Plate", "print_sequence": "by object", "locked": true, "name": "Batch"}}` + (null goes back to the global setting); `list_plates` reads every plate back, with its layer + G-codes. Add or delete filament slots with `run_action orca_command:filament_add:orca` and + `orca_command:filament_delete:orca` (`param`: the 1-based slot). +- Read preferences with `get_settings {"scope": "preferences", "keys": ["export_statistics"]}`; change + one in the dialog: + `run_action {"id": "orca_command:open_preferences:orca", "param": "developer:export_statistics"}`, + then `ui_input {"target": {"name": "export_statistics", "within": "Preferences"}, "value": true}` + and `dialog_respond {"button": "close"}`. Checkboxes and number or text fields save this way; most + of the dialog's drop-down lists do not. +- Import preset files with `run_action orca_command:import_configs:orca` and a `.json`, `.zip` or + `.orca_*` path (`{"path": ..., "on_conflict": "overwrite"}` replaces presets that exist). + `orca_command:export_config:orca` with a directory still opens the export dialog: tick presets by + `name` with `ui_input`, then press OK with `dialog_respond`. +- Make a calibration test with + `calibrate {"test": "pressure_advance", "method": "pattern", "speeds": [50, 100], "discard_changes": true, "changes": "discard"}` + rather than its dialog; it prints with filament slot 1, and its reply's `result_keys` say where the + measured value goes. To keep that value, `new_project {"discard_changes": true, "changes": "discard"}`, + then `set_settings` it and `save_preset`. + ## Gizmos Every gizmo is driven like a person drives it: its icon, its panel's controls, clicks on the model. @@ -159,11 +294,12 @@ Every gizmo is driven like a person drives it: its icon, its panel's controls, c only draws what shows (Texture Displacement's library) scrolls with `ui_mouse` `wheel` over it. - Click the model at a point instead of a pixel: `ui_mouse {"at": {"object": 0, "spot": "top"}}`, or `"point": [x, y, z]` in the part's mesh coordinates (`"frame": "world"` for scene coordinates; - add `"volume"` for a part). It fails, naming what is in the way, when the point is hidden, below - the bed or cut away; turn the camera with `set_view`. `"check": "point"` skips that, for a point - that is not on the surface (a cut plane). Strokes: `"action": "drag"` with `"path"` and `"to"` - points. `"modifiers": ["shift"]` holds Shift as a key (Measure's point picking); `"button": - "right"` paints blockers or erases. + add `"volume"` for a part; modifiers and negative parts too). It fails, naming what is in the way, + when the point is hidden, below the bed or cut away; turn the camera with `set_view` (from below, + the bed hides nothing). `"check": "point"` skips that, for a point that is not on the surface (a cut + plane). Either way it fails when the point lies under a panel or notification, which would take the + click. Strokes: `"action": "drag"` with `"path"` and `"to"` points. `"modifiers": ["shift"]` holds + Shift as a key (Measure's point picking); `"button": "right"` paints blockers or erases. - The panel's fields set grabber values (Position, rotation, scale, cut height); grabbers are not dragged. File pickers inside a gizmo: `gizmo_file` (`svg_change`, `svg_save_as`, `texture_import`); add an SVG with `run_action add_primitive_svg` and a path. @@ -173,6 +309,57 @@ Every gizmo is driven like a person drives it: its icon, its panel's controls, c `triangles`, `mesh_volume`, `text`, `svg`; per object `brim_ears`. After Simplify or a texture preview, `wait {"for": "idle"}` first. +## Design tab (CAD) + +Launch with `--cad`. Every call is `cad_call {"method": "", "params": {...}}`, and +`tools/mcp/tests/cad_*.json` has working examples of each method; copy their steps. + +- Look up a method's params with `cad_call {"method": "describe_tools", "params": {"method": ["extrude", "hole"]}}` + or `{"query": "sketch"}`, not the whole list. `describe_scene` lists the features, bodies, + variables, undo depth and `modeling_origin`. +- Base planes `"XY"`, `"XZ"` and `"YZ"` pass through `modeling_origin` (the bed centre), for sketches + and features alike, so sketch and feature coordinates are offsets from it. `{"datum": i}` is a + Plane feature, `{"body": b, "face": f}` a planar face. Replies carry the `frame` used. + `query_topology`, `measure` and bounding boxes are in world coordinates. +- Sketch to solid: `sketch_begin {"plane": "XY"}`, then `sketch_add` with `rect`, `entities` (lines, + arcs, circles) or a shape `type` (`polygon`, `slot`, `ellipse`, `ellipse_arc`, `spline`). Shape + the sketch with `sketch_fillet`, `sketch_chamfer`, `sketch_trim`, `sketch_transform` and + `sketch_constrain`, then `sketch_commit`. Its reply gives `sketch_index` and `closed_loops`. + Then `extrude {"sketch": 0, "distance": 10}` (`"loop": i` for one region; by default it joins the + body the sketch touches) or `revolve {"sketch": 0}` (about its only centerline, or `axis_entity`). + Committing an empty sketch fails and keeps it open; `sketch_cancel` leaves it. +- A call that fails is an error and changes nothing. The methods in `describe_tools`' + `legacy_ok_false` (`fillet`, `chamfer`, `boolean`, `pattern`, `shell` and others) answer + `{"ok": false, "error": …}` instead, so check `ok` after those. +- Face and edge ids from `query_topology` expire when the model rebuilds. Pass back the + `generation` you read them with, or query again before each call that takes one. Its filters + (`kinds`, `edge_kinds`, `direction`, `at_extreme`, `convex`, `adjacency`) find a face or edge + without paging through all of them. Deleting or moving features renumbers features and bodies. +- Holes and threads: `hole`, `hole_styled` and `hole_standard {"designation": "M3"}` take `at`, a + world point or a bore (`{"body": b, "face": f}`) or rim (`{"body": b, "edge": e}`) whose axis they + share, instead of `x`/`y`. `thread {"body": 0, "face": f}` taps a bore with the nearest standard. + `thread`, `sweep` and `loft` can take seconds and return a job: wait for it. +- Read back with `mass_properties {"body": 0}` (volume), `measure` (`min_distance`), + `describe_feature {"feature": i}`, `sketch_describe {"sketch": i}` and `sketch_constraints`. + Edit with `set_feature {"feature": 1, "fields": {"distance": 15}}` (the card's fields, within + `ranges`), `set_variable` and `set_feature_expr`, `feature_delete`, `feature_move`, + `feature_set_enabled`, `feature_rename`, `body_set {"body": 0, "name": …, "color": "#3080ff", + "visible": …}` and `body_delete`. +- `cad_call undo` / `redo` undo the Design history, or the open sketch's; `run_action undo` undoes + Prepare's. +- Hand off with `commit {}` (Commit to Plate; `"mode": "bodies"` makes one object per body, + `"replace": [i]` deletes those Prepare objects in the same undo step), then `list_objects`. + `export_step {"path": …}` writes STEP; `import_step` and `import_mesh` take absolute paths; + `new_design {"discard_changes": true}` starts over. +- `export_script` leaves out failed calls and drops `generation`, so a session replays as is. +- See the design with `set_view {"tab": "design", "camera": "iso"}` (`default` is its Home view, + `fit_selection` frames the pick), then `screenshot {"target": "canvas"}`, which shows the Design + view and its status line. `ui_mouse {"canvas": "design", "x": …, "y": …}` clicks the view at + pixels (a left click picks, a right click lists the offer's verbs as `popup_menu`; model points + are Prepare's), and `ui_key` reaches the tab's shortcuts: Escape closes an open card. +- A change in the Design tab marks the project modified: save it, or pass `"discard_changes": true` + to `open_files` and `new_project`. + ## Script format ```jsonc diff --git a/docs/HLSD/design-tab.md b/docs/HLSD/design-tab.md index 95b42966b4..887da2976b 100644 --- a/docs/HLSD/design-tab.md +++ b/docs/HLSD/design-tab.md @@ -14,7 +14,8 @@ Its coupling to the rest of the application is deliberately narrow. It adds no s slicing pipeline and touches neither the preset system nor `Tab`. It reaches the rest of Orca in two places: **Commit to Plate**, which hands finished solids to Prepare as ordinary model objects (by default one assembly object with a part per body, which keeps the bodies' relative -placement, or one object per body), and one optional 3MF archive entry that carries the recipe. +placement, or one object per body) in one Prepare undo step, named after the bodies the user +named, and one optional 3MF archive entry that carries the recipe. Everything else is contained in `src/libslic3r/CAD/` and `src/slic3r/GUI/CAD/`. The user-facing manual lives in the wiki @@ -123,6 +124,13 @@ A Text feature follows the same rule: it stores the outlines it was vectorised i its string, font and height, so the project opens identically on a machine that lacks the font; the three parameters are only what an edit reopens the dialog with. +The recipe is copied into `Model::cad_recipe` after every document change +(`DesignPanel::sync_recipe_to_model()`), so every save path writes it. A change marks the project +modified the way other project data outside Prepare's undo stack does, with the backup's change +mark and the plater's dirty flag, so the title, autosave and the unsaved-changes prompt of New +Project and Open all see it. A project that holds only a design loads no objects; it still opens +under its file's name, since `Plater::load_project()` counts a loaded recipe as a loaded project. + ## The interaction contract Three inputs carry the whole modelling loop — left click, right click and `Esc` — and the @@ -310,7 +318,10 @@ The tab is a page of Orca's main window and answers to the same settings as Prep frame and was left floating over other applications. - **Undo.** The tab keeps its own history (the recipe is not part of Prepare's snapshots), but it has no Undo/Redo of its own: the top bar, `Ctrl+Z` and Edit drive it while the tab is - shown, greyed to what an undo would actually do. + shown, greyed to what an undo would actually do. Every change to the recipe is one step, a + feature rename included, and an edit the kernel refuses leaves none and keeps what was + redoable. A body's name and colour are saved with the recipe but are not in the history, and + its visibility is view state. - **Docking.** The sidebar docks like Prepare's — either side, floating, resized, or collapsed with the canvas's collapse button or `Shift+Tab` — through its own AUI manager under the toolbar, because Prepare's manages the Plater and the Plater is not on this page. The button is @@ -347,9 +358,70 @@ for a checked-in header, not documentation. ## Automation surface `McpControl` exposes the document over JSON-RPC when `ORCA_CAD_MCP` is set in the environment, -with `tools/orca_cad_mcp_bridge.py` as the client side. It describes the scene, queries -topology, measures, and runs the same verbs the offer does — it re-implements nothing, so a -scripted action and a clicked one cannot diverge. It is off unless the variable is set. +with `tools/orca_cad_mcp_bridge.py` as the client side, and to the app's MCP server through its +`cad_call` tool on every platform. It describes the scene, queries topology, measures, and runs +the same verbs the offer does — it re-implements nothing, so a scripted action and a clicked one +cannot diverge. The socket is off unless the variable is set. 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 +automation calls that function with explicit arguments instead of driving the widgets. + +Its methods add features through the kernel calls the cards use, named as the cards name them, +one checkpoint per call. A rebuild that fails is taken back with `CadDocument::rollback()`, which +leaves nothing to redo, and the status line says "Edit rejected" as it does for a refused GUI +edit; the call reports the kernel's reason. Planes are named as in the cards: a +base plane through the modeling origin, the frame every feature uses, a datum Plane feature, or a +planar face, where a hole drills from the Hole card's inward face plane +(`CadDocument::inward_plane_of_face()`, shared with the card). A feature is read and edited as its +card shows it: `describe_feature` and `set_feature` share one table of each type's card fields and +ranges, and an edit goes through `replace_feature()` as the card's Confirm does in edit mode. + +Commit to Plate and Export STEP… are split from their button and file dialog +(`commit_to_plate()`, `export_step_to()`), so `commit` and `export_step` run the GUI's own work, +and `new_design` is New Design's `clear_document()` without the confirmation. The Feature tree's +and Bodies list's row actions are split the same way, into cores that take an index +(`delete_feature()`, `move_feature()`, `show_feature()`, `rename_feature()`, `delete_body()`, +`rename_body()`, `set_body_color()`, `show_body()`), which the rows call with the selected one and +the automation calls without selecting anything; `undo` and `redo` are Edit > Undo and Redo. + +A sketch session opens through `begin_sketch_session()`, which a plane or face pick also runs, on +the same plane frames, so a sketch on a base plane passes through the modeling origin. Committing an +empty sketch is refused and leaves the session open. `extrude` and `revolve` take a committed +sketch, or one of its loops, as their cards do; a committed sketch's loops come from +`DesignSketchTool::loop_report(entities)`, numbered as the viewport's loop pick numbers them. +Inside a session, `DesignSketchTool`'s scripted entry points run the tools' own apply steps without +a pointer: `fillet_scripted()` is the Fillet and Chamfer tools' Confirm (`confirm_op()`, which +reports a refused value), `trim_scripted()` a Trim or Extend click (`apply_live_trim()`), +`transform_scripted()` the transform gizmo's Confirm, `add_shape_scripted()` the Polygon, Slot, +Ellipse, Elliptical arc and Spline tools' last click, and `constrain_scripted()` a CONSTRAIN bar +button, whose picks the shared planner (`plan_entity_constraint()`, `write_plan_value()`) turns +into constraints. Each keeps the armed tool and its sticky settings, and refuses while a gesture or +a value field is pending. + +Topology reads come from the kernel: `GeometryEngine::surface_info()` gives a face's surface type, +area and analytic numbers, `edge_faces()` the faces along each edge, `edge_convexity()` whether +two faces meet in an outside or inside corner (OCCT's fillet classification), and +`min_distance()` the closest points of two shapes. The Plane card's Confirm and the `plane` method +share `CadDocument::datum_plane_refusal()`, which refuses a construction that is missing a +reference, names a face or edge no longer on the model, or puts a tangent plane on a face that is +not a cylinder, so neither reaches the kernel's silent fallback to an offset plane; a refused +Confirm leaves no undo step. + +The Thread card's pick and `thread` share `CadDocument::thread_target()` (the picked cylinder's +axis frame) and `nearest_thread_standard()` (the size inferred from it). The Sweep card's path list +holds Helix features as well as sketches, and a sweep along a helix keeps its profile at a fixed +angle to the helix axis. Thread, sweep and loft automation rebuilds through `recompute_guarded()`, +as the cards do, so the window stays live during a long build. + +The viewport is a canvas target like Prepare's for the app's MCP server (`DesignCanvas::gl_canvas()`): +`set_view {tab: "design"}` shows the tab and points its camera, `screenshot` captures the view +(sketch overlay and status line included) and composites it into window captures, `ui_mouse` +clicks and drags it at pixels, so a left click picks and a right click opens the offer, and +`ui_snapshot` lists its in-canvas value fields. Keys sent with `ui_key` reach the panel's +`wxEVT_CHAR_HOOK` as a real key press does, travelling up from the focused widget, so Escape, +Enter and the tool shortcuts behave as they do for a person. + +`docs/HLSD/mcp-server.md` describes the method table, access rules, error convention and replay +tests. ## Where the code lives @@ -364,6 +436,7 @@ scripted action and a clicked one cannot diverge. It is off unless the variable | `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/CAD/McpControl.*` | the automation surface: the method table, shared by `cad_call` and the socket | | `src/slic3r/GUI/CAD/DesignInteraction.hpp` | the Esc level contract | | `src/slic3r/GUI/CAD/DesignOffer.hpp` | generated offer table | | `scripts/CAD/tool_atlas.json` | source of truth for the offer | @@ -379,3 +452,8 @@ The GUI half is not covered by CI, which has no OpenGL canvas or synthetic input in `scripts/CAD/` drive a running application in a local rig instead, and `scripts/CAD/run-all-checks.sh` is the gate that runs all of them. A green kernel run says nothing about the viewport, so the two are reported separately rather than as one number. + +The automation surface has its own checks: `tests/slic3rutils/test_mcp_cad.cpp` runs the methods' +argument checks and kernel calls on a `CadDocument` or a bare `DesignSketchTool`, with no panel, and +the replay scripts `tools/mcp/tests/cad_*.json` run the methods on a live application through +`cad_call`, launched with `tools/mcp/orca_mcp.py launch --cad`. diff --git a/docs/HLSD/mcp-server.md b/docs/HLSD/mcp-server.md index 687faf4664..5ba092eaf4 100644 --- a/docs/HLSD/mcp-server.md +++ b/docs/HLSD/mcp-server.md @@ -88,14 +88,25 @@ file, and one that stops must not hide another's server from the stdio bridge. `GUI_App::on_init_inner()` starts the service once AppConfig is loaded. That is before the first startup dialog, such as the TLS prompt or the setup wizard, so an agent can answer those dialogs. `--mcp` or the `mcp_enabled` preference opens the endpoint, while `--mcp-script` alone only builds -the catalog. `get_state.ready` stays false until `post_init()` calls `mark_ready()`, and tools that -need the main window fail with "still starting". `mark_ready()` also starts a command-line script. +the catalog. `get_state.ready` stays false until `post_init()` calls `mark_ready()`, the Prepare +canvas has loaded OpenGL and the main window has built its tab pages, and tools that need the main +window fail with "still starting". Starting on Home, the canvas loads OpenGL at idle after +`post_init()` (MainFrame's GL prebuild), and before that a 3MF save would draw its thumbnail with no +GL functions loaded. The same idle queue builds the tab pages (`MainFrame::prebuild_pending()`); a +page's web view registers its `wx` script message handler with a script it waits for in a nested +loop, and on GTK calls that came in meanwhile have left that wait unfinished for good, so that no web +view made afterwards gets `window.wx` and a dialog page's own buttons do nothing. So `mark_ready()` +polls every 100 ms until both are done. A hidden canvas that can't get a GL context loads OpenGL on +its first draw instead, and the pages build only while no input arrives, so after 10 s ready no +longer waits for either. Becoming ready also starts a command-line script. Notifications don't depend on this: one pushed or updated before the first +ImGui frame has built the font waits for its first render to measure its text. The service stops, idempotently, at the start of `MainFrame::shutdown()` when the app closes (before panels are destroyed) and on `wxEVT_END_SESSION` (after which macOS calls `exit()`). `McpService::stop()` wakes every waiting call with "shutting down" (`UiInvoker::shutdown()`, `JobRegistry::wake_all()`), refuses new calls, closes the endpoint and removes the discovery file, -drops every auto-answer rule, clears `SyntheticInput` and turns ImGui recording off. It frees +drops every auto-answer rule, clears `SyntheticInput`, removes the menu capture and turns ImGui +recording off. It frees nothing: a call may still be on the UI thread's stack inside a nested event loop, using the inspector and the modal tracker, and job and request threads may still be returning. A stopped service never starts again. `GUI_App` holds the service in an `McpServicePtr`, whose @@ -167,8 +178,8 @@ refusal lists the dialogs. It is also refused when it would run inside another U event loop: a modal, `ProgressDialog::Update` or `wxYield`. The GUI input tools (`ui_click`, `ui_input`, `ui_key`) and `dialog_respond` run as recover calls. Once a target resolves outside the topmost modal, they apply the mutate checks themselves (`UiInvoker::require_mutate()`), along with -operation admission. `cancel` is a recover call too, so neither a dialog the operation opened nor -another call's nested loop keeps it out. +operation admission (`McpCore::admit()`). `cancel` is a recover call too, so neither a dialog the +operation opened nor another call's nested loop keeps it out. `ToolDef::inline_call` decides where a call runs. Pure observation tools run on the request thread. Every tool that can activate UI runs as a job on its own thread, recover tools that click @@ -215,12 +226,35 @@ through `observe_ui()` every 200 ms, so a dialog that opens meanwhile doesn't st the work ends or the deadline passes. The deadline is `slice.timeout_s` (default 30 minutes) for a slice and 10 minutes for an export. -**Admission.** While an operation job runs, every other `Mutate` call is refused ("Busy: job j12 (a -slice or export) is running"), whichever client or script sends it. So an agent can't change the -project under its own operation. The check runs when the call arrives and again in its UI closure, -where operations start, so a call admitted just before an operation began still can't change the -project under it. Inline tools, recover tools and `allowed_during_operation` tools (`cancel`) still -run. +**Worker jobs.** Arrange, orient, Fill bed and the jobs of the Text, SVG and texture gizmos run on +the Plater's UI job worker, whatever started them: the typed `arrange`, `run_action obj_arrange`, a +GL toolbar item, an ImGui button such as the Arrange options panel's, or a gizmo control. `McpCore` +watches that worker through `WorkerHooks` (busy and cancel, both on the UI thread). A call that finds +the worker idle at the start of one of its UI closures and busy at the end of that closure, or of a +later one (a toolbar event or a render queued by the call starts the job between closures), has +started a worker job, and `McpCore::claim_worker()` makes that job the call's operation. The call's +own job then ends only once the worker is idle again, its finalization included, since the job holds +`ModelInstance` pointers until then. (`Worker::is_idle()` reads true from the moment the worker takes +the finalize message, so a dialog finalization opens, such as an arrange's geometry error, ends the +hold early; the modal guard keeps changes out until it closes.) Its reply waits within the reply budget and +then becomes a running job, as for any call. `cancel` (or the call's own timeout, 30 minutes unless +the tool sets a shorter one, as `arrange` does) asks the job to stop, but `Worker::cancel()` does not +wait, so the call keeps the operation until the worker is idle and then fails as cancelled. `cancel` +stops only a job an MCP call claimed. The worker doesn't record who queued a job, so a job a person +starts while a call is still between its closures, after one that found the worker idle, is claimed +by that call too: its reply then waits for that job. The window is the call's own length, a +second or so for most calls and up to its poll timeout for a call that waits on the UI. + +**Admission.** While an operation job runs, every other `Mutate` call is refused ("Busy: job j12 is +running an operation (slice, export, arrange or another background job)"), whichever client or script +sends it. So an agent can't change the project under its own operation. While the worker runs a job +no call holds, a person's (typing in the Text gizmo) or one not yet claimed, changes are refused too +("Busy: a background job ..."); reads are not. The check, `McpCore::admit()`, runs when the call +arrives (operations only, since the worker lives on the UI thread) and again in each of its UI +closures, where operations start, so a call admitted just before an operation began still can't +change the project under it. Inline tools, recover tools answering the topmost modal and +`allowed_during_operation` tools (`cancel`) still run; the GUI input tools apply the same check once +their target is outside the topmost modal. **Identity.** An operation must never take another's completion for its own. `Plater` numbers slice requests (`slice_request_seq`, bumped through `request_slice()` by every user-facing slice @@ -234,7 +268,8 @@ already refused, a broken mixed filament, missing plugins, a UI job that won't s reason, so it is never taken for a cached result. `Plater` also notes each request that a later request reached while it was still slicing (`slice_request_interrupted()`). `Plater::project_revision()` rises with every undoable model edit, undo/redo, load, new project and -config change, but not when a plate is selected (`Plater::take_plate_selection_snapshot()`), since +config change, and with every change of a plate's layer G-codes (the plater's handler of the layer +slider's ticks), but not when a plate is selected (`Plater::take_plate_selection_snapshot()`), since Slice All selects each plate in turn. A ticket's own runs are those numbered after it began that its request started (`SliceRun::for_request`); Slice All's later plates run for the same request, while a reslice from a Preview switch or automatic slicing, or an export, merely runs under the @@ -252,7 +287,16 @@ sliced, `error` with the latest validation message when the configuration was re request so no run started (`Plater::plate_validation_error()`), `cancelled` when the operation was cancelled, or `skipped` (Slice All stops at a failing plate). Statistics come with an `ok` plate only while the project is as the operation sliced it and nobody has sliced that plate since -(`plate_result_is_own()`). `cancel` also drops a pending automatic reslice: it stops the delay timer, +(`plate_result_is_own()`). They are `plate_summary()` of the plate's `gcode_statistics_json()`, the +serializer of the exported `statistics.json`, so the reply agrees with that file and with the +legend: `filament_g` and `filament_m` count the flush, as the legend's Total Filament and the +G-code's per-filament totals do, and `filaments` lists every filament slot of the project +(`filaments[i]` is slot i + 1, zeros for slots the plate does not use) with its model, support, +flush and prime tower grams. The silent-mode time and extruder changes, which that file leaves +out, come from the result's estimates, and only when the printer has them. The summary is read in +the poll closure that decides the outcome, since a UI call of its own would wait behind the +preview's loading of the new result; the serializer's one pass over the moves is short next to +that. `cancel` also drops a pending automatic reslice: it stops the delay timer, whose callback wx then never delivers, and moves on a generation that a zero-delay reslice already queued with `CallAfter` checks. An export is numbered in `export_seq` once scheduled, so an unchanged number means it never started; otherwise its `ExportRecord` ends `ok`, `failed`, @@ -275,38 +319,48 @@ the UI thread. | Group | Tool | Purpose | |---|---|---| -| App | `get_state` | version, platform and display backend, ready, tab, mode, project, presets, plates, objects, slicing, the open gizmo, dialogs, notifications, jobs, window | +| App | `get_state` | version, platform and display backend, ready, tab, mode, project, presets, plates, the Preview's view type, time mode and layer range, objects, slicing, print host uploads, the open gizmo, dialogs, menus closed unseen, notifications, jobs, window | | | `wait` | `ready`, `idle`, `dialog`, `no_dialog` or a `job`; `timeout_s` up to 50 | | | `get_log` | end of the current log file, filtered by minimum level | | Speed Dial | `list_actions` | search the action catalog, paged | -| | `run_action` | run an action by id, with its optional `param` | +| | `run_action` | run an action by id, with its optional `param`; an error when the action did nothing; waits for a background job it starts (arrange, orient) | | Project | `open_files` | load models, a project or G-code by absolute path, with no dialog | -| | `new_project` | start an empty project (`discard_changes` if it has unsaved changes) | +| | `new_project` | start an empty project (`discard_changes` if it has unsaved changes); `changes` keeps or discards modified presets | +| | `calibrate` | a Calibration menu test with typed parameters and no dialog: a new project with the test model and the preset changes the test needs, printed with filament slot 1; refused while presets are modified unless `changes` keeps or discards them | | | `save_project` | save the project as `.3mf` to a path | | | `export` | `gcode`, `sliced_3mf`, `3mf` or `stl` to a path; `gcode` is an export operation | -| Presets | `list_presets` | printer, process or filament presets with flags, paged | -| | `select_preset` | select by name through the selector (filament per slot) | -| | `get_settings` | values and metadata of a preset, or of an object's or part's overrides | -| | `set_settings` | set values the way the settings tab does, all or none; object and part overrides | -| Objects | `list_objects` | objects, instances (with their canvas rectangles on request), parts (triangles, mesh volume, painted facets, text and SVG sources), bounding boxes, brim ears, overrides, paged | +| Presets | `list_presets` | printer, process or filament presets with flags (system, user, inside the project, the preset inherited from), paged | +| | `select_preset` | select by name through the selector (filament per slot); `changes` transfers or discards unsaved changes without the prompt | +| | `get_settings` | values and metadata (enum labels, per-variant entries) of the edited or any saved preset, of an object's or part's overrides with the values they print with, of the project's own settings (plate type, slot colours, flushing volumes, purge mode, prime tower positions, mixed slots), of a plate's (plate type, print sequence, spiral vase, filament orders, name, lock), or of named preferences (read only); `compare` lists only what differs from another preset, the saved one or the parent | +| | `set_settings` | set values the way the settings tab does, all or none; one entry of a per-variant value; object and part overrides and filaments; the project's and a plate's own settings through their controls' and dialogs' code; `null` takes a preset's key back to its saved or parent value, `reset_all` drops a preset's unsaved changes first; replies with every setting that `changed` | +| | `save_preset` | save the preset being edited under a name, as a user preset or inside the project | +| | `delete_preset` | delete a user or project preset, selected or not, as the tab's Delete does (destructive) | +| Objects | `list_objects` | objects (filament, auto drop, overrides, brim ears, height range modifiers, variable layer height profile), instances (placement, mirrored, bounding box, canvas rectangle on request) and parts (type, filament, placement and bounding box on the bed, scaled and mesh volume, painted facets, text and SVG sources), paged | +| | `list_plates` | plates with the settings they print with and those they set themselves, objects, name, lock, slice state, prime tower position and layer G-codes, paged | | | `select` | select objects, instances or parts, all, or none | -| | `transform` | translate, rotate or scale one instance, relative or absolute | -| Slice | `slice` | current, one or all plates, then the Preview tab as after the Slice button; outcome and stats for each plate | -| | `cancel` | stop the running slice or G-code export, or a pending automatic reslice (optionally only a given job); allowed during an operation | -| View | `set_view` | tab, 3D view (Prepare, preview, assemble), camera, preview layers and color scheme, window size | -| | `screenshot` | window, 3D canvas, topmost dialog or one widget: a downscaled image and a full-size PNG | -| GUI | `ui_snapshot` | widgets, menus, GL toolbar items, gizmos and ImGui items, with refs | -| | `ui_click` | activate a ref or locator | -| | `ui_input` | set a control's text, value, selection or checked state | -| | `ui_key` | send a key chord to a target or the focused window | -| | `ui_mouse` | canvas gestures: move, down, up, click, drag, wheel, at pixels or at points of the model | +| | `transform` | translate, rotate, scale or size one instance, relative or absolute, or move it to another plate; or the same for one part (`volume`) | +| | `add_part` | add a part, negative part, modifier, support blocker or enforcer, or precise seam to an object: a shape at a size or a model file, optionally at a position | +| | `arrange` | arrange every unlocked plate or one plate, or fill an object's plate with instances or copies, with the Arrange options panel's settings; waits for the job | +| | `set_layer_ranges` | replace an object's height range modifiers: Z ranges with their own layer height, filament and process settings | +| | `set_layer_height_profile` | the Variable layer height panel's Adaptive (with its quality), Smooth (radius, keep min) or Reset on an object | +| Slice | `slice` | current, one or all plates, then the Preview tab as after the Slice button; outcome for each plate, and for an `ok` one its time, filament totals with the flush, cost, layers, max Z, filament changes and grams per slot by use | +| | `cancel` | stop the running slice or G-code export, a pending automatic reslice, or a background job an MCP call started (optionally only a given job); allowed during an operation | +| | `set_layer_gcode` | add or remove a plate's pauses, custom G-code, custom templates and filament changes on its sliced layers, as the Preview layer slider's menu does | +| View | `set_view` | tab (Design included), 3D view (Prepare, preview, assemble), camera (the Design view's on the Design tab), preview layers (by number or height), color scheme as the legend's combo picks it, legend rows and time estimate, window size | +| | `screenshot` | window, the 3D view shown (the Design view on the Design tab), topmost dialog or one widget: a downscaled image and a full-size PNG | +| | `get_preview` | a sliced plate's summary, time and grams per feature type, per-layer Z, height, time and grams (paged), grams per object instance, and the Preview's legend state and colour ranges | +| GUI | `ui_snapshot` | widgets, rows of lists, trees and tables, popups, menus, GL toolbar items, gizmos, the Prepare view's plates and plate icons, and ImGui items, with refs | +| | `ui_click` | activate a ref or locator, click a row's cell or a plate icon, or click a point of a 3D canvas or custom-drawn widget; list the menu it opens, or run one of its items | +| | `ui_input` | set a control's text, value, selection or checked state, or a row's checkbox | +| | `ui_key` | send a key chord to a target or the focused window, whose panels' key hooks see it first; list or run the menu it opens | +| | `ui_mouse` | canvas gestures: move, down, up, click, drag, wheel, at pixels or at points of the model (the Design view at pixels); list or run a right click's menu | | | `gizmo_file` | what the open gizmo's file pickers do, with a path: SVG change file and save as, texture import | | | `dialog_respond` | press a button of the topmost wx dialog | -| | `dialog_auto_answer` | answer matching modals before they show, and one already open | -| | `webview_eval` | run JavaScript in a web view and return the result | +| | `dialog_auto_answer` | answer matching modals as they open (native ones unseen), and one already open | +| | `webview_eval` | run JavaScript in a web view, the setup wizard's and preset bundle dialogs' included while they are modal, and return the result | | Scripts | `run_script` | run a script file or inline script, with results per step | -| | `export_script` | write the session journal as a script that can be replayed | -| CAD | `cad_call` | forward to the Design tab's control surface (CAD builds, Design tab enabled) | +| | `export_script` | write the session journal as a script that can be replayed; calls whose job is still running are left out and listed | +| CAD | `cad_call` | a method of the Design tab: sketches, features, reads and measurements, feature and body edits, undo, commit to plate; `describe_tools` lists them (CAD builds, Design tab enabled) | Each tool family registers itself from its own `McpTools*.cpp` through `register_*_tools()`. List tools take `limit` and `offset` and report `total` and `next_offset`. `McpPaths.hpp` requires @@ -316,6 +370,759 @@ directory; an output's directory must exist, and an existing file is replaced on `path_from_utf8()` and `path_to_utf8()` convert, through wide strings on Windows, where boost's narrow conversion would use the ANSI code page. +### list_objects + +`list_objects` describes the model through `object_info()` and `volume_info()` (McpToolsScene.cpp, +libslic3r only, so unit tests build them from a `Model`); the handler adds what the GUI knows: each +instance's plate from the plate registry and, on request, its canvas rectangle. Bounding boxes are +`ModelObject::instance_bounding_box()`, on the bed and of model parts only, which is what prints; the +Object manipulation panel's Size also counts modifiers and negative parts. A part's `position`, +`bbox` and `scaled_volume` (the mesh's volume times the determinant of its placement) are measured on +instance 0, like the object's `bbox`; its `rotation_deg` and `scale` are in the object's frame, the +panel's Object coordinates. `mirrored` says whether a placement is left-handed +(`is_left_handed()`), not along which axis, since the split of a mirror from a rotation is not unique +(mirrored in X and in Y is a half turn about Z). `filament` follows the object list's filament +column: an object's `extruder`, 1 when unset; a part's own, else its object's; a modifier's only when +it sets one, since a modifier without one leaves the filament of what it covers alone; none for +negative parts, support blockers and enforcers, and precise seams. A precise seam has `type: +"precise_seam"` and its `subtype` (`center`, `left`, `right`, `enforced`, `blocked`, `neutral`, the 3MF +names without their prefix). The `transform` reply on a part carries the same `volume_info`. An +object with height range modifiers lists them as `layer_config_ranges` (`layer_config_ranges_json()`), +each with its whole config serialized as `get_settings` serializes values, so a range always shows +its `layer_height` and `extruder`, and the list can be handed back to `set_layer_ranges` unchanged. An +object whose `layer_height_profile` has more than a flat bottom-to-top pair, which the object list marks +as a variable layer height, reports it as `layer_height_profile: {points, min_height, max_height}` +(`layer_height_profile_json()`): the number of (z, height) points and the extreme heights, to 0.001 mm. +The points themselves stay in the 3MF's `layer_heights_profile.txt`. + +### transform + +On an instance, `transform` writes the `ModelInstance` directly: a relative rotation composes as +Euler angles, and a rotation or scale applies to that instance only, where the panel applies it to +every instance of the object. `size` sets mm along +the object's own axes (its model parts' box, unrotated, times the instance's scale; a single number +with two nulls keeps the proportions), and `plate` is one more relative move by the difference of the +two plates' origins, applied last. Then the bounding box is invalidated before +`ModelObject::ensure_on_bed()`, so a scale that grows an object drops it onto the bed instead of +leaving it sunk, and the instance is registered with the plate it is on now +(`PartPlateList::notify_instance_update()`, then `ObjectList::update_plate_values_for_items()`), as +`GLCanvas3D::do_move()` does for a person's moves. Slicing and `list_objects` read plates from that +registry. + +On a part (`volume`), it takes the Object manipulation panel's path. It refuses the assemble view, an +open gizmo and an object with one part (which has no row of its own), selects the part's row in the +object list with nothing else selected, so the 3D view selects it on instance 0, takes one undo +snapshot, and runs `Selection::translate()` / `rotate()` along the bed's axes and `scale()` along the +part's own axes, each followed by `do_move("")` / `do_rotate("")` / `do_scale("")`. Those write the +part, drop the object when Auto Drop is on, register every instance with its plate and update the +object list. An absolute translate is a delta from the part's position on instance 0; an absolute +scale or a `size` (mesh box times the part's scale, in the object's frame) becomes factors on the +current scale, as the panel computes them, since `Selection::scale()` multiplies a part's scale +whatever the transformation type. A part's rotation is relative only. + +### add_part + +`add_part` runs what the object's context menu Add items run. It refuses the assemble view, an open +gizmo and an object with more than one instance, since adding a shape folds instance 0's rotation +and scale into the parts (`ObjectList::apply_object_instance_transfrom_to_all_volumes()`), which the +other instances would not follow. It selects the object's row, which the menu's functions act on, +then calls `ObjectList::load_generic_subobject()` with `interactive` false and the size, so neither +the Primitive size dialog nor the Add Modifier tips show, or, for a file, +`ObjectList::load_subobject(type, files, ...)`: the Load... item after its file dialog, which hands +back the reason a file failed to load instead of showing the error dialog. A STEP file still asks +for its mesh options when the preference says so, as it does a person (`blocked_by_dialog`). A size +is checked against `primitive_size_names()`, the fields the size dialog asks for; without one, the +shape gets the built-in size (10 % of the bed's larger side), never a size the user saved, so a +replay does not depend on the machine. The menu's function takes the undo snapshot ("Add +primitive", "Load Part" or "Load Modifier"; a file that fails to load leaves it, as in the GUI). +`position` then selects the new part and moves it along the Move panel's path +(`Selection::translate()`, `do_move("")`), all inside one `Plater::SingleSnapshot`, so the call is +one undo step. The new part is found by pointer, since `ModelObject::sort_volumes()` orders parts +by type. SVG files are refused: SVG parts come from the SVG gizmo, which places them where the +camera looks. + +### arrange + +`arrange` runs what the GUI runs: with `plates: "all"`, `set_prepare_state(PREPARE_STATE_DEFAULT)` and +`Plater::arrange()`, as the toolbar does; with a plate index or `"current"`, `select_plate()`, +`PREPARE_STATE_MENU` and `arrange()`, as the plate's Arrange icon does, without its +`last_arrange_job_is_finished()` flag, which a cancelled job never clears; with `fill`, the object's +row selected and `fill_bed_with_instances()` or `fill_bed_with_copies()`, which fill the object's own +plate. Each takes one "Arrange" undo snapshot. It refuses the assemble view, an open gizmo, a locked +or empty plate, `fill` with `plates`, and an object Fill bed refuses (`can_increase_instances()`). +`spacing`, `rotate`, `align_y` and `multi_material` go into the current print mode's +`GLCanvas3D::ArrangeSettings`, which both jobs read, by the panel's rules (`apply_arrange_args()`: +Align to Y axis stays off while rotation is on), and `GLCanvas3D::store_arrange_settings()` saves +spacing, rotation and the material rule under the keys the panel writes, so later arranges, the +panel and a replaying machine's app config all see them. The journal records the settings in force, +so a replay does not depend on the replaying machine's saved options. + +The call waits for the worker (see Worker jobs), then reports the settings in force with `by_object` +(which mode's set was used), instances on no plate (`off_plate`, measured against the plate boxes, +since Fill bed leaves its new instances out of the plate registry), the plates an all-plates arrange +leaves alone (`skipped_plates`: locked, or printing in another sequence than the project, which +`ArrangeJob::prepare_all()` locks for the run), notifications the job raised, and a `note` when a +setting asked for did not apply (one plate in another sequence is arranged with automatic spacing). +An arrange sorts the model's objects by arrange order +(`PartPlateList::rebuild_plates_after_arrangement()`), so indices may change. After `timeout_s` +(default 300) the call cancels the job. + +### set_layer_ranges + +`set_layer_ranges` gives an object's whole set of height ranges (`ModelObject::layer_config_ranges`), +which a person builds with the object list's Height Range Modifier, its "+" buttons and the range +editors in the sidebar, one gesture and one undo step at a time. Each range starts from what the object +list gives a new one, `ObjectList::get_default_layer_config()` (the object's layer height, else the +process's, and filament 0, the object's), then takes its `values`, parsed strictly. The keys are those a +range's page and the object list's Add settings menus offer (`layer_range_option_keys()`): `layer_height`, +the per-region settings with a category, without support settings or, with one filament, per-feature +filaments and wipe options, and `extruder`, the range row's filament column. A `layer_height` given is +checked against the bounds the range editor enforces (`get_min_layer_height()` / +`get_max_layer_height()` for the range's filament: the printer's per-nozzle values indexed by filament +number, so the first serves a single-nozzle printer). Ranges may touch but not overlap: the slicer would +trim an overlap silently (`layer_height_profile_from_ranges()`), and from an agent it is a mistake. A +range above the object is kept, as the GUI keeps it, and slicing cuts it; the reply gives the object's +height. All of this is checked before anything changes, and a call that gives the ranges the object +already has changes nothing and takes no undo step. + +Like `add_part`, it refuses the assemble view and an open gizmo and switches to Prepare. To change the +ranges it selects the object's row, so no Layers row and no sidebar range editor stays in use, then +takes one snapshot ("Edit height ranges"), writes the new ranges, rebuilds the Layers rows from the +model with `ObjectList::reload_layer_rows()` (shared with pasting ranges) and calls +`Plater::changed_object()`. A range editor that loses focus later reports an edit of a range that is +gone; `ObjectList::edit_layer_range()` then edits nothing rather than adding the range back without a +layer height. The dialog the menu shows when the process uses mixed colour sublayers becomes a +`warnings` entry, and so does a variable layer height profile on the object, which decides its layer +heights instead of the ranges' `layer_height` (`PrintObject::update_layer_height_profile()` falls back to +the ranges only without a valid profile). + +### set_layer_height_profile + +`set_layer_height_profile` runs what the Variable layer height panel's Adaptive, Smooth and Reset buttons +post: `GLCanvas3D::adaptive_layer_height_profile(quality)`, `smooth_layer_height_profile({radius, +keep_min})` and `reset_layer_height_profile()`, each with the GUI's undo snapshot ("Variable layer height - +Adaptive", "- Smooth all", "- Reset"), followed by a background update and the object list's variable +mark. The defaults are the panel's (quality 0.5, radius 5, keep min off), fixed rather than read from the +panel, so a replay does not depend on what a person last set there; an argument of another action is +refused. Like the panel, it works on the selected object: it refuses the assemble view and an open gizmo, +switches to Prepare, selects the object's row, and requires `Plater::can_layers_editing()`, the rule that +enables the toolbar item (FFF, the object above the bed, the layer editing shader loaded), naming the +condition that fails. It does not open the panel. Reset of an object without a profile changes nothing +and takes no undo step. + +The panel's buttons act on the object its last frame picked (`LayersEditing::select_object()`), with +the profile that frame loaded, and a closed panel has no such frame. So each canvas function first picks +the selected object (`GLCanvas3D::_select_layers_editing_object()`), dropping what an earlier call left +while the panel is closed, and `LayersEditing::smooth_layer_height_profile()` loads the object's profile +with `PrintObject::update_layer_height_profile()` (the model's profile, or the one its height ranges give) +as the frame does. With the panel open both are what the frame did already. The Prepare canvas edits layer +heights only once it has drawn, since `GLCanvas3D::init()` creates the texture `is_layers_editing_allowed()` +checks; the call waits up to 15 s for it. + +Adaptive keeps a height range's own `layer_height` inside the range (`layer_height_profile_adaptive()`), +so on an object whose ranges cover its height it gives the ranges' heights at any quality. Once an object +has a profile, the profile decides its layer heights, and the reply warns when it also has ranges; it +also passes on the warning the panel shows when the process mixes colours in sublayers. A profile is +stored per object, saved in the 3MF, and discarded by the slicer when it no longer ends at the object's +top (after a scale, for example). + +### set_layer_gcode + +`set_layer_gcode` places what the Preview layer slider's right-click menu adds at the start of a layer +(Add Pause, Add Custom G-code, Add Custom Template, Change Filament > Filament N) and removes them, on one +plate. The codes are a plate's `Model::plates_custom_gcodes` entry, saved in the 3MF +(`custom_gcode_per_layer.xml`) and read back by `list_plates` as `layer_gcode`, with the same type names +(`pause`, `custom`, `template`, `change_filament`, and `color_change` for an old project's colour change, +which the slider never adds). The slider is the source of truth: the plater's handler of its tick event +writes the slider's whole set over the plate's entry, and the slider is not refilled while the plate's slice +is invalid, so a code written to the model alone would vanish at the next tick event. The call therefore +edits the slider with its own functions (`IMSlider::add_code_as_tick()`, `add_custom_gcode()` and +`delete_tick()`, given an explicit layer instead of the active thumb) and hands the ticks over with +`GLCanvas3D::send_layer_ticks_changes()`, what each Preview frame does, then waits for the handler: the +plate's entry rewritten, its slice invalidated, the project dirty and its revision raised. + +Codes sit on the layers of the plate's slice. `layer` is the slider's value plus one, as `set_view` and +`get_preview` number layers; `z` takes the layer whose top is at or above it +(`IMSlider::get_tick_from_value(z, true)`, the rule the slider uses for a stored height), so a code is +always stored at a layer's top, where the slider and the G-code generator agree on its layer. The reply +gives both for every code. A plate's layers are in the slider only while the Preview shows that plate's +result (`GCodeViewer::last_result_id()` against the plate's slice result), so when the plate's slice is +up to date the call shows the Preview and selects the plate as the Preview's plate toolbar does +(`Plater::select_sliced_plate()`), which loads its result; a plain plate switch leaves the Preview +showing the old plate. A plate whose slice is not up to date is refused unless the Preview still shows +its layers (it was edited and not sliced again since), as a person can go on editing there: opening the +Preview on such a plate would start a slice. The call waits for a pending update of the slicing state, +which may invalidate the plate, and a slice in progress refuses it; a plate that prints by object takes +no codes, and an empty plate has no layers. + +The arguments apply in order: `clear`, then `remove`, then `add`, all checked on a copy of the slider's +ticks before it changes (`edit_layer_gcode()`), with the menus' rules: one code per layer, so a code of +another type on the layer is refused unless the call removes it, and a custom code or filament change on +a layer with one replaces it (Edit Custom G-code, Change Filament on the tick); a template only when the +printer's `template_custom_gcode` is set; a filament change only with two or more filaments, when the +slider offers it (the plate's objects on one filament, no spiral vase) and while the filament count is the +slice's, since the slider colours the change from the slice's filament list; custom G-code up to the +dialog's 1023 bytes. The check matters because the slider's own add turns any code on a layer into a +filament change. A call that changes nothing hands nothing over and leaves the slice valid; a pause on a +printer with an empty `machine_pause_gcode` is a warning. As in the GUI, the edit takes no undo step (the +undo archive does not hold the plates' codes), and the slider drops codes it can't keep when it next loads +the plate: filament changes once the objects use different filaments, every code on a plate printed by +object or across a spiral vase change. The journal records the plate the call resolved. + +### Object and part settings + +The object and volume scopes of `get_settings` and `set_settings` take the keys the object list +offers to add to an object, or to a part or modifier: `SettingsFactory::get_options()` less what +`SettingsFactory::is_improper_category()` hides with the current filament count, the rule of the +list's Add Settings menu. Keys a person cannot add there, such as the internal `print_extruder_id`, +the process-wide `print_sequence` or, with one filament, the per-feature filaments, are refused rather +than stored and ignored by slicing. Parts and modifiers take region keys only. + +`extruder`, the object's or part's filament, is the one key outside that list. `set_settings` writes +it through `ObjectList::set_extruder_for_items()`, the Change Filament code without the selection, +so a call leaves the user's selection alone. An object's filament clears its parts' own; 0 or null +is Default, which is filament 1 on an object, the object's filament on a part and no filament +override on a modifier. A single-part object has no part row, so its volume 0 sets the object's +filament, and the reply notes it. Filament numbers (`extruder`, the per-feature and the support +filaments) past the project's slots are refused before anything changes, and the support filaments +refuse a mixed slot, as their combos do. A call is one undo step (`Plater::SingleSnapshot`). + +In these scopes each `get_settings` item has `effective` and `source`, resolved as the object's +settings tab shows it: the part's override (`part`), else the object's (`object`), else the process +being edited (`process`), else the option's default (`default`). An `extruder` of 0 is no override. +An object's item also lists in `parts` the parts and modifiers that override the key; their values +apply only inside their own volume, and the reply's `note` says so. + +### Saving presets + +`save_preset` saves the printer, process or filament preset being edited, unsaved changes included, +through `Tab::save_preset()` with the name given, the call the Save preset dialog's OK leads to, so +no dialog opens and the saved preset is selected. A filament is first made the one the filament tab +edits for `filament_slot`, as `set_settings` does, and saving it moves every slot that used the old +preset to the new one, as in the GUI. The name is checked by the dialog's own +`check_preset_name()`, and its status decides: an invalid name is refused with the dialog's text, +and the name of another existing preset needs `overwrite`, while the selected preset's own name is +the plain Save. A new preset goes where the edited one is (user or inside the project) unless +`inside_project` says otherwise; an existing one stays where it is, since the dialog locks that +choice. `detach` is refused outside Developer mode, where the dialog has no such checkbox. For a +printer, the selected physical printer, if any, takes the dialog's default action +(`SavePresetDialog::update_physical_printers()` with `ChangePreset`). Preset files live in the +datadir, not the project, so a script meant to be rerun passes `overwrite`. A filament temperature +warning, the unresolved-plugin confirmation or the unsaved-changes prompt of a slot switch makes the +reply `blocked_by_dialog`. + +There is no subset of edits to save. `set_settings {"reset_all": true, "values": {...}}` on a preset +scope first discards every unsaved change with `Tab::on_roll_back_value()`, the tab's undo button, +then applies the values in the same call, so `save_preset` keeps exactly those. The reply lists the +discarded keys in `reverted`. The values are parsed before the reset, so a bad one leaves the edits in +place. The object and volume scopes refuse `reset_all`; a null value removes an override there. + +### Reading, comparing and changing preset values + +`get_settings` reads the preset being edited (for a filament, the slot's preset, edited or not), or +with `preset` any saved preset of the scope, selected or not, without selecting it: the named preset +is read as saved, without the edits the tab holds. `preset` and `filament_slot` are exclusive, and a +name that matches no preset is refused with the closest names. `compare` lists only the keys, among +those named or matched, that differ from another preset: a saved preset by name, `:saved` (the read +preset as saved, so the list is its unsaved changes, what the Unsaved Changes dialog shows) or +`:parent` (the preset it inherits from, a system preset itself, what the tab's lock icons compare +against). `:` cannot be part of a preset name, so the two never clash with one. The key list is +`PresetCollection::dirty_options()` with the Compare presets dialog's rules: printer and filament +vectors are compared entry by entry (an item then carries `index`), a printer with fewer extruders is +compared from the other side, and both presets have one printer technology. Each item has `value` +(the preset read) and `other`; the bookkeeping `*_settings_id` keys are left out. `list_presets` +reports `inherits` and `project: true` for presets kept inside the project. + +An enum's meta lists `labels`, the untranslated texts its combo shows, in the order of `values`, so +a person's wording maps to a value. + +Many process, filament and printer values hold one entry per extruder variant (an extruder type and +nozzle flow type, such as the X1C's "Direct Drive Standard" and "Direct Drive High Flow"), the machine +limits a normal and a silent mode entry per variant, and some printer values one entry per extruder. +For such a value with more than one entry, the meta lists `variants`, what each entry is for, and +`active`, the entry each extruder prints with (extruder 1 first), found as the slicer and the tab's +variant switch find it (`DynamicPrintConfig::get_index_for_extruder()` with the printer's +`extruder_type` and the project's `nozzle_volume_type`). The tab edits one variant at a time: its +field shows the variant in use and typing writes that entry. So a single value for such a key goes to +the entries in use, `set_settings` writes one entry as `{"key": {"index": i, "value": v}}`, and an +array writes them all. Either way the whole vector, with the entries replaced, goes through the tab's +transaction (`Tab::apply_preset_config_values()`), whose commit runs the key's handling as a field edit +does, and the other entries stay as they are. A value with another number of entries is refused, with +the entries and the one in use in the error and its details: written as given, it would collapse the +vector and leave the preset inconsistent with its variants. Values of one entry, and vectors that are not +per variant or per extruder, take a single value. Object and part overrides take whole values. + +`set_settings` replies with `changed`: every key of the edited config (preset, object or part) whose +value differs after the call, including the settings the app adjusted in turn, such as spiral vase +setting one wall loop and no top shell layers once its dialog is confirmed, and the keys `reset_all` +reverted. Dependency order within one call is not resolved; a call can be split instead. + +### Unsaved preset changes + +On a preset scope, a `null` value takes the key back to the saved preset's value, as the key's undo +arrow does, and with `reset_to: "parent"` to the value of the preset it inherits from (the `:parent` +of `compare`), as its lock icon does. The value joins the call's other values in the tab's +transaction, so its handling runs as for a typed value. `reset_to` without a null value, and in the +object and volume scopes, is refused. + +`Tab::select_preset()` asks about unsaved changes through `Tab::may_discard_current_dirty_preset()`: +for the preset it leaves, and for each modified preset a process or printer switch may replace (the +filament, or the process and filament). `select_preset`'s `changes` sets `Tab::m_dirty_preset_answer` +for the one switch, so every prompt is answered with the dialog's Transfer or Discard without +showing it, and the switch then does what it does after a person's answer. Transfer moves what the +dialog would list: the changed options a settings page shows in the current mode, so a setting the +mode hides is dropped, as in the GUI. The dialog offers no Transfer for a printer's own changes or +between filaments of different types (`Tab::can_transfer_changes_to()`); there `transfer` is refused +before anything changes. The GUI's outcomes stay as they are: a modified filament that suits the new +process keeps its changes whatever the answer. Without `changes` the prompt opens, as it does for a +person, and the reply is `blocked_by_dialog`. The message box that a printer switch shows when it drops +other extruder variants' values is shown only to a person. With several filament slots the sidebar does +not move the filament tab when a slot's filament changes (`Plater::priv::on_select_preset()`), so no +prompt opens there: the edits stay with the preset the tab edits, and the reply's `modified` lists them. + +`new_project` without `changes`, or with `"keep"`, keeps modified presets for the new project, as +New Project's Keep does with every option. `"discard"` is the prompt's Discard, +`GUI_App::discard_current_preset_changes()`, called only when a preset is modified, since it reloads +the presets, which can ask about the printer's. Modified presets make the project dirty, so +`discard_changes` is needed too. + +Both replies carry `discarded` and `modified` when presets had or have unsaved changes, each +`{type: {name, keys}}`: a change is discarded when the preset edited afterwards no longer holds its +value, and modified lists the unsaved changes left. Only presets that `list_presets` calls modified +count, with the keys of their preset type; the full comparison also lists bookkeeping keys that only +one of the two configs has. + +### Deleting presets + +`delete_preset` deletes a user preset or one kept inside the project, with its file and its cloud copy, +through the GUI's own delete, so no confirmation opens; it is marked destructive, so clients that gate +such tools ask first. What may be deleted is checked first, as the GUI offers and checks it: the tab +shows its Delete button only for user and project presets, refuses a base preset that other presets +inherit from (they would no longer load), and for a custom printer (a base printer that is not a system +one) asks before deleting the user presets made for it alone, which `delete_attached` answers. The +reply lists those in `attached`. + +The selected preset (for a filament, the one the filament tab edits) goes through +`Tab::delete_preset()`, the Delete button, with `ask` false to skip the confirmations MCP has made +itself. The tab then selects the preset it inherited from, or the next one, through the normal +selection, so a printer or process switch can still ask about other presets' unsaved changes, and the +reply is then `blocked_by_dialog`; the deleted preset's own changes go with it. With a physical +printer selected the tab's Delete only takes the preset off that printer, so that case is refused. A +filament the tab does not edit is deleted as the Edit filament dialog deletes it +(`delete_unselected_filament_preset()`): the selection stays and the slots that used it take the +selected filament; the sidebar and tabs are refreshed as the dialog's opener does. The tab deletes +only its selected preset, so a process that is not selected is selected, deleted and the previous +process selected again, as a person would do it. A printer is not: switching printers recomputes the +process and the filaments, so the call is refused until the printer is selected. Both routes select +the preset being edited again, which would drop its unsaved changes (filament) or ask about them +(process), so they are refused while it has any. + +The reply carries `selected`, the preset of that type selected afterwards, `filaments`, each slot's +preset, and `discarded`/`modified` as `select_preset`'s. A replayed script needs the preset to exist, +so scripts create it first with `save_preset`. + +### Project settings + +The project scope of `get_settings` and `set_settings` covers the settings of the project itself +(`PresetBundle::project_config`) that a person sets in the sidebar, on the canvas or in their dialogs: +`curr_bed_type`, `filament_colour`, `flush_volumes_matrix`, `flush_multiplier`, `prime_volume_mode` +and `wipe_tower_x`/`wipe_tower_y`, plus the read-only `filament_is_mixed` and, on a printer with +several extruders, the read-only `filament_map_mode` and `filament_map`. A generic config write would +skip what each control does after setting its value, so `set_settings` writes every key through that +control's own code. Everything is checked before anything changes, `null` is refused (project values +always exist), and `{"index": i, "value": v}` sets one slot's colour, one matrix cell or one plate's +tower position. + +- `curr_bed_type` goes through the plate type selector (`Sidebar::set_bed_type_accord_combox()`, whose + handler updates the project, the printer's remembered plate type and the plates on the global type). + Only the types the selector lists are taken (`meta.offered`), and none while the selector is hidden + for the printer. +- `filament_colour` is one `#RRGGBB` per slot in config order. Each changed slot goes through its + colour button's code: `PlaterPresetComboBox::sync_colour_config()` and the queued + `EVT_FILAMENT_COLOR_CHANGED`, which recalculates that slot's flushing volumes when the "Auto flush + after changing" preference is on. +- `flush_volumes_matrix` and `flush_multiplier` go through `apply_flushing_volumes()`, the Flushing + volumes dialog's OK split from the dialog, then the button's scene reload and update. The matrix is + N x N per nozzle (row = from slot, column = to slot) in config order over every slot, as + `project_config` and the G-code header hold it, not over the physical slots the dialog shows. The + values are before the multiplier: the header prints the matrix multiplied by it. Volumes are limited + to `g_max_flush_volume` / multiplier as the dialog limits them; negative volumes and a non-zero + diagonal are refused. A multiplier is one per nozzle (one value sets all) within the dialog's 0..3. +- `prime_volume_mode` is what the Purge mode dialog's OK writes, followed by the update it does. It is + offered only while the Purge mode button shows (printers with several nozzles per extruder or fast + purge), with the dialog's choices. +- `wipe_tower_x`/`wipe_tower_y` are one position per plate, in mm from the plate's origin, as a tower + drag stores them: one undo step ("Move object", which takes the old positions along), then an + update. A position off the plate is refused; one where the tower does not fit is re-placed by the + scene reload, as after a drag, with its notification, and the reply's `note` says so. + +Colours are applied in a first UI closure and the rest in a second after a settle, so a matrix given +in the same call is written after the recalculation the colour change triggered, and a matrix cell +given by index is set in the matrix that recalculation left. The recalculation also runs when a slot +is added and, depending on the preference, when a slot's preset changes, so a matrix is best set +last; a replay matches only on a datadir with the same preference. + +A mixed filament is a virtual slot made of physical ones (the sidebar's mixed filament list); its +colour comes from its components and it is never flushed. `filament_is_mixed` tells which slots they +are, and their colours and matrix rows and columns are refused unless left as they are, as the +dialog keeps them. The filament grouping is set per plate in the Filament grouping dialog, and every +plate carries its own mode from the start, so a project-wide `filament_map_mode` or `filament_map` +would not change a slice: both are listed for reading only. Nothing here except the tower position +enters the undo stack, as in the GUI. + +### Plate settings + +The plate scope of `get_settings` and `set_settings` (`plate`, the current plate by default) holds what +the Plate Settings dialog sets on a plate: `curr_bed_type`, `print_sequence`, `spiral_mode`, +`first_layer_print_sequence` and `other_layers_print_sequence`, plus the plate's `name` and `locked`, which +its icons set. Values take the forms the dialog offers: an enum value, a boolean, a filament order that +lists every slot once (the dialog's drag canvas), and layer ranges `[{from, to, order}]` starting at layer +2 (the first layer has its own order), sorted and not overlapping, `to` left out for the dialog's "End". +`null` is the dialog's "Same as Global" or "Auto". The dialog's Auto/Customize choices are not separate +keys: an order given is Customize. `get_settings` lists each key with `value`, the plate's own (null where +it follows the global setting or Auto), and `effective`, what the plate prints with. + +`set_settings` checks everything first, then selects the plate as its settings and name icons do and +passes the plate's values, changed by the call, to `Plater::apply_plate_settings()`, the dialog's OK +split from the dialog. It is called only when one of them changes, since the OK marks the project dirty. +The plate types are those the sidebar's selector offers (`meta.offered`), none while it is hidden. The +custom filament orders are refused while a slot is a mixed filament, where the dialog greys them out. +Turning spiral vase on asks the dialog's question about the settings it changes, so the reply can be +`blocked_by_dialog`. `locked` goes through `PartPlateList::lock_plate()` as the lock icon does, and only +when it differs, so setting it twice leaves the plate locked (the palette's `plate_toggle_lock` stays a +toggle). `name` goes through `Plater::rename_plate()`. The call is one undo step (`Plater::SingleSnapshot`; +the dialog itself takes none, the plate tab one per change). The journal records the plate the call +resolved, so a replay sets the same plate. The reply has `applied` (the plate's own values), `effective` +and `changed`. The plate tab's `skirt_start_angle` and the per-plate filament grouping are not in the +scope. + +`list_plates` reports every plate with these values as it prints them, `overrides` (the keys it sets +itself), `current`, `objects` (`[object, instance]`, as `list_objects` places instances), `sliced` (an +up-to-date slice), `wipe_tower` (the project's tower position for the plate) and `layer_gcode`, the +plate's entry of `Model::plates_custom_gcodes`: the Preview slider's ticks, pauses, custom G-code, +templates and filament changes, each `{z, layer, type, filament, color, gcode}` by height. `z` is rounded +to the G-code's 0.001 mm. `layer` is the number the slider shows for the code, found by the slider's rule +for a stored height (the first layer at or above it, `IMSlider::get_tick_from_value()`) in the layers of +the plate's slice result, numbered and placed as the viewer loads them (`gcode_layer_zs()`); it is given +only while that slice is up to date and no slice is running, and it is left out for a code above the top +layer. + +### Preferences + +The preferences scope of `get_settings` reads the app configuration's `app` section, where the +Preferences dialog keeps its settings: `{"scope": "preferences", "keys": [...]}` returns each key's value as +stored (`"true"`, `"1"`, an enum's stored text) and `unknown_keys` for keys the section does not hold. +Keys are required, since the section also holds account and device state and nothing outside the dialog +lists which keys it shows. `set_settings` refuses the scope: a preference changes in the dialog, whose +handlers carry its effects (dark mode, the language, which recreates the GUI, the network plug-in, stealth +mode, render settings redrawn after the dialog closes, and this server's own `mcp_enabled` and `mcp_port`, +which close the endpoint the call came through). Writing the key would skip all of them. + +The dialog's controls are named after their AppConfig keys, so `ui_snapshot` shows the key and +`ui_input {"target": {"name": "export_statistics", "within": "Preferences"}, "value": true}` changes one +through its own handler. The Speed Dial's `open_preferences` takes `[:]` (`general`, `control`, +`graphics`, `online` or `developer`) and opens the dialog there through `GUI_App::open_preferences()`, +scrolled to the key's control and focused; a key on another tab is shown on its own tab. Checkboxes, +number and text fields and the language combobox change this way. The other comboboxes (those of +`create_item_combobox()`, the log level, the login region and the network plug-in version) save from a +handler on their drop-down list, where a person's pick arrives, while `ui_input` sends the selection to the +combobox itself: it shows the new choice and saves nothing. + +### Calibration tests + +`calibrate` runs a Calibration menu test (temperature, max volumetric speed, pressure advance as tower, +line or pattern, flow ratio in its four passes, retraction, VFA, cornering, input shaping frequency and +damping) one level below its dialog: it calls the same `Plater::calib_*` the dialog's OK calls, with +the `Calib_Params` the dialog would build, and never shows the dialog. The dialogs only collect and check +numbers, so their rules are shared with the tool in `libslic3r/calib.cpp`: `calib_default_params()` (the +values each dialog opens with), `check_calib_params()` (what each dialog refuses, as an enum, so each +dialog keeps its own message box and the tool states the rule with the values given), +`cornering_end_limits()`, `has_junction_deviation()`, `belt_temp_tower_asset()` and the VFA dialog's +auto-adjust, `fit_vfa_speed()` with `vfa_candidate_layer_heights()`. The input shaper types offered per +firmware come from `shaper_type_values()` beside the dialogs. A parameter the test does not take is +refused, so a misplaced argument never passes silently. + +Two choices that only refill the dialogs' fields are not parameters: the pressure advance defaults follow +the printer's `extruder_type` (the dialog's Extruder type radio, which starts at Direct Drive whatever the +printer), and the temperature dialog's filament type is replaced by the range itself. Temperatures are +clamped to 155-500 °C and rounded down to multiples of 5, as the dialog's fields do when they lose focus, +with a warning naming the corrected range (the field's message box says 170). The input shaping Y range, +and the damping test's Y frequency, default to the X one; RepRapFirmware, whose dialogs show one range, +refuses them. VFA's Yes/No questions are answered Yes: the reply's `adjusted` gives the lowered layer +height or end speed, and a warning says when the upper blocks stay above the filament's limit. + +Every test starts a new project, whose prompts the tool answers itself (`skip_confirm` on each +`calib_*`): a project with unsaved changes needs `discard_changes`, and modified presets need `changes`, +`"keep"` to run the test with them or `"discard"` to drop them first through +`GUI_App::discard_current_preset_changes()`. Unlike `new_project`, which keeps modified presets silently, +`calibrate` refuses without `changes` and lists the modified keys: a previous test's settings would +otherwise spoil this one. With `"discard"` the test's rules and defaults come from the saved printer +preset, which is what remains. The tests write their filament settings to the preset the filament tab +edits, while the test objects print with slot 1, so the tool first points the tab at slot 1's preset +(`edit_filament_slot()`, the switch `set_settings` uses for a slot), as a person must; the reply's +`presets_changed.filament` says `filament_slot: 1` and `tab_switched_from` when the tab moved. A tab that +edits another slot's modified preset is refused with `"keep"`. `run_action calib_*` keeps the GUI's +behaviour. + +The reply has `test`, `project`, `params` (the values used, in the tool's units: max volumetric speed in +mm³/s, a pattern's default acceleration and speed read back from the process), `objects`, `names`, +`plates`, `presets_changed` (per preset type, the settings the test changed, as `set_settings`' +`changed`), `result_keys` (the scope and keys where the measured value belongs), `warnings`, `adjusted`, +and `discarded` and `modified` as `new_project` reports them. The journal records the call with its +effective parameters, defaults included, so a replay does not depend on the dialogs' defaults; VFA's end +speed is recorded as asked and a pattern's default acceleration and speed are left out, since both are +computed from the presets again on replay. To keep a measured value, the agent leaves the test with +`new_project {"discard_changes": true, "changes": "discard"}`, sets the value with `set_settings` and saves +it with `save_preset`; staying in the test project, `set_settings {"reset_all": true, "values": ...}` on +the preset's scope drops the test's settings there and sets the value in one call. The Speed Dial's `calib_*` commands still open +the dialogs, and their descriptions point at `calibrate`. + +### Design tab: `cad_call` + +`cad_call {method, params}` reaches the Design tab's control surface (`CAD/McpControl.cpp`), the +same methods the `ORCA_CAD_MCP` socket serves, as one generic tool rather than a schema per +method, so agents that never open the Design tab pay nothing for it. It needs the CAD feature on +(Preferences > Features), which the app reads only at startup. One table, `kCadMethods`, declares +every method's name, access and handler; the dispatcher, the busy gate and `describe_tools` all +read it. `describe_tools` is the parameter schema of record: one row per method with typed params, +units and defaults, and its access. `params.method` (a name or a list) and `params.query` (text in a +name or summary, any case) narrow the reply; an unknown name fails with the close ones. + +Access decides what `DesignPanel::mcp_busy()` lets through. `read` methods run under an open +feature card or sketch session, `sketch` methods drive the live sketch session, and `change` +methods are refused under either, as the GUI would not let the edit land there. Neither `change` +nor `sketch` methods run while a body Move is open, since its session holds a body index that a +change could point at another body. Nothing runs while a rebuild's worker owns the document. + +A method that fails is an error (`CadCallError` → `isError`) and leaves the design as it was, so +`export_script` drops it and a script never replays a call that did nothing. That holds for +argument errors and for a rebuild the kernel rejects alike. The exceptions are the older methods +`describe_tools` lists in `legacy_ok_false` (`fillet`, `chamfer`, `boolean`, `pattern`, `mirror`, +`shell`, the surface methods, `import_step`, `set_variable` and others): they report a rejected +rebuild in their reply, `{ok: false, error}`, after the same rollback, so such a call is journaled +and replays the same rejection. `extrude`, `revolve`, the `hole` methods, `split` and `sketch_add` +are not on that list, so none of them fails two ways depending on its arguments. The feature +methods off the list add through `add_feature()`: one checkpoint, a rebuild, and on failure +`CadDocument::rollback()`, which restores the checkpoint without leaving the refused recipe on the +redo stack and with the redo branch the checkpoint cleared, then "Edit rejected" on the status line +as for a refused GUI edit. Features made through `cad_call` are named as the cards name them +("Extrude 3"), from the panel's own counter. + +`generation` guards face and edge ids within a session, but its value depends on the session's +history, so the journal records `cad_call` without it and a replay rebuilds the same ids. + +The plane-taking methods (`sketch_begin`, `extrude`, `revolve`, the `hole` methods, `thread`, +`split`, `pattern`, `mirror`, `helix`, `project`) share one resolver, `cad_resolve_plane()`: `"XY"`, +`"XZ"` or `"YZ"` through `modeling_origin`, `{"datum": i}` for a Plane feature, or +`{"body": b, "face": f}` for a planar face. A face plane for sketching is +`CadDocument::plane_of_face()` (outward normal); for drilling it is +`CadDocument::inward_plane_of_face()`, the Hole card's plane (normal into the body, x along the +longest edge), and the hole or thread goes into that face's body. Their replies carry the `frame` +used. Because a sketch's base plane passes through `modeling_origin` like every feature's, a sketch +lands where the features drawn on the same plane land, and the coordinates in a script are relative +to the modeling origin on any printer. + +`describe_scene` reads the document: the features, each with the fields an expression drives +(`bound`), the variables with their values (all null, with `variables_error`, when one does not +evaluate), the bodies with the feature that made them, whether their eye is on, the colour the +canvas draws and whether the Move gizmo placed them, the undo and redo depth, mate conflicts and the +document's `auto_close_loops`. `describe_feature {feature}` reads one feature as its card shows +it, from one per-type table, `feature_card()`: `params`, the `editable` ones named as the +`CadFeature` members (the names `set_feature_expr` binds) with the `ranges` of the card's spin +controls, `expr`, the structure the card keeps in `refs` (feature and body indices, face and edge +ids), a sketch's plane, entities and constraints (snake_case types, point references with a role, +angles in degrees), and `used_by` / `bodies_made`. `used_by` comes from the kernel's own reference +visitors, `CadDocument::for_each_feature_ref()` and, for a datum plane, `for_each_datum_ref()`, +the lists that deleting and moving a feature remap. + +`set_feature {feature, fields}` is a card's Confirm in edit mode: one checkpoint, then +`CadDocument::replace_feature()` with a copy whose fields `cad_apply_feature_fields()` checked +against the same table, so it takes only what the card edits (numbers within the card's range, and +its choices). A field an expression drives is refused, since the next rebuild would overwrite it, +and so is an end condition that needs a pick the feature does not hold. A rebuild the kernel +refuses fails the call after `rollback()`. Numeric fields go through +`CadDocument::set_numeric_field()`, the allow-list expressions use, so a literal edit and a binding +reach the same fields. An empty `expr` removes a binding (`set_feature_expr`) or a variable +(`set_variable`), as the Variables panel's Clear and Remove do; a binding on a field the evaluator +does not know, or removing one that is not there, is refused. + +A sketch goes from a session to a solid in typed calls. `sketch_begin {plane}` opens the session +through `DesignPanel::begin_sketch_session()`, the code a plane or face pick runs, without the tool +menu that follows the click. `sketch_commit` is the sketch's ✓, whose commit handler adds the Sketch +feature and solves its dimensions; the reply reads the committed feature back: `sketch_index`, its +name and its loops. An empty sketch is refused before anything changes and the session stays open, +because an exported script leaves the failed call out and its next sketch call needs that session. +`sketch_describe {sketch}` describes a committed sketch as the open one is described, through +`DesignSketchTool::loop_report(entities)`. Its loop indices are those `extrude {loop}` takes: a +region lists the loops inside it under `holes`, and each of those is a loop of its own. +`extrude {sketch}` and `revolve {sketch}` are the cards' Confirm on a committed sketch. Extrude +takes the whole sketch (`add_extrude`) or, with `loop`, one region and the loops inside it, the list +a loop picked in the viewport hands the card (`add_extrude_entities`). Its `boolean: "auto"`, the +default with a sketch, joins the body the sketch touches (`CadDocument::body_touching_sketch()`), +else makes a new body, as the card's default does; `body` names the body to work on in every form. +Revolve's axis is a line of the sketch (`axis_entity`), else the sketch's only centerline, which the +card also offers first (`DesignPanel::default_revolve_axis_entity()`), else a plane axis. +`cad_sketch_extrude()` and `cad_sketch_revolve()` check every argument before the checkpoint and +return the call that adds the feature. + +Inside the session, the sketch's own tools are reached without a pointer through +`cad_sketch_call()`, which needs only the live `DesignSketchTool` and checks every argument before +it changes anything. `sketch_add` takes, besides lines, arcs, circles and points, the shapes the +drawing tools build: a polygon (by its circumradius, or across the flats, the tool's inscribed and +circumscribed fits), a slot, an ellipse, an elliptical arc and a spline. Their fields are those +`sketch_describe` reads back (`radius`, `rminor`, `rotation`, `ctrl`); each is turned into the clicks +its tool takes and built by the tool's own builder and shape grouping +(`DesignSketchTool::add_shape_scripted()`), leaving the tool's sticky polygon and construction +settings alone. Angles are radians, or degrees under a `_deg` name. `sketch_fillet`, +`sketch_chamfer`, `sketch_trim` (with `extend`) and `sketch_transform` (move, rotate, scale, array, +polar array) run the edit tools' own apply steps through scripted entry points, so they keep the +constraint upkeep a click gets: a fillet arc bound coincident and tangent to its legs, constraints +an op invalidates released, array copies bound to their source. They leave the armed tool armed, +and are refused while a gesture or a value field is pending, which the tool's apply step would +take over. `sketch_trim` picks the entity nearest `at` within a `tolerance` in mm, where the +scissors' click uses a pixel radius. `sketch_constrain` is a CONSTRAIN bar button: with +`entities` (else the selection) the bar's planner, `plan_entity_constraint()` with +`write_plan_value()` in `SketchEngine`, shared with the panel, chooses the points, and the value it +would ask for defaults to the current one; with `refs` the references are taken as written, in the form +`sketch_constraints` and `describe_feature` report them (`{entity, role}` for a point, `{entity}` for +a whole entity, `"origin"`, `"x_axis"` and `"y_axis"` for the sketch's implicit references), which +also reaches the types the bar has no button for (distance, lock, point on line or object). A +constraint the sketch cannot solve with is rolled back and the call fails; a refused pick names the +planner's reason as a code. `sketch_unconstrain` is a constraint row's delete button; the later +indices move down. `sketch_constraints` reads the open sketch's constraints, or a committed one's +by `sketch`. Live sketch edits are not on the Design undo stack until the commit, as in the GUI. + +`query_topology` reads a body from one enumeration (`faces_of()`, `edges_of()`, whose ordinals are +the ids every other method takes). A face's kind is its OCCT surface type, from +`GeometryEngine::surface_info()`, with its area and the numbers that define it: a cylinder's radius +and axis, a cone's apex, axis into its opening, half angle and the radii the face reaches, a +sphere's centre and radius, a torus's centre, axis and radii; `internal` marks a bore or a +countersink. Edges are lines, circles, ellipses, B-splines, Béziers or other. Filters narrow the +list they apply to: `kinds`, `at_extreme` (the face on one side of the bounding box) and `direction` +(a planar face's normal) for faces; `edge_kinds`, `direction` (a line) and `convex` for edges. When +filters are given, a list none of its filters names is empty, or with `adjacency` holds the +neighbours of the other list's matches, so `{kinds: ["conical"], adjacency: true}` returns the cones +with their edges. Adjacency comes from `edge_faces()` (one face for a seam), and convexity from +`edge_convexity()`, OCCT's fillet classification (`ChFi3d::DefineConnectType`). `limit` and `offset` +page both lists alike; `face_count`/`edge_count` stay the body's totals and +`faces_total`/`edges_total` count what matched. + +`measure` keeps `distance`, between the refs' representative points (a face's centroid, an edge's +middle sample), and adds `min_distance` with the closest points (`GeometryEngine::min_distance()`, +OCCT's `BRepExtrema_DistShapeShape`), and `parallel_gap` across two parallel planar faces. Each ref +may name its own body, and `{"face": f, "axis": true}` stands for a cylinder's axis over the face's +length, so a hole's height or spacing is one call. + +The hole methods drill a face plane's own body, or the body `body` names, else the last body, and +take `at` instead of `x`/`y`: a world point projected onto the plane along its normal (the reply's +`off_plane` says how far), or a cylindrical face or circular edge whose axis the hole shares, which +replays on any printer. `cad_hole_placement()` resolves all of it before the checkpoint. `extrude +{face}` is the Extrude card's push/pull of a picked planar face (`add_extrude_face`), joined to that +face's body by default. `plane` is the Plane card's Confirm: every construction (offset, angle, +midplane, tangent, two edges, coincident) with its references as `{body, face}` or `{body, edge}`, +checked by `CadDocument::datum_plane_refusal()`, the card's own check, before the checkpoint; a +parameter the construction would ignore is refused. + +`thread`, `sweep`, `loft` and `split` are their cards' Confirm. `thread` takes a cylindrical face or +a circular edge, as a pick sets the Thread card: `CadDocument::thread_target()`, which the card's +pick also runs, puts the thread on that cylinder's axis from its base, on that body, internal for a +bore. Without a `designation` the size is the standard nearest the cylinder, +`nearest_thread_standard()`, the card's inference: a bore is matched on the minor diameter, a boss +on the major, over ISO metric and UTS together, so a 5 mm bore infers 1/4-20 UNC. On a plane the +thread is placed as a hole is (`cad_hole_placement()`), needs `internal`, and either a designation or +a custom `diameter` and `pitch`; the depth is the 60 degree V's for the pitch and role unless given. +`sweep` takes a sketch or a Helix feature as its path, as the Sweep card lists both; along a helix +the kernel keeps the profile at a fixed angle to the helix axis (`SketchEngine::make_sweep` with a +binormal), as a spring's or a thread's wire is drawn. `helix` replies with its `start` and +`tangent`, where a profile is drawn across the curve. `loft` takes two or more sketches in order. +`split {plane}` is the Cut card's feature (`add_cut`) with the card's plane forms plus a face plane, +`offset`, `flip` and the kernel's `keep_upper`/`keep_lower`, which the card always leaves both on; +`split {face}` splits along a face's plane. A plane clear of the body is refused, since the kernel +would leave one piece empty. The reply names the pieces: the upper one keeps the body's index and +the lower one follows it. + +Thread, sweep and loft rebuild as their cards do, through `DesignPanel::recompute_guarded()`: the +kernel works on a worker thread while the UI thread waits in `wxYield()` behind a progress dialog +that appears after 300 ms. A long thread or sweep takes seconds, and meanwhile the window paints +and inspection tools answer from inside that loop: `get_state`, `ui_snapshot` (the dialog is a +non-modal `wxProgressDialog` titled "Design") and `screenshot`, of the window or of the dialog's own +ref. On Windows the dialog is the system's task dialog, run on a thread of its own, so it is no wx +window and `ui_snapshot` does not list it; the other tools answer as elsewhere. Mutating calls are refused by `UiInvoker` as running inside `cad_call`, and the `ORCA_CAD_MCP` +socket's requests by `mcp_busy()`, since the worker owns the document. A call past the reply budget +becomes a running job; the socket waits on such a request past its 15 s queue timeout once it has +started. + +`undo` and `redo` are 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. `run_action undo` stays Prepare's history. +They have sketch access, so they run in a sketch session, and like every changing method they are +refused under an open card, Constrain mode or a pending body Move. The Design history is not saved +with a project. + +The Feature tree's and Bodies list's edits are split from their handlers into index-taking +`DesignPanel` cores that the handlers call after resolving the selected row, so `feature_delete`, +`feature_move` (one place up or down), `feature_set_enabled`, `feature_rename`, `body_set` and +`body_delete` run the GUI's own code without selecting a row, and queue no face highlight of their +own. Each tree edit is one Design undo step; when the kernel refuses one (a consumer moved above +its input, a feature shown without the body it works on, a delete a later feature cannot survive), +the kernel has already put the features back, `CadDocument::abandon_checkpoint()` drops the +checkpoint and restores the redo branch it cleared, and the call fails with the kernel's reason. +A feature rename is its own undo step. `body_set {body, name?, color?, visible?}` checks every +argument before it changes anything; a body's name and colour are saved in the recipe and are not +in the undo history, and its visibility is view state that decides what `commit` sends. +`body_delete` deletes the feature that made the body (`CadBody::source_feature`). Deletes, moves and +hiding renumber features and bodies, so the replies carry the new counts and `generation`. + +`commit {mode, replace}` is Commit to Plate: `DesignPanel::commit_to_plate()`, which the button +also runs, sends the visible bodies (a lone body even when hidden) at their Move-gizmo positions, +as one Prepare undo step, and shows Prepare. A body named in the Bodies list names its object, or +its part of an assembly; otherwise the design's labels ("Design Body", "Design Assembly") are used. +`mode` applies to this call only and leaves the split button and `design_commit_mode`, the user's +choice, as they are. `replace` lists Prepare objects to delete afterwards through the Object +List's delete path, under one outer snapshot so the commit and the deletions are a single undo +step. It refuses before anything changes: an index out of range or repeated, an object that is +part of a cut (deleting one asks the person first), an open gizmo, a design with no body, or every +body hidden. The reply gives the new objects' `list_objects` indices after the deletions. +`commit` is the one method that changes Prepare's model, so the `ORCA_CAD_MCP` socket refuses it: +the socket has no mutate guard, no modal check, and runs requests inside any nested event loop. + +`new_design {discard_changes}` is New Design without its confirmation: `clear_document()`, which +also clears the Design undo history and leaves committed objects on the plate. A design with +features, bodies or variables needs `discard_changes: true`. `export_step {path, overwrite}` is +Export STEP… without its file dialog (`DesignPanel::export_step_to()`, shared with it): every +body as native B-rep at its Move-gizmo position, under the server's output-path rules. The +socket takes it with the same checks. `import_step`, `import_mesh` and `validate_against`'s +`reference.step` take an absolute, existing path, like every file the server reads. + +`set_view {tab: "design"}` shows the Design tab, and while it is shown `camera` points the Design +view as its own controls do: a direction through `DesignCanvas::set_view()`, `default` its Home +view (iso, fitted), `fit_objects` its `fit_view()`, and `fit_selection` the pick's box, refused when +nothing is picked. The camera is applied in a second UI closure after `settle()`, because the tab +takes the shared camera only when its page shows (`DesignPanel::on_tab_shown()`). `fit_bed`, `view` +and the Preview fields are refused with the Design tab, since they show Prepare or Preview. The +Design view is a canvas target for the `ui_*` tools and screenshots (see GUI automation and +Screenshots). + +A change made only in the Design tab marks the project modified, as other project data outside +Prepare's undo stack does: `sync_recipe_to_model()` sets the plater's dirty flag besides the +backup's change mark. So `get_state.project.dirty`, the window title and `open_files` / +`new_project {discard_changes}` agree with the unsaved-changes prompt that Open and New Project +show. A project holding only a design loads no objects, and `Plater::load_project()` still names +it after its file, since a loaded recipe counts as a loaded project. + +`tests/slic3rutils/test_mcp_cad.cpp` (`[Mcp][CAD]`) checks the method table against +`describe_tools`, the plane resolver, the rollbacks, and the methods through their public seams +(`cad_sketch_extrude()`, `cad_sketch_call()`, `cad_query_topology()`, `cad_thread()` and the rest), +which take a `CadDocument` or a bare `DesignSketchTool` and need no Design panel. The replay +scripts run on an instance that `tools/mcp/orca_mcp.py launch --cad` starts: +`tools/mcp/tests/cad_sketch_to_solid.json`, `cad_sketch_edit.json`, `cad_topology_targets.json`, +`cad_features.json`, `cad_doc.json` and `cad_canvas.json` (the Design view as a canvas target, its +key hook, and the dirty flag). `tools/mcp/test_cad_replay.py` records a session with +failed calls and `generation`s, exports it and replays it to the same features and mass +properties; `tools/mcp/test_cad_slow_build.py` checks the window during a guarded rebuild; +`tools/mcp/test_cad_failed_job.py` exports a session whose call failed after its reply budget +(a hole that misses a slow-to-rebuild coil), which leaves it out, and replays it. + ## Speed Dial catalog `list_actions` and `run_action` serve the Speed Dial's `ActionRegistry`: built-in commands, plates, @@ -324,7 +1131,7 @@ recent projects, plugin scripts and pages, and, on request, settings. Built-in c shows: `description` (English, for agents), `param` (a `CommandParam {type, help}`, typed `None`, `Percent`, `Tab`, `Path`, `Index` or `Text`) and `completion` (`Export` when the effect finishes in the background after `run()` returns). `describe_commands()` fills them from one table, with a -key-prefix rule for calibration wizards, camera views and primitives, and `CommandAction` copies +key-prefix rule for calibration dialogs (pointing at `calibrate`), camera views and primitives, and `CommandAction` copies them into the `AppAction`. The palette keeps `input` for its picker and never passes a path. `ActionRegistry::describe(Query)` searches id, title, group, source and description, including the @@ -345,7 +1152,7 @@ turns a bad path into an Error result. |---|---|---| | `load_project` | `.3mf` | `Plater::load_project(path)`; still asks about unsaved changes | | `import_file` | model file | `Plater::load_files({path})` | -| `import_configs` | `.ini` or `.json` | `MainFrame::load_config_file(path)` | +| `import_configs` | `.json`, `.zip`, `.orca_printer`, `.orca_filament`, `.orca_bundle`; `.gcode` | `MainFrame::import_configs(files, confirm)`; for G-code `MainFrame::load_config_file(path)` | | `save_project_as` | output `.3mf` | `Plater::save_project(true, path)` | | `export_gcode` | output `.gcode` | `Plater::export_gcode_to(path)`; completion `Export` | | `export_sliced_file`, `export_all_sliced_file` | output `.gcode.3mf` | `Plater::export_gcode_3mf(all, path)` | @@ -353,9 +1160,78 @@ turns a bad path into an Error result. | `export_3mf` | output `.3mf` | `Plater::export_core_3mf(path)` | | `export_stl_multi` | existing directory | `Plater::export_stl(..., multiple, dir)` | | `add_primitive_svg` | `.svg` | `GLGizmoSVG::create_volume(path, type)`: a new object, or a part of the selected one; a job | +| `export_config` | existing directory | `ExportConfigsDialog(parent, dir)`: the dialog still opens, and its OK writes there | -Commands that still open a dialog, such as `export_config` or `plate_rename`, return -`blocked_by_dialog`, and the agent answers the dialog. +The six shape commands (`add_primitive_cube`, `_cylinder`, `_sphere`, `_cone`, `_disc`, `_torus`) +take a `Text` param, the size the Primitive size dialog asks for (`"40 40 10"`, `"90 4"`), and then +call `ObjectList::load_generic_subobject(type, INVALID, true, size)`, which skips the dialog. A param +with the wrong count of positive numbers is an Error result. With an object selected they add +nothing (`ObjectList::can_add_shape_object()`), and say so as an Error, in the palette too. + +The object structure commands stand for the object list's context-menu items and the plate menu's +Order By. Like those items, they act on the object list's selected rows, which `select` sets: + +| Command | Param | Entry point | Refused when | +|---|---|---|---| +| `obj_type_part`, `_negative`, `_modifier`, `_support_blocker`, `_support_enforcer`, `_precise_seam` | none | `ObjectList::set_volume_type(type, true, false)` | a selected row is not a part; the object's last solid part; a text or SVG part to a support or seam type | +| `obj_rename` | Text: the name | `ObjectList::rename_item(item, name)` | not one object or part row; characters a file name cannot hold | +| `obj_set_instances` | Index: 1-1000 | `Plater::set_number_of_copies(num)` | no object selected; 0 (use `obj_delete`); a cut object; an unprintable instance | +| `obj_assemble` | none | `ObjectList::merge(true)` | fewer than two object rows; a cut object | +| `obj_instances_to_objects` | none | `ObjectList::split_instances()` | no object with more than one instance selected | +| `obj_order_by_name`, `_filament`, `_height`, `_size` | Text: `all` for every plate | `ObjectList::order_objects(order, all)` | no objects to order; a gizmo is open | + +Change Type checks the rows itself: with no part row selected, `set_volume_type()` falls back to the +3D selection, which for a selected object holds every part, a change no menu offers. That function +returns why it changed nothing and shows it only for the menu (`show_errors`), so the rule stays in +one place. `rename_item(item, name)` and `set_number_of_copies(num)` are the work of the Rename and +Set number of instances items without their dialogs, which the items keep; without a param, the +commands open those dialogs. Order By keeps the menu's toggle: choosing the order the objects already +have reverses it. + +A command whose effect its message does not carry sets `AppActionRunResult::reply`, a JSON object +whose fields `run_action` adds to its reply and the palette never shows. `obj_order_by_*` reply with +the sorted plates' objects in their new order (`order: [{object, name, plate}]`) and `descending`, +`obj_assemble` with the new object's `object` and `name`, `obj_instances_to_objects` with the +`objects` the instances are in, and `obj_set_instances` with `object` and `instances`. + +Commands that still open a dialog, such as `export_config`, `plate_rename` or `send_gcode` (see +Print host uploads), return `blocked_by_dialog`, and the agent answers the dialog; the plate scope sets +a name without one. + +`filament_add` and `filament_delete` are the filament list's + and - buttons and a slot's Delete menu item +(`Sidebar::add_filament()` and `Sidebar::delete_filament()`, then the slot counter). They run where the +buttons show, for printers that take several filaments through one extruder, and not on a G-code file; +elsewhere, and at the slot limit or with one slot left, they return Info. A new slot goes after the +physical slots, so mixed filaments move up by one with the objects on them; the message names the new +slot. `filament_delete` takes a 1-based slot, the last physical one without it, and remaps the objects on +it as the GUI does. A mixed filament is refused (an Error): it is deleted from the mixed filament list. + +`import_configs` with a path imports presets as the Import Configs dialog does, through +`MainFrame::import_configs()`, the dialog's work split from its file picker and result message: the files +go to `PresetBundle::import_presets()`, and the presets are reloaded and the sidebar refreshed. A preset +file (`.json`) is imported alone, a `.zip` or bundle (`.orca_printer`, `.orca_filament`, `.orca_bundle`) +with every preset inside it. The dialog asks about each preset that exists already; the command answers +that question itself, never with "to all", so it is asked about every such preset and the message can name +them all: the param `{"path": ..., "on_conflict": "overwrite"}` replaces them, and by default (`"skip"`) they +are kept. `overwrite`, which other path params use for an output file, is refused here rather than read +with that other meaning. The message lists the presets imported, replaced and kept, found by comparing the +preset names before and after; a call that changes nothing is an Error with the dialog's hint about adding +the printer first. A `.gcode` still loads the settings it was sliced with through +`MainFrame::load_config_file(path)`. + +`export_config` with a directory still opens the Export Preset Bundle dialog, given that directory: its +OK writes there instead of asking for a folder. The agent picks the kind by clicking its label +(`ui_click`), checks presets with `ui_input` on their checkboxes, which are named after the preset, printer +or filament they stand for, presses OK with `dialog_respond`, and answers the result message. The command +is an Error when the dialog is closed without exporting. Preset files are not exported without the +dialog: its archive functions read its own checkboxes. + +A command that does nothing, such as an object command with nothing selected, returns its message +with `AppActionRunResult::done` false. The palette shows it at its level, Info for most, as it always +has; `run_action` replies `isError`. `obj_arrange` and `obj_orient` say why they did nothing (no +objects, or another background job running) and reset the prepare state a plate's Arrange or Auto +Rotate icon leaves behind, so they act on every plate as the toolbar does. Their job is the call's +operation (see Worker jobs), so `run_action` returns once it is done. ### Making a feature reachable @@ -381,14 +1257,16 @@ and get the plater with `ui_plater()`, which fails until the main window is up. with a message the model can act on. Call `settle()` after a change so queued events are handled before the reply, and page lists with `page()`. For work that finishes later, call `ctx.begin_operation()`, wait with `poll_ui()`, and give the work an identity, as slicing and -export do. Describe the tool in English, including what the reply holds and when it is a job. +export do. Work on the UI job worker needs none of that: the call that starts it holds it as its +operation (see Worker jobs). Describe the tool in English, including what the reply holds and when it is a job. ## GUI automation -`ui_snapshot` (`UiInspector`) returns a compact text tree of the shown top-level windows, the -menus, the GL toolbar items and gizmos, and each canvas's last-frame ImGui items, capped by -`max_nodes` and filtered by `query`. The tree is a second text block of the result. Refs (`w`, `m`, -`t`, `z`, `g` plus a number) are never reused and carry the UI generation and a liveness check, so a +`ui_snapshot` (`UiInspector`) returns a compact text tree of the shown top-level windows, each +followed by the popups that opened from it, the rows of their lists, the menus, the GL toolbar items +and gizmos, and each canvas's last-frame ImGui items, capped by `max_nodes` and filtered by `query`. +The tree is a second text block of the result. Refs (`w`, `m`, `t`, `z`, `g`, `r`, `p` plus a number) are +never reused and carry the UI generation and a liveness check, so a ref to a destroyed or rebuilt widget is reported stale. A field is named by the setting it edits: its option key is read from the "parameter name" line of its tooltip, and its label comes from the option's definition. Failing that, the label to its left on the same row names it, then its @@ -401,13 +1279,20 @@ journal stores. A locator is one of: - `{label, class, name, within, index}` for other widgets; - `{tab: "General", within}` for a notebook page; - `{menu: "File>Export>Export G-code"}`, `{gltoolbar: "arrange"}` or `{gizmo: "Move"}`; -- `{imgui: "label", imgui_name: "name", window, canvas, index}` for an ImGui item, by either or both. +- `{imgui: "label", imgui_name: "name", window, canvas, index}` for an ImGui item, by either or both; +- `{row: "Plate 1>Cube>Cylinder", column, within, index}` for a row of a list, tree, table or + drop-down list (see Rows and popups below); +- `{plate_icon: "lock", plate: 0}` for a plate or one of its icons in the Prepare view (see Plate + icons below). -The object list's rows are items of a `wxDataViewCtrl`, not windows, so no locator names one. `select` selects objects, instances and parts, after which `run_action` runs the object operations -the catalog has (delete, split, mirror, center, drop, instances, arrange, orient) and `set_settings` -with the object or volume scope edits their settings. Adding a part or modifier and changing a -part's type have no tool yet. +the catalog has (delete, split, mirror, center, drop, instances, arrange, orient, change type, rename, +assemble, set as individual objects, order by) and `set_settings` with the object or volume scope +edits their settings and filament. `add_part` adds parts, modifiers and support shapes, +`set_layer_ranges` sets height range modifiers, and `set_layer_height_profile` runs the Variable layer +height panel's buttons. `set_layer_gcode` does what the Preview layer slider's right-click menu does. +The rest of the object menu is reached through a right click on the object in the 3D view, or on +its row of the object list, with `popup_item` (see Menus below). A label that matches both a row's label and the one field it names resolves to the field. `within` names a window other than the main one, whose title follows the project name and is left @@ -420,7 +1305,13 @@ labels unpainted. Activation prefers a widget's own dispatch: `wxEVT_MENU`, `GLToolbar::force_left_action()` (or `force_right_action()` for a right click), `GLGizmosManager::click_toolbar_icon()`, a notebook's `SetSelection()`, a native control's semantic event, or a custom widget's public API. Canvas -gestures and ImGui items get synthesized wx events with a render between steps. +gestures and ImGui items get synthesized wx events with a render between steps. A right click on a +plain window gets the context menu event a person's would: on macOS wx makes it from the right press +the window's handlers pass on, elsewhere the system sends it, so the click sends it there. A GL toolbar item's +visibility and enabled state are brought up to date (`GLToolbar::update_items_state()`, what the +canvas's idle handler does) before `ui_snapshot` lists them and before a click checks them, so an +item a `select` just enabled is not read as disabled. A click on an ImGui item whose centre lies +under another ImGui window (a notification over a panel's button) is refused, naming that window. `ImGuiWrapper::set_item_recording()` supplies the ImGui items (see below). `SyntheticInput` holds a gesture's keys, buttons and pointer for code that reads hardware state through `get_key_state()` and `get_mouse_state()`: the canvas, gizmos, and the object list's Ctrl/Shift multi-select. Mouse @@ -431,8 +1322,155 @@ keys are released however the gesture ends; a `ui_mouse` `down` keeps its button rejects for its arguments never runs and changes nothing), the end of the script that pressed it, the closing of the endpoint for a client's press, or the service's stop. A client's gesture that reaches the UI thread after its endpoint closed is refused. Keys without a target go to the -focused window inside the topmost modal, else that modal, else the focused window, else the 3D -canvas. +focused window inside the topmost modal, else that modal, else the focused window, else the 3D view +shown. + +A key is delivered as a real key press is on every port: `wxEVT_CHAR_HOOK` goes to the target first +and travels up through its parents (`wxKeyEvent` propagates it) to the top-level window, or stops +at a dialog (`wxWS_EX_BLOCK_EVENTS`); only when no hook takes it, or the one that does allows the +next event (`DoAllowNextEvent()`), do `KEY_DOWN` and `CHAR` reach the target. So a panel that binds +its own hook sees the keys sent to its widgets, as the Design tab's does for Escape, Enter and its +tool shortcuts, and the main frame's hook still sees what none below it takes. + +The Design tab's view is a `GLCanvas3D` of its own (`DesignCanvas::gl_canvas()`), outside the +plater's three. `live_canvases()` lists the plater's, which `get_state.gizmo` and the idle checks +read, since the Design view has no gizmos; `ui_canvases()` adds the Design view for what the `ui_*` +tools and screenshots reach: `ui_snapshot` lists its ImGui items, `ui_click` and `ui_key` act on it, +and `ui_mouse` takes `canvas: "design"` (`"current"` is the view shown, `shown_canvas()`). A click +there goes to the Design view's own handlers, so a left click picks a face, edge or body and a right +click opens the offer menu, which is listed or run like any other. Points of the model name +Prepare's objects, so on the Design view `ui_mouse` takes pixels only; `cad_call query_topology` +gives its faces. + +### Menus + +Every popup and context menu goes through `popup_menu()` (`SyntheticInput.hpp`), which is +`wxWindow::PopupMenu()` unless the MCP server has installed a capture +(`SyntheticInput::set_menu_capture()`). The capture is there because a native menu loop holds the UI +thread until a person closes the menu: on macOS it pauses wx's pending events, and with them every +`run_ui()` closure. So MCP never shows a menu. `UiInspector::on_menu()` takes a menu that opens in a call's window: from the start of each of +the call's UI closures (`UiInvoker`'s activity hook) until the first `wxEVT_IDLE` with nothing queued +after the closure ends, so a menu opened by an event the call queued (a 3D view posts its right click +to itself) or by a `CallAfter` chain is taken too. The window closes a second after its closure in any +case (`on_menu()` checks the age itself, so no idle is needed), so a stream of queued events can't +keep a person's menus from showing. Only menus of the event +loop the closure ran in are taken: a person's right click in a dialog the call opened, whose loop is +another, shows its menu, and a call working inside that dialog has a window of its own there. + +The capture does what `wxWindowBase::PopupMenu()` does before it shows a menu: it sets the invoking +window and calls `UpdateUI()`, so the `wxEVT_UPDATE_UI` handlers MenuFactory binds on the main frame +set each item's enabled and checked state as a person would see them. `ui_click`, `ui_mouse` and +`ui_key` arm a capture in the closure that delivers their input (`arm_menu()`). The first menu that +opens goes to it: without `popup_item` it is listed in the reply as `popup_menu` (`items`, and the +`disabled` and `checked` ones) and nothing runs, as if the person pressed Escape; with one, that item +runs: a check item is toggled or a radio item checked, then `SendEvent()` on the submenu holding it, +which dispatches through that menu, its parents and the invoking window as a pick from a shown menu +does, and the reply says `ran`. It runs inside the `popup_menu()` frame, so `Plater::PopupMenu()`'s +deferral of slicing and error messages, and the popup position Add Text uses, are in effect. A +command that opens a dialog from the 3D view's queued right click leaves it open when the call +returns; the reply then lists it under `dialogs`. The call waits for that queued click by queuing a +`CallAfter` on the canvas behind it (one handler's queue is first in, first out) before it settles +and reads the capture. A later menu in the same call is closed unseen and counted (`menus_closed`); +a menu that opens in a window where nothing is armed (a `cad_call run_verb` whose offer opens later) +is closed unseen too. The last three such menus, with the tool whose window took them, are in +`get_state.closed_menus`. + +A menu path is the item labels joined with `>`, as `GetItemLabelText()` gives them, matched without +case; a trailing `...` may be left out. A label repeated among its siblings is numbered from its +second time on (`Change Filament>Generic PLA #2`), so every listed path names one item, and the +marker the Change Filament list appends to the slot in use (" (current)", translated) is left out of +the numbering and the matching, so a path recorded with another slot in use still names the same +item. A path that names a submenu, a disabled item or nothing fails with the items to pick from, and +so does a `popup_item` when the input opened no menu (a right click on empty space while objects are +selected, in the Preview, or with a gizmo open). Paths are the UI language's text, as other locators +are. With `x`/`y`, `ui_click` clicks that point of a custom-drawn widget (such as the Design tab's +feature tree) as well as of a 3D canvas; a native control, which acts on what the system tells it +rather than on wx mouse events, is refused. + +MenuFactory builds the multi-selection, layer and assemble-view menus afresh for each popup. +`Plater::PopupMenu()` takes them back (`MenuFactory::take_transient()`) and frees them once the popup +has closed, for a person's right click as for MCP's. Their items' `wxEVT_UPDATE_UI` handlers stay bound +on the main frame, but under ids `wxNewId()` never hands out again, so they never run. + +### Rows and popups + +The rows of `wxDataViewCtrl`s (the object list, Compare presets, the upload queue and other data +views), of `wxListBox` and `wxCheckListBox` (the Add Settings checklist), of Orca's `DropDown` lists, +of `wxGrid` tables (the object settings table) and of the Design tab's `DesignRowList`s are listed +under their list as `row` nodes (`list_rows()`): the first text cell is the label, the other text +cells the value joined with ` | `, a checkbox cell its checked state. A data view is walked through +its model from the root, collapsed branches included. An object list row also says what it stands +for by the indices `list_objects` uses (`plate 1`, `object 0 part 1, modifier`, `object 0 layer +range 0-2`). A table's rows are named by their `Name` cell (the object settings table's part rows +by the part), else by their row label; a sort indicator after a column title is left out, and a +table that hides its column labels and draws its titles as its first row is read with that row as +the titles. A drop-down row in a group has the group's label above it; the picked row is the checked +one. A list node lists the names its cells are picked by (`columns:`): header text, `#n` for a +column without one, and for the object list, which shows no header, `Name`, `Height`, `Printable`, +`Filament`, `Support`, `Color`, `Sinking` and `Editing`. + +A row locator gives the labels from the top joined with `>` (an array when a label holds `>`), of +which it matches the last ones, so the plate above an object may be left out; the marker " (current)" +may be left out as in menu paths. Rows are found again by their labels on each use, since models +delete and rebuild their items; a ref stays alive while its list does and the path still names a +row, rows with the same labels being told apart by their order. The journal records the row's whole +path, its `column` and its window's `within`, with `index` when other rows match it. + +A click acts as a person's click on the row's cell (`click_row()`): the cell is the `column` named, +else the row's first. On a data view, the branches above the row are expanded and the row scrolled +into view; the selection is set as the click would set it (Ctrl toggles the row, Shift selects the +shown rows from the current one, a right click selects an unselected row only), and the owner gets +one `wxEVT_DATAVIEW_SELECTION_CHANGED` for the row. The controls report a selection they are given +differently (macOS each change it makes on the way, GTK and the generic control none), so their own +reports are held back for the call and the one a click makes is sent. The synthetic pointer sits at the cell's centre +for the gesture, and the object list reads it through `get_mouse_state()` where it would read the +real pointer: on Windows and Linux its selection handler then acts on the cell under it (Printable +toggles printability, Sinking drops the object, Editing resets the row's settings). On macOS the +native list starts editing an editable icon cell instead, which the object list turns into the same +actions, so a click that names such a column sends `wxEVT_DATAVIEW_ITEM_EDITING_STARTED` too. A +double click sends `wxEVT_DATAVIEW_ITEM_ACTIVATED` (the object list frames the object, or opens the +filament editor on the Filament column), a right click `wxEVT_DATAVIEW_ITEM_CONTEXT_MENU`, whose menu +is captured like any other. `ui_input` with true or false sets a checkbox cell through +`ChangeValue()`, as the toggle renderer does, which tells the owner. A list box row is selected with +`wxEVT_LISTBOX` and a checklist row ticked with `wxEVT_CHECKLISTBOX`; a drop-down row is picked with +`DropDown::ClickItem()`, which does what a release over it does; a table row's cell is made current +with `GoToCell()` (`wxEVT_GRID_SELECT_CELL`), and its cells are not edited: `set_settings` with the +object scope writes the same values. A Design list row is clicked at its centre, or at the action +icon whose tooltip `column` gives, through the list's own mouse handlers. + +Popups (`wxPopupWindow`: the print button's menu, drop-down lists) report themselves top-level but +are children of the window they opened from. `ui_snapshot` lists each shown one as a `popup` right +after its window (`popups_of()`), and `root: "popup"` lists only them. A widget in a popup belongs +to that window (`owning_window()`), so it is inside the topmost modal for the input guards when its +popup opened from there, and its locator's `within` names that window. A screenshot of a widget in +a popup is refused, since window captures leave popups out. + +### Plate icons + +A plate and its icons in the Prepare view (delete, orient, arrange, lock, settings, name, move to +front, filament grouping, IDEX mode) are GL picking models, which a person reaches only by pointing at +them. `ui_snapshot` lists under the Prepare canvas a `plate_icon` node for each plate, named as the +object list names it, then the icons of the current plate; the lock icon carries the plate's lock +state. A locator `{plate_icon, plate}` names any plate's icon by the picking action `PartPlate` gives +it: `plate` (the plate itself), `delete`, `orient`, `arrange`, `lock`, `settings`, `name`, +`move_to_front`, `filament_map`, `imex_mode`. The bed picking registry is the authority on what is +shown, since `PartPlate` registers only the icons it draws and hidden plates are inactive there: an +icon it does not offer (plate settings off, filament grouping without two nozzles, IDEX mode off) is +refused by name. + +A click calls `GLCanvas3D::click_plate()` with the icon's picking id, the code the canvas's mouse +handler runs for the plate under the pointer, so undo snapshots, notifications and dialogs are the +GUI's. It is refused where the canvas takes no plate clicks: outside the Prepare view, while variable +layer height is being edited, and while a gizmo is open, where the canvas would not open the plate +menu. A left click on lock replies the lock state; on the plate itself, move to front and delete the +current plate. Arrange and orient start a job on the UI job worker, which the reply waits for +(`done`); `started: false` says the click started nothing, with a note when the arrange icon's own +flag is stuck (an arrange that was cancelled or failed leaves it set until another arrange finishes). +Settings and filament grouping open their dialog from an event posted to the plater, so the call +queues a `CallAfter` on the plater behind it and replies once it ran, with the open dialog under +`dialogs`; the name icon opens its dialog inside the click, which the call reports as +`blocked_by_dialog`. A right click opens the plate menu, posted to the canvas, or the IDEX icon's mode +menu, and either is captured as any other menu (Menus above). ### ImGui items and gizmos @@ -503,8 +1541,15 @@ the ray through the whole pixel the click goes to must meet nothing before it (a parts of the instance the open gizmo works on, which it draws itself while their scene entries are inactive, and the plates), and must then meet the part near the point. A part the view does not draw (`GLVolume::visible`, false for objects the assemble view left out) is neither a target nor in -the way. Other inactive parts are hidden by the gizmo and modifiers are see-through, so neither counts. -`check: "point"` only projects, for points off the surface such as a cut plane. Every point of a +the way. Other inactive parts are hidden by the gizmo, and modifiers and negative parts other than the +target are see-through, so neither counts; a modifier or negative part is a target like any part. The +plates count only for a ray looking down: from below the GUI draws them see-through and picks and +paints through them (`SceneRaycaster` raycasts the bed only while the camera looks down). +`check: "point"` only projects, for points off the surface such as a cut plane. Either way, a gesture +that starts at a model point under an ImGui window (a gizmo panel, a notification, an open popup) is +refused, naming it, since ImGui would take its events: `imgui_window_at()` repeats ImGui's +hovered-window search (`FindHoveredWindow()`) on the windows of a frame drawn just before. A pixel +given as `x`/`y` is the client's to aim and is not checked. Every point of a gesture is resolved before its first event, and the journal keeps the model points, so a script replays at another window size or camera. A gesture's modifiers are pressed as a keyboard does: a key-down event each before it and a key-up after, which is what switches Measure and Assembly to @@ -522,22 +1567,45 @@ topmost wx dialog's button, so the dialog's own handler runs, or ends the dialog no such button exists. A native dialog can only be answered ahead with a `dialog_auto_answer` rule: a regex over title and message, and a button. `Enter()` then returns that button's id without showing the dialog, and logs it; a file or folder picker can only be cancelled, since any other -answer would return without a path. A new rule also answers a +answer would return without a path. A wx dialog that matches a rule opens, and the tracker presses +the button once the dialog's modal loop runs (`press_dialog_button()`, queued on the dialog), as +`dialog_respond` does: its buttons do the dialog's work in their handlers (`UnsavedChangesDialog`'s +Transfer and Discard, `CloneDialog`'s Fill), which a returned id would skip. A modal opened above it +before then leaves it to `dialog_respond`. A new rule also answers a matching wx dialog that is already open. A prompt posted around the same time, such as the restore prompt after startup, is handled whether it opens before or after the rule. A script's rules end with the script, a client's call replaces its earlier rules, and `get_state` lists the rules in -force. `webview_eval` runs JavaScript with `RunScriptAsync`. The result arrives as an event on the -UI thread, in a `ScriptSink` that only the UI thread creates and deletes, along with its weak -reference to the web view. The job thread waits for the result, up to `timeout_s` (default 10), -without the UI; a JSON result comes back parsed. +force. + +`webview_eval` runs JavaScript with `RunScriptAsync`, as a recover call. While a modal dialog is open +it runs only in a web view of the topmost one, and only when that dialog is the setup wizard +(`GuideFrame`) or a preset bundle dialog (`PresetBundleDialog`, `ExportPresetBundleDialog`), checked +by class: their pages have no typed route. Sign-in dialogs are never on that list, so no client reads +or fills a sign-in page, and neither are the flushing volumes and colour picker dialogs, whose values +`set_settings`'s project scope writes through the same apply code. A web view in a dialog under the +topmost one is refused, and any other gets a mutate call's checks. Without a target the web view of +the topmost dialog is used, else the only shown one. These dialogs have no wx buttons, so +`dialog_respond` only ends them: a page's work is committed through the page's own button. A web +view's locator names it by kind (`class: "webview"`), since its class differs per platform (WebKit, +WebView2). The result arrives as an event on the UI thread, in a `ScriptSink` that only the UI thread +creates and deletes, along with its weak reference to the web view. The job thread waits for the +result, up to `timeout_s` (default 10), without the UI; a JSON result comes back parsed. A page +closes its dialog with a message (`window.wx.postMessage`) the dialog answers by ending its modal +loop, which destroys the web view, while wx's script callback keeps a plain pointer to it. So the +script runs wrapped: messages the page posts while it runs are held and sent, in order, once it has +returned, and a script whose held messages closed its dialog replies its value with `closed: true` +once the dialog has left the modal stack. The sink also watches the web view's destruction, so a +dialog that goes away before the result by another route replies `closed: true` with a null result +instead of timing out. ## Screenshots `screenshot` captures on the UI thread and encodes off it. It has three targets. -- `canvas`: the visible 3D view, exactly as drawn, toolbars and ImGui panels included, on every - platform. `GLCanvas3D::render_and_capture()` forces a frame and reads the back buffer just before - the swap; it fails, saying why, when the canvas is hidden or mid-frame. +- `canvas`: the visible 3D view, the Design view while the Design tab is shown, exactly as drawn, + toolbars and ImGui panels included (the Design view's sketch overlay and status line too), on + every platform. `GLCanvas3D::render_and_capture()` forces a frame and reads the back buffer just + before the swap; it fails, saying why, when the canvas is hidden or mid-frame. - `window`: the main window's own pixels, never the screen, from `capture_native_window()`, with every visible 3D canvas composited in from its canvas capture, since window capture loses OpenGL content on several platforms. @@ -560,9 +1628,9 @@ On every platform, a canvas that can't be captured keeps whatever the window cap result is approximate. A canvas frame that reads back black (`is_blank()`, a stray pixel aside) has not been drawn yet. This happens on Wayland for a moment after the canvas is first shown, and while GNOME's overview hides an XWayland window. Such a capture is taken again every 300 ms for up to 3 s, -then returned as approximate, saying so. A 3D view other than Prepare's and Preview's (the Design -tab's) has no frame capture: a window capture says it is left out, and `target: "canvas"` refuses. -Minimized and hidden windows fail. X11 reads only the on-screen part of a window (`XGetImage` fails +then returned as approximate, saying so. The composite takes the canvases of `ui_canvases()`, +the Design view included; an OpenGL view outside them has no frame capture, and a window capture +says it is left out. Minimized and hidden windows fail. X11 reads only the on-screen part of a window (`XGetImage` fails for the rest), which leaves the remainder black. X11 keeps no backing store, so a part covered by another window reads back black. OrcaSlicer's own popups and tooltips stacked above the window are read and drawn in, as they appear on screen; another application's window leaves the @@ -570,6 +1638,88 @@ hole, and the result is approximate. The full-size PNG goes to `save_path` or `< block is scaled to `max_dim` on the long edge (default 1280, clamped to 256–2000). `include_image: false` returns only the path. +## Preview data + +`get_preview` reads what the Preview shows for a plate without selecting the plate. Its tables +come from the plate's `gcode_statistics_json()`, the serializer behind the slice reply's statistics +and the exported `statistics.json`, which sums the moves as the legend does: `summary` is the slice +reply's `plate_summary()` with the prepare and travel times and the travel distance; `features` has +each feature type's seconds, share of the normal-mode print time and grams, keyed by the English +`;FEATURE:` names (`ExtrusionEntity::role_to_string()`), and a `Travel` row (the shares leave out +retractions, wipes, Z moves, tool changes and the prepare time, as the legend's do); `layers`, +paged, numbers layers as the slider's value (G-code layer index + 1, which `set_view {layer}` and +`get_state.preview` use) and carries each one's Z, so tools that number layers by the slider's label +can be joined on Z. `objects` lists the G-code's object instances, which it names by object and +instance number; an entry gets the `list_objects` index only when one model object has that name. +The wx-free shaping (`preview_features()`, `preview_layers()`, `preview_objects()`) is unit tested. + +`view` is the legend's state, read from the libvgcode viewer it draws from +(`GCodeViewer::get_viewer()`), so only for the plate the Preview has loaded (its +`last_result_id()` is the plate's result id; the Preview loads a plate only while shown, so after +another plate is selected it keeps the last one's): view type, time mode, +the layer slider's range with its Z, which feature types and options are visible, and each view +type's colour range. The viewer recomputes ranges at its next frame after a legend change, so the +closure draws the Preview first; the ranges span the whole print but count travels, wipes and Custom +extrusions only while those rows are shown. For another plate `view` is null and a `note` says how to +show it. `get_state.preview` is the same state without the legend, or null when the Preview holds no +toolpaths of the current plate. + +The tool refuses while anything slices or exports (`Plater::is_slicing_any()`), since a worker may be +rewriting a result whatever its valid flag says, and for a plate without an up-to-date result. A +G-code file opened for viewing fills the current plate's result without marking the plate sliced; +that plate is read while the Preview shows it (`Plater::only_gcode_mode()`). Of a project opened from +a sliced 3MF, a plate the Preview has not shown keeps only the file's totals, without moves, so it is +refused with "slice again for layer data". The serializer's pass over the moves runs on the UI +thread, about 15 ms on a plate of 4 million moves. + +`set_view` changes the Preview through the functions the legend's own controls call +(`GCodeViewer::pick_view_type()` for the combo, `toggle_extrusion_role_visibility()` and +`toggle_option_visibility()` for its rows, `set_time_mode()` for the mode button), so a call leaves +the Preview as the same clicks would. Picking a view type therefore shows every feature type again +when it is Line Type, and is written to the app config as `preview_last_view_type`, which the "Last +used" preview default restores. Before a slice there is no legend to pick from, and `view_type` only +sets the type the next toolpaths show. `legend` names rows as `get_preview` lists them and clicks a +row only when its state differs; the viewer keeps one visibility set, so feature types can be set +whatever the view type, and are applied after it. Every key, and the time mode, is checked before +the Preview changes. `time_mode: "silent"` needs a separate silent-mode estimate, which the legend +offers only when the two estimates read differently (`can_switch_time_mode()`). `layer_z` takes the +layer the slider gives a height, `IMSlider::get_tick_from_value(z, true)`: the first layer whose top +is at or above it, which is where a custom G-code at that height goes, so a `z` lands on the same +layer in every tool. Layer replies carry `layers` [first, last, count] and the `z` of first and +last. + +## Print host uploads + +Sending G-code to a print host (OctoPrint, Moonraker, PrusaLink, Duet and the others in +`PrintHost::get_print_host()`) goes through the GUI's own dialog. The Speed Dial command +`send_gcode` ("Send G-code to printer host", the dialog's title) calls `Plater::send_gcode_legacy()`, +which the Print button calls for such a printer: it opens the Send dialog, whose file name an agent +sets with `ui_input` and whose Upload or Upload and Print button it presses with `dialog_respond`. +The plate is then sliced if needed, its G-code exported in the background process, and the upload +queued. Host settings are printer settings (`host_type`, `print_host`, `printhost_apikey`, and +`bbl_use_printhost` on a Bambu printer), written with `set_settings {scope: "printer"}`. Where the +Print button would not send to a print host, the command fails and says why: the printer prints +through the Bambu network or printer agents (`PresetBundle::use_bbl_network()`, +`use_printer_agents`), or has no `print_host`, the condition `MainFrame::can_send_gcode()` gives the +button. It is journaled like any `run_action`, so a replay uploads again. + +`get_state.uploads` lists the session's rows of the upload queue (`PrintHostQueueDialog`), as the +queue window shows them: `id` (its ID column, from 1), `state` (`queued`, `uploading`, `error`, +`cancelling`, `cancelled` or `completed`), `progress` (percent), `host`, `filename`, and `error`, the +queue's message, when there is one. Uploads a person started are listed too, so an agent can wait +for any of them by polling. A failed upload also opens the queue's error dialog +(`PrintHostQueueDialog::on_error()`), which blocks changes until it is closed with +`dialog_respond`. + +Two properties of the queue make its rows a reliable answer. A row reads `completed` only once the +host has accepted the file: while the bytes go out, `PrintHostJobQueue::sent_percent()` stops at 99, +and only `perform_job()`'s 100 after a successful `upload()` completes the row, so a host that +refuses the file after the last byte turns the row into an error without it reading completed on +the way. And rows are added on the UI thread: `PrintHostJobQueue::enqueue()` runs on the background +slicing thread, reads what the row shows (host, upload path, file size) before the upload thread can +remove the source file, and posts `append_job()` to the queue dialog itself, the handler the upload +thread's progress and error events go to, so the row exists before any of them is handled. + ## Scripts and the journal ```jsonc @@ -612,13 +1762,34 @@ GUI changes it. wx ignores `OnExit()`'s return value, so `GUI_Run()` returns The session journal records client calls to journaled tools in order: every mutate tool, plus `wait` and `screenshot`, which a replay needs. It keeps the last 5000 calls, dropping the oldest -call that has replied; a call still waiting for its reply keeps its place. GUI tools record locators instead of refs through +call whose outcome is known; a call still waiting for its reply or its job keeps its place. GUI tools record locators instead of refs through `ToolContext::set_journal_args()`. `export_script` returns it, and with `path` writes it, through `Journal::to_script()`; `clear` starts a new recording. `Journal::to_script()` -drops failed calls, turns a call that returned a job into a step with `"await": false` and +drops failed calls and an input call that only listed the menu it opened when the next call repeats +it with a `popup_item` (otherwise it stays: its right click changed the selection), turns a call that +returned a job into a step with `"await": false` and `"save_as": "jobN"`, points the `wait {for: "job"}` that followed at `${jobs.jobN}` (dropping waits on jobs it never saw start) and rewrites screenshot paths to `${out_dir}/`. +A call that runs as a job is judged by its job's final result, not by its reply. `McpCore` tells the +journal the job's id when it starts it (`Journal::job_started()`) and its result when the handler +returns (`Journal::job_ended()`), before `JobRegistry::finish()`, so an export right after the +`wait` that saw the result already knows it. A job that fails after its reply came back as +`running` is dropped like a call that failed at once, so a script never replays a call that did +nothing (a slow CAD rebuild that then fails). A call whose outcome is still open, because its job +is still running or it has not replied yet, is left out, and `export_script`'s reply lists it in +`left_out_running: [{tool, job}]` (`job` is absent for a call that is not one); a later export +includes it once its job has succeeded. A call whose reply was `blocked_by_dialog` stays in the +script while its job runs and whatever its job's result: the steps after it answer its dialog, and +a replay without it would fail at the first of them. A call whose job was still running when a later +call acted with a modal open (`dialog_respond`, or a recover tool's input while +`UiInvoker::open_dialogs()` lists one) stays the same way, whether it had replied yet or not, since that +dialog may be one its job opened; the journal can't tell whose dialog it was, so it keeps every such +job, as a step with `"await": false`. Its replayed reply can come before the dialog opens, so each +call that acted with a modal open is preceded in the script by `wait {"for": "dialog"}`, expected to +be satisfied. Only the call's own job counts as its job: a +`wait` that timed out names the job it waits on in its reply, and stays a plain step. + ## stdio bridge `orca-slicer --mcp-stdio [--datadir DIR] [--mcp-port N]` serves clients that speak only stdio, @@ -689,14 +1860,68 @@ who owns the discovery file and when a port counts as held by another window; `t `UiInvoker`, `McpCore` and `JobRegistry` on a hand-stepped dispatcher (guards, abandoned calls, jobs, blocked_by_dialog, admission, slots, idle, journal); `test_mcp_operations` the slice and export outcomes; `test_mcp_script` parsing, substitution, matchers and await; `test_mcp_ui` labels, -snapshot text, ref liveness, synthetic key state, how ImGui items are labelled and named, value -matching and the model-target projection and surface check (`CanvasTarget`); `test_imgui_wrapper` the +snapshot text, ref liveness, synthetic key state, a key's way through the hooks of its target's +parents (with a display), how ImGui items are labelled and named, value +matching and the model-target projection and surface check (`CanvasTarget`); `test_mcp_results` +what covers a canvas click (`imgui_window_at()`), the surface meshes of a modifier target, fresh GL +toolbar state and the auto-answer press (with a display), the slice reply's plate summary, +`get_preview`'s feature, layer and object tables, the legend rows' names, the slider's layer for +a height, menu paths and listings, the UI activity hook, the journal's dropped listing clicks and +calls whose job failed or still runs (with a replay of the export), the +menu capture on real wx menus, row paths and their snapshot text, (with a display) the rows of +real trees, lists, checklists and tables, clicks and checkbox input on them, and popups' owning +windows, plate icon names and bed picking ids, an upload's percentage while its bytes go out, and +the `send_gcode` command's catalog entry; +`test_imgui_wrapper` the ImGui recorder (named items, kinds, values, text, clipping) on frames drawn without OpenGL; -`test_mcp_tools` setting serialization. End to end, `tools/mcp/orca_mcp.py` launches +`test_mcp_tools` setting serialization; `test_mcp_config` the object and volume scopes' keys and +effective values, the names and places `save_preset` accepts, enum labels, per-variant entries and +their writes, preset comparison, `changed`, which unsaved changes a call discarded, which presets +`delete_preset` refuses or deletes with a custom printer, the project scope's slot colours, +flushing multipliers and matrix, and the plate scope's filament orders and layer ranges and +`list_plates`' layer numbers and layer G-codes, the preferences scope's keys, and `calibrate`'s arguments, +defaults, the dialogs' shared rules, VFA's auto-adjust and the parameters the journal records. End to end, `tools/mcp/orca_mcp.py` launches the app on a private Xvfb display on Linux (with `-noreset`, and the pointer parked in a corner so no tooltip lands in a screenshot), or on the desktop on macOS and Windows, and runs `tools/mcp/smoke_test.json`. `tools/mcp/tests/script_basic.json` checks `--mcp-script` headless, `tools/mcp/tests/gizmos.json` every gizmo through the GUI tools, +`tools/mcp/tests/multicolor.json` object and part filaments and the project scope, `tools/mcp/tests/presets.json` saving, +reading and comparing presets, per-variant entries, `changed`, reverting keys, answering the +unsaved-changes prompts of a preset switch and a new project, deleting presets, exporting and importing +presets with a path, and reading a preference changed in the Preferences dialog, +`tools/mcp/tests/plates.json` the plate scope, `list_plates` and the filament slot commands, +`tools/mcp/tests/calibration.json` every calibration test and its preset answers, +`tools/mcp/tests/dialogs_canvas_input.json` auto-answers that run a button's handler and canvas +targets on negative parts and from below the bed, `tools/mcp/tests/slice_stats.json` the slice +reply's statistics on one and two colours, `tools/mcp/tests/preview.json` `get_preview`, +`get_state.preview` and `set_view`'s preview arguments, `tools/mcp/tests/context_menus.json` context +and button menus listed and run without one ever showing, `tools/mcp/tests/rows.json` object list +rows, checklist rows, the object settings table and the print button's popup, +`tools/mcp/tests/plate_icons.json` plate icons (lock, settings, arrange, the plate menu, move to +front), `tools/mcp/tests/webview_modal.json` scripts in the preset bundle dialog and the setup +wizard, `tools/mcp/test_webview_modal.py` the dialogs scripts are refused in and a page that closes +its dialog, `tools/mcp/test_set_view_preview.py` the +legend combo's semantics of `set_view {view_type}` and its preview refusals, +`tools/mcp/test_export_running_job.py` an export during and after a job that outlived its reply, +`tools/mcp/test_send_gcode.py` `send_gcode` and `get_state.uploads` against a stub print host that +answers 200 or 500, `tools/mcp/test_stdio_bridge.py` the stdio bridge, and `tools/mcp/test_recovery_under_load.py` answering a dialog while stalled clients hold every connection. See `tools/mcp/README.md` and the `orca-mcp` skill. + +`test_mcp_scene` covers the scene and layer tools without the app: `transform`'s `size`, the shape +commands' size param, notifications updated before the first ImGui frame, `arrange`'s option rules, +worker-job admission on a stand-in worker (a job past the reply budget, a slow cancel and a timeout, +three ways to start one, recover input and a person's job), `list_objects`' descriptions of a `Model` +built in the test (placement and boxes on the bed, mirrors, filament fallback, precise seam subtypes, +height ranges, the summary of a variable layer height profile), `add_part`'s type names and shape +sizes, the object structure commands' params, the height ranges `set_layer_ranges` accepts (order, +overlaps, bounds, keys), and `set_layer_gcode`'s edits of a layer slider built in the test (by layer +and height, in-place edits, refusals that leave the slider as it was, the type names). On the app, +`tools/mcp/tests/scene.json` checks object structure and placement (transform on instances, plates and +parts, what `list_objects` reports of them, shapes at a size, arrange and Fill bed, `add_part`, the +object structure commands, then all of them on one scene through to a slice); +`tools/mcp/tests/layers.json` height range modifiers and variable layer height profiles (set, read +back, undone, sliced, refused, kept by a 3MF) and layer G-codes (placed by layer and height, edited in +place, refused, sliced, kept by a 3MF); and `tools/mcp/test_worker_admission.py` admission while an +arrange started three ways runs. diff --git a/src/libslic3r/CAD/CadDocument.cpp b/src/libslic3r/CAD/CadDocument.cpp index 7e85dd81ef..342f5b3a06 100644 --- a/src/libslic3r/CAD/CadDocument.cpp +++ b/src/libslic3r/CAD/CadDocument.cpp @@ -458,11 +458,8 @@ evaluate_variables(const std::map& variables) return done; } -// Write `value` into the CadFeature numeric field named `field`. Allow-list of -// the geometric dimension fields a variable realistically drives. Integer-valued -// fields are rounded. Throws std::runtime_error("unknown parameter: " + field) -// for anything not in the list. -static void assign_field(CadFeature& f, const std::string& field, double value) +// The allow-list is the geometric dimensions a variable realistically drives. +void CadDocument::set_numeric_field(CadFeature& f, const std::string& field, double value) { // double fields (alphabetical) if (field == "bool_tolerance") { f.bool_tolerance = value; return; } @@ -531,7 +528,7 @@ bool CadDocument::produces_body(CadFeatureType t) bool CadDocument::is_bindable_field(const std::string& field) { CadFeature probe; - try { assign_field(probe, field, 0.0); return true; } + try { set_numeric_field(probe, field, 0.0); return true; } catch (const std::exception&) { return false; } } @@ -1650,6 +1647,95 @@ bool CadDocument::plane_of_face(int body_idx, int face_idx, SketchPlane& out) co return true; } +bool CadDocument::inward_plane_of_face(int body_idx, int face_idx, SketchPlane& out) const +{ + if (face_idx < 0 || body_idx < 0 || body_idx >= int(bodies.size())) return false; + const TopoDS_Face face = GeometryEngine::face_by_index(bodies[body_idx].shape, face_idx); + if (face.IsNull()) return false; + SketchPlane p; + p.origin = GeometryEngine::face_centroid_world(face); + p.normal = (-GeometryEngine::face_normal_world(face)).normalized(); // inward + Vec3d x(0, 0, 0); double best = 0; + for (const TopoDS_Edge& e : GeometryEngine::edges_of_face(face)) { + const std::vector pts = GeometryEngine::sample_edge_world(e); + if (pts.size() < 2) continue; + Vec3d d = pts.back() - pts.front(); + d = d - p.normal * d.dot(p.normal); // project the edge direction into the plane + const double len = d.norm(); + if (len > best) { best = len; x = d / len; } + } + if (best < 1e-9) { // curved/edgeless face: an arbitrary in-plane basis; a hole is round anyway + const Vec3d ref = std::abs(p.normal.z()) < 0.9 ? Vec3d(0, 0, 1) : Vec3d(1, 0, 0); + x = ref.cross(p.normal).normalized(); + } + p.x_axis = x.normalized(); + p.y_axis = p.normal.cross(p.x_axis).normalized(); + out = p; + return true; +} + +bool CadDocument::thread_target(int body_idx, int face, int edge, SketchPlane& plane, GeometryEngine::CylinderFace& cyl, + bool* from_face) const +{ + cyl = GeometryEngine::CylinderFace(); + if (body_idx >= 0 && body_idx < int(bodies.size())) { + const TopoDS_Shape& shape = bodies[body_idx].shape; + if (face >= 0) cyl = GeometryEngine::cylinder_of_face(GeometryEngine::face_by_index(shape, face)); + if (from_face != nullptr) *from_face = cyl.ok; + if (!cyl.ok && edge >= 0) cyl = GeometryEngine::circle_of_edge(GeometryEngine::edge_by_index(shape, edge)); + } else if (from_face != nullptr) { + *from_face = false; + } + if (!cyl.ok) return false; + plane = frame_from(cyl.base, cyl.axis); + return true; +} + +std::string CadDocument::datum_plane_refusal(const CadFeature& f) const +{ + auto face_of = [&](int body, int face) { + return face < 0 || body < 0 || body >= int(bodies.size()) ? TopoDS_Face() + : GeometryEngine::face_by_index(bodies[body].shape, face); + }; + // As resolve_datum_planes() reads an edge: one it can sample end to end. + auto edge_on = [&](int body, int edge) { + if (edge < 0 || body < 0 || body >= int(bodies.size())) return false; + const TopoDS_Edge e = GeometryEngine::edge_by_index(bodies[body].shape, edge); + return !e.IsNull() && GeometryEngine::sample_edge_world(e).size() >= 2; + }; + const bool faceA_on = !face_of(f.plane_face_body, f.plane_face).IsNull(); + const char* gone = L("A picked face or edge is no longer on the model — pick it again"); + switch (f.plane_type) { + case PlaneType::Offset: + case PlaneType::Coincident: + // Face A is optional here; without it the plane is built from the base plane. + if (f.plane_face >= 0 && !faceA_on) return gone; + break; + case PlaneType::Angle: + if (f.plane_edge < 0) return L("An angled plane needs an edge to tilt about — pick Edge A"); + if (!edge_on(f.plane_edge_body, f.plane_edge) || (f.plane_face >= 0 && !faceA_on)) return gone; + break; + case PlaneType::Midplane: + if (f.plane_face < 0 || f.plane_face2 < 0) return L("A midplane needs two faces — pick Face A and Face B"); + // Well-defined but useless: the midplane of a face with itself is that same face. + if (f.plane_face == f.plane_face2 && f.plane_face_body == f.plane_face2_body) + return L("Face A and Face B are the same face — a midplane needs two different faces"); + if (!faceA_on || face_of(f.plane_face2_body, f.plane_face2).IsNull()) return gone; + break; + case PlaneType::Tangent: + if (f.plane_face < 0) return L("A tangent plane needs a cylindrical face — pick Face A"); + if (!faceA_on) return gone; + if (!GeometryEngine::cylinder_of_face(face_of(f.plane_face_body, f.plane_face)).ok) + return L("A tangent plane needs a cylindrical face — pick Face A"); + break; + case PlaneType::TwoEdges: + if (f.plane_edge < 0 || f.plane_edge2 < 0) return L("This plane needs two edges — pick Edge A and Edge B"); + if (!edge_on(f.plane_edge_body, f.plane_edge) || !edge_on(f.plane_edge2_body, f.plane_edge2)) return gone; + break; + } + return {}; +} + std::vector> CadDocument::resolve_datum_planes() const { std::vector> out; @@ -2043,20 +2129,25 @@ void CadDocument::clear() // A cleared document is a fresh start with no history. m_undo.clear(); m_redo.clear(); + m_redo_at_checkpoint.clear(); } void CadDocument::checkpoint() { m_undo.push_back(Snapshot{features, variables}); // snapshot the pre-mutation recipe - m_redo.clear(); // any new action invalidates the redo branch + m_redo_at_checkpoint = std::move(m_redo); // any new action invalidates the redo branch + m_redo.clear(); if (m_undo.size() > k_undo_cap) m_undo.erase(m_undo.begin()); } void CadDocument::abandon_checkpoint() { - if (!m_undo.empty()) - m_undo.pop_back(); + if (m_undo.empty()) + return; + m_undo.pop_back(); + m_redo = std::move(m_redo_at_checkpoint); // nothing happened, so what was redoable still is + m_redo_at_checkpoint.clear(); } bool CadDocument::undo() @@ -2083,6 +2174,19 @@ bool CadDocument::redo() return true; } +bool CadDocument::rollback() +{ + if (m_undo.empty()) + return false; + features = std::move(m_undo.back().features); + variables = std::move(m_undo.back().variables); + m_undo.pop_back(); + m_redo = std::move(m_redo_at_checkpoint); + m_redo_at_checkpoint.clear(); + recompute(); + return true; +} + // A feature's body index: -1 means "the last body", anything else must exist. An index past // the end used to fall back to the last body in silence, so a feature whose body had gone away @@ -2166,15 +2270,6 @@ static void settle_body_refs(CadFeature& f, const std::vector& v, bool }); } -// Datum-plane ordinals: plane_base, axis_plane_a, axis_plane_b hold 3 + N. -template -static void for_each_datum_ref(CadFeature& f, Visit&& visit) -{ - visit(f.plane_base); - visit(f.axis_plane_a); - visit(f.axis_plane_b); -} - // Prepare every reference for a change of history in which feature `i` ends up at // `map_feature(i)` (-1 = removed) and enabled as `enabled_after(i)`. Runs on the OLD history and // writes into `features` in the old order; the caller then performs the change. @@ -2202,7 +2297,7 @@ static void stage_history_change(std::vector& features, for (int j = 0; j < n; ++j) { if (map_feature(j) < 0) continue; CadFeature& f = features[j]; - for_each_datum_ref(f, [&](int& ref) { + CadDocument::for_each_datum_ref(f, [&](int& ref) { if (ref < 3) return; const int N = ref - 3; const int oldf = (N < int(planes_before.size())) ? planes_before[N] : -1; @@ -2260,33 +2355,6 @@ static bool commit_or_rollback(CadDocument& doc, std::vector& snapsh return false; } -// Visit every field of `f` that holds an index into features[]. -// -// Deliberately NOT dispatched on f.type. A type switch is what this replaced, and it was -// wrong in the way type switches go wrong: it listed Extrude and Mate, and every feature -// type added afterwards — Revolve, Sweep, Loft, Rib, Pattern-on-curve, the Surface* family — -// silently inherited a remap that skipped its references. Visiting the FIELDS instead means -// a new type is covered the moment it reuses one of them, and reaching a field its type -// never reads costs nothing: unset refs are -1 and every visitor here ignores those. -// -// The list is exactly the fields documented as "index into features[]" / "feature index" in -// CadDocument.hpp. Not included, because they are a different basis and need their own pass: -// plane_base / axis_plane_a / axis_plane_b encode `3 + N` = the Nth DATUM PLANE, an ordinal -// into resolve_datum_planes(), not into features[]. Everything named *_body / *_face / *_edge -// is a body index or a global topology id and must never be remapped here. -template -static void for_each_feature_ref(CadFeature& f, Visit&& visit) -{ - visit(f.sketch_ref); - visit(f.sweep_path_ref); - visit(f.pattern_curve_sketch); - visit(f.rib_sketch_ref); - visit(f.mate_cs_a); - visit(f.mate_cs_b); - for (int& r : f.loft_profile_refs) - visit(r); -} - bool CadDocument::remove_feature(int index) { if (index < 0 || index >= int(features.size())) @@ -2816,7 +2884,11 @@ void CadDocument::apply_feature(TopoDS_Shape& result, bool& have_body, throw std::runtime_error(_u8L("sweep path must be a sketch or helix")); } TopoDS_Wire profile = build_sketch_wire(sk, true); - TopoDS_Shape tool = SketchEngine::make_sweep(profile, path); + // Along a helix the profile keeps its angle to the helix axis, as a spring's wire does. + const Vec3d& axis = path_feat.plane.normal; + TopoDS_Shape tool = path_feat.type == CadFeatureType::Helix + ? SketchEngine::make_sweep(profile, path, gp_Dir(axis.x(), axis.y(), axis.z())) + : SketchEngine::make_sweep(profile, path); if (!have_body || f.mode == BooleanMode::New) { result = tool; have_body = true; @@ -4033,12 +4105,22 @@ void CadDocument::route_feature(std::vector& bodies, const CadFeature& } } +std::map CadDocument::variable_values(std::string& err) const +{ + try { + return evaluate_variables(variables); + } catch (const std::exception& e) { + err = e.what(); + return {}; + } +} + void CadDocument::bind_expressions() { std::map varvals = evaluate_variables(variables); for (CadFeature& f : features) for (const auto& [field, e] : f.expr) - assign_field(f, field, eval_expr(e, varvals)); + set_numeric_field(f, field, eval_expr(e, varvals)); } void CadDocument::replay_feature(size_t fi, std::vector& built) diff --git a/src/libslic3r/CAD/CadDocument.hpp b/src/libslic3r/CAD/CadDocument.hpp index 8adbd7b20c..7650961121 100644 --- a/src/libslic3r/CAD/CadDocument.hpp +++ b/src/libslic3r/CAD/CadDocument.hpp @@ -543,6 +543,39 @@ public: // Can a feature expression drive this numeric field? The single allow-list the evaluator // uses, so a caller can refuse a name before it breaks the next recompute. static bool is_bindable_field(const std::string& field); + // Write `value` into the numeric field named `field`: the allow-list above, so a literal edit + // and an expression binding reach exactly the same fields. Integer fields are rounded, and + // thread_diameter writes half of it to thread_radius. Throws std::runtime_error naming an + // unknown field. + static void set_numeric_field(CadFeature& f, const std::string& field, double value); + // The variables' values as recompute() evaluates them. Empty, with `err` set, on a cycle, an + // unknown name or an expression that does not evaluate. + std::map variable_values(std::string& err) const; + // Visit every field of `f` holding an index into `features`. It visits fields rather than + // dispatching on the type, so a feature type that reuses one of them is covered without being + // listed; an unset reference is -1. Body indices and face or edge ids are not visited, nor are + // datum-plane ordinals (for_each_datum_ref). `Feature` is CadFeature or const CadFeature. + template + static void for_each_feature_ref(Feature& f, Visit&& visit) + { + visit(f.sketch_ref); + visit(f.sweep_path_ref); + visit(f.pattern_curve_sketch); + visit(f.rib_sketch_ref); + visit(f.mate_cs_a); + visit(f.mate_cs_b); + for (auto& r : f.loft_profile_refs) + visit(r); + } + // Visit every field holding a datum-plane ordinal: 3 + N names the Nth enabled Plane feature + // (resolve_datum_planes()), below 3 a base plane. + template + static void for_each_datum_ref(Feature& f, Visit&& visit) + { + visit(f.plane_base); + visit(f.axis_plane_a); + visit(f.axis_plane_b); + } // Does a feature of this type leave a body behind? Sketches, datums, the helix curve and // Project (which emits sketch entities) do not. The one answer recompute(), the rollback // rule and the GUI's preview all use. @@ -733,6 +766,13 @@ public: // Every datum plane currently in the recipe, in feature order, as (name, plane). // Used by the GUI to populate plane pickers (after the 3 base planes). std::vector> resolve_datum_planes() const; + // Why the Plane feature `f` cannot be built as its plane_type asks, or "" when it can. Each + // construction needs its references (an angled plane an edge, a midplane two different faces, + // a tangent plane a cylindrical face, a two-edge plane two edges), and every reference it uses + // must still be on its body. resolve_datum_planes() falls back to an offset plane, silently, + // when they are not; this is the check that keeps a new plane off that fallback. The reason is + // an untranslated message (marked with L()), translated where it is shown. + std::string datum_plane_refusal(const CadFeature& f) const; // World-space sketch plane lying on a body's PLANAR face, so a face picked in the viewport can // be sketched on directly — no datum plane in between and nothing to choose from a list. @@ -740,6 +780,19 @@ public: // has no single plane, and guessing one from a mid-parameter normal would silently sketch on a // tangent). Same derivation the Coincident datum method uses, shared so the two cannot drift. bool plane_of_face(int body_idx, int face_idx, SketchPlane& out) const; + // The plane a hole drills from on a body's face: origin at the face centroid, normal pointing + // INTO the solid, so a positioned hole drills inward and its (x,y) read as the offset from the + // face centre, and x along the face's longest straight edge, so the hole's distances from the + // face sides read along the sides. False when the indices don't resolve. Any face is accepted, + // as the Hole card accepts any picked face; a curved one gets its mid-parameter normal. + bool inward_plane_of_face(int body_idx, int face_idx, SketchPlane& out) const; + // What a Thread is cut on when a body's face or rim is picked: the cylindrical face `face` of + // body `body_idx`, else its circular edge `edge` (-1 for none). `cyl` is that cylinder (an edge + // gives no length and reads as external); `plane` sits on its axis, origin at the base and + // normal along the axis, where a thread starts and the way it rises. False when neither is + // round; `from_face` says whether the face was. + bool thread_target(int body_idx, int face, int edge, SketchPlane& plane, GeometryEngine::CylinderFace& cyl, + bool* from_face = nullptr) const; // Resolved datum axes in feature order. axis_err is non-empty if construction failed. struct DatumAxis { std::string name; Vec3d origin{0,0,0}; Vec3d direction{0,0,1}; std::string error; }; @@ -800,10 +853,11 @@ public: // body) is derived by recompute(), snapshotting `features` alone is a complete, // exact history; one checkpoint == one Ctrl+Z step. void checkpoint(); // snapshot `features` for undo + invalidate redo - // Drop the most recent checkpoint. For a mutation that took a checkpoint, then failed - // and restored the pre-mutation state itself (the constraint paths reject an - // over-constrained addition this way): the snapshot now describes a state identical to - // the current one, and leaving it turns the next Ctrl+Z into a press that does nothing. + // Drop the most recent checkpoint and put back the redo branch it cleared. For a mutation + // that took a checkpoint, then failed and restored the pre-mutation state itself (the + // constraint paths reject an over-constrained addition this way, and the feature-tree edits + // below roll themselves back): the snapshot now describes a state identical to the current + // one, and leaving it turns the next Ctrl+Z into a press that does nothing. void abandon_checkpoint(); bool can_undo() const { return !m_undo.empty(); } bool can_redo() const { return !m_redo.empty(); } @@ -811,6 +865,12 @@ public: size_t redo_depth() const { return m_redo.size(); } bool undo(); // restore the previous feature list + recompute(); false if no history bool redo(); // re-apply the most recently undone change; false if none + // Take back a refused edit as if it had never been made: restore and drop the last checkpoint, + // recompute, and put back the redo branch that checkpoint() cleared. For an edit whose rebuild + // failed after its checkpoint; undo() there would leave the refused recipe on the redo stack, + // where Redo brings it back. Call it straight after the failed edit, in place of undo(). + // False if there is no checkpoint. + bool rollback(); // Feature-tree editing (Onshape-style). All are transactional: they snapshot // features, mutate, recompute(), and roll back to the snapshot (re-recomputing) @@ -912,6 +972,7 @@ private: }; std::vector m_undo; std::vector m_redo; + std::vector m_redo_at_checkpoint; // the redo branch the last checkpoint() cleared, for rollback() and abandon_checkpoint() static constexpr size_t k_undo_cap = 200; }; diff --git a/src/libslic3r/CAD/GeometryEngine.cpp b/src/libslic3r/CAD/GeometryEngine.cpp index 3417626307..3cb2949ca7 100644 --- a/src/libslic3r/CAD/GeometryEngine.cpp +++ b/src/libslic3r/CAD/GeometryEngine.cpp @@ -55,6 +55,14 @@ #include #include #include +#include +#include +#include +#include +#include +#include +#include +#include #include #include #include @@ -689,6 +697,110 @@ GeometryEngine::CylinderFace GeometryEngine::circle_of_edge(const TopoDS_Edge& e return cf; } +GeometryEngine::SurfaceInfo GeometryEngine::surface_info(const TopoDS_Face& face) +{ + SurfaceInfo s; + if (face.IsNull()) return s; + GProp_GProps props; + BRepGProp::SurfaceProperties(face, props); + s.area = props.Mass(); + s.centroid = Vec3d(props.CentreOfMass().X(), props.CentreOfMass().Y(), props.CentreOfMass().Z()); + + BRepAdaptor_Surface surf(face); + s.type = surf.GetType(); + auto vec = [](const gp_XYZ& v) { return Vec3d(v.X(), v.Y(), v.Z()); }; + // A bore or a countersink faces its axis: the outward normal at the face's middle points from + // the surface toward the axis (or the centre). + const gp_Pnt mid = surf.Value(0.5 * (surf.FirstUParameter() + surf.LastUParameter()), + 0.5 * (surf.FirstVParameter() + surf.LastVParameter())); + auto facing = [&](const Vec3d& toward) { return face_normal_world(face).dot(toward) > 0.0; }; + switch (s.type) { + case GeomAbs_Cylinder: { + const CylinderFace c = cylinder_of_face(face); + s.location = c.base; + s.axis = c.axis; + s.radius = c.radius; + s.internal = c.internal; + break; + } + case GeomAbs_Cone: { + // The radius at parameter v is RefRadius + v sin(SemiAngle), and v runs along the axis, so + // the cone opens along the axis when the semi-angle is positive. + const gp_Cone cone = surf.Cone(); + const double sa = cone.SemiAngle(); + const Vec3d dir = vec(cone.Axis().Direction().XYZ()); + s.location = vec(cone.Apex().XYZ()); + s.axis = sa >= 0.0 ? dir : Vec3d(-dir); + s.half_angle = std::abs(sa); + const double r0 = std::abs(cone.RefRadius() + surf.FirstVParameter() * std::sin(sa)); + const double r1 = std::abs(cone.RefRadius() + surf.LastVParameter() * std::sin(sa)); + s.radius = std::min(r0, r1); + s.radius2 = std::max(r0, r1); + const Vec3d m = vec(mid.XYZ()); + s.internal = facing(s.location + s.axis * (m - s.location).dot(s.axis) - m); + break; + } + case GeomAbs_Sphere: { + const gp_Sphere sphere = surf.Sphere(); + s.location = vec(sphere.Location().XYZ()); + s.radius = sphere.Radius(); + s.internal = facing(s.location - vec(mid.XYZ())); + break; + } + case GeomAbs_Torus: { + const gp_Torus torus = surf.Torus(); + s.location = vec(torus.Location().XYZ()); + s.axis = vec(torus.Axis().Direction().XYZ()); + s.radius = torus.MajorRadius(); + s.radius2 = torus.MinorRadius(); + break; + } + default: break; + } + return s; +} + +std::vector> GeometryEngine::edge_faces(const TopoDS_Shape& shape) +{ + NCollection_DataMap face_id; + int n = 0; + for (TopExp_Explorer e(shape, TopAbs_FACE); e.More(); e.Next(), ++n) + if (!face_id.IsBound(e.Current())) face_id.Bind(e.Current(), n); // faces_of's ordinal + NCollection_IndexedDataMap, TopTools_ShapeMapHasher> faces_of_edge; + TopExp::MapShapesAndAncestors(shape, TopAbs_EDGE, TopAbs_FACE, faces_of_edge); + const std::vector edges = edges_of(shape); + std::vector> out(edges.size()); + for (size_t i = 0; i < edges.size(); ++i) { + const int k = faces_of_edge.FindIndex(edges[i]); + if (k == 0 || BRep_Tool::Degenerated(edges[i])) continue; + for (NCollection_List::Iterator it(faces_of_edge.FindFromIndex(k)); it.More(); it.Next()) { + const int* f = face_id.Seek(it.Value()); + if (f != nullptr && std::find(out[i].begin(), out[i].end(), *f) == out[i].end()) out[i].push_back(*f); + } + } + return out; +} + +int GeometryEngine::edge_convexity(const TopoDS_Edge& edge, const TopoDS_Face& f1, const TopoDS_Face& f2) +{ + // Faces closer than a degree to each other along the edge count as tangent. + switch (ChFi3d::DefineConnectType(edge, f1, f2, std::sin(M_PI / 180.0), true)) { + case ChFiDS_Convex: return 1; + case ChFiDS_Concave: return -1; + default: return 0; + } +} + +double GeometryEngine::min_distance(const TopoDS_Shape& a, const TopoDS_Shape& b, Vec3d& pa, Vec3d& pb) +{ + BRepExtrema_DistShapeShape dss(a, b); + if (!dss.IsDone() || dss.NbSolution() < 1) return -1.0; + const gp_Pnt p = dss.PointOnShape1(1), q = dss.PointOnShape2(1); + pa = Vec3d(p.X(), p.Y(), p.Z()); + pb = Vec3d(q.X(), q.Y(), q.Z()); + return dss.Value(); +} + bool GeometryEngine::face_plane_bounds(const TopoDS_Face& face, const Vec3d& origin, const Vec3d& x_axis, const Vec3d& y_axis, double& umin, double& umax, double& vmin, double& vmax) diff --git a/src/libslic3r/CAD/GeometryEngine.hpp b/src/libslic3r/CAD/GeometryEngine.hpp index 66f00859be..142d94837c 100644 --- a/src/libslic3r/CAD/GeometryEngine.hpp +++ b/src/libslic3r/CAD/GeometryEngine.hpp @@ -4,6 +4,7 @@ #include "libslic3r/Point.hpp" #include "libslic3r/TriangleMesh.hpp" +#include #include #include #include @@ -138,6 +139,37 @@ public: // the edge is not a circle. Lets the Thread tool be driven by a picked circular rim. static CylinderFace circle_of_edge(const TopoDS_Edge& edge); + // What surface a face lies on, for reading a body's topology: its OCCT type, area and centre + // of mass, and the numbers that define an analytic surface. Cylinder: as cylinder_of_face + // (`location` its base). Cone: `location` the apex, `axis` from the apex into the opening, + // `half_angle` (radians), `radius` and `radius2` the smallest and largest radius the face + // reaches. Sphere: `location` the centre, `radius`. Torus: `location` the centre, `axis`, + // `radius` the major and `radius2` the minor radius. `internal` (cylinder, cone, sphere): the + // outward normal points toward the axis or centre, as in a bore or a countersink. + struct SurfaceInfo { + GeomAbs_SurfaceType type{GeomAbs_OtherSurface}; + double area{0}; + Vec3d centroid{0, 0, 0}; + Vec3d location{0, 0, 0}; + Vec3d axis{0, 0, 1}; + double radius{0}; + double radius2{0}; + double half_angle{0}; + bool internal{false}; + }; + static SurfaceInfo surface_info(const TopoDS_Face& face); + // The faces each edge bounds: entry i lists the faces_of() ids along edge i of edges_of(), each + // once. A seam (the line down a cylinder's side) lists its one face; a degenerate edge (a + // cone's apex) lists none. + static std::vector> edge_faces(const TopoDS_Shape& shape); + // How the two faces along `edge` meet, as OCCT's fillet code judges it: +1 convex (an outside + // corner), -1 concave (an inside corner), 0 when they meet tangentially, as along a fillet's + // boundary, or the edge cannot be judged. + static int edge_convexity(const TopoDS_Edge& edge, const TopoDS_Face& f1, const TopoDS_Face& f2); + // The shortest distance between two shapes (faces, edges, vertices), and the nearest point on + // each. Negative when OCCT finds none. + static double min_distance(const TopoDS_Shape& a, const TopoDS_Shape& b, Vec3d& pa, Vec3d& pb); + // Plane-coordinate (u,v) bounding box of a face's vertices, measured from `origin` along // `x_axis`/`y_axis`. Lets the Hole tool dimension the hole from the face SIDES (umin/vmin = // two adjacent edges) instead of from the centre. Returns false if the face has no vertices. diff --git a/src/libslic3r/CAD/SketchEngine.cpp b/src/libslic3r/CAD/SketchEngine.cpp index 019225a4aa..eb40bfcfd6 100644 --- a/src/libslic3r/CAD/SketchEngine.cpp +++ b/src/libslic3r/CAD/SketchEngine.cpp @@ -41,6 +41,7 @@ #include #include #include +#include #include #include #include @@ -408,6 +409,19 @@ TopoDS_Shape SketchEngine::make_sweep(const TopoDS_Wire& profile, const TopoDS_W return pipe.Shape(); } +TopoDS_Shape SketchEngine::make_sweep(const TopoDS_Wire& profile, const TopoDS_Wire& path, const gp_Dir& binormal) +{ + if (!BRepBuilderAPI_MakeFace(profile).IsDone()) // a closed planar profile, as above + throw std::runtime_error(_u8L("Failed to make face from sweep profile")); + BRepOffsetAPI_MakePipeShell pipe(path); + pipe.SetMode(binormal); + pipe.Add(profile); + pipe.Build(); + if (!pipe.IsDone() || !pipe.MakeSolid()) + throw std::runtime_error(_u8L("Failed to sweep profile along path")); + return pipe.Shape(); +} + TopoDS_Shape SketchEngine::make_loft(const std::vector& profiles, bool ruled) { if (profiles.size() < 2) @@ -2574,4 +2588,10 @@ ConstraintPlan plan_entity_constraint(const std::vector& ents, return plan; } +void write_plan_value(std::vector& defs, double v) +{ + for (auto& d : defs) + d.value = (d.type == SketchConstraintType::Angle) ? v * M_PI / 180.0 : v; +} + } // namespace Slic3r diff --git a/src/libslic3r/CAD/SketchEngine.hpp b/src/libslic3r/CAD/SketchEngine.hpp index 22dade5af0..71987f30a7 100644 --- a/src/libslic3r/CAD/SketchEngine.hpp +++ b/src/libslic3r/CAD/SketchEngine.hpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -202,6 +203,10 @@ struct ConstraintPlan { // e2 is the axis-line pick Symmetric needs (def.ec); every other type ignores it. ConstraintPlan plan_entity_constraint(const std::vector& ents, int e0, int e1, int e2, SketchConstraintType type); +// Write the value for a planned constraint into every def. The planner's prefill, and the value a +// person types, are in display units; Angle is the one type stored otherwise (degrees shown, +// radians stored). +void write_plan_value(std::vector& defs, double v); // Solve a bare entity list in place against entity-form constraints. Shared by // CadDocument::solve_sketch_feature (committed features) and the in-session GUI @@ -251,6 +256,11 @@ public: // perpendicular to the spine along its length. The path may be open or closed; // for a clean solid the path's first point should sit on/near the profile plane. static TopoDS_Shape make_sweep(const TopoDS_Wire& profile, const TopoDS_Wire& path); + // Sweep along a helix whose axis is `binormal`: the profile keeps its angle to that axis the + // whole way round, as a spring's or a thread's wire does (BRepOffsetAPI_MakePipeShell with a + // fixed binormal). The moving frame of the sweep above turns a profile about a helix, so a + // square wire would twist on its way up. + static TopoDS_Shape make_sweep(const TopoDS_Wire& profile, const TopoDS_Wire& path, const gp_Dir& binormal); // Loft a solid through 2+ closed profile wires (each on its own plane), in the // given order. ruled=true => straight (ruled) sections; false => smooth (C2). diff --git a/src/libslic3r/CAD/ThreadStandards.cpp b/src/libslic3r/CAD/ThreadStandards.cpp index 11b6b24d8f..1dcb598117 100644 --- a/src/libslic3r/CAD/ThreadStandards.cpp +++ b/src/libslic3r/CAD/ThreadStandards.cpp @@ -1,4 +1,5 @@ #include "libslic3r/CAD/ThreadStandards.hpp" +#include #include #include @@ -94,4 +95,18 @@ const ThreadSpec* find_thread_standard(const std::string& name) return nullptr; } +const ThreadSpec* nearest_thread_standard(double diameter, bool internal) +{ + const ThreadSpec* best = nullptr; + double best_err = 0.0; + for (const ThreadSpec& s : thread_standards()) { + const double err = std::abs((internal ? s.minor_diameter_mm() : s.major_diameter_mm) - diameter); + if (best == nullptr || err < best_err) { + best = &s; + best_err = err; + } + } + return best; +} + } // namespace Slic3r diff --git a/src/libslic3r/CAD/ThreadStandards.hpp b/src/libslic3r/CAD/ThreadStandards.hpp index c03c2033d8..1e0e9baba1 100644 --- a/src/libslic3r/CAD/ThreadStandards.hpp +++ b/src/libslic3r/CAD/ThreadStandards.hpp @@ -36,6 +36,13 @@ const std::vector& thread_standards(); // Exact case-sensitive designation lookup; nullptr if not a known standard. const ThreadSpec* find_thread_standard(const std::string& name); +// The standard nearest a measured cylinder of `diameter`, as the Thread tool infers it from a +// picked face or rim: a boss is matched on the major (nominal) diameter, a bore on the minor one, +// since a hole to be tapped is drilled at the tap-drill size. Every series is scanned together, so +// a 5 mm bore gives 1/4-20 UNC (minor 4.975) rather than M6 (minor 4.918); the first of equally +// near sizes wins. nullptr only for an empty table. +const ThreadSpec* nearest_thread_standard(double diameter, bool internal); + } // namespace Slic3r #endif diff --git a/src/libslic3r/calib.cpp b/src/libslic3r/calib.cpp index e800258ccf..d039657724 100644 --- a/src/libslic3r/calib.cpp +++ b/src/libslic3r/calib.cpp @@ -10,7 +10,10 @@ #include "Model.hpp" #include "GCode.hpp" #include "PrintConfig.hpp" +#include "Preset.hpp" +#include "Utils.hpp" #include +#include #include "Point.hpp" #include "libslic3r.h" #include @@ -26,6 +29,193 @@ namespace Slic3r { +namespace { + +// A per-extruder value: the extruder's entry, the last one past the end, or `fallback` without any. +double extruder_value(const ConfigOptionFloats* opt, int extruder_id, double fallback) +{ + if (opt == nullptr || opt->values.empty()) + return fallback; + return opt->values[std::min(static_cast(std::max(extruder_id, 0)), opt->values.size() - 1)]; +} + +} // namespace + +bool has_junction_deviation(const DynamicPrintConfig& printer) +{ + const auto* gcode_flavor = printer.option>("gcode_flavor"); + const auto* junction_dev = printer.option("machine_max_junction_deviation"); + return gcode_flavor != nullptr && gcode_flavor->value == GCodeFlavor::gcfMarlinFirmware && junction_dev != nullptr && + !junction_dev->values.empty() && junction_dev->values.front() > 0.0; +} + +Calib_Params calib_default_params(CalibMode mode, const DynamicPrintConfig& printer, bool bowden) +{ + Calib_Params p; + p.mode = mode; + switch (mode) { + case CalibMode::Calib_Temp_Tower: p.start = 230; p.end = 190; break; // in fixed 5 °C blocks + case CalibMode::Calib_Vol_speed_Tower: p.start = 5; p.end = 20; p.step = 0.5; break; + case CalibMode::Calib_PA_Tower: + case CalibMode::Calib_PA_Line: + case CalibMode::Calib_PA_Pattern: { + const bool pattern = mode == CalibMode::Calib_PA_Pattern; + p.start = 0.; + p.end = bowden ? 1.0 : pattern ? 0.08 : 0.1; + p.step = pattern ? (bowden ? 0.05 : 0.005) : (bowden ? 0.02 : 0.002); + p.print_numbers = mode != CalibMode::Calib_PA_Tower; + break; + } + case CalibMode::Calib_Retraction_tower: p.start = 0; p.end = 2; p.step = 0.1; break; + case CalibMode::Calib_VFA_Tower: p.start = 40; p.end = 200; p.step = 10; break; + case CalibMode::Calib_Input_shaping_freq: + p.freqStartX = p.freqStartY = 15; + p.freqEndX = p.freqEndY = 110; + p.start = 0.15; // the damping ratio the test prints with + break; + case CalibMode::Calib_Input_shaping_damp: + p.freqStartX = p.freqStartY = 30; + p.start = 0.; + p.end = 0.4; + break; + case CalibMode::Calib_Cornering: + if (has_junction_deviation(printer)) { + p.start = 0.; + p.end = 0.25; + } else { + p.start = 1.; + p.end = 15.; + } + break; + default: break; + } + return p; +} + +std::pair cornering_end_limits(const DynamicPrintConfig& printer) +{ + return has_junction_deviation(printer) ? std::make_pair(0.3, 0.25) : std::make_pair(100., 20.); +} + +CalibParamsError check_calib_params(const Calib_Params& p, const DynamicPrintConfig& printer) +{ + using E = CalibParamsError; + // RepRapFirmware takes one frequency range for both axes, so its dialogs have no Y fields. + const auto* flavor = printer.option>("gcode_flavor"); + const bool rrf = flavor != nullptr && flavor->value == GCodeFlavor::gcfRepRapFirmware; + switch (p.mode) { + case CalibMode::Calib_Temp_Tower: return p.start > 500 || p.end < 155 || p.end > p.start - 5 ? E::Range : E::None; + case CalibMode::Calib_Vol_speed_Tower: return p.start <= 0 || p.step <= 0 || p.end < p.start + p.step ? E::Range : E::None; + case CalibMode::Calib_PA_Tower: + case CalibMode::Calib_PA_Line: + case CalibMode::Calib_PA_Pattern: { + if (p.start < 0 || p.step < 10 * EPSILON || p.end < p.start + p.step) + return E::Range; + // PA Line and PA Pattern are drawn on the belt but not validated there yet. + const auto* belt = printer.option("belt_printer"); + if (belt != nullptr && belt->value && p.mode != CalibMode::Calib_PA_Tower) + return E::BeltMethod; + // Accelerations are larger than speeds, so this catches the two lists swapped. + if (!p.accelerations.empty() && !p.speeds.empty() && + *std::min_element(p.accelerations.begin(), p.accelerations.end()) <= *std::max_element(p.speeds.begin(), p.speeds.end())) + return E::AccelBelowSpeed; + return E::None; + } + case CalibMode::Calib_Retraction_tower: return p.start < 0 || p.step <= 0 || p.end < p.start + p.step ? E::Range : E::None; + case CalibMode::Calib_VFA_Tower: return p.start <= 10 || p.step <= 0 || p.end < p.start + p.step ? E::Range : E::None; + case CalibMode::Calib_Input_shaping_freq: + if (p.freqStartX < 0 || p.freqEndX > 500 || p.freqStartX >= p.freqEndX || + (!rrf && (p.freqStartY < 0 || p.freqEndY > 500 || p.freqStartY >= p.freqEndY))) + return E::Range; + return p.start < 0 || p.start >= 1 ? E::Damping : E::None; + case CalibMode::Calib_Input_shaping_damp: + if (p.freqStartX < 0 || p.freqStartX > 500 || (!rrf && (p.freqStartY < 0 || p.freqStartY > 500))) + return E::Range; + return p.start < 0 || p.end > 1 || p.start >= p.end ? E::Damping : E::None; + case CalibMode::Calib_Cornering: + return p.start < 0 || p.end > cornering_end_limits(printer).first || p.start >= p.end ? E::Range : E::None; + default: return E::None; + } +} + +std::string belt_temp_tower_asset(const Calib_Params& params) +{ + const int t_start = (int) lround(params.start); + const int t_end = (int) lround(params.end); + return Slic3r::resources_dir() + "/calib/temperature_tower/belt_temp_tower_" + std::to_string(t_start) + "_" + + std::to_string(t_end) + ".stl"; +} + +std::vector vfa_candidate_layer_heights(const PresetCollection& prints, const DynamicPrintConfig& printer, int extruder_id) +{ + const double machine_min_lh = extruder_value(printer.option("min_layer_height"), extruder_id, 0.0); + const double machine_max_lh = extruder_value(printer.option("max_layer_height"), extruder_id, 0.0); + std::vector candidates; + for (const Preset& preset : prints.get_presets()) { + if (!preset.is_compatible || preset.is_default) + continue; + const auto* lh_opt = preset.config.option("layer_height"); + if (lh_opt == nullptr || lh_opt->value <= 0.0) + continue; + const double lh = lh_opt->value; + if ((machine_min_lh > 0.0 && lh < machine_min_lh - 1e-6) || (machine_max_lh > 0.0 && lh > machine_max_lh + 1e-6)) + continue; + candidates.push_back(lh); + } + std::sort(candidates.begin(), candidates.end()); + candidates.erase(std::unique(candidates.begin(), candidates.end(), [](double a, double b) { return std::abs(a - b) < 1e-6; }), + candidates.end()); + return candidates; +} + +VfaSpeedFit fit_vfa_speed(const Calib_Params& params, const DynamicPrintConfig& printer, const DynamicPrintConfig& print, + const DynamicPrintConfig& filament, bool auto_adjust, const std::vector& candidate_layer_heights) +{ + const int extruder_id = std::max(params.extruder_id, 0); + const double nozzle_diameter = extruder_value(printer.option("nozzle_diameter"), extruder_id, vfa_base_nozzle_diameter); + double preset_lh = nozzle_diameter / 2.0; + if (const auto* lh_opt = print.option("layer_height")) + if (lh_opt->value > 0.0) + preset_lh = lh_opt->value; + double line_width = print.get_abs_value("outer_wall_line_width", nozzle_diameter); + if (line_width <= 0.0) + line_width = print.get_abs_value("line_width", nozzle_diameter); + if (line_width <= 0.0) + line_width = nozzle_diameter; + + VfaSpeedFit fit; + fit.max_vol_speed = extruder_value(filament.option("filament_max_volumetric_speed"), extruder_id, 0.0); + // The tower prints at half the nozzle diameter when scaled to the nozzle, else at the process's layer height. + fit.default_lh = params.nozzle_based_resize ? nozzle_diameter / 2.0 : preset_lh; + // The fastest outer wall the volumetric limit allows at a layer height. + auto speed_limit = [&](double lh) -> double { + const double mm3_per_mm = Flow(line_width, lh, nozzle_diameter).mm3_per_mm(); + return mm3_per_mm > 0.0 ? fit.max_vol_speed / mm3_per_mm : 1e9; + }; + if (fit.max_vol_speed <= 0.0 || nozzle_diameter <= 0.0) + return fit; + fit.speed_limit = speed_limit(fit.default_lh); + if (params.end <= fit.speed_limit) + return fit; + fit.kind = VfaSpeedFit::Clamped; + // Only a tower scaled to the nozzle may change its layer height. + if (!auto_adjust || !params.nozzle_based_resize || candidate_layer_heights.empty()) + return fit; + // The largest candidate up to the default layer height that reaches the end speed, the smallest change. + for (auto it = candidate_layer_heights.rbegin(); it != candidate_layer_heights.rend(); ++it) + if (*it <= fit.default_lh + 1e-6 && speed_limit(*it) >= params.end) { + fit.kind = VfaSpeedFit::ReducedLayerHeight; + fit.layer_height = *it; + return fit; + } + fit.kind = VfaSpeedFit::LoweredEnd; + fit.layer_height = candidate_layer_heights.front(); + fit.end = std::floor(speed_limit(fit.layer_height) / params.step) * params.step; // a step multiple it reaches + if (fit.end < params.start + params.step) + fit.end = params.start + params.step; + return fit; +} + // Calculate the optimal Pressure Advance speed float CalibPressureAdvance::find_optimal_PA_speed(const DynamicPrintConfig &config, double line_width, double layer_height, int extruder_id, int filament_idx) { diff --git a/src/libslic3r/calib.hpp b/src/libslic3r/calib.hpp index 6a63a243b9..0f78dba43f 100644 --- a/src/libslic3r/calib.hpp +++ b/src/libslic3r/calib.hpp @@ -19,6 +19,7 @@ namespace Slic3r { class GCode; class Model; class ModelObject; +class PresetCollection; enum class CalibMode : int { Calib_None = 0, @@ -65,6 +66,58 @@ static constexpr int vfa_layers_per_block = 25; static constexpr double vfa_base_block_height = 5.0; static constexpr double vfa_base_nozzle_diameter = 0.4; +// ---- Rules of the Calibration menu's dialogs, shared with automation ---------------------------- + +// Whether the printer corners by junction deviation (Marlin 2 with machine_max_junction_deviation set) +// rather than by classic jerk. +bool has_junction_deviation(const DynamicPrintConfig& printer); + +// The values a calibration dialog opens with for `mode`: start, end and step, and for input shaping the +// frequencies and damping. The pressure advance ones are the Bowden extruder's when `bowden`; cornering's +// are junction deviation or jerk values, as the printer corners. +Calib_Params calib_default_params(CalibMode mode, const DynamicPrintConfig& printer, bool bowden = false); + +// The first rule of its dialog that `params` breaks for its mode on `printer`, in the order the dialog +// checks them. Each dialog shows its own message for the error. +enum class CalibParamsError { None, Range, Damping, AccelBelowSpeed, BeltMethod }; +CalibParamsError check_calib_params(const Calib_Params& params, const DynamicPrintConfig& printer); + +// The cornering test's largest accepted end value, and the one above which its dialog warns of layer +// shifts: junction deviation in mm, or jerk in mm/s. +std::pair cornering_end_limits(const DynamicPrintConfig& printer); + +// The belt printer temperature tower of the "Overhang" model (test_model 1) for the range of `params`: +// only the ranges it was embossed for have one, so the file may not exist. +std::string belt_temp_tower_asset(const Calib_Params& params); + +// How a VFA tower's end speed fits the filament's maximum volumetric speed. The slicer caps the outer +// wall speed there, so the blocks above the cap would all print at one speed. +struct VfaSpeedFit +{ + enum Kind { + Fits, + ReducedLayerHeight, // a smaller layer height reaches the end speed: print at layer_height + LoweredEnd, // even the smallest one does not: print at layer_height up to end + Clamped, // not adjusted: the upper blocks print at speed_limit + }; + Kind kind = Fits; + double max_vol_speed = 0.; // the filament's limit, mm³/s + double default_lh = 0.; // the layer height the tower prints at unadjusted + double speed_limit = 0.; // the outer wall speed the limit allows at default_lh + double layer_height = 0.; + double end = 0.; +}; + +// The layer heights of the process presets compatible with the printer, within its layer height limits, +// smallest first: what VFA's auto-adjust may lower the layer height to. +std::vector vfa_candidate_layer_heights(const PresetCollection& prints, const DynamicPrintConfig& printer, int extruder_id); + +// The VFA dialog's auto-adjust: with `auto_adjust` and the model scaled to the nozzle, the largest +// candidate layer height at or below the default that reaches the end speed, else the smallest one with +// the end speed lowered to a step multiple it reaches; otherwise, or without candidates, Clamped. +VfaSpeedFit fit_vfa_speed(const Calib_Params& params, const DynamicPrintConfig& printer, const DynamicPrintConfig& print, + const DynamicPrintConfig& filament, bool auto_adjust, const std::vector& candidate_layer_heights); + enum FlowRatioCalibrationType { COMPLETE_CALIBRATION = 0, FINE_CALIBRATION, @@ -374,7 +427,9 @@ private: double pattern_shift() const; - const Calib_Params &m_params; + // A copy: the pattern outlives the call that made it and is read again whenever the plate is + // sliced, while callers pass params that may be temporaries. + const Calib_Params m_params; // Belt printers get belt kinematics installed on it (_refresh_writer); // shared_ptr keeps the class copyable — the writer is rebuilt by diff --git a/src/slic3r/CMakeLists.txt b/src/slic3r/CMakeLists.txt index 215a9c0ac8..9f2ffa3e42 100644 --- a/src/slic3r/CMakeLists.txt +++ b/src/slic3r/CMakeLists.txt @@ -171,6 +171,7 @@ set(SLIC3R_GUI_SOURCES GUI/Mcp/McpToolsApp.cpp GUI/Mcp/McpToolsCommon.cpp GUI/Mcp/McpToolsConfig.cpp + GUI/Mcp/McpToolsLayers.cpp GUI/Mcp/McpToolsProject.cpp GUI/Mcp/McpToolsScene.cpp GUI/Mcp/McpToolsScript.cpp diff --git a/src/slic3r/GUI/ActionRegistry.hpp b/src/slic3r/GUI/ActionRegistry.hpp index e2e34e89e9..fc2d5be9c8 100644 --- a/src/slic3r/GUI/ActionRegistry.hpp +++ b/src/slic3r/GUI/ActionRegistry.hpp @@ -32,6 +32,13 @@ struct AppActionRunResult Level level = Level::Info; wxString message; // empty = "nothing worth showing" + // False when the command did nothing (no selection, no objects): the palette shows the message + // at its level all the same, and automation reports the run as failed. + bool done = true; + // For automation only: a JSON object saying what the command did that its message does not + // (the new object order, the object an Assemble made). run_action adds its fields to the reply; + // the palette never shows it. + std::string reply; }; // Tag carrying a precomputed action id, used by the explicit-id ctor below. It exists so the diff --git a/src/slic3r/GUI/BBLTopbar.cpp b/src/slic3r/GUI/BBLTopbar.cpp index eb85b9413b..b839350489 100644 --- a/src/slic3r/GUI/BBLTopbar.cpp +++ b/src/slic3r/GUI/BBLTopbar.cpp @@ -24,6 +24,7 @@ #include "wxExtensions.hpp" #include "Plater.hpp" #include "MainFrame.hpp" +#include "SyntheticInput.hpp" #ifdef SLIC3R_CAD #include "CAD/DesignPanel.hpp" #endif @@ -652,7 +653,7 @@ void BBLTopbar::OnFileToolItem(wxAuiToolBarEvent& evt) if (!m_skip_popup_file_menu) { auto rec = this->GetToolRect(ID_TOP_FILE_MENU); - GetParent()->PopupMenu(m_file_menu, wxPoint(rec.GetLeft(), this->GetSize().GetHeight() - 2)); + popup_menu(*GetParent(), *m_file_menu, wxPoint(rec.GetLeft(), this->GetSize().GetHeight() - 2)); } else { m_skip_popup_file_menu = false; @@ -670,7 +671,7 @@ void BBLTopbar::OnDropdownToolItem(wxAuiToolBarEvent& evt) if (!m_skip_popup_dropdown_menu) { auto rec = this->GetToolRect(ID_TOP_DROPDOWN_MENU); - GetParent()->PopupMenu(&m_top_menu, wxPoint(rec.GetLeft(), this->GetSize().GetHeight() - 2)); + popup_menu(*GetParent(), m_top_menu, wxPoint(rec.GetLeft(), this->GetSize().GetHeight() - 2)); } else { m_skip_popup_dropdown_menu = false; @@ -688,7 +689,7 @@ void BBLTopbar::OnCalibToolItem(wxAuiToolBarEvent &evt) if (!m_skip_popup_calib_menu) { auto rec = this->GetToolRect(ID_CALIB); - GetParent()->PopupMenu(&m_calib_menu, wxPoint(rec.GetLeft(), this->GetSize().GetHeight() - 2)); + popup_menu(*GetParent(), m_calib_menu, wxPoint(rec.GetLeft(), this->GetSize().GetHeight() - 2)); } else { m_skip_popup_calib_menu = false; } diff --git a/src/slic3r/GUI/CAD/DesignCanvas.hpp b/src/slic3r/GUI/CAD/DesignCanvas.hpp index a7413dd370..ed90aede04 100644 --- a/src/slic3r/GUI/CAD/DesignCanvas.hpp +++ b/src/slic3r/GUI/CAD/DesignCanvas.hpp @@ -380,6 +380,8 @@ public: // having it — a socket that talked to a private copy would prove nothing about the app. DesignSketchTool& mcp_sketch_tool() { return m_sketch_tool; } const DesignSketchTool& mcp_sketch_tool() const { return m_sketch_tool; } + // The view's GL canvas, which MCP captures and sends input to as it does Prepare's. + GLCanvas3D* gl_canvas() const { return m_canvas; } void request_repaint(); // Repaint synchronously, once the pending show/resize has settled. Needed when the diff --git a/src/slic3r/GUI/CAD/DesignPanel.cpp b/src/slic3r/GUI/CAD/DesignPanel.cpp index c702bc1237..ededdf2f6a 100644 --- a/src/slic3r/GUI/CAD/DesignPanel.cpp +++ b/src/slic3r/GUI/CAD/DesignPanel.cpp @@ -7,6 +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/SyntheticInput.hpp" #include "slic3r/GUI/Widgets/Button.hpp" #include "libslic3r/CAD/GeometryEngine.hpp" // face_by_index for face-extrude gizmo anchor #include "libslic3r/AppConfig.hpp" // design_* view preferences @@ -378,34 +379,6 @@ static bool is_base_plane(const SketchPlane& p, const Vec3d& modeling_origin) && (p.x_axis - b.x_axis).norm() < e && (p.y_axis - b.y_axis).norm() < e; } -// #2: a sketch plane on `face` with origin at the face centroid and normal pointing INTO the -// solid, so a positioned hole drills inward and its (x,y) read as the offset from the face -// centre. A hole is rotationally symmetric, so the arbitrary in-plane basis is harmless. -static SketchPlane face_plane_inward(const TopoDS_Face& face) -{ - SketchPlane p; - p.origin = GeometryEngine::face_centroid_world(face); - p.normal = (-GeometryEngine::face_normal_world(face)).normalized(); // inward - // Align the in-plane x-axis with the face's LONGEST straight edge so the (u,v) frame matches - // the face sides — then "distance from a side" (the hole construction dims) reads correctly. - Vec3d x(0, 0, 0); double best = 0; - for (const TopoDS_Edge& e : GeometryEngine::edges_of_face(face)) { - const std::vector pts = GeometryEngine::sample_edge_world(e); - if (pts.size() < 2) continue; - Vec3d d = pts.back() - pts.front(); - d = d - p.normal * d.dot(p.normal); // project the edge direction into the plane - const double len = d.norm(); - if (len > best) { best = len; x = d / len; } - } - if (best < 1e-9) { // curved/edgeless face: fall back to an arbitrary in-plane basis - const Vec3d ref = std::abs(p.normal.z()) < 0.9 ? Vec3d(0, 0, 1) : Vec3d(1, 0, 0); - x = ref.cross(p.normal).normalized(); - } - p.x_axis = x.normalized(); - p.y_axis = p.normal.cross(p.x_axis).normalized(); - return p; -} - DesignPanel::DesignPanel(wxWindow* parent) : wxPanel(parent, wxID_ANY) { @@ -762,7 +735,7 @@ DesignPanel::DesignPanel(wxWindow* parent) {"design_sweep", _L("Sweep"), _L("Sweep a profile along a path"), [this] { m_sweep_profile_ref = resolve_extrude_sketch(); - m_sweep_path_ref = -1; // fresh sweep: default the picker to the first sketch + m_sweep_path_ref = -1; // fresh sweep: default the picker to the first path if (m_sweep_profile_ref < 0) { set_status(StatusKind::Error, _L("Create a profile sketch to sweep first")); return; @@ -1163,8 +1136,7 @@ DesignPanel::DesignPanel(wxWindow* parent) if (hf >= 0 && hb >= 0 && hb < int(m_doc.bodies.size())) { const TopoDS_Face face = GeometryEngine::face_by_index( m_doc.bodies[hb].shape, hf); - if (!face.IsNull()) { - m_hole_face_plane = face_plane_inward(face); + if (!face.IsNull() && m_doc.inward_plane_of_face(hb, hf, m_hole_face_plane)) { m_hole_on_face = true; m_hole_face_body = hb; set_hole_target_label(hf); // may be the top-face default, not a pick @@ -1191,22 +1163,9 @@ DesignPanel::DesignPanel(wxWindow* parent) m_thread_face_body = -1; set_thread_target_label(-1, -1); GeometryEngine::CylinderFace cf; + SketchPlane p; // plane on the axis (origin at the base) bool from_face = false; // which of the two the cylinder actually came from - if (m_sel_solid_body >= 0 && m_sel_solid_body < int(m_doc.bodies.size())) { - const TopoDS_Shape& shape = m_doc.bodies[m_sel_solid_body].shape; - if (m_sel_solid_face >= 0) - cf = GeometryEngine::cylinder_of_face(GeometryEngine::face_by_index(shape, m_sel_solid_face)); - from_face = cf.ok; - if (!cf.ok && m_sel_solid_edge >= 0) - cf = GeometryEngine::circle_of_edge(GeometryEngine::edge_by_index(shape, m_sel_solid_edge)); - } - if (cf.ok) { - SketchPlane p; // plane on the axis (origin at the base) - p.origin = cf.base; - p.normal = cf.axis; - const Vec3d ref = std::abs(cf.axis.z()) < 0.9 ? Vec3d(0, 0, 1) : Vec3d(1, 0, 0); - p.x_axis = ref.cross(cf.axis).normalized(); - p.y_axis = cf.axis.cross(p.x_axis).normalized(); + if (m_doc.thread_target(m_sel_solid_body, m_sel_solid_face, m_sel_solid_edge, p, cf, &from_face)) { m_thread_face_plane = p; m_thread_on_face = true; m_thread_face_body = m_sel_solid_body; @@ -3158,7 +3117,7 @@ DesignPanel::DesignPanel(wxWindow* parent) const int id_toggle = wxWindow::NewControlId(); menu.Append(id_toggle, bed ? bed_toggle_text(m_show_bed) : origin_toggle_text(m_show_origin)); menu.Bind(wxEVT_MENU, [this, bed](wxCommandEvent&) { bed ? toggle_bed() : toggle_origin(); }, id_toggle); - m_pinned->PopupMenu(&menu, m_pinned->ScreenToClient(screen)); + popup_menu(*m_pinned, menu, m_pinned->ScreenToClient(screen)); }; // Selecting a feature that leaves a body (Extrude, Fillet, Chamfer, Hole, ...) lights the @@ -3252,7 +3211,7 @@ DesignPanel::DesignPanel(wxWindow* parent) menu.Bind(wxEVT_MENU, [this, row](wxCommandEvent&) { on_transform_imported(row); }, id_art); if (zoom) menu.Bind(wxEVT_MENU, [this, row](wxCommandEvent&) { zoom_to_feature(row); }, id_zoom); - m_tree->PopupMenu(&menu, m_tree->ScreenToClient(screen)); + popup_menu(*m_tree, menu, m_tree->ScreenToClient(screen)); }; // In-place rename of a feature row (F2, the offer's Rename verb, or the row's menu). The name @@ -3260,9 +3219,7 @@ DesignPanel::DesignPanel(wxWindow* parent) // renaming belongs on the row, not in a side-panel field. The list hands the name over after // its editor's events have finished, so rebuilding the rows here is safe. m_tree->on_rename = [this](int row, const wxString& name) { - if (row < 0 || row >= int(m_doc.features.size())) return; - m_doc.features[row].name = std::string(name.ToUTF8().data()); - refresh_tree(); // which syncs the recipe, so the save path persists the name + rename_feature(row, std::string(name.ToUTF8().data())); }; // The header keeps what is not one row's own action: reordering, which moves the selected @@ -3384,11 +3341,7 @@ DesignPanel::DesignPanel(wxWindow* parent) // consider the extrusion = the body". CadBody::user_name is carried across recompute() by // index and written into the recipe, so the name outlives both the rebuild and the save. m_parts->on_rename = [this](int b, const wxString& name) { - if (b < 0 || b >= int(m_doc.bodies.size())) return; - m_doc.bodies[b].has_user_name = true; - m_doc.bodies[b].user_name = std::string(name.ToUTF8().data()); - sync_recipe_to_model(); // the name is part of what gets saved - refresh_parts(); + rename_body(b, std::string(name.ToUTF8().data())); }; // --- Variables (document-scope named expressions) --- @@ -3819,8 +3772,7 @@ DesignPanel::DesignPanel(wxWindow* parent) // Whole level), so no whole->face cycle is needed. if (m_active == Tool::Hole && face >= 0 && body >= 0 && body < int(m_doc.bodies.size())) { const TopoDS_Face fc = GeometryEngine::face_by_index(m_doc.bodies[body].shape, face); - if (!fc.IsNull()) { - m_hole_face_plane = face_plane_inward(fc); + if (!fc.IsNull() && m_doc.inward_plane_of_face(body, face, m_hole_face_plane)) { m_hole_on_face = true; m_hole_face_body = body; set_hole_target_label(face); @@ -3834,19 +3786,11 @@ DesignPanel::DesignPanel(wxWindow* parent) } } // Thread card open: clicking a cylindrical face or circular edge re-derives the thread. - if (m_active == Tool::Thread && body >= 0 && body < int(m_doc.bodies.size())) { - const TopoDS_Shape& shape = m_doc.bodies[body].shape; + if (m_active == Tool::Thread) { GeometryEngine::CylinderFace cf; - if (face >= 0) - cf = GeometryEngine::cylinder_of_face(GeometryEngine::face_by_index(shape, face)); - const bool from_face = cf.ok; // which of the two the cylinder actually came from - if (!cf.ok && edge >= 0) - cf = GeometryEngine::circle_of_edge(GeometryEngine::edge_by_index(shape, edge)); - if (cf.ok) { - SketchPlane p; p.origin = cf.base; p.normal = cf.axis; - const Vec3d ref = std::abs(cf.axis.z()) < 0.9 ? Vec3d(0, 0, 1) : Vec3d(1, 0, 0); - p.x_axis = ref.cross(cf.axis).normalized(); - p.y_axis = cf.axis.cross(p.x_axis).normalized(); + SketchPlane p; + bool from_face = false; // which of the two the cylinder actually came from + if (m_doc.thread_target(body, face, edge, p, cf, &from_face)) { m_thread_face_plane = p; m_thread_on_face = true; m_thread_face_body = m_sel_solid_body; @@ -4892,6 +4836,9 @@ bool DesignPanel::mcp_busy(bool read_only, bool sketch_method, std::string& why) if (m_active != Tool::None || m_edit_index >= 0) { why = "a feature card is open in the Design tab"; return true; } if (m_text_dlg != nullptr) { why = "the Text dialog is open in the Design tab"; return true; } if (m_ui_mode == UiMode::Constrain) { why = "the Design tab is constraining a sketch"; return true; } + // The Move holds a body index that any change to the document, an undo included, could point + // at another body; the tree edits and Undo refuse under it too. + if (body_move_pending()) { why = "a body Move is open in the Design tab"; return true; } // Sketch methods drive the live sketch session, which is the point of them; everything else // changes the feature list, which a live sketch session is about to commit into. if (!sketch_method && m_ui_mode == UiMode::Sketch) { why = "a sketch is open in the Design tab"; return true; } @@ -4924,8 +4871,11 @@ void DesignPanel::sync_recipe_to_model() // The plater's dirty flag rides its own undo/redo stack, which Design edits never touch, and // a design that has not been committed to the plate has no ModelObjects either — so without // this the project reads as clean: no autosave, and no "unsaved changes" prompt on quit. - // Same hook the auxiliary-files panel uses for project data that lives outside the model. + // Same hooks as other project data outside that stack (the auxiliary files, a plate's bed + // type): the backup's change mark, and the dirty flag that New/Open and the title read. Slic3r::put_other_changes(); + plater->set_plater_dirty(true); + plater->update_title_dirty_status(); } // Runs recompute() off the UI thread, because on a heavy imported solid it takes seconds. @@ -5442,20 +5392,12 @@ void DesignPanel::apply_thread_standard() void DesignPanel::infer_thread_spec(double diameter, bool internal) { - // Snap to the nearest standard thread, so picking a Ø9.9 boss gives M10 and a Ø5 tap-drill - // hole gives M6 — the M diameter, pitch AND depth all follow from the cylinder. A boss is - // matched on the MAJOR diameter; a hole on the MINOR one, since a hole to be tapped is - // drilled at the tap-drill size. - const auto& stds = thread_standards(); - int best = -1; double bestErr = 1e30; - for (int i = 0; i < int(stds.size()); ++i) { - const double ref = internal ? stds[i].minor_diameter_mm() : stds[i].major_diameter_mm; - const double e = std::abs(ref - diameter); - if (e < bestErr) { bestErr = e; best = i; } - } - if (best < 0) { if (m_thread_radius) m_thread_radius->SetValue(diameter); return; } - const ThreadSpec& s = stds[best]; - if (m_thread_std) m_thread_std->SetSelection(best + 1); // row 0 is "Custom" + // Snap to the nearest standard thread (nearest_thread_standard: a Ø9.9 boss gives M10, a + // Ø4.134 tap-drill hole M5), so the M diameter, pitch AND depth all follow from the cylinder. + const ThreadSpec* nearest = nearest_thread_standard(diameter, internal); + if (nearest == nullptr) { if (m_thread_radius) m_thread_radius->SetValue(diameter); return; } + const ThreadSpec& s = *nearest; + if (m_thread_std) m_thread_std->SetSelection(int(nearest - thread_standards().data()) + 1); // row 0 is "Custom" if (m_thread_radius) m_thread_radius->SetValue(s.major_diameter_mm); // field = NOMINAL diameter if (m_thread_pitch) m_thread_pitch->SetValue(s.pitch_mm); if (m_thread_depth) m_thread_depth->SetValue(internal ? s.internal_depth_mm() : s.thread_depth_mm()); @@ -6989,7 +6931,7 @@ void DesignPanel::show_offer_menu(const wxPoint& screen_pos) if (i >= 0 && i < int(bound.size()) && bound[i]) run_offer_action(bound[i]->action); }, base, base + 499); // 499: the mate section starts at base + 500 (see mate_base) - PopupMenu(&menu, ScreenToClient(screen_pos)); + popup_menu(*this, menu, ScreenToClient(screen_pos)); // PopupMenu is modal, so by here the menu is gone and any command it raised has already run. // A hover ghost that outlived the menu it belonged to would leave the committed bodies hidden // behind a preview nothing can dismiss — bind nothing to the close event, just clean up here. @@ -7153,31 +7095,13 @@ bool DesignPanel::on_add_plane() // dispatch falls back to offset_angle_plane() when its references are missing, so picking // Tangent and confirming with nothing selected used to produce an offset plane reported as // a success — the user asks for one construction and silently receives another. The kernel - // keeps its fallback (it must return SOMETHING), but no user gesture should reach it. - auto refuse = [this](const wxString& why) { - set_status(StatusKind::Error, why); - }; - switch ((PlaneType)m_plane_type->GetSelection()) { - case PlaneType::Angle: - if (m_pl_edgeA < 0) { refuse(_L("An angled plane needs an edge to tilt about — pick Edge A")); return false; } - break; - case PlaneType::Midplane: - if (m_pl_faceA < 0 || m_pl_faceB < 0) { refuse(_L("A midplane needs two faces — pick Face A and Face B")); return false; } - if (m_pl_faceA == m_pl_faceB && m_pl_faceA_body == m_pl_faceB_body) { - // Well-defined but useless: the midplane of a face with itself is that same face. - refuse(_L("Face A and Face B are the same face — a midplane needs two different faces")); - return false; - } - break; - case PlaneType::Tangent: - // The face must also be cylindrical; that check stays in the kernel, which has the geometry. - if (m_pl_faceA < 0) { refuse(_L("A tangent plane needs a cylindrical face — pick Face A")); return false; } - break; - case PlaneType::TwoEdges: - if (m_pl_edgeA < 0 || m_pl_edgeB < 0) { refuse(_L("This plane needs two edges — pick Edge A and Edge B")); return false; } - break; - default: - break; // Offset and Coincident are meaningful with no reference: they use the base plane + // keeps its fallback (it must return SOMETHING), but no user gesture should reach it. The + // rules are the kernel's, shared with cad_call's `plane`. + CadFeature candidate; + apply_plane_refs(candidate); + if (const std::string why = m_doc.datum_plane_refusal(candidate); !why.empty()) { + set_status(StatusKind::Error, _(why)); + return false; } m_feature_counter++; @@ -8046,14 +7970,29 @@ void DesignPanel::on_set_body_color() if (dlg.ShowModal() != wxID_OK) return; const wxColour picked = dlg.GetColourData().GetColour(); - m_doc.bodies[b].has_color = true; - m_doc.bodies[b].color = ColorRGBA((unsigned char)picked.Red(), (unsigned char)picked.Green(), - (unsigned char)picked.Blue(), (unsigned char)255); - feed_bodies(); // same refresh path the visibility toggle uses → viewport updates immediately + set_body_color(b, ColorRGBA((unsigned char)picked.Red(), (unsigned char)picked.Green(), + (unsigned char)picked.Blue(), (unsigned char)255)); +} +void DesignPanel::set_body_color(int b, const ColorRGBA& color) +{ + if (b < 0 || b >= int(m_doc.bodies.size())) return; + m_doc.bodies[b].has_color = true; + m_doc.bodies[b].color = color; + feed_bodies(); // same refresh path the visibility toggle uses → viewport updates immediately + sync_recipe_to_model(); // the colour is saved with the recipe set_status(StatusKind::Info, wxString::Format(_L("Body %d color set"), b + 1)); } +void DesignPanel::rename_body(int b, const std::string& name) +{ + if (b < 0 || b >= int(m_doc.bodies.size())) return; + m_doc.bodies[b].has_user_name = true; + m_doc.bodies[b].user_name = name; + sync_recipe_to_model(); // the name is part of what gets saved + refresh_parts(); +} + // Prepare's "Place on Face" (F), ported to Design. Pick a body face, then this rotates the // body so that face's outward normal points straight down (-Z) and drops it onto the bed — // Orca's exact math (Selection::flattening_rotate). Writes the per-body display transform @@ -8217,26 +8156,29 @@ void DesignPanel::clear_document() // other delete here, and a modal in the modelling loop is the thing charter 4.2 removes. void DesignPanel::on_delete_body() { - const int nb = int(m_doc.bodies.size()); - if (m_sel_solid_body < 0 || m_sel_solid_body >= nb) { + if (m_sel_solid_body < 0 || m_sel_solid_body >= int(m_doc.bodies.size())) { set_status(StatusKind::Error, _L("Select a body first")); return; } - const int src = m_doc.bodies[m_sel_solid_body].source_feature; + delete_body(m_sel_solid_body); +} + +bool DesignPanel::delete_body(int b) +{ + if (b < 0 || b >= int(m_doc.bodies.size())) return false; + const int src = m_doc.bodies[b].source_feature; if (src < 0 || src >= int(m_doc.features.size())) { // Only reachable for a body no feature claims — a stale recipe, or a feature type that // broke the "never replace a whole CadBody" invariant recompute() relies on. set_status(StatusKind::Error, _L("This body has no feature to delete — use New Design to start over")); - return; + return false; } const std::string& raw = m_doc.features[src].name; const wxString fname = raw.empty() ? wxString::Format(_L("feature %d"), src + 1) : wxString::FromUTF8(raw); - if (!begin_renumber()) return; - const bool ok = m_doc.remove_feature(src); - after_tree_edit(ok); - if (ok) - set_status(StatusKind::Ok, wxString::Format(_L("Deleted %s, the feature this body was made from — Ctrl+Z restores it"), fname)); + if (!delete_feature(src)) return false; + set_status(StatusKind::Ok, wxString::Format(_L("Deleted %s, the feature this body was made from — Ctrl+Z restores it"), fname)); + return true; } void DesignPanel::on_delete_feature() @@ -8252,35 +8194,32 @@ void DesignPanel::on_delete_feature() set_status(StatusKind::Info, _L("Select a feature in the tree first")); return; } - if (!begin_renumber()) return; - after_tree_edit(m_doc.remove_feature(sel)); + delete_feature(sel); +} + +bool DesignPanel::delete_feature(int f) +{ + if (f < 0 || f >= int(m_doc.features.size()) || !begin_renumber()) return false; + const bool ok = m_doc.remove_feature(f); + if (!ok) m_doc.abandon_checkpoint(); // the kernel put the features back: no undo step + after_tree_edit(ok); + return ok; } void DesignPanel::on_toggle_visibility() { - // A selected Body row toggles that body's visibility (per-body show/hide). The solid - // stays in the document; only its GLVolume + pickability flip. Falls through to the - // feature-level toggle below when a feature row (not a body row) is selected. + // A selected Body row toggles that body's visibility (per-body show/hide). Falls through to + // the feature-level toggle below when a feature row (not a body row) is selected. const int bsel = tree_body_selection(); if (bsel >= 0) { sync_body_visible(); if (bsel < int(m_body_visible.size())) { - const bool now_visible = !m_body_visible[bsel]; - m_body_visible[bsel] = now_visible; - if (m_viewport != nullptr) { - feed_bodies(); // flips is_active; m_solid_visible is a stable pointer (live) - m_viewport->set_solid_pick(&m_doc.bodies, &m_disp_pick_mesh, - &m_doc.display_tri_face, &m_doc.display_tri_body, - &m_body_visible, &m_body_xform); - } - refresh_tree(); + show_body(bsel, !m_body_visible[bsel]); // Keep the row selected for repeat toggles. m_parts, NOT m_tree: the row is a body, // and selecting it in the feature tree left the body row unselected — so the second // press of the eye found tree_body_selection() == -1 and fell through to the // FEATURE-level branch below instead of un-hiding the body. if (m_parts != nullptr) m_parts->select(bsel); - set_status(StatusKind::Info, wxString::Format(now_visible ? _L("Body %d shown") - : _L("Body %d hidden"), bsel + 1)); } return; } @@ -8295,16 +8234,42 @@ void DesignPanel::on_toggle_visibility() set_status(StatusKind::Error, _L("Select a feature in the tree first")); return; } - const bool shown = !m_doc.features[sel].enabled; + if (show_feature(sel, !m_doc.features[sel].enabled)) + set_tree_selection(sel); // keep the toggled feature selected +} + +// The solid stays in the document; only its GLVolume + pickability flip. +void DesignPanel::show_body(int b, bool shown) +{ + sync_body_visible(); + if (b < 0 || b >= int(m_body_visible.size())) return; + m_body_visible[b] = shown; + if (m_viewport != nullptr) { + feed_bodies(); // flips is_active; m_solid_visible is a stable pointer (live) + m_viewport->set_solid_pick(&m_doc.bodies, &m_disp_pick_mesh, + &m_doc.display_tri_face, &m_doc.display_tri_body, + &m_body_visible, &m_body_xform); + } + refresh_tree(); + set_status(StatusKind::Info, wxString::Format(shown ? _L("Body %d shown") : _L("Body %d hidden"), b + 1)); +} + +bool DesignPanel::show_feature(int f, bool shown) +{ + if (f < 0 || f >= int(m_doc.features.size())) return false; + if (m_doc.features[f].enabled == shown) return true; // Through the document, not a bare flag flip: hiding a feature that makes a body shifts // every later body index, and set_feature_enabled keeps those references on their bodies // (and datum-plane references on their planes). It accepts an all-hidden / sketch-only // result as the valid empty state it is, and rolls back — saying why — when a later // feature cannot do without what was hidden. m_doc.checkpoint(); - if (!m_doc.set_feature_enabled(sel, shown)) { after_tree_edit(false); return; } + if (!m_doc.set_feature_enabled(f, shown)) { + m_doc.abandon_checkpoint(); // rolled back: no undo step + after_tree_edit(false); + return false; + } refresh_tree(); // greys the row - set_tree_selection(sel); // keep the toggled feature selected if (m_viewport != nullptr) { if (m_doc.display_mesh.its.indices.empty()) { m_viewport->clear_mesh(); @@ -8321,6 +8286,7 @@ void DesignPanel::on_toggle_visibility() } sync_sketch_display(); // skips the hidden sketch + direct-renders set_status(StatusKind::Info, shown ? _L("Feature shown") : _L("Feature hidden")); + return true; } void DesignPanel::on_move_feature(int delta) @@ -8330,16 +8296,31 @@ void DesignPanel::on_move_feature(int delta) set_status(StatusKind::Info, _L("Select a feature in the tree first")); return; } - int target = sel + delta; - if (target < 0 || target >= int(m_doc.features.size())) - return; // already at the end - if (!begin_renumber()) return; - if (m_doc.move_feature(sel, delta)) { - after_tree_edit(true); - set_tree_selection(target); // keep the moved feature selected - } else { - after_tree_edit(false); - } + if (move_feature(sel, delta)) + set_tree_selection(sel + delta); // keep the moved feature selected +} + +bool DesignPanel::move_feature(int f, int delta) +{ + const int target = f + delta; + if (f < 0 || target < 0 || target >= int(m_doc.features.size())) + return false; // already at the end + if (!begin_renumber()) return false; + const bool ok = m_doc.move_feature(f, delta); + if (!ok) m_doc.abandon_checkpoint(); // the kernel put the features back: no undo step + after_tree_edit(ok); + return ok; +} + +// A feature's name is part of the recipe, so a rename is its own undo step: Undo takes back the +// rename and nothing before it. +void DesignPanel::rename_feature(int f, const std::string& name) +{ + if (f < 0 || f >= int(m_doc.features.size()) || m_doc.features[f].name == name) return; + m_doc.checkpoint(); + m_doc.features[f].name = name; + refresh_tree(); // which syncs the recipe, so the save path persists the name + update_undo_redo_buttons(); } // Commit the live sketch in place, then enter Constrain mode on the just-committed sketch. @@ -8439,16 +8420,6 @@ static wxString constraint_reject_text(ConstraintReject reason, SketchConstraint } } -// Write the typed value into every planned def. The planner returns the prefill in DISPLAY -// units and leaves def.value = 0; Angle is the one type whose stored value is not the number -// the user sees (it is radians), so the conversion lives here, exactly as the old -// apply_entity_constraint did on its Angle branch. -static void write_plan_value(std::vector& defs, double v) -{ - for (auto& d : defs) - d.value = (d.type == SketchConstraintType::Angle) ? v * M_PI / 180.0 : v; -} - void DesignPanel::apply_entity_constraint(SketchConstraintType type) { int e0 = -1, e1 = -1; @@ -10197,13 +10168,19 @@ void DesignPanel::on_export_step() wxFD_SAVE | wxFD_OVERWRITE_PROMPT); if (dlg.ShowModal() != wxID_OK) return; - sync_body_xform(); // export bodies at their displayed Move-gizmo positions std::string err; - const bool ok = m_doc.export_step(dlg.GetPath().ToUTF8().data(), m_body_xform, err); + export_step_to(dlg.GetPath().ToUTF8().data(), err); +} + +bool DesignPanel::export_step_to(const std::string& path_utf8, std::string& err) +{ + sync_body_xform(); // export bodies at their displayed Move-gizmo positions + const bool ok = m_doc.export_step(path_utf8, m_body_xform, err); set_status(ok ? StatusKind::Ok : StatusKind::Error, ok ? _L("Exported STEP") : wxString::Format(_L("STEP export failed: %s"), wxString::FromUTF8(err))); m_status->Refresh(); + return ok; } void DesignPanel::set_commit_mode(CommitMode mode) @@ -10220,6 +10197,11 @@ void DesignPanel::set_commit_mode(CommitMode mode) } void DesignPanel::on_commit() +{ + commit_to_plate(m_commit_mode); +} + +std::vector DesignPanel::commit_to_plate(CommitMode mode, std::vector* bodies_sent) { // A feature tool open with a live preview ghost (e.g. a fillet being previewed) is // NOT yet part of the body. Apply it first so "Commit to Plate" ships exactly what @@ -10230,11 +10212,19 @@ void DesignPanel::on_commit() if (m_doc.display_mesh.its.indices.empty()) { set_status(_L("Nothing to commit — add a feature first")); - return; + return {}; } + Plater* plater = wxGetApp().plater(); ObjectList* obj_list = wxGetApp().obj_list(); - if (obj_list == nullptr) - return; + if (plater == nullptr || obj_list == nullptr) + return {}; + + // A body the user named in the Bodies list gives its name to what it becomes on the plate; + // an unnamed one keeps the design's label. + auto body_label = [this](size_t b, const wxString& unnamed) { + const bool named = b < m_doc.bodies.size() && m_doc.bodies[b].has_user_name && !m_doc.bodies[b].user_name.empty(); + return named ? wxString::FromUTF8(m_doc.bodies[b].user_name) : unnamed; + }; // Multi-body: ship the (visible) bodies as the parts of one assembly object that keeps // their placement (the default), or each as its own plate object so they arrive as @@ -10242,24 +10232,34 @@ void DesignPanel::on_commit() // Hidden bodies are skipped — what you see on the Design plate is what gets committed. sync_body_visible(); rebuild_disp_meshes(); // ship moved bodies at their Move-gizmo positions + std::vector> parts; + std::vector sent; if (m_disp_body_meshes.size() > 1) { - std::vector> parts; for (size_t b = 0; b < m_disp_body_meshes.size(); ++b) { if (b < m_body_visible.size() && !m_body_visible[b]) continue; // skip hidden if (m_disp_body_meshes[b].its.indices.empty()) continue; - parts.emplace_back(&m_disp_body_meshes[b], wxString::Format(_L("Design Body %d"), int(b + 1))); + parts.emplace_back(&m_disp_body_meshes[b], body_label(b, wxString::Format(_L("Design Body %d"), int(b + 1)))); + sent.push_back(int(b)); } if (parts.empty()) { // every body hidden — nothing to ship set_status(_L("All bodies hidden — show one before committing")); - return; + return {}; } - if (m_commit_mode == CommitMode::Assembly && parts.size() > 1) + } else { + parts.emplace_back(&m_disp_pick_mesh, body_label(0, _L("Design Body"))); + sent.push_back(0); + } + + const size_t first = plater->model().objects.size(); + { + // One Prepare undo step, as Add Primitive takes around the same load, so Undo there + // takes back the commit and nothing before it. + Plater::TakeSnapshot snapshot(plater, _u8L("Commit to Plate")); + if (mode == CommitMode::Assembly && parts.size() > 1) obj_list->load_mesh_object(parts, _L("Design Assembly")); else for (const auto& [mesh, name] : parts) obj_list->load_mesh_object(*mesh, name); - } else { - obj_list->load_mesh_object(m_disp_pick_mesh, _L("Design Body")); } // Persist the editable parametric recipe alongside the committed meshes so the @@ -10269,6 +10269,13 @@ void DesignPanel::on_commit() if (wxGetApp().mainframe != nullptr) wxGetApp().mainframe->select_tab(TAB_ID_PREPARE); + + std::vector made; + for (size_t i = first; i < plater->model().objects.size(); ++i) + made.push_back(i); + if (bodies_sent != nullptr) + *bodies_sent = std::move(sent); + return made; } CadFeature DesignPanel::build_candidate(Tool t) const @@ -10722,14 +10729,22 @@ void DesignPanel::update_shell_gizmo() m_viewport->begin_shell_gizmo(c, (-n).normalized(), m_shell_thickness->GetValue()); } +int DesignPanel::default_revolve_axis_entity(const std::vector& ents) +{ + int centerline = -1, centerlines = 0; + for (int i = 0; i < int(ents.size()); ++i) + if (ents[i].type == SketchEntity::Type::Line && ents[i].construction) { centerline = i; ++centerlines; } + return centerlines == 1 ? centerline : -1; +} + void DesignPanel::fill_revolve_axes(ComboBox* combo, std::vector& ents, int sketch_ref, int axis, int entity) { combo->Clear(); ents.clear(); combo->Append(_L("Plane X")); combo->Append(_L("Plane Y")); - int centerline = -1, centerlines = 0; - if (sketch_ref >= 0 && sketch_ref < int(m_doc.features.size())) { + const bool has_sketch = sketch_ref >= 0 && sketch_ref < int(m_doc.features.size()); + if (has_sketch) { const std::vector& es = m_doc.features[sketch_ref].entities; for (int i = 0; i < int(es.size()); ++i) { if (es[i].type != SketchEntity::Type::Line) @@ -10738,11 +10753,10 @@ void DesignPanel::fill_revolve_axes(ComboBox* combo, std::vector& ents, int combo->Append(es[i].construction ? wxString::Format(_L("Centerline E%d"), i) : wxString::Format(_L("Line E%d"), i)); ents.push_back(i); - if (es[i].construction) { centerline = i; ++centerlines; } } } - if (entity == -2) // fresh revolve: a lone centerline is what the profile was drawn around - entity = centerlines == 1 ? centerline : -1; + if (entity == -2) // fresh revolve + entity = has_sketch ? default_revolve_axis_entity(m_doc.features[sketch_ref].entities) : -1; int sel = axis == 1 ? 1 : 0; for (int k = 0; k < int(ents.size()); ++k) if (ents[k] == entity) sel = 2 + k; @@ -11309,6 +11323,12 @@ void DesignPanel::start_sketch_on_target(bool offer_tools) if (!m_viewport) return; wxString on; const SketchPlane plane = sketch_plane_from_selection(on); + begin_sketch_session(plane, on, offer_tools); +} + +void DesignPanel::begin_sketch_session(const SketchPlane& plane, const wxString& on, bool offer_tools) +{ + if (!m_viewport) return; m_viewport->begin_sketch(plane, DesignSketchTool::Mode::Select); // The face or plane has been CONSUMED as the sketch plane, so drop the pick. A face left live // meant the next Extrude saw a selected face and push/pulled it instead of extruding the @@ -11686,14 +11706,14 @@ void DesignPanel::open_tool(Tool t) if (m_sweep_profile_ref >= 0 && m_sweep_profile_ref < int(m_doc.features.size())) m_sweep_profile_label->SetLabel(_L("Profile: ") + wxString::FromUTF8(m_doc.features[m_sweep_profile_ref].name)); - // Populate the path picker with every Sketch feature except the profile itself; - // the feature index rides in the entry's client data. Pre-select the stored path - // (re-edit), else the first available sketch. + // Populate the path picker with every Sketch feature except the profile itself, and every + // Helix (a spring or coil sweeps along one); the feature index rides in the entry's client + // data. Pre-select the stored path (re-edit), else the first available one. m_sweep_path->Clear(); int sel_idx = wxNOT_FOUND; for (int i = 0; i < int(m_doc.features.size()); ++i) { const CadFeature& sf = m_doc.features[i]; - if (sf.type != CadFeatureType::Sketch || i == m_sweep_profile_ref) continue; + if ((sf.type != CadFeatureType::Sketch && sf.type != CadFeatureType::Helix) || i == m_sweep_profile_ref) continue; const int pos = combo_append_index(m_sweep_path, wxString::FromUTF8(sf.name), i); if (i == m_sweep_path_ref) sel_idx = pos; } @@ -11986,7 +12006,12 @@ void DesignPanel::confirm_tool() case Tool::Revolve: on_add_revolve(); break; case Tool::Sweep: on_add_sweep(); break; case Tool::Pattern: on_add_pattern(); break; - case Tool::Plane: if (!on_add_plane()) return; break; // refused: keep the card and its picks + case Tool::Plane: + if (!on_add_plane()) { // refused: keep the card and its picks, and leave no empty undo step + m_doc.abandon_checkpoint(); + return; + } + break; case Tool::Loft: on_add_loft(); break; case Tool::Draft: on_add_draft(); break; case Tool::Boolean: on_add_boolean(); break; diff --git a/src/slic3r/GUI/CAD/DesignPanel.hpp b/src/slic3r/GUI/CAD/DesignPanel.hpp index 543dcefef0..79332e873a 100644 --- a/src/slic3r/GUI/CAD/DesignPanel.hpp +++ b/src/slic3r/GUI/CAD/DesignPanel.hpp @@ -1,9 +1,11 @@ #ifndef slic3r_DesignPanel_hpp_ #define slic3r_DesignPanel_hpp_ +#include #include #include #include +#include "libslic3r/Color.hpp" #include "libslic3r/Point.hpp" #include "libslic3r/CAD/SketchEngine.hpp" #include "libslic3r/TriangleMesh.hpp" @@ -82,11 +84,54 @@ public: void sync_recipe_to_model(); bool recompute_guarded(const wxString& message); + // What Commit to Plate sends: one object with a part per body (an assembly, which keeps the + // bodies' relative placement), or, "as bodies", one Prepare object per body. The split + // button's dropdown switches it, like Prepare's Slice button, without committing. + enum class CommitMode { Assembly, Bodies }; + CommitMode commit_mode() const { return m_commit_mode; } + // Commit to Plate in `mode`, as one Prepare undo step, then show Prepare. Returns the new + // object indices (empty when nothing was sent: no body, or every body hidden) and, in + // `bodies_sent`, the bodies they carry. The button and MCP's commit both run this. + std::vector commit_to_plate(CommitMode mode, std::vector* bodies_sent = nullptr); + // Export STEP… without its file dialog: every body at its Move-gizmo position, as native + // B-rep, to a UTF-8 path; the status line reports the result. False with `err` on failure. + bool export_step_to(const std::string& path_utf8, std::string& err); + + // The Feature tree's and Bodies list's edits, by index rather than the selected row: their + // handlers resolve the row and call these, and so does MCP. Each refreshes the tree, viewport + // and status line. A tree edit is one Design undo step, and one the kernel refuses (a consumer + // moved above its input, a feature a later one cannot do without) leaves none, with + // m_doc.error saying why. False when refused, or when an open tool or Move holds an index + // (delete and move only). + bool delete_feature(int f); + bool move_feature(int f, int delta); // -1 up, +1 down; false past either end + bool show_feature(int f, bool shown); // CadFeature::enabled; true when it already was + void rename_feature(int f, const std::string& name); // its own undo step + // The body behind body b goes by deleting the feature that made it (CadBody::source_feature), + // which can take other features with it; false when no feature claims the body. + bool delete_body(int b); + // A body's name and colour are saved in the recipe but are not in the undo history; its + // visibility is view state, in neither. + void rename_body(int b, const std::string& name); + void set_body_color(int b, const ColorRGBA& color); + void show_body(int b, bool shown); + // MCP control hooks: let the external control server (McpControl.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) - void mcp_after_change() { after_tree_edit(true); } // refresh tree + viewport + status + // Refresh tree + viewport + status after a change; `ok` false says "Edit rejected: ". + void mcp_after_change(bool ok = true) { after_tree_edit(ok); } + // The name a card gives the feature it adds ("Extrude 3"), numbered on from the GUI's features. + std::string mcp_feature_name(const wxString& kind) { ++m_feature_counter; return feature_name(kind); } DesignCanvas* mcp_viewport() { return m_viewport; } // live sketch + 3D view + // View state of body b that the recipe does not hold: whether its eye in the Bodies list is + // on, and whether the Move gizmo placed it away from where the recipe builds it (Commit and + // STEP export send it where it is shown). + bool mcp_body_shown(int b) const { return b < 0 || b >= int(m_body_visible.size()) || m_body_visible[b]; } + bool mcp_body_moved(int b) const + { + return b >= 0 && b < int(m_body_xform.size()) && !m_body_xform[b].isApprox(Transform3d::Identity()); + } // Put the PANEL into (or out of) sketch mode, not just the canvas tool. Measured on the // rig: a sketch started straight through DesignCanvas::begin_sketch leaves m_ui_mode at // Feature, and the keyboard map is dispatched on `m_ui_mode == UiMode::Sketch` while the @@ -98,6 +143,12 @@ public: set_ui_mode(on ? UiMode::Sketch : UiMode::Feature); update_action_bar(); } + // Open a sketch session on `plane` as picking that plane or face for a sketch does, without the + // tool menu the click pops up; `on` names the plane on the status line. + void mcp_begin_sketch(const SketchPlane& plane, const wxString& on) { begin_sketch_session(plane, on, false); } + // The axis a fresh Revolve card offers for a sketch's entities: its only centerline (construction + // line), which is what a profile is drawn around, or -1 for the plane axis. + static int default_revolve_axis_entity(const std::vector& ents); // The offer-table vocabulary without a right-click: the external controller asks which verbs // exist (and which apply to the current selection) and fires one by id, so a deck key names a // verb instead of spending a letter and every verb is reachable — including the rows with no @@ -243,10 +294,6 @@ private: // a modal dialog editing the feature's placement transform in place. void on_transform_imported(int feat_idx); void on_commit(); - // What Commit to Plate sends: one object with a part per body (an assembly, which keeps the - // bodies' relative placement), or, "as bodies", one Prepare object per body. The split - // button's dropdown switches it, like Prepare's Slice button, without committing. - enum class CommitMode { Assembly, Bodies }; void set_commit_mode(CommitMode mode); void on_export_step(); // write all bodies to a .step file (native B-rep) // Rehydrate the parametric model from a project's saved recipe (3MF @@ -394,6 +441,10 @@ private: // and wait for one (m_choosing_sketch_plane). void start_sketch(); void start_sketch_on_target(bool offer_tools); // a session on sketch_plane_from_selection() + // The session itself: the sketch tool on `plane`, the pick it consumed dropped, Sketch mode, and + // `on` naming the plane on the status line and the Sketch card; `offer_tools` then opens the + // tool menu, as a click that picked the plane does. + void begin_sketch_session(const SketchPlane& plane, const wxString& on, bool offer_tools); void end_sketch_plane_choice(); // leave the plane choice without a sketch; no-op outside it bool sketch_plane_pick_live() const; // may a pick made now still open the sketch? diff --git a/src/slic3r/GUI/CAD/DesignRowList.cpp b/src/slic3r/GUI/CAD/DesignRowList.cpp index 1c39009cd5..c5e7aa4f3e 100644 --- a/src/slic3r/GUI/CAD/DesignRowList.cpp +++ b/src/slic3r/GUI/CAD/DesignRowList.cpp @@ -338,6 +338,12 @@ wxRect DesignRowList::cell_rect(const wxRect& row, size_t count, size_t i) const return wxRect(x, row.y + (row.height - side) / 2, side, side); } +wxRect DesignRowList::action_rect(int row, size_t action) const +{ + const wxRect rect = GetItemRect(row); + return rect.IsEmpty() ? rect : cell_rect(rect, m_rows[row].actions.size(), action); +} + wxRect DesignRowList::label_rect(const wxRect& row, const Row& r) const { int left = row.x + FromDIP(kPadDip); diff --git a/src/slic3r/GUI/CAD/DesignRowList.hpp b/src/slic3r/GUI/CAD/DesignRowList.hpp index 7c2c524691..5a95e0efcd 100644 --- a/src/slic3r/GUI/CAD/DesignRowList.hpp +++ b/src/slic3r/GUI/CAD/DesignRowList.hpp @@ -69,6 +69,10 @@ public: void begin_rename(int row); // Re-rasterise the icons and re-measure the rows after a DPI or theme change. void Rescale(); + // For automation, which reads the rows and clicks an action icon without a pointer: the rows, and + // where a row's action icon is drawn (empty while the row is scrolled out of view). + const std::vector& rows() const { return m_rows; } + wxRect action_rect(int row, size_t action) const; std::function on_select; // the selection changed std::function on_activate; // the selected row was double-clicked diff --git a/src/slic3r/GUI/CAD/DesignSketchTool.cpp b/src/slic3r/GUI/CAD/DesignSketchTool.cpp index c1ad8b5710..a2d9860569 100644 --- a/src/slic3r/GUI/CAD/DesignSketchTool.cpp +++ b/src/slic3r/GUI/CAD/DesignSketchTool.cpp @@ -55,6 +55,7 @@ #include #include #include +#include #include "libslic3r/AppConfig.hpp" #include "libslic3r/Color.hpp" #include "slic3r/GUI/GLSelectionRectangle.hpp" @@ -1807,13 +1808,14 @@ void DesignSketchTool::drop_constraints_referencing(int ei) // Onshape scissors on the live sketch: cut the picked entity at its nearest intersection. // trim_entity/extend_entity mutate the subject in place (slide one endpoint) given the other // entities + the pick point — no entity is added/removed, so indices stay stable. -bool DesignSketchTool::apply_live_trim(const Vec2d& p, double tol, bool extend) +bool DesignSketchTool::apply_live_trim(const Vec2d& p, double tol, bool extend, int* picked) { double best = 1e30; int bi = -1; for (size_t i = 0; i < m_entities.size(); ++i) { const double d = entity_pick_dist(p, m_entities[i]); if (d < best) { best = d; bi = int(i); } } + if (picked != nullptr) *picked = best <= tol ? bi : -1; if (bi < 0 || best > tol) return false; using Ty = SketchEntity::Type; const Ty st = m_entities[bi].type; @@ -8944,9 +8946,9 @@ static bool entity_moved(const SketchEntity& a, const SketchEntity& b, double to } } -void DesignSketchTool::confirm_op() +bool DesignSketchTool::confirm_op() { - if (!op_ready()) return; + if (!op_ready()) return false; using R = SketchPointRole; using CT = SketchConstraintType; @@ -8961,7 +8963,7 @@ void DesignSketchTool::confirm_op() ? _u8L("Fillet: the radius overruns a leg, or the two lines do not meet at a corner") : _u8L("Chamfer: the distance overruns a leg, or the two lines do not meet at a corner")); reset_op(); - return; + return false; } const int a = m_op_a, b = m_op_b; m_entities[a] = a_out; m_entities[b] = b_out; @@ -9004,7 +9006,7 @@ void DesignSketchTool::confirm_op() if (out.empty()) { notify(_u8L("Offset: an ellipse or a spline has no parallel of its own kind — pick lines, arcs or circles")); reset_op(); - return; + return false; } const int ni = int(m_entities.size()); const bool single = m_op_chain.size() <= 1; @@ -9099,6 +9101,7 @@ void DesignSketchTool::confirm_op() m_selection.clear(); resolve_live(); if (on_selection_changed) on_selection_changed(0); + return true; } // ---- In-canvas transform gizmo (Move/Rotate/Scale/Array/PolarArray) ---- @@ -10476,6 +10479,115 @@ int DesignSketchTool::add_entities_scripted(const std::vector& ent return base; } +int DesignSketchTool::constrain_scripted(const std::vector& defs) +{ + const int first = int(m_constraints.size()); + if (defs.empty() || !try_add_constraints(defs)) return -1; + resolve_live(); // try_add_constraints solves but leaves the DoF readout as it was + return first; +} + +// The scripted ops set the armed tool's mode and picks for the one apply step and put the mode +// back. The entity-count baseline is resynced as add_entities_scripted does it, so a fillet arc or +// an array copy is not taken for something the armed tool just drew (j7gc). +bool DesignSketchTool::fillet_scripted(int a, int b, double value, bool chamfer) +{ + const int n = int(m_entities.size()); + if (gesture_pending() || value_field_open() || a < 0 || b < 0 || a >= n || b >= n || a == b + || m_entities[a].type != SketchEntity::Type::Line || m_entities[b].type != SketchEntity::Type::Line || !(value > 0.0)) + return false; + const Mode armed = m_mode; + m_mode = chamfer ? Mode::Chamfer : Mode::Fillet; + m_op_a = a; + m_op_b = b; + m_op_value = value; + const bool ok = confirm_op(); + m_mode = armed; + m_autoedit_seen = int(m_entities.size()); + return ok; +} + +bool DesignSketchTool::trim_scripted(const Vec2d& at, double tol, bool extend, int& picked) +{ + picked = -1; + if (gesture_pending() || value_field_open() || !apply_live_trim(at, tol, extend, &picked)) return false; + resolve_live(); // as the scissors' click does + return true; +} + +std::optional DesignSketchTool::transform_scripted(Mode mode, const std::vector& targets, const Vec2d& delta, + double angle, double scale, int count, + const std::optional& pivot) +{ + const bool transform = mode == Mode::Move || mode == Mode::Rotate || mode == Mode::Scale || mode == Mode::Array + || mode == Mode::PolarArray; + if (!transform || targets.empty() || gesture_pending() || value_field_open()) return std::nullopt; + for (int ti : targets) + if (ti < 0 || ti >= int(m_entities.size())) return std::nullopt; + const Mode armed = m_mode; + m_mode = mode; + m_tf_targets = targets; + compute_tf_pivot(); + if (pivot) m_tf_pivot = *pivot; + m_tf_delta = delta; + m_tf_angle = angle; + m_tf_scale = scale; + m_tf_count = count; + const Vec2d used = m_tf_pivot; + confirm_transform(); + m_mode = armed; + m_autoedit_seen = int(m_entities.size()); + return used; +} + +int DesignSketchTool::add_shape_scripted(Mode mode, const std::vector& clicks, int sides, bool circumscribed, + bool construction) +{ + if (gesture_pending() || value_field_open()) return -1; + const bool was_construction = m_construction, was_circumscribed = m_polygon_circumscribed; + m_construction = construction; + m_polygon_circumscribed = circumscribed; + const int base = int(m_entities.size()); + const size_t n = clicks.size(); + // The same builders and grouping as the gestures' last click (on_mouse_impl). + switch (mode) { + case Mode::Polygon: + if (n == 2) { + begin_feature(FeatureKind::Polygon); + append_entities(make_polygon(clicks[0], clicks[1], sides)); + end_feature(clicks[0], clicks[1], (clicks[1] - clicks[0]).norm(), sides); + } + break; + case Mode::Slot: + if (n == 3 && (clicks[1] - clicks[0]).squaredNorm() > 1e-12) { + const Vec2d u = (clicks[1] - clicks[0]).normalized(); + const double w = std::abs(Vec2d(-u.y(), u.x()).dot(clicks[2] - clicks[0])); + begin_feature(FeatureKind::Slot); + append_entities(make_slot(clicks[0], clicks[1], w)); + end_feature(clicks[0], clicks[1], w); + } + break; + case Mode::Ellipse: + if (n == 3) append_entities(make_ellipse(clicks[0], clicks[1], clicks[2])); + break; + case Mode::EllipseArc: + if (n == 5) append_entities(make_ellipse_arc(clicks[0], clicks[1], clicks[2], clicks[3], clicks[4])); + break; + case Mode::BSpline: + append_entities(make_bspline(clicks)); + break; + default: + break; + } + m_construction = was_construction; + m_polygon_circumscribed = was_circumscribed; + if (int(m_entities.size()) == base) return -1; + infer_auto_constraints(base, 0.0, 0.0); // exact, as add_entities_scripted infers (8xg1) + resolve_live(); + m_autoedit_seen = int(m_entities.size()); + return base; +} + bool DesignSketchTool::select_indices(const std::vector& idx) { m_selection.clear(); @@ -10489,13 +10601,13 @@ bool DesignSketchTool::select_indices(const std::vector& idx) return !m_selection.empty(); } -DesignSketchTool::LoopReport DesignSketchTool::loop_report() const +DesignSketchTool::LoopReport DesignSketchTool::loop_report(const std::vector& ents) const { LoopReport out; // Closed regions and their voids come straight from the code the viewport already uses to // decide what can be extruded, so the report cannot drift from what the tool will build. - const auto regs = region_loops(m_entities); + const auto regs = region_loops(ents); out.loops.reserve(regs.size()); for (const auto& r : regs) { LoopInfo li; @@ -10507,10 +10619,10 @@ DesignSketchTool::LoopReport DesignSketchTool::loop_report() const // Analytic where the loop IS one closed curve; shoelace only where it is a chain. // region_loops hands back the render polyline, and a circle's is a 64-gon whose area is // 0.3% short — a number reported as "area" must not be the faceting error. - if (r.ents.size() == 1 && r.ents[0] >= 0 && r.ents[0] < int(m_entities.size()) && - (m_entities[r.ents[0]].type == SketchEntity::Type::Circle || - m_entities[r.ents[0]].type == SketchEntity::Type::Ellipse)) { - const SketchEntity& c = m_entities[r.ents[0]]; + if (r.ents.size() == 1 && r.ents[0] >= 0 && r.ents[0] < int(ents.size()) && + (ents[r.ents[0]].type == SketchEntity::Type::Circle || + ents[r.ents[0]].type == SketchEntity::Type::Ellipse)) { + const SketchEntity& c = ents[r.ents[0]]; li.area = (c.type == SketchEntity::Type::Circle) ? M_PI * c.radius * c.radius : M_PI * c.radius * c.rminor; @@ -10528,7 +10640,7 @@ DesignSketchTool::LoopReport DesignSketchTool::loop_report() const // halved once at the end. (Doubling the arc term instead reads 5913.72 on the stadium // — exactly one arc's contribution too much, which is how the slip was caught.) auto ent_ends = [&](int ei, Vec2d& a, Vec2d& b) { - a = m_entities[ei].p0; b = m_entities[ei].p1; + a = ents[ei].p0; b = ents[ei].p1; }; const double eps = 1e-6; double area2 = 0.0; @@ -10536,8 +10648,8 @@ DesignSketchTool::LoopReport DesignSketchTool::loop_report() const Vec2d cur(0, 0); for (size_t k = 0; k < r.ents.size(); ++k) { const int ei = r.ents[k]; - if (ei < 0 || ei >= int(m_entities.size())) { exact = false; break; } - const SketchEntity& e = m_entities[ei]; + if (ei < 0 || ei >= int(ents.size())) { exact = false; break; } + const SketchEntity& e = ents[ei]; if (e.type != SketchEntity::Type::Line && e.type != SketchEntity::Type::Arc) { exact = false; break; // spline / ellipse arc: fall back below } @@ -10588,7 +10700,7 @@ DesignSketchTool::LoopReport DesignSketchTool::loop_report() const // coordinates, instead of only that it does. struct End { Vec2d p; }; std::vector ends; - for (const SketchEntity& e : m_entities) { + for (const SketchEntity& e : ents) { if (e.construction) continue; if (e.type == SketchEntity::Type::Line || e.type == SketchEntity::Type::Arc || e.type == SketchEntity::Type::EllipseArc || e.type == SketchEntity::Type::BSpline) { diff --git a/src/slic3r/GUI/CAD/DesignSketchTool.hpp b/src/slic3r/GUI/CAD/DesignSketchTool.hpp index 70d76cb9eb..355d4b9d96 100644 --- a/src/slic3r/GUI/CAD/DesignSketchTool.hpp +++ b/src/slic3r/GUI/CAD/DesignSketchTool.hpp @@ -593,6 +593,37 @@ public: // Drop constraint `idx` from the live session and re-solve. Same operation the badge click // performs, addressed by index instead of by position — the panel list needs the index form. bool remove_constraint(int idx); + // The CONSTRAIN bar's commit: try_add_constraints, then the live solve that refreshes dof(). + // Returns the index of the first new constraint, -1 when the batch was rolled back. + int constrain_scripted(const std::vector& defs); + + // The edit tools' and drawing tools' own apply steps, for a caller with no mouse. Each keeps + // the constraint upkeep a click gets: a fillet arc is bound Coincident and Tangent to its + // trimmed legs, constraints an op invalidates are dropped, array copies are bound to their + // source. Each refuses, changing nothing, while a gesture or a value field is pending (the + // tool's own apply step would take those over), leaves the armed tool as it was, and does not + // open a value field on what it added. + // Fillet (or chamfer) the corner of lines a and b by `value`, the radius (or setback), as the + // Fillet or Chamfer tool's Confirm does. False when the value overruns a leg. + bool fillet_scripted(int a, int b, double value, bool chamfer); + // Cut back (or extend) the entity nearest `at`, within `tol`, to its nearest crossing with the + // others, as a Trim or Extend click does. `picked` receives that entity, -1 when none is that + // close; it is also set when the entity could not be cut. + bool trim_scripted(const Vec2d& at, double tol, bool extend, int& picked); + // Move, Rotate, Scale, Array or PolarArray `targets` as the transform gizmo's Confirm does: by + // `delta` (Move; Array's step), `angle` (Rotate; PolarArray's whole sweep, radians) or `scale`, + // `count` instances counting the original. About `pivot`, else the targets' centroid, the + // gizmo's own pivot. Returns the pivot used, empty when refused. + std::optional transform_scripted(Mode mode, const std::vector& targets, const Vec2d& delta, double angle, + double scale, int count, const std::optional& pivot); + // A Polygon, Slot, Ellipse, EllipseArc or BSpline drawn from its clicks with the tool's own + // builder and shape grouping: polygon {centre, vertex or edge midpoint}, slot {centre, centre, + // a point half the width off the centreline}, ellipse {centre, major end, minor point} (+ start + // and end points for an arc), spline {poles}. `sides` and `circumscribed` are the polygon's; + // the tool's sticky polygon and construction settings are left as they were. Constraints are + // inferred exactly, as add_entities_scripted infers them. Returns the first new index, -1 when + // the clicks build nothing. + int add_shape_scripted(Mode mode, const std::vector& clicks, int sides, bool circumscribed, bool construction); // The loop report: what is CLOSED, what its internal voids are, and where a chain is still // open. This is the answer to "is my profile buildable", and it is the one question the @@ -609,7 +640,10 @@ public: std::vector loops; std::vector open_ends; // free endpoints: where a chain fails to close }; - LoopReport loop_report() const; + LoopReport loop_report() const { return loop_report(m_entities); } + // The same report for entities outside the session, such as a committed sketch's. Its loops are + // numbered as region_entity_indices_with_holes() numbers them. + LoopReport loop_report(const std::vector& ents) const; // FreeCAD's ValidateSketch, as one call: weld endpoints that are within `tol` of each other // and RECORD the Coincident constraints, so a loop that was closed by floating-point luck @@ -918,8 +952,8 @@ private: void drop_constraints_referencing(int ei); // Standalone Trim/Extend scissors on the LIVE sketch: pick the entity nearest `p` (within // `tol` plane units) and cut it back to / out to its nearest intersection with the others. - // Returns true if an entity was modified. - bool apply_live_trim(const Vec2d& p, double tol, bool extend); + // Returns true if an entity was modified; `picked`, when given, receives the entity picked. + bool apply_live_trim(const Vec2d& p, double tol, bool extend, int* picked = nullptr); // Pure-computation hover preview for Trim/Extend: mirror apply_live_trim's pick + the // engine's cut on a COPY (mutating nothing) and return, via `removed_poly`, the polyline // of the sub-portion a click would REMOVE (Trim) or ADD (Extend). `subject_ei` is the @@ -1026,7 +1060,7 @@ private: bool hit_test_op_arrow(const Vec2d& p, double tol) const; void drag_op_arrow(const Vec2d& target); // project cursor onto m_op_dir -> value void open_op_editor(); // inline-edit the value label - void confirm_op(); // apply + bind, then reset for the next gesture + bool confirm_op(); // apply + bind, then reset; false when refused void reset_op(); // clear gizmo state (keeps the tool active) bool op_ready() const; // required entities picked -> arrow/ghost live diff --git a/src/slic3r/GUI/CAD/McpControl.cpp b/src/slic3r/GUI/CAD/McpControl.cpp index 77b8f1a63c..f96a0cea4b 100644 --- a/src/slic3r/GUI/CAD/McpControl.cpp +++ b/src/slic3r/GUI/CAD/McpControl.cpp @@ -25,14 +25,28 @@ #include #include #include -#include +#include +#include +#include +#include +#include +#include #include #include +#include #include // OCCT base error #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/Mcp/McpPaths.hpp" +#include "slic3r/GUI/Mcp/UiInspector.hpp" // gizmo_name: the name get_state reports #include "slic3r/GUI/CAD/DesignPanel.hpp" #include "slic3r/GUI/CAD/DesignCanvas.hpp" #include "slic3r/GUI/CAD/DesignSketchTool.hpp" @@ -41,10 +55,16 @@ #include "libslic3r/CAD/CadDocument.hpp" #include "libslic3r/CAD/SketchEngine.hpp" #include "libslic3r/CAD/GeometryEngine.hpp" +#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 +#include #include +#include #include "libslic3r/BoundingBox.hpp" #include @@ -58,6 +78,22 @@ #include #include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include using json = nlohmann::json; @@ -115,12 +151,27 @@ std::string rpc_error(const json& id, int code, const std::string& msg) {"error", {{"code", code}, {"message", msg}}}}.dump(); } -// --- the three slice-1 methods (run on the wx MAIN thread) --------------------- +// --- describe_tools: the parameter schema of record ------------------------------ -json describe_tools() +// The `plane` param. A face resolves differently for drilling than for anything else (see +// cad_resolve_plane), so the row says which frame the method gets. +json plane_param(const json& def, bool drill) +{ + return json{{"name", "plane"}, {"type", "string|object"}, {"default", def}, + {"description", drill + ? "\"XY\", \"XZ\" or \"YZ\" through modeling_origin; {\"datum\": i}, a Plane feature; or " + "{\"body\": b, \"face\": f}, a planar face to drill into that body (origin at its " + "centroid, normal into the body, x along its longest edge). The reply's frame gives the axes." + : "\"XY\", \"XZ\" or \"YZ\" through modeling_origin; {\"datum\": i}, a Plane feature; or " + "{\"body\": b, \"face\": f}, a planar face (origin at its centroid, normal out of the " + "body, x from the world axes). The reply's frame gives the axes."}}; +} + +// One row per dispatched method (kCadMethods); each row's `access` is added from that table. +// The bridge turns these rows into MCP tool schemas, and treats a param without a default as +// required. +json tool_rows() { - // Hand-written descriptor. The bridge turns this into MCP tool schemas; later - // slices grow this list (ideally from the kernel directly). return json{ {"app", "Orca CAD"}, {"protocol", "jsonrpc-2.0"}, @@ -134,34 +185,53 @@ json describe_tools() "before each id-taking call, or pass the 'generation' you were given back with the " "call and have it refused if the model has moved on."}, {"tools", json::array({ - json{{"name", "describe_tools"}, {"summary", "List callable tools and their parameters."}, - {"params", json::array()}}, - json{{"name", "describe_scene"}, {"summary", "Feature tree + per-body bounding boxes of the Design document."}, - {"params", json::array()}}, - json{{"name", "extrude"}, {"summary", "Extrude a profile to a depth. Give an explicit closed `profile` (list of [x,y]) or default to a centred width x height rectangle. End conditions match Onshape."}, + json{{"name", "describe_tools"}, {"summary", "List callable methods and their parameters. Filter with method (a name or a list of names) and query (text in a name or summary)."}, {"params", json::array({ + json{{"name", "method"}, {"type", "string|array"}, {"default", ""}, {"description", "only these methods"}}, + json{{"name", "query"}, {"type", "string"}, {"default", ""}, {"description", "only methods whose name or summary contains this, in any case"}}, + })}}, + json{{"name", "describe_scene"}, {"summary", "The Design document: features (bound: fields an expression drives), variables with their values, bodies (bbox, source_feature, visible, color, moved by the Move gizmo), undo_depth / redo_depth and generation."}, + {"params", json::array()}}, + json{{"name", "describe_feature"}, {"summary", "One feature as its card shows it: params, the editable ones with their ranges, expr (bindings), refs (feature and body indices, face and edge ids), a sketch's plane, entities and constraints (angles in degrees), used_by and bodies_made."}, + {"params", json::array({ + json{{"name", "feature"}, {"type", "integer"}, {"description", "feature index (describe_scene)"}}, + })}}, + json{{"name", "set_feature"}, {"summary", "Change a feature's editable fields as its card's Confirm does when editing: one undo step and a rebuild. A field an expression drives is refused. Reply: changed {field: [old, new]}."}, + {"params", json::array({ + json{{"name", "feature"}, {"type", "integer"}, {"description", "feature index (describe_scene)"}}, + json{{"name", "fields"}, {"type", "object"}, {"description", "{field: value} from describe_feature's editable, e.g. {\"distance\": 15}: numbers within its ranges; mode new|union|subtract|intersect; extrude_end blind|symmetric|two_sided|through_all; shape rectangle|circle; xf_* vectors [x, y, z]"}}, + })}}, + json{{"name", "extrude"}, {"summary", "Extrude a committed sketch, or one loop of it, as the Extrude card does; push/pull a planar face of a body; or a profile drawn here: an explicit closed `profile` (list of [x,y]) or a centred width x height rectangle on `plane`. End conditions match Onshape. Reply: extrude_index, the index of its sketch (-1 for a face), the boolean and body used, end, frame."}, + {"params", json::array({ + json{{"name", "sketch"}, {"type", "integer"}, {"default", nullptr}, {"description", "a committed Sketch feature to extrude (sketch_commit's sketch_index); profile, width, height and plane are then refused"}}, + json{{"name", "loop"}, {"type", "integer"}, {"default", nullptr}, {"description", "with sketch: one closed loop (closed_loops[].index of sketch_describe {sketch}) with the loops inside it as holes; a hole is a loop of its own, so its index extrudes the disc. Omit for the whole sketch"}}, + json{{"name", "face"}, {"type", "integer"}, {"default", nullptr}, {"description", "push/pull: a planar face (query_topology id) of `body` grown along its outward normal (flip for inward); boolean auto joins that body. sketch, loop, profile, width, height, plane and taper are then refused, and end is blind or symmetric"}}, json{{"name", "width"}, {"type", "number"}, {"unit", "mm"}, {"default", 20}, {"min", 0.01}}, json{{"name", "height"}, {"type", "number"}, {"unit", "mm"}, {"default", 20}, {"min", 0.01}}, json{{"name", "distance"}, {"type", "number"}, {"unit", "mm"}, {"default", 10}, {"min", 0.01}}, - json{{"name", "plane"}, {"type", "string"}, {"enum", json::array({"XY", "XZ", "YZ"})}, {"default", "XY"}}, + plane_param("XY", false), json{{"name", "profile"}, {"type", "array"}, {"default", json::array()}, {"description", "optional closed contour [[x,y],...] in plane mm; overrides width/height"}}, - json{{"name", "boolean"}, {"type", "string"}, {"enum", json::array({"new", "union", "subtract", "intersect"})}, {"default", "new"}}, + json{{"name", "boolean"}, {"type", "string"}, {"enum", json::array({"auto", "new", "union", "subtract", "intersect"})}, {"default", nullptr}, {"description", "auto joins the body the profile touches, else makes a new body, as the card's default; default auto with sketch, new without"}}, + json{{"name", "body"}, {"type", "integer"}, {"default", -1}, {"description", "the body to join, subtract from or intersect, or whose face is pushed; omit for the body a sketch touches, else the last body"}}, json{{"name", "end"}, {"type", "string"}, {"enum", json::array({"blind", "symmetric", "two_sided", "through_all", "up_to_face"})}, {"default", "blind"}}, json{{"name", "distance2"},{"type", "number"}, {"unit", "mm"}, {"default", 0}, {"description", "second-side depth when end=two_sided (else falls back to distance)"}}, - json{{"name", "up_to_face"},{"type", "integer"}, {"default", -1}, {"description", "target face id (query_topology on the last body) when end=up_to_face"}}, + json{{"name", "up_to_face"},{"type", "integer"}, {"default", -1}, {"description", "face id (query_topology) of the body the extrude works on, when end=up_to_face"}}, json{{"name", "taper"}, {"type", "number"}, {"unit", "deg"}, {"default", 0}, {"description", "draft/taper of the side wall"}}, json{{"name", "flip"}, {"type", "boolean"}, {"default", false}}, })}}, - json{{"name", "revolve"}, {"summary", "Revolve a profile about a plane axis. Give an explicit `profile` offset from the axis (or a rectangle) — angle degrees about axis 0=plane X / 1=plane Y."}, + json{{"name", "revolve"}, {"summary", "Revolve a committed sketch as the Revolve card does, about a line of it or a plane axis; or a profile drawn here: an explicit `profile` offset from the axis, or a rectangle. Reply: revolve_index, the index of its sketch, the boolean, body and axis used, frame."}, {"params", json::array({ + json{{"name", "sketch"}, {"type", "integer"}, {"default", nullptr}, {"description", "a committed Sketch feature to revolve (sketch_commit's sketch_index); profile, width, height and plane are then refused"}}, + json{{"name", "axis_entity"}, {"type", "integer"}, {"default", nullptr}, {"description", "with sketch: a line of the sketch (entity index) as the axis, or -1 for the plane axis; omit for the sketch's only centerline (construction line) when it has one and axis is not given"}}, json{{"name", "width"}, {"type", "number"}, {"unit", "mm"}, {"default", 20}, {"min", 0.01}}, json{{"name", "height"}, {"type", "number"}, {"unit", "mm"}, {"default", 10}, {"min", 0.01}}, json{{"name", "angle"}, {"type", "number"}, {"unit", "deg"}, {"default", 360}}, - json{{"name", "axis"}, {"type", "integer"}, {"enum", json::array({0, 1})}, {"default", 0}}, + json{{"name", "axis"}, {"type", "integer"}, {"enum", json::array({0, 1})}, {"default", 0}, {"description", "the plane's X (0) or Y (1) axis through its origin"}}, json{{"name", "flip"}, {"type", "boolean"}, {"default", false}}, - json{{"name", "plane"}, {"type", "string"}, {"enum", json::array({"XY", "XZ", "YZ"})}, {"default", "XY"}}, + plane_param("XY", false), json{{"name", "profile"}, {"type", "array"}, {"default", json::array()}, {"description", "optional closed contour [[x,y],...] in plane mm; overrides width/height"}}, json{{"name", "boolean"}, {"type", "string"}, {"enum", json::array({"new", "union", "subtract", "intersect"})}, {"default", "new"}}, + json{{"name", "body"}, {"type", "integer"}, {"default", -1}, {"description", "the body to join, subtract from or intersect; omit for the last body"}}, })}}, json{{"name", "fillet"}, {"summary", "Round measured edges of a body (edge ids from query_topology on that body)."}, {"params", json::array({ @@ -175,23 +245,27 @@ json describe_tools() json{{"name", "distance"}, {"type", "number"}, {"unit", "mm"}, {"default", 1}, {"min", 0.01}}, json{{"name", "body"}, {"type", "integer"}, {"default", -1}, {"description", "target body; omit for the last body. edge id is resolved against THIS body."}}, })}}, - json{{"name", "hole"}, {"summary", "Drill a circular hole into the current body at (x,y) on a plane."}, + json{{"name", "hole"}, {"summary", "Drill a circular hole at (x,y) or `at` on a plane. Reply: hole_index, body, x and y in the frame, off_plane with at, frame."}, {"params", json::array({ json{{"name", "diameter"}, {"type", "number"}, {"unit", "mm"}, {"default", 5}, {"min", 0.01}}, json{{"name", "depth"}, {"type", "number"}, {"unit", "mm"}, {"default", 10}, {"min", 0.01}}, json{{"name", "through"}, {"type", "boolean"}, {"default", false}}, - json{{"name", "x"}, {"type", "number"}, {"unit", "mm"}, {"default", 0}, {"description", "in the sketch plane's frame (origin = describe_scene.modeling_origin), NOT world"}}, - json{{"name", "y"}, {"type", "number"}, {"unit", "mm"}, {"default", 0}, {"description", "in the sketch plane's frame (origin = describe_scene.modeling_origin), NOT world"}}, - json{{"name", "plane"}, {"type", "string"}, {"enum", json::array({"XY", "XZ", "YZ"})}, {"default", "XY"}}, + json{{"name", "x"}, {"type", "number"}, {"unit", "mm"}, {"default", 0}, {"description", "offset in the plane's frame from its origin, NOT world"}}, + json{{"name", "y"}, {"type", "number"}, {"unit", "mm"}, {"default", 0}, {"description", "offset in the plane's frame from its origin, NOT world"}}, + plane_param("XY", true), + json{{"name", "at"}, {"type", "array|object"}, {"default", nullptr}, {"description", "instead of x and y: a world point [x, y, z], projected onto the plane along its normal (off_plane says how far), or {\"body\": b, \"face\": f} a cylindrical face or {\"body\": b, \"edge\": e} a circular edge whose axis the hole shares. A world point moves with modeling_origin; x and y replay on any printer"}}, + json{{"name", "body"}, {"type", "integer"}, {"default", -1}, {"description", "the body to drill; omit for a face plane's body, else the last body"}}, })}}, - json{{"name", "hole_styled"}, {"summary", "Drill a hole with optional counterbore (style=1) or countersink (style=2) at (x,y) on a plane."}, + json{{"name", "hole_styled"}, {"summary", "Drill a hole with optional counterbore (style=1) or countersink (style=2) at (x,y) or `at` on a plane. Reply as hole."}, {"params", json::array({ json{{"name", "diameter"}, {"type", "number"}, {"unit", "mm"}, {"default", 5}, {"min", 0.01}}, json{{"name", "depth"}, {"type", "number"}, {"unit", "mm"}, {"default", 10}, {"min", 0.01}}, json{{"name", "through"}, {"type", "boolean"}, {"default", true}}, - json{{"name", "x"}, {"type", "number"}, {"unit", "mm"}, {"default", 0}, {"description", "in the sketch plane's frame (origin = describe_scene.modeling_origin), NOT world"}}, - json{{"name", "y"}, {"type", "number"}, {"unit", "mm"}, {"default", 0}, {"description", "in the sketch plane's frame (origin = describe_scene.modeling_origin), NOT world"}}, - json{{"name", "plane"}, {"type", "string"}, {"enum", json::array({"XY", "XZ", "YZ"})}, {"default", "XY"}}, + json{{"name", "x"}, {"type", "number"}, {"unit", "mm"}, {"default", 0}, {"description", "offset in the plane's frame from its origin, NOT world"}}, + json{{"name", "y"}, {"type", "number"}, {"unit", "mm"}, {"default", 0}, {"description", "offset in the plane's frame from its origin, NOT world"}}, + plane_param("XY", true), + json{{"name", "at"}, {"type", "array|object"}, {"default", nullptr}, {"description", "instead of x and y: a world point [x, y, z], projected onto the plane along its normal (off_plane says how far), or {\"body\": b, \"face\": f} a cylindrical face or {\"body\": b, \"edge\": e} a circular edge whose axis the hole shares. A world point moves with modeling_origin; x and y replay on any printer"}}, + json{{"name", "body"}, {"type", "integer"}, {"default", -1}, {"description", "the body to drill; omit for a face plane's body, else the last body"}}, json{{"name", "style"}, {"type", "integer"}, {"default", 0}, {"description", "0=simple, 1=counterbore, 2=countersink"}}, json{{"name", "cbore_diameter"}, {"type", "number"}, {"unit", "mm"}, {"default", 0}}, json{{"name", "cbore_depth"}, {"type", "number"}, {"unit", "mm"}, {"default", 0}}, @@ -199,15 +273,33 @@ json describe_tools() json{{"name", "csink_angle"}, {"type", "number"}, {"unit", "deg"}, {"default", 90}}, json{{"name", "standard"}, {"type", "string"}, {"default", ""}, {"description", "provenance designation, e.g. M6"}}, })}}, - json{{"name", "hole_standard"}, {"summary", "Drill a standard clearance hole (ISO 273 / ANSI) at (x,y) on a plane. style: 0=simple, 1=counterbore, 2=countersink."}, + json{{"name", "hole_standard"}, {"summary", "Drill a standard clearance hole (ISO 273 / ANSI) at (x,y) or `at` on a plane. style: 0=simple, 1=counterbore, 2=countersink. Reply as hole."}, {"params", json::array({ json{{"name", "designation"}, {"type", "string"}, {"description", "e.g. M6, 1/4-20"}}, json{{"name", "style"}, {"type", "integer"}, {"default", 0}}, json{{"name", "through"}, {"type", "boolean"}, {"default", true}}, json{{"name", "depth"}, {"type", "number"}, {"unit", "mm"}, {"default", 10}, {"min", 0.01}}, - json{{"name", "x"}, {"type", "number"}, {"unit", "mm"}, {"default", 0}, {"description", "in the sketch plane's frame (origin = describe_scene.modeling_origin), NOT world"}}, - json{{"name", "y"}, {"type", "number"}, {"unit", "mm"}, {"default", 0}, {"description", "in the sketch plane's frame (origin = describe_scene.modeling_origin), NOT world"}}, - json{{"name", "plane"}, {"type", "string"}, {"enum", json::array({"XY", "XZ", "YZ"})}, {"default", "XY"}}, + json{{"name", "x"}, {"type", "number"}, {"unit", "mm"}, {"default", 0}, {"description", "offset in the plane's frame from its origin, NOT world"}}, + json{{"name", "y"}, {"type", "number"}, {"unit", "mm"}, {"default", 0}, {"description", "offset in the plane's frame from its origin, NOT world"}}, + plane_param("XY", true), + json{{"name", "at"}, {"type", "array|object"}, {"default", nullptr}, {"description", "instead of x and y: a world point [x, y, z], projected onto the plane along its normal (off_plane says how far), or {\"body\": b, \"face\": f} a cylindrical face or {\"body\": b, \"edge\": e} a circular edge whose axis the hole shares. A world point moves with modeling_origin; x and y replay on any printer"}}, + json{{"name", "body"}, {"type", "integer"}, {"default", -1}, {"description", "the body to drill; omit for a face plane's body, else the last body"}}, + })}}, + json{{"name", "thread"}, {"summary", "Cut a thread as the Thread card does: along a cylindrical face (a bore is tapped, a boss threaded) or a circular edge, or on a plane at (x,y) or `at`. Without designation, a face or edge takes the nearest standard size, ISO metric and UTS alike. Long threads take seconds and the reply may be a job. Reply: thread_index, designation (null when custom), internal, diameter, pitch, depth, length, body, x, y, frame."}, + {"params", json::array({ + json{{"name", "face"}, {"type", "integer"}, {"default", nullptr}, {"description", "a cylindrical face id of `body` (query_topology); the thread runs its length from its lower end"}}, + json{{"name", "edge"}, {"type", "integer"}, {"default", nullptr}, {"description", "instead of face: a circular edge id of `body`, the thread rising along its normal; needs length"}}, + json{{"name", "body"}, {"type", "integer"}, {"default", -1}, {"description", "the body of face or edge, or the body threaded on a plane; omit for the last body (on a plane, a face plane's body)"}}, + json{{"name", "designation"}, {"type", "string"}, {"default", nullptr}, {"description", "e.g. M5, M8x1, 1/4-20 UNC: sets diameter, pitch and depth"}}, + json{{"name", "internal"}, {"type", "boolean"}, {"default", nullptr}, {"description", "true taps a hole, false threads a rod; required on a plane, else from the face (a bore is internal), external for an edge"}}, + json{{"name", "diameter"}, {"type", "number"}, {"unit", "mm"}, {"default", nullptr}, {"description", "nominal (major) diameter, replacing the standard's; with pitch, a custom thread"}}, + json{{"name", "pitch"}, {"type", "number"}, {"unit", "mm"}, {"default", nullptr}, {"description", "replaces the standard's"}}, + json{{"name", "depth"}, {"type", "number"}, {"unit", "mm"}, {"default", nullptr}, {"description", "radial depth; default the 60 degree V's for the pitch and role"}}, + json{{"name", "length"}, {"type", "number"}, {"unit", "mm"}, {"default", nullptr}, {"description", "default the face's length; required for an edge or a plane"}}, + plane_param(nullptr, true), + json{{"name", "x"}, {"type", "number"}, {"unit", "mm"}, {"default", 0}, {"description", "on a plane: offset in the plane's frame from its origin, NOT world"}}, + json{{"name", "y"}, {"type", "number"}, {"unit", "mm"}, {"default", 0}, {"description", "on a plane: offset in the plane's frame from its origin, NOT world"}}, + json{{"name", "at"}, {"type", "array|object"}, {"default", nullptr}, {"description", "on a plane, instead of x and y: a world point [x, y, z], or {\"body\": b, \"face\": f} a cylindrical face or {\"body\": b, \"edge\": e} a circular edge whose axis the thread shares, as hole takes it"}}, })}}, json{{"name", "boolean"}, {"summary", "Combine two bodies: union | subtract (tool from target) | intersect."}, {"params", json::array({ @@ -224,7 +316,7 @@ json describe_tools() json{{"name", "spacing"}, {"type", "number"}, {"unit", "mm"}, {"default", 10}, {"description", "linear step"}}, json{{"name", "dir"}, {"type", "integer"}, {"enum", json::array({0, 1})}, {"default", 0}, {"description", "linear axis: 0=plane X, 1=plane Y"}}, json{{"name", "angle"}, {"type", "number"}, {"unit", "deg"}, {"default", 360}, {"description", "circular total sweep"}}, - json{{"name", "plane"}, {"type", "string"}, {"enum", json::array({"XY", "XZ", "YZ"})}, {"default", "XY"}}, + plane_param("XY", false), json{{"name", "body"}, {"type", "integer"}, {"default", -1}, {"description", "target body; omit for the last body"}}, })}}, json{{"name", "pattern_on_curve"}, {"summary", "Replicate a body along a sketch curve: `count` copies placed at equal-parameter points on the entity, each translated by (P_i - P_0)."}, @@ -248,7 +340,7 @@ json describe_tools() })}}, json{{"name", "mirror"}, {"summary", "Mirror a body about a base plane. mode=new creates a mirrored copy; mode=add fuses the mirror back into the source."}, {"params", json::array({ - json{{"name", "plane"}, {"type", "string"}, {"enum", json::array({"XY", "XZ", "YZ"})}, {"default", "XZ"}}, + plane_param("XZ", false), json{{"name", "mode"}, {"type", "string"}, {"enum", json::array({"new", "add"})}, {"default", "new"}}, json{{"name", "keep_original"},{"type", "boolean"}, {"default", true}, {"description", "when mode=new, keep the source body"}}, json{{"name", "body"}, {"type", "integer"}, {"default", -1}, {"description", "target body; omit for the last body"}}, @@ -288,14 +380,41 @@ json describe_tools() json{{"name", "edge"}, {"type", "integer"}, {"default", -1}, {"description", "edge id (query_topology) for X axis hint"}}, json{{"name", "x_hint"}, {"type", "array"}, {"default", json::array({1,0,0})}, {"description", "fallback X direction hint if no edge given"}}, })}}, - json{{"name", "helix"}, {"summary", "Create a helical curve (consumed by sweep as a path to build springs/coils/augers). pitch = axial rise per turn. left_handed flips the winding. taper_deg != 0 gives a conical helix."}, + json{{"name", "plane"}, {"summary", "Add a datum plane as the Plane card does, to sketch or build on as {\"datum\": plane_index}: offset from a base plane or a face, at an angle about an edge, midway between two faces, tangent to a cylindrical face, through two edges, or coincident with a base plane or a face. Not the `plane` param of other methods. Reply: plane_index, name, frame."}, + {"params", json::array({ + json{{"name", "type"}, {"type", "string"}, {"enum", json::array({"offset", "angle", "midplane", "tangent", "two_edges", "coincident"})}, {"default", "offset"}}, + json{{"name", "base"}, {"type", "string|object"}, {"default", "XY"}, {"description", "\"XY\", \"XZ\" or \"YZ\" through modeling_origin, or {\"datum\": i}: what offset, coincident and angle build on without face_a"}}, + json{{"name", "offset"}, {"type", "number"}, {"unit", "mm"}, {"default", 20}, {"description", "offset: distance along the normal of base or face_a"}}, + json{{"name", "angle"}, {"type", "number"}, {"unit", "deg"}, {"default", 0}, {"description", "offset without face_a: tilt about the base axis `axis`; angle: turn about edge_a from the reference plane; tangent: position around the cylinder"}}, + json{{"name", "axis"}, {"type", "integer"}, {"enum", json::array({0, 1})}, {"default", 0}, {"description", "offset without face_a: tilt about the base plane's X (0) or Y (1) axis"}}, + json{{"name", "face_a"}, {"type", "object"}, {"default", nullptr}, {"description", "Face A, {\"body\": b, \"face\": f}: offset or coincident on a face; angle's reference plane; midplane's first face; tangent's cylindrical face"}}, + json{{"name", "face_b"}, {"type", "object"}, {"default", nullptr}, {"description", "Face B, {\"body\": b, \"face\": f}: midplane's second face"}}, + json{{"name", "edge_a"}, {"type", "object"}, {"default", nullptr}, {"description", "Edge A, {\"body\": b, \"edge\": e}: angle's hinge; two_edges' first edge"}}, + json{{"name", "edge_b"}, {"type", "object"}, {"default", nullptr}, {"description", "Edge B, {\"body\": b, \"edge\": e}: two_edges' second edge"}}, + json{{"name", "size"}, {"type", "array"}, {"unit", "mm"}, {"default", json::array({60, 60})}, {"description", "[u, v]: the size the plane is drawn at"}}, + })}}, + json{{"name", "helix"}, {"summary", "Create a helical curve, a sweep path for springs, coils and augers, starting on the plane's x axis at `radius` from its origin. pitch = axial rise per turn. left_handed flips the winding. taper_deg != 0 gives a conical helix. Reply: helix_index, frame, start and tangent (world), to draw a sweep's profile across the curve there."}, {"params", json::array({ json{{"name", "radius"}, {"type", "number"}, {"unit", "mm"}, {"default", 10}, {"min", 0.01}}, json{{"name", "pitch"}, {"type", "number"}, {"unit", "mm"}, {"default", 5}, {"min", 0.01}}, json{{"name", "height"}, {"type", "number"}, {"unit", "mm"}, {"default", 20}, {"min", 0.01}}, json{{"name", "left_handed"}, {"type", "boolean"}, {"default", false}}, json{{"name", "taper_deg"}, {"type", "number"}, {"unit", "deg"}, {"default", 0}}, - json{{"name", "plane"}, {"type", "string"}, {"enum", json::array({"XY", "XZ", "YZ"})}, {"default", "XY"}}, + plane_param("XY", false), + })}}, + json{{"name", "sweep"}, {"summary", "Sweep a committed sketch's closed profile along a path, a sketch or a helix, as the Sweep card does. Draw the profile across the path's start (a helix's start and tangent are in its reply); along a helix the profile keeps its angle to the helix axis. Long sweeps take seconds and the reply may be a job. Reply: sweep_index, bodies, boolean, body."}, + {"params", json::array({ + json{{"name", "sketch"}, {"type", "integer"}, {"description", "the profile: a committed sketch's feature index"}}, + json{{"name", "path"}, {"type", "integer"}, {"description", "feature index of a sketch or a helix, other than the profile"}}, + json{{"name", "boolean"}, {"type", "string"}, {"enum", json::array({"new", "union", "subtract", "intersect"})}, {"default", "new"}}, + json{{"name", "body"}, {"type", "integer"}, {"default", -1}, {"description", "the body a union, subtract or intersect works on; omit for the last body"}}, + })}}, + json{{"name", "loft"}, {"summary", "Loft a solid through two or more committed sketches, in order, each on its own plane (sketch on datum planes), as the Loft card does. Lofts take seconds and the reply may be a job. Reply: loft_index, bodies, boolean, body."}, + {"params", json::array({ + json{{"name", "profiles"}, {"type", "array"}, {"description", "sketch feature indices, in loft order"}}, + json{{"name", "ruled"}, {"type", "boolean"}, {"default", false}, {"description", "straight sections between the profiles instead of a smooth skin"}}, + json{{"name", "boolean"}, {"type", "string"}, {"enum", json::array({"new", "union", "subtract", "intersect"})}, {"default", "new"}}, + json{{"name", "body"}, {"type", "integer"}, {"default", -1}, {"description", "the body a union, subtract or intersect works on; omit for the last body"}}, })}}, json{{"name", "thicken"}, {"summary", "Offset a face of a body by a wall thickness, producing a new thin solid body."}, {"params", json::array({ @@ -304,11 +423,14 @@ json describe_tools() json{{"name", "thickness"}, {"type", "number"}, {"unit", "mm"}, {"default", 2}, {"min", 0.01}}, json{{"name", "flip"}, {"type", "boolean"}, {"default", false}}, })}}, - json{{"name", "split"}, {"summary", "Split a body along the plane of a picked face."}, + json{{"name", "split"}, {"summary", "Split a body with a plane, as the Cut card does, moved by offset and turned over by flip; or along the plane of a face. The upper piece is on the plane's normal side; keeping both makes two bodies, the lower one right after the upper. Reply: split_index, bodies, body, upper_body and lower_body (the pieces kept), frame (a plane's, after offset and flip)."}, {"params", json::array({ json{{"name", "body"}, {"type", "integer"}, {"default", -1}, {"description", "target body; omit for the last body"}}, - json{{"name", "face_body"}, {"type", "integer"}, {"default", -1}, {"description", "body that owns the face; -1 = target"}}, - json{{"name", "face"}, {"type", "integer"}, {"description", "face id to split along (query_topology)"}}, + plane_param(nullptr, false), + json{{"name", "offset"}, {"type", "number"}, {"unit", "mm"}, {"default", 0}, {"description", "with plane: along its normal"}}, + json{{"name", "flip"}, {"type", "boolean"}, {"default", false}, {"description", "with plane: turn it over, swapping upper and lower"}}, + json{{"name", "face"}, {"type", "integer"}, {"default", nullptr}, {"description", "instead of plane: a face id (query_topology) to split along"}}, + json{{"name", "face_body"}, {"type", "integer"}, {"default", -1}, {"description", "with face: the body that owns it; -1 = target"}}, json{{"name", "keep_upper"},{"type", "boolean"}, {"default", true}}, json{{"name", "keep_lower"},{"type", "boolean"}, {"default", true}}, })}}, @@ -317,7 +439,7 @@ json describe_tools() json{{"name", "source_body"}, {"type", "integer"}, {"default", -1}, {"description", "body owning the edges; -1 = last body"}}, json{{"name", "face"}, {"type", "integer"}, {"default", -1}, {"description", "global face id on the source body; when set, all its edges are projected"}}, json{{"name", "edges"}, {"type", "array"}, {"default", json::array()}, {"description", "global edge ids to project; empty => project the face"}}, - json{{"name", "plane"}, {"type", "string"}, {"default", "XY"}, {"description", "target sketch plane (XY/XZ/YZ)"}}, + plane_param("XY", false), })}}, json{{"name", "delete_face"}, {"summary", "Remove faces from a solid, healing the gap via OCCT defeaturing."}, {"params", json::array({ @@ -332,7 +454,7 @@ json describe_tools() json{{"name", "ent_b"}, {"type", "integer"}, {"description", "second entity index within the sketch"}}, json{{"name", "end_b"}, {"type", "integer"}, {"enum", json::array({0, 1})}, {"default", 0}, {"description", "0 = start/p0 side, 1 = end/p1 side"}}, })}}, - json{{"name", "rib"}, {"summary", "Grow a thin rib wall (stiffener) from an open Line sketch entity, fused to a body."}, + json{{"name", "rib"}, {"summary", "Grow a thin rib wall (stiffener) from an open Line sketch entity, fused to a body. The wall is centred on the line in the sketch plane, thickness wide, and grows depth along the sketch plane's normal."}, {"params", json::array({ json{{"name", "sketch"}, {"type", "integer"}, {"description", "sketch feature index holding the open line"}}, json{{"name", "entity"}, {"type", "integer"}, {"description", "entity index of the open Line within the sketch"}}, @@ -364,15 +486,23 @@ json describe_tools() {"params", json::array({ json{{"name", "min_volume"}, {"type", "number"}, {"unit", "mm^3"}, {"default", 1e-6}, {"description", "overlap volume above which a pair counts as interfering"}}, })}}, - json{{"name", "query_topology"}, {"summary", "Measured faces (centroid/normal/cylinder) and edges (length/circle) of a body."}, + json{{"name", "query_topology"}, {"summary", "A body's faces (kind, area, centroid, normal, and a cylinder's, cone's, sphere's or torus's numbers) and edges (kind, length, ends, a circle's centre and radius). Face filters (kinds, direction, at_extreme) and edge filters (edge_kinds, direction, convex) narrow their own list; when filters are given, a list none of its filters names is empty, or with adjacency holds the neighbours of the other list. Reply: face_count and edge_count of the body, faces_total and edges_total after filtering, next_offset while a page has more, generation."}, {"params", json::array({ - json{{"name", "body"}, {"type", "integer"}, {"default", 0}}, + json{{"name", "body"}, {"type", "integer"}, {"default", 0}}, + json{{"name", "kinds"}, {"type", "array"}, {"default", nullptr}, {"description", "face kinds to list: planar, cylindrical, conical, spherical, toroidal, bezier, bspline, revolution, extrusion, offset, other"}}, + json{{"name", "edge_kinds"}, {"type", "array"}, {"default", nullptr}, {"description", "edge kinds to list: line, circle, ellipse, bspline, bezier, other"}}, + json{{"name", "direction"}, {"type", "array"}, {"default", nullptr}, {"description", "[x, y, z]: planar faces whose outward normal points this way, and line edges along it either way, within 1 degree"}}, + json{{"name", "at_extreme"}, {"type", "string"}, {"enum", json::array({"+x", "-x", "+y", "-y", "+z", "-z"})}, {"default", nullptr}, {"description", "faces whose centroid lies on that side of the body's bounding box, e.g. +z for the top face"}}, + json{{"name", "convex"}, {"type", "boolean"}, {"default", nullptr}, {"description", "edges where two faces meet in an outside (true) or inside (false) corner; implies adjacency"}}, + json{{"name", "adjacency"}, {"type", "boolean"}, {"default", false}, {"description", "faces list their edges; edges list their faces (one for a seam) and say convex true or false, or tangent where the faces meet smoothly"}}, + json{{"name", "limit"}, {"type", "integer"}, {"default", nullptr}, {"min", 1}, {"description", "page size of both lists; omit for all"}}, + json{{"name", "offset"}, {"type", "integer"}, {"default", 0}}, })}}, - json{{"name", "measure"}, {"summary", "Distance (and angle, when both have direction) between two refs {face|edge|point} on a body."}, + json{{"name", "measure"}, {"summary", "Two refs, on one body or two: distance between their representative points (a face's centroid, an edge's middle, an axis's middle), min_distance with closest_a and closest_b, angle_deg when both have a direction, parallel_gap across two parallel planar faces."}, {"params", json::array({ - json{{"name", "body"}, {"type", "integer"}, {"default", 0}}, - json{{"name", "a"}, {"type", "object"}}, - json{{"name", "b"}, {"type", "object"}}, + json{{"name", "body"}, {"type", "integer"}, {"default", 0}, {"description", "the body of a ref that names none"}}, + json{{"name", "a"}, {"type", "object"}, {"description", "{\"face\": f}, {\"edge\": e} or {\"point\": [x, y, z]}, with an optional \"body\"; {\"face\": f, \"axis\": true} is a cylindrical face's axis over its length"}}, + json{{"name", "b"}, {"type", "object"}, {"description", "as a"}}, })}}, json{{"name", "mass_properties"}, {"summary", "Volume / surface area / centre of mass / inertia tensor of a body."}, {"params", json::array({ @@ -386,19 +516,206 @@ json describe_tools() })}}, json{{"name", "import_step"}, {"summary", "Import a STEP file as native B-rep bodies (the reference part to measure)."}, {"params", json::array({ - json{{"name", "path"}, {"type", "string"}}, + json{{"name", "path"}, {"type", "string"}, {"description", "absolute path"}}, })}}, json{{"name", "import_mesh"}, {"summary", "Convert a triangle mesh (STL/OBJ) into an editable B-rep body. Reports whether the result is a real solid or an open shell, and why."}, {"params", json::array({ - json{{"name", "path"}, {"type", "string"}}, + json{{"name", "path"}, {"type", "string"}, {"description", "absolute path"}}, json{{"name", "tolerance"}, {"type", "number"}, {"default", 0.01}}, json{{"name", "merge_angle_deg"}, {"type", "number"}, {"default", 5.0}}, })}}, + json{{"name", "commit"}, {"summary", "Commit to Plate: send the visible bodies to Prepare at their Move-gizmo positions, as one Prepare undo step, and show Prepare. A lone body is sent even when hidden. A body named in the Bodies list or with body_set names its object or part. Reply: objects (list_objects index after replace, name, volumes), bodies_sent, bodies_hidden, replaced."}, + {"params", json::array({ + json{{"name", "mode"}, {"type", "string"}, {"enum", json::array({"assembly", "bodies"})}, {"default", ""}, {"description", "assembly: one object with a part per body; bodies: an object per body. Default: the Commit button's mode, which this leaves as it is."}}, + json{{"name", "replace"}, {"type", "array"}, {"default", json::array()}, {"description", "list_objects indices to delete in the same undo step, such as an earlier commit. Their settings, modifiers and paint go with them."}}, + })}}, + json{{"name", "new_design"}, {"summary", "New Design: erase every feature, body and variable and the Design undo history. Committed objects stay on the plate. Reply: cleared {features, bodies, variables}."}, + {"params", json::array({ + json{{"name", "discard_changes"}, {"type", "boolean"}, {"default", false}, {"description", "needed when the design is not empty"}}, + })}}, + json{{"name", "export_step"}, {"summary", "Export STEP: write every body to a file as native B-rep, at its Move-gizmo position. Reply: path, bytes, bodies, moved_bodies."}, + {"params", json::array({ + json{{"name", "path"}, {"type", "string"}, {"description", "absolute path; its directory must exist"}}, + json{{"name", "overwrite"}, {"type", "boolean"}, {"default", false}, {"description", "replace an existing file"}}, + })}}, + json{{"name", "undo"}, {"summary", "Edit > Undo in the Design tab: take back the last change to the Design history (a feature added, edited, deleted, moved, shown or hidden, or renamed; a variable), or in a sketch session the last drawn shape. run_action undo undoes Prepare's history instead. Reply: scope (design or sketch), undo_depth, redo_depth, features, bodies; entities in a sketch."}, + {"params", json::array()}}, + json{{"name", "redo"}, {"summary", "Edit > Redo in the Design tab: put back what undo took back, until the next change. Reply as undo's."}, + {"params", json::array()}}, + json{{"name", "feature_delete"}, {"summary", "Delete a feature as its tree row's Delete does; deleting a sketch also deletes the features built on it. One undo step. Later indices shift. Reply: removed (how many features went), features, bodies."}, + {"params", json::array({ + json{{"name", "feature"}, {"type", "integer"}, {"description", "feature index (describe_scene)"}}, + })}}, + json{{"name", "feature_move"}, {"summary", "Move a feature one place up or down the history, as Move up / Move down do. A feature cannot come before one it uses. One undo step. Reply: feature (its new index), from."}, + {"params", json::array({ + json{{"name", "feature"}, {"type", "integer"}, {"description", "feature index (describe_scene)"}}, + json{{"name", "delta"}, {"type", "integer"}, {"enum", json::array({-1, 1})}, {"description", "-1 up, 1 down"}}, + })}}, + json{{"name", "feature_set_enabled"}, {"summary", "Show or hide (suppress) a feature as its row's eye does; a hidden feature is left out of the rebuild and bodies may renumber. One undo step, none when it already was. Reply: enabled, changed, bodies."}, + {"params", json::array({ + json{{"name", "feature"}, {"type", "integer"}, {"description", "feature index (describe_scene)"}}, + json{{"name", "enabled"}, {"type", "boolean"}}, + })}}, + json{{"name", "feature_rename"}, {"summary", "Rename a feature as F2 on its row does. Its own undo step. Reply: name, changed."}, + {"params", json::array({ + json{{"name", "feature"}, {"type", "integer"}, {"description", "feature index (describe_scene)"}}, + json{{"name", "name"}, {"type", "string"}, {"description", "trimmed; not empty"}}, + })}}, + json{{"name", "body_set"}, {"summary", "Rename, colour or show/hide a body, as its Bodies row and the Color button do; give one or more. Not in the undo history. The name and colour are saved with the project and the name names its committed object; visibility is view state, and commit leaves hidden bodies out. Reply: name, color, visible."}, + {"params", json::array({ + json{{"name", "body"}, {"type", "integer"}, {"description", "body index (describe_scene)"}}, + json{{"name", "name"}, {"type", "string"}, {"default", nullptr}, {"description", "trimmed; not empty"}}, + json{{"name", "color"}, {"type", "string"}, {"default", nullptr}, {"description", "\"#RRGGBB\""}}, + json{{"name", "visible"}, {"type", "boolean"}, {"default", nullptr}}, + })}}, + json{{"name", "body_delete"}, {"summary", "Delete a body as its row's Delete does: the feature that made it goes, which can take other features and bodies with it. One undo step. Reply: deleted_feature {index, type, name}, removed, features, bodies."}, + {"params", json::array({ + json{{"name", "body"}, {"type", "integer"}, {"description", "body index (describe_scene)"}}, + })}}, json{{"name", "validate_against"}, {"summary", "Volume + bbox/centroid + surface deviation (max/mean/rms mm) of a body vs a reference {step:path|body:id} (the RE acceptance metric)."}, {"params", json::array({ json{{"name", "body"}, {"type", "integer"}, {"default", 0}}, json{{"name", "reference"}, {"type", "object"}}, })}}, + json{{"name", "sketch_begin"}, {"summary", "Open a sketch session on a plane, as picking a plane or face for Sketch does. Sketch points are [x, y] in that plane's frame (mm), from its origin: modeling_origin for a base plane. Reply: frame."}, + {"params", json::array({ + plane_param("XY", false), + })}}, + json{{"name", "sketch_commit"}, {"summary", "Commit the open sketch as a Sketch feature, as the sketch's Confirm does, and leave sketch mode. An empty sketch is refused and stays open. Reply: sketch_index, name, features (the new count) and its loops (closed_loops with the index extrude's loop takes, open_ends, defects, buildable)."}, + {"params", json::array()}}, + json{{"name", "sketch_cancel"}, {"summary", "Discard the open sketch and leave sketch mode."}, + {"params", json::array()}}, + json{{"name", "sketch_add"}, {"summary", "Add entities or shapes to the open sketch: `entities` (a list), or one item's fields beside `type`, or `rect`. Entities: line {p0, p1}, circle {center, radius}, arc {center, radius, start_angle, end_angle}, point {p}. Shapes, built as their drawing tools build them: polygon {center, sides, radius (to a vertex) or across_flats, angle (of that vertex, or of the first edge's midpoint)}, slot {c0, c1, width}, ellipse {center, radius (semi-major), rminor, rotation}, ellipse_arc {the ellipse's fields, start_angle, end_angle: parametric, counter-clockwise}, spline {ctrl: 2 or more poles}. Points are [x, y] in the sketch plane (mm); angles are radians, or degrees as start_angle_deg and the like. A polygon is lines; its side count is not kept once committed. Reply: first_index, added, shapes [{first, count}] per item, entities, dof."}, + {"params", json::array({ + json{{"name", "entities"}, {"type", "array"}, {"default", json::array()}, {"description", "entity or shape objects, each with a type"}}, + json{{"name", "type"}, {"type", "string"}, {"enum", json::array({"line", "arc", "circle", "point", "polygon", "slot", "ellipse", "ellipse_arc", "spline"})}, {"default", ""}, {"description", "one item, its fields beside it"}}, + json{{"name", "rect"}, {"type", "array"}, {"default", json::array()}, {"description", "[x0, y0, x1, y1]: a closed rectangle of four lines"}}, + json{{"name", "start_angle"}, {"type", "number"}, {"unit", "rad"}, {"default", 0}, {"description", "arc start, counter-clockwise from the plane's x axis"}}, + json{{"name", "end_angle"}, {"type", "number"}, {"unit", "rad"}, {"default", 0}}, + json{{"name", "construction"}, {"type", "boolean"}, {"default", false}}, + })}}, + json{{"name", "sketch_select"}, {"summary", "Select sketch entities by index; an empty list clears the selection. Reply: selected."}, + {"params", json::array({ + json{{"name", "entities"}, {"type", "array"}, {"default", json::array()}, {"description", "entity indices"}}, + })}}, + json{{"name", "sketch_delete"}, {"summary", "Delete sketch entities. Reply: removed, entities."}, + {"params", json::array({ + json{{"name", "entities"}, {"type", "array"}, {"default", json::array()}, {"description", "entity indices; omit for the selection"}}, + })}}, + json{{"name", "sketch_construction"}, {"summary", "Toggle construction on sketch entities. Reply: changed."}, + {"params", json::array({ + json{{"name", "entities"}, {"type", "array"}, {"default", json::array()}, {"description", "entity indices; omit for the selection"}}, + })}}, + json{{"name", "sketch_offset"}, {"summary", "Add an offset copy of sketch lines, arcs and circles. Reply: first_index, added, dof."}, + {"params", json::array({ + json{{"name", "distance"}, {"type", "number"}, {"unit", "mm"}, {"description", "signed offset"}}, + json{{"name", "entities"}, {"type", "array"}, {"default", json::array()}, {"description", "entity indices; omit for the selection, else every entity"}}, + })}}, + json{{"name", "sketch_mirror"}, {"summary", "Add a mirrored copy of sketch entities about the line through axis_a and axis_b. Reply: first_index, added, dof."}, + {"params", json::array({ + json{{"name", "axis_a"}, {"type", "array"}, {"default", json::array({0, 0})}, {"description", "[x, y] in the sketch plane, mm"}}, + json{{"name", "axis_b"}, {"type", "array"}, {"default", json::array({0, 1})}, {"description", "[x, y] in the sketch plane, mm"}}, + json{{"name", "entities"}, {"type", "array"}, {"default", json::array()}, {"description", "entity indices; omit for the selection, else every entity"}}, + })}}, + json{{"name", "sketch_describe"}, {"summary", "The open sketch, or a committed one: entities, constraint count and its loops (closed_loops {index, entities, holes, area}, open_ends, defects, buildable). The open sketch adds dof, the armed tool and the selection; a committed one adds its name and plane."}, + {"params", json::array({ + json{{"name", "sketch"}, {"type", "integer"}, {"default", nullptr}, {"description", "a committed Sketch feature's index; omit for the open sketch"}}, + })}}, + json{{"name", "sketch_validate"}, {"summary", "The open sketch's loops (closed_loops, open_ends, defects, buildable) and dof."}, + {"params", json::array({ + json{{"name", "tolerance"}, {"type", "number"}, {"unit", "mm"}, {"default", 0.001}, {"description", "reported back"}}, + })}}, + json{{"name", "sketch_heal"}, {"summary", "Weld sketch endpoints that nearly meet and constrain them coincident, so loops are closed by construction. Reply: welded and the loops."}, + {"params", json::array({ + json{{"name", "tolerance"}, {"type", "number"}, {"unit", "mm"}, {"default", 0.001}}, + json{{"name", "ignore_construction"}, {"type", "boolean"}, {"default", true}}, + })}}, + json{{"name", "sketch_set_value"}, {"summary", "Set the dimension of the selected sketch entities, as the value field does: a line's length, a circle's diameter, an arc's radius, or the angle or distance between two. Select them with sketch_select first. Reply: kind, before, value, dof and the loops."}, + {"params", json::array({ + json{{"name", "value"}, {"type", "number"}, {"description", "mm, or degrees for an angle"}}, + })}}, + json{{"name", "sketch_fillet"}, {"summary", "Round the corner of two lines of the open sketch, as the Fillet tool does: both lines are cut back and joined by an arc of `radius`, bound coincident and tangent to them; constraints the sharp corner held are released. Reply: entity (the arc), lines, released_constraints, entities, constraints, dof, solve_ok."}, + {"params", json::array({ + json{{"name", "entities"}, {"type", "array"}, {"default", json::array()}, {"description", "the two line indices; omit for the selection"}}, + json{{"name", "radius"}, {"type", "number"}, {"unit", "mm"}}, + })}}, + json{{"name", "sketch_chamfer"}, {"summary", "Bevel the corner of two lines of the open sketch, as the Chamfer tool does: both lines are cut back by `distance` from the corner and joined by a line bound coincident to them. Reply: entity (the new line), lines, released_constraints, entities, constraints, dof, solve_ok."}, + {"params", json::array({ + json{{"name", "entities"}, {"type", "array"}, {"default", json::array()}, {"description", "the two line indices; omit for the selection"}}, + json{{"name", "distance"}, {"type", "number"}, {"unit", "mm"}, {"description", "setback along each line"}}, + })}}, + json{{"name", "sketch_trim"}, {"summary", "Trim the open sketch's entity nearest `at`, as a Trim click there does: a line or an arc is cut back from its end nearer `at` to the first crossing with another entity beyond `at`; a circle loses the part between the crossings either side of `at` and becomes an arc. With extend, as an Extend click: the line's or arc's end nearer `at` runs out to the next entity. The entity's constraints are released. Reply: entity, geometry (its new fields), released_constraints, entities, dof."}, + {"params", json::array({ + json{{"name", "at"}, {"type", "array"}, {"description", "[x, y] in the sketch plane, mm: a point on the part to cut, or near the end to extend"}}, + json{{"name", "extend"}, {"type", "boolean"}, {"default", false}}, + json{{"name", "tolerance"}, {"type", "number"}, {"unit", "mm"}, {"default", 0.05}, {"description", "how far from `at` the entity may be"}}, + })}}, + json{{"name", "sketch_transform"}, {"summary", "Move, rotate, scale or array entities of the open sketch, as the transform tools' Confirm does. move {dx, dy}, rotate {angle, pivot} and scale {scale, pivot} change the entities and release the constraints that no longer hold. array {dx, dy, count} adds copies stepped by dx, dy; polar_array {pivot, angle, count} adds copies every angle/count about pivot (angle is the whole sweep, default 360 degrees). count includes the original, and each copy is bound to its source (equal length and parallel, or its radius). pivot defaults to the entities' centroid. Angles are radians, or degrees as angle_deg. Reply: moved and released_constraints, or first_index, added and bound; pivot; entities, dof."}, + {"params", json::array({ + json{{"name", "op"}, {"type", "string"}, {"enum", json::array({"move", "rotate", "scale", "array", "polar_array"})}}, + json{{"name", "entities"}, {"type", "array"}, {"default", json::array()}, {"description", "entity indices; omit for the selection"}}, + json{{"name", "dx"}, {"type", "number"}, {"unit", "mm"}, {"default", 0}}, + json{{"name", "dy"}, {"type", "number"}, {"unit", "mm"}, {"default", 0}}, + json{{"name", "angle"}, {"type", "number"}, {"unit", "rad"}, {"default", nullptr}, {"description", "or angle_deg"}}, + json{{"name", "scale"}, {"type", "number"}, {"default", nullptr}}, + json{{"name", "count"}, {"type", "integer"}, {"default", nullptr}, {"min", 2}, {"max", 1000}}, + json{{"name", "pivot"}, {"type", "array"}, {"default", nullptr}, {"description", "[x, y] in the sketch plane, mm"}}, + })}}, + json{{"name", "sketch_constrain"}, {"summary", "Add a constraint to the open sketch, as a CONSTRAIN bar button does (sketch_set_value is the value field, V). With `entities`, else the selection, the button's own rules choose the points, and a value it would ask for is `value` or the current one. With `refs` the references are taken as written, in sketch_constraints' form: {entity, role} for a point (role p0, p1 or center; entity also \"origin\") and {entity} for a whole entity (also \"x_axis\", \"y_axis\"). distance, lock_x, lock_y, point_on_line and point_on_object have no button and take refs. A constraint the sketch cannot solve with is rolled back and the call fails. Reply: added (indices), items, constraints, dof, solve_ok."}, + {"params", json::array({ + json{{"name", "type"}, {"type", "string"}, {"enum", json::array({"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", "equal"})}, {"description", "\"equal\" is the Equal button: equal length, or equal radius for two curves"}}, + json{{"name", "entities"}, {"type", "array"}, {"default", json::array()}, {"description", "1 to 3 entity indices; omit for the selection"}}, + json{{"name", "refs"}, {"type", "array"}, {"default", json::array()}, {"description", "[{entity, role?}], instead of entities"}}, + json{{"name", "value"}, {"type", "number"}, {"default", nullptr}, {"description", "mm, or degrees for an angle"}}, + })}}, + json{{"name", "sketch_constraints"}, {"summary", "The constraints of the open sketch, or of a committed one: index, type, refs ({entity, role} for a point, {entity} for a whole entity) and value (mm, or degrees for an angle). Reply: scope (live or committed), items, and dof and solve_ok for the open sketch."}, + {"params", json::array({ + json{{"name", "sketch"}, {"type", "integer"}, {"default", nullptr}, {"description", "a committed Sketch feature's index; omit for the open sketch"}}, + })}}, + json{{"name", "sketch_unconstrain"}, {"summary", "Delete a constraint of the open sketch, as its row's delete button does; the constraints after it move down one index. Reply: removed, constraints, dof, solve_ok."}, + {"params", json::array({ + json{{"name", "index"}, {"type", "integer"}, {"description", "sketch_constraints' items[].index"}}, + })}}, + json{{"name", "list_verbs"}, {"summary", "The Design tab's right-click verbs: id, name, key, whether each applies to the current selection, and whether it opens a dialog."}, + {"params", json::array({ + json{{"name", "applicable_only"}, {"type", "boolean"}, {"default", false}}, + json{{"name", "sketch_mode"}, {"type", "boolean"}, {"default", nullptr}, {"description", "when given, only sketch-mode (true) or feature-mode (false) verbs"}}, + })}}, + json{{"name", "run_verb"}, {"summary", "Fire a verb from list_verbs as its menu row or key does. It runs on the next event-loop turn, so the reply says only that it was dispatched; a verb that opens a card or dialog leaves it open."}, + {"params", json::array({ + json{{"name", "verb"}, {"type", "string"}, {"description", "verb id"}}, + })}}, + json{{"name", "set_variable"}, {"summary", "Set a design variable to an expression, or remove it with an empty expr; feature fields bound with set_feature_expr follow it."}, + {"params", json::array({ + json{{"name", "name"}, {"type", "string"}}, + json{{"name", "expr"}, {"type", "string"}, {"description", "e.g. \"20\" or \"width / 2 + 3\"; \"\" removes the variable"}}, + })}}, + json{{"name", "set_feature_expr"}, {"summary", "Bind a feature's numeric field to an expression over the design variables, or remove the binding with an empty expr (the field keeps its value)."}, + {"params", json::array({ + json{{"name", "feature"}, {"type", "integer"}, {"description", "feature index (describe_scene)"}}, + json{{"name", "field"}, {"type", "string"}, {"description", "a numeric field of describe_feature's params, e.g. width, distance, hole_diameter, thread_diameter"}}, + json{{"name", "expr"}, {"type", "string"}, {"description", "\"\" removes the binding"}}, + })}}, + json{{"name", "surface_loft"}, {"summary", "Skin two or more profile sketches with no end caps -> an open sheet body."}, + {"params", json::array({ + json{{"name", "profiles"}, {"type", "array"}, {"description", "sketch feature indices, in order"}}, + json{{"name", "ruled"}, {"type", "boolean"}, {"default", false}}, + })}}, + json{{"name", "surface_fill"}, {"summary", "Fill a sketch's closed boundary with one smooth face -> a sheet body."}, + {"params", json::array({ + json{{"name", "sketch"}, {"type", "integer"}, {"description", "sketch feature index"}}, + })}}, + json{{"name", "surface_offset"}, {"summary", "Offset a sheet body by a signed distance -> another sheet body."}, + {"params", json::array({ + json{{"name", "body"}, {"type", "integer"}, {"default", -1}, {"description", "sheet body; omit for the last body"}}, + json{{"name", "offset"}, {"type", "number"}, {"unit", "mm"}, {"default", 1}}, + })}}, + json{{"name", "thicken_surface"}, {"summary", "Thicken a whole sheet body into a solid."}, + {"params", json::array({ + json{{"name", "body"}, {"type", "integer"}, {"default", -1}, {"description", "sheet body; omit for the last body"}}, + json{{"name", "thickness"}, {"type", "number"}, {"unit", "mm"}, {"default", 2}, {"min", 0.01}}, + json{{"name", "flip"}, {"type", "boolean"}, {"default", false}}, + })}}, })}, }; } @@ -410,11 +727,26 @@ json describe_scene(DesignPanel* panel) json features = json::array(); for (size_t i = 0; i < doc.features.size(); ++i) { const CadFeature& f = doc.features[i]; - features.push_back(json{ - {"index", int(i)}, {"type", feature_type_name(f.type)}, - {"name", f.name}, {"enabled", f.enabled}}); + json jf{{"index", int(i)}, {"type", feature_type_name(f.type)}, {"name", f.name}, {"enabled", f.enabled}}; + // The fields an expression drives: set_feature refuses them, describe_feature 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 @@ -422,7 +754,13 @@ json describe_scene(DesignPanel* panel) 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}}; + {"has_color", doc.bodies[i].has_color}, + {"source_feature", doc.bodies[i].source_feature}, + {"visible", panel->mcp_body_shown(int(i))}, + // The Move gizmo's placement, which bbox (the recipe's body) does not include. + {"moved", panel->mcp_body_moved(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(); @@ -434,27 +772,120 @@ json describe_scene(DesignPanel* panel) bodies.push_back(std::move(b)); } - return json{ + 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 note on the dispatcher. {"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_add's entities make. + {"auto_close_loops", doc.auto_close_loops}, }; + if (!var_error.empty()) out["variables_error"] = var_error; + 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["mate_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. -SketchPlane plane_from(const json& params, const CadDocument& doc) + +// The kinds query_topology 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) { - std::string n = params.value("plane", std::string("XY")); - SketchPlane pl = n == "XZ" ? SketchPlane::XZ() : n == "YZ" ? SketchPlane::YZ() : SketchPlane::XY(); - pl.origin = doc.modeling_origin; // land on the bed centre, like the GUI - return pl; + 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 script. +// `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; + 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 Standard_Failure& ex) { // derives from std::exception, so it comes first + why = std::string("OCCT: ") + (*ex.what() ? ex.what() : "failure"); + } catch (const std::exception& ex) { + why = *ex.what() ? ex.what() : "the feature could not be added"; + } + 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 CadCallError(-32000, why); + } + panel->mcp_after_change(); + return json{{"ok", true}, {index_key, idx}, {"bodies", int(doc.bodies.size())}}; } BooleanMode bool_from(const std::string& s) { @@ -465,19 +896,20 @@ BooleanMode bool_from(const std::string& s) } // 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")) return false; + 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; - return out.points.size() >= 3; + 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(DesignPanel* panel, const json& params) +const TopoDS_Shape& body_shape(const CadDocument& doc, const json& params) { - CadDocument& doc = panel->mcp_doc(); 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()) + ")"); @@ -486,91 +918,13 @@ const TopoDS_Shape& body_shape(DesignPanel* panel, const json& params) return doc.bodies[idx].shape; } -json query_topology(DesignPanel* panel, const json& params) -{ - const TopoDS_Shape& shape = body_shape(panel, params); - // 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 all_faces = GeometryEngine::faces_of(shape); - const std::vector all_edges = GeometryEngine::edges_of(shape); +json query_topology(DesignPanel* panel, const json& params) { return cad_query_topology(panel->mcp_doc(), params); } - json faces = json::array(); - const int nf = int(all_faces.size()); - for (int i = 0; i < nf; ++i) { - const TopoDS_Face& f = all_faces[i]; - if (f.IsNull()) continue; - json jf{{"id", i}, {"centroid", vec3(GeometryEngine::face_centroid_world(f))}, - {"normal", vec3(GeometryEngine::face_normal_world(f))}, {"kind", "planar"}}; - GeometryEngine::CylinderFace cyl = GeometryEngine::cylinder_of_face(f); - if (cyl.ok) { jf["kind"] = "cylindrical"; jf["radius"] = cyl.radius; - jf["axis"] = vec3(cyl.axis); jf["internal"] = cyl.internal; } - faces.push_back(std::move(jf)); - } - json edges = json::array(); - const int ne = int(all_edges.size()); - for (int i = 0; i < ne; ++i) { - const TopoDS_Edge& e = all_edges[i]; - if (e.IsNull()) continue; - std::vector pts = GeometryEngine::sample_edge_world(e); - if (pts.size() < 2) continue; - double len = 0; for (size_t k = 1; k < pts.size(); ++k) len += (pts[k] - pts[k-1]).norm(); - json je{{"id", i}, {"length", len}, {"p0", vec3(pts.front())}, {"p1", vec3(pts.back())}, - {"kind", "line"}}; - GeometryEngine::CylinderFace circ = GeometryEngine::circle_of_edge(e); - if (circ.ok) { je["kind"] = "circle"; je["radius"] = circ.radius; je["center"] = vec3(circ.base); } - edges.push_back(std::move(je)); - } - return json{{"body", params.value("body", 0)}, {"face_count", nf}, {"edge_count", ne}, - {"faces", std::move(faces)}, {"edges", std::move(edges)}, - // 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", panel->mcp_doc().topo_generation}}; -} - -// One measurement reference -> a representative point and (optionally) a direction. -// ref = {"face": id} | {"edge": id} | {"point": [x,y,z]} on the given body. -bool resolve_ref(const TopoDS_Shape& shape, const json& ref, Vec3d& point, Vec3d& dir, bool& has_dir) -{ - has_dir = false; - if (ref.contains("point")) { auto p = ref["point"]; point = Vec3d(p[0], p[1], p[2]); return true; } - if (ref.contains("face")) { - TopoDS_Face f = GeometryEngine::face_by_index(shape, ref["face"].get()); - if (f.IsNull()) return false; - point = GeometryEngine::face_centroid_world(f); - dir = GeometryEngine::face_normal_world(f); has_dir = true; return true; - } - if (ref.contains("edge")) { - TopoDS_Edge e = GeometryEngine::edge_by_index(shape, ref["edge"].get()); - if (e.IsNull()) return false; - std::vector pts = GeometryEngine::sample_edge_world(e); - if (pts.empty()) return false; - point = pts[pts.size() / 2]; // midpoint sample - if (pts.size() >= 2) { dir = (pts.back() - pts.front()).normalized(); has_dir = true; } - return true; - } - return false; -} - -json measure(DesignPanel* panel, const json& params) -{ - const TopoDS_Shape& shape = body_shape(panel, params); - Vec3d pa, pb, da, db; bool hda = false, hdb = false; - if (!params.contains("a") || !params.contains("b")) - throw std::runtime_error("measure needs refs 'a' and 'b' ({face|edge|point})"); - if (!resolve_ref(shape, params["a"], pa, da, hda) || !resolve_ref(shape, params["b"], pb, db, hdb)) - throw std::runtime_error("could not resolve a measurement reference"); - json r{{"distance", (pa - pb).norm()}, {"point_a", vec3(pa)}, {"point_b", vec3(pb)}}; - if (hda && hdb) { - 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; - } - return r; -} +json measure(DesignPanel* panel, const json& params) { return cad_measure(panel->mcp_doc(), params); } json mass_properties(DesignPanel* panel, const json& params) { - const TopoDS_Shape& shape = body_shape(panel, params); + const TopoDS_Shape& shape = body_shape(panel->mcp_doc(), params); auto mp = GeometryEngine::mass_properties(shape); if (!mp.valid) throw std::runtime_error("mass properties could not be computed (null/empty shape)"); // A sheet body has no volume and no inertia. Report the area and say so, rather than @@ -631,7 +985,7 @@ chain_segments(std::vector> segs, double tol) // sections-as-evidence: cross-section of a body by a named base plane at an offset. json slice_body(DesignPanel* panel, const json& params) { - const TopoDS_Shape& shape = body_shape(panel, 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. @@ -664,11 +1018,22 @@ json slice_body(DesignPanel* panel, const json& params) {"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 = params["path"].get(); + 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); @@ -679,14 +1044,14 @@ json import_step(DesignPanel* panel, const json& params) for (const TopoDS_Shape& s : solids) { CadFeature f; f.type = CadFeatureType::Import; - f.name = "STEP" + std::to_string(int(doc.features.size()) + 1); + 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.undo(); doc.error = why; } - panel->mcp_after_change(); + 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}}; } @@ -698,7 +1063,7 @@ json import_step(DesignPanel* panel, const json& params) json import_mesh(DesignPanel* panel, const json& params) { if (!params.contains("path")) throw std::runtime_error("import_mesh needs 'path'"); - const std::string path = params["path"].get(); + 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); @@ -724,14 +1089,14 @@ json import_mesh(DesignPanel* panel, const json& params) const int first = int(doc.features.size()); CadFeature f; f.type = CadFeatureType::Import; - f.name = "Mesh" + std::to_string(first + 1); + 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.undo(); doc.error = why; } - panel->mcp_after_change(); + 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}, @@ -759,14 +1124,14 @@ ShapeMetrics shape_metrics(const TopoDS_Shape& s) json validate_against(DesignPanel* panel, const json& params) { - const TopoDS_Shape& cand = body_shape(panel, params); // candidate = the reconstruction + const TopoDS_Shape& cand = body_shape(panel->mcp_doc(), params); // candidate = the reconstruction if (!params.contains("reference")) throw std::runtime_error("validate_against 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(r["step"].get(), 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); @@ -799,71 +1164,6 @@ json validate_against(DesignPanel* panel, const json& params) }; } -json action_extrude(DesignPanel* panel, const json& params) -{ - const double d = params.value("distance", 10.0); - if (d <= 0) throw std::runtime_error("distance must be > 0"); - CadDocument& doc = panel->mcp_doc(); - SketchPlane pl = plane_from(params, doc); - BooleanMode mode = bool_from(params.value("boolean", std::string("new"))); - - SketchProfile prof; - 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"); - } - doc.checkpoint(); - int s = has_prof ? doc.add_sketch_profile(prof, pl, "Sketch") - : doc.add_sketch(SketchShape::Rectangle, pl, w, h, 0.0, "Sketch"); - int e = doc.add_extrude(s, d, /*symmetric*/false, mode, "Extrude"); - // End condition (Onshape parity). apply reads extrude_end directly; the kernel `symmetric` - // bool is unused, so set the field here. up_to_face id comes from query_topology on the - // target (last) body. taper_deg lofts the side wall; flip negates the direction. - const std::string end = params.value("end", std::string("blind")); - CadFeature& fe = doc.features[e]; - fe.flip = params.value("flip", false); - fe.taper_deg = params.value("taper", 0.0); - if (end == "symmetric") fe.extrude_end = ExtrudeEnd::Symmetric; - else if (end == "two_sided") { fe.extrude_end = ExtrudeEnd::TwoSided; fe.distance2 = params.value("distance2", d); } - else if (end == "through_all") fe.extrude_end = ExtrudeEnd::ThroughAll; - else if (end == "up_to_face") { fe.extrude_end = ExtrudeEnd::UpToFace; fe.up_to_face = params.value("up_to_face", -1); } - else fe.extrude_end = ExtrudeEnd::Blind; - bool ok = doc.recompute(); - if (!ok) { const std::string why = doc.error; doc.undo(); doc.error = why; } - panel->mcp_after_change(); - return json{{"ok", ok}, {"sketch_index", s}, {"extrude_index", e}, {"end", end}, - {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; -} - -json action_revolve(DesignPanel* panel, const json& params) -{ - const double angle = params.value("angle", 360.0); - const int axis = params.value("axis", 0); // 0 = plane X, 1 = plane Y - const bool flip = params.value("flip", false); - CadDocument& doc = panel->mcp_doc(); - SketchPlane pl = plane_from(params, doc); - BooleanMode mode = bool_from(params.value("boolean", std::string("new"))); - - SketchProfile prof; - bool has_prof = profile_from(params, prof); - double w = 0, h = 0; - if (!has_prof) { // ponytail: rectangle centred on the axis may self-overlap; offset via `profile` - 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"); - } - doc.checkpoint(); - int s = has_prof ? doc.add_sketch_profile(prof, pl, "Sketch") - : doc.add_sketch(SketchShape::Rectangle, pl, w, h, 0.0, "Sketch"); - int r = doc.add_revolve(s, angle, axis, flip, mode, "Revolve"); - bool ok = doc.recompute(); - if (!ok) { const std::string why = doc.error; doc.undo(); doc.error = why; } - panel->mcp_after_change(); - return json{{"ok", ok}, {"sketch_index", s}, {"revolve_index", r}, - {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; -} - // 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) @@ -897,11 +1197,11 @@ json action_fillet(DesignPanel* panel, const json& params) if (doc.bodies.empty()) throw std::runtime_error("no body to fillet"); int bi = target_body_arg(params, doc); doc.checkpoint(); - int f = doc.add_fillet(radius, edges, "Fillet"); + int f = doc.add_fillet(radius, edges, panel->mcp_feature_name(_L("Fillet"))); if (bi >= 0) doc.features[f].target_body = bi; // edge id resolved against THIS body's shape bool ok = doc.recompute(); - if (!ok) { const std::string why = doc.error; doc.undo(); doc.error = why; } - panel->mcp_after_change(); + if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } + panel->mcp_after_change(ok); return json{{"ok", ok}, {"fillet_index", f}, {"body", bi < 0 ? int(doc.bodies.size()) - 1 : bi}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; } @@ -915,31 +1215,39 @@ json action_chamfer(DesignPanel* panel, const json& params) if (doc.bodies.empty()) throw std::runtime_error("no body to chamfer"); int bi = target_body_arg(params, doc); doc.checkpoint(); - int c = doc.add_chamfer(dist, edges, "Chamfer"); + int c = doc.add_chamfer(dist, edges, panel->mcp_feature_name(_L("Chamfer"))); if (bi >= 0) doc.features[c].target_body = bi; // edge id resolved against THIS body's shape bool ok = doc.recompute(); - if (!ok) { const std::string why = doc.error; doc.undo(); doc.error = why; } - panel->mcp_after_change(); + if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } + panel->mcp_after_change(ok); return json{{"ok", ok}, {"chamfer_index", c}, {"body", bi < 0 ? int(doc.bodies.size()) - 1 : bi}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; } +// A hole method's reply: the feature, where it went (cad_hole_placement) and the frame of its plane. +json hole_reply(json r, const json& placement, const SketchPlane& pl) +{ + r.update(placement); + r["frame"] = frame_json(pl); + return r; +} + json action_hole(DesignPanel* panel, const json& params) { const double dia = params.value("diameter", 5.0); const double depth = params.value("depth", 10.0); const bool thru = params.value("through", false); - const double x = params.value("x", 0.0), y = params.value("y", 0.0); if (dia <= 0) throw std::runtime_error("diameter must be > 0"); CadDocument& doc = panel->mcp_doc(); - if (doc.bodies.empty()) throw std::runtime_error("no body to drill"); - SketchPlane pl = plane_from(params, doc); - doc.checkpoint(); - int h = doc.add_hole(dia, depth, thru, x, y, pl, "Hole"); - bool ok = doc.recompute(); - if (!ok) { const std::string why = doc.error; doc.undo(); doc.error = why; } - panel->mcp_after_change(); - return json{{"ok", ok}, {"hole_index", h}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; + SketchPlane pl; + int body = -1; + const json at = cad_hole_placement(doc, params, pl, body); + const double x = at.at("x").get(), y = at.at("y").get(); + return hole_reply(add_feature(panel, "hole_index", [&] { + const int h = doc.add_hole(dia, depth, thru, x, y, pl, panel->mcp_feature_name(_L_CONTEXT("Hole", "Design"))); + doc.features[h].target_body = body; + return h; + }), at, pl); } json action_hole_styled(DesignPanel* panel, const json& params) @@ -947,7 +1255,6 @@ json action_hole_styled(DesignPanel* panel, const json& params) const double dia = params.value("diameter", 5.0); const double depth = params.value("depth", 10.0); const bool thru = params.value("through", true); - const double x = params.value("x", 0.0), y = params.value("y", 0.0); const int style = params.value("style", 0); const double cbore_diameter = params.value("cbore_diameter", 0.0); const double cbore_depth = params.value("cbore_depth", 0.0); @@ -956,16 +1263,18 @@ json action_hole_styled(DesignPanel* panel, const json& params) const std::string standard = params.value("standard", std::string("")); if (dia <= 0) throw std::runtime_error("diameter must be > 0"); CadDocument& doc = panel->mcp_doc(); - if (doc.bodies.empty()) throw std::runtime_error("no body to drill"); - SketchPlane pl = plane_from(params, doc); - doc.checkpoint(); - int h = doc.add_hole_styled(dia, depth, thru, x, y, pl, style, - cbore_diameter, cbore_depth, - csink_diameter, csink_angle, standard, "Hole"); - bool ok = doc.recompute(); - if (!ok) { const std::string why = doc.error; doc.undo(); doc.error = why; } - panel->mcp_after_change(); - return json{{"ok", ok}, {"hole_index", h}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; + SketchPlane pl; + int body = -1; + const json at = cad_hole_placement(doc, params, pl, body); + const double x = at.at("x").get(), y = at.at("y").get(); + return hole_reply(add_feature(panel, "hole_index", [&] { + const int h = doc.add_hole_styled(dia, depth, thru, x, y, pl, style, + cbore_diameter, cbore_depth, + csink_diameter, csink_angle, standard, + panel->mcp_feature_name(_L_CONTEXT("Hole", "Design"))); + doc.features[h].target_body = body; + return h; + }), at, pl); } json action_hole_standard(DesignPanel* panel, const json& params) @@ -975,22 +1284,18 @@ json action_hole_standard(DesignPanel* panel, const json& params) const int style = params.value("style", 0); const bool thru = params.value("through", true); const double depth = params.value("depth", 10.0); - const double x = params.value("x", 0.0), y = params.value("y", 0.0); CadDocument& doc = panel->mcp_doc(); - if (doc.bodies.empty()) throw std::runtime_error("no body to drill"); - SketchPlane pl = plane_from(params, doc); - doc.checkpoint(); - try { - int h = doc.add_hole_standard(desig, style, thru, depth, x, y, pl, "Hole"); - bool ok = doc.recompute(); - if (!ok) { const std::string why = doc.error; doc.undo(); doc.error = why; } - panel->mcp_after_change(); - return json{{"ok", ok}, {"hole_index", h}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; - } catch (const std::exception& ex) { - doc.undo(); - panel->mcp_after_change(); - return json{{"ok", false}, {"error", ex.what()}}; - } + SketchPlane pl; + int body = -1; + const json at = cad_hole_placement(doc, params, pl, body); + const double x = at.at("x").get(), y = at.at("y").get(); + // add_hole_standard throws on an unknown designation; add_feature rolls that back too. + return hole_reply(add_feature(panel, "hole_index", [&] { + const int h = doc.add_hole_standard(desig, style, thru, depth, x, y, pl, + panel->mcp_feature_name(_L_CONTEXT("Hole", "Design"))); + doc.features[h].target_body = body; + return h; + }), at, pl); } json action_boolean(DesignPanel* panel, const json& params) @@ -1007,10 +1312,10 @@ json action_boolean(DesignPanel* panel, const json& params) 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, "Boolean"); + 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.undo(); doc.error = why; } - panel->mcp_after_change(); + 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}}; } @@ -1025,13 +1330,15 @@ json action_pattern(DesignPanel* panel, const json& params) CadDocument& doc = panel->mcp_doc(); if (doc.bodies.empty()) throw std::runtime_error("no body to pattern"); int bi = target_body_arg(params, doc); + const SketchPlane pl = cad_resolve_plane(params.value("plane", json("XY")), doc, false); doc.checkpoint(); - int p = doc.add_pattern(circular, count, spacing, dir, angle, bi, "Pattern"); - doc.features[p].plane = plane_from(params, doc); // axis (circular) / step dirs (linear) + int p = doc.add_pattern(circular, count, spacing, dir, angle, bi, panel->mcp_feature_name(_L_CONTEXT("Pattern", "Design"))); + doc.features[p].plane = pl; // axis (circular) / step dirs (linear) bool ok = doc.recompute(); - if (!ok) { const std::string why = doc.error; doc.undo(); doc.error = why; } - panel->mcp_after_change(); - return json{{"ok", ok}, {"pattern_index", p}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; + if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } + panel->mcp_after_change(ok); + return json{{"ok", ok}, {"pattern_index", p}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}, + {"frame", frame_json(pl)}}; } json action_pattern_on_curve(DesignPanel* panel, const json& params) @@ -1046,10 +1353,10 @@ json action_pattern_on_curve(DesignPanel* panel, const json& params) if (doc.bodies.empty()) throw std::runtime_error("no body to pattern"); int bi = target_body_arg(params, doc); doc.checkpoint(); - int p = doc.add_pattern_on_curve(count, sketch, entity, bi, "PatternOnCurve"); + int p = doc.add_pattern_on_curve(count, sketch, entity, bi, panel->mcp_feature_name(_L_CONTEXT("Pattern", "Design"))); bool ok = doc.recompute(); - if (!ok) { const std::string why = doc.error; doc.undo(); doc.error = why; } - panel->mcp_after_change(); + if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } + panel->mcp_after_change(ok); return json{{"ok", ok}, {"pattern_index", p}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; } @@ -1062,10 +1369,10 @@ json action_shell(DesignPanel* panel, const json& params) if (doc.bodies.empty()) throw std::runtime_error("no body to shell"); int bi = target_body_arg(params, doc); doc.checkpoint(); - int s = doc.add_shell(thickness, face, bi, "Shell"); + 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.undo(); doc.error = why; } - panel->mcp_after_change(); + 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}}; } @@ -1081,10 +1388,10 @@ json action_rib(DesignPanel* panel, const json& params) 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, "Rib"); + 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.undo(); doc.error = why; } - panel->mcp_after_change(); + 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}}; } @@ -1095,10 +1402,10 @@ json action_surface_extrude(DesignPanel* panel, const json& params) int sketch = params["sketch"].get(); double distance = params.value("distance", 10.0); doc.checkpoint(); - int idx = doc.add_surface_extrude(sketch, distance, "SurfaceExtrude"); + 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.undo(); doc.error = why; } - panel->mcp_after_change(); + 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}}; } @@ -1110,10 +1417,10 @@ json action_surface_revolve(DesignPanel* panel, const json& params) double angle = params.value("angle", 360.0); int axis = params.value("axis", 0); doc.checkpoint(); - int idx = doc.add_surface_revolve(sketch, angle, axis, "SurfaceRevolve"); + int idx = doc.add_surface_revolve(sketch, angle, axis, panel->mcp_feature_name(_L("Surface Revolve"))); bool ok = doc.recompute(); - if (!ok) { const std::string why = doc.error; doc.undo(); doc.error = why; } - panel->mcp_after_change(); + 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}}; } @@ -1125,10 +1432,10 @@ json action_thicken_surface(DesignPanel* panel, const json& params) double thickness = params.value("thickness", 2.0); bool flip = params.value("flip", false); doc.checkpoint(); - int idx = doc.add_thicken_surface(bi, thickness, flip, "ThickenSurface"); + int idx = doc.add_thicken_surface(bi, thickness, flip, panel->mcp_feature_name(_L("Thicken Surface"))); bool ok = doc.recompute(); - if (!ok) { const std::string why = doc.error; doc.undo(); doc.error = why; } - panel->mcp_after_change(); + 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}}; } @@ -1139,10 +1446,10 @@ json action_surface_offset(DesignPanel* panel, const json& params) int bi = target_body_arg(params, doc); double offset = params.value("offset", 1.0); doc.checkpoint(); - int idx = doc.add_surface_offset(bi, offset, "SurfaceOffset"); + 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.undo(); doc.error = why; } - panel->mcp_after_change(); + 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}}; } @@ -1155,10 +1462,10 @@ json action_surface_loft(DesignPanel* panel, const json& params) 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, "SurfaceLoft"); + 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.undo(); doc.error = why; } - panel->mcp_after_change(); + 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}}; } @@ -1168,10 +1475,10 @@ json action_surface_fill(DesignPanel* panel, const json& params) CadDocument& doc = panel->mcp_doc(); int sketch = params["sketch"].get(); doc.checkpoint(); - int idx = doc.add_surface_fill(sketch, "SurfaceFill"); + 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.undo(); doc.error = why; } - panel->mcp_after_change(); + 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}}; } @@ -1183,10 +1490,10 @@ json action_draft(DesignPanel* panel, const json& params) if (doc.bodies.empty()) throw std::runtime_error("no body to draft"); int bi = target_body_arg(params, doc); doc.checkpoint(); - int d = doc.add_draft(angle, params["face"].get(), bi, "Draft"); + 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.undo(); doc.error = why; } - panel->mcp_after_change(); + 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}}; } @@ -1221,6 +1528,33 @@ DesignSketchTool& mcp_sketch(DesignPanel* panel) 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("")); @@ -1245,6 +1579,10 @@ SketchEntity sketch_entity_from(const json& j) throw std::runtime_error(std::string(what) + " needs a 'center' (or 'p0')"); }; 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") { @@ -1257,8 +1595,8 @@ SketchEntity sketch_entity_from(const json& j) e.type = SketchEntity::Type::Arc; e.center = centre_of("arc"); e.radius = j.value("radius", 0.0); - e.start_angle = j.value("start_angle", 0.0); - e.end_angle = j.value("end_angle", 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 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)); @@ -1266,7 +1604,7 @@ SketchEntity sketch_entity_from(const json& j) e.type = SketchEntity::Type::Point; e.p0 = p("p", 0, 0); } else { - throw std::runtime_error("unknown entity type '" + t + "' (line, arc, circle, point)"); + throw std::runtime_error("unknown entity type '" + t + "' (line, arc, circle, point, polygon, slot, ellipse, ellipse_arc, spline)"); } return e; } @@ -1335,6 +1673,494 @@ json sketch_entity_to(const SketchEntity& e, int index) return j; } +// --- A feature as its card shows it: describe_feature and set_feature ------------------------ + +// Names in the cad_call vocabulary, in enum order. +const char* const kModes[] = {"new", "union", "subtract", "intersect"}; // BooleanMode +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 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); +} + +// A constraint's value as cad_call states 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 set_feature_expr binds); `ranges` the limits +// its spin controls set on the numeric ones; `refs` the structure the card keeps as it is (feature +// and body indices, face and edge ids, which expire with every rebuild); `expr` the bindings. +// describe_feature shows it and set_feature 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: only its placement edits without the Text dialog. + if (f.is_text()) { + show("text_string", f.text_string); + show("text_font", f.text_font); + show("text_height", f.text_height); + } + show("regions", int(f.imported_regions.size())); + show("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("mode", enum_name(kModes, 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("mode", enum_name(kModes, 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("mode", enum_name(kModes, 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("mode", enum_name(kModes, 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 is not on the card; hole_styled and hole_standard set it. 0 = simple. + edit("hole_style", 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: + edit("pattern_circular", f.pattern_circular); + 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("mode", enum_name(kModes, 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("mode", enum_name(kModes, 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); + show("revolve_axis", f.revolve_axis); + show("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("mate_kind", 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 == "pattern_circular") return flag(f.pattern_circular); + 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 == "hole_style") return choice(f.hole_style, 2); + if (k == "pattern_dir") return choice(f.pattern_dir, 1); + if (k == "mate_kind") return choice(f.mate_kind, 4); + 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 == "shape") { + f.shape = SketchShape(enum_index(k, v, kShapes)); + return; + } + if (k == "mode") { + // A Boolean combines two bodies, so it makes no new one; a Mirror adds its mirrored body + // or fuses it back. + const BooleanMode m = BooleanMode(enum_index(k, v, kModes)); + if (f.type == CadFeatureType::Boolean && m == BooleanMode::New) + throw std::runtime_error("a Boolean's mode is union, subtract or intersect"); + if (f.type == CadFeatureType::Mirror && m != BooleanMode::New && m != BooleanMode::Add) + throw std::runtime_error("a Mirror's mode is new or union"); + f.mode = m; + return; + } + if (k == "extrude_end") { + // The face or vertex an end goes up to is picked on the canvas; set_feature 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: an index into describe_scene's features. +int feature_arg(const json& params, const CadDocument& doc) +{ + const json v = params.is_object() ? params.value("feature", json()) : json(); + if (!v.is_number_integer()) throw std::runtime_error("feature must be a feature index (describe_scene's features[].index)"); + check_feature_index(v.get(), doc); + return v.get(); +} + +json action_describe_feature(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): one undo step, then replace_feature(), +// which rebuilds and puts the old features back if the rebuild fails. +json action_set_feature(DesignPanel* panel, const json& params) +{ + CadDocument& doc = panel->mcp_doc(); + const int fi = feature_arg(params, doc); + if (!params.contains("fields")) throw std::runtime_error("set_feature needs 'fields', as {\"distance\": 15}"); + CadFeature edited = doc.features[fi]; + cad_apply_feature_fields(edited, params["fields"]); + const json before = feature_card(doc.features[fi])["params"]; + 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 CadCallError(-32000, why); + } + panel->mcp_after_change(); + const json after = feature_card(doc.features[fi])["params"]; + json changed = 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}); + } + return json{{"ok", true}, {"feature", fi}, {"changed", std::move(changed)}, {"bodies", int(doc.bodies.size())}, + {"generation", doc.topo_generation}, {"error", doc.error}}; +} + // Which entities a verb acts on: an explicit "entities" array, else the current selection, // else — only where the verb says so — everything. Same precedence the menu uses: what you // pointed at wins, and the menu never silently acts on the whole sketch. @@ -1351,34 +2177,71 @@ std::vector sketch_targets(const json& params, DesignSketchTool& t, bool al return out; } +// 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_begin(DesignPanel* panel, const json& params) { DesignCanvas* vp = panel->mcp_viewport(); if (vp == nullptr) throw std::runtime_error("no viewport"); if (vp->is_sketching()) throw std::runtime_error("a sketch is already open"); - const std::string pl = params.value("plane", std::string("XY")); - SketchPlane plane = SketchPlane::XY(); - if (pl == "XZ") plane = SketchPlane::XZ(); - else if (pl == "YZ") plane = SketchPlane::YZ(); - else if (pl != "XY") throw std::runtime_error("plane must be XY, XZ or YZ"); - vp->begin_sketch(plane, DesignSketchTool::Mode::Select); - // The panel has to enter sketch mode too, or the app is half in it: the tool sketches, the - // offer menu offers sketch verbs, and every sketch KEY is dead because key dispatch tests - // m_ui_mode while the menu tests the viewport. Driving the socket must leave the GUI in the - // state a user would be in, not a state only the socket can produce. - panel->mcp_set_sketch_mode(true); - return json{{"ok", true}, {"plane", pl}}; + 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. An empty sketch is refused before anything changes, where the GUI's commit +// drops it with a status line: a failed call is left out of an exported script, so the session +// must still be open when the script's next sketch call replays. json action_sketch_commit(DesignPanel* panel, const json& params) { (void)params; - DesignCanvas* vp = panel->mcp_viewport(); - if (vp == nullptr || !vp->is_sketching()) throw std::runtime_error("no sketch is open"); - vp->finish_sketch(); + DesignSketchTool& t = mcp_sketch(panel); + if (t.entities().empty()) throw std::runtime_error("the sketch is empty; add entities or call sketch_cancel"); + CadDocument& doc = panel->mcp_doc(); + const size_t before = doc.features.size(); + DesignCanvas* vp = panel->mcp_viewport(); + vp->sketch_confirm_pending(); // a ready edit-op or chain is kept, as the ✓ keeps it + vp->finish_sketch(); // the commit handler checkpoints, names, solves and rebuilds panel->mcp_set_sketch_mode(false); panel->mcp_after_change(); - return json{{"ok", true}, {"features", int(panel->mcp_doc().features.size())}}; + if (doc.features.size() <= before) throw std::runtime_error("the sketch was not committed"); + // Read back from the committed feature: solving its dimensions can move geometry, and extrude + // takes `loop` against these entities. + const CadFeature& f = doc.features[before]; + json out{{"ok", true}, {"sketch_index", int(before)}, {"name", f.name}, {"features", int(doc.features.size())}}; + out.update(sketch_report(t.loop_report(f.entities))); + return out; } json action_sketch_cancel(DesignPanel* panel, const json& params) @@ -1391,37 +2254,6 @@ json action_sketch_cancel(DesignPanel* panel, const json& params) return json{{"ok", true}}; } -json action_sketch_add(DesignPanel* panel, const json& params) -{ - DesignSketchTool& t = mcp_sketch(panel); - std::vector ents; - if (params.contains("entities")) { - for (const auto& j : params.at("entities")) ents.push_back(sketch_entity_from(j)); - } else if (params.contains("type")) { - ents.push_back(sketch_entity_from(params)); // single-entity shorthand - } else if (params.contains("rect")) { - // Corner rectangle as four shared-endpoint lines, so it arrives as ONE closed loop - // rather than four segments that happen to touch. - const json& r = params.at("rect"); - if (!r.is_array() || r.size() < 4) throw std::runtime_error("rect must be [x0, y0, x1, y1]"); - const double x0 = r[0].get(), y0 = r[1].get(); - const double x1 = r[2].get(), y1 = r[3].get(); - const bool c = params.value("construction", false); - auto seg = [&](Vec2d a, Vec2d b) { SketchEntity e; e.type = SketchEntity::Type::Line; - e.p0 = a; e.p1 = b; e.construction = c; return e; }; - ents.push_back(seg({x0, y0}, {x1, y0})); - ents.push_back(seg({x1, y0}, {x1, y1})); - ents.push_back(seg({x1, y1}, {x0, y1})); - ents.push_back(seg({x0, y1}, {x0, y0})); - } else { - throw std::runtime_error("sketch_add needs 'entities', a single 'type', or 'rect'"); - } - const int base = t.add_entities_scripted(ents); - panel->mcp_viewport()->request_repaint(); - return json{{"ok", base >= 0}, {"first_index", base}, {"added", int(ents.size())}, - {"entities", int(t.entities().size())}, {"dof", t.dof()}}; -} - json action_sketch_select(DesignPanel* panel, const json& params) { DesignSketchTool& t = mcp_sketch(panel); @@ -1495,30 +2327,29 @@ json action_sketch_mirror(DesignPanel* panel, const json& params) return json{{"ok", true}, {"first_index", base}, {"added", int(out.size())}, {"dof", t.dof()}}; } -json sketch_report(DesignSketchTool& t) +// The `sketch` a method 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) { - const auto rep = t.loop_report(); - json loops = json::array(); - for (const auto& l : rep.loops) { - json holes = json::array(); - for (int h : l.holes) holes.push_back(h); - loops.push_back(json{{"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}}; + if (!v.is_number_integer()) throw std::runtime_error("sketch must be a feature index (describe_scene'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) { - (void)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 std::runtime_error("no viewport"); + 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) @@ -1547,7 +2378,7 @@ json action_sketch_describe(DesignPanel* panel, const json& params) {"pending", t.pending_points()}, {"editing", t.value_field_open()}, {"selection", t.selection()}}; - out.update(sketch_report(t)); + out.update(sketch_report(t.loop_report())); return out; } @@ -1556,7 +2387,7 @@ 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", t.dof()}, {"solve_ok", t.solve_ok()}}; - out.update(sketch_report(t)); + out.update(sketch_report(t.loop_report())); return out; } @@ -1569,7 +2400,7 @@ json action_sketch_heal(DesignPanel* panel, const json& params) panel->mcp_viewport()->request_repaint(); json out{{"ok", true}, {"welded", welded}, {"tolerance", tol}, {"dof", t.dof()}, {"solve_ok", t.solve_ok()}}; - out.update(sketch_report(t)); + out.update(sketch_report(t.loop_report())); return out; } @@ -1629,10 +2460,256 @@ json action_sketch_set_value(DesignPanel* panel, const json& params) json out{{"ok", true}, {"kind", kind_name}, {"before", before}, {"value", value}, {"dof", t.dof()}, {"solve_ok", t.solve_ok()}}; - out.update(sketch_report(t)); + 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`. + +// The card's mode choice. "auto" (where allowed) comes back empty. bool_from, which the older +// methods keep, makes a new body of a word it does not know; here that is an error. +std::optional boolean_arg(const json& params, const char* def, bool allow_auto) +{ + json v = params.value("boolean", json()); + if (v.is_null()) v = def; + if (v.is_string()) { + const std::string b = v.get(); + if (allow_auto && b == "auto") return std::nullopt; + for (size_t i = 0; i < std::size(kModes); ++i) + if (b == kModes[i]) return BooleanMode(i); + } + throw std::runtime_error(allow_auto ? "boolean must be auto, new, union, subtract or intersect" + : "boolean must be new, union, subtract or intersect"); +} + +// 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 std::runtime_error("boolean " + std::string(kModes[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; +} + +// 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 boolean 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["boolean"] = kModes[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 std::runtime_error("no viewport"); + 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 CadCallError& 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. + if (!loop.is_null() || separate_regions(vp->mcp_sketch_tool(), doc.features[sketch.get()].entities) < 2) + throw; + throw CadCallError(e.code, std::string(e.what()) + + "; pass \"loop\" to extrude one of its regions (closed_loops of sketch_describe {sketch})"); + } + 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 = boolean_arg(params, "new", true); + 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 = *boolean_arg(params, "new", false); + const int body = std::max(-1, target_body_arg(params, doc)); + check_has_body(mode, doc); + SketchProfile prof; + const bool has_prof = profile_from(params, prof); + double w = 0, h = 0; + if (!has_prof) { // a rectangle centred on the axis may self-overlap; offset it with `profile` + 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"); + } + int s = -1; + json r = add_feature(panel, "revolve_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); + 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; +} + // Verbs whose handler opens a MODAL dialog. This matters more than it looks: the socket thread // posts the call to the wx main thread and waits 15 s on a future, so a verb that blocks that // thread inside ShowModal() times the RPC out AND leaves the main thread blocked until a human @@ -1753,13 +2830,15 @@ json action_mirror(DesignPanel* panel, const json& params) if (doc.bodies.empty()) throw std::runtime_error("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(plane_from(params, doc), bi, m, "Mirror"); + 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.undo(); doc.error = why; } - panel->mcp_after_change(); - return json{{"ok", ok}, {"mirror_index", idx}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; + 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) @@ -1773,10 +2852,10 @@ json action_transform(DesignPanel* panel, const json& params) 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, "Transform"); + 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.undo(); doc.error = why; } - panel->mcp_after_change(); + 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}}; } @@ -1790,29 +2869,25 @@ json action_thicken(DesignPanel* panel, const json& params) double thickness = params.value("thickness", 2.0); bool flip = params.value("flip", false); doc.checkpoint(); - int idx = doc.add_thicken(bi, face, thickness, flip, "Thicken"); + int idx = doc.add_thicken(bi, face, thickness, flip, panel->mcp_feature_name(_L("Thicken"))); bool ok = doc.recompute(); - if (!ok) { const std::string why = doc.error; doc.undo(); doc.error = why; } - panel->mcp_after_change(); + if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } + panel->mcp_after_change(ok); return json{{"ok", ok}, {"thicken_index", idx}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; } +// 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) { - if (!params.contains("face")) throw std::runtime_error("split needs 'face' (id from query_topology)"); CadDocument& doc = panel->mcp_doc(); - if (doc.bodies.empty()) throw std::runtime_error("no body to split"); - int bi = target_body_arg(params, doc); - int face_body = params.value("face_body", -1); - int face = params["face"].get(); - bool keep_upper = params.value("keep_upper", true); - bool keep_lower = params.value("keep_lower", true); - doc.checkpoint(); - int idx = doc.add_split_by_face(bi, face_body, face, keep_upper, keep_lower, "Split"); - bool ok = doc.recompute(); - if (!ok) { const std::string why = doc.error; doc.undo(); doc.error = why; } - panel->mcp_after_change(); - return json{{"ok", ok}, {"split_index", idx}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; + 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_project(DesignPanel* panel, const json& params) @@ -1824,13 +2899,14 @@ json action_project(DesignPanel* panel, const json& params) std::vector edges; if (params.contains("edges") && params["edges"].is_array()) for (const auto& v : params["edges"]) edges.push_back(v.get()); - SketchPlane pl = plane_from(params, doc); + const SketchPlane pl = cad_resolve_plane(params.value("plane", json("XY")), doc, false); doc.checkpoint(); - int idx = doc.add_project_edges(source_body, edges, face, pl, "Project"); + 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.undo(); doc.error = why; } - panel->mcp_after_change(); - return json{{"ok", ok}, {"project_index", idx}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; + if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } + panel->mcp_after_change(ok); + return json{{"ok", ok}, {"project_index", idx}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}, + {"frame", frame_json(pl)}}; } json action_delete_face(DesignPanel* panel, const json& params) @@ -1843,10 +2919,10 @@ json action_delete_face(DesignPanel* panel, const json& params) 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, "DeleteFace"); + 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.undo(); doc.error = why; } - panel->mcp_after_change(); + 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}}; } @@ -1864,8 +2940,8 @@ json action_bridge(DesignPanel* panel, const json& params) 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.undo(); doc.error = why; } - panel->mcp_after_change(); + 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}}; } @@ -1880,7 +2956,7 @@ json action_axis(DesignPanel* panel, const json& params) else if (t == "plane_intersection") at = AxisType::PlaneIntersection; else if (t == "along_edge") at = AxisType::AlongEdge; doc.checkpoint(); - int idx = doc.add_axis(at, "Axis"); + 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()); @@ -1911,7 +2987,7 @@ json action_coordsys(DesignPanel* panel, const json& params) 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, "CoordSys"); + 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); @@ -1927,18 +3003,72 @@ json action_coordsys(DesignPanel* panel, const json& params) 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_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) { - const double radius = params.value("radius", 10.0); - const double pitch = params.value("pitch", 5.0); - const double height = params.value("height", 20.0); - const bool left_handed = params.value("left_handed", false); - const double taper = params.value("taper_deg", 0.0); 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(plane_from(params, doc), radius, pitch, height, left_handed, taper, "Helix"); + 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}}; + 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"); } json action_mate(DesignPanel* panel, const json& params) @@ -1953,10 +3083,10 @@ json action_mate(DesignPanel* panel, const json& params) const bool flip = params.value("flip", false); CadDocument& doc = panel->mcp_doc(); doc.checkpoint(); - int idx = doc.add_mate(kind, cs_a, cs_b, offset, angle, flip, "Mate"); + int idx = doc.add_mate(kind, cs_a, cs_b, offset, angle, flip, panel->mcp_feature_name(_L("Mate"))); bool ok = doc.recompute(); - if (!ok) { const std::string why = doc.error; doc.undo(); doc.error = why; } - panel->mcp_after_change(); + if (!ok) { const std::string why = doc.error; doc.rollback(); doc.error = why; } + panel->mcp_after_change(ok); return json{{"ok", ok}, {"mate_index", idx}, {"bodies", int(doc.bodies.size())}, {"error", doc.error}}; } @@ -1978,41 +3108,1036 @@ 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(); - std::string name = params["name"].get(); - std::string expr = params["expr"].get(); - std::string old = doc.variables.count(name) ? doc.variables[name] : ""; + 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(); - doc.variables[name] = expr; - bool ok = doc.recompute(); - // undo() recomputes, which succeeds and clears doc.error; carry the reason across so - // the JSON reply below reports why the edit was rejected instead of an empty string. - if (!ok) { const std::string why = doc.error; doc.undo(); doc.error = why; } - panel->mcp_after_change(); - return json{{"ok", ok}, {"name", name}, {"error", doc.error}}; + 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_set_feature_expr(DesignPanel* panel, const json& params) { - if (!params.contains("feature")) throw std::runtime_error("set_feature_expr needs 'feature' index"); - if (!params.contains("field")) throw std::runtime_error("set_feature_expr needs 'field' name"); - if (!params.contains("expr")) throw std::runtime_error("set_feature_expr needs 'expr' string"); CadDocument& doc = panel->mcp_doc(); - int fi = params["feature"].get(); - if (fi < 0 || fi >= (int)doc.features.size()) - return json{{"ok", false}, {"error", "feature index out of range"}}; - std::string field = params["field"].get(); - std::string expr = params["expr"].get(); - std::string old = doc.features[fi].expr.count(field) ? doc.features[fi].expr[field] : ""; + const int fi = feature_arg(params, doc); + if (!params.contains("field")) throw std::runtime_error("set_feature_expr needs 'field' name"); + if (!params.contains("expr")) throw std::runtime_error("set_feature_expr 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(); - doc.features[fi].expr[field] = expr; - bool ok = doc.recompute(); - // undo() recomputes, which succeeds and clears doc.error; carry the reason across so - // the JSON reply below reports why the edit was rejected instead of an empty string. - if (!ok) { const std::string why = doc.error; doc.undo(); doc.error = why; } - panel->mcp_after_change(); + 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. Prepare's history is +// run_action undo's. +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 std::runtime_error(redo ? "Nothing to redo in the open sketch" : "Nothing to undo in the open sketch"); + throw std::runtime_error(redo ? "Nothing to redo in the Design history" + : "Nothing to undo in the Design history (run_action undo undoes Prepare's)"); + } + panel->menu_undo_redo(redo); + if (sketch) return json{{"ok", true}, {"scope", "sketch"}, {"entities", vp->mcp_sketch_tool().entities().size()}}; + const CadDocument& doc = panel->mcp_doc(); + return json{{"ok", true}, + {"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 CadCallError(-32000, doc.error.empty() ? "the Design tab refused the edit" : doc.error); +} + +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_scene'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_scene'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 std::runtime_error("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}}); +} + +json action_feature_set_enabled(DesignPanel* panel, const json& params) +{ + const CadDocument& doc = panel->mcp_doc(); + const int fi = feature_arg(params, doc); + const json enabled = param(params, "enabled"); + if (!enabled.is_boolean()) throw std::runtime_error("enabled must be true or false"); + const bool changed = doc.features[fi].enabled != enabled.get(); + if (!panel->show_feature(fi, enabled.get())) tree_edit_refused(doc); + return tree_edit_reply(doc, {{"feature", fi}, {"enabled", enabled}, {"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 std::runtime_error("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()}}); +} + +// --- 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(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 std::runtime_error("Prepare is not ready"); + Model& model = plater->model(); + const std::vector replace = cad_commit_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 std::runtime_error("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 std::runtime_error("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 std::runtime_error("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 std::runtime_error("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())}, {"name", o->name}, {"volumes", 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 new_project'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 std::runtime_error("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 std::runtime_error("STEP export failed: " + err); + + 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. + +size_t edit_distance(const std::string& a, const std::string& b); // with the method lookup below +std::string lower(std::string s); + +// 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 std::runtime_error("a value field is open in the sketch; commit or cancel it (Enter or Esc) first"); + if (t.gesture_pending()) throw std::runtime_error("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", t.dof()}, {"solve_ok", t.solve_ok()}}; +} + +// One item of sketch_add: entities added as given (`tool` Select), or a shape a drawing tool builds +// from its clicks. +struct SketchAddItem +{ + std::vector ents; + DesignSketchTool::Mode tool{DesignSketchTool::Mode::Select}; + std::vector clicks; + int sides{0}; + bool circumscribed{false}; + bool construction{false}; +}; + +// A sketch_add item: a shape's fields turned into the clicks its tool takes, or plain entities. +// Every check is made here, so adding a list of items cannot stop half way. +SketchAddItem sketch_add_item(const json& j) +{ + using Mode = DesignSketchTool::Mode; + SketchAddItem it; + const std::string t = j.value("type", std::string()); + 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; + }; + 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)); + } + return it; +} + +json sketch_add(DesignSketchTool& t, const json& params) +{ + std::vector items; + const json list = param(params, "entities"), type = param(params, "type"), rect = param(params, "rect"); + if (list.is_array() && !list.empty()) { + for (const json& j : list) items.push_back(sketch_add_item(j)); + } else if (type.is_string() && !type.get().empty()) { + items.push_back(sketch_add_item(params)); // one item, its fields beside `type` + } else if (rect.is_array() && !rect.empty()) { + // Corner rectangle as four shared-endpoint lines, so it arrives as ONE closed loop + // rather than four segments that happen to touch. + if (rect.size() < 4) throw std::runtime_error("rect must be [x0, y0, x1, y1]"); + const double x0 = rect[0].get(), y0 = rect[1].get(); + const double x1 = rect[2].get(), y1 = rect[3].get(); + const bool c = params.value("construction", false); + auto seg = [&](Vec2d a, Vec2d b) { SketchEntity e; e.type = SketchEntity::Type::Line; + e.p0 = a; e.p1 = b; e.construction = c; return e; }; + items.push_back(SketchAddItem{{seg({x0, y0}, {x1, y0}), seg({x1, y0}, {x1, y1}), seg({x1, y1}, {x0, y1}), seg({x0, y1}, {x0, y0})}}); + } else { + throw std::runtime_error("sketch_add needs 'entities', a single 'type', or 'rect'"); + } + if (std::any_of(items.begin(), items.end(), [](const SketchAddItem& it) { return it.tool != DesignSketchTool::Mode::Select; })) + check_sketch_idle(t); + + const int before = int(t.entities().size()); + json shapes = json::array(); + 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 SketchAddItem& it = items[i++]; + const int at = t.add_shape_scripted(it.tool, it.clicks, it.sides, it.circumscribed, it.construction); + 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}}); + } + } + return json{{"ok", true}, {"first_index", before}, {"added", int(t.entities().size()) - before}, + {"shapes", std::move(shapes)}, {"entities", int(t.entities().size())}, {"dof", t.dof()}}; +} + +// 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; +} + +// sketch_trim: a Trim (or Extend) click at `at`. +json sketch_trim(DesignSketchTool& t, const json& params) +{ + const Vec2d at = point_arg(params, "at"); + const bool extend = params.value("extend", false); + 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}, {"extend", extend}, {"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, Scale, Array and Polar array tools' Confirm. +json sketch_transform(DesignSketchTool& t, const json& params) +{ + using Mode = DesignSketchTool::Mode; + static const std::pair kOps[] = { + {"move", Mode::Move}, {"rotate", Mode::Rotate}, {"scale", Mode::Scale}, {"array", Mode::Array}, {"polar_array", Mode::PolarArray}}; + const json opv = param(params, "op"); + const char* op = nullptr; + Mode mode = Mode::Move; + for (const auto& [name, m] : kOps) + if (opv.is_string() && opv.get() == name) { op = name; mode = m; } + if (op == nullptr) throw std::runtime_error("op must be move, rotate, scale, array or polar_array"); + + // What each op 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(op) + " 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(op) + " 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(op) + " 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("polar_array needs pivot, the centre to array about"); + if (mode == Mode::PolarArray && std::abs(angle) < 1e-12) throw std::runtime_error("polar_array 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}, {"op", op}}; + 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\" (describe_tools lists them)"); + 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(lower(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) + + " (describe_tools lists them)"); +} + +// 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; +} + +// sketch_constrain: a CONSTRAIN bar button on the picks, or a constraint on named points. +json sketch_constrain(DesignSketchTool& t, const json& params) +{ + 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(t.dof()) + ")"); + 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_constraints(DesignSketchTool& t, const json&) +{ + json r{{"ok", true}, {"scope", "live"}, {"items", constraint_items(t.constraints())}}; + r.update(solve_state(t)); + return r; +} + +// sketch_unconstrain: a constraint row's delete button in a sketch session. +json sketch_unconstrain(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_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 method on the open sketch alone, then a repaint. +json on_open_sketch(DesignPanel* panel, const char* method, const json& params) +{ + json r = cad_sketch_call(mcp_sketch(panel), method, params); + panel->mcp_viewport()->request_repaint(); + return r; +} + +json action_sketch_constraints(DesignPanel* panel, const json& params) +{ + const json sketch = param(params, "sketch"); + if (sketch.is_null()) return cad_sketch_call(mcp_sketch(panel), "sketch_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; describe_feature reads its constraints"); + return json{{"ok", true}, {"scope", "committed"}, {"sketch", si}, {"items", constraint_items(f.entity_constraints)}, + {"constraints", int(f.entity_constraints.size())}}; +} + +// --- dispatcher --------------------------------------------------------------------- + +// What mcp_busy() lets through. Read only looks, so it runs under an open card or a sketch +// session; Sketch drives the live sketch session; Change edits the feature list or variables, +// which neither a card nor a sketch session may have changed under it. +enum class CadAccess { Read, Change, Sketch }; + +struct CadMethod +{ + const char* name; + CadAccess access; + bool ok_false; // legacy: a rejected rebuild is reported in the reply, not as an error + json (*run)(DesignPanel* panel, const json& params); + // It changes Prepare's model, so only the MCP server's cad_call, under its mutate guard, may + // run it; the socket would run it with no modal check, inside any nested event loop. + bool prepare = false; +}; + +// Every method, declared once: the dispatcher, the busy gate and describe_tools all read this. +const CadMethod kCadMethods[] = { + {"describe_tools", CadAccess::Read, false, [](DesignPanel*, const json& p) { return cad_describe_tools(p); }}, + {"describe_scene", CadAccess::Read, false, [](DesignPanel* panel, const json&) { return describe_scene(panel); }}, + {"describe_feature", CadAccess::Read, false, action_describe_feature}, + {"query_topology", CadAccess::Read, false, query_topology}, + {"measure", CadAccess::Read, false, measure}, + {"mass_properties", CadAccess::Read, false, mass_properties}, + {"slice_body", CadAccess::Read, false, slice_body}, + {"validate_against", CadAccess::Read, false, validate_against}, + {"check_interference", CadAccess::Read, false, action_check_interference}, + {"list_verbs", CadAccess::Read, false, action_list_verbs}, + {"sketch_describe", CadAccess::Read, false, action_sketch_describe}, + {"sketch_validate", CadAccess::Read, false, action_sketch_validate}, + {"sketch_constraints", CadAccess::Read, false, action_sketch_constraints}, + {"import_step", CadAccess::Change, true, import_step}, + {"import_mesh", CadAccess::Change, true, import_mesh}, + {"extrude", CadAccess::Change, false, action_extrude}, + {"revolve", CadAccess::Change, false, action_revolve}, + {"fillet", CadAccess::Change, true, action_fillet}, + {"chamfer", CadAccess::Change, true, action_chamfer}, + {"hole", CadAccess::Change, false, action_hole}, + {"hole_styled", CadAccess::Change, false, action_hole_styled}, + {"hole_standard", CadAccess::Change, false, action_hole_standard}, + {"boolean", CadAccess::Change, true, action_boolean}, + {"pattern", CadAccess::Change, true, action_pattern}, + {"pattern_on_curve", CadAccess::Change, true, action_pattern_on_curve}, + {"shell", CadAccess::Change, true, action_shell}, + {"rib", CadAccess::Change, true, action_rib}, + {"draft", CadAccess::Change, true, action_draft}, + {"mirror", CadAccess::Change, true, action_mirror}, + {"transform", CadAccess::Change, true, action_transform}, + {"thicken", CadAccess::Change, true, action_thicken}, + {"split", CadAccess::Change, false, action_split}, + {"thread", CadAccess::Change, false, action_thread}, + {"sweep", CadAccess::Change, false, action_sweep}, + {"loft", CadAccess::Change, false, action_loft}, + {"project", CadAccess::Change, true, action_project}, + {"delete_face", CadAccess::Change, true, action_delete_face}, + {"bridge", CadAccess::Change, true, action_bridge}, + {"axis", CadAccess::Change, true, action_axis}, + {"coordsys", CadAccess::Change, true, action_coordsys}, + {"plane", CadAccess::Change, false, action_plane}, + {"helix", CadAccess::Change, false, action_helix}, + {"mate", CadAccess::Change, true, action_mate}, + {"set_variable", CadAccess::Change, true, action_set_variable}, + {"set_feature_expr", CadAccess::Change, true, action_set_feature_expr}, + {"set_feature", CadAccess::Change, false, action_set_feature}, + {"feature_delete", CadAccess::Change, false, action_feature_delete}, + {"feature_move", CadAccess::Change, false, action_feature_move}, + {"feature_set_enabled", CadAccess::Change, false, action_feature_set_enabled}, + {"feature_rename", CadAccess::Change, false, action_feature_rename}, + {"body_set", CadAccess::Change, false, action_body_set}, + {"body_delete", CadAccess::Change, false, action_body_delete}, + {"commit", CadAccess::Change, false, action_commit, true}, + {"new_design", CadAccess::Change, false, action_new_design}, + {"export_step", CadAccess::Change, false, action_export_step}, + {"surface_extrude", CadAccess::Change, true, action_surface_extrude}, + {"surface_revolve", CadAccess::Change, true, action_surface_revolve}, + {"surface_loft", CadAccess::Change, true, action_surface_loft}, + {"surface_fill", CadAccess::Change, true, action_surface_fill}, + {"surface_offset", CadAccess::Change, true, action_surface_offset}, + {"thicken_surface", CadAccess::Change, true, action_thicken_surface}, + {"run_verb", CadAccess::Change, false, action_run_verb}, + // In a sketch session these take back or put back the last drawn shape, as Ctrl+Z does there. + {"undo", CadAccess::Sketch, false, [](DesignPanel* panel, const json&) { return undo_redo(panel, false); }}, + {"redo", CadAccess::Sketch, false, [](DesignPanel* panel, const json&) { return undo_redo(panel, true); }}, + {"sketch_begin", CadAccess::Sketch, false, action_sketch_begin}, + {"sketch_commit", CadAccess::Sketch, false, action_sketch_commit}, + {"sketch_cancel", CadAccess::Sketch, false, action_sketch_cancel}, + {"sketch_add", CadAccess::Sketch, false, [](DesignPanel* p, const json& a) { return on_open_sketch(p, "sketch_add", a); }}, + {"sketch_select", CadAccess::Sketch, false, action_sketch_select}, + {"sketch_delete", CadAccess::Sketch, false, action_sketch_delete}, + {"sketch_construction", CadAccess::Sketch, true, action_sketch_construction}, + {"sketch_offset", CadAccess::Sketch, false, action_sketch_offset}, + {"sketch_mirror", CadAccess::Sketch, false, action_sketch_mirror}, + {"sketch_heal", CadAccess::Sketch, false, action_sketch_heal}, + {"sketch_set_value", CadAccess::Sketch, false, action_sketch_set_value}, + {"sketch_fillet", CadAccess::Sketch, false, [](DesignPanel* p, const json& a) { return on_open_sketch(p, "sketch_fillet", a); }}, + {"sketch_chamfer", CadAccess::Sketch, false, [](DesignPanel* p, const json& a) { return on_open_sketch(p, "sketch_chamfer", a); }}, + {"sketch_trim", CadAccess::Sketch, false, [](DesignPanel* p, const json& a) { return on_open_sketch(p, "sketch_trim", a); }}, + {"sketch_transform", CadAccess::Sketch, false, [](DesignPanel* p, const json& a) { return on_open_sketch(p, "sketch_transform", a); }}, + {"sketch_constrain", CadAccess::Sketch, false, [](DesignPanel* p, const json& a) { return on_open_sketch(p, "sketch_constrain", a); }}, + {"sketch_unconstrain", CadAccess::Sketch, false, [](DesignPanel* p, const json& a) { return on_open_sketch(p, "sketch_unconstrain", a); }}, +}; + +const CadMethod* find_method(const std::string& name) +{ + for (const CadMethod& m : kCadMethods) + if (name == m.name) return &m; + return nullptr; +} + +size_t edit_distance(const std::string& a, const std::string& b) +{ + std::vector row(b.size() + 1); + for (size_t j = 0; j <= b.size(); ++j) row[j] = j; + for (size_t i = 1; i <= a.size(); ++i) { + size_t diag = row[0]; + row[0] = i; + for (size_t j = 1; j <= b.size(); ++j) { + const size_t up = row[j]; + row[j] = std::min({row[j] + 1, row[j - 1] + 1, diag + (a[i - 1] == b[j - 1] ? 0 : 1)}); + diag = up; + } + } + return row[b.size()]; +} + +std::string lower(std::string s) +{ + std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return char(std::tolower(c)); }); + return s; +} + +// "; did you mean a, b?" for a mistyped method name, or nothing when no name is close. +std::string close_methods(const std::string& name) +{ + const std::string want = lower(name); + std::string close; + for (const CadMethod& m : kCadMethods) { + const std::string n = m.name; + if ((!want.empty() && (n.find(want) != std::string::npos || want.find(n) != std::string::npos)) + || edit_distance(n, want) <= 2 + want.size() / 4) + close += (close.empty() ? "" : ", ") + n; + } + return close.empty() ? std::string() : "; did you mean " + close + "?"; +} + // Dispatch one parsed request ON THE MAIN THREAD. Returns a JSON-RPC reply string. std::string handle_on_main(const std::string& method, const json& params, const json& id) { @@ -2023,16 +4148,15 @@ std::string handle_on_main(const std::string& method, const json& params, const if (!panel) return rpc_error(id, -32001, "Design panel not ready"); - // Methods that only LOOK. Everything else changes the document or the live sketch, and - // must not do it under a GUI editor or a sketch session it does not own. No method may run - // during a rebuild, not even these: the rebuild's busy loop runs this request while the - // GUI's worker thread holds the document. Checked before hydrating, which writes it. - static const std::set kReadOnly = { - "describe_tools", "describe_scene", "query_topology", "measure", "mass_properties", - "slice_body", "validate_against", "list_verbs", "sketch_describe", "sketch_validate", - "check_interference" }; + const CadMethod* m = find_method(method); + if (m == nullptr) + return rpc_error(id, -32601, "Unknown method: " + method + close_methods(method)); + + // Only Read methods may run under a GUI editor or a sketch session they do not own. No method + // may run during a rebuild, not even these: the rebuild's busy loop runs this request while + // the GUI's worker thread holds the document. Checked before hydrating, which writes it. std::string why; - if (panel->mcp_busy(kReadOnly.count(method) != 0, method.rfind("sketch_", 0) == 0, why)) + if (panel->mcp_busy(m->access == CadAccess::Read, m->access == CadAccess::Sketch, why)) return rpc_error(id, -32002, "Design tab busy: " + why); // A project opened without ever showing the Design tab has its recipe only in the Model; @@ -2073,64 +4197,9 @@ std::string handle_on_main(const std::string& method, const json& params, const } try { - if (method == "describe_tools") return rpc_result(id, describe_tools()); - if (method == "describe_scene") return rpc_result(id, describe_scene(panel)); - if (method == "query_topology") return rpc_result(id, query_topology(panel, params)); - if (method == "measure") return rpc_result(id, measure(panel, params)); - if (method == "mass_properties") return rpc_result(id, mass_properties(panel, params)); - if (method == "slice_body") return rpc_result(id, slice_body(panel, params)); - if (method == "import_step") return rpc_result(id, import_step(panel, params)); - if (method == "import_mesh") return rpc_result(id, import_mesh(panel, params)); - if (method == "validate_against") return rpc_result(id, validate_against(panel, params)); - if (method == "extrude") return rpc_result(id, action_extrude(panel, params)); - if (method == "revolve") return rpc_result(id, action_revolve(panel, params)); - if (method == "fillet") return rpc_result(id, action_fillet(panel, params)); - if (method == "chamfer") return rpc_result(id, action_chamfer(panel, params)); - if (method == "hole") return rpc_result(id, action_hole(panel, params)); - if (method == "hole_styled") return rpc_result(id, action_hole_styled(panel, params)); - if (method == "hole_standard") return rpc_result(id, action_hole_standard(panel, params)); - if (method == "boolean") return rpc_result(id, action_boolean(panel, params)); - if (method == "pattern") return rpc_result(id, action_pattern(panel, params)); - if (method == "pattern_on_curve") return rpc_result(id, action_pattern_on_curve(panel, params)); - if (method == "shell") return rpc_result(id, action_shell(panel, params)); - if (method == "rib") return rpc_result(id, action_rib(panel, params)); - if (method == "draft") return rpc_result(id, action_draft(panel, params)); - if (method == "mirror") return rpc_result(id, action_mirror(panel, params)); - if (method == "sketch_begin") return rpc_result(id, action_sketch_begin(panel, params)); - if (method == "sketch_commit") return rpc_result(id, action_sketch_commit(panel, params)); - if (method == "sketch_cancel") return rpc_result(id, action_sketch_cancel(panel, params)); - if (method == "sketch_add") return rpc_result(id, action_sketch_add(panel, params)); - if (method == "sketch_select") return rpc_result(id, action_sketch_select(panel, params)); - if (method == "sketch_delete") return rpc_result(id, action_sketch_delete(panel, params)); - if (method == "sketch_construction") return rpc_result(id, action_sketch_construction(panel, params)); - if (method == "sketch_offset") return rpc_result(id, action_sketch_offset(panel, params)); - if (method == "sketch_mirror") return rpc_result(id, action_sketch_mirror(panel, params)); - if (method == "sketch_describe") return rpc_result(id, action_sketch_describe(panel, params)); - if (method == "sketch_validate") return rpc_result(id, action_sketch_validate(panel, params)); - if (method == "sketch_heal") return rpc_result(id, action_sketch_heal(panel, params)); - if (method == "sketch_set_value") return rpc_result(id, action_sketch_set_value(panel, params)); - if (method == "list_verbs") return rpc_result(id, action_list_verbs(panel, params)); - if (method == "run_verb") return rpc_result(id, action_run_verb(panel, params)); - if (method == "transform") return rpc_result(id, action_transform(panel, params)); - if (method == "thicken") return rpc_result(id, action_thicken(panel, params)); - if (method == "split") return rpc_result(id, action_split(panel, params)); - if (method == "project") return rpc_result(id, action_project(panel, params)); - if (method == "delete_face") return rpc_result(id, action_delete_face(panel, params)); - if (method == "bridge") return rpc_result(id, action_bridge(panel, params)); - if (method == "axis") return rpc_result(id, action_axis(panel, params)); - if (method == "coordsys") return rpc_result(id, action_coordsys(panel, params)); - if (method == "helix") return rpc_result(id, action_helix(panel, params)); - if (method == "set_variable") return rpc_result(id, action_set_variable(panel, params)); - if (method == "set_feature_expr") return rpc_result(id, action_set_feature_expr(panel, params)); - if (method == "surface_extrude") return rpc_result(id, action_surface_extrude(panel, params)); - if (method == "surface_revolve") return rpc_result(id, action_surface_revolve(panel, params)); - if (method == "thicken_surface") return rpc_result(id, action_thicken_surface(panel, params)); - if (method == "surface_offset") return rpc_result(id, action_surface_offset(panel, params)); - if (method == "surface_loft") return rpc_result(id, action_surface_loft(panel, params)); - if (method == "surface_fill") return rpc_result(id, action_surface_fill(panel, params)); - if (method == "mate") return rpc_result(id, action_mate(panel, params)); - if (method == "check_interference") return rpc_result(id, action_check_interference(panel, params)); - return rpc_error(id, -32601, "Unknown method: " + method); + return rpc_result(id, m->run(panel, params)); + } catch (const CadCallError& ex) { + return rpc_error(id, ex.code, ex.what()); } catch (const Standard_Failure& ex) { // derives from std::exception, so it comes first return rpc_error(id, -32000, std::string("OCCT: ") + (*ex.what() ? ex.what() : "failure")); } catch (const std::exception& ex) { @@ -2150,6 +4219,8 @@ std::string dispatch_request(const std::string& line) std::string method = req.value("method", std::string()); json params = req.contains("params") ? req["params"] : json::object(); if (method.empty()) return rpc_error(id, -32600, "missing method"); + if (const CadMethod* m = find_method(method); m != nullptr && m->prepare) + return rpc_error(id, -32601, method + " changes the plate; call it through the app's MCP server (cad_call)"); auto prom = std::make_shared>(); auto fut = prom->get_future(); @@ -2298,6 +4369,1085 @@ void start_mcp_control_if_enabled() #endif } +std::vector cad_control_methods() +{ + std::vector out; + for (const CadMethod& m : kCadMethods) out.emplace_back(m.name); + return out; +} + +json cad_describe_tools(const json& params) +{ + json out = tool_rows(); + json legacy = json::array(); + for (const CadMethod& m : kCadMethods) + if (m.ok_false) legacy.push_back(m.name); + out["errors"] = "A call that fails is an error and leaves the design as it was. The methods in " + "legacy_ok_false report a rejected rebuild in their reply instead (ok false, or " + "a non-empty error)."; + out["legacy_ok_false"] = std::move(legacy); + + std::vector names; + const json want = params.is_object() ? params.value("method", json()) : json(); + if (want.is_string()) { + if (!want.get().empty()) names.push_back(want.get()); + } else if (want.is_array()) { + for (const json& n : want) { + if (!n.is_string()) throw std::runtime_error("describe_tools: method takes a name or a list of names"); + names.push_back(n.get()); + } + } else if (!want.is_null()) { + throw std::runtime_error("describe_tools: method takes a name or a list of names"); + } + for (const std::string& n : names) + if (find_method(n) == nullptr) + throw std::runtime_error("describe_tools: unknown method '" + n + "'" + close_methods(n)); + const json q = params.is_object() ? params.value("query", json("")) : json(""); + if (!q.is_string()) throw std::runtime_error("describe_tools: query must be a string"); + const std::string query = lower(q.get()); + + json rows = json::array(); + for (json& row : out["tools"]) { + const std::string name = row.value("name", std::string()); + if (!names.empty() && std::find(names.begin(), names.end(), name) == names.end()) continue; + if (!query.empty() && lower(name + " " + row.value("summary", std::string())).find(query) == std::string::npos) continue; + if (const CadMethod* m = find_method(name)) + row["access"] = m->access == CadAccess::Read ? "read" : m->access == CadAccess::Sketch ? "sketch" : "change"; + rows.push_back(std::move(row)); + } + out["tools"] = std::move(rows); + return out; +} + +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 std::runtime_error("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 std::runtime_error("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["enabled"] = 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; + return j; +} + +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 set_feature 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 set_feature_expr {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); +} + +std::vector cad_commit_replace(const json& replace, const Model& model) +{ + if (!replace.is_array()) throw std::runtime_error("replace takes a list of object indices (list_objects)"); + 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 (list_objects), 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 std::runtime_error("object " + std::to_string(i) + + " is part of a cut object; delete it with select + run_action obj_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); describe_feature 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& method, const json& params) +{ + const json p = params.is_object() ? params : json::object(); + if (method == "sketch_add") return sketch_add(tool, p); + if (method == "sketch_fillet") return sketch_corner(tool, p, false); + if (method == "sketch_chamfer") return sketch_corner(tool, p, true); + if (method == "sketch_trim") return sketch_trim(tool, p); + if (method == "sketch_transform") return sketch_transform(tool, p); + if (method == "sketch_constrain") return sketch_constrain(tool, p); + if (method == "sketch_constraints") return sketch_constraints(tool, p); + if (method == "sketch_unconstrain") return sketch_unconstrain(tool, p); + throw std::runtime_error(method + " is not a method of the open sketch"); +} + +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 = boolean_arg(params, "auto", true); + 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 = *boolean_arg(params, "new", false); + const int body = std::max(-1, target_body_arg(params, doc)); + check_has_body(mode, doc); + // An entity axis is a line of this sketch; without one, a fresh card offers the sketch's only + // centerline, unless the caller chose a plane axis. + const std::vector& ents = doc.features[si].entities; + int axis_entity = -1; + const json ae = params.value("axis_entity", json()); + if (!ae.is_null()) { + 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"); + axis_entity = ae.get(); + if (axis_entity != -1 && (axis_entity < 0 || axis_entity >= int(ents.size()) || ents[axis_entity].type != SketchEntity::Type::Line)) + throw std::runtime_error("axis_entity " + std::to_string(axis_entity) + " is not a line of sketch " + std::to_string(si)); + } else if (!params.contains("axis")) { + axis_entity = DesignPanel::default_revolve_axis_entity(ents); + } + 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_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 (query_topology)"); + if (doc.bodies.empty()) throw std::runtime_error("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 = boolean_arg(params, "auto", true).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_query_topology(const CadDocument& doc, const json& params) +{ + 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"); + for (const json& k : v) out.push_back(enum_index(key, k, 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; + 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 std::runtime_error("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 std::runtime_error("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 std::runtime_error("no body to thread"); + if (!params.at(kind).is_number_integer()) throw std::runtime_error(kind + " must be an id from query_topology"); + 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 std::runtime_error("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 = lower(d.get()); + std::string close; + for (const ThreadSpec& t : thread_standards()) + if (lower(t.name) == want) close = t.name; + if (close.empty() && !want.empty()) + for (const ThreadSpec& t : thread_standards()) { + const std::string n = lower(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_scene)"); + 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 = *boolean_arg(params, "new", false); + 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_scene)"); + 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 = *boolean_arg(params, "new", false); + 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_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 std::runtime_error("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 (query_topology)"); + 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); + }; +} + json cad_control_call(const std::string& method, const json& params) { const json reply = json::parse(handle_on_main(method, params, json(1))); diff --git a/src/slic3r/GUI/CAD/McpControl.hpp b/src/slic3r/GUI/CAD/McpControl.hpp index bc03683544..1ca1daed1f 100644 --- a/src/slic3r/GUI/CAD/McpControl.hpp +++ b/src/slic3r/GUI/CAD/McpControl.hpp @@ -11,17 +11,31 @@ // thread and runs through the SAME CadDocument kernel the GUI uses (no parallel engine); // describe_tools lists the methods. Every method is refused (-32002) during a rebuild, whose // worker owns the document; one that changes the document is also refused while the Design tab -// is busy with it — an open feature card, a sketch session. +// is busy with it — an open feature card, a sketch session. `commit` changes Prepare's model, so +// the socket refuses it: only the MCP server runs it, under its mutate guard. // // The socket is POSIX only; on Windows the same methods are reached through the app's MCP server // (its cad_call tool), which calls cad_control_call(). #include +#include #include #include +#include -namespace Slic3r { namespace GUI { +namespace Slic3r { + +class CadDocument; +struct CadFeature; +struct SketchEntity; +struct SketchEntityConstraintDef; +struct SketchPlane; +class Model; + +namespace GUI { + +class DesignSketchTool; // Start the server thread iff ORCA_CAD_MCP is set. Safe to call once the MainFrame exists — // the Design panel is built on the first request. No-op when the env var is unset or on Windows. @@ -38,6 +52,126 @@ struct CadCallError : std::runtime_error // checks and returns its result. Throws CadCallError. UI thread only. nlohmann::json cad_control_call(const std::string& method, const nlohmann::json& params); +// The names of every method cad_control_call() dispatches. +std::vector cad_control_methods(); + +// describe_tools' reply: one row per method with its params and access (read, change or sketch), +// narrowed by params `method` (a name or a list of names) and `query` (text in a name or summary). +// Throws std::runtime_error naming close methods for an unknown name. Needs no Design panel. +nlohmann::json cad_describe_tools(const nlohmann::json& params); + +// The `plane` param shared by the plane-taking methods: "XY", "XZ" or "YZ" through the modeling +// origin, {"datum": feature index}, or {"body": b, "face": f} on a planar face. A face gives the +// sketch-on-face plane (outward normal), or with `drill` the Hole card's inward plane; `face_body` +// then receives b. Throws std::runtime_error with the message the call fails with. +SketchPlane cad_resolve_plane(const nlohmann::json& plane, const CadDocument& doc, bool drill, + int* face_body = nullptr); + +// describe_feature's reply for features[index]: what its card shows (`params`), the fields +// set_feature takes (`editable`) with the card's limits (`ranges`), its expression bindings and +// references, a sketch's geometry, and the features (`used_by`) and bodies (`bodies_made`) it +// feeds. Throws std::runtime_error for an index out of range. +nlohmann::json cad_feature_json(const CadDocument& doc, int index); + +// set_feature's edit: overwrite the fields of `f` named in `fields` ({name: value}). Throws +// std::runtime_error, leaving `f` as it was, for a field its card does not edit, a field bound to +// an expression, a value of the wrong type, or one outside the card's range. +void cad_apply_feature_fields(CadFeature& f, const nlohmann::json& fields); + +// commit's `replace`: the model's object indices to delete once the design is on the plate, sorted +// ascending. Throws std::runtime_error for a value that is not an index, one out of range or +// repeated, and an object that is part of a cut (deleting it asks the person first). +std::vector cad_commit_replace(const nlohmann::json& replace, const Model& model); + +// sketch_describe {sketch}: committed sketch features[sketch] as the open sketch is described, its +// entities, constraint count and loops, numbered as extrude's `loop` takes them; `tool` only +// finds the loops. Throws std::runtime_error for an index that is not a sketch with entities. +nlohmann::json cad_sketch_describe(const CadDocument& doc, const DesignSketchTool& tool, int sketch); + +// The methods that work on the open sketch alone, run on `tool`'s session: sketch_add, +// sketch_fillet, sketch_chamfer, sketch_trim, sketch_transform, sketch_constrain, +// sketch_constraints (the open sketch's) and sketch_unconstrain. Each runs the sketch tool's own +// step for the button or gesture it stands for, checks every argument before it changes anything, +// and throws std::runtime_error with the reason, leaving the sketch as it was. Needs no Design panel. +nlohmann::json cad_sketch_call(DesignSketchTool& tool, const std::string& method, const nlohmann::json& params); + +// sketch_constrain's constraints on the open sketch's entities `ents`, as the CONSTRAIN bar would +// add them. params.type is a SketchConstraintType in snake_case ("equal_length"; "equal" is the +// bar's Equal). With params.entities (or else `selection`) the bar's planner chooses the points +// (plan_entity_constraint), and a value it would ask for is params.value or the current one; with +// params.refs the references are taken as written, {entity, role} for a point ("origin" too) and +// {entity} for a whole entity ("x_axis", "y_axis" too), and params.value is required where the type +// carries one. Values are mm, or degrees for an angle. Throws std::runtime_error with the reason. +std::vector cad_constraint_defs(const nlohmann::json& params, const std::vector& ents, + const std::vector& selection); + +// extrude {sketch} and revolve {sketch}: check params against `doc` and return the call that adds, +// without rebuilding, the feature the Extrude or Revolve card adds for the committed sketch +// params.sketch; it takes the feature's name and returns its index. Checking first lets a bad +// argument fail before the caller takes an undo checkpoint. Extrude takes the whole sketch, or with +// params.loop one of its loops with the loops inside it; its params.boolean "auto" (the default) +// joins the body the sketch touches, else makes a new body, as the card's default does. Revolve's +// axis is params.axis_entity, a line of the sketch, else the sketch's only centerline when +// params.axis is not given, else the plane axis params.axis. Throws std::runtime_error. +std::function cad_sketch_extrude(CadDocument& doc, const DesignSketchTool& tool, + const nlohmann::json& params); +std::function cad_sketch_revolve(CadDocument& doc, const nlohmann::json& params); + +// extrude {face}: the Extrude card's push/pull of a picked face. Checks params against `doc` and +// returns the call that adds the face extrude of params.face, a planar face of params.body (default +// the last body), joined to that body unless params.boolean says otherwise; `frame` receives the +// face's plane. Throws std::runtime_error. +std::function cad_face_extrude(CadDocument& doc, const nlohmann::json& params, + SketchPlane& frame); + +// query_topology's reply for body params.body of `doc`: its faces (kind, area, centroid, normal and +// the numbers of an analytic surface) and edges (kind, length, ends), narrowed by the face filters +// (kinds, direction, at_extreme) and edge filters (edge_kinds, direction, convex); with adjacency, +// the faces' edges and the edges' faces and convexity, and a list whose filters were not given holds +// the neighbours of the other's matches. Both lists are paged by params.limit and params.offset. +// Throws std::runtime_error. +nlohmann::json cad_query_topology(const CadDocument& doc, const nlohmann::json& params); + +// measure's reply for refs params.a and params.b, each a face, an edge (of its own body, else +// params.body), a point, or a cylindrical face's axis: the distance between their representative +// points, the minimum distance and the closest points, their angle and, for two parallel planar +// faces, the gap between them. Throws std::runtime_error naming the ref that does not resolve. +nlohmann::json cad_measure(const CadDocument& doc, const nlohmann::json& params); + +// Where a hole method drills: `plane` from params.plane (a face gives the Hole card's inward plane), +// `target_body` the body (a face plane's own body, else params.body, else -1 for the kernel's last +// body), and the reply's {body, x, y}: params.x and params.y, or params.at (a world point, or a +// cylindrical face or circular edge whose axis the hole shares) projected onto the plane, with +// `off_plane`, how far it was moved. Throws std::runtime_error. +nlohmann::json cad_hole_placement(const CadDocument& doc, const nlohmann::json& params, SketchPlane& plane, + int& target_body); + +// plane: check params against `doc` as the Plane card's Confirm does (CadDocument::datum_plane_refusal) +// and return the call that adds the datum plane, without rebuilding. Throws std::runtime_error. +std::function cad_datum_plane(CadDocument& doc, const nlohmann::json& params); + +// thread, sweep, loft and split: check params against `doc` as their cards' Confirm does and return +// the call that adds the feature without rebuilding, as cad_datum_plane does. +// thread: on params.face (a cylindrical face) or params.edge (a circular edge) of params.body, along +// its axis (CadDocument::thread_target), internal for a bore; else on params.plane at x/y or `at`, +// placed as a hole is (cad_hole_placement), with params.internal required. The size is +// params.designation's, else the standard nearest the cylinder (nearest_thread_standard), else a +// custom params.diameter and params.pitch; diameter, pitch and depth override it, and length +// defaults to the face's. `resolved` receives what the call will build: designation (null when +// custom), internal, diameter, pitch, depth, length, x, y and the frame. +// sweep: committed sketch params.sketch along params.path, a sketch or a helix. +// loft: through the sketches params.profiles, in order, params.ruled. +// split: body params.body with params.plane, moved params.offset along its normal and turned over +// by params.flip (a Cut feature), or along the plane of params.face (of params.face_body); it keeps +// the pieces on the plane's normal side (keep_upper) and the other (keep_lower), and `resolved` +// receives the body split, the indices the pieces will have (upper_body, lower_body) and, for a +// plane, the frame cut along. A plane clear of the body is refused. +// Each throws std::runtime_error. +std::function cad_thread(CadDocument& doc, const nlohmann::json& params, nlohmann::json& resolved); +std::function cad_sweep(CadDocument& doc, const nlohmann::json& params); +std::function cad_loft(CadDocument& doc, const nlohmann::json& params); +std::function cad_split(CadDocument& doc, const nlohmann::json& params, nlohmann::json& resolved); + }} // namespace Slic3r::GUI #endif // slic3r_GUI_McpControl_hpp_ diff --git a/src/slic3r/GUI/CreatePresetsDialog.cpp b/src/slic3r/GUI/CreatePresetsDialog.cpp index b25d81a3b7..807d8f357f 100644 --- a/src/slic3r/GUI/CreatePresetsDialog.cpp +++ b/src/slic3r/GUI/CreatePresetsDialog.cpp @@ -326,6 +326,22 @@ static bool delete_filament_preset_by_name(std::string delete_preset_name, std:: return true; } +bool delete_unselected_filament_preset(const std::string &name) +{ + PresetBundle &bundle = *wxGetApp().preset_bundle; + std::string next_selected_preset_name = bundle.filaments.get_selected_preset().name; + bool delete_result = delete_filament_preset_by_name(name, next_selected_preset_name); + BOOST_LOG_TRIVIAL(info) << __LINE__ << " filament preset name: " << name << (delete_result ? " delete successful" : " delete failed"); + + // Deleting moved the presets after it, so the selection is made again by name. + bundle.filaments.select_preset_by_name(next_selected_preset_name, true); + for (size_t i = 0; i < bundle.filament_presets.size(); ++i) { + auto preset = bundle.filaments.find_preset(bundle.filament_presets[i]); + if (preset == nullptr) bundle.filament_presets[i] = bundle.filaments.get_selected_preset_name(); + } + return delete_result; +} + static std::string get_curr_time(const char* format = "%Y_%m_%d_%H_%M_%S") { std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); @@ -363,6 +379,7 @@ static wxBoxSizer* create_checkbox(wxWindow* parent, Preset* preset, wxString& p { wxBoxSizer *sizer = new wxBoxSizer(wxHORIZONTAL); ::CheckBox * checkbox = new ::CheckBox(parent); + checkbox->SetName(preset_name); // so automation finds the row by the text beside the box sizer->Add(checkbox, 0, 0, 0); preset_checkbox.push_back(std::make_pair(checkbox, preset)); wxStaticText *preset_name_str = new wxStaticText(parent, wxID_ANY, preset_name); @@ -387,6 +404,7 @@ static wxBoxSizer *create_checkbox(wxWindow *parent, wxString &preset_name, std: { wxBoxSizer *sizer = new wxBoxSizer(wxHORIZONTAL); ::CheckBox *checkbox = new ::CheckBox(parent); + checkbox->SetName(preset_name); // so automation finds the row by the text beside the box sizer->Add(checkbox, 0, 0, 0); preset_checkbox.push_back(std::make_pair(checkbox, into_u8(preset_name))); wxStaticText *preset_name_str = new wxStaticText(parent, wxID_ANY, preset_name); @@ -3602,8 +3620,9 @@ void CreatePresetSuccessfulDialog::on_dpi_changed(const wxRect &suggested_rect) Layout(); } -ExportConfigsDialog::ExportConfigsDialog(wxWindow *parent) +ExportConfigsDialog::ExportConfigsDialog(wxWindow *parent, const wxString &export_dir) : DPIDialog(parent ? parent : nullptr, wxID_ANY, _L("Export Preset Bundle"), wxDefaultPosition, wxDefaultSize, wxCAPTION | wxCLOSE_BOX) + , m_export_dir(export_dir) { m_exprot_type.preset_bundle = _L("Printer config bundle(.orca_printer)"); m_exprot_type.filament_bundle = _L("Filament bundle(.orca_filament)"); @@ -4361,9 +4380,11 @@ wxWindow *ExportConfigsDialog::create_dialog_buttons(wxWindow* parent) return; } - wxDirDialog dlg(this, _L("Choose a directory"), "", wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST); - wxString path; - if (dlg.ShowModal() == wxID_OK) path = dlg.GetPath(); + wxString path = m_export_dir; + if (path.IsEmpty()) { + wxDirDialog dlg(this, _L("Choose a directory"), "", wxDD_DEFAULT_STYLE | wxDD_DIR_MUST_EXIST); + if (dlg.ShowModal() == wxID_OK) path = dlg.GetPath(); + } ExportCase export_case = ExportCase::EXPORT_CANCEL; if (!path.IsEmpty()) { wxGetApp().app_config->update_config_dir(into_u8(path)); @@ -4713,16 +4734,7 @@ void EditFilamentPresetDialog::delete_preset() return; } - // delete preset - std::string next_selected_preset_name = wxGetApp().preset_bundle->filaments.get_selected_preset().name; - bool delete_result = delete_filament_preset_by_name(need_delete_preset->name, next_selected_preset_name); - BOOST_LOG_TRIVIAL(info) << __LINE__ << " filament preset name: " << need_delete_preset->name << (delete_result ? " delete successful" : " delete failed"); - - wxGetApp().preset_bundle->filaments.select_preset_by_name(next_selected_preset_name, true); - for (size_t i = 0; i < wxGetApp().preset_bundle->filament_presets.size(); ++i) { - auto preset = wxGetApp().preset_bundle->filaments.find_preset(wxGetApp().preset_bundle->filament_presets[i]); - if (preset == nullptr) wxGetApp().preset_bundle->filament_presets[i] = wxGetApp().preset_bundle->filaments.get_selected_preset_name(); - } + delete_unselected_filament_preset(need_delete_preset->name); } // remove preset shared_ptr from m_printer_compatible_presets diff --git a/src/slic3r/GUI/CreatePresetsDialog.hpp b/src/slic3r/GUI/CreatePresetsDialog.hpp index 197dfdf142..b259a7e5c2 100644 --- a/src/slic3r/GUI/CreatePresetsDialog.hpp +++ b/src/slic3r/GUI/CreatePresetsDialog.hpp @@ -243,7 +243,8 @@ protected: class ExportConfigsDialog : public DPIDialog { public: - ExportConfigsDialog(wxWindow *parent); + // With `export_dir`, OK writes there instead of asking for a folder (an automated export). + ExportConfigsDialog(wxWindow *parent, const wxString &export_dir = wxEmptyString); ~ExportConfigsDialog();//to do: delete preset protected: @@ -307,6 +308,7 @@ private: wxStaticText * m_serial_text = nullptr; ::CheckBox * m_include_bed_assets = nullptr; wxStaticText * m_include_bed_assets_label = nullptr; + wxString m_export_dir; }; class CreatePresetForPrinterDialog : public DPIDialog @@ -402,6 +404,11 @@ private: }; +// Deletes the filament preset `name`, which the filament tab does not edit, as the Edit filament dialog +// does: the selected preset is selected again (dropping its unsaved changes) and the filament slots that +// used `name` take it instead. The caller refreshes the sidebar and the tabs. False when nothing was deleted. +bool delete_unselected_filament_preset(const std::string &name); + } } #endif \ No newline at end of file diff --git a/src/slic3r/GUI/GCodeViewer.cpp b/src/slic3r/GUI/GCodeViewer.cpp index 85ebd4d109..0c18e2c5b3 100644 --- a/src/slic3r/GUI/GCodeViewer.cpp +++ b/src/slic3r/GUI/GCodeViewer.cpp @@ -1271,6 +1271,49 @@ void GCodeViewer::select_view_type(libvgcode::EViewType type) set_view_type(type); } +void GCodeViewer::pick_view_type(libvgcode::EViewType type) +{ + m_fold = false; + select_view_type(type); + reset_visible(type); + // ORCA: remember the pick so the "Last used" preview default can restore it + const std::string view_type_name = view_type_to_config_name(type); + if (!view_type_name.empty()) + wxGetApp().app_config->set("preview_last_view_type", view_type_name); + update_moves_slider(); +#if ENABLE_ENHANCED_IMGUI_SLIDER_FLOAT + wxGetApp().imgui()->set_requires_extra_frame(); +#else + wxGetApp().plater()->get_current_canvas3D()->set_as_dirty(); + wxGetApp().plater()->get_current_canvas3D()->request_extra_frame(); +#endif +} + +bool GCodeViewer::can_switch_time_mode() const +{ + std::vector time_strs; + for (size_t i = 0; i < m_print_statistics.modes.size(); ++i) { + if (m_print_statistics.modes[i].time > 0.0f) { + const std::string time_str = short_time(get_time_dhms(m_print_statistics.modes[i].time)); + const auto it = std::find(time_strs.begin(), time_strs.end(), time_str); + if (it == time_strs.end()) + time_strs.emplace_back(time_str); + } + } + return time_strs.size() > 1; +} + +void GCodeViewer::set_time_mode(libvgcode::ETimeMode mode) +{ + m_viewer.set_time_mode(mode); +#if ENABLE_ENHANCED_IMGUI_SLIDER_FLOAT + wxGetApp().imgui()->set_requires_extra_frame(); +#else + wxGetApp().plater()->get_current_canvas3D()->set_as_dirty(); + wxGetApp().plater()->get_current_canvas3D()->request_extra_frame(); +#endif // ENABLE_ENHANCED_IMGUI_SLIDER_FLOAT +} + // ORCA: Pick the view type the preview opens with, following the "preview_default_view_type" preference: // a fixed view type, the one the user picked last ("last"), or the automatic choice ("auto", the default) // which shows Filament for multi material prints and Line Type for single material ones. @@ -4407,23 +4450,8 @@ void GCodeViewer::render_legend(float &legend_height, int canvas_width, int canv ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 0.0f); for (int i = 0; i < view_type_items_str.size(); i++) { const bool is_selected = (m_view_type_sel == i); - if (ImGui::BBLSelectable(view_type_items_str[i].c_str(), is_selected)) { - m_fold = false; - m_view_type_sel = i; - set_view_type(view_type_items[m_view_type_sel]); - reset_visible(view_type_items[m_view_type_sel]); - // ORCA: remember the pick so the "Last used" preview default can restore it - const std::string view_type_name = view_type_to_config_name(view_type_items[m_view_type_sel]); - if (!view_type_name.empty()) - wxGetApp().app_config->set("preview_last_view_type", view_type_name); - update_moves_slider(); - #if ENABLE_ENHANCED_IMGUI_SLIDER_FLOAT - imgui.set_requires_extra_frame(); - #else - wxGetApp().plater()->get_current_canvas3D()->set_as_dirty(); - wxGetApp().plater()->get_current_canvas3D()->request_extra_frame(); - #endif - } + if (ImGui::BBLSelectable(view_type_items_str[i].c_str(), is_selected)) + pick_view_type(view_type_items[i]); if (is_selected) { ImGui::SetItemDefaultFocus(); } @@ -4752,8 +4780,7 @@ void GCodeViewer::render_legend(float &legend_height, int canvas_width, int canv if (full_layout && !count_text.empty()) columns_offsets.push_back({ count_text, distance_text.empty() ? offsets[3] : offsets[4] }); append_item(EItemType::Rect, color, columns_offsets, true, offsets.back()/*ORCA checkbox_pos*/, visible, [this, type]() { - m_viewer.toggle_option_visibility(type); - update_moves_slider(); + toggle_option_visibility(type); }); }; const bool visible = m_viewer.is_option_visible(type); @@ -4809,8 +4836,7 @@ void GCodeViewer::render_legend(float &legend_height, int canvas_width, int canv columns_offsets.push_back({used_filaments_weight[i], offsets[4]}); append_item(EItemType::Rect, libvgcode::convert(m_viewer.get_extrusion_role_color(role)), columns_offsets, true, offsets.back(), visible, [this, role]() { - m_viewer.toggle_extrusion_role_visibility(role); - update_moves_slider(); + toggle_extrusion_role_visibility(role); }); } @@ -4828,8 +4854,7 @@ void GCodeViewer::render_legend(float &legend_height, int canvas_width, int canv columns_offsets.push_back({ travel_distance, offsets[3] }); // Usage column columns_offsets.push_back({ travel_moves, offsets[4] }); // Usage column append_item(EItemType::Rect, libvgcode::convert(m_viewer.get_option_color(libvgcode::EOptionType::Travels)), columns_offsets, true, offsets.back()/*ORCA checkbox_pos*/, visible, [this, item]() { - m_viewer.toggle_option_visibility(item); - update_moves_slider(); + toggle_option_visibility(item); }); } } @@ -4847,9 +4872,8 @@ void GCodeViewer::render_legend(float &legend_height, int canvas_width, int canv const bool travel_visible = m_viewer.is_option_visible(libvgcode::EOptionType::Travels); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 3.0f)); append_item(EItemType::None, libvgcode::convert(m_viewer.get_option_color(libvgcode::EOptionType::Travels)), { {_u8L("Travel"), offsets[0] }}, true, predictable_icon_pos/*ORCA checkbox_pos*/, travel_visible, [this]() { - m_viewer.toggle_option_visibility(libvgcode::EOptionType::Travels); + toggle_option_visibility(libvgcode::EOptionType::Travels); // refresh(*m_gcode_result, wxGetApp().plater()->get_extruder_colors_from_plater_config(m_gcode_result)); - update_moves_slider(); }); ImGui::PopStyleVar(1); break; @@ -4864,9 +4888,8 @@ void GCodeViewer::render_legend(float &legend_height, int canvas_width, int canv const bool travel_visible = m_viewer.is_option_visible(libvgcode::EOptionType::Travels); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 3.0f)); append_item(EItemType::None, libvgcode::convert(m_viewer.get_option_color(libvgcode::EOptionType::Travels)), { {_u8L("Travel"), offsets[0] }}, true, predictable_icon_pos/*ORCA checkbox_pos*/, travel_visible, [this]() { - m_viewer.toggle_option_visibility(libvgcode::EOptionType::Travels); + toggle_option_visibility(libvgcode::EOptionType::Travels); // refresh(*m_gcode_result, wxGetApp().plater()->get_extruder_colors_from_plater_config(m_gcode_result)); - update_moves_slider(); }); ImGui::PopStyleVar(1); break; @@ -4881,8 +4904,7 @@ void GCodeViewer::render_legend(float &legend_height, int canvas_width, int canv const bool travel_visible = m_viewer.is_option_visible(libvgcode::EOptionType::Travels); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 3.0f)); append_item(EItemType::None, libvgcode::convert(m_viewer.get_option_color(libvgcode::EOptionType::Travels)), { {_u8L("Travel"), offsets[0] }}, true, predictable_icon_pos/*ORCA checkbox_pos*/, travel_visible, [this]() { - m_viewer.toggle_option_visibility(libvgcode::EOptionType::Travels); - update_moves_slider(); + toggle_option_visibility(libvgcode::EOptionType::Travels); }); ImGui::PopStyleVar(1); break; @@ -4897,8 +4919,7 @@ void GCodeViewer::render_legend(float &legend_height, int canvas_width, int canv const bool travel_visible = m_viewer.is_option_visible(libvgcode::EOptionType::Travels); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0.0f, 3.0f)); append_item(EItemType::None, libvgcode::convert(m_viewer.get_option_color(libvgcode::EOptionType::Travels)), { {_u8L("Travel"), offsets[0] }}, true, predictable_icon_pos/*ORCA checkbox_pos*/, travel_visible, [this]() { - m_viewer.toggle_option_visibility(libvgcode::EOptionType::Travels); - update_moves_slider(); + toggle_option_visibility(libvgcode::EOptionType::Travels); }); ImGui::PopStyleVar(1); break; @@ -5475,21 +5496,8 @@ void GCodeViewer::render_legend(float &legend_height, int canvas_width, int canv // total estimated printing time section ImGui::Spacing(); std::string time_title = m_viewer.get_view_type() == libvgcode::EViewType::FeatureType ? _u8L("Total estimation") : _u8L("Time Estimation"); - auto can_show_mode_button = [this](libvgcode::ETimeMode mode) { - std::vector time_strs; - for (size_t i = 0; i < m_print_statistics.modes.size(); ++i) { - if (m_print_statistics.modes[i].time > 0.0f) { - const std::string time_str = short_time(get_time_dhms(m_print_statistics.modes[i].time)); - const auto it = std::find(time_strs.begin(), time_strs.end(), time_str); - if (it == time_strs.end()) - time_strs.emplace_back(time_str); - } - } - return time_strs.size() > 1; - }; - const libvgcode::ETimeMode time_mode_id = m_viewer.get_time_mode(); - if (can_show_mode_button(time_mode_id)) { + if (can_switch_time_mode()) { switch (time_mode_id) { case libvgcode::ETimeMode::Normal: { time_title += " [" + _u8L("Normal mode") + "]"; break; } @@ -5569,18 +5577,9 @@ void GCodeViewer::render_legend(float &legend_height, int canvas_width, int canv ImGui::SameLine(max_len); imgui.text(short_time(get_time_dhms(time_mode.time))); - auto show_mode_button = [this, &imgui, can_show_mode_button](const std::string& label, libvgcode::ETimeMode mode) { - if (can_show_mode_button(mode)) { - if (imgui.button(label)) { - m_viewer.set_time_mode(mode); -#if ENABLE_ENHANCED_IMGUI_SLIDER_FLOAT - imgui.set_requires_extra_frame(); -#else - wxGetApp().plater()->get_current_canvas3D()->set_as_dirty(); - wxGetApp().plater()->get_current_canvas3D()->request_extra_frame(); -#endif // ENABLE_ENHANCED_IMGUI_SLIDER_FLOAT - } - } + auto show_mode_button = [this, &imgui](const std::string& label, libvgcode::ETimeMode mode) { + if (can_switch_time_mode() && imgui.button(label)) + set_time_mode(mode); }; switch (time_mode_id) { diff --git a/src/slic3r/GUI/GCodeViewer.hpp b/src/slic3r/GUI/GCodeViewer.hpp index ff24afa96b..b011bd4e9e 100644 --- a/src/slic3r/GUI/GCodeViewer.hpp +++ b/src/slic3r/GUI/GCodeViewer.hpp @@ -426,6 +426,9 @@ public: // void _render_calibration_thumbnail_framebuffer(ThumbnailData& thumbnail_data, unsigned int w, unsigned int h, const ThumbnailsParams& thumbnail_params, PartPlateList& partplate_list, OpenGLManager& opengl_manager); // void render_calibration_thumbnail(ThumbnailData& thumbnail_data, unsigned int w, unsigned int h, const ThumbnailsParams& thumbnail_params, PartPlateList& partplate_list, OpenGLManager& opengl_manager); bool has_data() const { return !m_viewer.get_extrusion_roles().empty(); } + // The id of the slice result last loaded, which tells whose toolpaths and layers the viewer and its + // layer slider hold. + unsigned int last_result_id() const { return m_last_result_id; } bool can_export_toolpaths() const; std::vector get_plater_extruder(); @@ -481,6 +484,17 @@ public: } // ORCA: select a view type in the preview combo box and apply it void select_view_type(libvgcode::EViewType type); + // What picking a view type in the legend's combo box does: it also shows every feature type again and + // is remembered for the "Last used" preview default. Only for the combo's types, and only once + // toolpaths were loaded, since it refits the moves slider to them. + void pick_view_type(libvgcode::EViewType type); + // What clicking a legend row does: show or hide those toolpaths, and fit the moves slider to what shows. + void toggle_extrusion_role_visibility(libvgcode::EGCodeExtrusionRole role) { m_viewer.toggle_extrusion_role_visibility(role); update_moves_slider(); } + void toggle_option_visibility(libvgcode::EOptionType type) { m_viewer.toggle_option_visibility(type); update_moves_slider(); } + // The legend offers the other time estimate only when the two read differently. + bool can_switch_time_mode() const; + // What the legend's "Show stealth mode" / "Show normal mode" button does. + void set_time_mode(libvgcode::ETimeMode mode); // ORCA: apply the "preview_default_view_type" preference, see the definition for the supported values void apply_default_view_type(); @@ -502,6 +516,8 @@ public: } libvgcode::EViewType get_view_type() const { return m_viewer.get_view_type(); } + // What the legend draws from (time mode, visible feature types and options, colour ranges), for reads. + const libvgcode::Viewer& get_viewer() const { return m_viewer; } // ORCA: darken the layers not scrubbed to while using the preview layer slider void set_dim_previous_layers(bool value) { m_viewer.set_dim_previous_layers(value); } diff --git a/src/slic3r/GUI/GLCanvas3D.cpp b/src/slic3r/GUI/GLCanvas3D.cpp index 825bfa3b6f..64e036a083 100644 --- a/src/slic3r/GUI/GLCanvas3D.cpp +++ b/src/slic3r/GUI/GLCanvas3D.cpp @@ -806,6 +806,9 @@ void GLCanvas3D::LayersEditing::adaptive_layer_height_profile(GLCanvas3D & canva void GLCanvas3D::LayersEditing::smooth_layer_height_profile(GLCanvas3D & canvas, const HeightProfileSmoothingParams & smoothing_params) { this->update_slicing_parameters(); + // A frame of the open panel has loaded the profile already; without one, start from the object's + // profile, or the one its height ranges give. + PrintObject::update_layer_height_profile(*m_model_object, *m_slicing_parameters, m_layer_height_profile); m_layer_height_profile = smooth_height_profile(m_layer_height_profile, *m_slicing_parameters, smoothing_params); const_cast(m_model_object)->layer_height_profile.set(m_layer_height_profile); m_layers_texture.valid = false; @@ -1605,6 +1608,21 @@ GLCanvas3D::ArrangeSettings& GLCanvas3D::get_arrange_settings() return *ptr; } +void GLCanvas3D::store_arrange_settings() +{ + // The panel's keys: spacing and rotation carry the print mode's postfix, the material rule is + // one key for every mode. Align to Y axis is not stored. + const PrinterTechnology ptech = current_printer_technology(); + const std::string postfix = ptech == ptSLA ? "_sla" : + wxGetApp().global_print_sequence() == PrintSequence::ByObject ? "_fff_seq_print" : "_fff"; + const ArrangeSettings& settings = get_arrange_settings(); + AppConfig* appcfg = wxGetApp().app_config; + appcfg->set("arrange", "min_object_distance" + postfix, float_to_string_decimal_point(settings.distance)); + appcfg->set("arrange", "enable_rotation" + postfix, settings.enable_rotation); + if (ptech == ptFFF) + appcfg->set("arrange", "allow_multi_materials_on_same_plate", settings.allow_multi_materials_on_same_plate); +} + int GLCanvas3D::GetHoverId() { if (m_hover_plate_idxs.size() == 0) { @@ -2299,8 +2317,22 @@ BoundingBoxf3 GLCanvas3D::plate_scene_bounding_box(int plate_idx) const return bb; } +// The Variable layer height panel's buttons act on the object its last frame picked, with the profile +// that frame drew. A caller without the panel open (MCP) has had no such frame, so the selected object +// is picked here, from its model profile; with the panel open this is the frame's own pick. +bool GLCanvas3D::_select_layers_editing_object() +{ + if (!m_layers_editing.is_enabled()) + m_layers_editing.select_object(*m_model, -1); + const int idx = m_selection.get_object_idx(); + m_layers_editing.select_object(*m_model, 0 <= idx && idx < int(m_model->objects.size()) ? idx : -1); + return m_layers_editing.last_object_id >= 0; +} + void GLCanvas3D::reset_layer_height_profile() { + if (!_select_layers_editing_object()) + return; wxGetApp().plater()->take_snapshot("Variable layer height - Reset"); m_layers_editing.reset_layer_height_profile(*this); m_layers_editing.state = LayersEditing::Completed; @@ -2309,6 +2341,8 @@ void GLCanvas3D::reset_layer_height_profile() void GLCanvas3D::adaptive_layer_height_profile(float quality_factor) { + if (!_select_layers_editing_object()) + return; wxGetApp().plater()->take_snapshot("Variable layer height - Adaptive"); m_layers_editing.adaptive_layer_height_profile(*this, quality_factor); m_layers_editing.state = LayersEditing::Completed; @@ -2317,6 +2351,8 @@ void GLCanvas3D::adaptive_layer_height_profile(float quality_factor) void GLCanvas3D::smooth_layer_height_profile(const HeightProfileSmoothingParams& smoothing_params) { + if (!_select_layers_editing_object()) + return; wxGetApp().plater()->take_snapshot("Variable layer height - Smooth all"); m_layers_editing.smooth_layer_height_profile(*this, smoothing_params); m_layers_editing.state = LayersEditing::Completed; @@ -2525,7 +2561,7 @@ bool GLCanvas3D::render_and_capture(wxImage& out, std::string& err) return false; } if (m_canvas == nullptr || !_is_shown_on_screen()) { - err = "The 3D view is not shown; switch to the Prepare or Preview tab first (the Design tab's view can't be captured; use target window)"; + err = "The 3D view is not shown; switch to its tab first"; return false; } out = wxImage(); @@ -5474,12 +5510,7 @@ void GLCanvas3D::on_mouse(wxMouseEvent& evt) // in which case it must not be treated as a click on the plate, otherwise the gizmo would be closed (see deselect_all below). else if (evt.LeftUp() && !m_mouse.ignore_left_up && !m_mouse.dragging && m_picking_enabled && !m_hover_plate_idxs.empty() && (m_canvas_type == CanvasView3D) && !is_layers_editing_enabled()) { - int hover_idx = m_hover_plate_idxs.front(); - wxGetApp().plater()->select_plate_by_hover_id(hover_idx); - //wxGetApp().plater()->get_partplate_list().select_plate_view(); - //deselect all the objects - if (m_gizmos.get_current_type() != GLGizmosManager::MeshBoolean && m_hover_volume_idxs.empty()) - deselect_all(); + click_plate(m_hover_plate_idxs.front(), false, Vec2d::Zero()); } else if (evt.RightUp() && !is_layers_editing_enabled()) { // forces a frame render to ensure that m_hover_volume_idxs is updated even when the user right clicks while @@ -5507,40 +5538,26 @@ void GLCanvas3D::on_mouse(wxMouseEvent& evt) } } - //BBS change plate selection - bool plate_icon_popup_shown = false; - if (!m_hover_plate_idxs.empty() && (m_canvas_type == CanvasView3D) && !m_mouse.dragging) { - int hover_idx = m_hover_plate_idxs.front(); - plate_icon_popup_shown = (wxGetApp().plater()->select_plate_by_hover_id(hover_idx, true) == 1); - if (m_hover_volume_idxs.empty()) - deselect_all(); - render(); - } - - //ORCA allow right click on empty space while an object selected - if (m_hover_plate_idxs.empty() && m_hover_volume_idxs.empty() && (m_canvas_type == CanvasView3D) && !m_mouse.dragging) { - deselect_all(); - render(); - } - Vec2d logical_pos = pos.cast(); #if ENABLE_RETINA_GL const float factor = m_retina_helper->get_scale_factor(); logical_pos = logical_pos.cwiseQuotient(Vec2d(factor, factor)); #endif // ENABLE_RETINA_GL - if (!m_mouse.ignore_right_up && m_gizmos.get_current_type() == GLGizmosManager::EType::Undefined) { - //BBS post right click event - if (!m_hover_plate_idxs.empty() && !plate_icon_popup_shown) { - post_event(RBtnPlateEvent(EVT_GLCANVAS_PLATE_RIGHT_CLICK, { logical_pos, m_hover_plate_idxs.front() })); - } - else if (!plate_icon_popup_shown) { - // do not post the event if the user is panning the scene - // or if right click was done over the wipe tower - bool post_right_click_event = m_hover_volume_idxs.empty() || !m_volumes.volumes[get_first_hover_volume_idx()]->is_wipe_tower; - if (post_right_click_event) - post_event(RBtnEvent(EVT_GLCANVAS_RIGHT_CLICK, { logical_pos, m_hover_volume_idxs.empty() })); + //BBS change plate selection + if (!m_hover_plate_idxs.empty()) + click_plate(m_hover_plate_idxs.front(), true, logical_pos); + else { + //ORCA allow right click on empty space while an object selected + if (m_hover_volume_idxs.empty() && (m_canvas_type == CanvasView3D) && !m_mouse.dragging) { + deselect_all(); + render(); } + // do not post the event if the user is panning the scene + // or if right click was done over the wipe tower + if (!m_mouse.ignore_right_up && m_gizmos.get_current_type() == GLGizmosManager::EType::Undefined && + (m_hover_volume_idxs.empty() || !m_volumes.volumes[get_first_hover_volume_idx()]->is_wipe_tower)) + post_event(RBtnEvent(EVT_GLCANVAS_RIGHT_CLICK, { logical_pos, m_hover_volume_idxs.empty() })); } } @@ -5601,6 +5618,27 @@ void GLCanvas3D::on_mouse(wxMouseEvent& evt) #endif /* __WXMSW__ */ } +void GLCanvas3D::click_plate(int picking_id, bool right_click, const Vec2d& logical_pos) +{ + if (!right_click) { + wxGetApp().plater()->select_plate_by_hover_id(picking_id); + //deselect all the objects + if (m_gizmos.get_current_type() != GLGizmosManager::MeshBoolean && m_hover_volume_idxs.empty()) + deselect_all(); + return; + } + bool plate_icon_popup_shown = false; + if ((m_canvas_type == CanvasView3D) && !m_mouse.dragging) { + plate_icon_popup_shown = (wxGetApp().plater()->select_plate_by_hover_id(picking_id, true) == 1); + if (m_hover_volume_idxs.empty()) + deselect_all(); + render(); + } + //BBS post right click event + if (!m_mouse.ignore_right_up && m_gizmos.get_current_type() == GLGizmosManager::EType::Undefined && !plate_icon_popup_shown) + post_event(RBtnPlateEvent(EVT_GLCANVAS_PLATE_RIGHT_CLICK, { logical_pos, picking_id })); +} + void GLCanvas3D::on_paint(wxPaintEvent& evt) { m_presented_signature.reset(); @@ -7094,9 +7132,10 @@ void GLCanvas3D::render_thumbnail_internal(ThumbnailData& thumbnail_data, const camera.apply_projection(volumes_box); } - //GLShaderProgram* shader = wxGetApp().get_shader("gouraud_light"); - if (!for_picking && (shader == nullptr)) { - BOOST_LOG_TRIVIAL(info) << boost::format("render_thumbnail with no picking: shader is null, return directly"); + // Both passes draw with a shader, which is null until OpenGL has loaded the shaders or when one + // failed to load. + if (shader == nullptr) { + BOOST_LOG_TRIVIAL(info) << boost::format("render_thumbnail: shader is null (for_picking=%1%), return directly") % for_picking; return; } @@ -10055,12 +10094,7 @@ void GLCanvas3D::_render_gcode_overlay(int canvas_width, int canvas_height) IMSlider *layers_slider = m_gcode_viewer.get_layers_slider(); IMSlider *moves_slider = m_gcode_viewer.get_moves_slider(); - if (layers_slider->is_need_post_tick_event()) { - auto evt = new wxCommandEvent(EVT_CUSTOMEVT_TICKSCHANGED, m_canvas->GetId()); - evt->SetInt((int)layers_slider->get_post_tick_event_type()); - wxPostEvent(m_canvas, *evt); - layers_slider->reset_post_tick_event(); - } + send_layer_ticks_changes(); if (layers_slider->is_dirty()) { set_volumes_z_range({layers_slider->GetLowerValueD(), layers_slider->GetHigherValueD()}); @@ -10078,6 +10112,17 @@ void GLCanvas3D::_render_gcode_overlay(int canvas_width, int canvas_height) } } +void GLCanvas3D::send_layer_ticks_changes() +{ + IMSlider* layers_slider = m_gcode_viewer.get_layers_slider(); + if (layers_slider->is_need_post_tick_event()) { + wxCommandEvent evt(EVT_CUSTOMEVT_TICKSCHANGED, m_canvas->GetId()); + evt.SetInt((int)layers_slider->get_post_tick_event_type()); + wxPostEvent(m_canvas, evt); + layers_slider->reset_post_tick_event(); + } +} + void GLCanvas3D::_render_selection() { float scale_factor = 1.0; diff --git a/src/slic3r/GUI/GLCanvas3D.hpp b/src/slic3r/GUI/GLCanvas3D.hpp index 9a740c3405..6efc0b91d4 100644 --- a/src/slic3r/GUI/GLCanvas3D.hpp +++ b/src/slic3r/GUI/GLCanvas3D.hpp @@ -380,7 +380,7 @@ class GLCanvas3D Vec2d position{ DBL_MAX, DBL_MAX }; bool ignore_left_up{ false }; Drag drag; - bool ignore_right_up; + bool ignore_right_up{ false }; // Orca: The screen-space start and world-space anchor describe the same pan session. // Invalidating one must invalidate the other so a new drag cannot reuse stale depth. @@ -860,6 +860,9 @@ public: void load_arrange_settings(); ArrangeSettings& get_arrange_settings(); + // Saves the current print mode's spacing, rotation and material rule to the app config under the + // keys the Arrange options panel writes, for settings changed outside the panel. + void store_arrange_settings(); class SequentialPrintClearance { @@ -1262,6 +1265,9 @@ public: void reset_gcode_layers_times_cache() { m_gcode_layers_times_cache.clear(); } void set_volumes_z_range(const std::array& range) { m_volumes.set_range(range[0] - 1e-6, range[1] + 1e-6); } size_t get_gcode_extruders_count() { return m_gcode_viewer.get_extruders_count(); } + // Hands the layer slider's tick edits, if any, to the plater (EVT_CUSTOMEVT_TICKSCHANGED), which writes + // them into the plate's custom G-codes. Each Preview frame calls it; so does MCP after editing ticks. + void send_layer_ticks_changes(); std::vector load_object(const ModelObject& model_object, int obj_idx, std::vector instance_idxs); std::vector load_object(const Model& model, int obj_idx); @@ -1304,6 +1310,11 @@ public: void on_set_color_timer(wxTimerEvent& evt); void on_fps_overlay_timer(wxTimerEvent& evt); void on_mouse(wxMouseEvent& evt); + // A click on a plate or one of its icons, by its bed picking id, as on_mouse() does it for the one + // under the pointer (MCP calls it for an icon it names): a left click selects the plate or runs the + // icon; a right click selects the plate, then opens the plate menu unless the icon opened its own. + // `logical_pos` is where the plate menu opens. The caller checks what on_mouse() checks first. + void click_plate(int picking_id, bool right_click, const Vec2d& logical_pos); void on_gesture(wxGestureEvent& evt); void on_paint(wxPaintEvent& evt); void on_set_focus(wxFocusEvent& evt); @@ -1486,6 +1497,9 @@ private: void _update_slice_error_status(); + // Picks the selected object for the variable layer height actions; false when none is selected. + bool _select_layers_editing_object(); + void _switch_toolbars_icon_filename(); bool _init_toolbars(); bool _init_main_toolbar(); diff --git a/src/slic3r/GUI/GUI_App.cpp b/src/slic3r/GUI/GUI_App.cpp index a19adb7a19..6678638027 100644 --- a/src/slic3r/GUI/GUI_App.cpp +++ b/src/slic3r/GUI/GUI_App.cpp @@ -9419,6 +9419,16 @@ void GUI_App::apply_keeped_preset_modifications() load_current_presets(false); } +void GUI_App::discard_current_preset_changes() +{ + PrinterTechnology printer_technology = preset_bundle->printers.get_edited_preset().printer_technology(); + for (const Tab* const tab : tabs_list) { + if (tab->supports_printer_technology(printer_technology) && tab->current_preset_is_dirty()) + tab->m_presets->discard_current_changes(); + } + load_current_presets(false); +} + // This is called when creating new project or load another project // OR close ConfigWizard // to ask the user what should we do with unsaved changes for presets. @@ -9436,20 +9446,8 @@ bool GUI_App::check_and_keep_current_preset_changes(const wxString& caption, con if (!no_need_change && dlg.ShowModal() == wxID_CANCEL) return false; - auto reset_modifications = [this]() { - //if (is_called_from_configwizard) - // return; // no need to discared changes. It will be done fromConfigWizard closing - - PrinterTechnology printer_technology = preset_bundle->printers.get_edited_preset().printer_technology(); - for (const Tab* const tab : tabs_list) { - if (tab->supports_printer_technology(printer_technology) && tab->current_preset_is_dirty()) - tab->m_presets->discard_current_changes(); - } - load_current_presets(false); - }; - if (dlg.discard() || no_need_change) - reset_modifications(); + discard_current_preset_changes(); else // save selected changes { //BBS: add project embedded preset relate logic @@ -9468,7 +9466,7 @@ bool GUI_App::check_and_keep_current_preset_changes(const wxString& caption, con // text += "\n\n" + _L("All modifications will be discarded for new project."); //MessageDialog(nullptr, text).ShowModal(); - reset_modifications(); + discard_current_preset_changes(); } else if (dlg.transfer_changes() && (dlg.has_unselected_options() || is_called_from_configwizard)) { // execute this part of code only if not all modifications are keeping to the new project diff --git a/src/slic3r/GUI/GUI_App.hpp b/src/slic3r/GUI/GUI_App.hpp index aaf590c3cf..1f044bdc69 100644 --- a/src/slic3r/GUI/GUI_App.hpp +++ b/src/slic3r/GUI/GUI_App.hpp @@ -727,6 +727,9 @@ public: bool check_and_save_current_preset_changes(const wxString& caption, const wxString& header, bool remember_choice = true, bool use_dont_save_insted_of_discard = false); void apply_keeped_preset_modifications(); bool check_and_keep_current_preset_changes(const wxString& caption, const wxString& header, int action_buttons, bool* postponed_apply_of_keeped_changes = nullptr); + // The Discard of check_and_keep_current_preset_changes(): drops every modified preset's unsaved + // changes and reloads the presets. + void discard_current_preset_changes(); bool can_load_project(); bool check_print_host_queue(); bool checked_tab(Tab* tab); diff --git a/src/slic3r/GUI/GUI_AuxiliaryList.cpp b/src/slic3r/GUI/GUI_AuxiliaryList.cpp index bfc3ecf044..72d5195fed 100644 --- a/src/slic3r/GUI/GUI_AuxiliaryList.cpp +++ b/src/slic3r/GUI/GUI_AuxiliaryList.cpp @@ -5,6 +5,7 @@ #include #include "GUI_AuxiliaryList.hpp" #include "I18N.hpp" +#include "SyntheticInput.hpp" #include "wxExtensions.hpp" #include @@ -252,7 +253,7 @@ void AuxiliaryList::on_context_menu(wxDataViewEvent& evt) }); } - PopupMenu(menu); + popup_menu(*this, *menu); } void AuxiliaryList::on_begin_drag(wxDataViewEvent& evt) diff --git a/src/slic3r/GUI/GUI_Factories.cpp b/src/slic3r/GUI/GUI_Factories.cpp index b0e8605b37..a6be6fd61e 100644 --- a/src/slic3r/GUI/GUI_Factories.cpp +++ b/src/slic3r/GUI/GUI_Factories.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include #include "libslic3r/PrintConfig.hpp" #include @@ -67,7 +68,7 @@ static int filaments_count() return wxGetApp().filaments_cnt(); } -static bool is_improper_category(const std::string& category, const int filaments_cnt, const bool is_object_settings = true) +bool SettingsFactory::is_improper_category(const std::string& category, const int filaments_cnt, const bool is_object_settings) { return category.empty() || (filaments_cnt == 1 && (category == "Extruders" || category == "Wipe options")) || @@ -430,7 +431,7 @@ static void get_full_settings_hierarchy(FullSettingsHierarchy& settings_menu, co { auto const opt = config.def()->get(option); auto category = opt->category; - if (is_improper_category(category, filaments_cnt, !is_part)) + if (SettingsFactory::is_improper_category(category, filaments_cnt, !is_part)) continue; const std::string& label = !opt->full_label.empty() ? opt->full_label : opt->label; @@ -500,7 +501,7 @@ static void create_freq_settings_popupmenu(wxMenu* menu, const bool is_object_se const int filaments_cnt = filaments_count(); for (auto& category : bundle) { - if (is_improper_category(category.first, filaments_cnt, is_object_settings)) + if (SettingsFactory::is_improper_category(category.first, filaments_cnt, is_object_settings)) continue; append_menu_item(menu, wxID_ANY, _(category.first), "", @@ -2181,7 +2182,7 @@ wxMenu* MenuFactory::instance_menu() wxMenu* MenuFactory::layer_menu() { - MenuWithSeparators* menu = new MenuWithSeparators(); + wxMenu* menu = transient(new MenuWithSeparators()); append_menu_item_settings(menu); return menu; @@ -2207,13 +2208,13 @@ wxMenu* MenuFactory::multi_selection_menu() } if (all_plates) { - wxMenu* menu = new MenuWithSeparators(); + wxMenu* menu = transient(new MenuWithSeparators()); append_menu_item_replace_all_with_stl(menu); return menu; } if (undefined_type) return nullptr; - wxMenu* menu = new MenuWithSeparators(); + wxMenu* menu = transient(new MenuWithSeparators()); if (!multi_volume) { int index = 0; if (obj_list()->can_merge_to_multipart_object()) { @@ -2290,7 +2291,7 @@ wxMenu* MenuFactory::assemble_multi_selection_menu() // show this menu only for Objects(Instances mixed with Objects)/Volumes selection return nullptr; - wxMenu* menu = new MenuWithSeparators(); + wxMenu* menu = transient(new MenuWithSeparators()); append_menu_item_set_visible(menu); //append_menu_item_fix_through_cgal(menu); //append_menu_item_simplify(menu); @@ -2321,6 +2322,23 @@ void MenuFactory::append_menu_items_instance_manipulation(wxMenu* menu) []() { return plater()->can_increase_instances(); }, m_parent); } +wxMenu* MenuFactory::transient(wxMenu* menu) +{ + m_transient_menus.emplace_back(menu); + return menu; +} + +std::unique_ptr MenuFactory::take_transient(wxMenu* menu) +{ + for (auto it = m_transient_menus.begin(); it != m_transient_menus.end(); ++it) + if (it->get() == menu) { + std::unique_ptr out = std::move(*it); + m_transient_menus.erase(it); + return out; + } + return nullptr; +} + wxMenu *MenuFactory::filament_action_menu(int active_filament_menu_id) { create_filament_action_menu(false, active_filament_menu_id); return &m_filament_action_menu; @@ -2338,7 +2356,7 @@ wxMenu* MenuFactory::plate_menu() wxMenu* MenuFactory::assemble_object_menu() { - wxMenu* menu = new MenuWithSeparators(); + wxMenu* menu = transient(new MenuWithSeparators()); // Set Visible append_menu_item_set_visible(menu); // Delete @@ -2359,7 +2377,7 @@ wxMenu* MenuFactory::assemble_object_menu() wxMenu* MenuFactory::assemble_part_menu() { - wxMenu* menu = new MenuWithSeparators(); + wxMenu* menu = transient(new MenuWithSeparators()); append_menu_item_set_visible(menu); menu->AppendSeparator(); diff --git a/src/slic3r/GUI/GUI_Factories.hpp b/src/slic3r/GUI/GUI_Factories.hpp index d2ab760205..aebf95abff 100644 --- a/src/slic3r/GUI/GUI_Factories.hpp +++ b/src/slic3r/GUI/GUI_Factories.hpp @@ -2,6 +2,7 @@ #define slic3r_GUI_Factories_hpp_ #include +#include #include #include #include @@ -41,6 +42,9 @@ struct SettingsFactory static wxBitmap get_category_bitmap(const std::string& category_name, bool menu_bmp = true); static Bundle get_bundle(const DynamicPrintConfig* config, bool is_object_settings, bool is_layer_settings = false); static std::vector get_options(bool is_part); + // Options of this category are not offered to objects (is_object_settings) or to parts and + // modifiers: internal options without a category, and per-feature filaments with one filament. + static bool is_improper_category(const std::string& category, int filaments_cnt, bool is_object_settings = true); //BBS: add api to get options for catogary static std::vector get_visible_options(const std::string& category, const bool is_part); static std::map> get_all_visible_options(const bool is_part); @@ -99,6 +103,10 @@ public: wxMenu *filament_action_menu(int active_filament_menu_id); + // Hands over a menu that layer_menu(), multi_selection_menu() or an assemble_*_menu() built + // for one popup, so whoever shows it frees it afterwards; null for a menu MenuFactory keeps. + std::unique_ptr take_transient(wxMenu* menu); + private: enum MenuType { mtObjectFFF = 0, @@ -132,6 +140,9 @@ private: MenuWithSeparators m_assemble_part_menu; wxMenu m_filament_action_menu; + // Menus built afresh for one popup, held until take_transient() hands them over. + std::vector> m_transient_menus; + wxMenu* transient(wxMenu* menu); // Removed/Prepended Items according to the view mode diff --git a/src/slic3r/GUI/GUI_ObjectList.cpp b/src/slic3r/GUI/GUI_ObjectList.cpp index 0eef9cd1c2..5e7d7ae24d 100644 --- a/src/slic3r/GUI/GUI_ObjectList.cpp +++ b/src/slic3r/GUI/GUI_ObjectList.cpp @@ -224,7 +224,7 @@ ObjectList::ObjectList(wxWindow* parent) : Bind(wxEVT_DATAVIEW_SELECTION_CHANGED, [this](wxDataViewEvent& event) { // detect the current mouse position here, to pass it to list_manipulation() method // if we detect it later, the user may have moved the mouse pointer while calculations are performed, and this would mess-up the HitTest() call performed into list_manipulation() - if (!GetScreenRect().Contains(wxGetMousePosition())) { + if (!GetScreenRect().Contains(get_mouse_state().GetPosition())) { return; } #ifndef __WXOSX__ @@ -1344,18 +1344,12 @@ void ObjectList::paste_layers_into_list() cache_ranges.empty() || printer_technology() == ptSLA) return; - const wxDataViewItem object_item = m_objects_model->GetItemById(obj_idx); - wxDataViewItem layers_item = m_objects_model->GetLayerRootItem(object_item); - if (layers_item) - m_objects_model->Delete(layers_item); - t_layer_config_ranges& ranges = object(obj_idx)->layer_config_ranges; - // and create Layer item(s) according to the layer_config_ranges for (const auto& range : cache_ranges) ranges.emplace(range); - layers_item = add_layer_root_item(object_item); + const wxDataViewItem layers_item = reload_layer_rows(obj_idx); changed_object(obj_idx); @@ -2245,19 +2239,19 @@ bool ObjectList::is_instance_or_object_selected() return selection.is_single_full_instance() || selection.is_single_full_object(); } +int ObjectList::selected_obj_idx_for_subobject() const +{ + // we can add volumes for Object or Instance + const wxDataViewItem item = GetSelection(); + if (!item || !(m_objects_model->GetItemType(item)&(itObject|itInstance))) + return -1; + return m_objects_model->GetObjectIdByItem(item); +} + void ObjectList::load_subobject(ModelVolumeType type, bool from_galery/* = false*/) { - wxDataViewItem item = GetSelection(); - // we can add volumes for Object or Instance - if (!item || !(m_objects_model->GetItemType(item)&(itObject|itInstance))) + if (selected_obj_idx_for_subobject() < 0) return; - const int obj_idx = m_objects_model->GetObjectIdByItem(item); - - if (obj_idx < 0) return; - - // Get object item, if Instance is selected - if (m_objects_model->GetItemType(item)&itInstance) - item = m_objects_model->GetItemById(obj_idx); wxArrayString input_files; /*if (from_galery) { @@ -2271,6 +2265,14 @@ void ObjectList::load_subobject(ModelVolumeType type, bool from_galery/* = false if (input_files.IsEmpty()) return; + load_subobject(type, input_files, from_galery); +} + +void ObjectList::load_subobject(ModelVolumeType type, const wxArrayString& input_files, bool from_galery, std::string* error) +{ + const int obj_idx = selected_obj_idx_for_subobject(); + if (obj_idx < 0) return; + take_snapshot((type == ModelVolumeType::MODEL_PART) ? _u8L("Load Part") : _u8L("Load Modifier")); std::vector volumes; @@ -2279,7 +2281,7 @@ void ObjectList::load_subobject(ModelVolumeType type, bool from_galery/* = false if (type == ModelVolumeType::MODEL_PART) load_part(*(*m_objects)[obj_idx], volumes, type, from_galery); else*/ - load_modifier(input_files, *(*m_objects)[obj_idx], volumes, type, from_galery); + load_modifier(input_files, *(*m_objects)[obj_idx], volumes, type, from_galery, error); if (volumes.empty()) return; @@ -2363,7 +2365,7 @@ void ObjectList::load_part(ModelObject& model_object, std::vector& } } */ -void ObjectList::load_modifier(const wxArrayString& input_files, ModelObject& model_object, std::vector& added_volumes, ModelVolumeType type, bool from_galery) +void ObjectList::load_modifier(const wxArrayString& input_files, ModelObject& model_object, std::vector& added_volumes, ModelVolumeType type, bool from_galery, std::string* error) { // ! ysFIXME - delete commented code after testing and rename "load_modifier" to something common //if (type == ModelVolumeType::MODEL_PART) @@ -2442,11 +2444,15 @@ void ObjectList::load_modifier(const wxArrayString& input_files, ModelObject& mo model = Model::read_from_file(input_file, nullptr, nullptr, LoadStrategy::LoadModel); } } - catch (std::exception&) { + catch (std::exception& e) { if (!is_user_cancel) { - // auto msg = _L("Error!") + " " + input_file + " : " + e.what() + "."; - auto msg = _L("Error!") + " " + _L("Failed to get the model data in the current file."); - show_error(parent, msg); + if (error != nullptr) + *error = input_file + ": " + e.what(); + else { + // auto msg = _L("Error!") + " " + input_file + " : " + e.what() + "."; + auto msg = _L("Error!") + " " + _L("Failed to get the model data in the current file."); + show_error(parent, msg); + } } return; } @@ -2505,23 +2511,35 @@ void ObjectList::load_modifier(const wxArrayString& input_files, ModelObject& mo } } +std::vector primitive_size_names(const std::string& type_name) +{ + if (type_name == "Cube") + return {L("X"), L("Y"), L("Z")}; + if (type_name == "Cylinder" || type_name == "Cone" || type_name == "Disc") + return {L("Diameter"), L("Height")}; + if (type_name == "Sphere") + return {L("Diameter")}; + if (type_name == "Torus") + // TRN Size of a torus (ring): the diameter of its hole and the thickness of the ring. + return {L("Inner diameter"), L("Tube diameter")}; + return {}; +} + // The dimensions the size dialog asks for, filled with the default size of the primitive. static std::vector primitive_size_fields(const std::string& type_name) { const double side = wxGetApp().plater()->canvas3D()->get_size_proportional_to_max_bed_size(0.1); - if (type_name == "Cube") - return {{_L("X"), side}, {_L("Y"), side}, {_L("Z"), side}}; - if (type_name == "Cylinder" || type_name == "Cone") - return {{_L("Diameter"), side}, {_L("Height"), side}}; - if (type_name == "Sphere") - return {{_L("Diameter"), side}}; + std::vector fields; + for (const char* name : primitive_size_names(type_name)) + fields.push_back({_(name), side}); if (type_name == "Disc") - return {{_L("Diameter"), side}, {_L("Height"), 0.2}}; - if (type_name == "Torus") - // TRN Size of a torus (ring): the diameter of its hole and the thickness of the ring. - return {{_L("Inner diameter"), 0.75 * side}, {_L("Tube diameter"), 0.25 * side}}; - return {}; + fields[1].value = 0.2; + else if (type_name == "Torus") { + fields[0].value = 0.75 * side; + fields[1].value = 0.25 * side; + } + return fields; } // Replaces the default values with the size the user saved for the primitive, stored as space separated numbers. @@ -2542,12 +2560,15 @@ static void apply_saved_primitive_size(std::vector& fields[i].value = values[i]; } -// interactive starts from the size the user saved and asks for the size unless the user turned the dialog off; -// otherwise the primitive gets its built-in default size. nullopt when the user cancels. -static std::optional> primitive_size(const std::string& type_name, bool interactive) +// The size given, when it has a value per field. Otherwise interactive starts from the size the user saved and asks +// for the size unless the user turned the dialog off, and a call that is not interactive gets the built-in default +// size. nullopt when the user cancels or the given size has the wrong number of values. +static std::optional> primitive_size(const std::string& type_name, bool interactive, const std::vector& given) { - std::vector fields = primitive_size_fields(type_name); - AppConfig* app_config = wxGetApp().app_config; + std::vector fields = primitive_size_fields(type_name); + if (!given.empty()) + return given.size() == fields.size() ? std::optional(given) : std::nullopt; + AppConfig* app_config = wxGetApp().app_config; if (interactive && !fields.empty()) { apply_saved_primitive_size(fields, app_config->get("primitive_size", type_name)); if (app_config->get_bool("enable_primitive_size_dialog")) { @@ -2604,13 +2625,14 @@ static TriangleMesh create_mesh(const std::string& type_name, const std::vector< return mesh; } -void ObjectList::load_generic_subobject(const std::string& type_name, const ModelVolumeType type, bool interactive) +void ObjectList::load_generic_subobject(const std::string& type_name, const ModelVolumeType type, bool interactive, + const std::vector& given_size) { // BBS: single snapshot Plater::SingleSnapshot single(wxGetApp().plater()); if (type == ModelVolumeType::INVALID) { - load_shape_object(type_name, interactive); + load_shape_object(type_name, interactive, given_size); return; } @@ -2629,7 +2651,7 @@ void ObjectList::load_generic_subobject(const std::string& type_name, const Mode if (instance_idx == -1) return; - const std::optional> size = primitive_size(type_name, interactive); + const std::optional> size = primitive_size(type_name, interactive, given_size); if (!size) return; @@ -2697,7 +2719,7 @@ void ObjectList::load_generic_subobject(const std::string& type_name, const Mode wxGetApp().params_panel()->switch_to_object(true); //Show Dialog - if (wxGetApp().app_config->get("do_not_show_modifer_tips").empty()) { + if (interactive && wxGetApp().app_config->get("do_not_show_modifer_tips").empty()) { TipsDialog dlg(wxGetApp().mainframe, _L("Add Modifier"), _L("Switch to per-object setting mode to edit modifier settings."), "do_not_show_modifer_tips"); dlg.ShowModal(); } @@ -2714,18 +2736,22 @@ void ObjectList::switch_to_object_process() } } -void ObjectList::load_shape_object(const std::string &type_name, bool interactive) +bool ObjectList::can_add_shape_object() const { - const Selection& selection = wxGetApp().plater()->canvas3D()->get_selection(); - //assert(selection.get_object_idx() == -1); // Add nothing is something is selected on 3DScene - if (selection.get_object_idx() != -1) + return wxGetApp().plater()->canvas3D()->get_selection().get_object_idx() == -1; +} + +void ObjectList::load_shape_object(const std::string &type_name, bool interactive, const std::vector& given_size) +{ + // Add nothing while an object is selected on the 3D scene. + if (!can_add_shape_object()) return; const int obj_idx = m_objects->size(); if (obj_idx < 0) return; - const std::optional> size = primitive_size(type_name, interactive); + const std::optional> size = primitive_size(type_name, interactive, given_size); if (!size) return; @@ -3574,6 +3600,14 @@ wxDataViewItem ObjectList::add_layer_root_item(const wxDataViewItem obj_item) return layers_item; } +wxDataViewItem ObjectList::reload_layer_rows(const int obj_idx) +{ + const wxDataViewItem object_item = m_objects_model->GetItemById(obj_idx); + if (const wxDataViewItem layers_item = m_objects_model->GetLayerRootItem(object_item)) + m_objects_model->Delete(layers_item); + return add_layer_root_item(object_item); +} + DynamicPrintConfig ObjectList::get_default_layer_config(const int obj_idx) { DynamicPrintConfig config; @@ -3581,10 +3615,7 @@ DynamicPrintConfig ObjectList::get_default_layer_config(const int obj_idx) object(obj_idx)->config.opt_float("layer_height") : wxGetApp().preset_bundle->prints.get_edited_preset().config.opt_float("layer_height"); config.set_key_value("layer_height",new ConfigOptionFloat(layer_height)); - // BBS - int extruder = object(obj_idx)->config.has("extruder") ? - object(obj_idx)->config.opt_int("extruder") : - wxGetApp().preset_bundle->prints.get_edited_preset().config.opt_float("extruder"); + // A new range prints with the object's filament ("Default"). config.set_key_value("extruder", new ConfigOptionInt(0)); return config; @@ -4731,13 +4762,13 @@ void ObjectList::del_layer_range(const t_layer_height_range& range) select_item(selectable_item); } -static double get_min_layer_height(const int extruder_idx) +double get_min_layer_height(const int extruder_idx) { const DynamicPrintConfig& config = wxGetApp().preset_bundle->printers.get_edited_preset().config; return config.opt_float("min_layer_height", std::max(0, extruder_idx - 1)); } -static double get_max_layer_height(const int extruder_idx) +double get_max_layer_height(const int extruder_idx) { const DynamicPrintConfig& config = wxGetApp().preset_bundle->printers.get_edited_preset().config; int extruder_idx_zero_based = std::max(0, extruder_idx - 1); @@ -4899,7 +4930,12 @@ bool ObjectList::edit_layer_range(const t_layer_height_range& range, coordf_t la if (obj_idx < 0) return false; - ModelConfig* config = &object(obj_idx)->layer_config_ranges[range]; + // A range editor losing focus may report an edit of a range that undo or a replacement of the + // object's ranges has removed meanwhile; indexing would add it back without a layer height. + const auto it = object(obj_idx)->layer_config_ranges.find(range); + if (it == object(obj_idx)->layer_config_ranges.end()) + return false; + ModelConfig* config = &it->second; if (fabs(layer_height - config->opt_float("layer_height")) < EPSILON) return false; @@ -4923,6 +4959,9 @@ bool ObjectList::edit_layer_range(const t_layer_height_range& range, const t_lay // But edit_layer_range(...) function can be called, when Selection in ObjectList could be changed const int obj_idx = m_selected_object_id; if (obj_idx < 0) return false; + // As above: the range may be gone, and moving it would add an empty one. + if (object(obj_idx)->layer_config_ranges.count(range) == 0) + return false; // BBS: remove snapeshot name "Edit Height Range" take_snapshot(""); @@ -5949,7 +5988,7 @@ static void move_volume_to_end(ModelObject* obj, ModelVolume* volume) } } -void ObjectList::set_volume_type(ModelVolumeType new_type, bool preserve_ps_subtype) +wxString ObjectList::set_volume_type(ModelVolumeType new_type, bool preserve_ps_subtype, bool show_errors) { struct VolumeSelection { int object_idx; @@ -6011,7 +6050,7 @@ void ObjectList::set_volume_type(ModelVolumeType new_type, bool preserve_ps_subt collect_from_canvas(wxGetApp().plater()->get_view3D_canvas3D()); } if (volumes.empty()) - return; + return {}; } // Defense-in-depth safety net against issue #5070: SVG/text volumes carry emboss metadata @@ -6022,17 +6061,19 @@ void ObjectList::set_volume_type(ModelVolumeType new_type, bool preserve_ps_subt // Support entries in the old choice dialog; the UI-side guard for the current submenu lives // in MenuFactory::append_menu_item_change_type, see #13120). // The same rationale applies to any Precise Seam subtype. - // This block must never be reachable under a healthy UI; if it ever logs, the UI guard has - // been bypassed (new entry point, refactor, plugin, etc.) and should be investigated. + // The menu never offers these types for such parts, so reaching this block from it (show_errors) + // means the UI guard has been bypassed and should be investigated. The Speed Dial's type + // commands have no such guard and report the reason instead. if (new_type == ModelVolumeType::SUPPORT_BLOCKER || new_type == ModelVolumeType::SUPPORT_ENFORCER || is_precise_seam(new_type)) { const bool has_text_or_svg = std::any_of(volumes.begin(), volumes.end(), [](const VolumeSelection& sel) { return sel.volume->is_svg() || sel.volume->is_text(); }); if (has_text_or_svg) { - BOOST_LOG_TRIVIAL(error) << __FUNCTION__ - << ": blocked attempt to set SUPPORT_BLOCKER/ENFORCER or Precise Seam on SVG/text volume; " - << "UI guard should have prevented this -- possible regression in the Change Type menu"; - return; + if (show_errors) + BOOST_LOG_TRIVIAL(error) << __FUNCTION__ + << ": blocked attempt to set SUPPORT_BLOCKER/ENFORCER or Precise Seam on SVG/text volume; " + << "UI guard should have prevented this -- possible regression in the Change Type menu"; + return _L("A text or SVG part can only be a part, a negative part or a modifier."); } } @@ -6060,7 +6101,7 @@ void ObjectList::set_volume_type(ModelVolumeType new_type, bool preserve_ps_subt }); if (!any_diff) - return; + return {}; // --- Last-solid-part guard (pre-existing behavior) --- // When converting away from MODEL_PART, ensure at least one solid part remains per object. @@ -6083,8 +6124,10 @@ void ObjectList::set_volume_type(ModelVolumeType new_type, bool preserve_ps_subt for (const auto& sel : selected_part_cnt) { auto it = total_part_cnt.find(sel.first); if (it != total_part_cnt.end() && it->second > 0 && sel.second == it->second) { - Slic3r::GUI::show_error(nullptr, _(L("The type of the last solid object part cannot be changed."))); - return; + const wxString why = _(L("The type of the last solid object part cannot be changed.")); + if (show_errors) + Slic3r::GUI::show_error(nullptr, why); + return why; } } } @@ -6136,6 +6179,7 @@ void ObjectList::set_volume_type(ModelVolumeType new_type, bool preserve_ps_subt SetSelections(new_selection); m_prevent_list_events = false; } + return {}; } void ObjectList::last_volume_is_deleted(const int obj_idx) @@ -6373,13 +6417,18 @@ void ObjectList::rename_item() if (new_name.IsEmpty()) return; - if (Plater::has_illegal_filename_characters(new_name)) { + if (!rename_item(item, new_name)) Plater::show_illegal_characters_warning(this); - return; - } +} + +bool ObjectList::rename_item(const wxDataViewItem& item, const wxString& new_name) +{ + if (Plater::has_illegal_filename_characters(new_name)) + return false; if (m_objects_model->SetName(new_name, item)) update_name_in_model(item); + return true; } void ObjectList::fix_through_cgal() @@ -6905,21 +6954,25 @@ void ObjectList::OnEditingDone(wxDataViewEvent &event) // BBS: remove "const" qualifier void ObjectList::set_extruder_for_selected_items(const int extruder) +{ + wxDataViewItemArray sels; + GetSelections(sels); + set_extruder_for_items(sels, extruder); +} + +void ObjectList::set_extruder_for_items(const wxDataViewItemArray& items, const int extruder) { // BBS: check extruder id std::vector colors = wxGetApp().plater()->get_extruder_colors_from_plater_config(); if (extruder > colors.size()) return; - wxDataViewItemArray sels; - GetSelections(sels); - - if (sels.empty()) + if (items.empty()) return; take_snapshot(_u8L("Change Filaments")); - for (const wxDataViewItem& sel_item : sels) + for (const wxDataViewItem& sel_item : items) { /* We can change extruder for Object/Volume only. * So, if Instance is selected, get its Object item and change it diff --git a/src/slic3r/GUI/GUI_ObjectList.hpp b/src/slic3r/GUI/GUI_ObjectList.hpp index 36446b4af1..c886962ad7 100644 --- a/src/slic3r/GUI/GUI_ObjectList.hpp +++ b/src/slic3r/GUI/GUI_ObjectList.hpp @@ -21,6 +21,7 @@ #include "Event.hpp" #include "ObjectDataViewModel.hpp" +#include "SyntheticInput.hpp" #include "libslic3r/PrintConfig.hpp" @@ -63,6 +64,16 @@ enum class ObjectOrder { Name, Filament, Height, Size }; // Stable sort by natural name order, filament, top Z, or bounding box volume of the first instance. void sort_objects(std::vector& objects, ObjectOrder order, bool descending = false); +// The dimensions the Primitive size dialog asks for a shape ("Cube", "Cylinder", "Sphere", "Cone", "Disc", "Torus"), in its +// order, as untranslated labels; none for another name. +std::vector primitive_size_names(const std::string& type_name); + +// The layer heights the height range editor accepts for a range printed with filament extruder_idx (0 = the +// object's): the printer's min_layer_height and max_layer_height, the latter 75 % of the nozzle diameter when 0. +// The printer's per-nozzle values are indexed by filament number, the first serving any filament beyond them. +double get_min_layer_height(int extruder_idx); +double get_max_layer_height(int extruder_idx); + class PartPlate; wxDECLARE_EVENT(EVT_OBJ_LIST_OBJECT_SELECT, SimpleEvent); @@ -310,13 +321,24 @@ public: void show_settings(const wxDataViewItem settings_item); bool is_instance_or_object_selected(); + // The Load... item of the Add Part / Add Modifier menus: asks for files, then loads them as below. void load_subobject(ModelVolumeType type, bool from_galery = false); + // Adds input_files as parts of the selected object, in one undo step, and selects them. A file that fails to load shows an + // error dialog, or, with error, leaves its reason there instead. + void load_subobject(ModelVolumeType type, const wxArrayString& input_files, bool from_galery = false, + std::string* error = nullptr); // ! ysFIXME - delete commented code after testing and rename "load_modifier" to something common //void load_part(ModelObject& model_object, std::vector& added_volumes, ModelVolumeType type, bool from_galery = false); - void load_modifier(const wxArrayString& input_files, ModelObject& model_object, std::vector& added_volumes, ModelVolumeType type, bool from_galery = false); - // interactive uses the size the user enters or saved as default; otherwise the shape gets its built-in default size. - void load_generic_subobject(const std::string& type_name, const ModelVolumeType type, bool interactive = true); - void load_shape_object(const std::string &type_name, bool interactive); + void load_modifier(const wxArrayString& input_files, ModelObject& model_object, std::vector& added_volumes, ModelVolumeType type, bool from_galery = false, + std::string* error = nullptr); + // size, in the order the size dialog asks for the dimensions, skips the dialog. Without it, interactive uses the size the + // user enters or saved as default; otherwise the shape gets its built-in default size. Only interactive shows the tips + // dialog after adding a part. + void load_generic_subobject(const std::string& type_name, const ModelVolumeType type, bool interactive = true, + const std::vector& size = {}); + void load_shape_object(const std::string &type_name, bool interactive, const std::vector& size = {}); + // Whether load_shape_object() adds an object now: not while an object is selected, whose Add Part menu adds shapes. + bool can_add_shape_object() const; void load_mesh_object(const TriangleMesh &mesh, const wxString &name, bool center = true); // One object holding one part per mesh; the parts keep their placement relative to each other. void load_mesh_object(const std::vector> &parts, const wxString &name, bool center = true); @@ -338,6 +360,9 @@ public: void boolean(); // BBS: Boolean Operation of parts wxDataViewItem add_layer_root_item(const wxDataViewItem obj_item); + // Rebuilds an object's Layers rows from its layer_config_ranges after a caller changed them, and returns the Layers + // row, invalid when the object has no ranges. + wxDataViewItem reload_layer_rows(const int obj_idx); wxDataViewItem add_settings_item(wxDataViewItem parent_item, const DynamicPrintConfig* config); DynamicPrintConfig get_default_layer_config(const int obj_idx); @@ -355,7 +380,8 @@ public: void delete_all_connectors_for_selection(); void delete_all_connectors_for_object(int obj_idx); - wxPoint get_mouse_position_in_control() const { return wxGetMousePosition() - this->GetScreenPosition(); } + // Through get_mouse_state(), so a click automation delivers to a row acts on the cell it aims at. + wxPoint get_mouse_position_in_control() const { return get_mouse_state().GetPosition() - this->GetScreenPosition(); } int get_selected_obj_idx() const; ModelConfig& get_item_config(const wxDataViewItem& item) const; @@ -451,7 +477,9 @@ public: // generic "Change type → Precise Seam" entry where CENTER is a default fallback. // preserve_ps_subtype = false: no preservation — target type is applied verbatim. Used // by the "Precise Seam Type" subtype picker where the user explicitly wants CENTER. - void set_volume_type(ModelVolumeType new_type, bool preserve_ps_subtype = true); + // Returns why the selected parts kept their type, empty when they changed or already had it. + // show_errors shows that reason as the menu always has; automation passes false and reports it. + wxString set_volume_type(ModelVolumeType new_type, bool preserve_ps_subtype = true, bool show_errors = true); ModelVolumeType get_selected_volume_type(); void last_volume_is_deleted(const int obj_idx); @@ -464,7 +492,11 @@ public: void instances_to_separated_object(const int obj_idx, const std::set& inst_idx); void instances_to_separated_objects(const int obj_idx); void split_instances(); + // Asks for the selected object's or part's new name. void rename_item(); + // Names an object or part row; false, changing nothing, when the name has characters a file + // name cannot hold. + bool rename_item(const wxDataViewItem& item, const wxString& new_name); void fix_through_cgal(); // Fixes every object on the selected plate, or on all plates. void fix_all_through_cgal(bool all_plates); @@ -494,6 +526,8 @@ public: //BBS: remove const qualifier void set_extruder_for_selected_items(const int extruder); + // Change Filament on the given object, part and instance rows, in one undo step; the selection is left alone. + void set_extruder_for_items(const wxDataViewItemArray& items, const int extruder); wxDataViewItemArray reorder_volumes_and_get_selection(int obj_idx, std::function add_to_selection = nullptr); void apply_volumes_order(); @@ -537,6 +571,8 @@ private: // apply the instance transform to all volumes and reset instance transform except the offset void apply_object_instance_transfrom_to_all_volumes(ModelObject *model_object, bool need_update_assemble_matrix = true); + // The object the Load... items add parts to: the one whose object or instance row is selected, else -1. + int selected_obj_idx_for_subobject() const; std::vector m_columns_width; wxSize m_last_size; diff --git a/src/slic3r/GUI/IMSlider.cpp b/src/slic3r/GUI/IMSlider.cpp index 7ddc5413de..a05926c704 100644 --- a/src/slic3r/GUI/IMSlider.cpp +++ b/src/slic3r/GUI/IMSlider.cpp @@ -407,10 +407,12 @@ void IMSlider::post_ticks_changed_event(Type type) m_is_need_post_tick_changed_event = true; } -void IMSlider::add_custom_gcode(std::string custom_gcode) +void IMSlider::add_custom_gcode(std::string custom_gcode, int tick) { - if (m_selection == ssUndef) return; - const int tick = m_selection == ssLower ? m_lower_value : m_higher_value; + if (tick < 0) { + if (m_selection == ssUndef) return; + tick = m_selection == ssLower ? m_lower_value : m_higher_value; + } const auto it = m_ticks.ticks.find(TickCode{ tick }); @@ -422,14 +424,16 @@ void IMSlider::add_custom_gcode(std::string custom_gcode) post_ticks_changed_event(Custom); } -void IMSlider::add_code_as_tick(Type type, int selected_extruder) +bool IMSlider::add_code_as_tick(Type type, int selected_extruder, int tick) { - if (m_selection == ssUndef) return; - const int tick = m_selection == ssLower ? m_lower_value : m_higher_value; + if (tick < 0) { + if (m_selection == ssUndef) return false; + tick = m_selection == ssLower ? m_lower_value : m_higher_value; + } if (!check_ticks_changed_event(type)) { BOOST_LOG_TRIVIAL(trace) << "check ticks change event false"; - return; + return false; } if (type == ColorChange && gcode(ColorChange).empty()) GUI::wxGetApp().plater()->get_notification_manager()->push_notification(GUI::NotificationType::EmptyColorChangeCode); @@ -439,14 +443,15 @@ void IMSlider::add_code_as_tick(Type type, int selected_extruder) if (it == m_ticks.ticks.end()) { // try to add tick - if (!m_ticks.add_tick(tick, type, extruder, m_values[tick])) return; + if (!m_ticks.add_tick(tick, type, extruder, m_values[tick])) return false; } else if (type == ToolChange || type == ColorChange) { // try to switch tick code to ToolChange or ColorChange accordingly - if (!m_ticks.switch_code_for_tick(it, type, extruder)) return; + if (!m_ticks.switch_code_for_tick(it, type, extruder)) return false; } else - return; + return false; post_ticks_changed_event(type); + return true; } void IMSlider::delete_tick(const TickCode& tick) { @@ -1793,9 +1798,9 @@ double IMSlider::get_double_value(const SelectedSlider &selection) return m_values[selection == ssLower ? m_lower_value : m_higher_value]; } -int IMSlider::get_tick_from_value(double value, bool force_lower_bound /* = false*/) +int IMSlider::get_tick_from_value(double value, bool force_lower_bound /* = false*/) const { - std::vector::iterator it; + std::vector::const_iterator it; if (m_is_wipe_tower && !force_lower_bound) it = std::find_if(m_values.begin(), m_values.end(), [value](const double &val) { return fabs(value - val) <= epsilon(); }); else diff --git a/src/slic3r/GUI/IMSlider.hpp b/src/slic3r/GUI/IMSlider.hpp index 4f02167669..1490496bc7 100644 --- a/src/slic3r/GUI/IMSlider.hpp +++ b/src/slic3r/GUI/IMSlider.hpp @@ -78,6 +78,9 @@ public: double GetLowerValueD() { return get_double_value(ssLower); } double GetHigherValueD() { return get_double_value(ssHigher); } SelectedSlider GetSelection() { return m_selection; } + // The tick of the layer at a height (mm): the first layer whose top is at or above it, or, on a plate + // with a wipe tower and without force_lower_bound, only a layer at that height. -1 when there is none. + int get_tick_from_value(double value, bool force_lower_bound = false) const; // Set low and high slider position. If the span is non-empty, disable the "one layer" mode. void SetLowerValue(const int lower_val); @@ -89,6 +92,8 @@ public: void SetSliderAlternateValues(const std::vector &values) { m_alternate_values = values; } CustomGCode::Info GetTicksValues() const; + // The codes by layer index (tick), as the menus show them. + const std::set& GetTicks() const { return m_ticks.ticks; } void SetTicksValues(const CustomGCode::Info &custom_gcode_per_print_z); void SetLayersTimes(const std::vector &layers_times, float total_time); void SetLayersTimes(const std::vector &layers_times); @@ -101,6 +106,11 @@ public: CustomGCode::Mode GetManipulationMode() const { return m_mode; } void SetModeAndOnlyExtruder(const bool is_one_extruder_printed_model, const int only_extruder, bool can_change_color); void SetExtruderColors(const std::vector &extruder_colors); + // The filaments the menus offer for a filament change, one colour each. + const std::vector& GetExtruderColors() const { return m_extruder_colors; } + // Whether the menus offer Change Filament: the plate's objects print with one filament, not in spiral vase + // mode and not by object. + bool can_change_color() const { return m_can_change_color; } bool IsNewPrint(); @@ -140,10 +150,14 @@ public: void on_change_color_mode(bool is_dark); void set_menu_enable(bool enable = true) { m_menu_enable = enable; } -protected: - void add_custom_gcode(std::string custom_gcode); - void add_code_as_tick(CustomGCode::Type type, int selected_extruder = -1); + // The menus' tick edits, on the layer `tick` or, with -1, on the active thumb's as the menus do. Each + // raises the event that hands the ticks to the plater at the next frame. add_code_as_tick returns + // whether the ticks changed; on a layer that holds a code it can only turn that code into a filament change. + void add_custom_gcode(std::string custom_gcode, int tick = -1); + bool add_code_as_tick(CustomGCode::Type type, int selected_extruder = -1, int tick = -1); void delete_tick(const TickCode& tick); + +protected: void do_go_to_layer(size_t layer_number); //menu void correct_lower_value(); void correct_higher_value(); @@ -169,7 +183,6 @@ protected: private: std::string get_label(int tick, LabelType label_type = ltHeightWithLayer); double get_double_value(const SelectedSlider& selection); - int get_tick_from_value(double value, bool force_lower_bound = false); float get_pos_from_value(int v_min, int v_max, int value, const ImRect& rect); int get_tick_near_point(int v_min, int v_max, const ImVec2& pt, const ImRect& rect); diff --git a/src/slic3r/GUI/IdleScheduler.hpp b/src/slic3r/GUI/IdleScheduler.hpp index 205b00c3d0..81600308f2 100644 --- a/src/slic3r/GUI/IdleScheduler.hpp +++ b/src/slic3r/GUI/IdleScheduler.hpp @@ -25,6 +25,7 @@ public: void clear() { m_queue.clear(); } // The task names in queue order, for a log line. std::string names() const { return m_queue.names(); } + bool pending() const { return m_queue.pending(); } // Arms the timer; it stops itself once no task is pending, so call again when a task // appears. diff --git a/src/slic3r/GUI/MainFrame.cpp b/src/slic3r/GUI/MainFrame.cpp index 05b2707750..0b6e21a7a6 100644 --- a/src/slic3r/GUI/MainFrame.cpp +++ b/src/slic3r/GUI/MainFrame.cpp @@ -4081,26 +4081,12 @@ void MainFrame::load_config_file() cfiles.push_back(into_u8(file)); m_last_config = file; } - bool update = false; - wxGetApp().preset_bundle->import_presets(cfiles, [this](std::string const & name) { + cfiles = import_configs(cfiles, [this](std::string const & name) { ConfigsOverwriteConfirmDialog dlg(this, from_u8(name), false); int res = dlg.ShowModal(); int ids[]{wxID_NO, wxID_YES, wxID_NOTOALL, wxID_YESTOALL}; return std::find(ids, ids + 4, res) - ids; - }, - ForwardCompatibilitySubstitutionRule::Enable, - *wxGetApp().app_config); - if (!cfiles.empty()) { - wxGetApp().app_config->update_config_dir(get_dir_name(cfiles.back())); - wxGetApp().load_current_presets(); - BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << " presets has been import,and size is" << cfiles.size(); - NetworkAgent* agent = wxGetApp().getAgent(); - if (agent) { - BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << " user is: " << agent->get_user_id(); - } - } - wxGetApp().preset_bundle->update_compatible(PresetSelectCompatibleType::Always); - update_side_preset_ui(); + }); auto msg = wxString::Format(_L_PLURAL("There is %d config imported. (Only non-system and compatible configs)", "There are %d configs imported. (Only non-system and compatible configs)", cfiles.size()), cfiles.size()); if(cfiles.empty()) @@ -4110,6 +4096,23 @@ void MainFrame::load_config_file() dlg2.ShowModal(); } +std::vector MainFrame::import_configs(std::vector files, std::function confirm) +{ + wxGetApp().preset_bundle->import_presets(files, confirm, ForwardCompatibilitySubstitutionRule::Enable, *wxGetApp().app_config); + if (!files.empty()) { + wxGetApp().app_config->update_config_dir(get_dir_name(files.back())); + wxGetApp().load_current_presets(); + BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << " presets has been import,and size is" << files.size(); + NetworkAgent* agent = wxGetApp().getAgent(); + if (agent) { + BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << " user is: " << agent->get_user_id(); + } + } + wxGetApp().preset_bundle->update_compatible(PresetSelectCompatibleType::Always); + update_side_preset_ui(); + return files; +} + // Load a config file containing a Print, Filament & Printer preset from command line. bool MainFrame::load_config_file(const std::string &path) { diff --git a/src/slic3r/GUI/MainFrame.hpp b/src/slic3r/GUI/MainFrame.hpp index d4ca99a5a2..748b92a836 100644 --- a/src/slic3r/GUI/MainFrame.hpp +++ b/src/slic3r/GUI/MainFrame.hpp @@ -420,6 +420,10 @@ public: void export_config(); // Query user for the config file and open it. void load_config_file(); + // Import preset files (.json, .zip, .orca_printer, .orca_filament, .orca_bundle) as the Import Configs + // dialog does, then refresh the presets. `confirm` answers for each preset that exists already + // (0 no, 1 yes, 2 no to all, 3 yes to all). Returns the files imported. + std::vector import_configs(std::vector files, std::function confirm); // Open a config file. Return true if loaded. bool load_config_file(const std::string &path); @@ -446,6 +450,7 @@ public: void select_prepare_for_gl_init(); // Builds the lazy tab pages while the user is idle; post_init() calls it once. void prebuild_pages_when_idle(); + bool prebuild_pending() const { return m_idle.pending(); } bool Show(bool show = true) override; int get_calibration_curr_tab(); void select_view(const std::string& direction); diff --git a/src/slic3r/GUI/Mcp/CanvasTarget.cpp b/src/slic3r/GUI/Mcp/CanvasTarget.cpp index d88f6c2736..b7d60c9626 100644 --- a/src/slic3r/GUI/Mcp/CanvasTarget.cpp +++ b/src/slic3r/GUI/Mcp/CanvasTarget.cpp @@ -125,7 +125,8 @@ std::string check_surface(const Vec3d& point, return "the point is on the side of the clipping plane that is cut away"; // What the ray meets, nearest first: each mesh's surfaces (a clipped mesh's only where the plane - // keeps them) and the bed. + // keeps them) and the bed, which only a ray looking down meets: from below it is drawn see-through + // and the GUI paints and picks through it. struct Hit { double t; @@ -141,7 +142,7 @@ std::string check_surface(const Vec3d& point, if (!(m.clipped && clip != nullptr && clip->is_point_clipped(h.p))) hits.push_back({h.t, h.p, h.n, &m}); } - if (std::abs(dir.z()) > 1e-9) { + if (dir.z() < -1e-9) { const double t = -origin.z() / dir.z(); const Vec3d p = origin + t * dir; if (t > 0. && on_bed(p)) diff --git a/src/slic3r/GUI/Mcp/CanvasTarget.hpp b/src/slic3r/GUI/Mcp/CanvasTarget.hpp index b86aa47e43..92f49806d3 100644 --- a/src/slic3r/GUI/Mcp/CanvasTarget.hpp +++ b/src/slic3r/GUI/Mcp/CanvasTarget.hpp @@ -57,10 +57,11 @@ struct SurfaceMesh // mesh at `point`, or empty when it would. `point` must lie on a target mesh, above the bed (the plane // z = 0 inside one of the `beds`, each plate's outline, scaled) and on the side of `clip` it keeps // when that mesh is clipped. The first thing the ray meets among `meshes` (clipped ones only where -// `clip` keeps them) and on the beds must be a target mesh near `point`: within `tolerance` plus twice -// the ray's distance from `point`, which a whole pixel adds, on a triangle whose plane holds `point` -// within `tolerance`. So on a slope the click may meet the point's surface a little nearer to the -// camera or beyond, but not another surface. +// `clip` keeps them) and on the beds (only looking down: from below the GUI draws and picks through +// them) must be a target mesh near `point`: within `tolerance` plus twice the ray's distance from +// `point`, which a whole pixel adds, on a triangle whose plane holds `point` within `tolerance`. So on +// a slope the click may meet the point's surface a little nearer to the camera or beyond, but not +// another surface. std::string check_surface(const Vec3d& point, const std::pair& ray, const std::vector& meshes, diff --git a/src/slic3r/GUI/Mcp/McpCore.cpp b/src/slic3r/GUI/Mcp/McpCore.cpp index 69ee054605..530b0b9f13 100644 --- a/src/slic3r/GUI/Mcp/McpCore.cpp +++ b/src/slic3r/GUI/Mcp/McpCore.cpp @@ -21,6 +21,12 @@ namespace Slic3r { namespace GUI { namespace Mcp { namespace { +// What a mutating call is told while another job's operation holds the project. +std::string busy_message(const std::string& op) +{ + return "Busy: job " + op + " is running an operation (slice, export, arrange or another background job); wait for it or cancel it"; +} + class CallContext final : public ToolContext { public: @@ -30,21 +36,36 @@ public: nlohmann::json run_ui(const std::function& fn) override { - if (m_def.guard != GuardClass::Mutate || m_def.allowed_during_operation) + if (m_def.guard == GuardClass::Inspect) return m_core.ui().run(m_def.guard, m_def.name, fn); - // Admission again on the UI thread, where operations start: a call admitted before an - // operation began must not change the project under it. + const bool admit = m_def.guard == GuardClass::Mutate && !m_def.allowed_during_operation; return m_core.ui().run(m_def.guard, m_def.name, [&]() -> nlohmann::json { - for (const std::string& op : m_core.jobs().running_operations()) - if (op != m_job) - throw ToolFailure("Busy: job " + op + " (a slice or export) is running; wait for it or cancel it before changing the project", - {{"job", op}}); - return fn(); + // Admission again on the UI thread, where operations and worker jobs start: a call admitted + // before one began must not change the project under it. + if (admit) + m_core.admit(m_job); + if (!m_core.worker_busy()) + m_saw_idle = true; + nlohmann::json out; + try { + out = fn(); + } catch (...) { + claim_worker(); + throw; + } + claim_worker(); + return out; }); } nlohmann::json observe_ui(const std::function& fn) override { - return m_core.ui().run(GuardClass::Inspect, m_def.name, fn); + // A job the call's change queued for later (a toolbar event, a render) starts between its + // closures; the next one the call makes claims it. + return m_core.ui().run(GuardClass::Inspect, m_def.name, [&]() -> nlohmann::json { + nlohmann::json out = fn(); + claim_worker(); + return out; + }); } const std::string& job_id() const override { return m_job; } bool cancelled() const override { return m_core.ui().is_shutdown(); } @@ -76,16 +97,25 @@ public: if (m_job.empty()) return; if (const std::string other = m_core.jobs().begin_operation(m_job); !other.empty()) - throw ToolFailure("Busy: job " + other + " (a slice or export) is running; wait for it or cancel it", {{"job", other}}); + throw ToolFailure(busy_message(other), {{"job", other}}); } private: + // A worker job is the call's own when the worker was idle as one of its changes began and is busy + // now. UI thread. + void claim_worker() + { + if (m_saw_idle) + m_core.claim_worker(m_job); + } + McpCore& m_core; const ToolDef& m_def; std::string m_job; std::string m_parent; Journal* m_journal; uint64_t m_seq; + bool m_saw_idle = false; // UI thread }; ToolResult invoke(const ToolDef& def, const nlohmann::json& args, ToolContext& ctx) @@ -103,8 +133,8 @@ ToolResult invoke(const ToolDef& def, const nlohmann::json& args, ToolContext& c } // namespace -McpCore::McpCore(const ToolRegistry& registry, UiInvoker& ui, JobRegistry& jobs, Journal* journal, CoreTiming timing) - : m_registry(registry), m_ui(ui), m_jobs(jobs), m_journal(journal), m_timing(timing) +McpCore::McpCore(const ToolRegistry& registry, UiInvoker& ui, JobRegistry& jobs, Journal* journal, CoreTiming timing, WorkerHooks worker) + : m_registry(registry), m_ui(ui), m_jobs(jobs), m_journal(journal), m_timing(timing), m_worker(std::move(worker)) {} McpCore::~McpCore() @@ -147,7 +177,7 @@ ToolResult McpCore::run(const ToolDef& def, const nlohmann::json& args, const st // Only client calls are journaled; a script's own steps replay through the script. const bool journal = m_journal != nullptr && parent.empty() && def.journal; - const uint64_t seq = journal ? m_journal->begin(def.name, args) : 0; + const uint64_t seq = journal ? m_journal->begin(def.name, args, def.guard == GuardClass::Recover && !m_ui.open_dialogs().empty()) : 0; auto finish = [&](ToolResult r) { if (journal) m_journal->end(seq, r); @@ -164,13 +194,11 @@ ToolResult McpCore::run(const ToolDef& def, const nlohmann::json& args, const st return finish(std::move(r)); } - // Operation admission: an MCP slice/export holds the project until it finishes; only recovery + // Operation admission: an MCP operation holds the project until it finishes; only recovery // input and the tools that may run during an operation (cancel) get through. if (def.guard == GuardClass::Mutate && !def.allowed_during_operation) if (const auto busy = m_jobs.running_operations(); !busy.empty()) - return finish(ToolResult::error("Busy: job " + busy.front() + - " (a slice or export) is running; wait for it or cancel it before changing the project", - {{"job", busy.front()}})); + return finish(ToolResult::error(busy_message(busy.front()) + " before changing the project", {{"job", busy.front()}})); std::string job; try { @@ -178,6 +206,8 @@ ToolResult McpCore::run(const ToolDef& def, const nlohmann::json& args, const st } catch (const ToolFailure& f) { return finish(ToolResult::error(f.what())); } + if (journal) + m_journal->job_started(seq, job); if (!enter()) { m_jobs.finish(job, ToolResult::error("OrcaSlicer is shutting down")); @@ -188,7 +218,10 @@ ToolResult McpCore::run(const ToolDef& def, const nlohmann::json& args, const st try { std::thread([this, def, args, job, parent, seq]() { CallContext ctx(*this, def, job, parent, m_journal, seq); - ToolResult result = invoke(def, args, ctx); + ToolResult result = await_worker(job, def.name, invoke(def, args, ctx)); + // Before finish(): an export_script right after the wait that sees the result must know it. + if (seq != 0) + m_journal->job_ended(seq, result); m_jobs.finish(job, std::move(result)); leave(); }).detach(); @@ -262,6 +295,103 @@ ToolResult McpCore::run(const ToolDef& def, const nlohmann::json& args, const st return finish(envelope("running", {{"note", running_note}})); } +void McpCore::admit(const std::string& job) const +{ + for (const std::string& op : m_jobs.running_operations()) + if (op != job) + throw ToolFailure(busy_message(op) + " before changing the project", {{"job", op}}); + if (!worker_busy()) + return; + { + std::lock_guard lock(m_worker_mutex); + if (!job.empty() && m_worker_job == job) + return; + } + throw ToolFailure("Busy: a background job (arrange, orient, fill bed, or one a gizmo started, such as Text typing) is " + "running in OrcaSlicer; wait {for:\"idle\"} before changing the project"); +} + +bool McpCore::worker_busy() const { return m_worker.busy && m_worker.busy(); } + +bool McpCore::claim_worker(const std::string& job) +{ + if (job.empty() || !worker_busy()) + return false; + { + std::lock_guard lock(m_worker_mutex); + if (!m_worker_job.empty()) + return m_worker_job == job; + } + // Under another call's operation (a dialog answer during a slice) the job stays unclaimed; the + // busy worker still keeps other changes out. + if (!m_jobs.begin_operation(job).empty()) + return false; + std::lock_guard lock(m_worker_mutex); + m_worker_job = job; + m_worker_cancelled = false; + return true; +} + +bool McpCore::cancel_worker(const std::string& job) +{ + { + std::lock_guard lock(m_worker_mutex); + if (job.empty() || m_worker_job != job) + return false; + m_worker_cancelled = true; + } + if (m_worker.cancel) + m_worker.cancel(); + return true; +} + +ToolResult McpCore::await_worker(const std::string& job, const std::string& tool, ToolResult result) +{ + { + std::lock_guard lock(m_worker_mutex); + if (m_worker_job != job) + return result; + } + // Worker::cancel() does not wait, so after a cancel the job keeps admission until the worker is + // really idle: until then the job may still touch the model. + const auto deadline = std::chrono::steady_clock::now() + m_timing.worker_timeout; + bool timed_out = false; + while (!m_ui.is_shutdown()) { + bool busy = true; + try { + busy = m_ui.run(GuardClass::Inspect, tool, [&] { + if (!timed_out && std::chrono::steady_clock::now() >= deadline) + timed_out = cancel_worker(job); + return nlohmann::json(worker_busy()); + }).get(); + } catch (const ToolFailure&) { + // Not run (a native dialog holds the UI thread, or the UI is being rebuilt); ask again. + } + if (!busy) + break; + std::this_thread::sleep_for(m_timing.worker_poll); + } + bool cancelled = false; + { + std::lock_guard lock(m_worker_mutex); + cancelled = m_worker_cancelled; + m_worker_job.clear(); + m_worker_cancelled = false; + } + if (m_ui.is_shutdown()) + return ToolResult::error("OrcaSlicer is shutting down"); + if (result.is_error) + return result; + if (timed_out) + return ToolResult::error("The background job this call started did not finish within " + + std::to_string(std::chrono::duration_cast(m_timing.worker_timeout).count()) + + " s, so it was cancelled", + {{"job", job}}); + if (cancelled) + return ToolResult::error("The background job this call started was cancelled", {{"job", job}}); + return result; +} + bool McpCore::acquire_slot() { std::lock_guard lock(m_slots_mutex); diff --git a/src/slic3r/GUI/Mcp/McpCore.hpp b/src/slic3r/GUI/Mcp/McpCore.hpp index 19ed192808..df1aad5d15 100644 --- a/src/slic3r/GUI/Mcp/McpCore.hpp +++ b/src/slic3r/GUI/Mcp/McpCore.hpp @@ -22,16 +22,33 @@ struct CoreTiming std::chrono::milliseconds soft_budget{1500}; // before probing for a blocking dialog std::chrono::milliseconds probe_timeout{1000}; int blocking_slots = 32; + // How long a call waits for a worker job it started before cancelling it, and how often it looks. + std::chrono::milliseconds worker_timeout{std::chrono::minutes(30)}; + std::chrono::milliseconds worker_poll{50}; +}; + +// The app's UI job worker (arrange, orient, fill bed, the Text, SVG and texture gizmos' jobs), which a +// call can start as a person's click does. Both run on the UI thread; without them nothing is busy. +struct WorkerHooks +{ + std::function busy; // a job is queued, running or not yet finalized + std::function cancel; // asks the running job to stop, without waiting for it }; // Executes tool calls for the protocol layer and for scripts: observation tools inline on the // calling thread, everything else as a job on a thread of its own, with the reply budget, the // blocked-by-dialog probe, blocking slots, operation admission and the session journal. Independent // of wx so the threading contract is unit-testable with a hand-driven UiDispatcher. +// +// A call that finds the UI job worker idle and leaves it busy has started a worker job, whichever +// tool or input did it, and that job is its operation: the call holds admission, and its job ends, +// only once the worker is idle again, finalization included, since the job keeps pointers into the +// model until then. class McpCore : public ToolCaller { public: - McpCore(const ToolRegistry& registry, UiInvoker& ui, JobRegistry& jobs, Journal* journal, CoreTiming timing = {}); + McpCore(const ToolRegistry& registry, UiInvoker& ui, JobRegistry& jobs, Journal* journal, CoreTiming timing = {}, + WorkerHooks worker = {}); // Refuses new calls and waits for every call and job thread to leave, however long that takes: // they use the core. The owner drains first, so this returns at once. ~McpCore() override; @@ -52,14 +69,38 @@ public: UiInvoker& ui() { return m_ui; } JobRegistry& jobs() { return m_jobs; } + // Operation admission for a change made by `job` ("" for a call that holds nothing), on the UI + // thread: throws ToolFailure while another job's operation holds the project, or while the UI job + // worker runs a job `job` does not hold (a person's, such as Text typing). Mutate calls get it in + // every UI closure; the GUI input tools apply it once their target is outside the topmost modal. + void admit(const std::string& job) const; + // UI thread. Whether the UI job worker has a job queued, running or left to finalize. + bool worker_busy() const; + // UI thread. Makes the busy worker's job `job`'s operation unless another call holds it or another + // operation runs; true when `job` holds it. + bool claim_worker(const std::string& job); + // UI thread. When `job` holds the UI job worker, asks its job to stop and returns true. The call + // keeps admission until the worker is idle, then fails as cancelled. + bool cancel_worker(const std::string& job); + private: ToolResult run(const ToolDef& def, const nlohmann::json& args, const std::string& parent); + // On `job`'s thread once its handler returned: when it holds the UI job worker, waits until the + // worker is idle, cancelling the job after CoreTiming::worker_timeout, and then lets it go. The + // result becomes a failure when the job was cancelled or timed out. + ToolResult await_worker(const std::string& job, const std::string& tool, ToolResult result); const ToolRegistry& m_registry; UiInvoker& m_ui; JobRegistry& m_jobs; Journal* m_journal; CoreTiming m_timing; + WorkerHooks m_worker; + + // The job whose call started the worker's current job, and whether a cancel was asked for it. + mutable std::mutex m_worker_mutex; + std::string m_worker_job; + bool m_worker_cancelled = false; // Requests that may block (a job within its reply budget, or wait) hold a slot, so the number of // blocked request threads stays below the connection limit and recovery calls always get through. diff --git a/src/slic3r/GUI/Mcp/McpJournal.cpp b/src/slic3r/GUI/Mcp/McpJournal.cpp index d7fa7fd44e..63c98edbda 100644 --- a/src/slic3r/GUI/Mcp/McpJournal.cpp +++ b/src/slic3r/GUI/Mcp/McpJournal.cpp @@ -7,26 +7,33 @@ #include #include #include +#include #include #include #include #include +#include namespace Slic3r { namespace GUI { namespace Mcp { -uint64_t Journal::begin(const std::string& tool, const nlohmann::json& args) +uint64_t Journal::begin(const std::string& tool, const nlohmann::json& args, bool answers_dialog) { std::lock_guard lock(m_mutex); + if (answers_dialog) + for (Entry& running : m_entries) + if (!running.job.empty() && !running.job_ended) + running.dialog_answered = true; Entry e; - e.seq = m_next++; - e.tool = tool; - e.args = args; + e.seq = m_next++; + e.tool = tool; + e.args = args; + e.answers_dialog = answers_dialog; m_entries.push_back(std::move(e)); // A session kept open for days must not grow without bound; a script is exported from the - // recent calls anyway (export_script {clear:true} starts afresh). The oldest call that has - // replied goes; a call still waiting for its reply keeps its place. + // recent calls anyway (export_script {clear:true} starts afresh). The oldest call whose outcome + // is known goes; a call still waiting for its reply or its job keeps its place. if (m_entries.size() > kMaxEntries) { - const auto oldest = std::find_if(m_entries.begin(), m_entries.end(), [](const Entry& entry) { return entry.finished; }); + const auto oldest = std::find_if(m_entries.begin(), m_entries.end(), [](const Entry& entry) { return !entry.running(); }); if (oldest != m_entries.end()) m_entries.erase(oldest); } @@ -46,10 +53,35 @@ void Journal::end(uint64_t seq, const ToolResult& result) std::lock_guard lock(m_mutex); for (Entry& e : m_entries) if (e.seq == seq) { - e.finished = true; - e.failed = result.is_error; - if (!result.is_error && result.data.is_object() && result.data.contains("job") && result.data.contains("status")) - e.job = result.data["job"].get(); + e.finished = true; + e.failed = e.failed || result.is_error; + e.menu_listed = !result.is_error && result.data.is_object() && result.data.contains("popup_menu"); + // The envelope names the call's own job; a `wait` that timed out names another one. + if (result.is_error || e.job.empty() || !result.data.is_object()) + continue; + const auto job = result.data.find("job"); + const auto status = result.data.find("status"); + if (job != result.data.end() && job->is_string() && job->get() == e.job && status != result.data.end() && + (*status == "running" || *status == "blocked_by_dialog")) + e.envelope = status->get(); + } +} + +void Journal::job_started(uint64_t seq, const std::string& job) +{ + std::lock_guard lock(m_mutex); + for (Entry& e : m_entries) + if (e.seq == seq) + e.job = job; +} + +void Journal::job_ended(uint64_t seq, const ToolResult& result) +{ + std::lock_guard lock(m_mutex); + for (Entry& e : m_entries) + if (e.seq == seq) { + e.job_ended = true; + e.failed = e.failed || result.is_error; } } @@ -59,13 +91,34 @@ void Journal::clear() m_entries.clear(); } -nlohmann::json Journal::to_script(const std::string& name) const +nlohmann::json Journal::to_script(const std::string& name, nlohmann::json* left_out_running) const { std::lock_guard lock(m_mutex); nlohmann::json steps = nlohmann::json::array(); std::map job_names; // live job id -> script name - for (const Entry& e : m_entries) { - if (e.failed) + if (left_out_running != nullptr) + *left_out_running = nlohmann::json::array(); + // Whether the next call in the script is `e` again, choosing an item of the menu it listed. + auto repeated_with_item = [this](std::vector::const_iterator e) { + const auto next = std::find_if(std::next(e), m_entries.end(), [](const Entry& n) { return n.kept(); }); + if (next == m_entries.end() || next->tool != e->tool || !next->args.is_object() || !next->args.contains("popup_item")) + return false; + nlohmann::json args = next->args; + args.erase("popup_item"); + return args == e->args; + }; + for (auto it = m_entries.begin(); it != m_entries.end(); ++it) { + const Entry& e = *it; + if (!e.kept()) { + if (!e.failed && left_out_running != nullptr) { + nlohmann::json call{{"tool", e.tool}}; + if (!e.job.empty()) + call["job"] = e.job; + left_out_running->push_back(std::move(call)); + } + continue; + } + if (e.menu_listed && repeated_with_item(it)) continue; nlohmann::json step{{"tool", e.tool}, {"args", e.args}}; if (e.tool == "wait" && e.args.value("for", "") == "job") { @@ -78,12 +131,14 @@ nlohmann::json Journal::to_script(const std::string& name) const const std::string file = path_to_utf8(path_from_utf8(e.args["save_path"].get()).filename()); step["args"]["save_path"] = "${out_dir}/" + file; } - if (!e.job.empty()) { + if (e.unawaited()) { const std::string job_name = "job" + std::to_string(job_names.size() + 1); job_names[e.job] = job_name; step["await"] = false; step["save_as"] = job_name; } + if (e.answers_dialog) + steps.push_back({{"tool", "wait"}, {"args", {{"for", "dialog"}, {"timeout_s", 50}}}, {"expect", {{"/satisfied", {{"eq", true}}}}}}); steps.push_back(std::move(step)); } return {{"orca_script", 1}, {"name", name}, {"steps", std::move(steps)}}; diff --git a/src/slic3r/GUI/Mcp/McpJournal.hpp b/src/slic3r/GUI/Mcp/McpJournal.hpp index 9351ad3ac1..8fec47b88f 100644 --- a/src/slic3r/GUI/Mcp/McpJournal.hpp +++ b/src/slic3r/GUI/Mcp/McpJournal.hpp @@ -14,19 +14,38 @@ namespace Slic3r { namespace GUI { namespace Mcp { // The session's client calls, in the order they were made, for export_script. A call that returned // a job envelope is replayed with `await:false` and a name its later `wait` refers to, so a step -// that opened a dialog can be followed by the steps that answered it. Thread-safe. +// that opened a dialog can be followed by the steps that answered it. An input call that only listed +// the menu it opened is kept, since it may have changed the selection, unless the next call repeats +// it with a popup_item. +// +// A call that runs as a job takes its job's final result, not its reply: a job that fails after its +// reply came back as running is left out like a call that failed at once, and one still running is +// left out because its outcome is not known yet. A job whose reply said it waits on a dialog stays +// in the script whatever becomes of it, since the steps after it answer that dialog. So does a job +// that was running while a later call answered a dialog: the dialog may be one the job opened, after +// its reply or before it, and the answer depends on it. Such a job replays with `await:false`, and a +// call that answered a dialog replays after a `wait {for:"dialog"}`, since the dialog may open later +// than the job's replayed reply. Thread-safe. class Journal { public: // Starts an entry; returns its sequence number. Calls made by scripts are not recorded. - uint64_t begin(const std::string& tool, const nlohmann::json& args); + // `answers_dialog`: the call acts while a modal dialog is open (dialog_respond, input to it). + uint64_t begin(const std::string& tool, const nlohmann::json& args, bool answers_dialog = false); void set_args(uint64_t seq, nlohmann::json args); + // The call's reply. void end(uint64_t seq, const ToolResult& result); + // The call runs as `job`; its outcome is open until job_ended(). + void job_started(uint64_t seq, const std::string& job); + // The job's final result, reported before a `wait` on the job can see it, so an export right + // after that wait already knows the outcome. + void job_ended(uint64_t seq, const ToolResult& result); void clear(); // {"orca_script":1, "name":..., "steps":[...]} with job names substituted and screenshot paths - // rewritten to ${out_dir}/. - nlohmann::json to_script(const std::string& name) const; + // rewritten to ${out_dir}/. The calls left out because their outcome is still open go + // to `left_out_running` as [{tool, job}] (no job for a call that is not one). + nlohmann::json to_script(const std::string& name, nlohmann::json* left_out_running = nullptr) const; private: struct Entry @@ -34,9 +53,21 @@ private: uint64_t seq = 0; std::string tool; nlohmann::json args; - bool finished = false; - bool failed = false; - std::string job; // set when the reply was a job envelope + bool finished = false; // the call replied + bool failed = false; // the reply, or the job's final result, was an error + bool menu_listed = false; // the reply listed a menu the call opened (popup_menu) + std::string job; // the call's job, when it runs as one + bool job_ended = false; + std::string envelope; // "running" or "blocked_by_dialog" when the reply was the job's envelope + bool dialog_answered = false; // a later call answered a dialog while the job ran + bool answers_dialog = false; // the call acted while a modal dialog was open + + // Whether the outcome is still open: the call has not replied, or its job has not ended. + bool running() const { return job.empty() ? !finished : !job_ended; } + // Whether the call goes into a script. + bool kept() const { return envelope == "blocked_by_dialog" || dialog_answered || (!failed && !running()); } + // Whether the step replays without waiting for its job: the steps after it answer its dialog. + bool unawaited() const { return !envelope.empty() || dialog_answered; } }; mutable std::mutex m_mutex; diff --git a/src/slic3r/GUI/Mcp/McpService.cpp b/src/slic3r/GUI/Mcp/McpService.cpp index a329b97a3b..5f4a0e301f 100644 --- a/src/slic3r/GUI/Mcp/McpService.cpp +++ b/src/slic3r/GUI/Mcp/McpService.cpp @@ -12,9 +12,12 @@ #include "UiInspector.hpp" #include "McpPaths.hpp" #include "slic3r/GUI/SyntheticInput.hpp" +#include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/GUI_App.hpp" #include "slic3r/GUI/ImGuiWrapper.hpp" +#include "slic3r/GUI/Jobs/Worker.hpp" #include "slic3r/GUI/MainFrame.hpp" +#include "slic3r/GUI/Plater.hpp" #include "libslic3r/AppConfig.hpp" #include "libslic3r/Utils.hpp" @@ -28,6 +31,8 @@ #include #include +#include +#include #include #include @@ -87,6 +92,36 @@ public: } }; +// Whether the Prepare canvas has loaded OpenGL: its functions, shaders and the ImGui font. +bool canvas_gl_ready() +{ + Plater* plater = wxGetApp().plater(); + GLCanvas3D* canvas = plater != nullptr ? plater->canvas3D() : nullptr; + return canvas == nullptr || canvas->is_initialized(); +} + +// Whether the main window has tab pages still to build at idle. +bool pages_pending() +{ + const MainFrame* frame = wxGetApp().mainframe; + return frame != nullptr && frame->prebuild_pending(); +} + +// The Plater's UI job worker, as McpCore watches it for jobs that calls start. +WorkerHooks ui_job_worker_hooks() +{ + WorkerHooks hooks; + hooks.busy = [] { + Plater* plater = wxGetApp().plater(); + return plater != nullptr && !plater->get_ui_job_worker().is_idle(); + }; + hooks.cancel = [] { + if (Plater* plater = wxGetApp().plater()) + plater->get_ui_job_worker().cancel(); + }; + return hooks; +} + // Server instructions shown to the model; clients truncate them at 4096 characters. const char* kInstructions = "OrcaSlicer, a 3D-printing slicer, driven through its GUI.\n" @@ -99,7 +134,8 @@ const char* kInstructions = "running: never retry it. Answer dialogs with dialog_respond (see get_state.dialogs), then wait {for:\"job\"}. " "A dialog marked native: true (a file or folder picker, a message box) can't be answered; register " "dialog_auto_answer before the step that opens one.\n" - "- While a slice or export runs, other changes are refused; use wait or cancel.\n" + "- While an operation (slice, export, arrange or another background job) runs, other changes are refused; use wait " + "or cancel.\n" "- Paths are absolute. Outputs never overwrite an existing file unless overwrite is true.\n" "- screenshot returns a downscaled image plus the full-size PNG path; target \"canvas\" is the 3D view.\n" "- export_script saves this session's calls as a replayable script; run_script replays one."; @@ -159,9 +195,11 @@ bool McpService::start(const McpLaunchOptions& options, bool serve, std::string& m_modals = std::make_unique(); m_inspector = std::make_unique(*this); m_invoker = std::make_unique(*m_dispatcher, [this] { return guards_on_ui(); }, [this] { return m_generation.load(); }, - [this] { return m_modals->snapshot(); }); - m_core = std::make_unique(m_registry, *m_invoker, m_jobs, &m_journal); + [this] { return m_modals->snapshot(); }, + [this](const std::string& tool, bool running) { m_inspector->ui_activity(tool, running); }); + m_core = std::make_unique(m_registry, *m_invoker, m_jobs, &m_journal, CoreTiming{}, ui_job_worker_hooks()); register_tools(); + m_inspector->capture_menus(true); if (ImGuiWrapper* imgui = wxGetApp().imgui()) imgui->set_item_recording(true); } @@ -268,6 +306,8 @@ void McpService::stop() if (m_core == nullptr || m_stopping.exchange(true)) return; BOOST_LOG_TRIVIAL(info) << "MCP server stopping"; + if (m_ready_timer) + m_ready_timer->Stop(); // Wake everything that waits, so running calls return. m_invoker->shutdown(); m_jobs.wake_all(); @@ -283,8 +323,10 @@ void McpService::stop() m_modals->pop_rules(layer); m_script_rule_layers.clear(); } - if (m_inspector) + if (m_inspector) { m_inspector->release_held(nullptr); + m_inspector->capture_menus(false); + } SyntheticInput::clear(); if (wxTheApp != nullptr) if (ImGuiWrapper* imgui = wxGetApp().imgui()) @@ -407,8 +449,39 @@ void McpService::resume() void McpService::mark_ready() { - if (m_ready.exchange(true)) + if (m_ready || m_ready_timer) return; + // Starting on Home, the Prepare canvas loads OpenGL at idle after post_init(), and until then a + // 3MF save draws its thumbnail with no GL functions loaded. The main window builds its tab pages + // at idle then too, and a page's web view registers its "wx" handler with a script it waits for in + // a nested loop; on GTK, calls that came in meanwhile have left that wait unfinished for good, + // and with it every later web view's window.wx, a dialog page's own buttons included. So ready + // waits for the canvas and the pages. When the hidden canvas can't get a GL context, the first + // draw of Prepare loads it instead, and the pages build only while no input comes, so ready stops + // waiting after 10 s. + const auto settled = [] { return canvas_gl_ready() && !pages_pending(); }; + if (settled()) { + set_ready(); + return; + } + const auto since = std::chrono::steady_clock::now(); + m_ready_timer = std::make_unique(); + m_ready_timer->Bind(wxEVT_TIMER, [this, since, settled](wxTimerEvent&) { + if (m_stopping || (!settled() && std::chrono::steady_clock::now() - since < std::chrono::seconds(10))) + return; + m_ready_timer->Stop(); + if (!canvas_gl_ready()) + BOOST_LOG_TRIVIAL(warning) << "MCP ready before the 3D view loaded OpenGL"; + if (pages_pending()) + BOOST_LOG_TRIVIAL(warning) << "MCP ready before the main window built its tab pages"; + set_ready(); + }); + m_ready_timer->Start(100); +} + +void McpService::set_ready() +{ + m_ready = true; if (!m_options.script.empty()) run_launch_script(); } @@ -435,6 +508,7 @@ void McpService::register_tools() register_project_tools(*this); register_config_tools(*this); register_scene_tools(*this); + register_layer_tools(*this); register_view_tools(*this); register_ui_tools(*this); register_script_tools(*this); diff --git a/src/slic3r/GUI/Mcp/McpService.hpp b/src/slic3r/GUI/Mcp/McpService.hpp index 25be98ef8f..5edda9fb14 100644 --- a/src/slic3r/GUI/Mcp/McpService.hpp +++ b/src/slic3r/GUI/Mcp/McpService.hpp @@ -22,6 +22,8 @@ #include #include +class wxTimer; + namespace Slic3r { namespace GUI { namespace Mcp { class McpHttpServer; @@ -75,7 +77,8 @@ public: void resume(); bool suspended() const { return m_suspended; } - // The main frame finished starting up (end of GUI_App::post_init). + // The main frame finished starting up (end of GUI_App::post_init). Ready follows once the Prepare + // canvas has loaded OpenGL, at once when it already has. void mark_ready(); bool ready() const { return m_ready && !m_suspended; } @@ -125,6 +128,7 @@ private: ~McpService(); void register_tools(); + void set_ready(); void run_launch_script(); GuardState guards_on_ui() const; @@ -153,6 +157,8 @@ private: bool m_endpoint_open = false; std::atomic m_ready{false}; + // Polls for the Prepare canvas's OpenGL between mark_ready() and ready. UI thread. + std::unique_ptr m_ready_timer; std::atomic m_suspended{false}; std::atomic m_stopping{false}; std::atomic m_generation{1}; diff --git a/src/slic3r/GUI/Mcp/McpTools.hpp b/src/slic3r/GUI/Mcp/McpTools.hpp index 943a045091..0f1fa3dc14 100644 --- a/src/slic3r/GUI/Mcp/McpTools.hpp +++ b/src/slic3r/GUI/Mcp/McpTools.hpp @@ -2,6 +2,11 @@ #include "McpTypes.hpp" +#include "libslic3r/CustomGCode.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/Slicing.hpp" +#include "slic3r/GUI/GLCanvas3D.hpp" + #include #include @@ -14,8 +19,23 @@ #include #include -namespace Slic3r { namespace GUI { +namespace Slic3r { +class AppConfig; +struct Calib_Params; +class ConfigOptionDef; +class DynamicPrintConfig; +class ModelObject; +class ModelVolume; +enum class ModelVolumeType : int; +class Preset; +class PresetCollection; +struct GCodeProcessorResult; +namespace CustomGCode { struct Info; } + +namespace GUI { + +class IMSlider; class Plater; namespace Mcp { @@ -70,6 +90,146 @@ bool arg_bool(const nlohmann::json& args, const char* key, bool fallback) // 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 = {}); +// ---- settings scopes (McpToolsConfig.cpp) ---------------------------------------------------- + +// The keys the object scope (or, with `is_part`, the volume scope) takes: those of `offered` +// (SettingsFactory::get_options()) that the object list offers with `filaments` filament slots, and +// extruder, the object's or part's filament. +std::vector model_scope_options(const std::vector& offered, bool is_part, int filaments); + +// What `key` is for an object (`volume` null) or one of its parts, and where it comes from: +// {"effective", "source"}, the part's override ("part"), else the object's ("object"), else the +// process's ("process"), else the option's default ("default"; extruder 1). An extruder of 0 is no +// override. For an object, "parts" lists [{volume, value}] for the parts and modifiers overriding +// `key`, each applying only inside its own volume. +nlohmann::json effective_setting(const std::string& key, const DynamicPrintConfig& process, const ModelObject& object, + const ModelVolume* volume); + +// Checks save_preset's `name` against `presets` as the Save preset dialog does, and returns whether the +// preset is kept inside the project: where an existing preset of that name is, else `inside_project`, +// else where the edited preset is. Throws ToolFailure for a name the dialog refuses, for replacing +// another existing preset without `overwrite`, and for an `inside_project` that contradicts where the +// existing preset is, which the dialog does not let a person change. +bool save_preset_inside_project(const PresetCollection& presets, const std::string& name, const nlohmann::json& args); + +// get_settings' meta of an option: label, type, mode, category, unit, tooltip, range, and for an enum its +// values with their labels (the untranslated texts the GUI shows), in the same order. +nlohmann::json option_meta(const ConfigOptionDef& def); + +// 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` +// and `nozzle_volume_types` are the printer's and the project's, one per extruder. Null for any other key. +nlohmann::json variant_entries(const std::string& key, const DynamicPrintConfig& config, const std::vector& extruder_types, + const std::vector& nozzle_volume_types); + +// The serialized value set_settings writes for `key` of the preset whose config is `config`: `value` +// itself, or for {"index": i, "value": v} the whole vector with entry i replaced, as editing one variant +// in the tab leaves it. Throws ToolFailure, naming the entries, for a value with another number of +// entries than a per-variant or per-extruder vector of several (a scalar would collapse it), and for a +// bad index or entry. +std::string preset_setting_value(const std::string& key, const nlohmann::json& value, const DynamicPrintConfig& config, + const std::vector& extruder_types, const std::vector& nozzle_volume_types); + +// The settings among `keys` that differ between two presets of one type, as the Compare presets dialog +// finds them: [{key, value, other}], or with "index" for one entry of a printer or filament vector. +// Values are serialized, and null where a preset lacks the key or entry. Bookkeeping *_settings_id keys +// are left out. +nlohmann::json preset_diff(const Preset& left, const Preset& right, const std::vector& keys); + +// set_settings' "changed": {key: value} for every key whose value differs between `before` and `after`, +// with null for a key `after` no longer has. +nlohmann::json changed_settings(const DynamicPrintConfig& before, const DynamicPrintConfig& after); + +// The keys of `changes`, unsaved changes as the tab marks them ({key: value}, or key#index for one entry of +// a vector), whose value `config` no longer holds; each key once. +nlohmann::json discarded_changes(const nlohmann::json& changes, const DynamicPrintConfig& config); + +// The process, filament and printer presets being edited that have unsaved changes: +// {type: {name, changes: {key or key#index: value}}}. UI thread. +nlohmann::json unsaved_changes(); + +// What a call did to the unsaved changes `before` (from unsaved_changes()): "discarded", the keys whose +// value is gone, and "modified", the keys still unsaved, each {type: {name, keys}} with only the presets +// that have keys, and left out when there are none. UI thread. +nlohmann::json unsaved_changes_outcome(const nlohmann::json& before); + +// Checks that delete_preset may delete the preset `name` of `presets`, as the GUI offers and checks it, and +// returns the presets deleted with it: for a custom printer (a base printer that is not a system one), +// {"process": [names], "filament": [names]} of the user presets of `prints` and `filaments` made for it +// alone; otherwise an empty object. Throws ToolFailure for an unknown name (with similar names), a system, +// default or bundle preset, a base preset other presets inherit from (details: inherited_by), and a custom +// printer with presets attached unless `delete_attached` (details: attached). +nlohmann::json check_preset_deletable(const PresetCollection& presets, const std::string& name, bool delete_attached, + const PresetCollection& prints, const PresetCollection& filaments); + +// The project scope's filament_colour to write: one colour per slot of `current`, each #RRGGBB (stored in +// upper case, as the colour pickers store it) or the slot's current colour in any case. `mixed` flags the +// mixed slots, whose colour comes from their components and cannot change. Throws ToolFailure otherwise. +std::vector check_filament_colours(std::vector colours, const std::vector& current, + const std::vector& mixed); + +// The project scope's flush_multiplier to write: one per nozzle, or one value for all, each within the +// Flushing volumes dialog's 0..3. Throws ToolFailure otherwise. +std::vector check_flush_multipliers(std::vector multipliers, std::size_t nozzles); + +// The project scope's flush_volumes_matrix to write: per nozzle, `slots` x `slots` volumes (row = from, +// column = to) in config order over every slot, as project_config and the G-code header hold it, limited +// as the Flushing volumes dialog limits them (g_max_flush_volume / the nozzle's multiplier). Throws +// ToolFailure for another length, a negative volume, a non-zero diagonal, or a changed entry of a mixed +// slot (flagged in `mixed`), which is never flushed and which the dialog keeps as `current` holds it. +std::vector check_flush_matrix(std::vector matrix, std::size_t slots, const std::vector& multipliers, + const std::vector& current, const std::vector& mixed); + +// 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); + +// A plate's other_layers_print_sequence from [{from, to?, order}] (LayerPrintSequence: {{from, to}, order}), +// sorted by layer: layers from 2 (the first layer has its own order), `to` at least `from` and without it +// to the last layer, as the dialog's "End", ranges not overlapping, and each order a filament_order(). +// Throws ToolFailure otherwise. +std::vector, std::vector>> layer_sequences(const nlohmann::json& ranges, int slots); + +// The inverse of layer_sequences(): [{from, to, order}], `to` left out for a range up to the last layer. +nlohmann::json layer_sequences_json(const std::vector, std::vector>>& ranges); + +// The heights of a plate's G-code layers as the Preview's layer slider lists them, read from its slice +// result: one layer per run of moves with one layer id (from the second move, as the viewer loads them), +// at the height of its last extrusion that is not custom G-code, or for a belt print at its print Z. +std::vector gcode_layer_zs(const GCodeProcessorResult& result); + +// list_plates' layer_gcode of a plate's codes: [{z, layer, type, filament, color, gcode}] by height, z +// rounded to the G-code's 0.001 mm; layer (1-based, as the slider numbers it) where `layer_zs` has a layer +// at or above z, the slider's rule for a stored height; filament and color for a filament or colour +// change, gcode for custom G-code. +nlohmann::json layer_gcode_json(const CustomGCode::Info& codes, const std::vector& layer_zs); + +// get_settings on the preferences scope: [{key, value}] for the `keys` of `args` that `config`'s app section, +// where the Preferences dialog keeps its settings, holds, paged, and unknown_keys for the others with a note +// that a preference never changed is not stored. Values are as stored. Throws ToolFailure without keys: the +// section also holds account and device state, so nothing is listed unasked. +nlohmann::json preferences_settings(const AppConfig& config, const nlohmann::json& args); + +// 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); + +// ---- calibration (McpToolsProject.cpp) ------------------------------------------------------- + +// calibrate'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), +// temperatures clamped to the dialog field's 155-500 °C and rounded down to its 5 °C, and the dialog's rules +// (check_calib_params()). Adds to `warnings` what the dialog would say without refusing. Throws ToolFailure +// for an argument the test does not take, a value the dialog refuses, or a choice the printer does not offer. +Calib_Params calib_params_from_args(const nlohmann::json& args, const DynamicPrintConfig& printer, std::vector& warnings); + +// The parameters `params` holds for calibrate's `args`, in its argument names and units: what calibrate +// 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); @@ -83,4 +243,135 @@ ToolResult await_gcode_export(ToolContext& ctx, uint64_t before, uint64_t after, nlohmann::json poll_ui(ToolContext& ctx, const std::function& poll, std::chrono::milliseconds timeout, const std::string& what); +// ---- scene ----------------------------------------------------------------------------------- + +// 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); + +// Scale factors that turn `current` (mm per axis) into the sizes of transform's `size` argument, [x, y, z] +// with null for an axis that keeps its size. With one number and two nulls, every axis scales by that +// axis's factor. Throws ToolFailure for another length, no number, or a size that is not positive. +Vec3d size_factors(const Vec3d& current, const nlohmann::json& size); + +// Applies arrange's spacing, rotate, align_y and multi_material to `settings` by the Arrange options +// panel's rules: Align to Y axis stays off while rotation is on. Settings not given keep their values. +// Returns why an asked-for value did not apply, or "". +std::string apply_arrange_args(GLCanvas3D::ArrangeSettings& settings, const nlohmann::json& args); +// The settings as arrange replies with them and records them for replay. +nlohmann::json arrange_settings_json(const GLCanvas3D::ArrangeSettings& settings); + +// An object as list_objects describes it: its filament, auto_drop, overrides, instances (without the +// plate, which the GUI's plate registry knows), parts, and its height ranges and variable layer height +// profile when it has them. Bounding boxes, on the bed and of model parts only, are {min, max, size}. +nlohmann::json object_info(const ModelObject& object, std::size_t index); +// A part as list_objects describes it: its type, filament, placement on the bed measured on instance 0, +// rotation and scale in the object's frame, mesh, paint, and what a text or SVG part was made from. +nlohmann::json volume_info(const ModelVolume& volume, std::size_t index); + +// A part's type as list_objects and add_part name it: part, negative, modifier, support_blocker, +// support_enforcer, precise_seam (any subtype), else other. +const char* volume_type_name(ModelVolumeType type); +// The type add_part's `type` adds, as the context menu's Add items do (precise_seam: a Center seam); +// ModelVolumeType::INVALID for another name. +ModelVolumeType volume_type_from_name(const std::string& name); +// add_part's size of a shape (cube, cylinder, sphere, cone, disc, torus): one positive number of mm +// 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); + +// ---- layers (McpToolsLayers.cpp) ------------------------------------------------------------- + +void register_layer_tools(McpService& service); + +// 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. +std::vector layer_range_option_keys(int filaments); +// set_layer_ranges' ranges as an object's layer_config_ranges. Each starts from `defaults`, what the +// object list gives a new range, and takes its values, parsed strictly. Throws ToolFailure for a range +// that is not 0 <= min_z < max_z or that overlaps another (touching is fine), a key a range does not +// take, an invalid value, an extruder above `filaments`, or a layer_height given outside +// `layer_height_bounds(extruder)`. +t_layer_config_ranges layer_config_ranges_from_json(const nlohmann::json& ranges, const DynamicPrintConfig& defaults, int filaments, + const std::function(int extruder)>& layer_height_bounds); +// An object's height range modifiers as list_objects and set_layer_ranges report them: +// [{min_z, max_z, values: {key: value serialized as get_settings 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 list_objects and set_layer_height_profile +// 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 set_layer_gcode and list_plates 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 set_layer_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); +// set_layer_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 { + +class GCodeViewer; + +namespace Mcp { + +// What a sliced plate reports in the slice 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 +// plate does not use, so filaments[i] is slot i + 1) split into model, support, flush and prime +// tower. Read from `statistics`, the plate's gcode_statistics_json() parsed, so the reply agrees with +// the legend and the statistics files; the silent-mode time and extruder changes, which that file +// leaves out, come from `result`. +nlohmann::json plate_summary(const nlohmann::json& statistics, const GCodeProcessorResult& result); + +// get_preview's tables, from the same parsed statistics, which sum the moves as the Preview does. +// Per feature type, keyed by the English names of the G-code's ;FEATURE: tags: seconds, share of +// the print time and grams, plus a Travel row with its distance. The shares need not add up to 100: +// the print time also counts retractions, wipes, Z moves, tool changes and the prepare time. +nlohmann::json preview_features(const nlohmann::json& statistics); +// Every layer, numbered from 1 as the Preview's layer slider and set_view count them, with its Z, +// its height above the layer below (a layer lower than that one, the next object of a by-object +// print, starts again from the bed), seconds and grams; with `with_features`, the seconds of each +// feature type on it. +nlohmann::json preview_layers(const nlohmann::json& statistics, bool with_features); +// Grams per object instance, model and support. The G-code names an instance by its object's name +// and its index among that object's instances, so an entry gets the list_objects index `object` +// only when exactly one of `object_names` (the model's objects, in order) has its name. +nlohmann::json preview_objects(const nlohmann::json& statistics, const std::vector& object_names); +// What the Preview shows: view type, time mode, the layer slider's range (1-based) with the Z of +// both ends, and the layer count; null when it has no toolpaths. UI thread. +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 get_preview and set_view 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 diff --git a/src/slic3r/GUI/Mcp/McpToolsActions.cpp b/src/slic3r/GUI/Mcp/McpToolsActions.cpp index ee90da8783..82de6aedd5 100644 --- a/src/slic3r/GUI/Mcp/McpToolsActions.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsActions.cpp @@ -125,7 +125,9 @@ void register_action_tools(McpService& service) "or an absolute path - commands with a path parameter skip their file dialog; outputs need {\"path\": ..., " "\"overwrite\": true} to replace a file). Actions that open a dialog return blocked_by_dialog; answer it with " "dialog_respond, or, for a native one, register dialog_auto_answer before the call. An export_gcode with a path " - "completes when the file is written.", + "completes when the file is written; an action that starts a background job (obj_arrange, obj_orient) 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 obj_order_by_* order, the object obj_assemble made).", object_schema({{"id", prop("string", "Action id from list_actions.")}, {"param", prop("string", "Parameter, when the action takes one.")}}, {"id"}), @@ -166,23 +168,30 @@ void register_action_tools(McpService& service) revision = plater->project_revision(); } const AppActionRunResult r = actions.run(id, param, /*record_stats=*/false); - json out{{"level", level_name(r.level)}, {"message", into_u8(r.message)}, {"background", background}}; + json out{{"level", level_name(r.level)}, {"message", into_u8(r.message)}, {"done", r.done}, {"background", background}}; + if (!r.reply.empty()) + out["reply"] = json::parse(r.reply, nullptr, /*allow_exceptions=*/false); if (background && plater != nullptr) out.update({{"before", before}, {"after", plater->export_seq()}, {"revision", revision}}); return out; }); + // A command that did nothing (no selection, no objects) fails here, though the palette + // shows it as information. + const bool done = started["done"].get(); if (started["background"].get()) { - if (started["level"] == "error") + if (started["level"] == "error" || !done) return ToolResult::error(started["message"].get()); return await_gcode_export(ctx, started["before"], started["after"], started["revision"], started["message"]); } settle(ctx); const std::string level = started["level"]; - if (level == "error" || level == "busy") + if (level == "error" || level == "busy" || !done) return ToolResult::error(started["message"].get().empty() ? "The action failed" : started["message"].get()); json out{{"ran", id}, {"level", level}}; if (!started["message"].get().empty()) out["message"] = started["message"]; + if (started.contains("reply") && started["reply"].is_object()) + out.update(started["reply"]); return ToolResult::ok(out); })); } diff --git a/src/slic3r/GUI/Mcp/McpToolsApp.cpp b/src/slic3r/GUI/Mcp/McpToolsApp.cpp index 61961403b3..83b4f77b20 100644 --- a/src/slic3r/GUI/Mcp/McpToolsApp.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsApp.cpp @@ -8,6 +8,7 @@ #include "McpTypes.hpp" #include "ModalTracker.hpp" #include "UiInspector.hpp" +#include "slic3r/GUI/GCodeViewer.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/GUI.hpp" #include "slic3r/GUI/GUI_App.hpp" @@ -18,6 +19,7 @@ #include "slic3r/GUI/NotificationManager.hpp" #include "slic3r/GUI/PartPlate.hpp" #include "slic3r/GUI/Plater.hpp" +#include "slic3r/GUI/PrintHostDialogs.hpp" #if defined(__WXGTK__) #include "slic3r/GUI/LinuxDisplayBackend.hpp" #endif @@ -96,6 +98,7 @@ json app_state(McpService& service) {"display_backend", display_backend()}, {"ready", service.ready()}, {"dialogs", service.modals().snapshot()}, + {"closed_menus", service.inspector().closed_menus()}, {"auto_answer_rules", service.modals().rules_json()}, {"mcp", service.describe()}, {"jobs", service.jobs().list()}}; @@ -129,6 +132,14 @@ json app_state(McpService& service) PartPlateList& plates = plater->get_partplate_list(); state["plates"] = {{"count", plates.get_plate_count()}, {"current", plates.get_curr_plate_index()}}; + // The current plate's toolpaths, as the Preview shows them; null without any, or while the Preview + // still holds another plate's. + GLCanvas3D* preview = plater->get_preview_canvas3D(); + state["preview"] = preview != nullptr && viewer_holds(preview->get_gcode_viewer(), plates.get_curr_plate()->get_slice_result()) ? + preview_state(preview->get_gcode_viewer()) : + json(); + if (!state["preview"].is_null()) + state["preview"]["plate"] = plates.get_curr_plate_index(); // The open gizmo, on the canvas shown first. state["gizmo"] = nullptr; std::vector canvases = live_canvases(); @@ -140,6 +151,17 @@ json app_state(McpService& service) } state["objects"] = plater->model().objects.size(); state["slicing"] = plater->is_slicing_any(); + // The session's print host uploads, as the upload queue lists them; `id` is its ID column. + json uploads = json::array(); + if (const PrintHostQueueDialog* queue = frame->printhost_queue_dlg()) + for (size_t row = 0; row < queue->job_count(); ++row) { + const PrintHostQueueDialog::JobInfo job = queue->job_info(row); + json upload{{"id", row + 1}, {"state", job.state}, {"progress", job.progress}, {"host", job.host}, {"filename", job.filename}}; + if (!job.error.empty()) + upload["error"] = job.error; + uploads.push_back(std::move(upload)); + } + state["uploads"] = std::move(uploads); json notes = json::array(); for (const NotificationSummary& n : plater->get_notification_manager()->summaries()) @@ -181,8 +203,9 @@ void register_app_tools(McpService& service) reg.add(inspect_tool( "get_state", "Get app state", "Snapshot of OrcaSlicer: version, platform, whether it is ready, current tab and mode, project, selected printer/process/" - "filament presets, plates, object count, slicing state, the open gizmo, open modal dialogs, notifications and running " - "jobs. Call it " + "filament presets, plates, the Preview's view type, time mode and layer range (1-based, with their Z), object count, " + "slicing state, print host uploads (state, progress, error), the open gizmo, open modal dialogs, menus closed " + "unseen (a menu a call opened that no reply listed), notifications and running jobs. Call it " "first and whenever you are unsure what the app is doing.", object_schema({}), [&service](const json&, ToolContext& ctx) { return ToolResult::ok(ctx.run_ui([&service] { return app_state(service); })); })); diff --git a/src/slic3r/GUI/Mcp/McpToolsCad.cpp b/src/slic3r/GUI/Mcp/McpToolsCad.cpp index 76302ac47d..d6addf831b 100644 --- a/src/slic3r/GUI/Mcp/McpToolsCad.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsCad.cpp @@ -17,16 +17,32 @@ void register_cad_tools(McpService& service) { service.registry().add(mutate_tool( "cad_call", "Use the Design tab", - "Call a method of the Design (CAD) tab's control surface: method \"describe_tools\" lists them with their params " - "(describe_scene, query_topology, measure, sketch_begin / sketch_add / sketch_commit, extrude, fillet, boolean, " - "import_step, ...). Pass the \"generation\" from describe_scene or query_topology with face and edge ids so ids " - "read before the model changed are refused. Needs the CAD feature enabled in Preferences (it takes effect after a " - "restart).", + "Call a method of the Design (CAD) tab's control surface. Method \"describe_tools\" lists the methods and their " + "params; narrow it with params {\"method\": name or [names]} or {\"query\": text}. Typical calls: describe_scene, " + "describe_feature / set_feature (read and edit a feature as its card does), sketch_begin / sketch_add (entities, " + "polygon, slot, ellipse, spline) / sketch_commit then extrude or revolve {sketch}; in the sketch, sketch_fillet, " + "sketch_trim, sketch_transform (move, rotate, array) and sketch_constrain / sketch_constraints; hole, thread, sweep (along a sketch or helix), loft, split {plane}, " + "fillet, boolean, plane (datum), query_topology " + "(face kinds, adjacency, filters), measure (min_distance), commit " + "(Commit to Plate), undo / redo (the Design history; run_action undo is Prepare's). A method " + "that fails is an error and leaves the design as it was; the older ones in describe_tools' legacy_ok_false " + "answer ok false instead. thread, sweep and loft can take seconds, and their reply may be a job. Pass the " + "\"generation\" from describe_scene or query_topology with face and edge ids so ids read before the model " + "changed are refused. Needs the CAD feature enabled in Preferences (it " + "takes effect after a restart).", object_schema({{"method", prop("string", "Method name.")}, {"params", {{"type", "object"}, {"description", "Its parameters."}}}}, {"method"}), [](const json& args, ToolContext& ctx) { const std::string method = arg_string(args, "method"); const json params = args.value("params", json::object()); + // `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. + if (params.is_object() && params.contains("generation")) { + json recorded = args; + recorded["params"].erase("generation"); + ctx.set_journal_args(std::move(recorded)); + } json result = ctx.run_ui([&] { if (!wxGetApp().is_enable_cad_feature()) throw ToolFailure("The CAD feature is off; enable it in Preferences > Features and restart OrcaSlicer"); diff --git a/src/slic3r/GUI/Mcp/McpToolsConfig.cpp b/src/slic3r/GUI/Mcp/McpToolsConfig.cpp index effb75bc94..2f2ba1b109 100644 --- a/src/slic3r/GUI/Mcp/McpToolsConfig.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsConfig.cpp @@ -1,31 +1,60 @@ -// list_presets, select_preset, get_settings and set_settings: presets are selected through the -// same selectors a person uses, 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. +// list_presets, select_preset, save_preset, delete_preset, get_settings, set_settings and list_plates: 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, dialogs and plate icons, +// so the UI and the project stay consistent. Preferences are only read here; they change in the Preferences +// dialog, whose handlers carry their effects. #include "McpService.hpp" #include "McpTools.hpp" #include "McpTypes.hpp" +#include "slic3r/GUI/CreatePresetsDialog.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/MainFrame.hpp" +#include "slic3r/GUI/ObjectDataViewModel.hpp" +#include "slic3r/GUI/PartPlate.hpp" #include "slic3r/GUI/Plater.hpp" #include "slic3r/GUI/PresetComboBoxes.hpp" +#include "slic3r/GUI/SavePresetDialog.hpp" #include "slic3r/GUI/Tab.hpp" +#include "slic3r/GUI/WipeTowerDialog.hpp" +#include "libslic3r/AppConfig.hpp" #include "libslic3r/Config.hpp" +#include "libslic3r/CustomGCode.hpp" +#include "libslic3r/ExtrusionEntity.hpp" +#include "libslic3r/FlushVolCalc.hpp" +#include "libslic3r/GCode/GCodeProcessor.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 #include +#include #include #include #include +#include #include #include +#include #include +#include +#include +#include +#include +#include #include #include #include @@ -59,6 +88,12 @@ PresetCollection& collection(Preset::Type type) } } +// The settings of a preset type, as its tab and set_settings take them. +const std::vector& preset_options(Preset::Type type) +{ + return type == Preset::TYPE_PRINT ? Preset::print_options() : type == Preset::TYPE_FILAMENT ? Preset::filament_options() : Preset::printer_options(); +} + std::string lower(std::string s) { std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return char(std::tolower(c)); }); @@ -99,27 +134,6 @@ const char* type_name(ConfigOptionType type) } } -json option_meta(const ConfigOptionDef& def) -{ - json meta{{"label", def.full_label.empty() ? def.label : def.full_label}, - {"type", type_name(def.type)}, - {"mode", mode_name(def.mode)}}; - if (!def.category.empty()) - meta["category"] = def.category; - if (!def.sidetext.empty()) - meta["unit"] = def.sidetext; - if (!def.tooltip.empty()) - meta["tooltip"] = def.tooltip.size() > 300 ? def.tooltip.substr(0, 300) + "..." : def.tooltip; - if (def.min > -FLT_MAX && def.min != -FLT_MAX) - meta["min"] = def.min; - if (def.max < FLT_MAX && def.max != FLT_MAX) - meta["max"] = def.max; - if (!def.enum_values.empty()) - meta["values"] = def.enum_values; - return meta; -} - - // Option keys whose key or label contains `query`, for "did you mean" and for get_settings' query. std::vector search_keys(const std::string& query, const std::vector& within, std::size_t limit) { @@ -137,16 +151,530 @@ std::vector search_keys(const std::string& query, const std::vector return out; } +// Preset names that share the most words with `name`, those compatible with the printer first, for a +// name no preset has. +json similar_presets(const PresetCollection& presets, const std::string& name) +{ + std::vector words; + std::istringstream in(lower(name)); + for (std::string w; in >> w;) + words.push_back(w); + std::vector> scored; + for (std::size_t i = 0; i < presets.size(); ++i) { + const Preset& p = presets.preset(i); + if (p.is_default) + continue; + const std::string n = lower(p.name); + const int matched = int(std::count_if(words.begin(), words.end(), [&n](const std::string& w) { return n.find(w) != std::string::npos; })); + if (matched > 0) + scored.emplace_back(-(2 * matched + (p.is_compatible ? 1 : 0)), p.name); + } + std::sort(scored.begin(), scored.end()); + json out = json::array(); + for (std::size_t i = 0; i < scored.size() && i < 5; ++i) + out.push_back(scored[i].second); + return out; +} + struct ConfigTarget { Preset::Type type = Preset::TYPE_INVALID; // preset scopes + const Preset* preset = nullptr; // the preset read: the one being edited, or a saved one + bool edited = false; // config is the edited preset's, unsaved changes included ModelObject* object = nullptr; // object/volume scopes ModelVolume* volume = nullptr; int object_index = -1; + bool project = false; // the project scope, read from `owned` + std::shared_ptr owned; const DynamicPrintConfig* config = nullptr; std::vector options; // keys valid in this scope }; +// The project scope: the project's own settings (PresetBundle::project_config) that a person sets in the +// sidebar, on the canvas or in their dialogs, and the filament slot facts they depend on, which are set +// elsewhere and listed for reading only. +bool project_key_read_only(const std::string& key) +{ + return key == "filament_is_mixed" || key == "filament_map_mode" || key == "filament_map"; +} + +std::vector project_options() +{ + std::vector keys{"curr_bed_type", "filament_colour", "filament_is_mixed", "flush_volumes_matrix", + "flush_multiplier", "prime_volume_mode", "wipe_tower_x", "wipe_tower_y"}; + // The filament grouping of a printer with several extruders. + if (wxGetApp().preset_bundle->get_printer_extruder_count() > 1) + keys.insert(keys.end(), {"filament_map_mode", "filament_map"}); + return keys; +} + +// The project scope's values: project_config's, with the wipe tower position one entry per plate and a +// mixed flag per slot, since a project can store fewer of either. UI thread. +DynamicPrintConfig project_settings() +{ + const PresetBundle& bundle = *wxGetApp().preset_bundle; + DynamicPrintConfig out; + for (const std::string& key : project_options()) + if (const ConfigOption* opt = bundle.project_config.option(key)) + out.set_key_value(key, opt->clone()); + const int plates = ui_plater().get_partplate_list().get_plate_count(); + for (const char* key : {"wipe_tower_x", "wipe_tower_y"}) { + // What the canvas reads for each plate (get_at() takes the first entry for a plate without one). + ConfigOptionFloats* position = out.option(key, true); + std::vector per_plate; + for (int i = 0; i < plates && !position->values.empty(); ++i) + per_plate.push_back(position->get_at(std::size_t(i))); + position->values = std::move(per_plate); + } + std::vector mixed; + for (std::size_t i = 0; i < bundle.project_config.option("filament_colour")->size(); ++i) + mixed.push_back(bundle.is_mixed_filament(i)); + out.set_key_value("filament_is_mixed", new ConfigOptionBools(std::move(mixed))); + return out; +} + +// 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) +{ + PresetBundle& bundle = *wxGetApp().preset_bundle; + const DynamicPrintConfig& printer = bundle.printers.get_edited_preset().config; + std::vector out; + if (key == "curr_bed_type") { + // The sidebar shows its plate type selector for these printers only (Sidebar::update_all_preset_comboboxes()). + if (bundle.is_bbl_vendor() || printer.opt_bool("support_multi_bed_types")) + for (const BedType type : ui_plater().sidebar().get_cur_combox_bed_types()) + out.push_back(print_config_def.get(key)->enum_values[std::size_t(type) - 1]); + } else if (key == "prime_volume_mode") { + // The Purge mode button shows for printers with several nozzles per extruder or fast purge + // (TabPrinter::on_preset_loaded()); its dialog offers Default and Fast, or else Default and Saving. + const auto* nozzles = printer.option("extruder_max_nozzle_count"); + const bool several = nozzles != nullptr && std::any_of(nozzles->values.begin(), nozzles->values.end(), [](int v) { + return v > 1 && v != ConfigOptionIntsNullable::nil_value(); + }); + const auto* fast_opt = printer.option("support_fast_purge_mode"); + const bool fast = fast_opt != nullptr && fast_opt->value; + if (several || fast) + out = {"Default", fast ? "Fast" : "Saving"}; + } + return out; +} + +// set_settings on the project scope. Every key is written by the code its control runs: the plate type +// selector, a colour button's picker, the Flushing volumes and Purge mode dialogs' OK, a wipe tower drag. +// Everything is checked before anything changes. Colours go first, in a closure of their own, so the +// flushing volumes their change recalculates ("Auto flush after changing") are in place before a matrix +// given in the same call replaces them. +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}"); + if (args.contains("reset_all") || args.contains("reset_to")) + throw ToolFailure("reset_all and reset_to are for preset scopes; project settings always have a value"); + DynamicPrintConfig before; + DynamicPrintConfig values; // checked, in the form the scope reads them + // The matrix to write, given whole or as one entry of `basis`'s matrix. + const auto checked_matrix = [&](const DynamicPrintConfig& basis) { + const char* const key = "flush_volumes_matrix"; + DynamicPrintConfig given; + given.set_deserialize_strict(key, preset_setting_value(key, values_in[key], basis, {}, {})); + const std::vector& mixed = before.option("filament_is_mixed")->values; + return check_flush_matrix(given.option(key)->values, mixed.size(), + (values.has("flush_multiplier") ? values : before).option("flush_multiplier")->values, + basis.option(key)->values, mixed); + }; + ctx.run_ui([&]() -> json { + ui_plater(); + before = project_settings(); + const std::vector options = project_options(); + for (auto it = values_in.begin(); it != values_in.end(); ++it) { + const std::string& key = it.key(); + if (std::find(options.begin(), options.end(), key) == options.end()) + throw ToolFailure("Unknown setting \"" + key + "\" for the project scope", {{"keys", options}}); + if (key == "filament_is_mixed") + throw ToolFailure("filament_is_mixed is read-only: mixed filaments are made in the sidebar's mixed filament list"); + if (project_key_read_only(key)) + throw ToolFailure(key + " is read-only here: the Filament grouping dialog sets it for each plate, and every plate keeps " + "its own grouping"); + if (it.value().is_null()) + throw ToolFailure(key + " always has a value; null is for object overrides and preset keys"); + const std::string text = preset_setting_value(key, it.value(), before, {}, {}); + try { + values.set_deserialize_strict(key, text); + } catch (const std::exception& e) { + throw ToolFailure("Invalid value for " + key + ": " + e.what()); + } + } + for (const char* key : {"curr_bed_type", "prime_volume_mode"}) { + if (!values.has(key)) + continue; + const std::vector offered = project_offered(key); + if (offered.empty()) + throw ToolFailure(std::string(key) + ": this printer has " + + (std::string(key) == "curr_bed_type" ? "a single plate type" : "no purge mode to choose")); + if (std::find(offered.begin(), offered.end(), values.opt_serialize(key)) == offered.end()) + throw ToolFailure("This printer does not offer " + std::string(key) + " \"" + values.opt_serialize(key) + "\"", + {{"offered", offered}}); + } + const std::vector& mixed = before.option("filament_is_mixed")->values; + if (values.has("filament_colour")) { + auto* colours = values.option("filament_colour"); + colours->values = check_filament_colours(colours->values, before.option("filament_colour")->values, mixed); + } + if (values.has("flush_multiplier")) { + auto* multipliers = values.option("flush_multiplier"); + const std::size_t nozzles = before.option("flush_multiplier")->size(); + multipliers->values = check_flush_multipliers(multipliers->values, nozzles); + } + if (values.has("flush_volumes_matrix")) + values.option("flush_volumes_matrix")->values = checked_matrix(before); + for (const char* key : {"wipe_tower_x", "wipe_tower_y"}) { + if (!values.has(key)) + continue; + const std::vector& position = values.option(key)->values; + const std::vector& current = before.option(key)->values; + if (position.size() != current.size()) + throw ToolFailure(std::string(key) + " holds one position per plate (" + std::to_string(current.size()) + + "); set one plate's with {\"index\": plate, \"value\": mm}"); + for (std::size_t i = 0; i < position.size(); ++i) { + const Vec2d size = ui_plater().get_partplate_list().get_plate(int(i))->get_size(); + const double extent = std::string(key) == "wipe_tower_x" ? size.x() : size.y(); + if (position[i] != current[i] && (position[i] < 0. || position[i] > extent)) + throw ToolFailure("The prime tower of plate " + std::to_string(i) + " would be off the plate: " + key + " is 0.." + + to_config_string(json(extent)) + " mm from the plate's origin"); + } + } + // A colour button's picker, then its EVT_FILAMENT_COLOR_CHANGED, slot by slot. + if (values.has("filament_colour")) { + const std::vector& colours = values.option("filament_colour")->values; + const std::vector& current = before.option("filament_colour")->values; + for (std::size_t i = 0; i < colours.size(); ++i) { + if (colours[i] == current[i]) + continue; + auto& combos = ui_plater().sidebar().combos_filament(); + auto combo = std::find_if(combos.begin(), combos.end(), + [i](PlaterPresetComboBox* c) { return c != nullptr && c->get_filament_idx() == int(i); }); + if (combo == combos.end()) + throw ToolFailure("Filament slot " + std::to_string(i + 1) + " has no colour button"); + (*combo)->sync_colour_config({colours[i]}, false); + wxCommandEvent* evt = new wxCommandEvent(EVT_FILAMENT_COLOR_CHANGED); + evt->SetInt(int(i)); + wxQueueEvent(&ui_plater(), evt); + } + } + return json(); + }); + settle(ctx); + json reply = ctx.run_ui([&]() -> json { + Plater& plater = ui_plater(); + PresetBundle& bundle = *wxGetApp().preset_bundle; + if (values.has("curr_bed_type")) + plater.sidebar().set_bed_type_accord_combox(values.opt_enum("curr_bed_type")); + // One entry given: the others are as the colour change may just have recalculated them. + if (values_in.contains("flush_volumes_matrix") && values_in["flush_volumes_matrix"].is_object()) + values.option("flush_volumes_matrix")->values = checked_matrix(project_settings()); + bool update = false; + if (values.has("flush_volumes_matrix") || values.has("flush_multiplier")) { + // Without a matrix, the one the colour change may just have recalculated. + const DynamicPrintConfig& source = values.has("flush_volumes_matrix") ? values : bundle.project_config; + const DynamicPrintConfig& multipliers = values.has("flush_multiplier") ? values : bundle.project_config; + apply_flushing_volumes(source.option("flush_volumes_matrix")->values, + multipliers.option("flush_multiplier")->values); + // What the Flushing volumes button does after its dialog; update() below schedules the + // background process, as the event the dialog's OK posts does. + plater.get_view3D_canvas3D()->reload_scene(true); + update = true; + } + if (values.has("prime_volume_mode")) { + const auto mode = values.opt_enum("prime_volume_mode"); + bundle.project_config.set_key_value("prime_volume_mode", new ConfigOptionEnum(mode)); + update = true; + } + // A tower drag, plate by plate: one undo step first, which takes the old positions along + // (Plater::take_snapshot()), then both coordinates of each plate whose tower moved. + const auto position = [&](const char* key, std::size_t plate) { + return (values.has(key) ? values : before).option(key)->values[plate]; + }; + std::vector moved; + for (std::size_t i = 0; i < before.option("wipe_tower_x")->size(); ++i) + if (position("wipe_tower_x", i) != before.option("wipe_tower_x")->values[i] || + position("wipe_tower_y", i) != before.option("wipe_tower_y")->values[i]) + moved.push_back(i); + if (!moved.empty()) { + plater.take_snapshot("Move object"); + for (const std::size_t i : moved) + for (const char* key : {"wipe_tower_x", "wipe_tower_y"}) { + const ConfigOptionFloat value(position(key, i)); + bundle.project_config.option(key, true)->set_at(&value, i, 0); + } + update = true; + } + // Reloading the scene re-places a tower that does not fit where it was put, as after a drag. + if (update) + plater.update(); + const DynamicPrintConfig after = project_settings(); + json applied = json::object(); + for (auto it = values_in.begin(); it != values_in.end(); ++it) + applied[it.key()] = after.opt_serialize(it.key()); + json out{{"applied", applied}, {"changed", changed_settings(before, after)}}; + for (const char* key : {"wipe_tower_x", "wipe_tower_y"}) + if (values.has(key) && *values.option(key) != *after.option(key)) + out["note"] = "A prime tower did not fit where it was put; the app moved it (see applied)."; + return out; + }); + settle(ctx); + return ToolResult::ok(reply); +} + +// The plate scope: what the Plate Settings dialog sets on one plate, and the plate's name and lock, which +// its icons set. +const char* const plate_scope_keys[] = {"curr_bed_type", "print_sequence", "spiral_mode", "first_layer_print_sequence", + "other_layers_print_sequence", "name", "locked"}; + +bool is_plate_setting(const std::string& key) { return key != "name" && key != "locked"; } + +// The plate the scope'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("plate must be 0.." + std::to_string(plates.get_plate_count() - 1)); + return index; +} + +// A plate setting in the form set_settings takes: the plate's own value, null where it follows the +// project's plate type, the process or Auto; or with `effective` what the plate prints with. +json plate_value(PartPlate& plate, const std::string& key, bool effective) +{ + if (key == "name") + return plate.get_plate_name(); + if (key == "locked") + return plate.is_locked(); + 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 plate scope value of a plate: its own, or with `effective` what it prints with. +json plate_values(PartPlate& plate, bool effective) +{ + json out = json::object(); + for (const char* key : plate_scope_keys) + out[key] = plate_value(plate, key, effective); + return out; +} + +// get_settings on the plate scope: 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) +{ + if (args.contains("compare") || args.contains("preset")) + throw ToolFailure("preset and compare are for the process, filament and printer scopes"); + const int index = scope_plate(args); + PartPlate& plate = *ui_plater().get_partplate_list().get_plate(index); + std::vector keys(std::begin(plate_scope_keys), std::end(plate_scope_keys)); + json unknown = json::array(); + if (args.contains("keys")) { + keys.clear(); + for (const json& k : args["keys"]) { + const std::string key = k.get(); + if (std::find(std::begin(plate_scope_keys), std::end(plate_scope_keys), key) != std::end(plate_scope_keys)) + 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)}}; + if (is_plate_setting(key)) { + item["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); + } + } + items.push_back(std::move(item)); + } + json out = page(items, args, 100); + out["plate"] = index; + if (!unknown.empty()) + out["unknown_keys"] = unknown; + return out; +} + +// set_settings on the plate scope. 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 lock and the name as their icons do. Everything is checked before anything +// changes, 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}"); + if (args.contains("reset_all") || args.contains("reset_to")) + throw ToolFailure("reset_all and reset_to are for preset scopes; here a null value takes the global setting or Auto"); + int index = -1; + json reply = ctx.run_ui([&]() -> json { + 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(); + for (auto it = values_in.begin(); it != values_in.end(); ++it) { + const std::string& key = it.key(); + const json& value = it.value(); + if (std::find(std::begin(plate_scope_keys), std::end(plate_scope_keys), key) == std::end(plate_scope_keys)) + throw ToolFailure("Unknown setting \"" + key + "\" for the plate scope", + {{"keys", std::vector(std::begin(plate_scope_keys), std::end(plate_scope_keys))}}); + if (key == "name" && !value.is_string()) + throw ToolFailure("name takes a string (\"\" for none)"); + if (key == "locked" && !value.is_boolean()) + throw ToolFailure("locked takes true or false"); + 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 (see the project scope's " + "filament_is_mixed); 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); + } + } + 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; + const bool rename = values_in.contains("name") && values_in["name"].get() != plate.get_plate_name(); + // The settings and name icons select their plate first; the dialogs work on the current plate. + if ((settings || rename) && index != plates.get_curr_plate_index()) + plater.select_plate(index); + Plater::SingleSnapshot single(&plater); + if (settings) { + plater.take_snapshot("Plate Settings"); + plater.apply_plate_settings(index, bed_type, first_layer, other_layers, sequence, spiral); + } + if (values_in.contains("locked") && values_in["locked"].get() != plate.is_locked()) { + plater.take_snapshot("lock partplate"); + plates.lock_plate(index, values_in["locked"].get()); + plater.set_current_canvas_as_dirty(); + } + if (rename) + plater.rename_plate(index, values_in["name"].get()); + 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[it.key()]; + if (is_plate_setting(it.key())) + effective[it.key()] = plate_value(plate, it.key(), true); + } + for (const char* key : plate_scope_keys) + if (after[key] != before[key]) + changed[key] = after[key]; + json out{{"plate", index}, {"applied", applied}, {"changed", changed}}; + if (!effective.empty()) + out["effective"] = std::move(effective); + return out; + }); + // 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); +} + +// list_plates: every plate's settings as it prints them, what it sets itself, its objects, 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["current"] = i == plates.get_curr_plate_index(); + json overrides = json::array(); + for (const char* key : plate_scope_keys) + if (is_plate_setting(key) && !plate_value(plate, key, false).is_null()) + overrides.push_back(key); + entry["overrides"] = std::move(overrides); + json objects = json::array(); + for (std::size_t o = 0; o < model.objects.size(); ++o) + for (std::size_t j = 0; j < model.objects[o]->instances.size(); ++j) + if (plates.find_instance(int(o), int(j)) == i) + objects.push_back({int(o), int(j)}); + entry["objects"] = std::move(objects); + 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); +} + // Resolves the scope arguments to the config they read and write. UI thread. ConfigTarget resolve_target(const json& args, bool for_write) { @@ -170,39 +698,185 @@ ConfigTarget resolve_target(const json& args, bool for_write) } else { t.config = &t.object->config.get(); } - // Per-object overrides take print (process) settings. - t.options = Preset::print_options(); + const bool is_part = t.volume != nullptr; + t.options = model_scope_options(SettingsFactory::get_options(is_part), is_part, wxGetApp().filaments_cnt()); + if (!for_write) { + // Reads take any print setting too: the object prints with every one of them, from its + // override or the process, which `effective` says. Writes keep to what the object list + // offers, so no override is made that the GUI can't show. + for (const std::string& key : preset_options(Preset::TYPE_PRINT)) + if (std::find(t.options.begin(), t.options.end(), key) == t.options.end()) + t.options.push_back(key); + } + return t; + } + if (scope == "project") { + t.project = true; + t.owned = std::make_shared(project_settings()); + t.config = t.owned.get(); + t.options = project_options(); return t; } t.type = preset_type(scope); - t.options = t.type == Preset::TYPE_PRINT ? Preset::print_options() : - t.type == Preset::TYPE_FILAMENT ? Preset::filament_options() : Preset::printer_options(); + t.options = preset_options(t.type); + if (args.contains("preset")) { + // A saved preset, selected or not, read without selecting it. + if (for_write) + throw ToolFailure("Only the preset being edited can be changed; select it first"); + if (args.contains("filament_slot")) + throw ToolFailure("preset or filament_slot, not both"); + const std::string name = arg_string(args, "preset"); + // `real`: the saved preset, not the edited copy find_preset() gives for the selected one. + t.preset = collection(t.type).find_preset(name, false, true); + if (t.preset == nullptr) + throw ToolFailure("No " + scope + " preset \"" + name + "\" (see list_presets)", {{"similar", similar_presets(collection(t.type), name)}}); + t.config = &t.preset->config; + return t; + } if (t.type == Preset::TYPE_FILAMENT) { const int slot = arg_int(args, "filament_slot", 1); if (slot < 1 || slot > int(bundle.filament_presets.size())) throw ToolFailure("filament_slot must be 1.." + std::to_string(bundle.filament_presets.size())); const std::string& name = bundle.filament_presets[size_t(slot - 1)]; - Tab* tab = wxGetApp().get_tab(Preset::TYPE_FILAMENT); - if (for_write && tab != nullptr && bundle.filaments.get_edited_preset().name != name) { - // The filament tab edits one preset at a time; switch it to this slot's preset first, - // through the normal flow (which asks about unsaved changes). - if (!tab->select_preset(name)) - throw ToolFailure("Switching the filament tab to \"" + name + "\" was cancelled"); - if (TabPresetComboBox* combo = tab->get_combo_box()) - combo->set_filament_idx(slot - 1); - } - if (bundle.filaments.get_edited_preset().name == name) - t.config = &bundle.filaments.get_edited_preset().config; - else if (const Preset* p = bundle.filaments.find_preset(name)) - t.config = &p->config; - else + if (for_write) + edit_filament_slot(slot); + t.edited = bundle.filaments.get_edited_preset().name == name; + t.preset = t.edited ? &bundle.filaments.get_edited_preset() : bundle.filaments.find_preset(name); + if (t.preset == nullptr) throw ToolFailure("Filament slot " + std::to_string(slot) + " has no preset"); + t.config = &t.preset->config; return t; } - t.config = &collection(t.type).get_edited_preset().config; + t.edited = true; + t.preset = &collection(t.type).get_edited_preset(); + t.config = &t.preset->config; return t; } +// The printer's extruder types and the project's nozzle volume types, one per extruder: together +// they pick the entry of a per-variant vector each extruder prints with. UI thread. +std::pair, std::vector> printer_extruders() +{ + const PresetBundle& bundle = *wxGetApp().preset_bundle; + const auto* types = bundle.printers.get_edited_preset().config.option("extruder_type"); + const auto* volumes = bundle.project_config.option("nozzle_volume_type"); + return {types != nullptr ? types->values : std::vector(), volumes != nullptr ? volumes->values : std::vector()}; +} + +// The preset get_settings' compare names: ":saved" is the read preset as saved (so the difference is +// its unsaved changes), ":parent" what the tab's lock icons compare against, else a saved preset by name. +const Preset& compare_preset(const ConfigTarget& t, const std::string& name) +{ + PresetCollection& presets = collection(t.type); + const Preset* other = nullptr; + if (name == ":saved") { + other = presets.find_preset(t.preset->name, false, true); + if (other == nullptr) + throw ToolFailure("\"" + t.preset->name + "\" has no saved copy"); + } else if (name == ":parent") { + // A system preset or a user preset that inherits nothing is its own parent, as for the lock icons. + other = t.edited ? presets.get_selected_preset_parent() : + presets.get_preset_base(*t.preset) == t.preset ? t.preset : presets.get_preset_parent(*t.preset); + if (other == nullptr) + throw ToolFailure("\"" + t.preset->name + "\" inherits from no preset"); + } else { + other = presets.find_preset(name, false, true); + if (other == nullptr) + throw ToolFailure("No preset \"" + name + "\" to compare with (see list_presets)", {{"similar", similar_presets(presets, name)}}); + } + // The Compare presets dialog compares presets of one printer technology only. + if (other->printer_technology() != t.preset->printer_technology()) + throw ToolFailure("\"" + other->name + "\" is for another printer technology"); + return *other; +} + +// Options whose value is a filament slot number, 0 meaning the default. +const char* const filament_number_keys[] = {"extruder", + "outer_wall_filament_id", + "inner_wall_filament_id", + "sparse_infill_filament_id", + "internal_solid_filament_id", + "top_surface_filament_id", + "bottom_surface_filament_id", + "support_filament", + "support_interface_filament"}; + +// Refuses the filament numbers the object list's combos do not offer: past the last slot, and for +// support a mixed slot, which the support code cannot resolve. Checked before anything changes, +// since ObjectList::set_extruder_for_items() ignores a number past the last slot silently. UI thread. +void check_filament_numbers(const DynamicPrintConfig& values) +{ + const int slots = int(ui_plater().get_extruder_colors_from_plater_config().size()); + for (const char* key : filament_number_keys) { + if (!values.has(key)) + continue; + const int n = values.opt_int(key); + if (n < 0 || n > slots) + throw ToolFailure("Filament " + std::to_string(n) + " does not exist; this project has " + std::to_string(slots) + + " filament slots (0 is the default)"); + if (n > 0 && std::string(key).rfind("support_", 0) == 0 && wxGetApp().preset_bundle->is_mixed_filament(size_t(n - 1))) + throw ToolFailure(std::string(key) + " takes a physical filament; slot " + std::to_string(n) + " is a mixed filament"); + } +} + +// The object list row whose Change Filament sets the target's filament: the object's, which is also +// what a single-part object shows for its one part, or the part's or modifier's own row. UI thread. +wxDataViewItem filament_row(const ConfigTarget& t) +{ + ObjectDataViewModel& rows = *wxGetApp().obj_list()->GetModel(); + if (t.volume != nullptr && !t.volume->is_model_part() && !t.volume->is_modifier()) + throw ToolFailure("Only parts and modifiers take a filament; this volume is a negative part, a support blocker or enforcer, " + "or a seam modifier"); + if (t.volume == nullptr || t.object->volumes.size() == 1) + return rows.GetItemById(t.object_index); + // MCP's part index is the model's; the object list orders its rows by type. + const int model_index = int(std::find(t.object->volumes.begin(), t.object->volumes.end(), t.volume) - t.object->volumes.begin()); + const wxDataViewItem row = rows.GetItemByVolumeId(t.object_index, rows.get_real_volume_index_in_ui(t.object_index, model_index)); + if (!row.IsOk() || (rows.GetItemType(row) & itVolume) == 0) + throw ToolFailure("This part has no row in the object list (a cut connector); set the object's filament instead"); + return row; +} + +// A changed option as the tab marks it, key or key#index: the key, and the entry (-1 for the whole value). +std::pair option_entry(const std::string& id) +{ + const std::size_t hash = id.find('#'); + return {id.substr(0, hash), hash == std::string::npos ? -1 : std::atoi(id.c_str() + hash + 1)}; +} + +// One entry of a vector, or the whole value with index -1; null where the config lacks it. +json entry_value(const DynamicPrintConfig& config, const std::string& key, int index) +{ + const ConfigOption* opt = config.option(key); + if (opt == nullptr) + return nullptr; + if (index < 0) + return opt->serialize(); + const auto* vec = dynamic_cast(opt); + return vec != nullptr && index < int(vec->size()) ? json(vec->vserialize()[std::size_t(index)]) : json(); +} + +// The keys of `changes` ({key or key#index: value}), each once. +json change_keys(const json& changes) +{ + json keys = json::array(); + for (auto it = changes.begin(); it != changes.end(); ++it) + if (const std::string key = option_entry(it.key()).first; std::find(keys.begin(), keys.end(), key) == keys.end()) + keys.push_back(key); + return keys; +} + +// The 1-based filament slots that use the preset `name`. +json filament_slots(const std::string& name) +{ + const std::vector& presets = wxGetApp().preset_bundle->filament_presets; + json slots = json::array(); + for (std::size_t s = 0; s < presets.size(); ++s) + if (presets[s] == name) + slots.push_back(int(s + 1)); + return slots; +} + json list_presets(const json& args) { const Preset::Type type = preset_type(arg_string(args, "type")); @@ -211,7 +885,6 @@ json list_presets(const json& args) const std::string query = lower(arg_string(args, "query")); PresetCollection& presets = collection(type); const std::string selected = presets.get_selected_preset_name(); - PresetBundle& bundle = *wxGetApp().preset_bundle; json items = json::array(); for (size_t i = 0; i < presets.size(); ++i) { const Preset& p = presets.preset(i); @@ -226,6 +899,10 @@ json list_presets(const json& args) json j{{"name", p.name}, {"system", p.is_system}, {"user", p.is_user()}}; if (!p.alias.empty() && p.alias != p.name) j["alias"] = p.alias; + if (!p.inherits().empty()) + j["inherits"] = p.inherits(); + if (p.is_project_embedded) + j["project"] = true; if (!p.is_compatible) j["compatible"] = false; if (!p.is_visible) @@ -235,14 +912,9 @@ json list_presets(const json& args) if (presets.current_is_dirty()) j["modified"] = true; } - if (type == Preset::TYPE_FILAMENT) { - json slots = json::array(); - for (size_t s = 0; s < bundle.filament_presets.size(); ++s) - if (bundle.filament_presets[s] == p.name) - slots.push_back(int(s + 1)); - if (!slots.empty()) + if (type == Preset::TYPE_FILAMENT) + if (json slots = filament_slots(p.name); !slots.empty()) j["filament_slots"] = std::move(slots); - } items.push_back(std::move(j)); } return page(items, args, 100); @@ -250,6 +922,574 @@ json list_presets(const json& args) } // namespace +std::vector model_scope_options(const std::vector& offered, bool is_part, int filaments) +{ + std::vector keys; + for (const std::string& key : offered) + if (const ConfigOptionDef* def = print_config_def.get(key); + def != nullptr && !SettingsFactory::is_improper_category(def->category, filaments, !is_part)) + keys.push_back(key); + // The filament column and the Change Filament menu, not a setting the list offers. + keys.push_back("extruder"); + return keys; +} + +json effective_setting(const std::string& key, const DynamicPrintConfig& process, const ModelObject& object, const ModelVolume* volume) +{ + // An extruder of 0 is the object list's "Default": no filament of its own. + const auto own = [&key](const ModelConfig& config) -> const ConfigOption* { + const ConfigOption* opt = config.option(key); + return opt != nullptr && (key != "extruder" || opt->getInt() != 0) ? opt : nullptr; + }; + json out; + if (const ConfigOption* opt = volume != nullptr ? own(volume->config) : nullptr) + out = {{"effective", opt->serialize()}, {"source", "part"}}; + else if (const ConfigOption* opt = own(object.config)) + out = {{"effective", opt->serialize()}, {"source", "object"}}; + else if (process.has(key)) + out = {{"effective", process.opt_serialize(key)}, {"source", "process"}}; + else if (key == "extruder") + out = {{"effective", "1"}, {"source", "default"}}; // the process has no extruder; filament 1 prints + else if (const ConfigOptionDef* def = print_config_def.get(key); def != nullptr && def->default_value) + out = {{"effective", def->default_value->serialize()}, {"source", "default"}}; + if (volume == nullptr) { + json parts = json::array(); + for (std::size_t i = 0; i < object.volumes.size(); ++i) { + const ModelVolume& v = *object.volumes[i]; + if (v.is_model_part() || v.is_modifier()) + if (const ConfigOption* opt = own(v.config)) + parts.push_back({{"volume", int(i)}, {"value", opt->serialize()}}); + } + if (!parts.empty()) + out["parts"] = std::move(parts); + } + return out; +} + +bool save_preset_inside_project(const PresetCollection& presets, const std::string& name, const json& args) +{ + wxString info; + const PresetNameStatus status = check_preset_name(presets, name, info); + if (status == PresetNameStatus::Invalid) { + std::string why = into_u8(info); + std::replace_if(why.begin(), why.end(), [](char c) { return c == '\n' || c == '\t'; }, ' '); + throw ToolFailure("Cannot save as \"" + name + "\": " + why); + } + // The dialog warns only for another preset of that name; saving the selected one again is its plain Save. + const Preset* existing = presets.find_preset(name, false); + if (status == PresetNameStatus::Warning && !arg_bool(args, "overwrite", false)) + throw ToolFailure("Preset \"" + name + "\" already exists" + + (existing != nullptr && !existing->is_compatible ? " and is incompatible with the current printer" : "") + + "; pass overwrite: true to replace it"); + if (existing == nullptr) + return arg_bool(args, "inside_project", presets.get_edited_preset().is_project_embedded); + // The dialog locks the choice to where the existing preset is. + if (args.contains("inside_project") && args["inside_project"].get() != existing->is_project_embedded) + throw ToolFailure("Preset \"" + name + "\" is " + (existing->is_project_embedded ? "kept inside the project" : "a user preset") + + " and is saved there; leave inside_project out"); + return existing->is_project_embedded; +} + +json option_meta(const ConfigOptionDef& def) +{ + json meta{{"label", def.full_label.empty() ? def.label : def.full_label}, + {"type", type_name(def.type)}, + {"mode", mode_name(def.mode)}}; + if (!def.category.empty()) + meta["category"] = def.category; + if (!def.sidetext.empty()) + meta["unit"] = def.sidetext; + if (!def.tooltip.empty()) + meta["tooltip"] = def.tooltip.size() > 300 ? def.tooltip.substr(0, 300) + "..." : def.tooltip; + if (def.min > -FLT_MAX && def.min != -FLT_MAX) + meta["min"] = def.min; + if (def.max < FLT_MAX && def.max != FLT_MAX) + meta["max"] = def.max; + if (!def.enum_values.empty()) + meta["values"] = def.enum_values; + // What the GUI's combo shows for each value, so a person's wording maps to a value. + if (!def.enum_labels.empty() && def.enum_labels.size() == def.enum_values.size()) + meta["labels"] = def.enum_labels; + return meta; +} + +json variant_entries(const std::string& key, const DynamicPrintConfig& config, const std::vector& extruder_types, + const std::vector& nozzle_volume_types) +{ + const auto* values = dynamic_cast(config.option(key)); + if (values == nullptr || values->size() < 2) + return nullptr; + // The keys naming each variant's extruder and kind; the machine limits hold a normal and a + // silent mode value per variant. + std::string id_key; + std::string variant_key; + unsigned int stride = 1; + if (print_options_with_variant.count(key) > 0) { + id_key = "print_extruder_id"; + variant_key = "print_extruder_variant"; + } else if (filament_options_with_variant.count(key) > 0) { + variant_key = "filament_extruder_variant"; // a filament's variants carry no extruder + } else if (printer_options_with_variant_1.count(key) > 0 || printer_options_with_variant_2.count(key) > 0) { + id_key = "printer_extruder_id"; + variant_key = "printer_extruder_variant"; + stride = printer_options_with_variant_2.count(key) > 0 ? 2 : 1; + } else if (printer_extruder_options.count(key) == 0 && key != "extruder_offset") { + return nullptr; + } + json names = json::array(); + if (variant_key.empty()) { + // One entry per extruder, as the printer's Extruder page edits it. + for (std::size_t i = 0; i < values->size(); ++i) + names.push_back("extruder " + std::to_string(i + 1)); + return {{"variants", std::move(names)}}; + } + const auto* ids = id_key.empty() ? nullptr : config.option(id_key); + const auto* variants = config.option(variant_key); + for (std::size_t i = 0; i < values->size(); ++i) { + const std::size_t v = i / stride; + std::string name = variants != nullptr && v < variants->size() ? variants->values[v] : "entry " + std::to_string(i); + if (extruder_types.size() > 1 && ids != nullptr && v < ids->size()) + name = "extruder " + std::to_string(ids->values[v]) + ": " + name; + if (stride == 2) + name += i % stride == 0 ? " (normal mode)" : " (silent mode)"; + names.push_back(std::move(name)); + } + // The entry each extruder prints with, as the slicer and the tab's variant switch pick it. + json active = json::array(); + for (std::size_t e = 0; e < extruder_types.size(); ++e) { + const auto volume = e < nozzle_volume_types.size() ? NozzleVolumeType(nozzle_volume_types[e]) : nvtStandard; + const int index = config.get_index_for_extruder(int(e + 1), id_key, ExtruderType(extruder_types[e]), volume, variant_key, stride); + active.push_back(index >= 0 && index < int(values->size()) ? json(index) : json()); + } + return {{"variants", std::move(names)}, {"active", std::move(active)}}; +} + +std::string preset_setting_value(const std::string& key, const json& value, const DynamicPrintConfig& config, + const std::vector& extruder_types, const std::vector& nozzle_volume_types) +{ + const auto* current = dynamic_cast(config.option(key)); + // "0 = Direct Drive Standard (in use), 1 = Direct Drive High Flow", and the same as details. + const auto entries = [&](json& details) { + details = variant_entries(key, config, extruder_types, nozzle_volume_types); + if (details.is_null()) + return std::string(); + const json active = details.value("active", json::array()); + std::string text; + for (std::size_t i = 0; i < details["variants"].size(); ++i) { + text += (i > 0 ? ", " : "") + std::to_string(i) + " = " + details["variants"][i].get(); + if (std::find(active.begin(), active.end(), json(i)) != active.end()) + text += " (in use)"; + } + return text; + }; + // Parses into a scratch config, so a bad value fails here with its key. + const auto parse = [&key](const std::string& text, DynamicPrintConfig& scratch) { + try { + scratch.set_deserialize_strict(key, text); + } catch (const std::exception& e) { + throw ToolFailure("Invalid value for " + key + ": " + e.what()); + } + return dynamic_cast(scratch.option(key)); + }; + if (value.is_object()) { + if (current == nullptr) + throw ToolFailure(key + " is a single value; give it without index"); + if (value.size() != 2 || !value.contains("index") || !value["index"].is_number_integer() || !value.contains("value")) + throw ToolFailure("One entry of " + key + " is given as {\"index\": i, \"value\": v}"); + const int index = value["index"].get(); + if (index < 0 || index >= int(current->size())) { + json details; + const std::string list = entries(details); + throw ToolFailure(key + " has " + std::to_string(current->size()) + " entries" + (list.empty() ? "" : ": " + list), details); + } + DynamicPrintConfig scratch; + const ConfigOptionVectorBase* entry = parse(to_config_string(value["value"], key), scratch); + if (entry == nullptr || entry->size() != 1) + throw ToolFailure("Entry " + std::to_string(index) + " of " + key + " takes one value"); + std::unique_ptr updated(current->clone()); + static_cast(updated.get())->set_at(entry, std::size_t(index), 0); + return updated->serialize(); + } + const std::string text = to_config_string(value, key); + if (current != nullptr && current->size() > 1) { + json details; + const std::string list = entries(details); + DynamicPrintConfig scratch; + const ConfigOptionVectorBase* given = list.empty() ? nullptr : parse(text, scratch); + if (!value.is_array() && given != nullptr && given->size() == 1 && details.contains("active")) { + // One value for a per-variant key goes to the entries in use, as typing into the tab's + // field writes the variant it shows; the other variants keep theirs. An array is every + // entry, so one of a single value is refused below. + std::unique_ptr updated(current->clone()); + bool written = false; + for (const json& index : details["active"]) + if (index.is_number_integer()) { + static_cast(updated.get())->set_at(given, index.get(), 0); + written = true; + } + if (written) + return updated->serialize(); + } + if (given != nullptr && given->size() != current->size()) + throw ToolFailure(key + " holds " + std::to_string(current->size()) + " values, one per " + + (details.contains("active") ? "extruder variant" : "extruder") + ": " + list + + ". Set one with {\"index\": i, \"value\": v}, or all of them as an array.", + details); + } + return text; +} + +json preset_diff(const Preset& left, const Preset& right, const std::vector& keys) +{ + // The Compare presets dialog's rule: printer and filament vectors are compared entry by entry, and + // a printer with fewer extruders is compared from the other side. + const bool deep = left.type == Preset::TYPE_PRINTER || left.type == Preset::TYPE_FILAMENT; + const auto colours = [](const Preset& p) { + const auto* opt = p.config.option("extruder_colour"); + return opt != nullptr ? opt->size() : std::size_t(0); + }; + const std::vector dirty = left.type == Preset::TYPE_PRINTER && colours(left) < colours(right) ? + PresetCollection::dirty_options(&right, &left, deep) : + PresetCollection::dirty_options(&left, &right, deep); + const auto settings_id = [](const std::string& key) { + const std::string suffix = "_settings_id"; + return key.size() > suffix.size() && key.compare(key.size() - suffix.size(), suffix.size(), suffix) == 0; + }; + json items = json::array(); + for (const std::string& id : dirty) { + const auto [key, index] = option_entry(id); + if (settings_id(key) || std::find(keys.begin(), keys.end(), key) == keys.end()) + continue; + json item{{"key", key}}; + if (index >= 0) + item["index"] = index; + item["value"] = entry_value(left.config, key, index); + item["other"] = entry_value(right.config, key, index); + items.push_back(std::move(item)); + } + return items; +} + +json discarded_changes(const json& changes, const DynamicPrintConfig& config) +{ + json gone = json::object(); + for (auto it = changes.begin(); it != changes.end(); ++it) { + const auto [key, index] = option_entry(it.key()); + if (entry_value(config, key, index) != it.value()) + gone[it.key()] = it.value(); + } + return change_keys(gone); +} + +json unsaved_changes() +{ + json out = json::object(); + for (const char* type : {"process", "filament", "printer"}) { + // What list_presets calls modified, in the settings the tab shows: the full comparison also lists + // bookkeeping keys that only one of the two configs has. + const PresetCollection& presets = collection(preset_type(type)); + if (!presets.current_is_dirty()) + continue; + const std::vector& options = preset_options(presets.type()); + const DynamicPrintConfig& config = presets.get_edited_preset().config; + json changes = json::object(); + for (const std::string& id : presets.current_dirty_options(true)) { + const auto [key, index] = option_entry(id); + if (std::find(options.begin(), options.end(), key) != options.end()) + changes[id] = entry_value(config, key, index); + } + if (!changes.empty()) + out[type] = {{"name", presets.get_edited_preset().name}, {"changes", std::move(changes)}}; + } + return out; +} + +json unsaved_changes_outcome(const json& before) +{ + json discarded = json::object(); + for (auto it = before.begin(); it != before.end(); ++it) + if (json keys = discarded_changes(it.value()["changes"], collection(preset_type(it.key())).get_edited_preset().config); !keys.empty()) + discarded[it.key()] = {{"name", it.value()["name"]}, {"keys", std::move(keys)}}; + json modified = json::object(); + const json after = unsaved_changes(); + for (auto it = after.begin(); it != after.end(); ++it) + modified[it.key()] = {{"name", it.value()["name"]}, {"keys", change_keys(it.value()["changes"])}}; + json out = json::object(); + if (!discarded.empty()) + out["discarded"] = std::move(discarded); + if (!modified.empty()) + out["modified"] = std::move(modified); + return out; +} + +json check_preset_deletable(const PresetCollection& presets, const std::string& name, bool delete_attached, const PresetCollection& prints, + const PresetCollection& filaments) +{ + const char* const type = presets.type() == Preset::TYPE_PRINT ? "process" : presets.type() == Preset::TYPE_FILAMENT ? "filament" : "printer"; + const Preset* preset = presets.find_preset(name, false); + if (preset == nullptr) + throw ToolFailure(std::string("No ") + type + " preset \"" + name + "\" (see list_presets)", {{"similar", similar_presets(presets, name)}}); + // The tab shows its Delete button for these only (Tab::update_btns_enabling()). + if (preset->is_system || preset->is_default) + throw ToolFailure("\"" + name + "\" is a system preset; only user presets and presets inside the project can be deleted"); + if (preset->is_from_bundle()) + throw ToolFailure("\"" + name + "\" comes from a preset bundle; only user presets and presets inside the project can be deleted"); + if (presets.get_preset_base(*preset) != preset) + return json::object(); + // A base preset: the tab refuses it while presets inherit from it, since they would no longer load. + json children = json::array(); + for (const Preset& p : presets) + if (p.inherits() == preset->name) + children.push_back(p.name); + if (!children.empty()) + throw ToolFailure("\"" + name + "\" cannot be deleted while other presets inherit from it; delete them first", + {{"inherited_by", std::move(children)}}); + // A custom printer takes the user presets made for it alone with it (Tab::select_preset()). + json attached = json::object(); + if (presets.type() == Preset::TYPE_PRINTER) + for (const auto& [key, made_for] : {std::pair{"process", &prints}, std::pair{"filament", &filaments}}) { + json names = json::array(); + for (const Preset* p : made_for->get_user_presets_for_printer(name)) + names.push_back(p->name); + if (!names.empty()) + attached[key] = std::move(names); + } + if (!attached.empty() && !delete_attached) + throw ToolFailure("\"" + name + "\" has presets made for it alone (process: " + + std::to_string(attached.value("process", json::array()).size()) + + ", filament: " + std::to_string(attached.value("filament", json::array()).size()) + + "), which are deleted with it; pass delete_attached: true", + {{"attached", attached}}); + return attached; +} + +std::vector check_filament_colours(std::vector colours, const std::vector& current, + const std::vector& mixed) +{ + if (colours.size() != current.size()) + throw ToolFailure("filament_colour takes one colour per filament slot: " + std::to_string(current.size()) + ", not " + + std::to_string(colours.size())); + for (std::size_t i = 0; i < colours.size(); ++i) { + std::string& colour = colours[i]; + if (lower(colour) == lower(current[i])) { + colour = current[i]; // unchanged, whatever its form + continue; + } + if (i < mixed.size() && mixed[i] != 0) + throw ToolFailure("Slot " + std::to_string(i + 1) + " is a mixed filament; its colour comes from its components"); + if (colour.size() != 7 || colour[0] != '#' || + !std::all_of(colour.begin() + 1, colour.end(), [](unsigned char c) { return std::isxdigit(c) != 0; })) + throw ToolFailure("Slot " + std::to_string(i + 1) + "'s colour \"" + colour + "\" is not #RRGGBB"); + // As the colour pickers store it. + std::transform(colour.begin(), colour.end(), colour.begin(), [](unsigned char c) { return char(std::toupper(c)); }); + } + return colours; +} + +std::vector check_flush_multipliers(std::vector multipliers, std::size_t nozzles) +{ + if (multipliers.size() == 1) + multipliers = std::vector(nozzles, multipliers.front()); + if (multipliers.size() != nozzles) + throw ToolFailure("flush_multiplier takes one value per nozzle (" + std::to_string(nozzles) + "), or one for all"); + // The Flushing volumes dialog's range (g_min_flush_multiplier, g_max_flush_multiplier). + for (const double m : multipliers) + if (m < 0. || m > 3.) + throw ToolFailure("flush_multiplier " + to_config_string(json(m)) + " is outside 0..3, the Flushing volumes dialog's range"); + return multipliers; +} + +std::vector check_flush_matrix(std::vector matrix, std::size_t slots, const std::vector& multipliers, + const std::vector& current, const std::vector& mixed) +{ + const std::size_t cells = slots * slots; + if (matrix.size() != multipliers.size() * cells) + throw ToolFailure("flush_volumes_matrix takes " + std::to_string(multipliers.size() * cells) + " values: " + + std::to_string(slots) + "x" + std::to_string(slots) + " for each of " + std::to_string(multipliers.size()) + + " nozzle(s), in config order over every filament slot"); + const auto is_mixed = [&mixed](std::size_t slot) { return slot < mixed.size() && mixed[slot] != 0; }; + for (std::size_t i = 0; i < matrix.size(); ++i) { + const std::size_t nozzle = i / cells, from = i % cells / slots, to = i % slots; + const std::string where = "flush_volumes_matrix[" + std::to_string(i) + "] (nozzle " + std::to_string(nozzle + 1) + + ", from slot " + std::to_string(from + 1) + " to slot " + std::to_string(to + 1) + ")"; + // The dialog shows physical slots only and keeps the rest; a mixed filament is never flushed. + if (is_mixed(from) || is_mixed(to)) { + if (current.size() == matrix.size() && matrix[i] != current[i]) + throw ToolFailure(where + " belongs to a mixed filament, which is never flushed; keep its value " + + to_config_string(json(current[i]))); + continue; + } + if (matrix[i] < 0.) + throw ToolFailure(where + " is negative"); + if (from == to && matrix[i] != 0.) + throw ToolFailure(where + " must be 0: no flush from a filament to itself"); + // The limit the dialog applies before storing, which scales with the multiplier. + if (multipliers[nozzle] > 0.) + matrix[i] = std::min(matrix[i], double(g_max_flush_volume) / multipliers[nozzle]); + } + return matrix; +} + +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(); + for (const std::string& key : after.keys()) + if (const ConfigOption* old = before.option(key); old == nullptr || *old != *after.option(key)) + changed[key] = after.opt_serialize(key); + for (const std::string& key : before.keys()) + if (!after.has(key)) + changed[key] = nullptr; + return changed; +} + +json preferences_settings(const AppConfig& config, const json& args) +{ + if (!args.contains("keys") || args.contains("query") || args.contains("preset") || args.contains("compare")) + throw ToolFailure("The preferences scope reads the keys named in keys, nothing else: it lists no preferences unasked, " + "since the app configuration also holds account and device state"); + json items = json::array(), unknown = json::array(); + for (const json& k : args["keys"]) { + std::string value; + if (config.get("app", k.get(), value)) + items.push_back({{"key", k}, {"value", value}}); + else + unknown.push_back(k); + } + json out = page(items, args, 100); + if (!unknown.empty()) { + out["unknown_keys"] = unknown; + // Many preferences are stored only once they are changed. + out["note"] = "unknown_keys are not stored: a preference never changed shows its default in the dialog (most " + "checkboxes unchecked), or the key is not a preference."; + } + return out; +} + +std::string edit_filament_slot(int slot) +{ + PresetBundle& bundle = *wxGetApp().preset_bundle; + const std::string& name = bundle.filament_presets[size_t(slot - 1)]; + const std::string before = bundle.filaments.get_edited_preset().name; + Tab* tab = wxGetApp().get_tab(Preset::TYPE_FILAMENT); + if (tab == nullptr || before == name) + return {}; + // The filament tab edits one preset at a time; the normal switch asks about its unsaved changes. + if (!tab->select_preset(name)) + throw ToolFailure("Switching the filament tab to \"" + name + "\" was cancelled"); + if (TabPresetComboBox* combo = tab->get_combo_box()) + combo->set_filament_idx(slot - 1); + return before; +} + std::string to_config_string(const json& v, const std::string& key) { const ConfigOptionDef* def = v.is_array() && !key.empty() ? print_config_def.get(key) : nullptr; @@ -305,9 +1545,11 @@ std::string to_config_string(const json& v, const std::string& key) void register_config_tools(McpService& service) { ToolRegistry& reg = service.registry(); - const json scope_prop = enum_prop({"print", "process", "filament", "printer", "object", "volume"}, - "Which settings: the process (print), filament or printer preset being edited, or an " - "object's / part's own overrides."); + const json scope_prop = enum_prop({"print", "process", "filament", "printer", "object", "volume", "project", "plate", "preferences"}, + "Which settings: the process (print), filament or printer preset being edited, an " + "object's / part's own overrides, the project's own settings, a plate's, or the " + "app's preferences (read only)."); + const json plate_prop = {{"type", "integer"}, {"minimum", 0}, {"description", "Plate index (plate scope; default: the current plate)."}}; reg.add(inspect_tool( "list_presets", "List presets", @@ -325,43 +1567,43 @@ void register_config_tools(McpService& service) reg.add(mutate_tool( "select_preset", "Select a preset", "Select a printer, process or filament preset by the name its selector shows (or its internal name), as a person " - "would - which may open the unsaved-changes dialog (the reply is then blocked_by_dialog). A filament is assigned to " - "filament_slot (1-based, default 1).", + "would. With unsaved changes the Transfer-or-discard prompt opens (blocked_by_dialog) unless changes answers it. A " + "filament is assigned to filament_slot (1-based, default 1). Reply: selected; when presets had or have unsaved " + "changes, discarded and modified list per preset the keys dropped and the keys still unsaved.", object_schema({{"type", enum_prop({"printer", "process", "filament"}, "Preset category.")}, {"name", prop("string", "Preset name as list_presets shows it.")}, - {"filament_slot", {{"type", "integer"}, {"minimum", 1}, {"description", "Filament slot, 1-based."}}}}, + {"filament_slot", {{"type", "integer"}, {"minimum", 1}, {"description", "Filament slot, 1-based."}}}, + {"changes", enum_prop({"transfer", "discard"}, "Unsaved changes of the presets the switch replaces: move " + "them to the new preset or drop them, as the prompt's " + "buttons do. Omitted: the prompt opens.")}}, {"type", "name"}), [](const json& args, ToolContext& ctx) { - const Preset::Type type = preset_type(arg_string(args, "type")); - const std::string name = arg_string(args, "name"); + const Preset::Type type = preset_type(arg_string(args, "type")); + const std::string name = arg_string(args, "name"); + const std::string changes = arg_string(args, "changes"); json result = ctx.run_ui([&]() -> json { - ui_plater(); + Plater& plater = ui_plater(); PresetBundle& bundle = *wxGetApp().preset_bundle; + Tab* tab = wxGetApp().get_tab(type); + if (tab == nullptr) + throw ToolFailure("The settings tab is not available"); + const int slot = arg_int(args, "filament_slot", 1); + PlaterPresetComboBox* filament_combo = nullptr; + int filament_item = -1; + std::string target = name; if (type == Preset::TYPE_FILAMENT) { - const int slot = arg_int(args, "filament_slot", 1); - auto& combos = wxGetApp().plater()->sidebar().combos_filament(); + auto& combos = plater.sidebar().combos_filament(); if (slot < 1 || slot > int(combos.size()) || combos[size_t(slot - 1)] == nullptr) throw ToolFailure("filament_slot must be 1.." + std::to_string(combos.size())); - PlaterPresetComboBox* combo = combos[size_t(slot - 1)]; - const auto match = combo->find_by_name(name); + filament_combo = combos[size_t(slot - 1)]; + const auto match = filament_combo->find_by_name(name); if (match.ambiguous) throw ToolFailure("\"" + name + "\" is ambiguous in filament slot " + std::to_string(slot) + "'s selector; use the internal name"); if (match.item < 0) throw ToolFailure("Filament slot " + std::to_string(slot) + " does not offer \"" + name + "\" (see list_presets)"); - // The sidebar's own selection path: mapping, flush volumes, badges, project state. - combo->SetSelection(match.item); - wxCommandEvent evt(wxEVT_COMBOBOX, combo->GetId()); - evt.SetEventObject(combo); - evt.SetInt(match.item); - evt.SetString(combo->GetString(match.item)); - combo->GetEventHandler()->ProcessEvent(evt); - return {{"type", "filament"}, {"filament_slot", slot}, {"selected", bundle.filament_presets[size_t(slot - 1)]}}; - } - Tab* tab = wxGetApp().get_tab(type); - if (tab == nullptr) - throw ToolFailure("The settings tab is not available"); - std::string target = name; - if (TabPresetComboBox* combo = tab->get_combo_box(); combo != nullptr && combo->GetCount() > 0) { + filament_item = match.item; + target = match.internal_name; + } else if (TabPresetComboBox* combo = tab->get_combo_box(); combo != nullptr && combo->GetCount() > 0) { const auto match = combo->find_by_name(name); if (match.ambiguous) throw ToolFailure("\"" + name + "\" is ambiguous; use the internal name"); @@ -369,32 +1611,209 @@ void register_config_tools(McpService& service) throw ToolFailure("The selector does not offer \"" + name + "\" (see list_presets)"); target = match.internal_name; } - if (!tab->select_preset(target)) - throw ToolFailure("Selecting \"" + target + "\" was cancelled"); - return {{"type", arg_string(args, "type")}, {"selected", collection(type).get_selected_preset_name()}}; + // The prompt about the tab's own changes offers Transfer only where can_transfer_changes_to() says; + // refused here, before anything changes. The sidebar switches the filament tab for a single filament only. + const bool switches_tab = type != Preset::TYPE_FILAMENT || !plater.sidebar().is_multifilament(); + if (changes == "transfer" && switches_tab && collection(type).current_is_dirty() && !tab->can_transfer_changes_to(target)) + throw ToolFailure(std::string("The unsaved-changes prompt offers no Transfer here: ") + + (type == Preset::TYPE_PRINTER ? "a printer's changes stay with it" : + "\"" + target + "\" is a filament of another type") + + ". Pass changes: \"discard\", or save_preset first."); + const json before = unsaved_changes(); + tab->m_dirty_preset_answer = changes == "transfer" ? Tab::DirtyPresetAnswer::Transfer : + changes == "discard" ? Tab::DirtyPresetAnswer::Discard : + Tab::DirtyPresetAnswer::Ask; + ScopeGuard ask_again([tab] { tab->m_dirty_preset_answer = Tab::DirtyPresetAnswer::Ask; }); + json out; + if (filament_combo != nullptr) { + // The sidebar's own selection path: mapping, flush volumes, badges, project state. + filament_combo->SetSelection(filament_item); + wxCommandEvent evt(wxEVT_COMBOBOX, filament_combo->GetId()); + evt.SetEventObject(filament_combo); + evt.SetInt(filament_item); + evt.SetString(filament_combo->GetString(filament_item)); + filament_combo->GetEventHandler()->ProcessEvent(evt); + out = {{"type", "filament"}, {"filament_slot", slot}, {"selected", bundle.filament_presets[size_t(slot - 1)]}}; + } else { + if (!tab->select_preset(target)) + throw ToolFailure("Selecting \"" + target + "\" was cancelled"); + out = {{"type", arg_string(args, "type")}, {"selected", collection(type).get_selected_preset_name()}}; + } + out.update(unsaved_changes_outcome(before)); + return out; }); settle(ctx); return ToolResult::ok(result); })); + reg.add(mutate_tool( + "save_preset", "Save a preset", + "Save the printer, process or filament preset being edited, unsaved changes included, under name, as the tab's Save " + "and the Save preset dialog's OK do; it is then selected. A filament is filament_slot's (default 1), and every slot " + "using the old preset takes the new one. Replacing another existing preset needs overwrite (pass it in scripts meant " + "to be rerun). Reply: saved, user, project, inherits, filament_slots. A temperature warning or an unsaved-changes " + "prompt makes it blocked_by_dialog. To keep only some edits, set_settings {reset_all: true, values} first.", + object_schema({{"type", enum_prop({"printer", "process", "filament"}, "Preset category.")}, + {"name", prop("string", "Name to save under.")}, + {"filament_slot", {{"type", "integer"}, {"minimum", 1}, {"description", "Filament slot, 1-based."}}}, + {"inside_project", prop("boolean", "Keep it inside the project, not as a user preset. Default: where the " + "edited preset is.")}, + {"detach", prop("boolean", "Copy inherited values and drop the parent (Developer mode).")}, + {"overwrite", prop("boolean", "Replace another preset of that name.")}}, + {"type", "name"}), + [](const json& args, ToolContext& ctx) { + const Preset::Type type = preset_type(arg_string(args, "type")); + const std::string name = arg_string(args, "name"); + const bool detach = arg_bool(args, "detach", false); + json result = ctx.run_ui([&]() -> json { + ui_plater(); + // The dialog shows its detach checkbox only in Developer mode. + if (detach && wxGetApp().get_mode() != comDevelop) + throw ToolFailure("Detach is offered only in Developer mode; run_action orca_command:toggle_developer_mode:orca first"); + Tab* tab = wxGetApp().get_tab(type); + if (tab == nullptr) + throw ToolFailure("The settings tab is not available"); + // The filament tab edits one slot's preset; edit this slot's, as set_settings does. + if (type == Preset::TYPE_FILAMENT) + resolve_target({{"scope", "filament"}, {"filament_slot", arg_int(args, "filament_slot", 1)}}, true); + PresetCollection& presets = collection(type); + const bool inside_project = save_preset_inside_project(presets, name, args); + // With the name given, the tab saves without opening the dialog. + if (!tab->save_preset(name, detach, inside_project)) + throw ToolFailure("Saving was cancelled"); + // After the save, so a cancelled save leaves the physical printer alone. + if (type == Preset::TYPE_PRINTER) + SavePresetDialog::update_physical_printers(SavePresetDialog::ChangePreset, name); + const Preset* saved = presets.find_preset(name, false); + if (saved == nullptr) + throw ToolFailure("The preset was not saved"); + json out{{"saved", saved->name}, + {"type", arg_string(args, "type")}, + {"user", saved->is_user()}, + {"project", saved->is_project_embedded}, + {"selected", presets.get_selected_preset_name() == saved->name}}; + if (!saved->inherits().empty()) + out["inherits"] = saved->inherits(); + if (type == Preset::TYPE_FILAMENT) + out["filament_slots"] = filament_slots(saved->name); + return out; + }); + settle(ctx); + return ToolResult::ok(result); + })); + + reg.add(mutate_tool( + "delete_preset", "Delete a preset", + "Delete a user preset or one inside the project, its file and its cloud copy, as the tab's Delete does, without " + "asking. A selected preset is replaced as the tab does (its parent or the next preset). Another filament is deleted " + "without changing the selection, and slots using it take the selected one; another process is selected, deleted " + "and the selection restored; a printer must be selected first. Refused: system presets, presets others inherit from, " + "another preset while the edited one of its type has unsaved changes. Deleting a selected printer or process can " + "ask about other presets' unsaved changes (blocked_by_dialog). Reply: deleted, selected, filaments (per slot), " + "attached, and discarded/modified as select_preset's.", + object_schema({{"type", enum_prop({"printer", "process", "filament"}, "Preset category.")}, + {"name", prop("string", "Preset name as list_presets shows it.")}, + {"delete_attached", prop("boolean", "A custom printer: also delete the process and filament presets made " + "for it alone, which the GUI deletes with it.")}}, + {"type", "name"}), + [](const json& args, ToolContext& ctx) { + const std::string type_name = arg_string(args, "type"); + const Preset::Type type = preset_type(type_name); + const std::string name = arg_string(args, "name"); + json result = ctx.run_ui([&]() -> json { + Plater& plater = ui_plater(); + PresetBundle& bundle = *wxGetApp().preset_bundle; + Tab* tab = wxGetApp().get_tab(type); + if (tab == nullptr) + throw ToolFailure("The settings tab is not available"); + PresetCollection& presets = collection(type); + const json attached = check_preset_deletable(presets, name, arg_bool(args, "delete_attached", false), bundle.prints, + bundle.filaments); + const std::string selected = presets.get_selected_preset_name(); + const json before = unsaved_changes(); + if (name == selected) { + // With a physical printer selected, the tab's Delete only takes the preset off that printer. + if (TabPresetComboBox* combo = tab->get_combo_box(); type == Preset::TYPE_PRINTER && combo != nullptr && combo->is_selected_physical_printer()) + throw ToolFailure("A physical printer is selected; select the printer preset itself first"); + tab->delete_preset(false); + } else if (type == Preset::TYPE_PRINTER) { + // Switching to another printer and back recomputes the process and the filaments, so it is no round trip. + throw ToolFailure("\"" + name + "\" is not the selected printer; select it first with select_preset"); + } else if (presets.current_is_dirty()) { + // Both routes select the edited preset again, which would drop or ask about its changes. + throw ToolFailure("The edited " + type_name + " \"" + selected + "\" has unsaved changes; save_preset or set_settings " + "{reset_all: true} first"); + } else if (type == Preset::TYPE_FILAMENT) { + delete_unselected_filament_preset(name); + // What the Edit filament dialog's opener refreshes once it closes (Plater::priv::on_modify_filament()). + wxGetApp().mainframe->update_side_preset_ui(); + plater.update_ui_from_settings(); + plater.sidebar().update_all_preset_comboboxes(); + } else { + // The tab deletes only its selected process, so this is what a person does: select, delete, select back. + if (!tab->select_preset(name)) + throw ToolFailure("Selecting \"" + name + "\" to delete it was cancelled"); + if (presets.get_selected_preset_name() == name) + tab->delete_preset(false); + if (presets.get_selected_preset_name() != selected) + tab->select_preset(selected); + } + if (presets.find_preset(name, false) != nullptr) + throw ToolFailure("\"" + name + "\" was not deleted: a preset switch was cancelled"); + json out{{"deleted", name}, + {"type", type_name}, + {"selected", presets.get_selected_preset_name()}, + {"filaments", bundle.filament_presets}}; + if (!attached.empty()) + out["attached"] = attached; + out.update(unsaved_changes_outcome(before)); + return out; + }); + settle(ctx); + return ToolResult::ok(result); + }, + true)); + reg.add(inspect_tool( "get_settings", "Read settings", - "Read setting values (as OrcaSlicer serializes them) with label, type, unit, range, allowed values and mode. Name " - "keys, or search with query (matches key or label); without either, every option of the scope is listed, paged. " - "For object/volume scopes only the overrides that object or part carries are listed.", + "Read setting values (as OrcaSlicer serializes them) with label, type, unit, range, allowed values and their labels, " + "and mode. Name keys, or search with query (matches key or label); without either, every option of the scope is " + "listed, paged. A per-variant value lists in meta its variants (what each entry is for) and active (the entry each " + "extruder prints with). preset reads a saved preset without selecting it; compare lists only the keys that differ " + "from another preset, each with value and other. For object/volume scopes only the overrides that object or part " + "carries are listed, each with effective (the value it prints with) and source (part, object, process or default); " + "an object's item lists in parts the parts and modifiers that override the key inside their own volume. The project " + "scope has the plate type, slot colours, flushing volumes, purge mode, prime tower position per plate, which slots are " + "mixed and, with several extruders, the filament grouping; meta.offered lists the choices this printer has. The plate " + "scope lists a plate's curr_bed_type, print_sequence, spiral_mode, first_layer_print_sequence, " + "other_layers_print_sequence, name and locked, each with value (the plate's own, null where it follows the global " + "setting or Auto) and effective. The preferences scope reads the named keys of the app configuration (the Preferences " + "dialog's settings, keys as its controls are named), values as stored, and lists no keys unasked.", object_schema({{"scope", scope_prop}, {"keys", array_prop({{"type", "string"}}, "Option keys, e.g. [\"layer_height\", \"wall_loops\"].")}, {"query", prop("string", "Search keys and labels.")}, {"object", {{"type", "integer"}, {"minimum", 0}, {"description", "Object index (object/volume scope)."}}}, {"volume", {{"type", "integer"}, {"minimum", 0}, {"description", "Part index (volume scope)."}}}, + {"plate", plate_prop}, {"filament_slot", {{"type", "integer"}, {"minimum", 1}, {"description", "Filament slot, 1-based."}}}, - {"include_meta", prop("boolean", "Include labels, types and ranges. Default true.")}, + {"preset", prop("string", "Preset scopes: read this saved preset (a name from list_presets) instead of the " + "one being edited.")}, + {"compare", prop("string", "Preset scopes: a preset name, \":saved\" (the unsaved changes) or \":parent\" " + "(the preset it inherits from).")}, + {"include_meta", prop("boolean", "Include labels, types and ranges. Default true, false with compare.")}, {"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 500}}}, {"offset", {{"type", "integer"}, {"minimum", 0}}}}), [](const json& args, ToolContext& ctx) { return ToolResult::ok(ctx.run_ui([&] { - const ConfigTarget t = resolve_target(args, false); - const bool meta = arg_bool(args, "include_meta", true); + if (arg_string(args, "scope") == "plate") + return plate_settings(args); + if (arg_string(args, "scope") == "preferences") + return preferences_settings(*wxGetApp().app_config, args); + const ConfigTarget t = resolve_target(args, false); + const bool compare = args.contains("compare"); + const bool meta = arg_bool(args, "include_meta", !compare); + if ((t.object != nullptr || t.project) && (compare || args.contains("preset"))) + throw ToolFailure("preset and compare are for the process, filament and printer scopes"); std::vector keys; if (args.contains("keys")) { for (const json& k : args["keys"]) @@ -406,24 +1825,62 @@ void register_config_tools(McpService& service) } else { keys = t.options; } - json items = json::array(); - json unknown = json::array(); + std::vector known; + json unknown = json::array(); for (const std::string& key : keys) { - const ConfigOptionDef* def = print_config_def.get(key); - if (def == nullptr || std::find(t.options.begin(), t.options.end(), key) == t.options.end()) { - unknown.push_back(key); - continue; - } - json item{{"key", key}}; - if (t.config->has(key)) - item["value"] = t.config->opt_serialize(key); + if (print_config_def.get(key) != nullptr && std::find(t.options.begin(), t.options.end(), key) != t.options.end()) + known.push_back(key); else - item["value"] = nullptr; // not overridden at this level - if (meta) - item["meta"] = option_meta(*def); - items.push_back(std::move(item)); + unknown.push_back(key); + } + const auto extruders = printer_extruders(); + const auto add_meta = [&](json& item, const std::string& key) { + item["meta"] = option_meta(*print_config_def.get(key)); + if (t.project) { + if (key == "curr_bed_type" || key == "prime_volume_mode") + item["meta"]["offered"] = project_offered(key); + if (project_key_read_only(key)) + item["meta"]["read_only"] = true; + } else if (t.object == nullptr) { + if (json v = variant_entries(key, *t.config, extruders.first, extruders.second); !v.is_null()) + item["meta"].update(v); + } + }; + json out; + if (compare) { + const Preset& other = compare_preset(t, arg_string(args, "compare")); + json items = preset_diff(*t.preset, other, known); + if (meta) + for (json& item : items) + add_meta(item, item["key"].get()); + const bool edited = t.edited && collection(t.type).current_is_dirty(); + out = page(items, args, 100); + out["left"] = t.preset->name + (edited ? " (edited)" : ""); + out["right"] = other.name; + } else { + // What an object or part prints with falls back to the process being edited, as its + // settings tab shows it. + const DynamicPrintConfig& process = wxGetApp().preset_bundle->prints.get_edited_preset().config; + bool part_only = false; + json items = json::array(); + for (const std::string& key : known) { + json item{{"key", key}}; + if (t.config->has(key)) + item["value"] = t.config->opt_serialize(key); + else + item["value"] = nullptr; // not overridden at this level + if (t.object != nullptr) { + item.update(effective_setting(key, process, *t.object, t.volume)); + part_only = part_only || item.contains("parts") || item.value("source", "") == "part"; + } + if (meta) + add_meta(item, key); + items.push_back(std::move(item)); + } + out = page(items, args, 100); + if (part_only) + out["note"] = "A part's value (source \"part\", or in parts) applies only inside that part's volume."; } - json out = page(items, args, 100); if (!unknown.empty()) out["unknown_keys"] = unknown; return out; @@ -434,45 +1891,88 @@ void register_config_tools(McpService& service) "set_settings", "Change settings", "Change settings as if typed into the settings tab: all values are parsed strictly first and applied together, and " "nothing changes if any is invalid. Values may be strings in OrcaSlicer's format (\"15%\", \"0.2\", \"1,2\") or JSON " - "numbers, booleans and arrays (a point as [x, y]). object/volume scopes set per-object or per-part overrides; a null value removes an " - "override.", + "numbers, booleans and arrays (a point as [x, y]). object/volume scopes set per-object or per-part overrides, of the " + "keys the object list offers there; a null value removes an override. extruder is the object's or part's filament " + "(1-based; 0 or null is Default), set as the Change Filament menu does. A preset's per-variant value (get_settings " + "meta.variants) takes a single value for the entries in use (meta.active, as the tab writes the variant it shows), " + "{\"index\": i, \"value\": v} for one entry, or an array of all. " + "In a preset scope, null takes a key back to its saved value (reset_to parent: the parent's), and reset_all first " + "discards every unsaved change, as the tab's undo button does (reply: reverted), then applies values. Reply: applied, " + "and changed, every setting the call changed, including those the app adjusted in turn. Spiral vase and some others " + "confirm their adjustments in a dialog (blocked_by_dialog). The project scope writes as the sidebar's controls do: " + "curr_bed_type, filament_colour (#RRGGBB per slot), flush_multiplier, flush_volumes_matrix (per nozzle, slots x slots " + "from row to column, in config order over every slot, mixed ones left as they are; before the multiplier, which the " + "G-code header applies; a colour change can recalculate it, so set it last), prime_volume_mode, and wipe_tower_x/y " + "(mm from the plate's origin, one per plate; undoable). The plate scope writes as the Plate Settings dialog's OK does, " + "after selecting the plate as its icon does: curr_bed_type, print_sequence (\"by layer\", \"by object\"), " + "spiral_mode (true asks for confirmation: blocked_by_dialog), 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), null for the " + "global setting or Auto; name, and locked (true or false). One undo step.", object_schema({{"scope", scope_prop}, - {"values", {{"type", "object"}, {"description", "{key: value}"}}}, + {"values", {{"type", "object"}, {"description", "{key: value}, or {key: {index, value}} for one entry"}}}, + {"reset_all", prop("boolean", "Preset scopes: discard the unsaved changes before applying values.")}, + {"reset_to", enum_prop({"saved", "parent"}, "Preset scopes: what a null value takes a key back to: the " + "saved preset (default) or the preset it inherits from.")}, {"object", {{"type", "integer"}, {"minimum", 0}}}, {"volume", {{"type", "integer"}, {"minimum", 0}}}, - {"filament_slot", {{"type", "integer"}, {"minimum", 1}}}}, - {"values"}), + {"plate", plate_prop}, + {"filament_slot", {{"type", "integer"}, {"minimum", 1}}}}), [](const json& args, ToolContext& ctx) { - if (!args["values"].is_object() || args["values"].empty()) - throw ToolFailure("values must be a non-empty object {key: value}"); + // A preference's control carries its effects (theme, language, network, this server's own port), which + // writing the key would skip. + if (arg_string(args, "scope") == "preferences") + throw ToolFailure("Preferences change in the Preferences dialog: run_action orca_command:open_preferences:orca " + "with param \":\", then ui_input {\"target\": {\"name\": \"\", \"within\": " + "\"Preferences\"}, \"value\": ...}"); + if (arg_string(args, "scope") == "project") + return set_project_settings(args, ctx); + if (arg_string(args, "scope") == "plate") + return set_plate_settings(args, ctx); + const json values_in = args.value("values", json::object()); + const bool reset_all = arg_bool(args, "reset_all", false); + if (values_in.empty() && !reset_all) + throw ToolFailure("values must be a non-empty object {key: value}, unless reset_all is true"); + if (args.contains("reset_to") && std::none_of(values_in.begin(), values_in.end(), [](const json& v) { return v.is_null(); })) + throw ToolFailure("reset_to applies to the keys given as null"); json result = ctx.run_ui([&]() -> json { ui_plater(); const ConfigTarget t = resolve_target(args, true); + if ((reset_all || args.contains("reset_to")) && t.object != nullptr) + throw ToolFailure(std::string(reset_all ? "reset_all" : "reset_to") + " is for preset scopes; here a null value removes an override"); + // What a null value takes a preset's key back to: its saved value, as the key's undo arrow does, + // or the parent's, as its lock icon does. + const Preset* reference = t.object != nullptr ? nullptr : + arg_string(args, "reset_to", "saved") == "parent" ? &compare_preset(t, ":parent") : + &collection(t.type).get_selected_preset(); + // A preset's value is checked against what it will replace: after reset_all, the saved preset. + const DynamicPrintConfig& basis = reset_all ? collection(t.type).get_selected_preset().config : *t.config; + const auto extruders = printer_extruders(); + const DynamicPrintConfig before = *t.config; std::vector> values; std::vector removals; - for (auto it = args["values"].begin(); it != args["values"].end(); ++it) { + for (auto it = values_in.begin(); it != values_in.end(); ++it) { if (std::find(t.options.begin(), t.options.end(), it.key()) == t.options.end()) - throw ToolFailure("Unknown setting \"" + it.key() + "\" for this scope", + throw ToolFailure(t.object != nullptr && print_config_def.get(it.key()) != nullptr ? + "The object list does not offer \"" + it.key() + "\" for " + + (t.volume != nullptr ? "a part or modifier" : "an object") : + "Unknown setting \"" + it.key() + "\" for this scope", {{"similar", search_keys(it.key().substr(0, std::max(3, it.key().size() / 2)), t.options, 5)}}); - if (it.value().is_null()) { - if (t.object == nullptr) - throw ToolFailure("null removes an object/part override; preset settings always have a value"); + if (it.value().is_null() && reference != nullptr) { + if (!reference->config.has(it.key())) + throw ToolFailure("\"" + reference->name + "\" has no " + it.key()); + values.emplace_back(it.key(), reference->config.opt_serialize(it.key())); + } else if (it.value().is_null()) { removals.push_back(it.key()); + } else if (t.object == nullptr) { + values.emplace_back(it.key(), preset_setting_value(it.key(), it.value(), basis, extruders.first, extruders.second)); + } else if (it.value().is_object()) { + throw ToolFailure("{\"index\", \"value\"} sets one entry of a preset's setting; an override takes the whole value"); } else { values.emplace_back(it.key(), to_config_string(it.value(), it.key())); } } - if (t.object == nullptr) { - Tab* tab = wxGetApp().get_tab(t.type); - if (tab == nullptr) - throw ToolFailure("The settings tab is not available"); - try { - tab->apply_preset_config_values(values); - } catch (const std::exception& e) { - throw ToolFailure(e.what()); - } - } else { - // Strict-parse everything into a scratch config before touching the model. + // Strict-parses every value into a scratch config, so a bad one fails before anything changes. + const auto parse_values = [&values] { DynamicPrintConfig scratch; for (const auto& [key, value] : values) try { @@ -480,15 +1980,53 @@ void register_config_tools(McpService& service) } catch (const std::exception& e) { throw ToolFailure("Invalid value for " + key + ": " + e.what()); } + return scratch; + }; + json reverted; + if (t.object == nullptr) { + Tab* tab = wxGetApp().get_tab(t.type); + if (tab == nullptr) + throw ToolFailure("The settings tab is not available"); + if (reset_all) { + parse_values(); + reverted = collection(t.type).current_dirty_options(); + tab->on_roll_back_value(); + } + try { + tab->apply_preset_config_values(values); + } catch (const std::exception& e) { + throw ToolFailure(e.what()); + } + } else { + DynamicPrintConfig scratch = parse_values(); + check_filament_numbers(scratch); + // The filament goes through the object list's Change Filament, as a person sets it; + // null is its "Default" (0). + const bool set_extruder = scratch.has("extruder") || + std::find(removals.begin(), removals.end(), "extruder") != removals.end(); + const int extruder = scratch.has("extruder") ? scratch.opt_int("extruder") : 0; + wxDataViewItem extruder_row = set_extruder ? filament_row(t) : wxDataViewItem(); + scratch.erase("extruder"); + removals.erase(std::remove(removals.begin(), removals.end(), "extruder"), removals.end()); + Plater& plater = ui_plater(); - plater.take_snapshot("Change object settings"); - ModelConfig& cfg = t.volume != nullptr ? static_cast(t.volume->config) : static_cast(t.object->config); - for (const auto& [key, value] : values) - cfg.set_key_value(key, scratch.option(key)->clone()); - for (const std::string& key : removals) - cfg.erase(key); - wxGetApp().obj_list()->object_config_options_changed(ObjectVolumeID{t.object, t.volume}); - plater.changed_object(t.object_index); + // One undo step for the whole call: the filament's own snapshot folds into this one. + Plater::SingleSnapshot single(&plater); + if (!scratch.empty() || !removals.empty()) { + plater.take_snapshot("Change object settings"); + ModelConfig& cfg = t.volume != nullptr ? static_cast(t.volume->config) : static_cast(t.object->config); + for (const std::string& key : scratch.keys()) + cfg.set_key_value(key, scratch.option(key)->clone()); + for (const std::string& key : removals) + cfg.erase(key); + wxGetApp().obj_list()->object_config_options_changed(ObjectVolumeID{t.object, t.volume}); + plater.changed_object(t.object_index); + } + if (set_extruder) { + wxDataViewItemArray rows; + rows.Add(extruder_row); + wxGetApp().obj_list()->set_extruder_for_items(rows, extruder); + } } const ConfigTarget after = resolve_target(args, false); json applied = json::object(); @@ -496,11 +2034,33 @@ void register_config_tools(McpService& service) applied[key] = after.config->has(key) ? json(after.config->opt_serialize(key)) : json(); for (const std::string& key : removals) applied[key] = nullptr; - return {{"applied", applied}}; + json out{{"applied", applied}, {"changed", changed_settings(before, *after.config)}}; + if (reset_all) + out["reverted"] = std::move(reverted); + if (values_in.contains("extruder")) { + // A single-part object shows no part row; its filament is the object's. + const bool on_object = after.volume != nullptr && after.object->volumes.size() == 1; + const DynamicPrintConfig& cfg = on_object ? after.object->config.get() : *after.config; + out["applied"]["extruder"] = cfg.has("extruder") ? json(cfg.opt_serialize("extruder")) : json(); + if (on_object) + out["note"] = "A single-part object's filament is the object's; it was set there."; + } + return out; }); settle(ctx); return ToolResult::ok(result); })); + + reg.add(inspect_tool( + "list_plates", "List plates", + "Plates with name, locked, current, objects ([object, instance]), and the settings they print with: curr_bed_type, " + "print_sequence, spiral_mode, first_layer_print_sequence and other_layers_print_sequence (null: Auto); overrides " + "lists those the plate sets itself (set_settings scope plate). Also 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}}}, + {"offset", {{"type", "integer"}, {"minimum", 0}}}}), + [](const json& args, ToolContext& ctx) { return ToolResult::ok(ctx.run_ui([&] { return list_plates(args); })); })); } }}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpToolsLayers.cpp b/src/slic3r/GUI/Mcp/McpToolsLayers.cpp new file mode 100644 index 0000000000..e57cc5152c --- /dev/null +++ b/src/slic3r/GUI/Mcp/McpToolsLayers.cpp @@ -0,0 +1,694 @@ +// set_layer_ranges: an object's height range modifiers (the object list's Height Range Modifier), +// given as the whole set of ranges. set_layer_height_profile: the Variable layer height panel's +// Adaptive, Smooth and Reset on an object. And how list_objects reports both. set_layer_gcode: the +// pauses, custom G-codes and filament changes of a plate's layers, through the Preview's layer slider. + +#include "McpService.hpp" +#include "McpTools.hpp" +#include "McpTypes.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/PartPlate.hpp" +#include "slic3r/GUI/Plater.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 +#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(); +} + +std::string range_text(const Slic3r::t_layer_height_range& range) { return mm(range.first) + "-" + mm(range.second); } + +ToolFailure overlap(const Slic3r::t_layer_height_range& lower, const Slic3r::t_layer_height_range& upper) +{ + return ToolFailure("Ranges " + range_text(lower) + " and " + range_text(upper) + + " overlap; ranges may touch, one's max_z being the next one's min_z"); +} + +// For "did you mean": keys holding the first half of `key`, those that begin as it does first. +json similar_keys(const std::string& key, const std::vector& keys) +{ + const std::string part = key.substr(0, std::max(3, key.size() / 2)); + std::vector hits; + std::copy_if(keys.begin(), keys.end(), std::back_inserter(hits), [&part](const std::string& k) { return k.find(part) != std::string::npos; }); + const auto common = [&key](const std::string& k) { return std::mismatch(k.begin(), k.end(), key.begin(), key.end()).first - k.begin(); }; + std::stable_sort(hits.begin(), hits.end(), [&common](const std::string& a, const std::string& b) { return common(a) > common(b); }); + hits.resize(std::min(hits.size(), 5)); + return hits; +} + +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 object a layer call names, on an FFF printer. +ModelObject& layer_object(Plater& plater, const json& args) +{ + const ModelObjectPtrs& objects = plater.model().objects; + const int oi = arg_int(args, "object", -1); + if (oi < 0 || oi >= int(objects.size())) + throw ToolFailure("object index out of range"); + if (plater.printer_technology() != ptFFF) + throw ToolFailure("Height range modifiers and variable layer heights are for FFF printers"); + return *objects[std::size_t(oi)]; +} + +// The object set_layer_height_profile names, after the checks that need no view, such as an argument +// that goes with another action. +ModelObject& profile_object(Plater& plater, const json& args) +{ + ModelObject& object = 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 object; +} + +// 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_layer_height_profile(Plater& plater, const json& args) +{ + ModelObject& object = profile_object(plater, args); + const int oi = arg_int(args, "object", -1); + 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{{"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, edits and removes ranges, with the whole set given at +// once. Everything the arguments can tell is checked before anything changes. +json set_layer_ranges(Plater& plater, const json& args) +{ + ModelObject* object = &layer_object(plater, args); + const int oi = arg_int(args, "object", -1); + ObjectList* list = wxGetApp().obj_list(); + t_layer_config_ranges ranges = layer_config_ranges_from_json(args.value("layer_config_ranges", json()), list->get_default_layer_config(oi), + wxGetApp().filaments_cnt(), [](int extruder) { + return std::make_pair(get_min_layer_height(extruder), get_max_layer_height(extruder)); + }); + 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{{"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 set_layer_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; list_plates 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("plate must be 0.." + std::to_string(plates.get_plate_count() - 1)); + 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; 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 list_plates' 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; +} + +// set_layer_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 set_settings scope printer)"}); + break; + } + return out; +} + +// Selects the plate set_layer_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 (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_layer_gcode(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::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 DynamicPrintConfig& defaults, int filaments, + const std::function(int extruder)>& layer_height_bounds) +{ + if (!ranges.is_array()) + throw ToolFailure("layer_config_ranges must be a list of {min_z, max_z, values}"); + const std::vector keys = layer_range_option_keys(filaments); + t_layer_config_ranges out; + for (const json& r : ranges) { + if (!r.is_object()) + throw ToolFailure("A range is {min_z, max_z, values}"); + 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 " + range_text(range)); + const json values = r.value("values", json::object()); + if (!values.is_object()) + throw ToolFailure("A range's values are {key: value}"); + DynamicPrintConfig config = defaults; + for (auto it = values.begin(); it != values.end(); ++it) { + if (std::find(keys.begin(), keys.end(), it.key()) == keys.end()) + throw ToolFailure("\"" + it.key() + + "\" is not a height range setting; a range takes layer_height, extruder and per-region " + "process settings such as sparse_infill_density", + {{"similar", similar_keys(it.key(), keys)}}); + try { + config.set_deserialize_strict(it.key(), to_config_string(it.value(), it.key())); + } catch (const std::exception& e) { + throw ToolFailure("Invalid value for " + it.key() + ": " + e.what()); + } + } + const int extruder = config.opt_int("extruder"); + if (extruder < 0 || extruder > filaments) + throw ToolFailure("extruder " + std::to_string(extruder) + " is not a filament: 0 (the object's) or " + + (filaments > 1 ? "1-" + std::to_string(filaments) : std::string("1"))); + // Only a layer height given is checked, as the range editor checks only what a person types. + if (values.contains("layer_height")) { + const double height = config.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)); + } + if (out.count(range) != 0) + throw overlap(range, range); + out[range].assign_config(std::move(config)); + } + // 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; +} + +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 (set_settings scope 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 (list_plates lists them)" : "")); + changed = true; + event = code.type; + } + if (changed && event != CustomGCode::Unknown) + slider.post_ticks_changed_event(event); + return changed; +} + +void register_layer_tools(McpService& service) +{ + ToolRegistry& reg = service.registry(); + 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."}}}, + {"values", {{"type", "object"}, + {"description", "{key: value} as set_settings takes them: layer_height, extruder (0 = the object's " + "filament) and per-region process settings such as sparse_infill_density or wall_loops."}}}}, + {"min_z", "max_z"}); + + reg.add(mutate_tool( + "set_layer_ranges", "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, starting from the object's layer height and filament. " + "Ranges may touch but not overlap; [] removes them all. One undo step; the object is selected. Replies with the " + "object's height and its ranges as list_objects shows them, and warnings, such as a variable layer height profile " + "deciding the layer heights instead.", + object_schema({{"object", {{"type", "integer"}, {"minimum", 0}}}, + {"layer_config_ranges", array_prop(range, "The object's ranges afterwards, in any order.")}}, + {"object", "layer_config_ranges"}), + [](const json& args, ToolContext& ctx) { + json out = ctx.run_ui([&] { return set_layer_ranges(ui_plater(), args); }); + settle(ctx); + return ToolResult::ok(out); + })); + + reg.add(mutate_tool( + "set_layer_height_profile", "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. One undo step; " + "the object is selected. Replies with the object's height, its layer_height_profile {points, min_height, " + "max_height} as list_objects shows it (absent after reset), and warnings.", + object_schema({{"object", {{"type", "integer"}, {"minimum", 0}}}, + {"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).")}}, + {"object", "action"}), + [](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. + ctx.run_ui([&] { + Plater& plater = ui_plater(); + 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_layer_height_profile(ui_plater(), args); }); + 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."}}; + reg.add(mutate_tool( + "set_layer_gcode", "Set layer G-codes", + "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: a custom " + "code or filament change where there is one replaces it. Not undoable, as in the slider. A change invalidates the " + "plate's slice: slice again before exporting. Replies with the plate's codes as list_plates' 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_layer_gcode(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/McpToolsProject.cpp b/src/slic3r/GUI/Mcp/McpToolsProject.cpp index 174b5013db..85d7d03fb0 100644 --- a/src/slic3r/GUI/Mcp/McpToolsProject.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsProject.cpp @@ -1,4 +1,5 @@ -// open_files, new_project, save_project and export: files in and out without file dialogs. +// open_files, new_project, save_project and export: files in and out without file dialogs. calibrate: the +// Calibration menu's tests, which start a new project. #include "libslic3r/Format/ProjectStrategy.hpp" #include "McpPaths.hpp" @@ -10,13 +11,22 @@ #include "slic3r/GUI/MainFrame.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 @@ -48,18 +58,317 @@ json objects_summary(Plater& plater) return {{"objects", plater.model().objects.size()}, {"names", std::move(names)}, {"plates", plater.get_partplate_list().get_plate_count()}}; } +// Fails when the project has unsaved changes the caller did not say to drop. +void require_project_discardable(Plater& plater, bool discard) +{ + if (plater.is_project_dirty() && !discard) + throw ToolFailure("The project has unsaved changes; save_project first, or pass discard_changes: true"); +} + // Discards unsaved changes without a prompt when the caller said so, or fails. void require_clean_or_discard(Plater& plater, bool discard) { if (!plater.is_project_dirty()) return; - if (!discard) - throw ToolFailure("The project has unsaved changes; save_project first, or pass discard_changes: true"); + require_project_discardable(plater, discard); plater.new_project(/*skip_confirm=*/true, /*silent=*/true); } +// 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; +} + +// calibrate'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 {{"scope", "filament"}, {"keys", {"nozzle_temperature", "nozzle_temperature_initial_layer"}}}; + case CalibMode::Calib_Vol_speed_Tower: return {{"scope", "filament"}, {"keys", {"filament_max_volumetric_speed"}}}; + case CalibMode::Calib_PA_Tower: + case CalibMode::Calib_PA_Line: return {{"scope", "filament"}, {"keys", {"enable_pressure_advance", "pressure_advance"}}}; + case CalibMode::Calib_PA_Pattern: + return {{"scope", "filament"}, + {"keys", {"enable_pressure_advance", "pressure_advance", "adaptive_pressure_advance", "adaptive_pressure_advance_model"}}}; + case CalibMode::Calib_Flow_Rate: return {{"scope", "filament"}, {"keys", {"filament_flow_ratio"}}}; + case CalibMode::Calib_Retraction_tower: return {{"scope", "filament"}, {"keys", {"filament_retraction_length"}}}; + case CalibMode::Calib_VFA_Tower: + return {{"scope", "printer"}, {"keys", {"resonance_avoidance", "min_resonance_avoidance_speed", "max_resonance_avoidance_speed"}}}; + case CalibMode::Calib_Cornering: + return {{"scope", "printer"}, + {"keys", has_junction_deviation(printer) ? json{"machine_max_junction_deviation"} : json{"machine_max_jerk_x", "machine_max_jerk_y"}}}; + default: + return {{"scope", "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, discard_changes and 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() != "discard_changes" && it.key() != "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 (*t > 500 || *t < 155) { + *t = *t > 500 ? 500 : 155; + warnings.push_back(std::string(name) + " " + num(given) + " °C is outside the supported range 155-500 °C; clamped to " + num(*t) + " °C"); + } + if (const double rounded = std::floor(*t / 5) * 5; 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(McpService& service) { ToolRegistry& reg = service.registry(); @@ -115,22 +424,181 @@ void register_project_tools(McpService& service) reg.add(mutate_tool( "new_project", "New project", - "Start a new, empty project. Fails when the current project has unsaved changes unless discard_changes is true.", - object_schema({{"discard_changes", prop("boolean", "Drop unsaved changes without asking.")}}), + "Start a new, empty project. Fails when the current project has unsaved changes unless discard_changes is true. " + "Modified printer, process and filament presets are kept for the new project, unless changes is \"discard\", the " + "two answers of New Project's prompt. Reply: objects, names, plates; when presets had or have unsaved changes, " + "discarded and modified list per preset the keys dropped and the keys still unsaved.", + object_schema({{"discard_changes", prop("boolean", "Drop unsaved changes without asking.")}, + {"changes", enum_prop({"keep", "discard"}, "Unsaved changes of the presets: keep them (default) or drop them.")}}), [](const json& args, ToolContext& ctx) { - const bool discard = arg_bool(args, "discard_changes", false); - json out = ctx.run_ui([&] { + const bool discard = arg_bool(args, "discard_changes", false); + const bool discard_presets = arg_string(args, "changes", "keep") == "discard"; + json out = ctx.run_ui([&] { Plater& plater = ui_plater(); - if (plater.is_project_dirty() && !discard) - throw ToolFailure("The project has unsaved changes; save_project first, or pass discard_changes: true"); + require_project_discardable(plater, discard); + const json before = unsaved_changes(); + // The prompt's Discard, before the reset as in the GUI; only with changes to drop, since it + // reloads the presets, which can ask about the printer's. + if (discard_presets && wxGetApp().has_current_preset_changes()) + wxGetApp().discard_current_preset_changes(); plater.new_project(/*skip_confirm=*/true, /*silent=*/true); - return objects_summary(plater); + json o = objects_summary(plater); + o.update(unsaved_changes_outcome(before)); + return o; }); settle(ctx); return ToolResult::ok(out); }, true)); + reg.add(mutate_tool( + "calibrate", "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 (presets_changed). The test prints " + "with filament slot 1, so the filament tab is pointed at slot 1's preset. Omitted parameters take the dialog's " + "defaults (pressure advance's by the printer's extruder type); temperatures are clamped to 155-500 °C and rounded " + "down to 5 °C. Fails, changing nothing, when the project has unsaved changes (pass discard_changes) or presets do " + "(pass changes). Reply: test, project, params (the values used, which the journal records), objects, names, " + "plates, presets_changed, result_keys (where the measured value belongs), warnings, adjusted (vfa), and discarded " + "and modified as new_project. Then slice and export. To save a measured value: new_project {discard_changes, " + "changes: \"discard\"}, set_settings the value, save_preset.", + object_schema( + {{"test", enum_prop({"temperature", "max_volumetric", "pressure_advance", "flow_ratio", "retraction", "vfa", "cornering", + "input_shaping_freq", "input_shaping_damp"}, + "The test, named as the calib_* actions.")}, + {"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).")}, + {"discard_changes", prop("boolean", "Replace a project with unsaved changes.")}, + {"changes", enum_prop({"keep", "discard"}, "Unsaved preset changes: keep them for the test, or drop them first. " + "Required when presets are modified.")}}, + {"test"}), + [](const json& args, ToolContext& ctx) { + json recorded = args; + 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, "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); + require_project_discardable(plater, arg_bool(args, "discard_changes", false)); + // The GUI asks whether to keep or discard modified presets here; the caller answers with changes. + const json before = unsaved_changes(); + if (!before.empty() && !args.contains("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 changes: \"discard\" to drop them first, or \"keep\" " + "to run the test with them", + {{"modified", modified}}); + } + // The test prints with slot 1; switching the filament tab to it must not ask about another preset's changes. + const std::string& slot1 = bundle.filament_presets.front(); + if (!discard_presets && bundle.filaments.get_edited_preset().name != slot1 && 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 1 (\"" + slot1 + + "\"); pass 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(1); + + // 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, 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", 1}, + {"changes", changed_settings(filament_before, bundle.filaments.get_edited_preset().config)}}; + 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 get_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); + }, + true)); + reg.add(mutate_tool( "save_project", "Save the project", "Save the project as a .3mf at an absolute path without a dialog; it becomes the project's file.", diff --git a/src/slic3r/GUI/Mcp/McpToolsScene.cpp b/src/slic3r/GUI/Mcp/McpToolsScene.cpp index 879ca5115c..ddbe2e2467 100644 --- a/src/slic3r/GUI/Mcp/McpToolsScene.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsScene.cpp @@ -1,37 +1,52 @@ -// list_objects, select, transform, slice and cancel: the model on the plates, and the slice -// operation, which reports its own outcome per plate (see McpOperations). +// list_objects, select, transform, add_part, arrange, slice and cancel: the model on the plates, the +// arrange and Fill bed jobs, and the slice operation, which reports its own outcome per plate (see +// McpOperations). #include "CanvasTarget.hpp" #include "JobRegistry.hpp" +#include "McpCore.hpp" #include "libslic3r/Config.hpp" #include "libslic3r/Point.hpp" #include "McpOperations.hpp" +#include "McpPaths.hpp" #include "McpService.hpp" #include "McpTools.hpp" #include "McpTypes.hpp" +#include "UiInspector.hpp" #include "slic3r/GUI/3DScene.hpp" #include "slic3r/GUI/Camera.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/GUI.hpp" #include "slic3r/GUI/GUI_App.hpp" +#include "slic3r/GUI/GUI_Geometry.hpp" #include "slic3r/GUI/GUI_ObjectList.hpp" +#include "slic3r/GUI/Gizmos/GLGizmosManager.hpp" +#include "slic3r/GUI/Jobs/Job.hpp" +#include "slic3r/GUI/Jobs/Worker.hpp" #include "slic3r/GUI/MainFrame.hpp" #include "slic3r/GUI/NotificationManager.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/EmbossShape.hpp" #include "libslic3r/GCode/GCodeProcessor.hpp" +#include "libslic3r/GCode/GCodeStatistics.hpp" #include "libslic3r/Geometry.hpp" #include "libslic3r/Model.hpp" +#include "libslic3r/PrintConfig.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 @@ -39,7 +54,10 @@ #include #include #include +#include +#include #include +#include #include #include #include @@ -60,18 +78,6 @@ Vec3d to_vec3(const json& v, const char* what) return {v[0].get(), v[1].get(), v[2].get()}; } -const char* volume_type_name(ModelVolumeType type) -{ - switch (type) { - case ModelVolumeType::MODEL_PART: return "part"; - case ModelVolumeType::NEGATIVE_VOLUME: return "negative"; - case ModelVolumeType::PARAMETER_MODIFIER: return "modifier"; - case ModelVolumeType::SUPPORT_BLOCKER: return "support_blocker"; - case ModelVolumeType::SUPPORT_ENFORCER: return "support_enforcer"; - default: return "other"; - } -} - // The 3D canvas object operations act on: the assemble view while it is shown, else the Prepare // view, switched to when another is shown. GLCanvas3D& object_canvas() @@ -87,6 +93,50 @@ GLCanvas3D& object_canvas() return *plater.canvas3D(); } +} // namespace + +// Refused in the assemble view, which shows another canvas, and while a gizmo owns the selection. +GLCanvas3D& require_prepare_scene(Plater& plater) +{ + if (GLCanvas3D* assemble = plater.get_assmeble_canvas3D(); assemble != nullptr && plater.get_current_canvas3D() == assemble) + throw ToolFailure("Leave the assemble view first (set_view {view: \"3d\"})"); + GLCanvas3D& canvas = object_canvas(); + if (const auto type = canvas.get_gizmos_manager().get_current_type(); type != GLGizmosManager::Undefined) + throw ToolFailure("Close the " + gizmo_name(type) + " gizmo first (ui_click {gizmo: \"" + gizmo_name(type) + "\"})"); + // A canvas hidden while the model changed loads its scene on its next draw; the selection needs + // it now, as when the Prepare tab is requested while shown (Plater::priv::set_current_panel()). + if (canvas.is_reload_delayed()) + canvas.reload_scene(true); + return canvas; +} + +// The 3D view then selects a part on instance 0, since nothing else is selected. +void select_rows(ModelObject* object, ModelVolume* volume) +{ + ui_plater().deselect_all(); + wxGetApp().obj_list()->select_items(std::vector{{object, volume}}); +} + +namespace { + +// A scale argument: one factor or [x, y, z] factors, all positive. +Vec3d scale_factors(const json& s) +{ + const Vec3d f = s.is_number() ? Vec3d::Constant(s.get()) : to_vec3(s, "scale"); + if (f.minCoeff() <= 0.) + throw ToolFailure("scale factors must be positive"); + return f; +} + +// Where a part is on the bed, measured on instance 0: the Move panel's World position. +Vec3d part_position(const ModelObject& object, const ModelVolume& volume) +{ + return (object.instances.front()->get_matrix() * volume.get_matrix()).translation(); +} + +// A part's size along its own axes, in the object's frame: the instance's scale is left out. +Vec3d part_size(const ModelVolume& volume) { return volume.mesh().bounding_box().size().cwiseProduct(volume.get_scaling_factor().cwiseAbs()); } + // Facets painted in each state of an annotation: [none, state 1, state 2, ...], empty when unpainted. std::vector painted_facets(const FacetsAnnotation& paint, const ModelVolume& volume) { @@ -105,51 +155,47 @@ std::size_t painted_in(const std::vector& counts, EnforcerBlockerTy return std::size_t(state) < counts.size() ? counts[std::size_t(state)] : 0; } -// A part as list_objects describes it: its mesh, what is painted on it, and what a text or SVG part -// was made from. -json volume_info(const ModelVolume& v, std::size_t index) +json degrees(const Vec3d& radians) { return vec3(radians * Geometry::rad2deg(1.)); } + +json box_json(const BoundingBoxf3& box) { - const TriangleMesh& mesh = v.mesh(); - json out{{"index", index}, - {"name", v.name}, - {"type", volume_type_name(v.type())}, - {"triangles", mesh.its.indices.size()}, - {"mesh_volume", std::round(its_volume(mesh.its) * 1000.) / 1000.}}; - json painted = json::object(); - if (const auto c = painted_facets(v.supported_facets, v); !c.empty()) - painted["supports"] = {{"enforcers", painted_in(c, EnforcerBlockerType::ENFORCER)}, {"blockers", painted_in(c, EnforcerBlockerType::BLOCKER)}}; - if (const auto c = painted_facets(v.seam_facets, v); !c.empty()) - painted["seam"] = {{"enforcers", painted_in(c, EnforcerBlockerType::ENFORCER)}, {"blockers", painted_in(c, EnforcerBlockerType::BLOCKER)}}; - if (const auto c = painted_facets(v.fuzzy_skin_facets, v); !c.empty()) - painted["fuzzy_skin"] = painted_in(c, EnforcerBlockerType::FUZZY_SKIN); - if (const auto c = painted_facets(v.mmu_segmentation_facets, v); !c.empty()) { - json mmu = json::object(); - for (std::size_t state = 1; state < c.size(); ++state) - if (c[state] > 0) - mmu[std::to_string(state)] = c[state]; // filament (extruder) number - painted["mmu"] = std::move(mmu); - } - if (!v.texture_displacement_layers.empty()) { - json layers = json::array(); - for (const TextureDisplacementLayer& layer : v.texture_displacement_layers) { - json l{{"slot", layer.slot}, {"name", layer.name}, {"path", layer.path}, {"depth_mm", layer.depth_mm}}; - if (layer.slot >= 0 && layer.slot < int(TEXTURE_DISPLACEMENT_MAX_LAYERS)) - l["painted"] = painted_in(painted_facets(v.texture_displacement_facet(layer.slot), v), EnforcerBlockerType::ENFORCER); - layers.push_back(std::move(l)); - } - painted["texture"] = std::move(layers); - } - if (!painted.empty()) - out["painted"] = std::move(painted); - if (v.text_configuration) { - const EmbossStyle& style = v.text_configuration->style; - out["text"] = {{"text", v.text_configuration->text}, - {"style", style.name}, - {"font", style.prop.face_name ? *style.prop.face_name : style.path}}; - } - if (v.emboss_shape && v.emboss_shape->svg_file) - out["svg"] = {{"path", v.emboss_shape->svg_file->path}, {"path_in_3mf", v.emboss_shape->svg_file->path_in_3mf}}; - return out; + if (!box.defined) + return nullptr; + return {{"min", vec3(box.min)}, {"max", vec3(box.max)}, {"size", vec3(box.size())}}; +} + +// The filament a config's own "extruder" names, 0 when it names none ("Default"). +int own_filament(const ModelConfig& config) +{ + const ConfigOption* opt = config.option("extruder"); + return opt != nullptr ? opt->getInt() : 0; +} + +int object_filament(const ModelObject& object) { return std::max(own_filament(object.config), 1); } + +// The filament the object list's column shows for a part: a model part prints with its own, else +// its object's; a modifier overrides the filament of what it covers only when it has its own; other +// volumes print nothing. 0 for none. +int volume_filament(const ModelVolume& volume) +{ + const int own = own_filament(volume.config); + if (volume.is_model_part()) + return own > 0 ? own : object_filament(*volume.get_object()); + return volume.is_modifier() ? own : 0; +} + +// An instance as list_objects describes it, except its plate and canvas rectangle, which the GUI knows. +json instance_info(const ModelObject& object, std::size_t index) +{ + const ModelInstance& inst = *object.instances[index]; + return {{"index", index}, + {"offset", vec3(inst.get_offset())}, + {"rotation_deg", degrees(inst.get_rotation())}, + {"scale", vec3(inst.get_scaling_factor())}, + // Whether, not along which axis: a mirror in X equals one in Y plus a half turn. + {"mirrored", inst.is_left_handed()}, + {"printable", inst.printable}, + {"bbox", box_json(object.instance_bounding_box(index))}}; } // The rectangle of logical canvas pixels an instance covers in the shown 3D view, or null when none @@ -190,38 +236,22 @@ json list_objects(const json& args) json items = json::array(); for (size_t i = 0; i < objects.size(); ++i) { const ModelObject* o = objects[i]; - json instances = json::array(); - bool on_plate = only_plate < 0; + std::vector on(o->instances.size()); + bool on_plate = only_plate < 0; for (size_t j = 0; j < o->instances.size(); ++j) { - const ModelInstance* inst = o->instances[j]; - const int plate = plates.find_instance(int(i), int(j)); - on_plate = on_plate || plate == only_plate; - const Vec3d rot = inst->get_rotation(); - instances.push_back({{"index", j}, - {"plate", plate}, - {"offset", vec3(inst->get_offset())}, - {"rotation_deg", vec3(Vec3d(Geometry::rad2deg(rot.x()), Geometry::rad2deg(rot.y()), Geometry::rad2deg(rot.z())))}, - {"scale", vec3(inst->get_scaling_factor())}, - {"printable", inst->printable}}); - if (canvas != nullptr) - instances.back()["screen"] = screen_rect(*canvas, int(i), int(j)); + on[j] = plates.find_instance(int(i), int(j)); + on_plate = on_plate || on[j] == only_plate; } if (!on_plate) continue; - json volumes = json::array(); - for (size_t v = 0; v < o->volumes.size(); ++v) - volumes.push_back(volume_info(*o->volumes[v], v)); - const BoundingBoxf3 bb = o->instance_bounding_box(0); - json overrides = json::array(); - for (const std::string& key : o->config.keys()) - overrides.push_back(key); - items.push_back({{"index", i}, - {"name", o->name}, - {"instances", std::move(instances)}, - {"volumes", std::move(volumes)}, - {"bbox", {{"min", vec3(bb.min)}, {"max", vec3(bb.max)}, {"size", vec3(bb.size())}}}, - {"brim_ears", o->brim_points.size()}, - {"overrides", std::move(overrides)}}); + json item = object_info(*o, i); + for (size_t j = 0; j < o->instances.size(); ++j) { + json& inst = item["instances"][j]; + inst["plate"] = on[j]; + if (canvas != nullptr) + inst["screen"] = screen_rect(*canvas, int(i), int(j)); + } + items.push_back(std::move(item)); } json out = page(items, args, 200); out["plates"] = plates.get_plate_count(); @@ -243,46 +273,622 @@ json selection_summary(const Selection& sel) return out; } -// Per-plate statistics of a valid slice result. -json plate_stats(PartPlate& plate) -{ - json out = json::object(); - GCodeProcessorResult* result = plate.get_slice_result(); - if (result == nullptr) - return out; - const auto& stats = result->print_statistics; - const double seconds = stats.modes[static_cast(PrintEstimatedStatistics::ETimeMode::Normal)].time; - double meters = 0., grams = 0.; - for (const auto& [role, used] : stats.used_filaments_per_role) { - meters += used.first; - grams += used.second; - } - out["time_s"] = std::lround(seconds); - out["time"] = get_time_dhms(float(seconds)); - out["filament_m"] = std::round(meters * 100.) / 100.; - out["filament_g"] = std::round(grams * 100.) / 100.; - return out; -} - struct SliceTicket { SliceTicketState state; std::vector plates; }; +// 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) +{ + ModelObject* object = plater.model().objects[size_t(oi)]; + const int ii = arg_int(args, "instance", 0); + if (ii < 0 || ii >= int(object->instances.size())) + throw ToolFailure("instance index out of range"); + ModelInstance* inst = object->instances[size_t(ii)]; + const bool absolute = arg_string(args, "mode", "relative") == "absolute"; + + std::optional translate, rotate, scale; + if (args.contains("translate")) + translate = to_vec3(args["translate"], "translate"); + if (args.contains("rotate")) + rotate = to_vec3(args["rotate"], "rotate") * Geometry::deg2rad(1.0); + if (args.contains("scale")) + scale = absolute ? scale_factors(args["scale"]) : Vec3d(inst->get_scaling_factor().cwiseProduct(scale_factors(args["scale"]))); + else if (args.contains("size")) + // Along the object's own axes: its model parts unrotated, times the instance's scale. + scale = Vec3d(inst->get_scaling_factor().cwiseProduct( + size_factors(object->raw_mesh_bounding_box().size().cwiseProduct(inst->get_scaling_factor().cwiseAbs()), args["size"]))); + PartPlateList& plates = plater.get_partplate_list(); + Vec3d to_plate = Vec3d::Zero(); + if (args.contains("plate")) { + const int to = arg_int(args, "plate", 0); + if (to >= plates.get_plate_count()) + throw ToolFailure("plate " + std::to_string(to) + " does not exist; run_action plate_add makes one"); + const int from = plates.find_instance(oi, ii); + if (from < 0) + throw ToolFailure("instance " + std::to_string(ii) + " is off every plate; place it with translate (absolute) first"); + to_plate = plates.get_plate(to)->get_origin() - plates.get_plate(from)->get_origin(); + } + + plater.take_snapshot("Transform object"); + if (translate) + inst->set_offset(absolute ? *translate : Vec3d(inst->get_offset() + *translate)); + if (rotate) { + if (absolute) + inst->set_rotation(*rotate); + else { + const Transform3d rot = Geometry::rotation_transform(*rotate) * Geometry::rotation_transform(inst->get_rotation()); + inst->set_rotation(Geometry::extract_euler_angles(rot)); + } + } + if (scale) + inst->set_scaling_factor(*scale); + // The plate move is one more relative translate, after the others. + inst->set_offset(inst->get_offset() + to_plate); + // The bounding box is cached: ensure_on_bed() must measure the new placement. + object->invalidate_bounding_box(); + if (arg_bool(args, "drop_to_bed", true)) + object->ensure_on_bed(); + // Slicing and the object list read the plate an instance is on from the plate registry, which + // GLCanvas3D::do_move() updates for a person's moves. + plates.notify_instance_update(oi, ii); + wxGetApp().obj_list()->update_plate_values_for_items(); + plater.changed_object(oi); + return {{"object", oi}, + {"instance", ii}, + {"offset", vec3(inst->get_offset())}, + {"scale", vec3(inst->get_scaling_factor())}, + {"plate", plates.find_instance(oi, ii)}}; +} + +// transform on a part: the Object manipulation panel's path with the part selected, so do_move(), +// do_rotate() and do_scale() write the part, drop the object (Auto Drop), register its instances +// with their plates and update the object list. Translate and rotate are along the bed's axes on +// instance 0, scale and size along the part's own axes. +json transform_part(Plater& plater, int oi, const json& args) +{ + ModelObject* object = plater.model().objects[size_t(oi)]; + const int vi = arg_int(args, "volume", 0); + if (vi >= int(object->volumes.size())) + throw ToolFailure("volume index out of range"); + // A single part has no row of its own in the object list, so the panel can't select it. + if (object->volumes.size() == 1) + throw ToolFailure("object " + std::to_string(oi) + " has one part; transform the instance"); + if (arg_int(args, "instance", 0) != 0) + throw ToolFailure("a part belongs to its object and moves on every instance; leave instance out"); + if (args.contains("plate")) + throw ToolFailure("plate moves an instance; leave volume out"); + const bool absolute = arg_string(args, "mode", "relative") == "absolute"; + if (absolute && args.contains("rotate")) + throw ToolFailure("rotate a part relative to its current rotation (mode \"relative\")"); + ModelVolume* volume = object->volumes[size_t(vi)]; + GLCanvas3D& canvas = require_prepare_scene(plater); + + std::optional translate, rotate, scale; + if (args.contains("translate")) { + const Vec3d t = to_vec3(args["translate"], "translate"); + translate = absolute ? Vec3d(t - part_position(*object, *volume)) : t; + } + if (args.contains("rotate")) + rotate = to_vec3(args["rotate"], "rotate") * Geometry::deg2rad(1.0); + // Factors on the current scale, as the panel's change_scale_value() and change_size_value() + // compute them: Selection::scale() multiplies a part's scale whatever the transformation type. + if (args.contains("scale")) + scale = absolute ? Vec3d(scale_factors(args["scale"]).cwiseQuotient(volume->get_scaling_factor())) : scale_factors(args["scale"]); + else if (args.contains("size")) + scale = size_factors(part_size(*volume), args["size"]); + + select_rows(object, volume); + Selection& sel = canvas.get_selection(); + if (!sel.is_single_volume_or_modifier()) + throw ToolFailure("part " + std::to_string(vi) + " of object " + std::to_string(oi) + " could not be selected"); + plater.take_snapshot("Transform part", UndoRedo::SnapshotType::GizmoAction); + if (translate) { + sel.setup_cache(); + sel.translate(*translate, TransformationType::World_Relative_Joint); + canvas.do_move(""); + } + if (rotate) { + sel.setup_cache(); + sel.rotate(*rotate, TransformationType::World_Relative_Joint); + canvas.do_rotate(""); + } + if (scale) { + sel.setup_cache(); + sel.scale(*scale, TransformationType::Local_Relative_Joint); + canvas.do_scale(""); + } + return {{"object", oi}, {"volume", vi}, {"size", vec3(part_size(*volume))}, {"volume_info", volume_info(*volume, size_t(vi))}}; +} + +// An arrange or Fill bed the call started, and what its reply compares with once the job is done. +struct ArrangeStart +{ + json settings; + json skipped = json::array(); // plates the all-plates arrange leaves alone + std::string note; + std::set> notifications; // shown before it started + int fill_object = -1; + bool copies = false; + std::size_t before = 0; // the fill object's instances, or the objects for copies +}; + +std::set> shown_notifications(Plater& plater) +{ + std::set> out; + for (const NotificationSummary& n : plater.get_notification_manager()->summaries()) + out.emplace(n.type, n.text); + return out; +} + +// Validates arrange's arguments, applies its settings and starts the job the toolbar's Arrange, a +// plate's Arrange icon or Fill bed starts. UI thread. +ArrangeStart start_arrange(Plater& plater, const json& args) +{ + GLCanvas3D& canvas = require_prepare_scene(plater); + PartPlateList& plates = plater.get_partplate_list(); + const ModelObjectPtrs& objects = plater.model().objects; + ArrangeStart start; + const bool fill = args.contains("fill"); + if (fill && args.contains("plates")) + throw ToolFailure("fill fills the object's own plate; leave plates out"); + if (!fill && args.contains("fill_with")) + throw ToolFailure("fill_with goes with fill"); + if (objects.empty()) + throw ToolFailure("There are no objects to arrange"); + int plate = -1; // every unlocked plate + if (fill) { + start.fill_object = arg_int(args, "fill", 0); + if (start.fill_object >= int(objects.size())) + throw ToolFailure("object index out of range"); + select_rows(objects[size_t(start.fill_object)], nullptr); + if (!plater.can_increase_instances()) + throw ToolFailure("Fill bed refuses object " + std::to_string(start.fill_object) + + ": it is a cut object or has an instance that is not printable"); + } else if (const json p = args.value("plates", json("all")); p.is_string()) { + if (p == "current") + plate = plates.get_curr_plate_index(); + else if (p != "all") + throw ToolFailure("plates is \"all\", \"current\" or a plate index"); + } else { + plate = p.get(); + if (plate < 0 || plate >= plates.get_plate_count()) + throw ToolFailure("plate " + std::to_string(plate) + " does not exist; there are " + std::to_string(plates.get_plate_count())); + } + const std::string plate_name = "Plate " + std::to_string(plate); + if (plate >= 0 && plates.get_plate(plate)->is_locked()) + throw ToolFailure(plate_name + " is locked; unlock it first (run_action plate_goto with param " + std::to_string(plate) + + ", then plate_toggle_lock)"); + if (plate >= 0 && plates.get_plate(plate)->empty()) + throw ToolFailure(plate_name + " has no objects to arrange"); + + // Applied and saved as the panel does, once the call is known to go ahead. + GLCanvas3D::ArrangeSettings& settings = canvas.get_arrange_settings(); + start.note = apply_arrange_args(settings, args); + if (args.contains("spacing") || args.contains("rotate") || args.contains("multi_material")) + canvas.store_arrange_settings(); + start.settings = arrange_settings_json(settings); + start.settings["by_object"] = settings.is_seq_print; + + // A plate whose print sequence differs from the project's is arranged with automatic spacing on + // its own (init_arrange_params()), and left alone by the all-plates arrange (prepare_all()). + for (int i = 0; i < plates.get_plate_count(); ++i) { + PartPlate* pp = plates.get_plate(i); + bool same = true; + pp->get_real_print_seq(&same); + if (i == plate && !same && settings.distance > 0.f) + start.note += std::string(start.note.empty() ? "" : " ") + plate_name + + "'s print sequence differs from the project's, so its spacing was automatic."; + if (plate < 0 && !fill && !pp->empty() && (pp->is_locked() || !same)) + start.skipped.push_back({{"plate", i}, + {"reason", pp->is_locked() ? "locked" : "its print sequence differs from the project's; arrange it by index"}}); + } + + start.notifications = shown_notifications(plater); + if (fill) { + start.copies = arg_string(args, "fill_with", "instances") == "copies"; + start.before = start.copies ? objects.size() : objects[size_t(start.fill_object)]->instances.size(); + if (start.copies) + plater.fill_bed_with_copies(); + else + plater.fill_bed_with_instances(); + } else if (plate < 0) { + plater.set_prepare_state(Job::PREPARE_STATE_DEFAULT); + plater.arrange(); + } else { + if (plate != plates.get_curr_plate_index() && plater.select_plate(plate) != 0) + throw ToolFailure(plate_name + " could not be selected"); + plater.set_prepare_state(Job::PREPARE_STATE_MENU); + plater.arrange(); + } + if (plater.get_ui_job_worker().is_idle()) + throw ToolFailure("The arrangement did not start"); + return start; +} + +// arrange's reply once the worker is idle. UI thread. +json arrange_reply(Plater& plater, const ArrangeStart& start) +{ + PartPlateList& plates = plater.get_partplate_list(); + const ModelObjectPtrs& objects = plater.model().objects; + json out{{"settings", start.settings}, {"plates", plates.get_plate_count()}}; + if (start.fill_object >= 0 && start.fill_object < int(objects.size())) { + const std::size_t now = start.copies ? objects.size() : objects[size_t(start.fill_object)]->instances.size(); + out.update({{"object", start.fill_object}, + {"filled_with", start.copies ? "copies" : "instances"}, + {"added", int(now) - int(start.before)}, + {start.copies ? "objects" : "instances", now}, + {"plate", plates.find_instance(start.fill_object, 0)}}); + } + // Instances arrange could not fit: the job reports them only in its status line. Measured rather + // than read from the plate registry, which Fill bed leaves without its new instances. + json off_plate = json::array(); + for (std::size_t o = 0; o < objects.size(); ++o) + for (std::size_t i = 0; i < objects[o]->instances.size(); ++i) { + bool on_plate = false; + for (int p = 0; p < plates.get_plate_count() && !on_plate; ++p) + on_plate = plates.get_plate(p)->intersect_instance(int(o), int(i)); + if (!on_plate) + off_plate.push_back({o, i}); + } + out["off_plate"] = std::move(off_plate); + if (!start.skipped.empty()) + out["skipped_plates"] = start.skipped; + // What the job told the person: objects too large for any bed (a plain notification), zero-size + // objects and locked plates (warnings). Selection info and progress are left out. + json notes = json::array(); + for (const NotificationSummary& n : plater.get_notification_manager()->summaries()) + if ((n.level == "warning" || n.level == "error" || n.type == int(NotificationType::CustomNotification)) && + start.notifications.count({n.type, n.text}) == 0) + notes.push_back({{"level", n.level}, {"text", n.text}}); + if (!notes.empty()) + out["notifications"] = std::move(notes); + if (!start.note.empty()) + out["note"] = start.note; + return out; +} + +// The object list's name of an add_part shape, which its menus and the Primitive size dialog use; +// nullptr for another shape. +const char* shape_type_name(const std::string& shape) +{ + static const std::pair names[] = {{"cube", "Cube"}, {"cylinder", "Cylinder"}, {"sphere", "Sphere"}, + {"cone", "Cone"}, {"disc", "Disc"}, {"torus", "Torus"}}; + for (const auto& [shape_name, type_name] : names) + if (shape == shape_name) + return type_name; + return nullptr; +} + +// add_part: what the object's context menu Add items do, with the size or the file given instead +// of asked for, then a move to `position` along the Move panel's path. Everything the arguments +// can tell is checked before anything changes. +json add_part(Plater& plater, const json& args) +{ + const ModelObjectPtrs& objects = plater.model().objects; + const int oi = arg_int(args, "object", -1); + if (oi < 0 || oi >= int(objects.size())) + throw ToolFailure("object index out of range"); + const ModelVolumeType type = volume_type_from_name(arg_string(args, "type")); + if (type == ModelVolumeType::INVALID) + throw ToolFailure("type must be part, negative, modifier, support_blocker, support_enforcer or precise_seam"); + if (args.contains("shape") == args.contains("path")) + throw ToolFailure("Give shape or path"); + const std::string shape = arg_string(args, "shape"); + std::vector size; + wxArrayString files; + if (!shape.empty()) + size = part_shape_size(shape, args.value("size", json())); + else { + if (args.contains("size")) + throw ToolFailure("size goes with shape; a file's part keeps the file's size"); + std::string err; + const auto file = resolve_input_path(arg_string(args, "path"), err); + if (!file) + throw ToolFailure(err); + // The SVG gizmo makes SVG parts, placed where the camera looks. + if (boost::algorithm::iends_with(path_to_utf8(*file), ".svg")) + throw ToolFailure("SVG parts come from run_action add_primitive_svg (a part of the selected object) or the SVG gizmo"); + files.Add(from_path(*file)); + } + std::optional position; + if (args.contains("position")) + position = to_vec3(args["position"], "position"); + ModelObject* object = objects[size_t(oi)]; + // Adding a shape folds instance 0's transformation into the parts, which other instances + // would not follow. + if (object->instances.size() > 1) + throw ToolFailure("object " + std::to_string(oi) + " has " + std::to_string(object->instances.size()) + + " instances; add the part before adding instances"); + GLCanvas3D& canvas = require_prepare_scene(plater); + + // The menu's functions add to the object selected in the object list. + select_rows(object, nullptr); + ObjectList* list = wxGetApp().obj_list(); + if (list->get_selected_obj_idx() != oi || !list->is_instance_or_object_selected()) + throw ToolFailure("object " + std::to_string(oi) + " could not be selected"); + + // The add's own snapshot ("Add primitive", "Load Part", "Load Modifier") is the call's only undo step. + Plater::SingleSnapshot single(&plater); + const std::set before(object->volumes.begin(), object->volumes.end()); + if (!files.IsEmpty()) { + std::string error; + list->load_subobject(type, files, false, &error); + if (!error.empty()) + throw ToolFailure("The file could not be loaded: " + error); + } else + list->load_generic_subobject(shape_type_name(shape), type, false, size); + const auto added = std::find_if(object->volumes.begin(), object->volumes.end(), + [&before](const ModelVolume* v) { return before.count(v) == 0; }); + if (added == object->volumes.end()) + throw ToolFailure("The part was not added"); + ModelVolume* volume = *added; + + if (position) { + select_rows(object, volume); + Selection& sel = canvas.get_selection(); + if (!sel.is_single_volume_or_modifier()) + throw ToolFailure("The part was added but could not be selected to move it"); + sel.setup_cache(); + sel.translate(*position - part_position(*object, *volume), TransformationType::World_Relative_Joint); + canvas.do_move(""); + } + const auto vi = std::size_t(std::find(object->volumes.begin(), object->volumes.end(), volume) - object->volumes.begin()); + return {{"object", oi}, {"volume", vi}, {"volume_count", object->volumes.size()}, {"volume_info", volume_info(*volume, vi)}}; +} + } // namespace +const char* volume_type_name(ModelVolumeType type) +{ + if (is_precise_seam(type)) + return "precise_seam"; + switch (type) { + case ModelVolumeType::MODEL_PART: return "part"; + case ModelVolumeType::NEGATIVE_VOLUME: return "negative"; + case ModelVolumeType::PARAMETER_MODIFIER: return "modifier"; + case ModelVolumeType::SUPPORT_BLOCKER: return "support_blocker"; + case ModelVolumeType::SUPPORT_ENFORCER: return "support_enforcer"; + default: return "other"; + } +} + +ModelVolumeType volume_type_from_name(const std::string& name) +{ + for (const ModelVolumeType type : {ModelVolumeType::MODEL_PART, ModelVolumeType::NEGATIVE_VOLUME, ModelVolumeType::PARAMETER_MODIFIER, + ModelVolumeType::SUPPORT_BLOCKER, ModelVolumeType::SUPPORT_ENFORCER, ModelVolumeType::PRECISE_SEAM_CENTER}) + if (name == volume_type_name(type)) + return type; + return ModelVolumeType::INVALID; +} + +std::vector part_shape_size(const std::string& shape, const json& size) +{ + const char* type_name = shape_type_name(shape); + if (type_name == nullptr) + throw ToolFailure("shape must be cube, cylinder, sphere, cone, disc or torus"); + if (size.is_null()) + return {}; + const std::vector names = primitive_size_names(type_name); + std::vector out; + if (size.is_array() && size.size() == names.size()) + for (const json& value : size) + if (value.is_number() && std::isfinite(value.get()) && value.get() > 0.) + out.push_back(value.get()); + if (out.size() != names.size()) { + std::string fields; + for (const char* name : names) + fields += (fields.empty() ? "" : ", ") + std::string(name); + throw ToolFailure("A " + shape + "'s size is [" + fields + "] in mm, each above 0"); + } + return out; +} + +json object_info(const ModelObject& object, std::size_t index) +{ + json instances = json::array(); + for (std::size_t j = 0; j < object.instances.size(); ++j) + instances.push_back(instance_info(object, j)); + json volumes = json::array(); + for (std::size_t v = 0; v < object.volumes.size(); ++v) + volumes.push_back(volume_info(*object.volumes[v], v)); + json overrides = json::array(); + for (const std::string& key : object.config.keys()) + overrides.push_back(key); + json out{{"index", index}, + {"name", object.name}, + {"filament", object_filament(object)}, + {"auto_drop", object.auto_drop}, + {"instances", std::move(instances)}, + {"volumes", std::move(volumes)}, + {"bbox", object.instances.empty() ? json(nullptr) : box_json(object.instance_bounding_box(0))}, + {"brim_ears", object.brim_points.size()}, + {"overrides", std::move(overrides)}}; + if (!object.layer_config_ranges.empty()) + out["layer_config_ranges"] = layer_config_ranges_json(object.layer_config_ranges); + if (json profile = layer_height_profile_json(object.layer_height_profile.get()); !profile.is_null()) + out["layer_height_profile"] = std::move(profile); + return out; +} + +json volume_info(const ModelVolume& v, std::size_t index) +{ + const TriangleMesh& mesh = v.mesh(); + const double mesh_volume = its_volume(mesh.its); + json out{{"index", index}, + {"name", v.name}, + {"type", volume_type_name(v.type())}, + {"rotation_deg", degrees(v.get_rotation())}, + {"scale", vec3(v.get_scaling_factor())}, + {"mirrored", v.is_left_handed()}, + {"triangles", mesh.its.indices.size()}, + {"mesh_volume", std::round(mesh_volume * 1000.) / 1000.}}; + if (v.is_precise_seam()) // the 3MF type name without its "precise_seam_" prefix: center, left, ... + out["subtype"] = ModelVolume::type_to_string(v.type()).substr(std::strlen("precise_seam_")); + if (const int filament = volume_filament(v); filament > 0) + out["filament"] = filament; + // On the bed, measured on instance 0 as the object's bbox is. + if (const ModelObject* object = v.get_object(); object != nullptr && !object->instances.empty()) { + const Transform3d placed = object->instances.front()->get_matrix() * v.get_matrix(); + out["position"] = vec3(placed.translation()); + out["bbox"] = box_json(mesh.transformed_bounding_box(placed)); + out["scaled_volume"] = std::round(mesh_volume * std::abs(placed.linear().determinant()) * 1000.) / 1000.; + } + json painted = json::object(); + if (const auto c = painted_facets(v.supported_facets, v); !c.empty()) + painted["supports"] = {{"enforcers", painted_in(c, EnforcerBlockerType::ENFORCER)}, {"blockers", painted_in(c, EnforcerBlockerType::BLOCKER)}}; + if (const auto c = painted_facets(v.seam_facets, v); !c.empty()) + painted["seam"] = {{"enforcers", painted_in(c, EnforcerBlockerType::ENFORCER)}, {"blockers", painted_in(c, EnforcerBlockerType::BLOCKER)}}; + if (const auto c = painted_facets(v.fuzzy_skin_facets, v); !c.empty()) + painted["fuzzy_skin"] = painted_in(c, EnforcerBlockerType::FUZZY_SKIN); + if (const auto c = painted_facets(v.mmu_segmentation_facets, v); !c.empty()) { + json mmu = json::object(); + for (std::size_t state = 1; state < c.size(); ++state) + if (c[state] > 0) + mmu[std::to_string(state)] = c[state]; // filament (extruder) number + painted["mmu"] = std::move(mmu); + } + if (!v.texture_displacement_layers.empty()) { + json layers = json::array(); + for (const TextureDisplacementLayer& layer : v.texture_displacement_layers) { + json l{{"slot", layer.slot}, {"name", layer.name}, {"path", layer.path}, {"depth_mm", layer.depth_mm}}; + if (layer.slot >= 0 && layer.slot < int(TEXTURE_DISPLACEMENT_MAX_LAYERS)) + l["painted"] = painted_in(painted_facets(v.texture_displacement_facet(layer.slot), v), EnforcerBlockerType::ENFORCER); + layers.push_back(std::move(l)); + } + painted["texture"] = std::move(layers); + } + if (!painted.empty()) + out["painted"] = std::move(painted); + if (v.text_configuration) { + const EmbossStyle& style = v.text_configuration->style; + out["text"] = {{"text", v.text_configuration->text}, + {"style", style.name}, + {"font", style.prop.face_name ? *style.prop.face_name : style.path}}; + } + if (v.emboss_shape && v.emboss_shape->svg_file) + out["svg"] = {{"path", v.emboss_shape->svg_file->path}, {"path_in_3mf", v.emboss_shape->svg_file->path_in_3mf}}; + return out; +} + +std::string apply_arrange_args(GLCanvas3D::ArrangeSettings& settings, const json& args) +{ + if (args.contains("spacing")) + settings.distance = std::max(0.f, args["spacing"].get()); + if (args.contains("rotate")) + settings.enable_rotation = args["rotate"].get(); + if (args.contains("multi_material")) + settings.allow_multi_materials_on_same_plate = args["multi_material"].get(); + if (args.contains("align_y")) + settings.align_to_y_axis = args["align_y"].get(); + // The panel disables Align to Y axis while rotation is on, and clears it. + if (settings.enable_rotation && settings.align_to_y_axis) { + settings.align_to_y_axis = false; + if (arg_bool(args, "align_y", false)) + return "align_y is off while rotate is on, as in the Arrange options panel."; + } + return {}; +} + +json arrange_settings_json(const GLCanvas3D::ArrangeSettings& settings) +{ + return {{"spacing", std::round(double(settings.distance) * 100.) / 100.}, + {"rotate", settings.enable_rotation}, + {"align_y", settings.align_to_y_axis}, + {"multi_material", settings.allow_multi_materials_on_same_plate}}; +} + +Vec3d size_factors(const Vec3d& current, const json& size) +{ + if (!size.is_array() || size.size() != 3) + throw ToolFailure("size must be [x, y, z] mm, with null for an axis to keep"); + Vec3d factors = Vec3d::Ones(); + int given = 0, axis = 0; + for (int i = 0; i < 3; ++i) { + if (size[i].is_null()) + continue; + if (!size[i].is_number() || size[i].get() <= 0.) + throw ToolFailure("sizes must be positive numbers of mm"); + if (current[i] < EPSILON) + throw ToolFailure(std::string("it is flat along ") + "XYZ"[i] + ", so that size can't be set"); + factors[i] = size[i].get() / current[i]; + ++given; + axis = i; + } + if (given == 0) + throw ToolFailure("size needs a number for at least one axis"); + 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; +} + void register_scene_tools(McpService& service) { ToolRegistry& reg = service.registry(); reg.add(inspect_tool( "list_objects", "List objects", - "Objects in the project with their instances (plate, position, rotation in degrees, scale), parts and modifiers " - "(triangle count and mesh volume in mm3; painted facets: supports and seam enforcers/blockers, fuzzy_skin, mmu per " - "filament, texture per layer; a text part's text and font, an SVG part's file), bounding box, brim ear count and " - "the settings they override. Indices are what select, transform, ui_mouse targets and the object/volume settings " - "scopes take.", + "Objects in the project: filament, auto_drop, bounding box (instance 0), brim ear count and the settings they " + "override; their instances (plate, offset, rotation in degrees, scale, mirrored, bbox); their parts and modifiers " + "(type, with subtype for a precise seam; filament: a part's own or its object's, a modifier's only when it sets " + "one; position, bbox and scaled_volume in mm3 on the bed, measured on instance 0; rotation_deg and scale in the " + "object's frame; mirrored; triangle count; mesh_volume, the unscaled mesh's mm3; painted facets: supports and " + "seam enforcers/blockers, fuzzy_skin, mmu per filament, texture per layer; a text part's text and font, an SVG " + "part's file); its height range modifiers when it has any (layer_config_ranges: [{min_z, max_z, values}], as " + "set_layer_ranges takes them) and its variable layer height profile when it has one (layer_height_profile: " + "{points, min_height, max_height}). A bbox is {min, max, size} in mm of model parts only, so unlike the panel's Size it " + "leaves out modifiers. Indices are what select, transform, ui_mouse targets and the object/volume settings scopes take.", object_schema({{"plate", {{"type", "integer"}, {"minimum", 0}, {"description", "Only objects on this plate."}}}, {"screen", prop("boolean", "Add each instance's rectangle in the shown 3D view, logical pixels [x, y, w, h].")}, {"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 500}}}, @@ -352,72 +958,122 @@ void register_scene_tools(McpService& service) })); reg.add(mutate_tool( - "transform", "Move, rotate or scale an instance", - "Change one instance's placement. translate is in mm, rotate in degrees about X/Y/Z, scale a factor (one number or " - "[x, y, z]). mode \"relative\" (default) adds to the current placement, \"absolute\" sets it. The object is dropped " - "back onto the bed afterwards unless drop_to_bed is false. One undo step.", + "transform", "Move, rotate or scale an instance or a part", + "Change one instance's placement, or one part's with volume. translate is in mm, rotate in degrees about X/Y/Z, " + "scale a factor (one number or [x, y, z]), size [x, y, z] mm along the object's or part's own axes, plate moves " + "the instance onto that plate at the same place. mode \"relative\" (default) adds to the current placement, " + "\"absolute\" sets it. An instance is dropped back onto the bed unless drop_to_bed is false. A part moves as the " + "Object manipulation panel moves it: translate and rotate along the bed's axes, measured on instance 0, scale and " + "size along its own axes; every instance shows the change, and Auto Drop may lower the object afterwards. One " + "undo step. Replies with the instance's offset, scale and plate, or the part's size along its own axes and its " + "list_objects entry (volume_info).", object_schema({{"object", {{"type", "integer"}, {"minimum", 0}}}, {"instance", {{"type", "integer"}, {"minimum", 0}, {"description", "Default 0."}}}, + {"volume", {{"type", "integer"}, {"minimum", 0}, {"description", "Transform this part instead of the instance."}}}, {"translate", array_prop({{"type", "number"}}, "[x, y, z] mm")}, - {"rotate", array_prop({{"type", "number"}}, "[x, y, z] degrees")}, + {"rotate", array_prop({{"type", "number"}}, "[x, y, z] degrees; relative only for a part")}, {"scale", {{"type", {"number", "array"}}, {"description", "Factor or [x, y, z] factors."}}}, + {"size", array_prop({{"type", {"number", "null"}}}, "[x, y, z] mm, null keeps an axis; one number and two " + "nulls keep the proportions. Not with scale.")}, + {"plate", {{"type", "integer"}, {"minimum", 0}, {"description", "Move the instance to this plate."}}}, {"mode", enum_prop({"relative", "absolute"}, "Default relative.")}, - {"drop_to_bed", prop("boolean", "Default true.")}}, + {"drop_to_bed", prop("boolean", "Default true; instances only.")}}, {"object"}), [](const json& args, ToolContext& ctx) { json out = ctx.run_ui([&]() -> json { - Plater& plater = ui_plater(); - ModelObjectPtrs& objects = plater.model().objects; - const int oi = arg_int(args, "object", -1); - if (oi < 0 || oi >= int(objects.size())) + Plater& plater = ui_plater(); + const int oi = arg_int(args, "object", -1); + if (oi < 0 || oi >= int(plater.model().objects.size())) throw ToolFailure("object index out of range"); - ModelObject* object = objects[size_t(oi)]; - const int ii = arg_int(args, "instance", 0); - if (ii < 0 || ii >= int(object->instances.size())) - throw ToolFailure("instance index out of range"); - ModelInstance* inst = object->instances[size_t(ii)]; - const bool absolute = arg_string(args, "mode", "relative") == "absolute"; - plater.take_snapshot("Transform object"); - if (args.contains("translate")) { - const Vec3d t = to_vec3(args["translate"], "translate"); - inst->set_offset(absolute ? t : Vec3d(inst->get_offset() + t)); - } - if (args.contains("rotate")) { - const Vec3d r = to_vec3(args["rotate"], "rotate") * Geometry::deg2rad(1.0); - if (absolute) - inst->set_rotation(r); - else { - const Transform3d rot = Geometry::rotation_transform(r) * Geometry::rotation_transform(inst->get_rotation()); - inst->set_rotation(Geometry::extract_euler_angles(rot)); - } - } - if (args.contains("scale")) { - const json& s = args["scale"]; - const Vec3d f = s.is_number() ? Vec3d(s.get(), s.get(), s.get()) : to_vec3(s, "scale"); - if (f.minCoeff() <= 0.) - throw ToolFailure("scale factors must be positive"); - inst->set_scaling_factor(absolute ? f : Vec3d(inst->get_scaling_factor().cwiseProduct(f))); - } - if (arg_bool(args, "drop_to_bed", true)) - object->ensure_on_bed(); - object->invalidate_bounding_box(); - plater.changed_object(oi); - return {{"object", oi}, - {"instance", ii}, - {"offset", vec3(inst->get_offset())}, - {"scale", vec3(inst->get_scaling_factor())}}; + if (args.contains("scale") && args.contains("size")) + throw ToolFailure("give scale or size, not both"); + return args.contains("volume") ? transform_part(plater, oi, args) : transform_instance(plater, oi, args); }); settle(ctx); return ToolResult::ok(out); })); + reg.add(mutate_tool( + "add_part", "Add a part or modifier to an object", + "Add a part, negative part, modifier, support blocker or enforcer, or precise seam to an object, as its context " + "menu's Add items do: a primitive shape at a size, or a model file as Load... adds it. The part lands where the " + "menu puts it (a shape beside the object, a file at its coordinates relative to the object's first part) unless " + "position is given. Like the menu, adding a shape folds the instance's rotation and scale into the object's parts " + "(the instance's scale then reads 1). Refused for an object with several instances: add parts first. A STEP file " + "may ask for mesh options (blocked_by_dialog). The new part is selected; one undo step. Replies with its index, which is not always the last (parts are ordered by type), " + "the object's part count and the part's list_objects entry (volume_info).", + object_schema({{"object", {{"type", "integer"}, {"minimum", 0}}}, + {"type", enum_prop({"part", "negative", "modifier", "support_blocker", "support_enforcer", "precise_seam"}, + "What the new part is.")}, + {"shape", enum_prop({"cube", "cylinder", "sphere", "cone", "disc", "torus"}, "A primitive shape.")}, + {"size", array_prop({{"type", "number"}}, "mm, the Primitive size dialog's fields: cube [x, y, z]; cylinder, " + "cone, disc [diameter, height]; sphere [diameter]; torus [inner " + "diameter, tube diameter]. Default: the built-in size.")}, + {"path", prop("string", "Instead of shape: absolute path of a model file (STL, OBJ, 3MF, STEP, ...).")}, + {"position", array_prop({{"type", "number"}}, "[x, y, z] mm on the bed for the part's centre, on " + "instance 0, as the Move panel shows it.")}}, + {"object", "type"}), + [](const json& args, ToolContext& ctx) { + json out = ctx.run_ui([&] { return add_part(ui_plater(), args); }); + settle(ctx); + return ToolResult::ok(out); + })); + + reg.add(mutate_tool( + "arrange", "Arrange objects or fill the bed", + "Arrange objects as the toolbar's Arrange does (every unlocked plate) or as one plate's Arrange icon does (plates: " + "an index or \"current\"), or fill object fill's plate with more of it, as Fill bed with instances or copies does. " + "spacing, rotate, align_y and multi_material are the Arrange options panel's settings: values given are kept as the " + "panel keeps them, so later arranges use them too. Waits for the arrangement (a longer one replies with a job); " + "the reply has the settings in force, instances left off every plate, plates the all-plates arrange skipped and " + "the job's notifications. An arrange may reorder objects, so list_objects again. One undo step.", + object_schema({{"plates", {{"type", {"string", "integer"}}, {"description", "\"all\" (default), \"current\" or a plate index."}}}, + {"spacing", {{"type", "number"}, {"minimum", 0}, {"description", "mm between objects; 0 means auto."}}}, + {"rotate", prop("boolean", "Auto rotate for arrangement.")}, + {"align_y", prop("boolean", "Align to Y axis (off while rotate is on).")}, + {"multi_material", prop("boolean", "Allow multiple materials on same plate.")}, + {"fill", {{"type", "integer"}, {"minimum", 0}, {"description", "Instead of arranging, fill this object's plate with more of it."}}}, + {"fill_with", enum_prop({"instances", "copies"}, "Default instances.")}, + {"timeout_s", {{"type", "integer"}, {"minimum", 10}, {"maximum", 1800}, {"description", "Cancel it after this long (default 300)."}}}}), + [&service](const json& args, ToolContext& ctx) { + ArrangeStart start; + ctx.run_ui([&] { + start = start_arrange(ui_plater(), args); + return json(); + }); + // A replay arranges with the settings in force here, whatever the replaying machine saved. + json recorded = args; + for (const auto& [key, value] : start.settings.items()) + if (key != "by_object") + recorded[key] = value; + ctx.set_journal_args(std::move(recorded)); + const auto timeout = std::chrono::seconds(arg_int(args, "timeout_s", 300)); + try { + return ToolResult::ok(poll_ui( + ctx, + [&]() -> json { + Plater& plater = ui_plater(); + return plater.get_ui_job_worker().is_idle() ? arrange_reply(plater, start) : json(); + }, + timeout, "the arrangement")); + } catch (const ToolFailure&) { + if (ctx.cancelled()) + throw; + // McpCore keeps the call's admission until the cancelled job has really stopped. + ctx.observe_ui([&] { return json(service.core().cancel_worker(ctx.job_id())); }); + throw ToolFailure("The arrangement did not finish within " + std::to_string(timeout.count()) + " s, so it was cancelled"); + } + })); + ToolDef slice = mutate_tool( "slice", "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 " - "(with print time and filament), error, cancelled, empty or skipped; the whole operation is superseded when " - "someone else started a slice or edited the project while it ran. Other changes are refused until it finishes; " - "cancel stops it.", + "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; cancel stops it.", object_schema({{"plates", {{"type", {"string", "integer"}}, {"description", "\"current\" (default), \"all\", or a plate index."}}}, {"timeout_s", {{"type", "integer"}, {"minimum", 10}, {"maximum", 7200}, {"description", "Give up after this long (default 1800)."}}}}), [](const json& args, ToolContext& ctx) { @@ -515,11 +1171,15 @@ void register_scene_tools(McpService& service) 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. - PartPlate* plate = list.get_plate(ticket->plates[i]); - if (plate != nullptr && plate->is_slice_result_valid() && + // 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_stats(*plate)); + 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."; } @@ -543,19 +1203,24 @@ void register_scene_tools(McpService& service) reg.add(slice); ToolDef cancel = mutate_tool( - "cancel", "Cancel slicing", - "Stop the running slice or G-code export, as the cancel button on the slicing progress does. The slice or export " - "job then reports cancelled. With job, only when that job is the running slice or export. Allowed while a slice or " - "export holds the project.", - object_schema({{"job", prop("string", "The slice or export job to cancel, e.g. \"j12\".")}}), + "cancel", "Cancel an operation", + "Stop the running slice or G-code export, as the cancel button on the slicing progress does, or the background job " + "(an arrange, orient or fill bed) an MCP call started. That job then reports cancelled; a background job keeps " + "other changes out until it has really stopped. With job, only when that job is the running operation. Allowed " + "while an operation holds the project.", + object_schema({{"job", prop("string", "The operation's job to cancel, e.g. \"j12\".")}}), [&service](const json& args, ToolContext& ctx) { const auto ops = service.jobs().running_operations(); if (args.contains("job")) { const std::string job = arg_string(args, "job"); if (std::find(ops.begin(), ops.end(), job) == ops.end()) - throw ToolFailure("Job " + job + " is not a running slice or export", {{"running", ops}}); + throw ToolFailure("Job " + job + " is not a running operation", {{"running", ops}}); } - json out = ctx.run_ui([&ops] { + 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")) && service.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(); diff --git a/src/slic3r/GUI/Mcp/McpToolsScript.cpp b/src/slic3r/GUI/Mcp/McpToolsScript.cpp index 42ab6c0ae2..e6971bf25e 100644 --- a/src/slic3r/GUI/Mcp/McpToolsScript.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsScript.cpp @@ -159,14 +159,19 @@ void register_script_tools(McpService& service) "export_script", "Export this session as a script", "Turn the calls this session made into a script run_script can replay: mutating calls, wait and screenshot, in order, " "with refs replaced by locators, job replies replayed with await:false, and screenshot paths moved under ${out_dir}. " + "Calls that failed, at once or as a job later, are left out; so is a call whose job is still running (unless it " + "waits on a dialog), which left_out_running lists as {tool, job}. " "Returns the script; with path, also writes it. clear:true starts a new recording afterwards.", object_schema({{"name", prop("string", "Script 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.")}}), [&service](const json& args, ToolContext&) { - json script = service.journal().to_script(arg_string(args, "name", "session " + timestamp())); + json running; + json script = service.journal().to_script(arg_string(args, "name", "session " + timestamp()), &running); json out{{"steps", script["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); diff --git a/src/slic3r/GUI/Mcp/McpToolsUi.cpp b/src/slic3r/GUI/Mcp/McpToolsUi.cpp index e7a3f96969..3078ba45db 100644 --- a/src/slic3r/GUI/Mcp/McpToolsUi.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsUi.cpp @@ -2,12 +2,14 @@ // dialogs and run JavaScript in web views. #include "JobRegistry.hpp" +#include "McpCore.hpp" #include "McpPaths.hpp" #include "McpService.hpp" #include "McpTools.hpp" #include "McpTypes.hpp" #include "ModalTracker.hpp" #include "UiInspector.hpp" +#include "slic3r/GUI/ExportPresetBundleDialog.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/GUI.hpp" #include "slic3r/GUI/GUI_App.hpp" @@ -17,9 +19,10 @@ #include "slic3r/GUI/Jobs/Worker.hpp" #include "slic3r/GUI/MainFrame.hpp" #include "slic3r/GUI/Plater.hpp" +#include "slic3r/GUI/PresetBundleDialog.hpp" +#include "slic3r/GUI/WebGuideDialog.hpp" #include -#include #include #include #include @@ -39,6 +42,7 @@ #include #include #include +#include #include #include @@ -52,8 +56,11 @@ namespace { const json kTargetSchema = {{"type", json::array({"string", "object"})}, {"description", "A ref from the latest ui_snapshot (\"w12\") or a locator: {label, class, name, within, index} for " - "widgets, {option:\"layer_height\"} for a setting field, {menu:\"File>Export>Export G-code\"}, {gltoolbar:\"arrange\"}, {gizmo:\"Move\"}, or " - "{imgui:\"label\", imgui_name?:\"name\", window?, canvas?, index?} for an ImGui item, by its label, its name or both."}}; + "widgets, {option:\"layer_height\"} for a setting field, {menu:\"File>Export>Export G-code\"}, {gltoolbar:\"arrange\"}, {gizmo:\"Move\"}, " + "{imgui:\"label\", imgui_name?:\"name\", window?, canvas?, index?} for an ImGui item, by its label, its name or both, or " + "{row:\"Plate 1>Cube>Cylinder\", column?, within?, index?} for a row of a list, tree, table or drop-down list, by its " + "last labels and the column of the cell to act on, or {plate_icon:\"lock\", plate:0} for a plate or its icon in the " + "Prepare view: plate, delete, orient, arrange, lock, settings, name, move_to_front, filament_map, imex_mode."}}; const json kModifiersSchema = {{"type", "array"}, {"items", {{"type", "string"}, {"enum", {"ctrl", "cmd", "rawctrl", "shift", "alt"}}}}, @@ -63,23 +70,25 @@ const json kModifiersSchema = {{"type", "array"}, bool in_top_dialog(McpService& service, wxWindow* window) { wxDialog* top = service.modals().top(); - return top != nullptr && window != nullptr && wxGetTopLevelParent(window) == top; + return top != nullptr && window != nullptr && owning_window(window) == top; } // GUI input tools run under the recover guard so they can work in the topmost modal dialog; a // target anywhere else gets the checks a mutate call would: no other call's nested loop, no open -// modal, and no MCP slice or export holding the project. +// modal, and operation admission (no MCP operation holding the project, no busy UI job worker). void guard_target(McpService& service, wxWindow* window) { if (in_top_dialog(service, window)) return; service.ui().require_mutate(); - if (const auto ops = service.jobs().running_operations(); !ops.empty()) - throw ToolFailure("Busy: job " + ops.front() + " (a slice or export) is running; wait for it or cancel it first", - {{"job", ops.front()}}); + service.core().admit({}); } -wxWindow* target_window(const UiTarget& t) { return t.kind == UiTarget::Kind::Window ? t.window.get() : nullptr; } +// The window a target is in: a widget's own, a row's list. +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) @@ -97,6 +106,70 @@ ToolDef recover_input_tool(std::string name, std::string title, std::string desc return d; } +const json kPopupItemSchema = prop("string", "Run this item of the menu the input opens (a right click's context menu, a button's menu), " + "by its label path, \"Add Modifier>Cylinder\"; \"#2\" picks a repeated label's second item. " + "Without it, such a menu is listed in the reply (popup_menu), not shown."); + +// The menu an input call may open, which the inspector takes instead of showing it +// (UiInspector::arm_menu()): armed in the closure that delivers the input, read once the events the +// input queued have run. A call that fails before reading it drops it. +struct PopupCapture +{ + McpService& service; + ToolContext& ctx; + std::string item; + int token = 0; + // Also reply the dialogs open once the input's events ran: an input whose work opens a dialog + // from a posted event (a plate icon) returns before the dialog shows. + bool dialogs = false; + // Set by a call queued on the 3D view behind the click, which the view posts to itself and opens + // its menu from: once it has run, so has the click (or the click's command is in a dialog's loop, + // which runs it too). + std::shared_ptr marked; + + PopupCapture(McpService& service, ToolContext& ctx, std::string item) : service(service), ctx(ctx), item(std::move(item)) {} + PopupCapture(const PopupCapture&) = delete; + PopupCapture& operator=(const PopupCapture&) = delete; + ~PopupCapture() + { + if (token == 0) + return; + try { + ctx.observe_ui([this] { + service.inspector().drop_menu(token); + return json(); + }); + } catch (const ToolFailure&) { + } + } + + // UI thread, in the input's closure, before the input. + void arm() { token = service.inspector().arm_menu(item); } + // UI thread, after an input to a 3D view, on the handler the input posted its work to. + void mark(wxEvtHandler* queue) + { + if (queue == nullptr) + return; + marked = std::make_shared(false); + queue->CallAfter([m = marked] { *m = true; }); + } + // Job thread: settles, then {popup_menu} or {ran} (with the dialogs a command it ran left open), + // or {} when no menu opened. + json read() + { + for (int i = 0; marked && i < 100 && !ctx.observe_ui([this] { return json(*marked); }).get(); ++i) + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + settle(ctx); + const int t = std::exchange(token, 0); + return ctx.observe_ui([&] { + json out = service.inspector().disarm_menu(t); + if ((dialogs || out.contains("ran")) && service.modals().any_open()) + out["dialogs"] = service.modals().snapshot(); + return out; + }); + } +}; + // Every shown web view, main window first. std::vector visible_webviews() { @@ -108,8 +181,10 @@ std::vector visible_webviews() out.push_back(web); return; } + // A dialog is its parent's child too; it is visited once, as a top-level window. for (wxWindow* child : w->GetChildren()) - visit(child); + if (dynamic_cast(child) == nullptr) + visit(child); }; if (wxGetApp().mainframe != nullptr) visit(wxGetApp().mainframe); @@ -119,8 +194,78 @@ std::vector visible_webviews() return out; } -// Receives the result of one RunScriptAsync call into a State the job thread waits on. Created, -// used and deleted on the UI thread only, like the weak reference it keeps to its web view. +// The modal dialogs whose web views take scripts: the setup wizard and the preset bundle dialogs, +// whose pages have no typed route. Sign-in dialogs are never among them, and the flushing volumes +// and filament colours are written through set_settings's project scope instead. +bool takes_scripts(const wxDialog* dialog) +{ + return dynamic_cast(dialog) != nullptr || dynamic_cast(dialog) != nullptr || + dynamic_cast(dialog) != nullptr; +} + +// The web view a script without a target runs in: the one in the topmost modal dialog while one is +// open, else the only one shown. +wxWebView* default_webview(McpService& service) +{ + std::vector webs = visible_webviews(); + std::string where; + if (wxDialog* top = service.modals().top()) { + std::vector in_top; + for (wxWebView* w : webs) + if (owning_window(w) == top) + in_top.push_back(w); + if (!in_top.empty()) { + webs = std::move(in_top); + where = " in \"" + into_u8(top->GetTitle()) + "\""; + } + } + if (webs.empty()) + throw ToolFailure("No web view is shown (the Home tab has one: set_view tab=home)"); + if (webs.size() > 1) { + json urls = json::array(); + for (wxWebView* w : webs) + urls.push_back(into_u8(w->GetCurrentURL())); + throw ToolFailure("Several web views are shown" + where + "; pass target (ui_snapshot query=webview)", {{"web_views", urls}}); + } + return webs.front(); +} + +// A web view in the topmost modal dialog takes scripts when that dialog is one of takes_scripts(), +// one in a dialog under it is refused, and any other gets the checks a mutate call would. +void guard_script(McpService& service, wxWebView* web) +{ + const std::vector& stack = service.modals().stack(); + const auto in = std::find(stack.begin(), stack.end(), owning_window(web)); + if (in != stack.end()) { + const std::string title = into_u8((*in)->GetTitle()); + if (*in != stack.back()) + throw ToolFailure("\"" + title + "\" is under \"" + into_u8(stack.back()->GetTitle()) + "\"; answer the topmost dialog first"); + if (!takes_scripts(*in)) + throw ToolFailure("Scripts run in a dialog only in the setup wizard and the preset bundle dialogs, not in \"" + title + "\""); + } + guard_target(service, web); +} + +// The script as webview_eval runs it. Messages the page posts to its host (window.wx.postMessage) while +// the script runs are held until it has returned: a host that ends its dialog on one (a page's Close or +// OK button) would otherwise destroy the web view before the result comes back, and wx's script +// callback, which keeps a plain pointer to the web view, would then reach a destroyed one. The result +// is JSON: the value as wx gives it (an object as JSON, undefined as "undefined") and how many messages +// were held. +std::string with_held_messages(const std::string& script) +{ + return "(function () { var host = window.wx, held = [], swapped = !!(host && host.postMessage);" + " if (swapped) window.wx = {postMessage: function (m) { held.push(m); }};" + " try { var res = eval(" + json(script).dump(-1, ' ', true) + ");" + " return JSON.stringify({held: held.length, value: typeof res == 'object' ? JSON.stringify(res) :" + " typeof res == 'undefined' ? 'undefined' : String(res)}); }" + " finally { if (swapped) { window.wx = host; if (held.length) setTimeout(function () {" + " held.forEach(function (m) { host.postMessage(m); }); }, 0); } } })()"; +} + +// Receives the result of one RunScriptAsync call into a State the job thread waits on, or the web +// view's destruction when its dialog went away while the script ran. Created, used and deleted on the +// UI thread only, like the weak reference it keeps to its web view. class ScriptSink : public wxEvtHandler { public: @@ -128,19 +273,38 @@ public: { std::mutex mutex; std::condition_variable cv; - bool done = false; - bool error = false; + bool done = false; + bool error = false; + bool destroyed = false; // the web view went away first std::string text; }; ScriptSink(wxWebView* web, std::shared_ptr state) : m_web(web), m_state(std::move(state)) { web->Bind(wxEVT_WEBVIEW_SCRIPT_RESULT, &ScriptSink::on_result, this); + web->Bind(wxEVT_DESTROY, &ScriptSink::on_destroy, this); } ~ScriptSink() override { - if (wxWebView* web = m_web.get()) + if (wxWebView* web = m_web.get()) { web->Unbind(wxEVT_WEBVIEW_SCRIPT_RESULT, &ScriptSink::on_result, this); + web->Unbind(wxEVT_DESTROY, &ScriptSink::on_destroy, this); + } + } + + void on_destroy(wxWindowDestroyEvent& evt) + { + evt.Skip(); + if (evt.GetEventObject() != m_web.get()) + return; + { + std::lock_guard lock(m_state->mutex); + if (m_state->done) + return; + m_state->done = true; + m_state->destroyed = true; + } + m_state->cv.notify_all(); } void on_result(wxWebViewEvent& evt) @@ -170,33 +334,6 @@ void delete_on_ui(ScriptSink* sink) wxTheApp->CallAfter([sink] { delete sink; }); } -// Presses the button with `id` in `dialog` so the dialog's own handler runs, or ends the dialog with -// that id when no such button exists. Returns whether a button was pressed. UI thread only. -bool press_dialog_button(wxDialog* dialog, int id) -{ - wxWindow* pressed = nullptr; - std::function find = [&](wxWindow* w) { - for (wxWindow* child : w->GetChildren()) { - if (pressed != nullptr || dynamic_cast(child) != nullptr) - continue; - if (child->GetId() == id && child->IsShown() && child->IsEnabled() && - (dynamic_cast(child) != nullptr || class_name(child).find("Button") != std::string::npos)) - pressed = child; - else - find(child); - } - }; - find(dialog); - if (pressed == nullptr) { - dialog->EndModal(id); - return false; - } - wxCommandEvent evt(wxEVT_BUTTON, id); - evt.SetEventObject(pressed); - pressed->GetEventHandler()->ProcessEvent(evt); - return true; -} - } // namespace void register_ui_tools(McpService& service) @@ -207,12 +344,15 @@ void register_ui_tools(McpService& service) ToolDef def = inspect_tool( "ui_snapshot", "List the GUI", "Describe what is on screen as an indented tree, one element per line with a ref: wx widgets of every shown window " - "(buttons, fields, checkboxes, combos, tabs, labels), the main menus, the 3D canvas's toolbar items and gizmos, and " + "(buttons, fields, checkboxes, combos, tabs, labels), the rows of lists, trees and tables (label, other cells, " + "checkbox, what an object list row is), each shown popup after the window it opened from, the main menus, the 3D " + "canvas's toolbar items and gizmos, and " "each ImGui panel drawn in the last frame with its items (kind, value, name) and text. Pass the refs to ui_click / " "ui_input / ui_key. Refs go stale when the " - "element goes away; take a new snapshot then. root: \"all\" (default), \"main\", \"dialog\" (topmost modal) or a " - "window's ref. query filters by label, value, name or class. Prefer run_action and the typed tools when one fits.", - object_schema({{"root", prop("string", "all | main | dialog | .")}, + "element goes away; take a new snapshot then. root: \"all\" (default), \"main\", \"dialog\" (topmost modal), " + "\"popup\" or a window's ref. query filters by label, value, name or class. Prefer run_action and the typed tools " + "when one fits.", + object_schema({{"root", prop("string", "all | main | dialog | popup | .")}, {"query", prop("string", "Case-insensitive text to look for.")}, {"max_nodes", {{"type", "integer"}, {"minimum", 1}, {"maximum", 5000}, {"description", "Default 400."}}}, {"include_imgui", prop("boolean", "List ImGui items (default true).")}, @@ -240,15 +380,21 @@ void register_ui_tools(McpService& service) "Activate a GUI element: menu items, buttons, checkboxes, toggles, radio buttons, toolbar items and gizmos are activated " "the way their owners expect (a gizmo as its toolbar icon: it opens, a second click closes it, and Text on an object " "with no text creates a text part and replies created); other widgets and ImGui items get a synthesized mouse click, " - "after the item is scrolled into view. With x/y on a 3D canvas " - "target, clicks that point (logical pixels from the canvas's top left). Modifiers are seen by the 3D canvas, the " - "object list and handlers that read the event. A click that opens a dialog returns blocked_by_dialog with the job.", + "after the item is scrolled into view. A row is selected as a click on its cell selects it (ctrl adds, shift extends; " + "the object list acts on the column named, as Printable toggles), a double click activates it, a right click opens " + "its menu; a drop-down row is picked. A plate icon does what clicking it in the Prepare view does: the reply says the " + "plate's lock state (locked), arrange and orient wait for their job (done), settings and filament_map list the dialog " + "they open (dialogs), and a right click opens the plate menu. With x/y, clicks that point of a 3D canvas or a " + "custom-drawn widget (logical pixels from its top left). Modifiers are seen by the 3D canvas, the " + "object list and handlers that read the event. A menu the click opens is never shown: it is listed as popup_menu, " + "or popup_item runs one of its items (ran). A click that opens a dialog returns blocked_by_dialog with the job.", object_schema({{"target", kTargetSchema}, {"button", enum_prop({"left", "right", "middle"}, "Default left.")}, {"double", prop("boolean", "Double click.")}, {"modifiers", kModifiersSchema}, - {"x", prop("integer", "Canvas x for a click on a 3D canvas.")}, - {"y", prop("integer", "Canvas y for a click on a 3D canvas.")}}, + {"x", prop("integer", "x of the point to click, in a 3D canvas or a custom-drawn widget.")}, + {"y", prop("integer", "y of the point to click.")}, + {"popup_item", kPopupItemSchema}}, {"target"}), [&service](const json& args, ToolContext& ctx) { ClickOptions o; @@ -258,18 +404,48 @@ void register_ui_tools(McpService& service) o.at_point = args.contains("x") || args.contains("y"); o.x = arg_int(args, "x", 0); o.y = arg_int(args, "y", 0); - json locator; - GLCanvas3D* canvas = nullptr; - int gizmo = -1; + json locator; + GLCanvas3D* canvas = nullptr; + int gizmo = -1; + PopupCapture menu(service, ctx, arg_string(args, "popup_item")); + // A list's rows get their places a frame after they change (on GTK; a dialog's tree rebuilt + // by a preset choice), so a row is scrolled to first and given up to 1 s to take its place. + for (int i = 0; i < 20; ++i) { + const bool placed = ctx.run_ui([&] { + UiTarget t = service.inspector().resolve(args["target"]); + guard_target(service, target_window(t)); + return json(service.inspector().place_row(t)); + }).get(); + if (placed) + break; + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + } json out = ctx.run_ui([&] { UiTarget t = service.inspector().resolve(args["target"]); locator = service.inspector().locator_for(t); guard_target(service, target_window(t)); canvas = t.canvas; gizmo = t.gizmo; - return service.inspector().click(t, o); + menu.arm(); + json clicked = service.inspector().click(t, o); + // A 3D view posts a click's work to itself; a plate icon posts its dialogs to the plater. + const bool plate_icon = t.kind == UiTarget::Kind::PlateIcon; + GLCanvas3D* view = service.inspector().canvas_of(&t); + if (plate_icon && o.button == "left") + menu.mark(&ui_plater()); + else if (view != nullptr) + menu.mark(view->get_wxglcanvas()); + menu.dialogs = plate_icon; + return clicked; }); journal_with_locator(ctx, args, locator); + if (out.value("started", false)) { + // A plate's arrange or orient icon started a job on the UI job worker: the reply + // follows its end. + out.update(poll_ui( + ctx, [] { return ui_plater().get_ui_job_worker().is_idle() ? json{{"done", true}} : json(); }, + std::chrono::minutes(30), "the plate's " + out.value("clicked", std::string()) + " job")); + } if (out.value("creating", false)) { // The Text gizmo's icon with no text selected queued a job that creates a text part // and opens the gizmo when it ends. @@ -285,7 +461,7 @@ void register_ui_tools(McpService& service) }, std::chrono::seconds(30), "the new text part"); } - settle(ctx); + out.update(menu.read()); return ToolResult::ok(out); })); @@ -293,7 +469,8 @@ void register_ui_tools(McpService& service) "ui_input", "Set a control's value", "Set the text, number, selection or checked state of a control and send the event a person's edit would: text fields " "(submit:true also presses Enter and leaves the field, which is when Orca's setting fields commit), spin controls, " - "sliders, choice / combo / list boxes (by option text or index), checkboxes and toggles (true/false). An ImGui item " + "sliders, choice / combo / list boxes (by option text or index), checkboxes and toggles (true/false), a row's " + "checkbox (true/false). An ImGui item " "is set by its kind and its value read back: a field is typed into (a slider through the number field beside it, " "multiline text with \\n), a combo's option is picked by its text or 0-based index, a checkbox, radio or toggle " "clicked when it differs. For " @@ -318,16 +495,20 @@ void register_ui_tools(McpService& service) reg.add(recover_input_tool( "ui_key", "Press keys", "Send a key chord (\"Ctrl+S\", \"Escape\", \"Return\", \"Delete\", \"Shift+Tab\", \"Left\", \"F5\") and/or type text to " - "a target or, without one, to the focused window (the topmost dialog while one is open, the 3D canvas when nothing " - "has focus). The window's shortcut handling " - "sees it first, as with a real key press. Typing reaches ImGui fields and key handlers; to fill a native text field " - "use ui_input.", - object_schema({{"target", kTargetSchema}, {"keys", prop("string", "Key chord.")}, {"text", prop("string", "Characters to type.")}}), + "a target or, without one, to the focused window (the topmost dialog while one is open, the 3D view shown when nothing " + "has focus). As with a real key press, the shortcut handling of the target's panels and window sees it first. " + "Typing reaches ImGui fields and key handlers; to fill a native text field " + "use ui_input. A menu the keys open is listed as popup_menu, or popup_item runs one of its items.", + object_schema({{"target", kTargetSchema}, + {"keys", prop("string", "Key chord.")}, + {"text", prop("string", "Characters to type.")}, + {"popup_item", kPopupItemSchema}}), [&service](const json& args, ToolContext& ctx) { const std::string keys = arg_string(args, "keys"), text = arg_string(args, "text"); if (keys.empty() && text.empty()) throw ToolFailure("Give keys, text or both"); - json locator; + json locator; + PopupCapture menu(service, ctx, arg_string(args, "popup_item")); json out = ctx.run_ui([&] { std::optional t; if (args.contains("target")) { @@ -335,10 +516,11 @@ void register_ui_tools(McpService& service) locator = service.inspector().locator_for(*t); } guard_target(service, service.inspector().key_target(t ? &*t : nullptr)); + menu.arm(); return service.inspector().key(t ? &*t : nullptr, keys, text); }); journal_with_locator(ctx, args, locator); - settle(ctx); + out.update(menu.read()); return ToolResult::ok(out); })); @@ -358,6 +540,10 @@ void register_ui_tools(McpService& service) {"additionalProperties", false}}; const json pixel_or_target = {{"type", json::array({"array", "object"})}, {"description", "A canvas pixel [x, y] or a point of the model, as for at."}}; + std::vector mouse_canvases{"3d", "preview", "assemble", "current"}; +#ifdef SLIC3R_CAD + mouse_canvases.insert(mouse_canvases.end() - 1, "design"); +#endif reg.add(mutate_tool( "ui_mouse", "Mouse gesture on the 3D view", "Synthesize a mouse gesture on a 3D canvas, as a person's would: move, down, up, click, drag (from the start through " @@ -367,9 +553,10 @@ void register_ui_tools(McpService& service) "that part there (check \"point\" only projects it), or as x/y, logical pixels from the canvas's top left. " "Modifiers are pressed as keys for the gesture (shift for Measure's point picking, alt for erasing). A down keeps " "its button and modifiers held, so moves drag with it, until an up or another gesture. Grabbers are set through " - "the gizmo's panel fields or transform, not dragged.", + "the gizmo's panel fields or transform, not dragged. A menu a right click opens is listed as popup_menu, or " + "popup_item (with click or up) runs one of its items.", object_schema({{"action", enum_prop({"move", "down", "up", "click", "drag", "wheel"}, "Default click.")}, - {"canvas", enum_prop({"3d", "preview", "assemble", "current"}, "Default current.")}, + {"canvas", enum_prop(mouse_canvases, "Default current, the view shown. design takes x/y only.")}, {"at", target_schema}, {"x", prop("integer", "Start x, instead of at.")}, {"y", prop("integer", "Start y, instead of at.")}, @@ -381,31 +568,40 @@ void register_ui_tools(McpService& service) {"button", enum_prop({"left", "right", "middle"}, "Default left.")}, {"double", prop("boolean", "Double click.")}, {"delta", prop("integer", "Wheel notches.")}, - {"modifiers", kModifiersSchema}}), + {"modifiers", kModifiersSchema}, + {"popup_item", kPopupItemSchema}}), [&service](const json& args, ToolContext& ctx) { + const std::string action = arg_string(args, "action", "click"); + if (args.contains("popup_item") && action != "click" && action != "up") + throw ToolFailure("popup_item goes with action click or up, which open a right click's menu"); const std::string owner = service.script_owner(service.jobs().ancestry(ctx.job_id())); + PopupCapture menu(service, ctx, arg_string(args, "popup_item")); json out = ctx.run_ui([&] { // A client's press that runs after the endpoint closed would stay held, with no one left // to release it. if (owner.empty() && !service.endpoint_open()) throw ToolFailure("The MCP server was turned off before this gesture ran; it was not performed"); try { + ui_plater(); // refuses while OrcaSlicer starts or closes const std::string name = arg_string(args, "canvas", "current"); - Plater& plater = ui_plater(); - GLCanvas3D* canvas = name == "3d" ? plater.get_view3D_canvas3D() : - name == "preview" ? plater.get_preview_canvas3D() : - name == "assemble" ? plater.get_assmeble_canvas3D() : - plater.get_current_canvas3D(); + GLCanvas3D* canvas = name == "current" ? shown_canvas() : canvas_by_name(name); if (canvas == nullptr || !canvas->get_wxglcanvas()->IsShownOnScreen()) - throw ToolFailure("That 3D view is not shown; switch to it with set_view first"); - return service.inspector().mouse(*canvas, args, owner); + throw ToolFailure(name == "design" ? "The Design view is not shown; set_view {\"tab\": \"design\"} first" : + "That 3D view is not shown; switch to it with set_view first"); + // The Design view sets up its GL at its first frame, as DesignCanvas guards its own renders. + if (canvas == design_canvas() && !canvas->is_initialized()) + throw ToolFailure("The Design view has not drawn yet"); + menu.arm(); + json done = service.inspector().mouse(*canvas, args, owner); + menu.mark(canvas->get_wxglcanvas()); + return done; } catch (...) { // A gesture that fails ends a press held from before it, as any other gesture would. service.inspector().release_held(nullptr); throw; } }); - settle(ctx); + out.update(menu.read()); return ToolResult::ok(out); })); @@ -507,8 +703,9 @@ void register_ui_tools(McpService& service) { ToolDef def = recover_input_tool( "dialog_auto_answer", "Pre-answer dialogs", - "Answer modal dialogs automatically, native ones included: a dialog whose title or message matches a rule's regex " - "(case-insensitive) returns that button at once and never shows. A matching wx dialog that is already open is " + "Answer modal dialogs automatically, native ones included, when their title or message matches a rule's regex " + "(case-insensitive): a native dialog returns that button at once and never shows; a wx dialog has the button " + "pressed as dialog_respond does, so its handler runs. A matching wx dialog that is already open is " "answered too, so a prompt that appears around the same time (the restore prompt after startup) is handled " "either way. Native file pickers can only be cancelled. Called from a script, the rules last until the script " "ends; otherwise they replace the rules this session set before (an empty list clears them).", @@ -550,11 +747,14 @@ void register_ui_tools(McpService& service) reg.add(def); } - reg.add(mutate_tool( + reg.add(recover_input_tool( "webview_eval", "Run JavaScript in a web view", - "Evaluate JavaScript in one of OrcaSlicer's web views (Home, the device page, login and others) and return the value of " - "its last expression (JSON values come back parsed). Without a target the only shown web view is used. Waits up to " - "timeout_s (default 10).", + "Evaluate JavaScript in one of OrcaSlicer's web views (Home, the device page and others) and return the value of its " + "last expression (JSON values come back parsed). While a modal dialog is open, scripts run only in the setup " + "wizard's and the preset bundle dialogs' pages, never in a sign-in dialog; without a target, the web view of the " + "topmost dialog is used, else the only shown one. Commit such a page through its own button, since dialog_respond " + "only closes the dialog; closed: true says the script closed its dialog. Messages the page posts to OrcaSlicer " + "reach it once the script has returned. Waits up to timeout_s (default 10).", object_schema({{"script", prop("string", "JavaScript to run.")}, {"target", kTargetSchema}, {"timeout_s", {{"type", "integer"}, {"minimum", 1}, {"maximum", 120}, {"description", "Default 10."}}}}, @@ -564,28 +764,24 @@ void register_ui_tools(McpService& service) const auto timeout = std::chrono::seconds(arg_int(args, "timeout_s", 10)); auto state = std::make_shared(); ScriptSink* sink = nullptr; // the UI thread's to create and delete + json locator; + const wxDialog* modal = nullptr; // the dialog the web view is in, only compared json started = ctx.run_ui([&]() -> json { wxWebView* web = nullptr; if (args.contains("target")) { UiTarget t = service.inspector().resolve(args["target"]); + locator = service.inspector().locator_for(t); web = dynamic_cast(target_window(t)); if (web == nullptr) throw ToolFailure("The target is not a web view (ui_snapshot lists them as kind webview)"); - } else { - const auto all = visible_webviews(); - if (all.empty()) - throw ToolFailure("No web view is shown (the Home tab has one: set_view tab=home)"); - if (all.size() > 1) { - json urls = json::array(); - for (wxWebView* w : all) - urls.push_back(into_u8(w->GetCurrentURL())); - throw ToolFailure("Several web views are shown; pass target (ui_snapshot query=webview)", {{"web_views", urls}}); - } - web = all.front(); - } + } else + web = default_webview(service); + guard_script(service, web); + if (in_top_dialog(service, web)) + modal = service.modals().top(); sink = new ScriptSink(web, state); try { - web->RunScriptAsync(from_u8(script), sink); + web->RunScriptAsync(from_u8(with_held_messages(script)), sink); } catch (...) { delete sink; sink = nullptr; @@ -593,27 +789,52 @@ void register_ui_tools(McpService& service) } return {{"url", into_u8(web->GetCurrentURL())}}; }); + journal_with_locator(ctx, args, locator); // The result arrives as an event on the UI thread; wait for it here, without the UI. - bool done = false, error = false; + bool done = false, error = false, destroyed = false; std::string text; { std::unique_lock lock(state->mutex); const auto end = std::chrono::steady_clock::now() + timeout; while (!state->done && !ctx.cancelled() && std::chrono::steady_clock::now() < end) state->cv.wait_until(lock, std::min(end, std::chrono::steady_clock::now() + std::chrono::milliseconds(200))); - done = state->done; - error = state->error; - text = state->text; + done = state->done; + error = state->error; + destroyed = state->destroyed; + text = state->text; } delete_on_ui(sink); if (!done) throw ToolFailure(ctx.cancelled() ? "OrcaSlicer is shutting down" : "Timed out waiting for the script result"); if (error) throw ToolFailure("The script failed: " + text); - json value = json::parse(text, nullptr, false); + int held = 0; + if (const json wrapped = json::parse(text, nullptr, false); wrapped.is_object() && wrapped.contains("value") && wrapped["value"].is_string()) { + held = wrapped.value("held", 0); + text = wrapped["value"].get(); + } + // The page's held messages reach its host just after the result; a dialog one of them ends + // leaves the modal stack when its loop returns. + bool closed = destroyed; + for (int i = 0; !closed && modal != nullptr && held > 0 && i < 10; ++i) { + try { + closed = ctx.observe_ui([&] { + const auto& stack = service.modals().stack(); + return json(std::find(stack.begin(), stack.end(), modal) == stack.end()); + }).get(); + } catch (const ToolFailure&) { + break; + } + if (!closed) + std::this_thread::sleep_for(std::chrono::milliseconds(30)); + } + json value = destroyed ? json() : json::parse(text, nullptr, false); if (value.is_discarded()) value = text; - return ToolResult::ok({{"result", value}, {"url", started["url"]}}); + json out{{"result", value}, {"url", started["url"]}}; + if (closed) + out["closed"] = true; + return ToolResult::ok(out); })); } diff --git a/src/slic3r/GUI/Mcp/McpToolsView.cpp b/src/slic3r/GUI/Mcp/McpToolsView.cpp index 1a87ac8edd..72d897d44b 100644 --- a/src/slic3r/GUI/Mcp/McpToolsView.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsView.cpp @@ -1,6 +1,9 @@ -// screenshot and set_view: what the agent looks at, and pointing the view before looking. +// screenshot, get_preview and set_view: what the agent looks at and reads off the Preview, and +// pointing the view before looking. +#include "libvgcode/include/ColorRange.hpp" #include "libvgcode/include/Types.hpp" +#include "libvgcode/include/Viewer.hpp" #include "McpPaths.hpp" #include "McpService.hpp" #include "McpTools.hpp" @@ -13,8 +16,20 @@ #include "slic3r/GUI/GUI.hpp" #include "slic3r/GUI/GUI_App.hpp" #include "slic3r/GUI/IMSlider.hpp" +#include "slic3r/GUI/LibVGCode/LibVGCodeWrapper.hpp" #include "slic3r/GUI/MainFrame.hpp" +#include "slic3r/GUI/PartPlate.hpp" #include "slic3r/GUI/Plater.hpp" +#ifdef SLIC3R_CAD +#include "slic3r/GUI/CAD/DesignCanvas.hpp" +#include "slic3r/GUI/CAD/DesignPanel.hpp" +#endif + +#include "libslic3r/Config.hpp" +#include "libslic3r/ExtrusionEntity.hpp" +#include "libslic3r/GCode/GCodeProcessor.hpp" +#include "libslic3r/GCode/GCodeStatistics.hpp" +#include "libslic3r/Model.hpp" #include #include @@ -25,14 +40,19 @@ #include #include #include +#include #include #include #include +#include #include #include #include +#include +#include #include +#include #include #include #include @@ -72,11 +92,205 @@ const char* tab_id(const std::string& name) if (name == "multi_device") return TAB_ID_MULTI_DEVICE; if (name == "project") return TAB_ID_PROJECT; if (name == "calibration") return TAB_ID_CALIBRATION; +#ifdef SLIC3R_CAD + if (name == "design") return TAB_ID_DESIGN; +#endif return nullptr; } +// 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; +} + +// set_view's legend argument: each named row shown or hidden as a click on it does, clicked only when its +// state differs. The rows are the feature types and options the print has, whatever the view type: the +// viewer keeps one visibility set, though the legend lists feature types only in Line Type. The keys are +// checked here, before the Preview changes; the returned function applies them and gives each row's +// state afterwards. UI thread. +std::function legend_change(GCodeViewer& viewer, const json& legend) +{ + const libvgcode::Viewer& toolpaths = viewer.get_viewer(); + const std::vector roles = toolpaths.get_extrusion_roles(); + const std::vector& options = toolpaths.get_options(); + std::vector> role_rows; + std::vector> option_rows; + for (auto item = legend.begin(); item != legend.end(); ++item) { + const std::string& key = item.key(); + if (!item.value().is_boolean()) + throw ToolFailure("legend \"" + key + "\" must be true (show) or false (hide)"); + const auto role = std::find_if(roles.begin(), roles.end(), [&key](libvgcode::EGCodeExtrusionRole r) { return legend_feature_key(r) == key; }); + const auto option = std::find_if(options.begin(), options.end(), [&key](libvgcode::EOptionType o) { + const char* name = legend_option_key(o); + return name != nullptr && key == name; + }); + if (role != roles.end()) + role_rows.emplace_back(*role, item.value().get()); + else if (option != options.end()) + option_rows.emplace_back(*option, item.value().get()); + else { + std::string features, keys; + for (const libvgcode::EGCodeExtrusionRole r : roles) + features += (features.empty() ? "" : ", ") + legend_feature_key(r); + for (const libvgcode::EOptionType o : options) + if (const char* name = legend_option_key(o)) + keys += (keys.empty() ? "" : ", ") + std::string(name); + throw ToolFailure("Unknown legend item \"" + key + "\"; this print has " + features + + (keys.empty() ? std::string() : " and the options " + keys)); + } + } + return [&viewer, role_rows, option_rows]() { + const libvgcode::Viewer& toolpaths = viewer.get_viewer(); + json done = json::object(); + for (const auto& [role, show] : role_rows) { + if (toolpaths.is_extrusion_role_visible(role) != show) + viewer.toggle_extrusion_role_visibility(role); + done[legend_feature_key(role)] = toolpaths.is_extrusion_role_visible(role); + } + for (const auto& [option, show] : option_rows) { + if (toolpaths.is_option_visible(option) != show) + viewer.toggle_option_visibility(option); + done[legend_option_key(option)] = toolpaths.is_option_visible(option); + } + return done; + }; +} + } // namespace +std::string legend_feature_key(libvgcode::EGCodeExtrusionRole role) { return ExtrusionEntity::role_to_string(libvgcode::convert(role)); } + +const char* legend_option_key(libvgcode::EOptionType type) +{ + switch (type) { + case libvgcode::EOptionType::Travels: return "travel"; + case libvgcode::EOptionType::Wipes: return "wipe"; + case libvgcode::EOptionType::Retractions: return "retract"; + case libvgcode::EOptionType::Unretractions: return "unretract"; + case libvgcode::EOptionType::Seams: return "seams"; + case libvgcode::EOptionType::ToolChanges: return "filament_changes"; + case libvgcode::EOptionType::ColorChanges: return "color_changes"; + case libvgcode::EOptionType::PausePrints: return "pauses"; + case libvgcode::EOptionType::CustomGCodes: return "custom_gcode"; + default: return nullptr; + } +} + +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}}; +} + void register_view_tools(McpService& service) { ToolRegistry& reg = service.registry(); @@ -85,7 +299,8 @@ void register_view_tools(McpService& service) "screenshot", "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: \"window\" (the main " - "window), \"canvas\" (the visible 3D view exactly as rendered: scene, toolpaths, toolbars, ImGui panels), " + "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 widget's ref from ui_snapshot (a window that is not modal, or just " "that widget). The result says when parts may differ from the screen (approximate). Point the view first with " "set_view.", @@ -126,10 +341,10 @@ void register_view_tools(McpService& service) std::string err; std::optional cap; if (target == "canvas") { - Plater& plater = ui_plater(); - GLCanvas3D* canvas = plater.get_current_canvas3D(); + ui_plater(); // refuses while OrcaSlicer starts or closes + GLCanvas3D* canvas = shown_canvas(); if (canvas == nullptr) - throw ToolFailure("No Prepare or Preview 3D view is shown; switch to one with set_view tab (the Design tab's view can't be captured; use target window)"); + throw ToolFailure("No 3D view is shown; switch to one with set_view tab"); cap = capture_canvas(*canvas, err); } else if (target == "dialog") { wxDialog* top = service.modals().top(); @@ -155,7 +370,11 @@ void register_view_tools(McpService& service) if (GLCanvas3D* canvas = service.inspector().canvas_of(&t); canvas != nullptr && canvas->get_wxglcanvas() == w) { cap = capture_canvas(*canvas, err); } else { - auto* tlw = dynamic_cast(wxGetTopLevelParent(w)); + wxWindow* top = wxGetTopLevelParent(w); + // A popup is a native window of its own, which window captures leave out. + if (dynamic_cast(top) != nullptr) + throw ToolFailure("The widget is in a popup, which screenshots don't capture; ui_snapshot {root: \"popup\"} lists it"); + auto* tlw = dynamic_cast(top); if (tlw == nullptr) throw ToolFailure("The widget has no window"); tlw->Update(); @@ -220,25 +439,119 @@ void register_view_tools(McpService& service) screenshot.journal = true; // a replay takes the same screenshots reg.add(screenshot); + reg.add(inspect_tool( + "get_preview", "Read the Preview", + "What the Preview shows for a sliced plate. summary: the slice reply'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 set_view's layer) Z, height, seconds and grams, paged; layer_features adds " + "each feature type's seconds. objects: grams per object instance, with its list_objects 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; 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("plate index out of range (0.." + std::to_string(plates.get_plate_count() - 1) + ")"); + 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 = "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 (run_action orca_command:plate_goto:orca, param \"" + 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 set_view {\"tab\": \"preview\"}"; + } + return out; + })); + })); + + // The legend combo's view types; the first-layer inspection type has no name and no combo entry. std::vector view_types; for (int i = 0; i < int(libvgcode::EViewType::COUNT); ++i) - view_types.push_back(GCodeViewer::view_type_to_config_name(libvgcode::EViewType(i))); + if (std::string name = GCodeViewer::view_type_to_config_name(libvgcode::EViewType(i)); !name.empty()) + view_types.push_back(std::move(name)); + + std::vector tabs{"home", "prepare", "preview", "device", "multi_device", "project", "calibration"}; +#ifdef SLIC3R_CAD + tabs.insert(tabs.begin() + 1, "design"); +#endif reg.add(mutate_tool( "set_view", "Point the view", "Set up what the window shows, for screenshots and GUI work: the main tab, the 3D view (Prepare's, the preview or " "the assemble view, which has its own gizmos), the 3D camera (a named direction, the default view, or fit to bed / " - "objects / selection), the preview's layer or layer range (1-based) and color scheme, and the window size. Only " - "the given fields change.", - object_schema({{"tab", enum_prop({"home", "prepare", "preview", "device", "multi_device", "project", "calibration"}, "Main window tab.")}, + "objects / selection), the preview's color scheme (picked as in the legend's combo, which shows every feature type " + "again), legend rows, time estimate and layers (1-based, or up to a height), and the window size. Only the given " + "fields change. On the Design tab the camera points its view (default is its Home view; no fit_bed). The reply " + "echoes them; preview layers as [first, last, count] with z, the heights of first and last.", + object_schema({{"tab", enum_prop(tabs, "Main window tab.")}, {"view", enum_prop({"3d", "preview", "assemble"}, "3D view: Prepare's, the preview, or the assemble view (needs an object; leave it with 3d, as its Return button does).")}, {"camera", enum_prop({"iso", "top", "bottom", "front", "rear", "left", "right", "default", "fit_bed", "fit_objects", "fit_selection"}, "Camera direction or fit.")}, {"layer", {{"type", "integer"}, {"minimum", 1}, {"description", "Preview: show layers up to this one (1-based)."}}}, {"layer_range", array_prop({{"type", "integer"}}, "Preview: [first, last] layers, 1-based.")}, + {"layer_z", {{"type", "number"}, {"minimum", 0}, {"description", "Preview: show layers up to the first whose top is at or above this height (mm), as the slider places a custom G-code."}}}, {"view_type", enum_prop(view_types, "Preview color scheme.")}, + {"legend", {{"type", "object"}, {"additionalProperties", {{"type", "boolean"}}}, + {"description", "Preview: show (true) or hide (false) legend rows: feature types by name as get_preview lists them " + "(\"Sparse infill\"), and travel, wipe, retract, unretract, seams, filament_changes, color_changes, " + "pauses, custom_gcode. Applied after view_type."}}}, + {"time_mode", enum_prop({"normal", "silent"}, "Preview: the time estimate the legend and layer times show; silent only when the print has its own.")}, {"window_size", array_prop({{"type", "integer"}}, "[width, height] of the main window in pixels.")}}), [](const json& args, ToolContext& ctx) { + const bool preview_args = args.contains("layer") || args.contains("layer_range") || args.contains("layer_z") || + args.contains("view_type") || args.contains("legend") || args.contains("time_mode"); + if (arg_string(args, "tab") == "design" && (args.contains("view") || preview_args)) + throw ToolFailure("view and the Preview fields show Prepare or Preview; give them without tab design"); json out = ctx.run_ui([&]() -> json { Plater& plater = ui_plater(); MainFrame* frame = wxGetApp().mainframe; @@ -256,6 +569,10 @@ void register_view_tools(McpService& service) const char* id = tab_id(arg_string(args, "tab")); if (id == nullptr) throw ToolFailure("Unknown tab"); +#ifdef SLIC3R_CAD + if (id == std::string(TAB_ID_DESIGN) && frame->m_design_page == nullptr) + throw ToolFailure("The Design tab is off; enable the CAD feature in Preferences and restart"); +#endif frame->select_tab(wxString(id)); done["tab"] = arg_string(args, "tab"); } @@ -283,14 +600,105 @@ void register_view_tools(McpService& service) frame->select_tab(wxString(TAB_ID_PREVIEW)); done["view"] = view; } - const bool preview_args = args.contains("layer") || args.contains("layer_range") || args.contains("view_type"); if (preview_args && !args.contains("tab") && !args.contains("view")) { plater.select_view_3D("Preview", false); frame->select_tab(wxString(TAB_ID_PREVIEW)); } - if (args.contains("camera")) { + if (preview_args) { + GLCanvas3D* canvas = plater.get_preview_canvas3D(); + if (canvas == nullptr) + throw ToolFailure("The preview is not available"); + GCodeViewer& viewer = canvas->get_gcode_viewer(); + if (args.contains("layer_z") && (args.contains("layer") || args.contains("layer_range"))) + throw ToolFailure("Give layer_z or layer/layer_range, not both"); + if ((args.contains("legend") || args.contains("time_mode")) && !viewer.has_data()) + throw ToolFailure("legend and time_mode need the Preview's toolpaths; slice first"); + const std::function show_legend = args.contains("legend") ? legend_change(viewer, args["legend"]) : nullptr; + const bool silent = arg_string(args, "time_mode") == "silent"; + if (silent && !viewer.can_switch_time_mode()) + throw ToolFailure("This print has no separate silent-mode estimate"); + // In this order, as a person would: picking Line Type shows every feature type again. + if (args.contains("view_type")) { + libvgcode::EViewType type; + if (!GCodeViewer::view_type_from_config_name(arg_string(args, "view_type"), type)) + throw ToolFailure("Unknown view_type"); + // Without toolpaths there is no legend to pick from; the type then applies to the next ones. + if (viewer.has_data()) + viewer.pick_view_type(type); + else + viewer.select_view_type(type); + done["view_type"] = arg_string(args, "view_type"); + } + if (show_legend) + done["legend"] = show_legend(); + if (args.contains("time_mode")) { + const libvgcode::ETimeMode mode = silent ? libvgcode::ETimeMode::Stealth : libvgcode::ETimeMode::Normal; + if (viewer.get_viewer().get_time_mode() != mode) + viewer.set_time_mode(mode); + done["time_mode"] = arg_string(args, "time_mode"); + } + if (args.contains("layer") || args.contains("layer_range") || args.contains("layer_z")) { + IMSlider* layers = viewer.get_layers_slider(); + if (layers == nullptr || layers->GetMaxValue() <= 0) + throw ToolFailure("The preview has no layers; slice first"); + const int max = layers->GetMaxValue(); + int lo = 0, hi = max; + if (args.contains("layer")) + hi = std::clamp(args["layer"].get() - 1, 0, max); + if (args.contains("layer_range")) { + const json& r = args["layer_range"]; + if (!r.is_array() || r.size() != 2) + throw ToolFailure("layer_range must be [first, last]"); + lo = std::clamp(r[0].get() - 1, 0, max); + hi = std::clamp(r[1].get() - 1, lo, max); + } + if (args.contains("layer_z")) { + // The slider's own rule for a height, which set_layer_gcode's z follows too. + const double z = args["layer_z"].get(); + hi = layers->get_tick_from_value(z, true); + if (hi < 0 || hi > max) + throw ToolFailure("layer_z " + json(z).dump() + " is above the top layer (" + + json(rounded(layers->GetMaxValueD(), 1000.)).dump() + " mm)"); + } + layers->SetHigherValue(hi); + layers->SetLowerValue(lo); + layers->set_as_dirty(); + if (IMSlider* moves = viewer.get_moves_slider()) { + moves->SetHigherValue(moves->GetMaxValue()); + moves->set_as_dirty(); + } + done["layers"] = {lo + 1, hi + 1, max + 1}; + done["z"] = {rounded(layers->GetLowerValueD(), 1000.), rounded(layers->GetHigherValueD(), 1000.)}; + } + canvas->set_as_dirty(); + } + if (GLCanvas3D* canvas = plater.get_current_canvas3D()) + canvas->set_as_dirty(); + return done; + }); + if (args.contains("camera")) { + // A tab's page shows, and the Design tab takes the shared camera, once the tab change is + // handled; the camera then points the view on screen. + settle(ctx); + out["camera"] = ctx.run_ui([&]() -> json { + Plater& plater = ui_plater(); const std::string cam = arg_string(args, "camera"); - GLCanvas3D* canvas = plater.get_current_canvas3D(); +#ifdef SLIC3R_CAD + if (DesignPanel* design = wxGetApp().mainframe->shown_design_panel()) { + DesignCanvas* view = design->mcp_viewport(); + if (cam == "fit_bed") + throw ToolFailure("fit_bed is not offered in the Design tab"); + if (cam == "fit_objects") + view->fit_view(); + else if (cam == "fit_selection") { + if (!view->zoom_to_box(view->selection_box())) + throw ToolFailure("Nothing is selected in the Design tab"); + } else + view->set_view(cam == "default" ? "iso" : cam); // default: the tab's Home view + return cam; + } +#endif + GLCanvas3D* canvas = plater.get_current_canvas3D(); if (cam == "default") { plater.select_view("plate"); if (canvas) @@ -307,50 +715,11 @@ void register_view_tools(McpService& service) } else { plater.select_view(cam); } - done["camera"] = cam; - } - if (preview_args) { - GLCanvas3D* canvas = plater.get_preview_canvas3D(); - if (canvas == nullptr) - throw ToolFailure("The preview is not available"); - GCodeViewer& viewer = canvas->get_gcode_viewer(); - if (args.contains("view_type")) { - libvgcode::EViewType type; - if (!GCodeViewer::view_type_from_config_name(arg_string(args, "view_type"), type)) - throw ToolFailure("Unknown view_type"); - viewer.select_view_type(type); - done["view_type"] = arg_string(args, "view_type"); - } - if (args.contains("layer") || args.contains("layer_range")) { - IMSlider* layers = viewer.get_layers_slider(); - if (layers == nullptr || layers->GetMaxValue() <= 0) - throw ToolFailure("The preview has no layers; slice first"); - const int max = layers->GetMaxValue(); - int lo = 0, hi = max; - if (args.contains("layer")) - hi = std::clamp(args["layer"].get() - 1, 0, max); - if (args.contains("layer_range")) { - const json& r = args["layer_range"]; - if (!r.is_array() || r.size() != 2) - throw ToolFailure("layer_range must be [first, last]"); - lo = std::clamp(r[0].get() - 1, 0, max); - hi = std::clamp(r[1].get() - 1, lo, max); - } - layers->SetHigherValue(hi); - layers->SetLowerValue(lo); - layers->set_as_dirty(); - if (IMSlider* moves = viewer.get_moves_slider()) { - moves->SetHigherValue(moves->GetMaxValue()); - moves->set_as_dirty(); - } - done["layers"] = {lo + 1, hi + 1, max + 1}; - } - canvas->set_as_dirty(); - } - if (GLCanvas3D* canvas = plater.get_current_canvas3D()) - canvas->set_as_dirty(); - return done; - }); + if (canvas) + canvas->set_as_dirty(); + return cam; + }); + } if (out.value("view", "") == "assemble") // A canvas shown for the first time loads its scene at its first frame, once its GL // surface exists (a moment later on Wayland), and the next call may act on its objects. diff --git a/src/slic3r/GUI/Mcp/ModalTracker.cpp b/src/slic3r/GUI/Mcp/ModalTracker.cpp index 8b2b891c64..4a639b09ff 100644 --- a/src/slic3r/GUI/Mcp/ModalTracker.cpp +++ b/src/slic3r/GUI/Mcp/ModalTracker.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -24,6 +25,7 @@ #include #include #include +#include #include #include #include @@ -162,6 +164,31 @@ int resolve_dialog_button(wxDialog* dialog, const std::string& button) return wxID_NONE; } +bool press_dialog_button(wxDialog* dialog, int id) +{ + wxWindow* pressed = nullptr; + std::function find = [&](wxWindow* w) { + for (wxWindow* child : w->GetChildren()) { + if (pressed != nullptr || dynamic_cast(child) != nullptr) + continue; + if (child->GetId() == id && child->IsShown() && child->IsEnabled() && + (dynamic_cast(child) != nullptr || class_name(child).find("Button") != std::string::npos)) + pressed = child; + else + find(child); + } + }; + find(dialog); + if (pressed == nullptr) { + dialog->EndModal(id); + return false; + } + wxCommandEvent evt(wxEVT_BUTTON, id); + evt.SetEventObject(pressed); + pressed->GetEventHandler()->ProcessEvent(evt); + return true; +} + AutoAnswerRule make_rule(const std::string& pattern, const std::string& button) { AutoAnswerRule rule; @@ -237,9 +264,9 @@ int ModalTracker::Enter(wxDialog* dialog) { // An exception must never escape into ShowModal(). try { - const json info = describe_dialog(dialog); - const std::string text = info["title"].get() + "\n" + info["message"].get(); - { + const json info = describe_dialog(dialog); + const std::string text = info["title"].get() + "\n" + info["message"].get(); + const int answer = [&] { std::lock_guard lock(m_mutex); for (auto layer = m_layers.rbegin(); layer != m_layers.rend(); ++layer) for (AutoAnswerRule& rule : layer->second) @@ -251,12 +278,26 @@ int ModalTracker::Enter(wxDialog* dialog) ++rule.uses; BOOST_LOG_TRIVIAL(info) << "MCP: auto-answered dialog \"" << info["title"].get() << "\" with " << rule.button << " (rule \"" << rule.pattern << "\")"; - return id; // ShowModal() returns it without showing the dialog + return id; } } - } + return int(wxID_NONE); + }(); + // A native dialog has no handlers to run: ShowModal() returns the id without showing it. + if (answer != wxID_NONE && is_native_dialog(dialog)) + return answer; m_stack.push_back(dialog); publish(); + // A wx dialog's buttons do its work in their handlers (Transfer, Discard, Clone's Fill), which + // a returned id would skip. So it opens, and the button is pressed once its modal loop runs, as + // dialog_respond does. Queued on the dialog, the press goes with it if it is destroyed first; + // a modal opened above it before then leaves it to dialog_respond. The tracker lives as long + // as the app. + if (answer != wxID_NONE) + dialog->CallAfter([this, dialog, answer] { + if (top() == dialog) + press_dialog_button(dialog, answer); + }); } catch (...) { } return wxID_NONE; diff --git a/src/slic3r/GUI/Mcp/ModalTracker.hpp b/src/slic3r/GUI/Mcp/ModalTracker.hpp index e7c38661f8..5c156580db 100644 --- a/src/slic3r/GUI/Mcp/ModalTracker.hpp +++ b/src/slic3r/GUI/Mcp/ModalTracker.hpp @@ -29,8 +29,9 @@ AutoAnswerRule make_rule(const std::string& pattern, const std::string& button); // Every modal dialog shown through ShowModal - Orca's own, wxMessageDialog and the native file // dialogs alike - passes through this hook. It keeps the stack of open modals for the guards and -// the tools, answers dialogs that match a registered rule without showing them, and publishes a -// description snapshot that other threads may read. +// the tools, answers dialogs that match a registered rule, and publishes a description snapshot +// that other threads may read. A matching native dialog is answered without showing; a matching wx +// dialog opens and has the rule's button pressed (press_dialog_button()), so its handler runs. class ModalTracker final : public wxModalDialogHook { public: @@ -79,6 +80,11 @@ bool is_picker(wxDialog* dialog); // The id a button name or label stands for in `dialog`, or wxID_NONE. UI thread only. int resolve_dialog_button(wxDialog* dialog, const std::string& button); +// Presses the button with `id` in `dialog` so the dialog's own handler runs, or ends the dialog with +// that id when no such button exists. Returns whether a button was pressed. UI thread only, while +// the dialog is modal. +bool press_dialog_button(wxDialog* dialog, int id); + // Demangled C++ class name of a window, e.g. "Slic3r::GUI::MessageDialog". std::string class_name(const wxWindow* window); diff --git a/src/slic3r/GUI/Mcp/ScreenCapture.cpp b/src/slic3r/GUI/Mcp/ScreenCapture.cpp index 4fe71f0c02..6c06f2cfbc 100644 --- a/src/slic3r/GUI/Mcp/ScreenCapture.cpp +++ b/src/slic3r/GUI/Mcp/ScreenCapture.cpp @@ -1,8 +1,7 @@ #include "ScreenCapture.hpp" +#include "UiInspector.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" -#include "slic3r/GUI/GUI_App.hpp" -#include "slic3r/GUI/Plater.hpp" #include #include @@ -108,36 +107,31 @@ std::optional capture_window(wxTopLevelWindow& window, std::string& err return std::nullopt; // Composite every visible 3D canvas inside this window from an exact frame capture. - Plater* plater = wxGetApp().plater(); - if (plater != nullptr) - for (GLCanvas3D* canvas : {plater->get_view3D_canvas3D(), plater->get_preview_canvas3D(), plater->get_assmeble_canvas3D()}) { - if (canvas == nullptr || canvas->get_wxglcanvas() == nullptr) - continue; - wxGLCanvas* glc = canvas->get_wxglcanvas(); - if (!glc->IsShownOnScreen() || wxGetTopLevelParent(glc) != &window) - continue; - std::string canvas_err; - wxImage frame; - if (!canvas->render_and_capture(frame, canvas_err)) { - c.approximate = true; - c.note += (c.note.empty() ? "" : "; ") + std::string("3D view not composited: ") + canvas_err; - continue; - } - c.blank_canvas = c.blank_canvas || is_blank(frame); - composite(c.image, frame, client_offset_in(*glc, window)); + std::vector captured; + for (GLCanvas3D* canvas : ui_canvases()) { + wxGLCanvas* glc = canvas->get_wxglcanvas(); + if (glc == nullptr) + continue; + captured.push_back(glc); + if (!glc->IsShownOnScreen() || wxGetTopLevelParent(glc) != &window) + continue; + std::string canvas_err; + wxImage frame; + if (!canvas->render_and_capture(frame, canvas_err)) { + c.approximate = true; + c.note += (c.note.empty() ? "" : "; ") + std::string("3D view not composited: ") + canvas_err; + continue; } + c.blank_canvas = c.blank_canvas || is_blank(frame); + composite(c.image, frame, client_offset_in(*glc, window)); + } - // Other OpenGL views (the Design tab's) have no frame capture: say so rather than return their - // area as the window capture left it. - std::vector plater_canvases; - if (plater != nullptr) - for (GLCanvas3D* canvas : {plater->get_view3D_canvas3D(), plater->get_preview_canvas3D(), plater->get_assmeble_canvas3D()}) - if (canvas != nullptr) - plater_canvases.push_back(canvas->get_wxglcanvas()); + // An OpenGL view with no frame capture: say so rather than return its area as the window + // capture left it. std::function other_gl = [&](wxWindow* w) { if (!w->IsShownOnScreen()) return false; - if (dynamic_cast(w) != nullptr && std::find(plater_canvases.begin(), plater_canvases.end(), w) == plater_canvases.end()) + if (dynamic_cast(w) != nullptr && std::find(captured.begin(), captured.end(), w) == captured.end()) return true; for (wxWindow* child : w->GetChildren()) if (dynamic_cast(child) == nullptr && other_gl(child)) @@ -146,7 +140,7 @@ std::optional capture_window(wxTopLevelWindow& window, std::string& err }; if (other_gl(&window)) { c.approximate = true; - c.note += (c.note.empty() ? "" : "; ") + std::string("a 3D view outside Prepare and Preview (the Design tab) is not captured"); + c.note += (c.note.empty() ? "" : "; ") + std::string("an OpenGL view other than the 3D views is not captured"); } return c; } diff --git a/src/slic3r/GUI/Mcp/UiInspector.cpp b/src/slic3r/GUI/Mcp/UiInspector.cpp index 94f4f8497a..72d193474d 100644 --- a/src/slic3r/GUI/Mcp/UiInspector.cpp +++ b/src/slic3r/GUI/Mcp/UiInspector.cpp @@ -9,24 +9,30 @@ #include "slic3r/GUI/BBLTopbar.hpp" #include "slic3r/GUI/Camera.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" +#include "slic3r/GUI/ExtraRenderers.hpp" #include "slic3r/GUI/GLToolbar.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/Gizmos/GLGizmoBase.hpp" #include "slic3r/GUI/Gizmos/GLGizmoSVG.hpp" #include "slic3r/GUI/Gizmos/GLGizmosManager.hpp" #include "slic3r/GUI/ImGuiWrapper.hpp" +#include "slic3r/GUI/Jobs/Worker.hpp" #include "slic3r/GUI/KeyChord.hpp" #include "slic3r/GUI/MainFrame.hpp" #include "slic3r/GUI/MeshUtils.hpp" +#include "slic3r/GUI/ObjectDataViewModel.hpp" #include "slic3r/GUI/PartPlate.hpp" #include "slic3r/GUI/Plater.hpp" +#include "slic3r/GUI/SceneRaycaster.hpp" #include "slic3r/GUI/Selection.hpp" #include "slic3r/GUI/SyntheticInput.hpp" #include "slic3r/GUI/Widgets/Button.hpp" #include "slic3r/GUI/Widgets/SideButton.hpp" #include "slic3r/GUI/Widgets/ComboBox.hpp" +#include "slic3r/GUI/Widgets/DropDown.hpp" #include "slic3r/GUI/Widgets/SpinInput.hpp" #include "slic3r/GUI/Widgets/TextInput.hpp" #include "libslic3r/AABBMesh.hpp" @@ -36,27 +42,39 @@ #include "libslic3r/Polygon.hpp" #include "libslic3r/PrintConfig.hpp" #include "UiRefs.hpp" +#ifdef SLIC3R_CAD +#include "slic3r/GUI/CAD/DesignCanvas.hpp" +#include "slic3r/GUI/CAD/DesignPanel.hpp" +#include "slic3r/GUI/CAD/DesignRowList.hpp" +#endif #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 @@ -69,6 +87,7 @@ #include #include #include +#include #include #include #include @@ -80,16 +99,21 @@ #include #include #include +#include #include #include #include #include +#include #include #include +#include #include +#include #include #include #include +#include #include #include @@ -118,6 +142,8 @@ std::string short_class(const wxWindow* w) // The role a window plays for an agent; empty for plain containers. std::string kind_of(wxWindow* w) { + if (dynamic_cast(w) != nullptr) + return "popup"; if (dynamic_cast(w) != nullptr) return "dialog"; if (dynamic_cast(w) != nullptr) @@ -144,8 +170,12 @@ std::string kind_of(wxWindow* w) return "text"; if (dynamic_cast(w) != nullptr) return "slider"; - if (dynamic_cast(w) != nullptr || dynamic_cast(w) != nullptr) + if (dynamic_cast(w) != nullptr || dynamic_cast(w) != nullptr || dynamic_cast(w) != nullptr) return "list"; +#ifdef SLIC3R_CAD + if (dynamic_cast(w) != nullptr) + return "list"; +#endif if (dynamic_cast(w) != nullptr) return "tabs"; if (dynamic_cast(w) != nullptr) @@ -242,6 +272,9 @@ std::string option_label(const std::string& key) std::string label_of(wxWindow* w) { + // A popup has no title, and a drop-down list's tooltip is the hovered item's. + if (dynamic_cast(w) != nullptr) + return {}; if (auto* tlw = dynamic_cast(w)) return into_u8(tlw->GetTitle()); // Input fields are named by the setting they edit or the label on their row; their own label is @@ -411,6 +444,43 @@ wxMenuItem* find_menu_path(const std::string& wanted, int& id) return nullptr; } +// What a menu appends to the label of the item in use, which menu paths may leave out. +std::string current_marker() { return " (" + _u8L("current") + ")"; } + +// The items of a popup menu, a submenu before its items, with the paths automation names them by. +std::vector menu_entries(wxMenu& menu) +{ + std::vector entries; + std::function walk = [&](wxMenu& m, int parent, bool enabled) { + for (wxMenuItem* item : m.GetMenuItems()) { + if (item->IsSeparator()) + continue; + MenuEntry e; + e.label = into_u8(item->GetItemLabelText()); + e.parent = parent; + e.id = item->GetId(); + e.enabled = enabled && item->IsEnabled(); + e.checkable = item->IsCheckable(); + e.checked = e.checkable && item->IsChecked(); + e.submenu = item->IsSubMenu(); + entries.push_back(e); + if (e.submenu) + walk(*item->GetSubMenu(), int(entries.size()) - 1, e.enabled); + } + }; + walk(menu, -1, true); + name_menu_entries(entries, current_marker()); + return entries; +} + +// Native controls act on what the system tells them, not on wx mouse events sent to them, so a +// click at a point of one does nothing. +bool is_native_control(wxWindow* w) +{ + return dynamic_cast(w) != nullptr || dynamic_cast(w) != nullptr || dynamic_cast(w) != nullptr || + dynamic_cast(w) != nullptr || dynamic_cast(w) != nullptr; +} + } // namespace // Stable English gizmo names for refs and locators: the names Orca uses for the gizmos it names, @@ -549,14 +619,14 @@ struct HeldKeys HeldKeys& operator=(const HeldKeys&) = delete; }; -// A mouse click on a plain window at its centre: down, up, and the double-click or context-menu -// event a real click produces. +// A mouse click on a plain window, at its centre or at the point the options give: down, up, and the +// double-click or context-menu event a real click produces. void click_window(wxWindow* w, const ClickOptions& o) { const int mods = parse_modifiers(o.modifiers); HeldKeys held(modifier_keys(mods)); const wxSize size = w->GetClientSize(); - const wxPoint pos(size.x / 2, size.y / 2); + const wxPoint pos = o.at_point ? wxPoint(o.x, o.y) : wxPoint(size.x / 2, size.y / 2); const bool right = o.button == "right", middle = o.button == "middle", left = !right && !middle; const auto down = left ? wxEVT_LEFT_DOWN : right ? wxEVT_RIGHT_DOWN : wxEVT_MIDDLE_DOWN; const auto up = left ? wxEVT_LEFT_UP : right ? wxEVT_RIGHT_UP : wxEVT_MIDDLE_UP; @@ -570,10 +640,14 @@ void click_window(wxWindow* w, const ClickOptions& o) wxMouseEvent u2 = mouse_event(wxEVT_LEFT_UP, pos, false, false, false, mods); send(w, u2); } +#ifndef __WXOSX__ + // On macOS wx makes the context menu event itself from a right press its handlers pass on, as for a + // real click; elsewhere it comes from the system. if (right) { wxContextMenuEvent menu(wxEVT_CONTEXT_MENU, w->GetId(), w->ClientToScreen(pos)); send(w, menu); } +#endif } // Delivers synthesized mouse events to a 3D canvas, drawing a frame after each so ImGui sees the @@ -717,6 +791,30 @@ bool in_popup(const ImGuiWrapper::RecordedItem& item) return item.window.rfind("##Combo", 0) == 0 || item.window.rfind("##Popup", 0) == 0; } +// What a click at logical pixel `pixel` of `canvas` would reach instead of its target, described for +// a reason: the ImGui window over the pixel, unless it is `own` (the window of the ImGui item the +// click is for) or one of `own`'s children; for a click on the scene (no `own`), also an open popup, +// which takes any click to close itself. Empty when the click reaches its target. Judged on a frame +// drawn now, whose windows ImGui hands the click's events to. +std::string covered_by(GLCanvas3D& canvas, const wxPoint& pixel, const std::string& own = {}) +{ + ImGuiWrapper* imgui = wxGetApp().imgui(); + if (imgui == nullptr || ImGui::GetCurrentContext() == nullptr) + return {}; + canvas.set_as_dirty(); + canvas.render(); + const float scale = canvas.get_scale(); + ImGuiWindow* hit = imgui_window_at(ImVec2(float(pixel.x) * scale, float(pixel.y) * scale)); + ImGuiWindow* mine = own.empty() ? nullptr : ImGui::FindWindowByName(own.c_str()); + if (hit != nullptr && mine != nullptr && hit->RootWindow == mine->RootWindow) + return {}; + const ImGuiContext& g = *ImGui::GetCurrentContext(); + ImGuiWindow* cover = hit != nullptr ? hit : own.empty() && g.OpenPopupStack.Size > 0 ? g.OpenPopupStack.back().Window : nullptr; + if (cover == nullptr) + return {}; + return imgui_window_description(cover->RootWindow->Name, imgui->recorded_texts(&canvas)); +} + // The logical pixel of `canvas` showing a point of the model: {object, instance, volume} and either // `point` (with `frame` "volume", the part's mesh coordinates, or "world", the scene's) or `spot`. // With `check` "surface" a click there must land on that part at that point (see check_surface()). @@ -779,24 +877,16 @@ wxPoint target_pixel(GLCanvas3D& canvas, const json& target, const std::string& const wxPoint pixel(int(std::lround(projected->x())), int(std::lround(projected->y()))); if (check == "surface") { - // What a person sees: active parts, and the parts of the instance the open gizmo works on. - // Other inactive parts are hidden, modifiers are see-through, and gizmo geometry takes clicks - // as it would from a person. + // What a person sees (surface_meshes()): other inactive parts are hidden, other modifiers and + // negative parts are see-through, and gizmo geometry takes clicks as it would from a person. // The manager hands the plane out flipped, for drawing; the gizmos' own raycasts use it as // the object clipper holds it. std::optional clip; if (gizmo) if (const auto drawn = gizmos.get_clipping_plane()) clip = drawn->inverted_normal(); - std::vector meshes; - BoundingBoxf3 target_box; - for (const GLVolume* v : canvas.get_volumes().volumes) { - if (v->mesh_raycaster == nullptr || !v->visible || v->is_modifier || (!v->is_active && !own(v))) - continue; - meshes.push_back({&v->mesh_raycaster->get_aabb_mesh(), v->world_matrix(), v == shown, own(v), - "object " + std::to_string(v->object_idx()) + " instance " + std::to_string(v->instance_idx()) + - " part " + std::to_string(v->volume_idx())}); - } + const std::vector meshes = surface_meshes(canvas.get_volumes().volumes, shown, own); + BoundingBoxf3 target_box; for (const Vec3f& vertex : mesh.vertices()) target_box.merge(world * vertex.cast()); std::vector beds; @@ -831,7 +921,7 @@ bool selection_is_svg_part(GLCanvas3D& canvas) const char* canvas_name(GLCanvas3D* canvas) { Plater* plater = wxGetApp().plater(); - if (plater == nullptr) + if (plater == nullptr || canvas == nullptr) return ""; if (canvas == plater->get_view3D_canvas3D()) return "3d"; @@ -839,11 +929,11 @@ const char* canvas_name(GLCanvas3D* canvas) return "preview"; if (canvas == plater->get_assmeble_canvas3D()) return "assemble"; + if (canvas == design_canvas()) + return "design"; return ""; } -namespace { - GLCanvas3D* canvas_by_name(const std::string& name) { Plater* plater = wxGetApp().plater(); @@ -853,17 +943,51 @@ GLCanvas3D* canvas_by_name(const std::string& name) return plater->get_preview_canvas3D(); if (name == "assemble") return plater->get_assmeble_canvas3D(); + if (name == "design") + return design_canvas(); if (name == "3d" || name.empty()) return plater->get_view3D_canvas3D(); return nullptr; } +namespace { + bool is_live_canvas(GLCanvas3D* canvas) { - const auto canvases = live_canvases(); + const auto canvases = ui_canvases(); return canvas != nullptr && std::find(canvases.begin(), canvases.end(), canvas) != canvases.end(); } +static_assert(kPlateIconCount == int(PartPlate::GRABBER_COUNT), "plate icon names follow PartPlate's picking actions"); + +// The plates and plate icons the Prepare view can pick now, by bed picking id. PartPlate registers +// the icons it shows (settings where plate settings are offered, filament_map on two-nozzle Bambu +// printers, imex_mode on IDEX printers), and other plates are inactive while they are hidden, so the +// registry says what a click can reach. +std::set plate_picking_ids(GLCanvas3D& canvas) +{ + std::set ids; + if (const auto* items = canvas.get_raycasters_for_picking(SceneRaycaster::EType::Bed)) + for (const std::shared_ptr& item : *items) + if (item->is_active()) + ids.insert(SceneRaycaster::decode_id(SceneRaycaster::EType::Bed, item->get_id())); + return ids; +} + +// A plate as the object list names it: "Plate 2", with its own name after it. +std::string plate_label(PartPlate& plate) +{ + std::string label = _u8L("Plate") + " " + std::to_string(plate.get_index() + 1); + if (!plate.get_plate_name().empty()) + label += " (" + plate.get_plate_name() + ")"; + return label; +} + +std::string no_such_plate(int plate, int count) +{ + return "Plate " + std::to_string(plate) + " does not exist (plates 0.." + std::to_string(count - 1) + ")"; +} + } // namespace std::vector live_canvases() @@ -876,6 +1000,685 @@ std::vector live_canvases() return out; } +GLCanvas3D* design_canvas() +{ +#ifdef SLIC3R_CAD + if (DesignPanel* design = DesignPanel::if_built()) + if (DesignCanvas* view = design->mcp_viewport()) + return view->gl_canvas(); +#endif + return nullptr; +} + +std::vector ui_canvases() +{ + std::vector out = live_canvases(); + if (GLCanvas3D* design = design_canvas()) + out.push_back(design); + return out; +} + +GLCanvas3D* shown_canvas() +{ +#ifdef SLIC3R_CAD + if (MainFrame* frame = wxGetApp().mainframe; frame != nullptr && frame->shown_design_panel() != nullptr) + return design_canvas(); +#endif + Plater* plater = wxGetApp().plater(); + return plater != nullptr ? plater->get_current_canvas3D() : nullptr; +} + +// ---- popups and rows of lists ----------------------------------------------------------------- + +wxWindow* owning_window(wxWindow* w) +{ + wxWindow* top = w != nullptr ? wxGetTopLevelParent(w) : nullptr; + while (dynamic_cast(top) != nullptr && top->GetParent() != nullptr) + top = wxGetTopLevelParent(top->GetParent()); + return top; +} + +std::vector popups_of(wxWindow* top) +{ + std::vector out; + std::function visit = [&](wxWindow* w) { + for (wxWindow* child : w->GetChildren()) { + if (dynamic_cast(child) != nullptr || !child->IsShown()) + continue; + if (dynamic_cast(child) != nullptr) + out.push_back(child); + visit(child); + } + }; + if (top != nullptr) + visit(top); + return out; +} + +namespace { + +std::string joined(const std::vector& parts, const char* separator) +{ + std::string out; + for (std::size_t i = 0; i < parts.size(); ++i) + out += (i == 0 ? "" : separator) + parts[i]; + return out; +} + +// The object list's columns by model column (ColumnNumber): it shows no header, so they are named here. +const char* const kObjectListColumns[] = {"Name", "Height", "Printable", "Filament", "Support", "Color", "Sinking", "Editing"}; + +std::vector shown_columns(wxDataViewCtrl& ctrl) +{ + std::vector out; + for (unsigned i = 0; i < ctrl.GetColumnCount(); ++i) + if (wxDataViewColumn* c = ctrl.GetColumn(i); c != nullptr && !c->IsHidden()) + out.push_back(c); + return out; +} + +std::string column_name(wxDataViewCtrl& ctrl, const wxDataViewColumn& col, std::size_t pos) +{ + if (dynamic_cast(&ctrl) != nullptr && col.GetModelColumn() < std::size(kObjectListColumns)) + return kObjectListColumns[col.GetModelColumn()]; + wxString title = col.GetTitle(); + const std::string name = into_u8(title.Trim().Trim(false)); + return name.empty() ? "#" + std::to_string(pos + 1) : name; +} + +// The column `name` picks (see list_columns()), or the first shown one for none. +wxDataViewColumn* data_view_column(wxDataViewCtrl& ctrl, const std::string& name) +{ + const std::vector cols = shown_columns(ctrl); + if (cols.empty()) + throw ToolFailure("The list shows no columns"); + if (name.empty()) + return cols.front(); + for (std::size_t i = 0; i < cols.size(); ++i) + if (lower(column_name(ctrl, *cols[i], i)) == lower(name)) + return cols[i]; + throw ToolFailure("The list has no column \"" + name + "\"", {{"columns", list_columns(&ctrl)}}); +} + +// A cell's text as it shows: outside macOS the compare presets and unsaved changes trees draw theirs from +// markup (, ), whose tags and entities are not shown. Other text is kept as it is. +std::string shown_text(const wxString& value) +{ + const std::string text = into_u8(value); + if (text.empty() || text.front() != '<') + return text; + static constexpr std::pair entities[] = {{"<", '<'}, {">", '>'}, {"&", '&'}, {""", '"'}, {"'", '\''}}; + std::string out; + for (std::size_t i = 0; i < text.size(); ++i) { + if (text[i] == '<') { + if ((i = text.find('>', i)) == std::string::npos) + return text; + continue; + } + char c = text[i]; + if (c == '&') + for (const auto& [entity, plain] : entities) + if (text.compare(i, entity.size(), entity) == 0) { + c = plain; + i += entity.size() - 1; + break; + } + out += c; + } + return out; +} + +// The text a data view cell shows, or for a checkbox cell nothing, its state going to `checked` (the +// row's first). Icon cells show nothing. +std::optional cell_text(wxDataViewModel& model, const wxDataViewItem& item, unsigned col, int& checked) +{ + wxVariant v; + model.GetValue(v, item, col); + const wxString type = v.GetType(); + if (type == "bool") { + if (checked < 0) + checked = v.GetBool() ? 1 : 0; + return std::nullopt; + } + if (type == "string") + return shown_text(v.GetString()); + if (type == "wxDataViewIconText") { + wxDataViewIconText text; + text << v; + return shown_text(text.GetText()); + } + if (type == "DataViewBitmapText") { + DataViewBitmapText text; + text << v; + return shown_text(text.GetText()); + } + if (type == "long" || type == "double") + return into_u8(v.MakeString()); + return std::nullopt; +} + +// What an object list row stands for, by the indices list_objects uses. +std::string object_row_note(ObjectDataViewModel& model, const wxDataViewItem& item) +{ + int plate = -1; + const ItemType type = model.GetItemType(item, plate); + const std::string object = "object " + std::to_string(model.GetObjectIdByItem(item)); + switch (type) { + case itPlate: return plate >= 0 ? "plate " + std::to_string(plate) : "outside the plates"; + case itObject: return object; + case itVolume: { + const std::string part = object + " part " + std::to_string(model.GetVolumeIdByItem(item)); + switch (model.GetVolumeType(item)) { + case ModelVolumeType::NEGATIVE_VOLUME: return part + ", negative"; + case ModelVolumeType::PARAMETER_MODIFIER: return part + ", modifier"; + case ModelVolumeType::SUPPORT_BLOCKER: return part + ", support_blocker"; + case ModelVolumeType::SUPPORT_ENFORCER: return part + ", support_enforcer"; + default: return part; + } + } + case itInstanceRoot: return "instances of " + object; + case itInstance: return object + " instance " + std::to_string(model.GetInstanceIdByItem(item)); + case itSettings: return "settings of " + object_row_note(model, model.GetParent(item)); + case itLayerRoot: return "layer ranges of " + object; + case itLayer: { + const auto range = model.GetLayerRangeByItem(item); + char text[64]; + std::snprintf(text, sizeof(text), " layer range %g-%g", range.first, range.second); + return object + text; + } + case itInfo: return "info of " + object; + default: return {}; + } +} + +void data_view_rows(wxDataViewCtrl& ctrl, std::vector& out) +{ + wxDataViewModel* model = ctrl.GetModel(); + if (model == nullptr) + return; + const std::vector cols = shown_columns(ctrl); + auto* objects = dynamic_cast(model); + // Collapsed branches too: acting on a row expands the branches above it. + std::function&, int, bool)> add = + [&](const wxDataViewItem& parent, const std::vector& above, int depth, bool shown) { + wxDataViewItemArray children; + model->GetChildren(parent, children); + for (const wxDataViewItem& item : children) { + ListRow row; + row.path = above; + bool labelled = false; + for (wxDataViewColumn* col : cols) { + const std::optional text = cell_text(*model, item, col->GetModelColumn(), row.checked); + if (!text) + continue; + if (!labelled) + row.path.push_back(*text); + else if (!text->empty()) + row.value += (row.value.empty() ? "" : " | ") + *text; + labelled = true; + } + if (!labelled) + row.path.emplace_back(); + if (objects != nullptr) + row.note = object_row_note(*objects, item); + row.selected = ctrl.IsSelected(item); + row.shown = shown; + row.depth = depth; + row.item = item; + const std::vector path = row.path; + out.push_back(std::move(row)); + if (model->IsContainer(item)) + add(item, path, depth + 1, shown && ctrl.IsExpanded(item)); + } + }; + add(wxDataViewItem(nullptr), {}, 0, true); +} + +void list_box_rows(wxListBox& box, std::vector& out) +{ + auto* checks = dynamic_cast(&box); + for (unsigned i = 0; i < box.GetCount(); ++i) { + ListRow row; + row.path = {into_u8(box.GetString(i))}; + row.checked = checks == nullptr ? -1 : checks->IsChecked(i) ? 1 : 0; + row.selected = box.IsSelected(int(i)); + row.index = int(i); + out.push_back(std::move(row)); + } +} + +// A drop-down list's items; one of a group, which shows in a sublist, has the group's label above it. +// The picked item is the checked one. +void drop_down_rows(DropDown& drop, std::vector& out) +{ + if (drop.IsSubList()) + return; // its main list has the same items + const std::vector& items = drop.GetItems(); + for (std::size_t i = 0; i < items.size(); ++i) { + const DropDown::Item& item = items[i]; + if ((item.style & DD_ITEM_STYLE_SPLIT_ITEM) != 0) + continue; + ListRow row; + if (!item.group_key.IsEmpty()) { + row.path.push_back(into_u8(item.group_label.IsEmpty() ? item.group_key : item.group_label)); + row.note = "in " + row.path.back(); + } + row.path.push_back(into_u8(item.text)); + row.enabled = (item.style & DD_ITEM_STYLE_DISABLED) == 0; + row.checked = drop.GetSelection() == int(i) ? 1 : -1; + row.index = int(i); + out.push_back(std::move(row)); + } +} + +// A table's column titles as its header shows them, without a sort indicator ("Name ↑↓" in the object +// settings table); empty for a hidden or untitled column. A table that hides its column labels draws +// its titles as its first row, so they are read from there. +std::vector grid_titles(wxGrid& grid) +{ + const bool header_row = grid.GetColLabelSize() == 0; + std::vector out(std::size_t(std::max(grid.GetNumberCols(), 0))); + for (int c = 0; c < int(out.size()); ++c) { + if (!grid.IsColShown(c) || (header_row && grid.GetNumberRows() == 0)) + continue; + wxString title = header_row ? grid.GetCellValue(0, c) : grid.GetColLabelValue(c); + title.Trim(); + while (title.EndsWith(wxString::FromUTF8("\u2191")) || title.EndsWith(wxString::FromUTF8("\u2193"))) + title.RemoveLast().Trim(); + out[std::size_t(c)] = into_u8(title); + } + return out; +} + +// A cell's text without the indent a table may draw parts with; a checkbox cell's state. +std::string grid_cell(wxGrid& grid, int row, int col) +{ + wxGridTableBase* table = grid.GetTable(); + if (table->GetTypeName(row, col) == wxGRID_VALUE_BOOL && table->CanGetValueAs(row, col, wxGRID_VALUE_BOOL)) + return table->GetValueAsBool(row, col) ? "yes" : "no"; + wxString text = grid.GetCellValue(row, col); + return into_u8(text.Trim().Trim(false)); +} + +// The column a table row is named and clicked by: its "Name" column, else its first titled one. +int grid_name_column(const std::vector& titles) +{ + const auto name = std::find(titles.begin(), titles.end(), "Name"); + if (name != titles.end()) + return int(name - titles.begin()); + const auto titled = std::find_if(titles.begin(), titles.end(), [](const std::string& t) { return !t.empty(); }); + return titled == titles.end() ? -1 : int(titled - titles.begin()); +} + +// A table's rows, read-only: named by their "Name" cell, else by their row label where the table +// shows one, else by their first titled cell, with every titled cell as the value. +void grid_rows(wxGrid& grid, std::vector& out) +{ + if (grid.GetTable() == nullptr) + return; + const std::vector titles = grid_titles(grid); + const bool named = std::find(titles.begin(), titles.end(), "Name") != titles.end(); + const int name = grid_name_column(titles); + for (int r = grid.GetColLabelSize() == 0 ? 1 : 0; r < grid.GetNumberRows(); ++r) { + if (!grid.IsRowShown(r)) + continue; + ListRow row; + std::vector cells; + for (int c = 0; c < int(titles.size()); ++c) + if (!titles[c].empty()) + cells.push_back(grid_cell(grid, r, c)); + row.path = {!named && grid.GetRowLabelSize() > 0 ? into_u8(grid.GetRowLabelValue(r)) : name >= 0 ? grid_cell(grid, r, name) : std::string()}; + row.value = joined(cells, " | "); + row.selected = grid.GetGridCursorRow() == r; + row.index = r; + out.push_back(std::move(row)); + } +} + +#ifdef SLIC3R_CAD +// The Design tab's feature tree and body lists: each row with the tips of its action icons, which +// `column` names. +void design_rows(DesignRowList& list, std::vector& out) +{ + const std::vector& rows = list.rows(); + for (std::size_t i = 0; i < rows.size(); ++i) { + ListRow row; + std::vector tips; + for (const DesignRowList::Action& action : rows[i].actions) + if (!action.icon.empty()) + tips.push_back(into_u8(action.tip)); + row.path = {into_u8(rows[i].label)}; + row.note = tips.empty() ? std::string() : "actions: " + joined(tips, " | "); + row.selected = list.selection() == int(i); + row.index = int(i); + out.push_back(std::move(row)); + } +} +#endif + +std::optional find_row(wxWindow& list, const std::vector& path, int twin) +{ + for (ListRow& row : list_rows(&list)) + if (row.path == path && row.twin == twin) + return std::move(row); + return std::nullopt; +} + +json selected_rows(wxWindow& list) +{ + json out = json::array(); + for (const ListRow& row : list_rows(&list)) + if (row.selected) + out.push_back(joined(row.path, ">")); + return out; +} + +void swallow_selection(wxDataViewEvent&) {} + +// Sets a data view's selection as a click does, and tells its owner once, for the clicked row. The +// controls report a selection they are given differently (macOS each change it makes on the way, GTK +// and the generic control none), and a click reports it once. +void select_rows(wxDataViewCtrl& ctrl, const wxDataViewItemArray& selection, const wxDataViewItem& clicked) +{ + ctrl.Bind(wxEVT_DATAVIEW_SELECTION_CHANGED, &swallow_selection); + ctrl.SetSelections(selection); + if (ctrl.IsSelected(clicked)) + ctrl.SetCurrentItem(clicked); + ctrl.Unbind(wxEVT_DATAVIEW_SELECTION_CHANGED, &swallow_selection); + wxDataViewEvent changed(wxEVT_DATAVIEW_SELECTION_CHANGED, &ctrl, clicked); + send(&ctrl, changed); +} + +json click_data_view_row(wxDataViewCtrl& ctrl, const ListRow& row, const std::string& column, const ClickOptions& o) +{ + const bool right = o.button == "right"; + wxDataViewColumn* col = data_view_column(ctrl, column); + const int mods = parse_modifiers(o.modifiers); + HeldKeys held(modifier_keys(mods)); + ctrl.EnsureVisible(row.item, col); // expands the branches above it and scrolls to it + scroll_into_view(&ctrl); + const wxRect cell = ctrl.GetItemRect(row.item, col); + if (cell.IsEmpty()) + throw ToolFailure("\"" + row.path.back() + "\" can't be scrolled into the list's view; make the window taller with set_view window_size"); + // The pointer stays on the cell for the click: the object list acts on the cell under it (Printable + // toggles printability, Editing resets the row's settings). + wxMouseState pointer; + pointer.SetPosition(ctrl.ClientToScreen(wxPoint(cell.x + cell.width / 2, cell.y + cell.height / 2))); + SyntheticInput::set_mouse(pointer); + + // A right click selects an unselected row only; Ctrl toggles a row in the selection, Shift selects + // the shown rows from the current one. + if (!right || !ctrl.IsSelected(row.item)) { + wxDataViewItemArray selection; + if (right || !ctrl.HasFlag(wxDV_MULTIPLE) || (mods & (wxMOD_CONTROL | wxMOD_SHIFT)) == 0) { + selection.Add(row.item); + } else if ((mods & wxMOD_CONTROL) != 0) { + ctrl.GetSelections(selection); + if (const int at = selection.Index(row.item); at != wxNOT_FOUND) + selection.RemoveAt(std::size_t(at)); + else + selection.Add(row.item); + } else { + const std::vector rows = list_rows(&ctrl); + const wxDataViewItem anchor = ctrl.GetCurrentItem().IsOk() ? ctrl.GetCurrentItem() : row.item; + int from = -1, to = -1; + for (int i = 0; i < int(rows.size()); ++i) { + if (rows[i].item == anchor) + from = i; + if (rows[i].item == row.item) + to = i; + } + if (from < 0) + from = to; + for (int i = std::min(from, to); i <= std::max(from, to); ++i) + if (rows[std::size_t(i)].shown) + selection.Add(rows[std::size_t(i)].item); + } + select_rows(ctrl, selection, row.item); + } +#ifdef __WXOSX__ + // The native list acts on a click in an editable icon cell by starting to edit it, which the object + // list turns into the column's action; elsewhere the owner acts on the cell under the pointer when + // the selection changes. + if (!right && !o.double_click && !column.empty() && col->GetRenderer() != nullptr && + dynamic_cast(col->GetRenderer()) != nullptr && col->GetRenderer()->GetMode() == wxDATAVIEW_CELL_EDITABLE) { + wxDataViewEvent edit(wxEVT_DATAVIEW_ITEM_EDITING_STARTED, &ctrl, col, row.item); + send(&ctrl, edit); + } +#endif + if (o.double_click && !right) { + wxDataViewEvent activated(wxEVT_DATAVIEW_ITEM_ACTIVATED, &ctrl, col, row.item); + send(&ctrl, activated); + } + if (right) { + wxDataViewEvent menu(wxEVT_DATAVIEW_ITEM_CONTEXT_MENU, &ctrl, col, row.item); + send(&ctrl, menu); + } + return {{"clicked", joined(row.path, ">")}, {"selected", selected_rows(ctrl)}}; +} + +json click_list_box_row(wxListBox& box, const ListRow& row, const ClickOptions& o) +{ + const bool right = o.button == "right"; + const int n = row.index; + const int mods = parse_modifiers(o.modifiers); + const wxString text = box.GetString(unsigned(n)); + if (!right || !box.IsSelected(n)) { + if (box.HasMultipleSelection() && !right && (mods & (wxMOD_CONTROL | wxMOD_SHIFT)) != 0) { + if (box.IsSelected(n)) + box.Deselect(n); + else + box.SetSelection(n); + } else { + if (box.HasMultipleSelection()) + box.DeselectAll(); + box.SetSelection(n); + } + command(&box, wxEVT_LISTBOX, n, text); + } + if (o.double_click && !right) + command(&box, wxEVT_LISTBOX_DCLICK, n, text); + if (right) { + // As from the keyboard: the menu is for the selection. + wxContextMenuEvent menu(wxEVT_CONTEXT_MENU, box.GetId(), wxDefaultPosition); + send(&box, menu); + } + return {{"clicked", joined(row.path, ">")}, {"selected", selected_rows(box)}}; +} + +json click_grid_row(wxGrid& grid, const ListRow& row, const std::string& column, const ClickOptions& o) +{ + if (o.button != "left" || o.double_click) + throw ToolFailure("A table row takes a single left click, which makes its cell the current one; the table is read-only here"); + const std::vector titles = grid_titles(grid); + int col = grid_name_column(titles); + if (!column.empty()) { + col = -1; + for (int c = 0; c < int(titles.size()); ++c) + if (!titles[c].empty() && lower(titles[c]) == lower(column)) + col = c; + if (col < 0) + throw ToolFailure("The table has no column \"" + column + "\"", {{"columns", list_columns(&grid)}}); + } + grid.GoToCell(row.index, std::max(col, 0)); // sends wxEVT_GRID_SELECT_CELL, as a click does + return {{"clicked", joined(row.path, ">")}, {"column", col >= 0 ? titles[std::size_t(col)] : std::string()}}; +} + +#ifdef SLIC3R_CAD +// A click at the row's centre, or at its action icon whose tip `column` gives, through the list's own +// mouse handlers. +json click_design_row(DesignRowList& list, const ListRow& row, const std::string& column, const ClickOptions& o) +{ + const int n = row.index; + if (!list.IsRowVisible(std::size_t(n))) + list.ScrollToRow(std::size_t(n)); + wxRect cell = list.GetItemRect(std::size_t(n)); + if (!column.empty()) { + const std::vector& actions = list.rows()[std::size_t(n)].actions; + std::size_t i = 0; + while (i < actions.size() && (actions[i].icon.empty() || lower(into_u8(actions[i].tip)) != lower(column))) + ++i; + if (i == actions.size()) + throw ToolFailure("\"" + row.path.back() + "\" has no action icon \"" + column + "\"", {{"actions", row.note}}); + cell = list.action_rect(n, i); + } + if (cell.IsEmpty()) + throw ToolFailure("\"" + row.path.back() + "\" can't be scrolled into the list's view"); + ClickOptions at = o; + at.at_point = true; + at.x = cell.x + cell.width / 2; + at.y = cell.y + cell.height / 2; + click_window(&list, at); + return {{"clicked", joined(row.path, ">")}}; +} +#endif + +} // namespace + +std::vector list_rows(wxWindow* list) +{ + std::vector out; + if (auto* view = dynamic_cast(list)) + data_view_rows(*view, out); + else if (auto* box = dynamic_cast(list)) + list_box_rows(*box, out); + else if (auto* drop = dynamic_cast(list)) + drop_down_rows(*drop, out); + else if (auto* grid = dynamic_cast(list)) + grid_rows(*grid, out); +#ifdef SLIC3R_CAD + else if (auto* design = dynamic_cast(list)) + design_rows(*design, out); +#endif + // Rows with the same labels are told apart by their order. + std::map, int> seen; + for (ListRow& row : out) + row.twin = seen[row.path]++; + return out; +} + +bool is_row_list(wxWindow* w) +{ +#ifdef SLIC3R_CAD + if (dynamic_cast(w) != nullptr) + return true; +#endif + return dynamic_cast(w) != nullptr || dynamic_cast(w) != nullptr || dynamic_cast(w) != nullptr || + dynamic_cast(w) != nullptr; +} + +std::vector list_columns(wxWindow* list) +{ + std::vector out; + if (auto* view = dynamic_cast(list)) { + const std::vector cols = shown_columns(*view); + for (std::size_t i = 0; i < cols.size(); ++i) + out.push_back(column_name(*view, *cols[i], i)); + } else if (auto* grid = dynamic_cast(list)) { + for (const std::string& title : grid_titles(*grid)) + if (!title.empty()) + out.push_back(title); + } + return out; +} + +std::vector> find_rows(const std::vector& roots, const std::vector& wanted) +{ + std::vector> out; + const std::string current = current_marker(); + std::function visit = [&](wxWindow* w) { + if (!w->IsShownOnScreen()) + return; + if (is_row_list(w)) + for (ListRow& row : list_rows(w)) + if (wanted.empty() || row_matches(row.path, wanted, current)) + out.emplace_back(w, std::move(row)); + for (wxWindow* child : w->GetChildren()) + if (dynamic_cast(child) == nullptr && dynamic_cast(child) == nullptr) + visit(child); + }; + for (wxWindow* root : roots) { + visit(root); + for (wxWindow* popup : popups_of(root)) + visit(popup); + } + return out; +} + +json click_row(wxWindow& list, const ListRow& row, const std::string& column, const ClickOptions& o) +{ + if (!list.IsShownOnScreen()) + throw ToolFailure("The list is no longer shown; take a new ui_snapshot"); + if (!list.IsEnabled()) + throw ToolFailure("The list is disabled"); + if (!row.enabled) + throw ToolFailure("\"" + row.path.back() + "\" is disabled"); + if (o.at_point) + throw ToolFailure("x/y don't go with a row; name its cell with column"); + if (o.button != "left" && o.button != "right") + throw ToolFailure("A row takes a left or right click"); + if (auto* view = dynamic_cast(&list)) + return click_data_view_row(*view, row, column, o); + if (auto* grid = dynamic_cast(&list)) + return click_grid_row(*grid, row, column, o); +#ifdef SLIC3R_CAD + if (auto* design = dynamic_cast(&list)) + return click_design_row(*design, row, column, o); +#endif + if (!column.empty()) + throw ToolFailure("This list has no columns; leave out column"); + if (auto* box = dynamic_cast(&list)) + return click_list_box_row(*box, row, o); + if (auto* drop = dynamic_cast(&list)) { + if (o.button != "left" || o.double_click || !o.modifiers.empty()) + throw ToolFailure("A drop-down list's row takes a plain left click, which picks it"); + if (!drop->ClickItem(row.index)) + throw ToolFailure("\"" + row.path.back() + "\" can't be picked"); + return {{"clicked", joined(row.path, ">")}}; + } + throw ToolFailure("Not a list"); +} + +json input_row(wxWindow& list, const ListRow& row, const std::string& column, const json& value) +{ + if (!list.IsShownOnScreen()) + throw ToolFailure("The list is no longer shown; take a new ui_snapshot"); + if (!list.IsEnabled()) + throw ToolFailure("The list is disabled"); + if (dynamic_cast(&list) != nullptr) + throw ToolFailure("Table cells are read-only here; edit object settings with set_settings {scope: \"object\"}"); + const std::string text = value.is_string() ? lower(value.get()) : value.dump(); + if (!value.is_boolean() && text != "true" && text != "false" && text != "1" && text != "0") + throw ToolFailure("A row takes true or false, for its checkbox"); + const bool want = value.is_boolean() ? value.get() : (text == "true" || text == "1"); + if (auto* view = dynamic_cast(&list)) { + // The checkbox cell: the column named, else the row's first. + wxDataViewModel* model = view->GetModel(); + std::vector cols = column.empty() ? shown_columns(*view) : std::vector{data_view_column(*view, column)}; + for (wxDataViewColumn* col : cols) { + wxVariant now; + model->GetValue(now, row.item, col->GetModelColumn()); + if (now.GetType() != "bool") + continue; + view->EnsureVisible(row.item, col); + // What the toggle renderer does on a click; the model's notifier tells the owner + // (wxEVT_DATAVIEW_ITEM_VALUE_CHANGED). + if (now.GetBool() != want) + model->ChangeValue(wxVariant(want), row.item, col->GetModelColumn()); + model->GetValue(now, row.item, col->GetModelColumn()); + return {{"row", joined(row.path, ">")}, {"checked", now.GetBool()}}; + } + } else if (auto* checks = dynamic_cast(&list)) { + const unsigned n = unsigned(row.index); + if (checks->IsChecked(n) != want) { + checks->Check(n, want); + command(checks, wxEVT_CHECKLISTBOX, int(n), checks->GetString(n)); + } + return {{"row", joined(row.path, ">")}, {"checked", checks->IsChecked(n)}}; + } + throw ToolFailure("This row has no checkbox; use ui_click"); +} + // ---- snapshot --------------------------------------------------------------------------------- bool UiInspector::push(UiNode node, UiTarget target, std::vector& nodes, std::size_t& omitted, const SnapshotOptions& o) @@ -931,6 +1734,21 @@ bool UiInspector::push(UiNode node, UiTarget target, std::vector& nodes, alive = [canvas] { return is_live_canvas(canvas); }; break; } + case UiTarget::Kind::Row: { + kind = 'r'; + alive = [weak = target.window, path = target.row_path, twin = target.row_twin] { + wxWindow* w = weak.get(); + return w != nullptr && find_row(*w, path, twin).has_value(); + }; + break; + } + case UiTarget::Kind::PlateIcon: { + kind = 'p'; + alive = [canvas = target.canvas, id = target.plate * kPlateIconCount + target.plate_action] { + return is_live_canvas(canvas) && plate_picking_ids(*canvas).count(id) > 0; + }; + break; + } case UiTarget::Kind::ImGuiItem: { kind = 'g'; GLCanvas3D* canvas = target.canvas; @@ -982,9 +1800,16 @@ void UiInspector::add_menus(wxMenu* menu, const std::string& path, wxWindow* fra void UiInspector::add_canvas_items(GLCanvas3D& canvas, int depth, std::vector& nodes, std::size_t& omitted, const SnapshotOptions& o) { - const std::string cname = canvas_name(&canvas); - GLToolbar& toolbar = canvas.get_main_toolbar(); - for (GLToolbarItem* item : toolbar.get_items()) { + // Plate icons and ImGui items are what the last frame drew. A canvas that changed since (a new + // project, a tab just shown) waits for its paint, which a Wayland compositor holds back until its + // frame callback, so it is drawn now and the items match it. + if (canvas.get_wxglcanvas()->IsShownOnScreen()) { + canvas.set_as_dirty(); + canvas.render(); + } + const std::string cname = canvas_name(&canvas); + bool changed = false; + for (GLToolbarItem* item : toolbar_items(canvas.get_main_toolbar(), &changed)) { if (item == nullptr || item->is_separator() || !item->is_visible()) continue; UiNode node; @@ -1002,6 +1827,8 @@ void UiInspector::add_canvas_items(GLCanvas3D& canvas, int depth, std::vectorget_name()}, {"canvas", cname}}; push(std::move(node), std::move(t), nodes, omitted, o); } + if (changed) + canvas.set_as_dirty(); GLGizmosManager& gizmos = canvas.get_gizmos_manager(); if (gizmos.is_enabled()) for (int type = 0; type < int(GLGizmosManager::Undefined); ++type) { @@ -1031,6 +1858,38 @@ void UiInspector::add_canvas_items(GLCanvas3D& canvas, int depth, std::vectorget_partplate_list(); + const std::set shown = plate_picking_ids(canvas); + const int current = plates.get_curr_plate_index(); + auto add = [&](int plate, int action) { + if (shown.count(plate * kPlateIconCount + action) == 0) + return; + UiNode node; + node.kind = "plate_icon"; + node.label = action == 0 ? plate_label(*plates.get_plate(plate)) : plate_icon_name(action); + node.name = action == 0 ? "plate" : ""; + node.note = "plate " + std::to_string(plate) + (action == 0 && plate == current ? ", current" : ""); + if (action == plate_icon_action("lock")) + node.checked = plates.is_locked(plate) ? 1 : 0; + node.depth = depth; + UiTarget t; + t.kind = UiTarget::Kind::PlateIcon; + t.window = canvas.get_wxglcanvas(); + t.canvas = &canvas; + t.name = plate_icon_name(action); + t.plate = plate; + t.plate_action = action; + t.locator = {{"plate_icon", t.name}, {"plate", plate}}; + push(std::move(node), std::move(t), nodes, omitted, o); + }; + for (int plate = 0; plate < plates.get_plate_count(); ++plate) + add(plate, 0); + for (int action = 1; action < kPlateIconCount; ++action) + add(current, action); + } if (o.include_imgui && wxGetApp().imgui() != nullptr) add_imgui_items(canvas, depth, nodes, omitted, o); } @@ -1181,7 +2040,9 @@ void UiInspector::walk(wxWindow* w, int depth, std::vector& nodes, std:: const std::string name = meaningful_name(w); std::string label = label_of(w); const bool top = dynamic_cast(w) != nullptr; + const bool popup = kind == "popup"; const bool interesting = top || (!kind.empty() && (kind != "label" || !label.empty())) || !name.empty(); + const bool list = is_row_list(w); int child_depth = depth; if (interesting) { UiNode node; @@ -1195,14 +2056,18 @@ void UiInspector::walk(wxWindow* w, int depth, std::vector& nodes, std:: node.focused = wxWindow::FindFocus() == w; node.checked = checked_of(w); node.depth = depth; - const wxPoint pos = top ? w->GetScreenPosition() : client_pos_in_tlw(w); + if (list) + if (const std::vector columns = list_columns(w); columns.size() > 1) + node.note = "columns: " + joined(columns, " | "); + const wxPoint pos = top || popup ? w->GetScreenPosition() : client_pos_in_tlw(w); const wxSize size = w->GetSize(); node.x = pos.x, node.y = pos.y, node.w = size.x, node.h = size.y; UiTarget t; t.kind = UiTarget::Kind::Window; t.window = w; - wxWindow* tlw = wxGetTopLevelParent(w); - t.locator = {{"class", node.cls}}; + wxWindow* tlw = owning_window(w); + // A web view's class differs per platform (WebKit, WebView2), so its locator names the kind. + t.locator = {{"class", kind == "webview" ? kind : node.cls}}; if (!label.empty()) t.locator["label"] = label; if (!name.empty()) @@ -1228,7 +2093,7 @@ void UiInspector::walk(wxWindow* w, int depth, std::vector& nodes, std:: add_menus(menu, label_text, w, child_depth + 1, nodes, omitted, o); } if (kind == "canvas") - for (GLCanvas3D* canvas : live_canvases()) + for (GLCanvas3D* canvas : ui_canvases()) if (canvas->get_wxglcanvas() == w) add_canvas_items(*canvas, child_depth, nodes, omitted, o); // A notebook's pages, so one can be picked by its tab. @@ -1245,16 +2110,36 @@ void UiInspector::walk(wxWindow* w, int depth, std::vector& nodes, std:: t.page = int(i); t.name = page.label; t.locator = {{"tab", page.label}}; - if (wxWindow* tlw = wxGetTopLevelParent(book); tlw != nullptr && tlw != wxGetApp().mainframe) + if (wxWindow* tlw = owning_window(book); tlw != nullptr && tlw != wxGetApp().mainframe) t.locator["within"] = label_of(tlw); push(std::move(page), std::move(t), nodes, omitted, o); } + // A list's rows; row locators find them again by their labels (locator_for()). + if (list) + for (ListRow& r : list_rows(w)) { + UiNode row; + row.kind = "row"; + row.label = r.path.back(); + row.value = r.value; + row.checked = r.checked; + row.enabled = r.enabled && w->IsEnabled(); + row.note = r.selected ? (r.note.empty() ? "selected" : r.note + ", selected") : r.note; + row.depth = child_depth + r.depth; + UiTarget t; + t.kind = UiTarget::Kind::Row; + t.window = w; + t.row_path = std::move(r.path); + t.row_twin = r.twin; + push(std::move(row), std::move(t), nodes, omitted, o); + } // Web views and canvases are listed by their own means; Orca's composite inputs are one - // control to the agent, not their inner text field and buttons. - if (kind == "webview" || kind == "canvas" || kind == "text" || kind == "spin" || kind == "combo") + // control to the agent, not their inner text field and buttons; a table's inner windows are its + // rows. + if (kind == "webview" || kind == "canvas" || kind == "text" || kind == "spin" || kind == "combo" || dynamic_cast(w) != nullptr) return; + // Popups are listed after the window they belong to (snapshot()). for (wxWindow* child : w->GetChildren()) - if (dynamic_cast(child) == nullptr) + if (dynamic_cast(child) == nullptr && dynamic_cast(child) == nullptr) walk(child, child_depth, nodes, omitted, o); } @@ -1263,22 +2148,32 @@ json UiInspector::snapshot(const SnapshotOptions& o) std::vector nodes; std::size_t omitted = 0; std::vector roots; + // A window, then the popups that opened from it, before any window above it. + auto with_popups = [&roots](wxWindow* top) { + roots.push_back(top); + for (wxWindow* popup : popups_of(top)) + roots.push_back(popup); + }; if (o.root == "dialog") { if (wxDialog* d = m_service.modals().top()) - roots.push_back(d); + with_popups(d); else throw ToolFailure("No modal dialog is open"); } else if (o.root == "main") { if (wxGetApp().mainframe == nullptr) throw ToolFailure("The main window is not up yet"); - roots.push_back(wxGetApp().mainframe); + with_popups(wxGetApp().mainframe); + } else if (o.root == "popup") { + for (wxTopLevelWindow* tlw : top_level_windows(m_service)) + for (wxWindow* popup : popups_of(tlw)) + roots.push_back(popup); } else if (o.root == "all" || o.root.empty()) { for (wxTopLevelWindow* tlw : top_level_windows(m_service)) - roots.push_back(tlw); + with_popups(tlw); } else { const UiTarget t = resolve(json(o.root)); if (t.kind != UiTarget::Kind::Window || t.window.get() == nullptr) - throw ToolFailure("root must be all, main, dialog or the ref of a window"); + throw ToolFailure("root must be all, main, dialog, popup or the ref of a window"); roots.push_back(t.window.get()); } for (wxWindow* root : roots) @@ -1331,6 +2226,29 @@ UiTarget UiInspector::resolve(const json& target) t.menu_path = path; return t; } + if (target.contains("plate_icon")) { + Plater* plater = wxGetApp().plater(); + t.kind = UiTarget::Kind::PlateIcon; + t.canvas = plater != nullptr ? plater->get_view3D_canvas3D() : nullptr; + if (t.canvas == nullptr) + throw ToolFailure("No Prepare view"); + t.window = t.canvas->get_wxglcanvas(); + t.name = target["plate_icon"].is_string() ? target["plate_icon"].get() : std::string(); + t.plate_action = plate_icon_action(t.name); + if (t.plate_action < 0) { + json names = json::array(); + for (int a = 0; a < kPlateIconCount; ++a) + names.push_back(plate_icon_name(a)); + throw ToolFailure("No plate icon \"" + t.name + "\"", {{"plate_icons", names}}); + } + if (!target.contains("plate") || !target["plate"].is_number_integer()) + throw ToolFailure("A plate_icon locator needs plate, the 0-based plate index"); + t.plate = target["plate"].get(); + const int plates = plater->get_partplate_list().get_plate_count(); + if (t.plate < 0 || t.plate >= plates) + throw ToolFailure(no_such_plate(t.plate, plates)); + return t; + } const bool imgui = target.contains("imgui") || target.contains("imgui_name"); if (target.contains("gltoolbar") || target.contains("gizmo") || imgui) { t.canvas = canvas_by_name(target.value("canvas", imgui ? "" : "3d")); @@ -1375,6 +2293,33 @@ UiTarget UiInspector::resolve(const json& target) } const int index = target.value("index", -1); + if (target.contains("row")) { + const auto matches = match_rows(target); + if (matches.empty()) { + // The rows a person would look at instead: those whose label holds the one asked for. + const std::string wanted = lower(row_segments(target["row"]).back()); + json similar = json::array(), any = json::array(); + for (const auto& [list, row] : match_rows(json{{"row", json::array()}, {"within", target.value("within", "")}})) { + const std::string path = joined(row.path, ">"); + if (!row.path.back().empty() && similar.size() < 30 && lower(row.path.back()).find(wanted) != std::string::npos) + similar.push_back(path); + if (any.size() < 30) + any.push_back(path); + } + throw ToolFailure("No shown list has a row " + target["row"].dump() + "; take a ui_snapshot", {{"rows", similar.empty() ? any : similar}}); + } + if (matches.size() > 1 && index < 0) + throw ToolFailure(std::to_string(matches.size()) + " rows match " + target.dump() + "; add \"index\" (0-based) or use a ref"); + if (index >= int(matches.size())) + throw ToolFailure("index " + std::to_string(index) + " is past the " + std::to_string(matches.size()) + " matches"); + const auto& [list, row] = matches[index < 0 ? 0 : std::size_t(index)]; + t.kind = UiTarget::Kind::Row; + t.window = list; + t.row_path = row.path; + t.row_twin = row.twin; + t.column = target.value("column", ""); + return t; + } if (target.contains("tab")) { const auto matches = match_tabs(target); if (matches.empty()) @@ -1393,7 +2338,7 @@ UiTarget UiInspector::resolve(const json& target) // A wx window by option key, class, label or name, optionally within a titled top-level window. if (!target.contains("option") && !target.contains("class") && !target.contains("label") && !target.contains("name")) - throw ToolFailure("A locator needs option, label, name or class (or menu, tab, gltoolbar, gizmo, imgui, imgui_name)"); + throw ToolFailure("A locator needs option, label, name or class (or menu, tab, row, gltoolbar, gizmo, imgui, imgui_name)"); const std::vector matches = match_windows(target); if (matches.empty()) throw ToolFailure("Nothing matches " + target.dump() + "; take a ui_snapshot"); @@ -1417,7 +2362,8 @@ std::vector UiInspector::match_windows(const json& locator) std::function visit = [&](wxWindow* w) { if (!w->IsShownOnScreen()) return; - if ((option.empty() || option_key_of(w) == option) && (cls.empty() || short_class(w) == cls) && + if ((option.empty() || option_key_of(w) == option) && + (cls.empty() || short_class(w) == cls || (cls == "webview" && dynamic_cast(w) != nullptr)) && (label.empty() || label_of(w) == label || value_of(w) == label) && (name.empty() || into_u8(w->GetName()) == name)) { matches.push_back(w); if (!option.empty()) @@ -1451,7 +2397,7 @@ std::vector> UiInspector::mat const bool by_label = locator.contains("imgui"), by_name = locator.contains("imgui_name"); const std::string label = locator.value("imgui", ""), name = locator.value("imgui_name", ""); const std::string window = locator.value("window", ""); - std::vector canvases = live_canvases(); + std::vector canvases = ui_canvases(); if (locator.contains("canvas")) { GLCanvas3D* named = canvas_by_name(locator["canvas"].get()); canvases = named != nullptr ? std::vector{named} : std::vector{}; @@ -1471,6 +2417,19 @@ std::vector> UiInspector::mat return out; } +// {row: } finds rows of the shown lists by the last labels of their paths; an empty array finds +// every row. +std::vector> UiInspector::match_rows(const json& locator) +{ + const std::string within = locator.value("within", ""); + std::vector roots; + for (wxTopLevelWindow* tlw : top_level_windows(m_service)) + if (within.empty() || label_of(tlw) == within) + roots.push_back(tlw); + const json& row = locator["row"]; + return find_rows(roots, row.is_array() && row.empty() ? std::vector() : row_segments(row)); +} + std::vector> UiInspector::match_tabs(const json& locator) { const std::string text = locator["tab"].get(); @@ -1496,7 +2455,8 @@ std::vector> UiInspector::match_tabs(const json& json UiInspector::locator_for(const UiTarget& t) { json loc = t.locator; - loc.erase("index"); + if (loc.is_object()) // a row's is built below + loc.erase("index"); int position = -1, count = 0; if (t.kind == UiTarget::Kind::ImGuiItem && (loc.contains("imgui") || loc.contains("imgui_name"))) { auto find = [&] { @@ -1514,6 +2474,18 @@ json UiInspector::locator_for(const UiTarget& t) loc["imgui_name"] = t.imgui_name; find(); } + } else if (t.kind == UiTarget::Kind::Row) { + // The row's whole path, which names it after other rows come and go, with its cell and window. + loc = {{"row", row_locator(t.row_path)}}; + if (!t.column.empty()) + loc["column"] = t.column; + if (wxWindow* top = owning_window(t.window.get()); top != nullptr && top != wxGetApp().mainframe) + loc["within"] = label_of(top); + const auto matches = match_rows(loc); + count = int(matches.size()); + for (int i = 0, twin = 0; i < count; ++i) + if (matches[i].first == t.window.get() && matches[i].second.path == t.row_path && twin++ == t.row_twin) + position = i; } else if (t.kind == UiTarget::Kind::Window && t.page >= 0 && loc.contains("tab")) { const auto matches = match_tabs(loc); count = int(matches.size()); @@ -1583,17 +2555,26 @@ GLCanvas3D* UiInspector::canvas_of(const UiTarget* target) const if (target != nullptr && target->canvas != nullptr && is_live_canvas(target->canvas)) return target->canvas; if (target != nullptr && target->window.get() != nullptr) - for (GLCanvas3D* c : live_canvases()) + for (GLCanvas3D* c : ui_canvases()) if (c->get_wxglcanvas() == target->window.get()) return c; - if (target == nullptr) - if (Plater* plater = wxGetApp().plater()) - return plater->get_current_canvas3D(); - return nullptr; + return target == nullptr ? shown_canvas() : nullptr; } // ---- actions ---------------------------------------------------------------------------------- +bool UiInspector::place_row(const UiTarget& t) +{ + auto* ctrl = t.kind == UiTarget::Kind::Row ? dynamic_cast(t.window.get()) : nullptr; + const std::optional row = ctrl != nullptr ? find_row(*ctrl, t.row_path, t.row_twin) : std::nullopt; + if (!row) + return true; // nothing to place; the click says why + wxDataViewColumn* col = data_view_column(*ctrl, t.column); + ctrl->EnsureVisible(row->item, col); + scroll_into_view(ctrl); + return !ctrl->GetItemRect(row->item, col).IsEmpty(); +} + json UiInspector::click(const UiTarget& t, const ClickOptions& o) { switch (t.kind) { @@ -1617,7 +2598,8 @@ json UiInspector::click(const UiTarget& t, const ClickOptions& o) return {{"clicked", t.menu_path}}; } case UiTarget::Kind::ToolbarItem: { - GLToolbar& tb = t.canvas->get_main_toolbar(); + GLToolbar& tb = t.canvas->get_main_toolbar(); + toolbar_items(tb); GLToolbarItem* item = tb.get_item(t.name); if (item == nullptr) throw ToolFailure("The toolbar item is gone"); @@ -1673,9 +2655,71 @@ json UiInspector::click(const UiTarget& t, const ClickOptions& o) UiTarget shown = t; reveal(shown); const wxPoint pos = imgui_to_canvas(*shown.canvas, shown.x + shown.w / 2.f, shown.y + shown.h / 2.f); + if (const std::string cover = covered_by(*shown.canvas, pos, shown.imgui_window); !cover.empty()) + throw ToolFailure("\"" + shown.imgui_label + "\" is under " + cover + + ", which would take the click; close it, or enlarge the window with set_view window_size"); canvas_click(*shown.canvas, pos, o); return {{"clicked", shown.imgui_label}, {"at", {pos.x, pos.y}}}; } + case UiTarget::Kind::Row: { + wxWindow* list = t.window.get(); + const std::optional row = list != nullptr ? find_row(*list, t.row_path, t.row_twin) : std::nullopt; + if (!row) + throw ToolFailure("The row is gone; take a new ui_snapshot"); + return click_row(*list, *row, t.column, o); + } + case UiTarget::Kind::PlateIcon: { + // What the canvas does for a click on the icon's picking id, refused where the canvas takes + // no plate clicks. + GLCanvas3D& canvas = *t.canvas; + if (!is_live_canvas(t.canvas) || !canvas.get_wxglcanvas()->IsShownOnScreen()) + throw ToolFailure("Plate icons are on the Prepare view; set_view {\"tab\": \"prepare\"} first"); + if (o.button == "middle" || o.double_click || o.at_point) + throw ToolFailure("A plate icon takes a single left or right click"); + if (canvas.is_layers_editing_enabled()) + throw ToolFailure("Plate icons take no clicks while variable layer height is being edited; close it with " + "ui_click {\"gltoolbar\": \"layersediting\"} first"); + if (const auto open = canvas.get_gizmos_manager().get_current_type(); open != GLGizmosManager::Undefined) + throw ToolFailure("Close the " + gizmo_name(open) + " gizmo first: plate icons take no clicks while it is open"); + Plater& plater = *wxGetApp().plater(); + PartPlateList& plates = plater.get_partplate_list(); + if (t.plate >= plates.get_plate_count()) + throw ToolFailure(no_such_plate(t.plate, plates.get_plate_count())); + const int id = t.plate * kPlateIconCount + t.plate_action; + if (plate_picking_ids(canvas).count(id) == 0) + throw ToolFailure("Plate " + std::to_string(t.plate) + " shows no " + t.name + " icon"); + const bool right = o.button == "right"; + const bool arrange = t.plate_action == plate_icon_action("arrange"); + const bool job = arrange || t.plate_action == plate_icon_action("orient"); + Worker& worker = plater.get_ui_job_worker(); + const bool idle = worker.is_idle(); + // The arrange icon does nothing while this flag is set, which an arrange that was cancelled + // or failed leaves behind. + const bool arrange_stuck = arrange && plater.m_arrange_running.load(); + // A right click's plate menu is listed or run by the caller; where it would open matters only + // to a menu that is shown. + const wxSize size = canvas.get_wxglcanvas()->GetClientSize(); + canvas.click_plate(id, right, Vec2d(size.x / 2., size.y / 2.)); + canvas.set_as_dirty(); + json out{{"clicked", t.name}, {"plate", t.plate}}; + if (right) + return out; + if (t.plate_action == 0 || t.plate_action == plate_icon_action("move_to_front") || t.plate_action == plate_icon_action("delete")) + out["current"] = plates.get_curr_plate_index(); + if (t.plate_action == plate_icon_action("delete")) + out["plates"] = plates.get_plate_count(); + if (t.plate_action == plate_icon_action("lock")) + out["locked"] = plates.is_locked(t.plate); + if (t.plate_action == plate_icon_action("imex_mode")) + out["imex_mode"] = plates.get_plate(t.plate)->get_imex_mode(); + if (job) { + out["started"] = idle && !worker.is_idle(); + if (!out["started"].get() && arrange_stuck) + out["note"] = "The arrange icon does nothing after an arrange was cancelled or failed, until another arrange " + "finishes; arrange with the arrange tool or run_action obj_arrange"; + } + return out; + } case UiTarget::Kind::Window: break; } @@ -1692,7 +2736,13 @@ json UiInspector::click(const UiTarget& t, const ClickOptions& o) book->SetSelection(size_t(t.page)); // sends the page-changing and page-changed events return {{"clicked", t.name}, {"page", t.page}}; } - if (o.at_point || dynamic_cast(w) != nullptr) { + if (o.at_point && dynamic_cast(w) == nullptr) { + if (is_native_control(w)) + throw ToolFailure("x/y clicks a point of a custom-drawn widget; this is a native control, so use ui_click without x/y"); + click_window(w, o); + return {{"clicked", label_of(w)}, {"at", {o.x, o.y}}}; + } + if (dynamic_cast(w) != nullptr) { GLCanvas3D* canvas = canvas_of(&t); if (canvas == nullptr) throw ToolFailure("Not a 3D canvas"); @@ -1737,8 +2787,15 @@ json UiInspector::input(const UiTarget& t, const json& value, bool submit) { if (t.kind == UiTarget::Kind::ImGuiItem) return imgui_input(t, value, submit); + if (t.kind == UiTarget::Kind::Row) { + wxWindow* list = t.window.get(); + const std::optional row = list != nullptr ? find_row(*list, t.row_path, t.row_twin) : std::nullopt; + if (!row) + throw ToolFailure("The row is gone; take a new ui_snapshot"); + return input_row(*list, *row, t.column, value); + } if (t.kind != UiTarget::Kind::Window || t.window.get() == nullptr) - throw ToolFailure("ui_input works on controls and ImGui fields"); + throw ToolFailure("ui_input works on controls, list rows and ImGui fields"); wxWindow* w = t.window.get(); if (!w->IsEnabled()) throw ToolFailure("The control is disabled"); @@ -1942,7 +2999,7 @@ wxWindow* UiInspector::key_target(const UiTarget* t) const return t->window.get(); wxWindow* focus = wxWindow::FindFocus(); if (wxDialog* top = m_service.modals().top()) - return focus != nullptr && wxGetTopLevelParent(focus) == top ? focus : top; + return focus != nullptr && owning_window(focus) == top ? focus : top; if (focus != nullptr) return focus; GLCanvas3D* canvas = canvas_of(nullptr); @@ -1956,11 +3013,12 @@ json UiInspector::key(const UiTarget* t, const std::string& chord_text, const st throw ToolFailure("No window to send keys to"); if (t != nullptr) scroll_into_view(target); + // A 3D view draws a frame after each key, so ImGui fields take what was typed. GLCanvas3D* canvas = nullptr; - for (GLCanvas3D* c : live_canvases()) - if (c->get_wxglcanvas() == target) - canvas = c; - wxWindow* tlw = wxGetTopLevelParent(target); + if (dynamic_cast(target) != nullptr) + for (GLCanvas3D* c : ui_canvases()) + if (c->get_wxglcanvas() == target) + canvas = c; auto deliver = [&](int key_code, int modifiers, wxChar uni) { auto make = [&](wxEventType type) { @@ -1975,9 +3033,13 @@ json UiInspector::key(const UiTarget* t, const std::string& chord_text, const st codes.push_back(key_code); HeldKeys held(codes); bool handled = false; - if (tlw != nullptr && key_code != 0) { + if (key_code != 0) { + // As a real key press: CHAR_HOOK goes to the target first and travels up through its + // parents (wxKeyEvent propagates it) to the top-level window, or stops at a dialog, so the + // hooks of the panels holding the target see it. A hook that allows the next event lets + // KEY_DOWN through, as on every port. wxKeyEvent hook = make(wxEVT_CHAR_HOOK); - handled = tlw->GetEventHandler()->ProcessEvent(hook); + handled = target->GetEventHandler()->ProcessEvent(hook) && !hook.IsNextEventAllowed(); } if (!handled && key_code != 0) { wxKeyEvent down = make(wxEVT_KEY_DOWN); @@ -2035,9 +3097,12 @@ json UiInspector::mouse(GLCanvas3D& canvas, const json& g, const std::string& ow const std::string check = g.value("check", "surface"); const double tolerance = g.value("tolerance", 0.); json pixels = json::array(); + const bool design = canvas_name(&canvas) == std::string("design"); auto pixel_of = [&](const json& p) { if (p.is_array() && p.size() != 2) throw ToolFailure("A pixel is [x, y]"); + if (!p.is_array() && design) + throw ToolFailure("Points of the model name Prepare objects; on the Design view give x/y (cad_call query_topology gives faces)"); const wxPoint px = p.is_array() ? wxPoint(p[0].get(), p[1].get()) : target_pixel(canvas, p, check, tolerance); pixels.push_back({px.x, px.y}); return px; @@ -2056,6 +3121,15 @@ json UiInspector::mouse(GLCanvas3D& canvas, const json& g, const std::string& ow if (stops.empty()) throw ToolFailure("drag needs to or path"); } + // A gesture that starts at a model point under an ImGui window or a notification would go to that + // instead, so it is refused. A press held from before goes on to the scene wherever it moves, and + // a pixel given as x and y is the client's to aim, ImGui panels included. + const bool continues_held = m_held && m_held->canvas == &canvas && (action == "move" || action == "up"); + if (!by_pixel && !continues_held) + if (const std::string cover = covered_by(canvas, from); !cover.empty()) + throw ToolFailure("The model point at pixel (" + std::to_string(from.x) + ", " + std::to_string(from.y) + ") is under " + cover + + ", which would take the " + (action == "move" ? "pointer" : action == "wheel" ? "wheel" : "click") + + "; turn or zoom the camera with set_view, or close it"); json out{{"action", action}, {"canvas", canvas_name(&canvas)}, {"pixels", pixels}}; // A press an earlier `down` left held: a `move` drags with it and an `up` releases it; any other @@ -2130,6 +3204,166 @@ void UiInspector::release_held(const std::string* owner) m.event(h.left ? wxEVT_LEFT_UP : h.right ? wxEVT_RIGHT_UP : wxEVT_MIDDLE_UP, h.pos, false, false, false); } +// ---- popup and context menus ------------------------------------------------------------------ + +void UiInspector::capture_menus(bool on) +{ + if (on == m_capturing_menus) + return; + m_capturing_menus = on; + SyntheticInput::set_menu_capture(on ? std::function([this](wxMenu& menu, wxWindow& owner) { return on_menu(menu, owner); }) : + nullptr); + if (wxTheApp == nullptr) + return; + if (on) + wxTheApp->Bind(wxEVT_IDLE, &UiInspector::on_idle, this); + else + wxTheApp->Unbind(wxEVT_IDLE, &UiInspector::on_idle, this); +} + +void UiInspector::ui_activity(const std::string& tool, bool running) +{ + if (running) { + wxEventLoopBase* const loop = wxEventLoopBase::GetActive(); + // The new window covers what an ended one in this loop still waited for. + m_menu_windows.erase(std::remove_if(m_menu_windows.begin(), m_menu_windows.end(), + [loop](const MenuWindow& w) { return !w.running && w.loop == loop; }), + m_menu_windows.end()); + m_menu_windows.push_back({loop, tool, true, {}}); + return; + } + // Closures end in the reverse order they start, so the newest one running is ending. + for (auto it = m_menu_windows.rbegin(); it != m_menu_windows.rend(); ++it) + if (it->running) { + it->running = false; + it->ended = std::chrono::steady_clock::now(); + return; + } +} + +void UiInspector::on_idle(wxIdleEvent& event) +{ + event.Skip(); + // Idle comes once the queue is drained, so the events and CallAfter()s a call queued, and those + // they queued, have run. Past kMenuWindowGrace the window is closed anyway (on_menu() ignores it + // even before an idle comes), so that a person's menus show again while something keeps queuing + // events. + const bool queued = wxTheApp != nullptr && wxTheApp->HasPendingEvents(); + const auto now = std::chrono::steady_clock::now(); + m_menu_windows.erase(std::remove_if(m_menu_windows.begin(), m_menu_windows.end(), + [&](const MenuWindow& w) { return !w.running && (!queued || now - w.ended > kMenuWindowGrace); }), + m_menu_windows.end()); +} + +int UiInspector::arm_menu(const std::string& path) +{ + MenuCapture c; + c.token = ++m_menu_tokens; + c.path = path; + c.loop = wxEventLoopBase::GetActive(); + m_menu_captures.push_back(std::move(c)); + return m_menu_tokens; +} + +UiInspector::MenuCapture* UiInspector::menu_capture(int token) +{ + const auto it = std::find_if(m_menu_captures.begin(), m_menu_captures.end(), [token](const MenuCapture& c) { return c.token == token; }); + return it == m_menu_captures.end() ? nullptr : &*it; +} + +json UiInspector::disarm_menu(int token) +{ + MenuCapture* found = menu_capture(token); + if (found == nullptr) + return json::object(); + const MenuCapture c = std::move(*found); + drop_menu(token); + if (!c.error.empty()) + throw ToolFailure(c.error, c.details); + if (!c.fired) { + if (!c.path.empty()) + throw ToolFailure("The input opened no menu, so \"" + c.path + + "\" was not run. A right click shows none on empty space while objects are selected, in the " + "Preview, or while a gizmo is open."); + return json::object(); + } + json out = c.result; + if (c.closed > 0) + out["menus_closed"] = c.closed; + return out; +} + +void UiInspector::drop_menu(int token) +{ + m_menu_captures.erase(std::remove_if(m_menu_captures.begin(), m_menu_captures.end(), [token](const MenuCapture& c) { return c.token == token; }), + m_menu_captures.end()); +} + +json UiInspector::closed_menus() const +{ + json out = json::array(); + const auto now = std::chrono::steady_clock::now(); + for (const ClosedMenu& m : m_closed_menus) { + json entry{{"tool", m.tool}, {"ago_s", std::chrono::duration_cast(now - m.at).count()}}; + entry.update(m.listing); + out.push_back(std::move(entry)); + } + return out; +} + +bool UiInspector::on_menu(wxMenu& menu, wxWindow& owner) +{ + wxEventLoopBase* const loop = wxEventLoopBase::GetActive(); + const auto now = std::chrono::steady_clock::now(); + const auto window = std::find_if(m_menu_windows.rbegin(), m_menu_windows.rend(), [&](const MenuWindow& w) { + return w.loop == loop && (w.running || now - w.ended <= kMenuWindowGrace); + }); + if (window == m_menu_windows.rend()) + return false; // no call is acting in this loop: a person's menu + const std::string tool = window->tool; + const auto capture = std::find_if(m_menu_captures.rbegin(), m_menu_captures.rend(), [loop](const MenuCapture& c) { return c.loop == loop; }); + + // What wxWindowBase::PopupMenu() does before it shows a menu: the menu's wxEVT_UPDATE_UI handlers, + // which find them through the invoking window, set each item's state as a person would see it. + wxMenuInvokingWindowSetter invoker(menu, &owner); + menu.UpdateUI(); + const std::vector entries = menu_entries(menu); + if (capture == m_menu_captures.rend() || capture->fired) { + if (capture != m_menu_captures.rend()) + ++capture->closed; + m_closed_menus.push_back({tool, std::chrono::steady_clock::now(), menu_listing(entries)}); + if (m_closed_menus.size() > 3) + m_closed_menus.pop_front(); + return true; + } + capture->fired = true; + capture->result = {{"popup_menu", menu_listing(entries)}}; + if (capture->path.empty()) + return true; + const MenuEntry* entry = find_menu_entry(entries, capture->path, current_marker(), capture->error, capture->details); + if (entry == nullptr) + return true; + capture->result = {{"ran", entry->path}}; + const int token = capture->token, id = entry->id; + const std::string ran = entry->path; + // As a pick from a shown menu: a check item toggles and a radio item is checked before the event. + wxMenu* holder = nullptr; + wxMenuItem* item = menu.FindItem(id, &holder); + int checked = -1; + if (item->IsCheckable()) { + item->Check(item->GetKind() == wxITEM_RADIO || !item->IsChecked()); + checked = item->IsChecked() ? 1 : 0; + } + // The command may open a dialog whose loop runs this call's later closures, which end the + // capture, so it is looked up again afterwards instead of being held. + if (!holder->SendEvent(id, checked)) + if (MenuCapture* c = menu_capture(token)) { + c->result = json(); + c->error = "Nothing handled \"" + ran + "\""; + } + return true; +} + std::vector imgui_display_labels(const std::vector& items, const std::vector& texts) { @@ -2213,4 +3447,76 @@ bool imgui_value_matches(const std::string& shown, const json& wanted) return std::abs(got - want) <= 0.5 * std::pow(10., -decimals) + 1e-9; } +ImGuiWindow* imgui_window_at(const ImVec2& pos) +{ + // ImGui's own search (FindHoveredWindow()), run for a position the mouse is not at yet. + ImGuiContext* g = ImGui::GetCurrentContext(); + if (g == nullptr) + return nullptr; + const ImVec2 padding = g->Style.TouchExtraPadding; + const ImVec2 resize_padding = g->IO.ConfigWindowsResizeFromEdges ? g->WindowsHoverPadding : padding; + for (int i = g->Windows.Size - 1; i >= 0; --i) { + ImGuiWindow* w = g->Windows[i]; + if (!w->Active || w->Hidden || (w->Flags & ImGuiWindowFlags_NoMouseInputs) != 0) + continue; + const bool fixed = (w->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize)) != 0; + ImRect bb(w->OuterRectClipped); + bb.Expand(fixed ? padding : resize_padding); + if (!bb.Contains(pos)) + continue; + if (w->HitTestHoleSize.x != 0) { + const ImVec2 hole(w->Pos.x + float(w->HitTestHoleOffset.x), w->Pos.y + float(w->HitTestHoleOffset.y)); + if (ImRect(hole, ImVec2(hole.x + float(w->HitTestHoleSize.x), hole.y + float(w->HitTestHoleSize.y))).Contains(pos)) + continue; + } + return w; + } + return nullptr; +} + +std::string imgui_window_description(const std::string& window, const std::vector& texts) +{ + // NotificationManager names its windows "!!Ntfctn"; their text tells which one it is. + if (window.rfind("!!Ntfctn", 0) == 0) { + for (const ImGuiWrapper::RecordedText& t : texts) { + if (t.text.empty() || (t.window != window && t.window.rfind(window + "/", 0) != 0)) + continue; + std::string text = t.text.substr(0, t.text.find('\n')); + if (text.size() > 60) { + std::size_t cut = 57; // not inside a UTF-8 sequence + while (cut > 0 && (static_cast(text[cut]) & 0xC0) == 0x80) + --cut; + text = text.substr(0, cut) + "..."; + } + return "the notification \"" + text + "\""; + } + return "a notification"; + } + const std::string label = imgui_window_label(window); + return label.empty() ? std::string("an ImGui window") : "the \"" + label + "\" window"; +} + +std::vector surface_meshes(const std::vector& volumes, + const GLVolume* target, + const std::function& own) +{ + std::vector meshes; + for (const GLVolume* v : volumes) { + if (v->mesh_raycaster == nullptr || !v->visible || (v->is_modifier && v != target) || (!v->is_active && !own(v))) + continue; + meshes.push_back({&v->mesh_raycaster->get_aabb_mesh(), v->world_matrix(), v == target, own(v), + "object " + std::to_string(v->object_idx()) + " instance " + std::to_string(v->instance_idx()) + " part " + + std::to_string(v->volume_idx())}); + } + return meshes; +} + +const std::vector& toolbar_items(GLToolbar& toolbar, bool* changed) +{ + const bool any = toolbar.update_items_state(); + if (changed != nullptr) + *changed = any; + return toolbar.get_items(); +} + }}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/UiInspector.hpp b/src/slic3r/GUI/Mcp/UiInspector.hpp index 679a8ef587..b603e91bd2 100644 --- a/src/slic3r/GUI/Mcp/UiInspector.hpp +++ b/src/slic3r/GUI/Mcp/UiInspector.hpp @@ -1,27 +1,42 @@ #pragma once +#include "CanvasTarget.hpp" #include "UiRefs.hpp" #include "slic3r/GUI/ImGuiWrapper.hpp" +#include #include +#include #include #include #include +#include #include +#include +#include #include #include #include #include class wxBookCtrlBase; +class wxEventLoopBase; +class wxIdleEvent; class wxMenu; class wxTopLevelWindow; +struct ImGuiWindow; -namespace Slic3r { namespace GUI { +namespace Slic3r { + +class GLVolume; + +namespace GUI { class GLCanvas3D; +class GLToolbar; +class GLToolbarItem; namespace Mcp { @@ -30,7 +45,7 @@ class McpService; // What a ref or locator points at. struct UiTarget { - enum class Kind { Window, MenuItem, ToolbarItem, Gizmo, ImGuiItem }; + enum class Kind { Window, MenuItem, ToolbarItem, Gizmo, ImGuiItem, Row, PlateIcon }; Kind kind = Kind::Window; wxWeakRef window; // Window: the window; others: the frame or GL canvas window GLCanvas3D* canvas = nullptr; @@ -44,12 +59,35 @@ struct UiTarget std::string imgui_name; // see imgui_item_name() int imgui_twins = 0; // items with its name in its window when found (see imgui_find_item()) float x = 0.f, y = 0.f, w = 0.f, h = 0.f; // ImGuiItem rectangle in ImGui coordinates + // Row of the list `window`, by its labels from the top and how many earlier rows of the list have + // the same labels; found again for each use, since lists rebuild their rows. `column` names the + // cell to act on, empty for the row's first. + std::vector row_path; + int row_twin = 0; + std::string column; + // PlateIcon of the Prepare view's `canvas`: the plate and the icon's picking action (plate_icon_action()). + int plate = -1, plate_action = -1; nlohmann::json locator; }; +// A row of a list, tree, table or drop-down list, as ui_snapshot lists it and row locators find it. +struct ListRow +{ + std::vector path; // labels from the top: the row's own label last + std::string value; // its other cells' text, joined with " | " + std::string note; // what the row stands for (object list rows, by model indices) + int checked = -1; // its checkbox cell: 0/1; -1 for none + bool enabled = true, selected = false; + bool shown = true; // every tree branch above it is expanded + int depth = 0; // nesting below the list + int twin = 0; // earlier rows of the list with the same path + wxDataViewItem item; // a data view's row + int index = -1; // the position of a row of any other list +}; + struct SnapshotOptions { - std::string root = "all"; // all | main | dialog | + std::string root = "all"; // all | main | dialog | popup | int max_nodes = 400; bool include_imgui = true; bool include_menus = true; @@ -62,7 +100,7 @@ struct ClickOptions std::string button = "left"; // left | right | middle bool double_click = false; std::vector modifiers; // ctrl, shift, alt, cmd - // Canvas coordinates (logical pixels) when clicking a point of a 3D canvas. + // Logical pixels from the target's top left: a point of a 3D canvas or of a custom-drawn widget. bool at_point = false; int x = 0, y = 0; }; @@ -75,6 +113,9 @@ class UiInspector { public: explicit UiInspector(McpService& service) : m_service(service) {} + ~UiInspector() { capture_menus(false); } + UiInspector(const UiInspector&) = delete; + UiInspector& operator=(const UiInspector&) = delete; // {tree, nodes, omitted} nlohmann::json snapshot(const SnapshotOptions& options); @@ -85,13 +126,16 @@ public: nlohmann::json locator_for(const UiTarget& target); nlohmann::json click(const UiTarget& target, const ClickOptions& options); + // Scrolls a data view row to view and says whether it has its place there yet: GTK lays a list's + // rows out a frame after they change. Any other target has its place. + bool place_row(const UiTarget& target); nlohmann::json input(const UiTarget& target, const nlohmann::json& value, bool submit); nlohmann::json key(const UiTarget* target, const std::string& chord, const std::string& text); // Where keys without a target go: the focused window inside the topmost modal dialog or that - // dialog itself while one is open, else the focused window, else the current 3D canvas. + // dialog itself while one is open, else the focused window, else the 3D view shown. wxWindow* key_target(const UiTarget* target) const; // Mouse gestures on a 3D canvas: move, down, up, click, drag, wheel, at canvas pixels or at - // points of the model. `owner` started the call: "" for a client, else the job of the script + // points of the model (not on the Design view, whose model is not Prepare's). `owner` started the call: "" for a client, else the job of the script // running it, which a held press belongs to (see release_held()). It throws before the first // event when a point does not resolve; the caller ends a press held from before then. nlohmann::json mouse(GLCanvas3D& canvas, const nlohmann::json& gesture, const std::string& owner); @@ -101,9 +145,36 @@ public: // Scrolls a widget into view, as clicks and typing do before they act. An ImGui item outside // the visible part of its panel is scrolled into it, and the target's rectangle updated. void reveal(UiTarget& target); - // The 3D canvas a target is in (or the current one when `target` is null). + // The 3D canvas a target is in (or the one shown when `target` is null). GLCanvas3D* canvas_of(const UiTarget* target) const; + // Popup and context menus while MCP acts on the UI. A menu that opens through popup_menu() is + // taken instead of shown, since a native menu loop would hold the UI thread until a person + // closed it. A call's window for this runs from the start of each of its UI closures until the + // first idle event with nothing queued after the closure ends, so menus that its queued events + // open are taken too; between calls a person's menu shows. Only menus of the event loop a + // closure ran in are taken: a person's right click in a dialog that a call opened shows its menu. + // An input call arms a capture (arm_menu()), which the first menu it opens goes to: listed, or + // the item it names run. Any other menu is closed unseen and kept for closed_menus(). + + // Installs the capture in SyntheticInput, or removes it. + void capture_menus(bool on); + // UiInvoker's activity hook: a closure of `tool` starts or ends. + void ui_activity(const std::string& tool, bool running); + // Arms a capture in the active event loop, for the item `path` names ("Add Modifier>Cylinder"), + // or for a listing when it is empty. Returns the token for disarm_menu(). + int arm_menu(const std::string& path); + // Ends a capture: {popup_menu: listing} for a menu it listed, {ran: path} for the item it ran, + // either with menus_closed when more menus opened after it; {} when no menu opened. Throws + // ToolFailure when no menu opened for a `path`, or the menu had no item it could run. + nlohmann::json disarm_menu(int token); + // Ends a capture without reading it, when the input failed. + void drop_menu(int token); + // The last menus closed unseen, oldest first: {tool, ago_s, items, disabled?, checked?}. + nlohmann::json closed_menus() const; + // SyntheticInput's capture: true when it took `menu`, which `owner` was about to show. + bool on_menu(wxMenu& menu, wxWindow& owner); + private: void walk(wxWindow* window, int depth, std::vector& nodes, std::size_t& omitted, const SnapshotOptions& options); void add_menus(wxMenu* menu, const std::string& path, wxWindow* frame, int depth, std::vector& nodes, std::size_t& omitted, @@ -113,6 +184,7 @@ private: // What a locator finds, in snapshot order; resolve() and locator_for() share them. std::vector match_windows(const nlohmann::json& locator); std::vector> match_imgui(const nlohmann::json& locator); + std::vector> match_rows(const nlohmann::json& locator); void add_imgui_items(GLCanvas3D& canvas, int depth, std::vector& nodes, std::size_t& omitted, const SnapshotOptions& options); // The item's record in the canvas's last frame; throws when it is gone. ImGuiWrapper::RecordedItem imgui_record(const UiTarget& target) const; @@ -132,12 +204,86 @@ private: McpService& m_service; RefTable m_refs; std::optional m_held; + + // A call's window for taking menus: a closure running, or one that ended before the next idle and + // at most kMenuWindowGrace ago. + static constexpr std::chrono::seconds kMenuWindowGrace{1}; + struct MenuWindow + { + wxEventLoopBase* loop = nullptr; + std::string tool; + bool running = true; + std::chrono::steady_clock::time_point ended; + }; + struct MenuCapture + { + int token = 0; + std::string path; + wxEventLoopBase* loop = nullptr; + bool fired = false; + int closed = 0; + nlohmann::json result; + std::string error; + nlohmann::json details; + }; + struct ClosedMenu + { + std::string tool; + std::chrono::steady_clock::time_point at; + nlohmann::json listing; + }; + void on_idle(wxIdleEvent& event); + MenuCapture* menu_capture(int token); + + bool m_capturing_menus = false; + std::vector m_menu_windows; + std::vector m_menu_captures; + std::deque m_closed_menus; + int m_menu_tokens = 0; }; +// The top-level window `w` belongs to: its own, or for a widget in a popup (a drop-down list, the print +// button's menu), the one the popup opened from, which on every port is the popup's parent. Guards and +// `within` judge popup widgets by it. +wxWindow* owning_window(wxWindow* w); +// The shown popups that opened from `top` or from its widgets, which ui_snapshot lists after it. +std::vector popups_of(wxWindow* top); + +// Rows of the lists ui_snapshot reads: wxDataViewCtrl (every row, collapsed branches too), wxListBox and +// wxCheckListBox, Orca's DropDown, wxGrid (read-only) and the Design tab's DesignRowList. Empty for +// other windows. +std::vector list_rows(wxWindow* list); +bool is_row_list(wxWindow* w); +// The names a row's cell is picked by (`column`): header text, "#n" for a column without one, and for +// the object list, which shows no header, fixed English names. Empty for lists without columns. +std::vector list_columns(wxWindow* list); +// The rows under `roots` (in snapshot order, popups after the window they belong to) that the labels +// `wanted` name, by row_matches(). +std::vector> find_rows(const std::vector& roots, const std::vector& wanted); +// Acts on a row as a person's click on its cell under `column` does: a data view row is selected as +// the click would select it, with one wxEVT_DATAVIEW_SELECTION_CHANGED for it, while the pointer is +// held over the cell for code that reads where it is; a double click activates it and a right click +// sends its context menu event. A list box row is selected, a drop-down row picked, a table row's cell +// made current, a Design list row clicked at its cell. Throws ToolFailure. +nlohmann::json click_row(wxWindow& list, const ListRow& row, const std::string& column, const ClickOptions& options); +// Ticks or clears a row's checkbox cell as a person's click on it does. Throws ToolFailure. +nlohmann::json input_row(wxWindow& list, const ListRow& row, const std::string& column, const nlohmann::json& value); + // The canvases of the plater that are alive now: the 3D view, the preview and the assembly view. std::vector live_canvases(); -// "3d", "preview" or "assemble". +// The Design tab's view once the tab is built, else null. +GLCanvas3D* design_canvas(); +// live_canvases() and the Design view: the canvases the ui_* tools list, find items in and send +// input to. The gizmo state and the idle checks read live_canvases(), since the Design view has no +// gizmos. +std::vector ui_canvases(); +// The 3D view on screen: the Design view while its tab is shown, else the plater's current canvas. +GLCanvas3D* shown_canvas(); +// "3d", "preview", "assemble" or "design". const char* canvas_name(GLCanvas3D* canvas); +// The canvas of a name canvas_name() gives; "" is the Prepare view. Null for an unknown name, and for +// "design" while the Design tab is not built. +GLCanvas3D* canvas_by_name(const std::string& name); // The stable English name automation uses for a gizmo (GLGizmosManager::EType). std::string gizmo_name(int type); @@ -165,4 +311,27 @@ std::optional imgui_find_item(const std::vector"` for a notification, +// `the "" window` for another, "an ImGui window" for one without a title. `texts` are the +// recorded texts of its canvas. +std::string imgui_window_description(const std::string& window, const std::vector<ImGuiWrapper::RecordedText>& texts); + +// The meshes a click on the model meets, as a person sees them (see check_surface()): shown parts +// that are active or of the instance the open gizmo works on (`own`). Modifiers and negative parts +// are see-through, except `target`, the part the click is for. +std::vector<SurfaceMesh> surface_meshes(const std::vector<GLVolume*>& volumes, + const GLVolume* target, + const std::function<bool(const GLVolume*)>& own); + +// A GL toolbar's items, with the visibility and enabled state the canvas's idle handler gives them +// (GLToolbar::update_items_state()) brought up to date first: until that handler runs they keep the +// state of the last idle event, so an item a `select` just enabled would still read disabled. +// `changed` tells whether a state changed, which the canvas has yet to draw. +const std::vector<GLToolbarItem*>& toolbar_items(GLToolbar& toolbar, bool* changed = nullptr); + }}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/UiInvoker.cpp b/src/slic3r/GUI/Mcp/UiInvoker.cpp index 6bfa753f1b..4344cc81ed 100644 --- a/src/slic3r/GUI/Mcp/UiInvoker.cpp +++ b/src/slic3r/GUI/Mcp/UiInvoker.cpp @@ -39,6 +39,7 @@ struct UiInvoker::Shared std::function<GuardState()> guards_on_ui; std::function<uint64_t()> generation; std::function<nlohmann::json()> open_dialogs; + std::function<void(const std::string&, bool)> activity; std::atomic<bool> stopped{false}; // UI-thread only: the calls currently executing, outermost first. More than one means a call is @@ -50,12 +51,13 @@ struct UiInvoker::Shared }; UiInvoker::UiInvoker(UiDispatcher& dispatcher, std::function<GuardState()> guards_on_ui, std::function<uint64_t()> generation, - std::function<nlohmann::json()> open_dialogs) + std::function<nlohmann::json()> open_dialogs, std::function<void(const std::string&, bool)> activity) : m_shared(std::make_shared<Shared>()), m_dispatcher(dispatcher) { m_shared->guards_on_ui = std::move(guards_on_ui); m_shared->generation = std::move(generation); m_shared->open_dialogs = std::move(open_dialogs); + m_shared->activity = std::move(activity); } UiInvoker::~UiInvoker() { shutdown(); } @@ -103,6 +105,8 @@ nlohmann::json UiInvoker::run(GuardClass guard, const std::string& tool, const s } if (error.empty()) { shared->running_tools.push_back(tool); + if (shared->activity) + shared->activity(tool, true); try { value = fn(); } catch (const ToolFailure& f) { @@ -113,6 +117,8 @@ nlohmann::json UiInvoker::run(GuardClass guard, const std::string& tool, const s } catch (...) { error = "Internal error"; } + if (shared->activity) + shared->activity(tool, false); shared->running_tools.pop_back(); } { diff --git a/src/slic3r/GUI/Mcp/UiInvoker.hpp b/src/slic3r/GUI/Mcp/UiInvoker.hpp index 41944cb3a7..42f50a7a49 100644 --- a/src/slic3r/GUI/Mcp/UiInvoker.hpp +++ b/src/slic3r/GUI/Mcp/UiInvoker.hpp @@ -43,9 +43,12 @@ public: // `generation` (any thread) counts UI rebuilds; a closure posted before a rebuild does not run // after it. `open_dialogs` (any thread) describes the open modals outermost first, as // ModalTracker::snapshot() does; it names a native dialog that holds the UI thread when the - // UI thread itself can't answer. + // UI thread itself can't answer. `activity` (UI thread) is told when a closure that passed its + // guards starts (`running` true) and when it ends, with the calling tool's name: the GUI + // automation keeps native menus from opening while a call acts on the UI. UiInvoker(UiDispatcher& dispatcher, std::function<GuardState()> guards_on_ui, std::function<uint64_t()> generation = {}, - std::function<nlohmann::json()> open_dialogs = {}); + std::function<nlohmann::json()> open_dialogs = {}, + std::function<void(const std::string& tool, bool running)> activity = {}); ~UiInvoker(); // Runs `fn` on the UI thread under `guard` and returns its value. Throws ToolFailure when a diff --git a/src/slic3r/GUI/Mcp/UiRefs.cpp b/src/slic3r/GUI/Mcp/UiRefs.cpp index 64bbc95897..0effb36be1 100644 --- a/src/slic3r/GUI/Mcp/UiRefs.cpp +++ b/src/slic3r/GUI/Mcp/UiRefs.cpp @@ -1,7 +1,16 @@ #include "UiRefs.hpp" +#include "McpTypes.hpp" + +#include <nlohmann/json.hpp> + +#include <cctype> #include <cstddef> +#include <cstdlib> +#include <initializer_list> +#include <map> #include <string> +#include <utility> #include <vector> namespace Slic3r { namespace GUI { namespace Mcp { @@ -86,4 +95,184 @@ std::string format_snapshot(const std::vector<UiNode>& nodes, std::size_t omitte return out; } +namespace { + +// What a menu label is matched and numbered by: lower case, trimmed, without the in-use marker and +// trailing dots ("...", or the ellipsis character some translations use). +std::string menu_key(std::string label, std::string current) +{ + for (std::string* s : {&label, ¤t}) + for (char& c : *s) + c = char(std::tolower(static_cast<unsigned char>(c))); + const auto trim = [&label] { + const auto first = label.find_first_not_of(' '); + label = first == std::string::npos ? std::string() : label.substr(first, label.find_last_not_of(' ') - first + 1); + }; + trim(); + if (!current.empty() && label.size() >= current.size() && label.compare(label.size() - current.size(), current.size(), current) == 0) + label.resize(label.size() - current.size()); + for (;;) { + if (!label.empty() && label.back() == '.') + label.pop_back(); + else if (label.size() >= 3 && label.compare(label.size() - 3, 3, "\xE2\x80\xA6") == 0) + label.resize(label.size() - 3); + else + break; + } + trim(); + return label; +} + +// The `n`-th child of `parent` (counting from 1) whose label has `key`. +int menu_child(const std::vector<MenuEntry>& entries, int parent, const std::string& key, int n, const std::string& current) +{ + for (std::size_t i = 0; i < entries.size(); ++i) + if (entries[i].parent == parent && menu_key(entries[i].label, current) == key && --n == 0) + return int(i); + return -1; +} + +} // namespace + +void name_menu_entries(std::vector<MenuEntry>& entries, const std::string& current) +{ + std::map<std::pair<int, std::string>, int> seen; + for (MenuEntry& e : entries) { + const int n = ++seen[{e.parent, menu_key(e.label, current)}]; + const std::string label = n > 1 ? e.label + " #" + std::to_string(n) : e.label; + e.path = e.parent < 0 ? label : entries[std::size_t(e.parent)].path + ">" + label; + } +} + +nlohmann::json menu_listing(const std::vector<MenuEntry>& entries, int under) +{ + nlohmann::json items = nlohmann::json::array(), disabled = nlohmann::json::array(), checked = nlohmann::json::array(); + for (std::size_t i = 0; i < entries.size(); ++i) { + const MenuEntry& e = entries[i]; + int p = e.parent; + while (under >= 0 && p >= 0 && p != under) + p = entries[std::size_t(p)].parent; + if (e.submenu || (under >= 0 && p != under)) + continue; + items.push_back(e.path); + if (!e.enabled) + disabled.push_back(e.path); + if (e.checked) + checked.push_back(e.path); + } + nlohmann::json out{{"items", std::move(items)}}; + if (!disabled.empty()) + out["disabled"] = std::move(disabled); + if (!checked.empty()) + out["checked"] = std::move(checked); + return out; +} + +const MenuEntry* find_menu_entry(const std::vector<MenuEntry>& entries, const std::string& path, const std::string& current, + std::string& err, nlohmann::json& details) +{ + int at = -1; + for (std::size_t start = 0;;) { + const std::size_t end = path.find('>', start); + const std::string part = path.substr(start, end == std::string::npos ? std::string::npos : end - start); + // The label itself first: a label may end in " #2" of its own. + int found = menu_child(entries, at, menu_key(part, current), 1, current); + if (const auto hash = part.rfind(" #"); found < 0 && hash != std::string::npos) { + const std::string digits = part.substr(hash + 2); + if (!digits.empty() && digits.size() <= 4 && digits.find_first_not_of("0123456789") == std::string::npos) + found = menu_child(entries, at, menu_key(part.substr(0, hash), current), std::atoi(digits.c_str()), current); + } + if (found < 0) { + err = "The menu has no item \"" + path + "\""; + details = menu_listing(entries); + return nullptr; + } + at = found; + if (end == std::string::npos) + break; + start = end + 1; + } + const MenuEntry& e = entries[std::size_t(at)]; + if (e.submenu) { + err = "\"" + e.path + "\" is a submenu; name one of its items"; + details = menu_listing(entries, at); + return nullptr; + } + if (!e.enabled) { + err = "\"" + e.path + "\" is disabled here"; + details = menu_listing(entries); + return nullptr; + } + return &e; +} + +std::vector<std::string> row_segments(const nlohmann::json& row) +{ + std::vector<std::string> out; + if (row.is_array()) { + for (const nlohmann::json& label : row) + if (label.is_string()) + out.push_back(label.get<std::string>()); + else + out.clear(); + if (out.size() == row.size() && !out.empty()) + return out; + } else if (row.is_string() && !row.get<std::string>().empty()) { + const std::string path = row.get<std::string>(); + for (std::size_t start = 0;;) { + const std::size_t end = path.find('>', start); + out.push_back(path.substr(start, end == std::string::npos ? std::string::npos : end - start)); + if (end == std::string::npos) + return out; + start = end + 1; + } + } + throw ToolFailure("row is a label path, \"Cube>Cylinder\", or an array of labels"); +} + +nlohmann::json row_locator(const std::vector<std::string>& path) +{ + std::string joined; + for (const std::string& label : path) { + if (label.find('>') != std::string::npos) + return path; + joined += (joined.empty() ? "" : ">") + label; + } + return joined; +} + +bool row_matches(const std::vector<std::string>& path, const std::vector<std::string>& wanted, const std::string& current) +{ + if (wanted.empty() || wanted.size() > path.size()) + return false; + const std::size_t skip = path.size() - wanted.size(); + for (std::size_t i = 0; i < wanted.size(); ++i) { + const std::string& label = path[skip + i]; + const bool marked = !current.empty() && label.size() > current.size() && + label.compare(label.size() - current.size(), current.size(), current) == 0; + if (label != wanted[i] && !(marked && label.substr(0, label.size() - current.size()) == wanted[i])) + return false; + } + return true; +} + +namespace { + +constexpr const char* kPlateIcons[kPlateIconCount] = {"plate", "delete", "orient", "arrange", "lock", + "settings", "name", "move_to_front", "filament_map", "imex_mode"}; + +} // namespace + +int plate_icon_action(const std::string& name) +{ + for (int a = 0; a < kPlateIconCount; ++a) + if (name == kPlateIcons[a]) + return a; + return -1; +} + +std::string plate_icon_name(int action) { return action >= 0 && action < kPlateIconCount ? kPlateIcons[action] : ""; } + +std::pair<int, int> plate_icon_of(int picking_id) { return {picking_id / kPlateIconCount, picking_id % kPlateIconCount}; } + }}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/UiRefs.hpp b/src/slic3r/GUI/Mcp/UiRefs.hpp index 9cbc411f71..413ef3b349 100644 --- a/src/slic3r/GUI/Mcp/UiRefs.hpp +++ b/src/slic3r/GUI/Mcp/UiRefs.hpp @@ -46,6 +46,53 @@ struct UiNode // Compact indented text, one node per line, e.g. ` [w12] button "Slice plate"`. std::string format_snapshot(const std::vector<UiNode>& nodes, std::size_t omitted); +// One item of a popup menu, from a walk that lists a submenu before its items. +struct MenuEntry +{ + std::string label; // as shown, without mnemonic and accelerator + int parent = -1; // the entry of the submenu holding it; -1 at the top + int id = 0; + bool enabled = true; // false under a disabled submenu too + bool checkable = false, checked = false, submenu = false; + std::string path; // set by name_menu_entries() +}; + +// Gives each entry its path: the labels from the top, joined with '>'. A label repeated among its +// siblings is numbered from its second time on ("Change Filament>Generic PLA #2"), so each path +// names one item. `current` is the marker a menu appends to the item in use (" (current)"); the +// numbering leaves it out, so the numbers stay when another item is in use. +void name_menu_entries(std::vector<MenuEntry>& entries, const std::string& current); +// {items, disabled?, checked?}: the paths of the items that run something (under the submenu entry +// `under`, or all of them for -1), then those of them that are disabled and those checked. +nlohmann::json menu_listing(const std::vector<MenuEntry>& entries, int under = -1); +// The entry `path` names. Labels match case-insensitively, `current` and a trailing "..." may be +// left out, and "#2" picks a label's second time among its siblings. A submenu or a disabled item +// can't run: null then, as with no match, with `err` saying why and `details` what there is to pick. +const MenuEntry* find_menu_entry(const std::vector<MenuEntry>& entries, const std::string& path, const std::string& current, + std::string& err, nlohmann::json& details); + +// The labels a row locator names, from the top: {row: "Cube>Cylinder"}, or an array of labels, which +// the journal writes when a label holds '>'. Throws ToolFailure for anything else. +std::vector<std::string> row_segments(const nlohmann::json& row); +// What a locator records for a row's labels from the top: joined with '>', or the array when one +// holds '>'. +nlohmann::json row_locator(const std::vector<std::string>& path); +// Whether `wanted` names a row whose labels from the top are `path`: it matches the path's last +// segments, so the plate an object is on may be left out. A label matches as shown or without +// `current`, the marker a list appends to the item in use. +bool row_matches(const std::vector<std::string>& path, const std::vector<std::string>& wanted, const std::string& current); + +// A plate's icons in the Prepare view, by the picking action PartPlate gives each: "plate" (0, the +// plate itself), "delete", "orient", "arrange", "lock", "settings", "name", "move_to_front", +// "filament_map", "imex_mode". The bed picking id of plate p's icon a is p * kPlateIconCount + a. +constexpr int kPlateIconCount = 10; +// The action an icon name stands for, or -1. +int plate_icon_action(const std::string& name); +// The name of an action, or "" outside 0..kPlateIconCount-1. +std::string plate_icon_name(int action); +// {plate, action} of a bed picking id. +std::pair<int, int> plate_icon_of(int picking_id); + // The refs ui_snapshot hands out. Ids are never reused, so two clients can't confuse each other's // refs; each stores what it points at and how to tell whether that still exists, plus the UI // generation it was taken in (a rebuilt main window invalidates every ref). diff --git a/src/slic3r/GUI/NativeCommands.cpp b/src/slic3r/GUI/NativeCommands.cpp index 1dc2f312db..f629047b47 100644 --- a/src/slic3r/GUI/NativeCommands.cpp +++ b/src/slic3r/GUI/NativeCommands.cpp @@ -2,6 +2,7 @@ #include "calib_dlg.hpp" #include "Camera.hpp" +#include "CreatePresetsDialog.hpp" #include "DailyTips.hpp" #include "GCodeViewer.hpp" #include "GLCanvas3D.hpp" @@ -14,36 +15,59 @@ #include "I18N.hpp" #include "Shortcuts.hpp" #include "IMSlider.hpp" +#include "Jobs/Job.hpp" +#include "Jobs/Worker.hpp" #include "MainFrame.hpp" +#include "ObjectDataViewModel.hpp" #include "NetworkTestDialog.hpp" #include "Plater.hpp" #include "PluginsDialog.hpp" #include "PartPlate.hpp" #include "PlateSettingsDialog.hpp" +#include "Preferences.hpp" #include "SceneBenchmark.hpp" +#include "format.hpp" #include "DeviceCore/DevManager.h" #include "Mcp/McpPaths.hpp" +#include "libslic3r/AppConfig.hpp" #include "libslic3r/Config.hpp" +#include "libslic3r/LocalesUtils.hpp" +#include "libslic3r/Preset.hpp" +#include "libslic3r/PresetBundle.hpp" +#include "libslic3r/Utils.hpp" +#include <boost/algorithm/string/classification.hpp> +#include <boost/algorithm/string/constants.hpp> +#include <boost/algorithm/string/join.hpp> +#include <boost/algorithm/string/predicate.hpp> +#include <boost/algorithm/string/split.hpp> +#include <boost/algorithm/string/trim.hpp> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/path.hpp> +#include <nlohmann/json.hpp> #include <functional> #include <initializer_list> #include <libslic3r/Model.hpp> +#include <nlohmann/json.hpp> #include <algorithm> +#include <charconv> #include <cmath> +#include <cstddef> #include <cstdlib> #include <exception> #include "libslic3r/libslic3r.h" #include <memory> #include "slic3r/GUI/ActionRegistry.hpp" #include <optional> +#include <set> #include <string> +#include <system_error> #include <tuple> #include <utility> #include <vector> +#include <wx/dataview.h> #include <wx/string.h> #include <wx/utils.h> @@ -75,14 +99,85 @@ void ensure_3d_view(Plater* plater) AppActionRunResult object_op(Plater* plater, bool (*ok)(Plater*), void (*op)(Plater*)) { if (!plater) - return {AppActionRunResult::Level::Info, _L("Open the 3D view first.")}; + return {AppActionRunResult::Level::Info, _L("Open the 3D view first."), false}; ensure_3d_view(plater); if (!ok(plater)) - return {AppActionRunResult::Level::Info, _L("Select an object first.")}; + return {AppActionRunResult::Level::Info, _L("Select an object first."), false}; op(plater); return {AppActionRunResult::Level::Success}; } +// Arrange and orient as the toolbar runs them: on every plate, in the background. Plater::can_arrange() +// is false with no objects or while another job runs, and each gets its own message. +AppActionRunResult arrange_op(Plater* plater, void (*op)(Plater*), const wxString& no_objects) +{ + if (!plater) + return {AppActionRunResult::Level::Info, _L("Open the 3D view first."), false}; + ensure_3d_view(plater); + if (plater->model().objects.empty()) + return {AppActionRunResult::Level::Info, no_objects, false}; + if (!plater->get_ui_job_worker().is_idle()) + return {AppActionRunResult::Level::Info, _L("Wait for the running background job to finish."), false}; + // A plate's Arrange or Auto Rotate icon leaves the plate-only state behind. + plater->set_prepare_state(Job::PREPARE_STATE_DEFAULT); + op(plater); + return {AppActionRunResult::Level::Success}; +} + +// The object list, once the Prepare view is shown; the object structure commands act on its selected +// rows, as the context menu items they stand for do. +ObjectList* object_list_in_3d_view() +{ + Plater* plater = wxGetApp().plater(); + ObjectList* list = wxGetApp().obj_list(); + if (plater == nullptr || list == nullptr) + return nullptr; + ensure_3d_view(plater); + return list; +} + +// The object list's selected rows, or none unless every one is of one of `types` (ItemType bits). +wxDataViewItemArray selected_rows(const ObjectList& list, int types) +{ + wxDataViewItemArray rows; + list.GetSelections(rows); + for (const wxDataViewItem& row : rows) + if ((list.GetModel()->GetItemType(row) & types) == 0) + return {}; + return rows; +} + +AppActionRunResult with_reply(const nlohmann::json& reply) +{ + AppActionRunResult r{AppActionRunResult::Level::Success}; + r.reply = reply.dump(); + return r; +} + +// What an Order By left: the sorted plates' objects in their new order, and whether they run +// descending (choosing the order the objects already have reverses it). +AppActionRunResult ordered(Plater& plater, ObjectOrder order, bool all_plates) +{ + PartPlateList& plates = plater.get_partplate_list(); + const ModelObjectPtrs& objects = plater.model().objects; + nlohmann::json list = nlohmann::json::array(); + bool descending = false; + for (int plate = 0; plate < plates.get_plate_count(); ++plate) { + if (!all_plates && plate != plates.get_curr_plate_index()) + continue; + std::vector<ModelObject*> on_plate; + for (size_t i = 0; i < objects.size(); ++i) + if (plates.find_instance(int(i), 0) == plate) { + on_plate.push_back(objects[i]); + list.push_back({{"object", i}, {"name", objects[i]->name}, {"plate", plate}}); + } + std::vector<ModelObject*> ascending = on_plate; + sort_objects(ascending, order, false); + descending = descending || ascending != on_plate; + } + return with_reply({{"order", list}, {"descending", descending}}); +} + // Jump the preview to a layer selected by a 0-100 percent of the layer range. The caller has already // switched to Preview (which may request a slice); if a slicer result is present the slider is // repositioned immediately, otherwise the jump is a no-op until the user re-slices. @@ -159,6 +254,64 @@ AppActionRunResult calib_command(CalibKind kind) return {AppActionRunResult::Level::Success}; } +// What import_configs does with a preset that exists already: the `on_conflict` of its param +// {"path": ..., "on_conflict": "skip" | "overwrite"}, skip by default. `overwrite`, which other path +// params use for an output file, is refused rather than ignored. nullopt with an Error in `fail`. +std::optional<bool> import_overwrites(const std::string& param, AppActionRunResult& fail) +{ + const auto first = param.find_first_not_of(" \t"); + if (first == std::string::npos || param[first] != '{') + return false; + const nlohmann::json j = nlohmann::json::parse(param, nullptr, false); + const nlohmann::json conflict = j.is_object() ? j.value("on_conflict", nlohmann::json("skip")) : nlohmann::json(); + if (!j.is_object() || j.contains("overwrite") || (conflict != "skip" && conflict != "overwrite")) { + fail = {AppActionRunResult::Level::Error, "on_conflict is \"skip\" (default) or \"overwrite\": what happens to a preset that exists already"}; + return std::nullopt; + } + return conflict == "overwrite"; +} + +// Imports preset files from `path` (UTF-8) as the Import Configs dialog does, answering for each preset +// that exists already as the dialog's Yes or No would, so that every one of them is asked about and can +// be named: the message lists the presets imported, replaced and kept. +AppActionRunResult import_preset_file(MainFrame& mf, const std::string& path, bool overwrite) +{ + const PresetBundle& bundle = *wxGetApp().preset_bundle; + const auto names = [&bundle] { + std::set<std::pair<int, std::string>> out; + for (const PresetCollection* presets : std::initializer_list<const PresetCollection*>{&bundle.prints, &bundle.filaments, &bundle.printers}) + for (const Preset& preset : presets->get_presets()) + out.emplace(int(presets->type()), preset.name); + return out; + }; + const auto before = names(); + std::vector<std::string> replaced, kept; + mf.import_configs({path}, [&](const std::string& name) { + (overwrite ? replaced : kept).push_back(name); + return overwrite ? 1 : 0; // never "to all", which would stop the questions + }); + std::vector<std::string> added; + for (const auto& name : names()) + if (before.count(name) == 0) + added.push_back(name.second); + + wxString message; + const auto add = [&message](const wxString& text, const std::vector<std::string>& list) { + if (!list.empty()) + message += (message.empty() ? "" : " ") + format_wxstr(text, boost::algorithm::join(list, ", ")); + }; + // TRN %1% is a comma-separated list of preset names. + add(_L("Imported presets: %1%."), added); + // TRN %1% is a comma-separated list of preset names. + add(_L("Replaced presets: %1%."), replaced); + // TRN %1% is a comma-separated list of preset names. + add(_L("Kept the existing presets: %1%."), kept); + if (message.empty()) + return {AppActionRunResult::Level::Error, + _L("No presets were imported.") + _L("\nHint: Make sure you have added the corresponding printer before importing the configs.")}; + return {AppActionRunResult::Level::Success, message}; +} + constexpr const char* kCommandPrefix = "orca_command"; // Thin AppAction wrapper for one catalog entry: identity and presentation come from the catalog, @@ -212,7 +365,10 @@ void describe_commands(std::vector<NativeCommand>& commands) {"new_project", "Start a new, empty project (asks first if the current one has unsaved changes)."}, {"undo", "Undo the last change to the project."}, {"redo", "Redo the last undone change."}, - {"open_preferences", "Open the Preferences dialog."}, + {"open_preferences", "Open the Preferences dialog on a tab, scrolled to one preference when given (shown on its own tab). Its " + "controls are named after their preference keys: ui_input {\"target\": {\"name\": key, \"within\": " + "\"Preferences\"}} changes one through the dialog; get_settings scope preferences reads them.", + CommandParamType::Text, "general, control, graphics, online or developer, optionally :<key>, e.g. control:auto_arrange"}, {"mode_simple", "Switch the settings view to Simple mode."}, {"mode_advanced", "Switch the settings view to Advanced mode."}, {"mode_expert", "Switch the settings view to Expert mode."}, @@ -222,14 +378,22 @@ void describe_commands(std::vector<NativeCommand>& commands) {"export_3mf", "Export the model as a .3mf without slicing data. With a path, writes there without a dialog.", CommandParamType::Path, "absolute .3mf path, or {\"path\": ..., \"overwrite\": true}"}, {"export_sliced_file", "Export the current plate's sliced file (.gcode.3mf). With a path, writes there without a dialog.", CommandParamType::Path, "absolute .3mf path, or {\"path\": ..., \"overwrite\": true}"}, {"export_all_sliced_file", "Export every plate's sliced file into one .gcode.3mf. With a path, writes there without a dialog.", CommandParamType::Path, "absolute .3mf path, or {\"path\": ..., \"overwrite\": true}"}, + {"send_gcode", "Open the Send G-code to printer host dialog for the current plate, as the Print button does for a printer with a print host (OctoPrint, Moonraker, PrusaLink, Duet...). Set the file name with ui_input and press Upload or Upload and Print with dialog_respond; the plate is sliced if needed, then uploaded in the background: get_state.uploads shows the row's state, and a failed upload also opens an error dialog. A replay uploads again. Fails for a printer without a print host, or one that prints through the Bambu network or printer agents."}, {"export_stl_multi", "Export each object as its own STL. With a directory, writes there without a dialog.", CommandParamType::Path, "absolute path of an existing directory"}, {"export_drc_single", "Export all objects as one Draco (.drc) file."}, {"export_drc_multi", "Export each object as its own Draco (.drc) file."}, {"export_toolpaths_obj", "Export the sliced toolpaths as an OBJ."}, - {"export_config", "Export presets as a bundle (opens a dialog to choose them)."}, + {"export_config", "Export presets as a bundle or ZIP archives. Opens a dialog: click the label of the kind to export, check " + "the presets (their checkboxes are named after them), press OK, then answer the result message. With a " + "directory, OK writes there instead of asking for a folder.", + CommandParamType::Path, "absolute path of an existing directory"}, {"import_file", "Import models (3MF/STL/STEP/SVG/OBJ/AMF). With a path, imports that file without a dialog.", CommandParamType::Path, "absolute path of a model file"}, {"import_zip_archive", "Import models from a ZIP archive (opens a file dialog)."}, - {"import_configs", "Import configuration presets. With a path, loads that .ini/.json without a dialog.", CommandParamType::Path, "absolute path of a config file"}, + {"import_configs", "Import presets. With a path, imports a preset .json, a .zip of them or an .orca_printer, " + ".orca_filament or .orca_bundle without a dialog, and the message names the presets imported, " + "replaced and kept; a .gcode loads the settings it was sliced with.", + CommandParamType::Path, "absolute path, or {\"path\": ..., \"on_conflict\": \"overwrite\"} to replace presets that exist " + "already (default \"skip\")"}, {"view_default", "Reset the 3D camera to the default view and fit the plate."}, {"view_fit_bed", "Fit the build plate in the 3D view."}, {"view_toggle_perspective", "Switch the 3D camera between perspective and orthographic."}, @@ -248,9 +412,33 @@ void describe_commands(std::vector<NativeCommand>& commands) {"obj_fit_volume", "Scale the selection to fit the print volume."}, {"obj_instances_up", "Add an instance of the selected object."}, {"obj_instances_down", "Remove an instance of the selected object."}, - {"obj_arrange", "Arrange all objects on the plates (runs in the background)."}, - {"obj_orient", "Auto-orient the selection (runs in the background)."}, + {"obj_arrange", "Arrange all objects on the unlocked plates with the saved Arrange options, as the toolbar does; the " + "call returns when the arrangement is done. The arrange tool also takes options, one plate or fill bed."}, + {"obj_orient", "Auto-orient the selection, or every object when nothing is selected; the call returns when it is done."}, + // Object structure: the object list's Change Type, Rename, instance and Assemble items, and the plate + // menu's Order By. A param stands in for the item's dialog. + {"obj_type_part", "Make the selected parts (select {volumes} first) solid parts, as Change Type does. Parts are listed by type, so part indices change."}, + {"obj_type_negative", "Make the selected parts negative parts, as Change Type does; not the object's last solid part. Parts are listed by type, so part indices change."}, + {"obj_type_modifier", "Make the selected parts modifiers, as Change Type does; not the object's last solid part. Parts are listed by type, so part indices change."}, + {"obj_type_support_blocker", "Make the selected parts support blockers, as Change Type does; not the object's last solid part, nor a text or SVG part. Parts are listed by type, so part indices change."}, + {"obj_type_support_enforcer", "Make the selected parts support enforcers, as Change Type does; not the object's last solid part, nor a text or SVG part. Parts are listed by type, so part indices change."}, + {"obj_type_precise_seam", "Make the selected parts Center precise seams (seams keep their subtype), as Change Type does; not the object's last solid part, nor a text or SVG part. Parts are listed by type, so part indices change."}, + {"obj_rename", "Rename the selected object or part (select one). With a name, skips the Rename dialog; a name with characters a file name cannot hold is refused.", CommandParamType::Text, "the new name"}, + {"obj_set_instances", "Give the selected object this many instances, in one undo step. With a number, skips the dialog. New instances overlap; arrange afterwards. The reply has object and instances.", CommandParamType::Index, "total number of instances, 1-1000"}, + {"obj_assemble", "Assemble two or more selected objects into one object of parts named Assembly. They are removed and it is added last, so object indices change; the reply has its index (object) and name."}, + {"obj_instances_to_objects", "Make each instance of the selected object a separate object (select {objects: [n]}); with some of its instances selected, only those. New objects are added last; the reply lists the objects the instances are in now (objects)."}, + {"obj_order_by_name", "Order the current plate's objects by name, which sets the object list and print order, as the plate menu's Order By does. Choosing the order they already have reverses it. Object indices change; the reply lists the new order (order: [{object, name, plate}]) and descending.", CommandParamType::Text, "all, to order every plate"}, + {"obj_order_by_filament", "Order the current plate's objects by filament, which sets the object list and print order, as the plate menu's Order By does. Choosing the order they already have reverses it. Object indices change; the reply lists the new order (order: [{object, name, plate}]) and descending.", CommandParamType::Text, "all, to order every plate"}, + {"obj_order_by_height", "Order the current plate's objects by height, which sets the object list and print order, as the plate menu's Order By does. Choosing the order they already have reverses it. Object indices change; the reply lists the new order (order: [{object, name, plate}]) and descending.", CommandParamType::Text, "all, to order every plate"}, + {"obj_order_by_size", "Order the current plate's objects by size (bounding box volume), which sets the object list and print order, as the plate menu's Order By does. Choosing the order they already have reverses it. Object indices change; the reply lists the new order (order: [{object, name, plate}]) and descending.", CommandParamType::Text, "all, to order every plate"}, {"add_primitive_svg", "Add an SVG as a new object, or as a part of the selected object. With a path, uses that file without a dialog; the part is created in the background (wait for idle), and the SVG gizmo opens on it.", CommandParamType::Path, "absolute path of an .svg file"}, + // Shapes: a size skips the Primitive size dialog. + {"add_primitive_cube", "Add a cube object to the current plate; fails while an object is selected. With a size, skips the size dialog.", CommandParamType::Text, "X Y Z in mm, separated by spaces"}, + {"add_primitive_cylinder", "Add a cylinder object to the current plate; fails while an object is selected. With a size, skips the size dialog. The shape may then be turned toward the part-cooling fan, so the size is along its own axes before that turn.", CommandParamType::Text, "diameter and height in mm, separated by a space"}, + {"add_primitive_sphere", "Add a sphere object to the current plate; fails while an object is selected. With a size, skips the size dialog.", CommandParamType::Text, "diameter in mm"}, + {"add_primitive_cone", "Add a cone object to the current plate; fails while an object is selected. With a size, skips the size dialog. The shape may then be turned toward the part-cooling fan, so the size is along its own axes before that turn.", CommandParamType::Text, "base diameter and height in mm, separated by a space"}, + {"add_primitive_disc", "Add a disc object to the current plate; fails while an object is selected. With a size, skips the size dialog. The shape may then be turned toward the part-cooling fan, so the size is along its own axes before that turn.", CommandParamType::Text, "diameter and height in mm, separated by a space"}, + {"add_primitive_torus", "Add a torus object to the current plate; fails while an object is selected. With a size, skips the size dialog. The shape may then be turned toward the part-cooling fan, so the size is along its own axes before that turn.", CommandParamType::Text, "inner diameter and tube diameter in mm, separated by a space"}, {"plate_add", "Add a plate."}, {"plate_duplicate", "Duplicate the current plate."}, {"plate_delete", "Delete the current plate."}, @@ -276,6 +464,14 @@ void describe_commands(std::vector<NativeCommand>& commands) {"refresh_plugins", "Reload plugins."}, {"install_plugin", "Open the plugin hub to install a plugin."}, {"install_local_plugin", "Install a plugin from a local file (opens a file dialog)."}, + // Filament slots + {"filament_add", "Add a filament slot, as the + button above the filament list does; the message names the new slot. It " + "takes the next colour and the last slot's preset (change them with select_preset filament_slot and " + "set_settings scope project filament_colour). It goes after the physical slots: mixed filaments move " + "up by one, and objects on them follow."}, + {"filament_delete", "Delete a filament slot, as its Delete menu item does; objects on it move to another slot. A mixed " + "filament (project scope filament_is_mixed) is refused.", CommandParamType::Index, + "1-based filament slot; without it, the last physical slot, as the - button"}, }; for (NativeCommand& c : commands) { auto it = std::find_if(std::begin(details), std::end(details), [&](const Detail& d) { return c.key == d.key; }); @@ -284,7 +480,7 @@ void describe_commands(std::vector<NativeCommand>& commands) c.param = {it->param, it->param_help}; c.completion = it->completion; } else if (c.key.rfind("calib_", 0) == 0) { - c.description = "Open the " + c.title + " wizard."; + c.description = "Open the " + c.title + " dialog; the calibrate tool runs the same test with typed parameters and no dialog."; } else if (c.key.rfind("view_", 0) == 0) { c.description = "Point the 3D camera: " + c.title + "."; } else if (c.key.rfind("add_primitive_", 0) == 0 || c.key.rfind("add_handy_", 0) == 0) { @@ -406,8 +602,24 @@ std::vector<NativeCommand> build_command_catalog() plater->redo(); return AppActionRunResult{AppActionRunResult::Level::Success}; }); - add_with_icon("open_preferences", L("Preferences"), L("Commands"), "cog", [](const std::string&) { - wxGetApp().open_preferences(); + add_with_icon("open_preferences", L("Preferences"), L("Commands"), "cog", [](const std::string& param) { + if (param.empty()) { + wxGetApp().open_preferences(); + return AppActionRunResult{AppActionRunResult::Level::Success}; + } + // "tab[:key]": the tab to show, and the preference whose control is scrolled into view and focused. + static const std::pair<const char*, PreferencesTab> tabs[] = {{"general", PreferencesTab::General}, + {"control", PreferencesTab::Control}, + {"graphics", PreferencesTab::Graphics}, + {"online", PreferencesTab::Online}, + {"developer", PreferencesTab::Developer}}; + const std::size_t colon = param.find(':'); + const std::string tab = param.substr(0, colon); + const auto it = std::find_if(std::begin(tabs), std::end(tabs), [&](const auto& t) { return tab == t.first; }); + if (it == std::end(tabs)) + return AppActionRunResult{AppActionRunResult::Level::Error, + from_u8("Unknown tab \"" + tab + "\": general, control, graphics, online or developer")}; + wxGetApp().open_preferences(it->second, colon == std::string::npos ? std::string() : param.substr(colon + 1)); return AppActionRunResult{AppActionRunResult::Level::Success}; }); @@ -504,6 +716,26 @@ std::vector<NativeCommand> build_command_catalog() add_with_icon("export_sliced_file", L("Export Sliced File"), L("Slice & Export"), "save", export_sliced(false)); add_with_icon("export_all_sliced_file", L("Export All Sliced Files"), L("Slice & Export"), "save", export_sliced(true)); + // ---- Send to print host ---- + // The Print button's send for a printer with a print host: the Send G-code dialog, then the upload queue. Where + // the button would not send to a print host, the command says why instead of doing nothing. + add_with_icon("send_gcode", L("Send G-code to printer host"), L("Slice & Export"), "printer", [](const std::string&) { + Plater* plater = wxGetApp().plater(); + if (plater == nullptr) + return AppActionRunResult{}; + PresetBundle& bundle = *wxGetApp().preset_bundle; + if (bundle.use_bbl_network() || wxGetApp().app_config->get_bool("use_printer_agents")) + // TRN "Print plate" is the print button's action, which sends to such a printer through its own dialog. + return AppActionRunResult{AppActionRunResult::Level::Error, _L("This printer prints with Print plate, not through a print host.")}; + // The Print button sends only to a printer with a print host address, as MainFrame::can_send_gcode() checks. + const auto* host = bundle.printers.get_edited_preset().config.option<ConfigOptionString>("print_host"); + if (host == nullptr || host->value.empty()) + return AppActionRunResult{AppActionRunResult::Level::Error, + _L("This printer has no print host. Set one in the printer's connection settings.")}; + plater->send_gcode_legacy(); + return AppActionRunResult{AppActionRunResult::Level::Success}; + }); + // ---- Calibration ---- // The tab-strip calib_sf glyph is drawn white for the dark tab bar and vanishes on the palette's // light tile, so each wizard borrows the matching settings-group icon instead (gray + accent green). @@ -621,21 +853,151 @@ std::vector<NativeCommand> build_command_catalog() wxGetApp().plater(), [](Plater* p) { return p->can_decrease_instances(); }, [](Plater* p) { p->decrease_instances(); }); }); add_with_icon("obj_arrange", L("Auto-Arrange"), L("Object"), "toolbar_arrange", [](const std::string&) { - return object_op(wxGetApp().plater(), [](Plater* p) { return p->can_arrange(); }, [](Plater* p) { p->arrange(); }); + return arrange_op(wxGetApp().plater(), [](Plater* p) { p->arrange(); }, _L("There are no objects to arrange.")); }); add_with_icon("obj_orient", L("Auto-Orient"), L("Object"), "toolbar_orient", [](const std::string&) { - return object_op(wxGetApp().plater(), [](Plater* p) { return p->can_arrange(); }, [](Plater* p) { p->orient(); }); + return arrange_op(wxGetApp().plater(), [](Plater* p) { p->orient(); }, _L("There are no objects to orient.")); }); + // ---- Object structure ---- (the object list's context menus and the plate menu's Order By) + // Change Type is in the part menus only: without part rows, set_volume_type() would change every + // part of a selected object, which no menu offers. + auto add_type = [&](std::string key, std::string title, ModelVolumeType type) { + add(std::move(key), std::move(title), L("Object"), [type](const std::string&) { + ObjectList* list = object_list_in_3d_view(); + if (list == nullptr) + return AppActionRunResult{}; + if (selected_rows(*list, itVolume).empty()) + return AppActionRunResult{AppActionRunResult::Level::Info, _L("Select a part first."), false}; + const wxString why = list->set_volume_type(type, true, /*show_errors=*/false); + if (!why.empty()) + return AppActionRunResult{AppActionRunResult::Level::Error, why}; + return AppActionRunResult{AppActionRunResult::Level::Success}; + }); + }; + add_type("obj_type_part", L("Change Type to Part"), ModelVolumeType::MODEL_PART); + add_type("obj_type_negative", L("Change Type to Negative Part"), ModelVolumeType::NEGATIVE_VOLUME); + add_type("obj_type_modifier", L("Change Type to Modifier"), ModelVolumeType::PARAMETER_MODIFIER); + add_type("obj_type_support_blocker", L("Change Type to Support Blocker"), ModelVolumeType::SUPPORT_BLOCKER); + add_type("obj_type_support_enforcer", L("Change Type to Support Enforcer"), ModelVolumeType::SUPPORT_ENFORCER); + add_type("obj_type_precise_seam", L("Change Type to Precise Seam"), ModelVolumeType::PRECISE_SEAM_CENTER); + add("obj_rename", L("Rename"), L("Object"), [](const std::string& param) { + ObjectList* list = object_list_in_3d_view(); + if (list == nullptr) + return AppActionRunResult{}; + const wxDataViewItemArray rows = selected_rows(*list, itObject | itVolume); + if (rows.size() != 1) + return AppActionRunResult{AppActionRunResult::Level::Info, _L("Select one object or part first."), false}; + if (param.empty()) + list->rename_item(); + else if (!list->rename_item(rows.front(), from_u8(param))) + return AppActionRunResult{AppActionRunResult::Level::Error, + _L("Invalid name, the following characters are not allowed:") + " <>:/\\|?*\""}; + return AppActionRunResult{AppActionRunResult::Level::Success}; + }); + add_with_icon("obj_set_instances", L("Set Number of Instances"), L("Object"), "instance_add", [](const std::string& param) { + Plater* plater = wxGetApp().plater(); + ObjectList* list = object_list_in_3d_view(); + if (list == nullptr) + return AppActionRunResult{}; + const std::optional<int> count = param.empty() ? std::nullopt : NativeCommands::parse_count(param); + if (!param.empty() && (!count || *count > 1000)) + return AppActionRunResult{AppActionRunResult::Level::Error, from_u8("The number of instances is a whole number from 1 to 1000.")}; + if (count == 0) + return AppActionRunResult{AppActionRunResult::Level::Error, from_u8("0 instances would delete the object; use obj_delete.")}; + const int obj_idx = plater->get_selected_object_idx(); + if (obj_idx < 0) + return AppActionRunResult{AppActionRunResult::Level::Info, _L("Select an object first."), false}; + // The menu item is enabled by can_increase_instances(); each of its reasons gets a message. + const ModelObject* object = plater->model().objects[obj_idx]; + if (list->has_selected_cut_object()) + return AppActionRunResult{AppActionRunResult::Level::Error, _L("A cut object keeps its number of instances.")}; + if (std::any_of(object->instances.begin(), object->instances.end(), [](const ModelInstance* i) { return !i->printable; })) + return AppActionRunResult{AppActionRunResult::Level::Error, _L("Make every instance of the object printable first.")}; + if (!plater->can_increase_instances()) + return AppActionRunResult{AppActionRunResult::Level::Info, _L("Wait for the running background job to finish."), false}; + if (!count) { + plater->set_number_of_copies(); + return AppActionRunResult{AppActionRunResult::Level::Success}; + } + plater->set_number_of_copies(*count); + return with_reply({{"object", obj_idx}, {"instances", object->instances.size()}}); + }); + add("obj_assemble", L("Assemble"), L("Object"), [](const std::string&) { + ObjectList* list = object_list_in_3d_view(); + if (list == nullptr) + return AppActionRunResult{}; + // Assemble is in the menu of two or more selected objects only; can_merge_to_multipart_object() + // alone accepts one, which merge() would replace with an "Assembly" of one. + if (selected_rows(*list, itObject | itInstance).size() < 2) + return AppActionRunResult{AppActionRunResult::Level::Info, _L("Select two or more objects first."), false}; + if (!list->can_merge_to_multipart_object()) + return AppActionRunResult{AppActionRunResult::Level::Error, _L("Cut objects can't be assembled.")}; + list->merge(true); + const ModelObjectPtrs& objects = wxGetApp().plater()->model().objects; + return with_reply({{"object", objects.size() - 1}, {"name", objects.back()->name}}); + }); + add("obj_instances_to_objects", L("Set as Individual Objects"), L("Object"), [](const std::string&) { + Plater* plater = wxGetApp().plater(); + ObjectList* list = object_list_in_3d_view(); + if (list == nullptr) + return AppActionRunResult{}; + if (!plater->can_set_instance_to_object()) + return AppActionRunResult{AppActionRunResult::Level::Info, _L("Select an object with more than one instance first."), false}; + const int obj_idx = plater->get_selected_object_idx(); + const size_t before = plater->model().objects.size(); + list->split_instances(); + nlohmann::json objects = nlohmann::json::array({obj_idx}); + for (size_t i = before; i < plater->model().objects.size(); ++i) + objects.push_back(i); + return with_reply({{"objects", objects}}); + }); + auto add_order = [&](std::string key, std::string title, ObjectOrder order) { + add(std::move(key), std::move(title), L("Object"), [order](const std::string& param) { + Plater* plater = wxGetApp().plater(); + ObjectList* list = object_list_in_3d_view(); + if (list == nullptr) + return AppActionRunResult{}; + if (!param.empty() && param != "all") + return AppActionRunResult{AppActionRunResult::Level::Error, + from_u8("The param is all, to order every plate, or nothing for the current plate.")}; + const bool all = param == "all"; + if (all ? plater->model().objects.empty() : plater->get_partplate_list().get_selected_plate()->empty()) + return AppActionRunResult{AppActionRunResult::Level::Info, _L("There are no objects to order."), false}; + // order_objects() only shows a notification while a gizmo is open. + if (plater->get_view3D_canvas3D()->get_gizmos_manager().get_current_type() != GLGizmosManager::Undefined) + return AppActionRunResult{AppActionRunResult::Level::Error, _L("Error: Please close all toolbar menus first")}; + list->order_objects(order, all); + return ordered(*plater, order, all); + }); + }; + add_order("obj_order_by_name", L("Order by Name"), ObjectOrder::Name); + add_order("obj_order_by_filament", L("Order by Filament"), ObjectOrder::Filament); + add_order("obj_order_by_height", L("Order by Height"), ObjectOrder::Height); + add_order("obj_order_by_size", L("Order by Size"), ObjectOrder::Size); + // ---- Add Primitive ---- (the Add > Add Primitive submenu; creates a new object) + // A size param holds the dimensions the size dialog asks for, in its order, and skips the dialog. auto add_primitive = [&](std::string key, std::string title, std::string icon, const char* type_name) { - add_with_icon(std::move(key), std::move(title), L("Add Primitive"), std::move(icon), [type_name](const std::string&) { - Plater* plater = wxGetApp().plater(); - if (plater) { - ensure_3d_view(plater); - if (ObjectList* list = wxGetApp().obj_list()) - list->load_generic_subobject(type_name, ModelVolumeType::INVALID); + add_with_icon(key, std::move(title), L("Add Primitive"), std::move(icon), [key, type_name](const std::string& param) { + Plater* plater = wxGetApp().plater(); + ObjectList* list = wxGetApp().obj_list(); + if (plater == nullptr || list == nullptr) + return AppActionRunResult{}; + ensure_3d_view(plater); + if (!list->can_add_shape_object()) + return AppActionRunResult{AppActionRunResult::Level::Error, + _L("Deselect all objects to add a primitive object. To add a shape to the selected object, " + "use its Add Part menu.")}; + std::vector<double> size; + if (!param.empty()) { + const std::optional<std::vector<double>> parsed = NativeCommands::parse_sizes(param); + if (!parsed || parsed->size() != primitive_size_names(type_name).size()) + return AppActionRunResult{AppActionRunResult::Level::Error, + from_u8(std::string("The size is ") + NativeCommands::find(key)->param.help + ".")}; + size = *parsed; } + list->load_generic_subobject(type_name, ModelVolumeType::INVALID, true, size); return AppActionRunResult{AppActionRunResult::Level::Success}; }); }; @@ -768,6 +1130,59 @@ std::vector<NativeCommand> build_command_catalog() return AppActionRunResult{AppActionRunResult::Level::Info, _L("Connect a printer to synchronize the AMS filament list.")}; }); + // ---- Filament slots ---- + // The + and - buttons above the filament list and a slot's Delete menu item. They show for printers + // that take several filaments through one extruder (Sidebar::show_SEMM_buttons()), and a G-code file + // shown in place of a project has its own filament list. + const auto filament_slots_unavailable = [](Plater* plater) -> std::optional<AppActionRunResult> { + if (!is_fff_plater(plater) || plater->using_exported_file()) + return AppActionRunResult{AppActionRunResult::Level::Info, _L("Filament slots belong to a filament (FFF) project, not to a G-code file.")}; + if (!Sidebar::should_show_SEMM_buttons()) + return AppActionRunResult{AppActionRunResult::Level::Info, + _L("This printer has one filament per extruder; change the number of extruders in the printer settings.")}; + return std::nullopt; + }; + add_with_icon("filament_add", L("Add Filament Slot"), L("Filament"), "add_filament", [filament_slots_unavailable](const std::string&) { + Plater* plater = wxGetApp().plater(); + if (const auto refused = filament_slots_unavailable(plater)) + return *refused; + const PresetBundle& bundle = *wxGetApp().preset_bundle; + if (bundle.filament_presets.size() >= MAXIMUM_EXTRUDER_NUMBER) + return AppActionRunResult{AppActionRunResult::Level::Info, _L("No more filament slots can be added.")}; + // A new physical slot goes after the physical ones; mixed filaments move up by one. + const size_t slot = bundle.num_physical_filaments() + 1; + plater->sidebar().add_filament(); + plater->sidebar().update_filaments_counter(); + return AppActionRunResult{AppActionRunResult::Level::Success, format_wxstr(_L("Added filament slot %1%."), slot)}; + }); + add_with_icon("filament_delete", L("Delete Filament Slot"), L("Filament"), "delete_filament", [filament_slots_unavailable](const std::string& param) { + Plater* plater = wxGetApp().plater(); + if (const auto refused = filament_slots_unavailable(plater)) + return *refused; + const PresetBundle& bundle = *wxGetApp().preset_bundle; + const size_t physical = bundle.num_physical_filaments(); + if (physical < 2) + return AppActionRunResult{AppActionRunResult::Level::Info, _L("The only filament slot cannot be deleted.")}; + // Without a slot, the last physical one, as the - button. + size_t slot = physical; + if (!param.empty()) { + try { + slot = size_t(std::stoul(param)); + } catch (const std::exception&) { + slot = 0; + } + if (slot < 1 || slot > bundle.filament_presets.size()) + return AppActionRunResult{AppActionRunResult::Level::Error, + format_wxstr(_L("Filament slot must be 1 to %1%."), bundle.filament_presets.size())}; + if (bundle.is_mixed_filament(slot - 1)) + return AppActionRunResult{AppActionRunResult::Level::Error, + format_wxstr(_L("Filament slot %1% is a mixed filament; delete it from the mixed filament list."), slot)}; + } + plater->sidebar().delete_filament(slot - 1); + plater->sidebar().update_filaments_counter(); + return AppActionRunResult{AppActionRunResult::Level::Success, format_wxstr(_L("Deleted filament slot %1%."), slot)}; + }); + // ---- Presets / cloud ---- add_with_icon("preset_bundle", L("Open Preset Bundle"), L("Presets"), "menu_edit_preset", [](const std::string&) { wxGetApp().open_presetbundledialog(); @@ -815,12 +1230,21 @@ std::vector<NativeCommand> build_command_catalog() return AppActionRunResult{AppActionRunResult::Level::Success}; } AppActionRunResult fail; - const auto path = path_param(param, false, fail); - if (!path) + const auto path = path_param(param, false, fail); + const auto overwrite = path ? import_overwrites(param, fail) : std::nullopt; + if (!overwrite) return fail; - if (!mf->load_config_file(path->string())) - return AppActionRunResult{AppActionRunResult::Level::Error, _L("The configuration was not loaded.")}; - return AppActionRunResult{AppActionRunResult::Level::Success}; + const std::string file = Mcp::path_to_utf8(*path); + if (is_gcode_file(file)) { + if (!mf->load_config_file(file)) + return AppActionRunResult{AppActionRunResult::Level::Error, _L("The configuration was not loaded.")}; + return AppActionRunResult{AppActionRunResult::Level::Success}; + } + for (const char* ext : {".json", ".zip", ".orca_printer", ".orca_filament", ".orca_bundle"}) + if (boost::iends_with(file, ext)) + return import_preset_file(*mf, file, *overwrite); + return AppActionRunResult{AppActionRunResult::Level::Error, + "Not a preset file: give a .json, .zip, .orca_printer, .orca_filament, .orca_bundle or .gcode"}; }); // ---- Export extras ---- @@ -855,10 +1279,22 @@ std::vector<NativeCommand> build_command_catalog() plater->export_toolpaths_to_obj(); return AppActionRunResult{AppActionRunResult::Level::Success}; }); - add_with_icon("export_config", L("Export Preset Bundle"), L("Export"), "save", [](const std::string&) { - if (MainFrame* mf = wxGetApp().mainframe) - mf->export_config(); - return AppActionRunResult{AppActionRunResult::Level::Success}; + add_with_icon("export_config", L("Export Preset Bundle"), L("Export"), "save", [](const std::string& param) { + if (param.empty()) { + if (MainFrame* mf = wxGetApp().mainframe) + mf->export_config(); + return AppActionRunResult{AppActionRunResult::Level::Success}; + } + std::string err; + auto pp = Mcp::parse_path_param(param, err); + auto dir = pp ? Mcp::resolve_output_dir(pp->path, err) : std::nullopt; + if (!dir) + return AppActionRunResult{AppActionRunResult::Level::Error, from_u8(err)}; + // The dialog MainFrame::export_config() opens, given the folder its OK writes to. + ExportConfigsDialog dlg(nullptr, from_path(*dir)); + if (dlg.ShowModal() != wxID_OK) + return AppActionRunResult{AppActionRunResult::Level::Error, _L("Nothing was exported.")}; + return AppActionRunResult{AppActionRunResult::Level::Success, from_path(*dir)}; }); // ---- Help ---- (mirrors the top-bar Help menu, plus the wiki/YouTube links) @@ -971,6 +1407,36 @@ const char* NativeCommands::param_type_name(CommandParamType type) } } +std::optional<std::vector<double>> NativeCommands::parse_sizes(const std::string& param) +{ + std::vector<std::string> tokens; + boost::split(tokens, param, boost::is_any_of(" ,\t"), boost::token_compress_on); + std::vector<double> sizes; + for (const std::string& token : tokens) { + if (token.empty()) + continue; + size_t end = 0; + const double value = string_to_double_decimal_point(token, &end); + if (end != token.size() || !std::isfinite(value) || value <= 0.) + return std::nullopt; + sizes.push_back(value); + } + if (sizes.empty()) + return std::nullopt; + return sizes; +} + +std::optional<int> NativeCommands::parse_count(const std::string& param) +{ + const std::string text = boost::algorithm::trim_copy(param); + int value = 0; + const char* end = text.data() + text.size(); + const auto res = std::from_chars(text.data(), end, value); + if (text.empty() || res.ec != std::errc() || res.ptr != end || value < 0) + return std::nullopt; + return value; +} + AppActionRunResult NativeCommands::run(const std::string& key, const std::string& param) { GUI_App& app = wxGetApp(); diff --git a/src/slic3r/GUI/NativeCommands.hpp b/src/slic3r/GUI/NativeCommands.hpp index fa6b334f0d..df5fb0c2b8 100644 --- a/src/slic3r/GUI/NativeCommands.hpp +++ b/src/slic3r/GUI/NativeCommands.hpp @@ -2,6 +2,7 @@ #include <functional> #include <memory> +#include <optional> #include <string> #include <vector> @@ -55,6 +56,13 @@ const NativeCommand* find(const std::string& key); const char* param_type_name(CommandParamType type); +// The positive numbers of a size param, separated by spaces or commas ("90 4", "90,4"); nullopt when +// it holds anything else or nothing. +std::optional<std::vector<double>> parse_sizes(const std::string& param); + +// A count param: a whole number of 0 or more, nothing else ("6", " 6 "); nullopt otherwise. +std::optional<int> parse_count(const std::string& param); + // Materialises one catalog entry as a runnable AppAction, titled in the current UI language with the // English title/group kept as search aliases. Keeps the catalog's identity, presentation and // behaviour as the single source of truth; ActionRegistry only stores and dispatches the result. diff --git a/src/slic3r/GUI/NotificationManager.cpp b/src/slic3r/GUI/NotificationManager.cpp index da049ba19d..f85fc3bcbc 100644 --- a/src/slic3r/GUI/NotificationManager.cpp +++ b/src/slic3r/GUI/NotificationManager.cpp @@ -628,6 +628,15 @@ void NotificationManager::PopNotification::init() if (is_finished()) return; + // Text is measured with the font ImGuiWrapper::new_frame() builds on the first ImGui frame. A + // notification pushed or updated before that (the app starts on Home, and slicing or arranging + // begins before the 3D view is drawn) is measured in render(), which inits it again because its + // line height then differs from the font's. + if (ImGui::GetFont() == nullptr) { + m_line_height = 0.f; + return; + } + count_spaces(); count_lines(); diff --git a/src/slic3r/GUI/Plater.cpp b/src/slic3r/GUI/Plater.cpp index 93874c9f7c..c7c332d8a1 100644 --- a/src/slic3r/GUI/Plater.cpp +++ b/src/slic3r/GUI/Plater.cpp @@ -44,6 +44,7 @@ #include "libslic3r/Preset.hpp" #include <fstream> #include "libslic3r/calib.hpp" +#include "libslic3r/ParameterUtils.hpp" #include <iterator> #include "libslic3r/Format/OBJ.hpp" #include "libslic3r/Geometry.hpp" @@ -211,6 +212,7 @@ #include "3DScene.hpp" #include "GLCanvas3D.hpp" #include "Selection.hpp" +#include "SyntheticInput.hpp" #include "GLToolbar.hpp" #include "GUI_Preview.hpp" #include "UVEditorCanvas.hpp" @@ -1401,21 +1403,6 @@ struct DynamicFilamentList : DynamicList } }; -// Check if the machine supports Junction Deviation (Marlin firmware with machine_max_junction_deviation > 0) -static bool has_junction_deviation(const DynamicPrintConfig* printer_config) -{ - if (!printer_config) { - return false; - } - const auto gcode_flavor = printer_config->option<ConfigOptionEnum<GCodeFlavor>>("gcode_flavor"); - const auto junction_dev = printer_config->option<ConfigOptionFloats>("machine_max_junction_deviation"); - return gcode_flavor && - gcode_flavor->value == GCodeFlavor::gcfMarlinFirmware && - junction_dev && - !junction_dev->values.empty() && - junction_dev->values.front() > 0.0; -} - static DynamicFilamentList dynamic_filament_list; // every slot, mixed included (per-feature *_filament_id keys) static DynamicFilamentList dynamic_physical_filament_list(true); // physical slots only (support_*, wipe_tower_filament) @@ -4774,7 +4761,7 @@ void Sidebar::update_mixed_filament_list() delete_mixed_filament_at(panel_idx); }, del_item->GetId()); - PopupMenu(&menu); + popup_menu(*this, menu); }); combo_and_btn_sizer->Add(menu_btn, 0, wxALIGN_CENTER_VERTICAL | wxLEFT, FromDIP(SidebarProps::ElementSpacing()) - FromDIP(2)); // ElementSpacing - 2 (from combo box)) @@ -8233,6 +8220,8 @@ Plater::priv::priv(Plater *q, MainFrame *main_frame) } } set_plater_dirty(true); + // A layer code changes the G-code as a setting does, so an MCP slice running meanwhile is superseded. + ++project_revision; preview->on_tick_changed(tick_event_type); @@ -16333,8 +16322,10 @@ void Plater::load_project(wxString const& filename2, update_project_dirty_from_presets(); wxGetApp().preset_bundle->export_selections(*wxGetApp().app_config); - // if res is empty no data has been loaded - if (!res.empty() && !loaded_published && (load_restore || !(strategy & LoadStrategy::Silence))) { + // Nothing was loaded when res is empty, unless the project holds only a Design-tab model, which + // loads no objects but a recipe. + const bool loaded = !res.empty() || !model().cad_recipe.empty(); + if (loaded && !loaded_published && (load_restore || !(strategy & LoadStrategy::Silence))) { BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << __LINE__ << " call set_project_filename: " << (load_restore ? originfile : filename); p->set_project_filename(load_restore ? originfile : filename); if (load_restore && originfile.IsEmpty()) { @@ -16352,11 +16343,11 @@ void Plater::load_project(wxString const& filename2, if (using_exported_file()) { BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << __LINE__ << " using ecported set project filename: " << filename; p->set_project_filename(filename); - } else if (loaded_published && !res.empty()) { + } else if (loaded_published && loaded) { // A "published" 3MF loads as a new project: its path must not become the project // filename (Save/Ctrl-S prompts for a destination instead of overwriting it); // reset() already cleared the project name, so restore the default title and keep - // the file in recents. Only on a successful load (res not empty): a failed or + // the file in recents. Only on a successful load: a failed or // cancelled load must not pollute "Recently opened". p->set_project_name(_L("Untitled")); if (!filename.IsEmpty()) @@ -16956,7 +16947,7 @@ void Plater::_calib_apply_belt_mode() changed_objects(obj_idxs); } -void Plater::calib_pa(const Calib_Params& params) +void Plater::calib_pa(const Calib_Params& params, bool skip_confirm) { // ORCA-Belt: PA Line / PA Pattern have the belt plumbing in place // (belt kinematics in world-coordinates mode draws them on the belt surface) @@ -16972,7 +16963,7 @@ void Plater::calib_pa(const Calib_Params& params) } } const auto calib_pa_name = _L("Pressure Advance Test"); - new_project(false, false, calib_pa_name); + new_project(skip_confirm, false, calib_pa_name); wxGetApp().mainframe->select_tab(TAB_ID_PREPARE); auto print_config = &wxGetApp().preset_bundle->prints.get_edited_preset().config; auto printer_config = &wxGetApp().preset_bundle->printers.get_edited_preset().config; @@ -17032,7 +17023,7 @@ void Plater::_calib_pa_pattern(const Calib_Params& params) print_config.set_key_value( "print_sequence", new ConfigOptionEnum(PrintSequence::ByLayer)); //Orca: find jerk value to use in the test - if(!has_junction_deviation(printer_config) && print_config.get_abs_value_at("default_jerk", params.extruder_id) > 0){ // we have set a jerk value + if(!has_junction_deviation(*printer_config) && print_config.get_abs_value_at("default_jerk", params.extruder_id) > 0){ // we have set a jerk value auto jerk = print_config.get_abs_value_at("outer_wall_jerk", params.extruder_id); // get outer wall jerk if (jerk == 0) // if outer wall jerk is not defined, get inner wall jerk jerk = print_config.get_abs_value_at("inner_wall_jerk", params.extruder_id); @@ -17049,7 +17040,7 @@ void Plater::_calib_pa_pattern(const Calib_Params& params) set_config_values<double, ConfigOptionFloatsNullable>(&print_config, "travel_jerk", jerk); } - if (has_junction_deviation(printer_config)){ + if (has_junction_deviation(*printer_config)){ set_config_values<double, ConfigOptionFloatsNullable>(&print_config, "default_junction_deviation", 0); } @@ -17446,7 +17437,7 @@ void adjust_settings_for_flowrate_calib(ModelObjectPtrs& objects, bool linear, i } // ORCA: Add pattern parameter -void Plater::calib_flowrate(bool is_linear, int pass, InfillPattern pattern) { +void Plater::calib_flowrate(bool is_linear, int pass, InfillPattern pattern, bool skip_confirm) { if (pass != 1 && pass != 2) return; wxString calib_name; @@ -17455,7 +17446,7 @@ void Plater::calib_flowrate(bool is_linear, int pass, InfillPattern pattern) { } else calib_name = wxString::Format(_L("Flowrate Test - Pass%d"), pass); - if (new_project(false, false, calib_name) == wxID_CANCEL) + if (new_project(skip_confirm, false, calib_name) == wxID_CANCEL) return; wxGetApp().mainframe->select_tab(TAB_ID_PREPARE); @@ -17490,17 +17481,7 @@ void Plater::calib_flowrate(bool is_linear, int pass, InfillPattern pattern) { } -// The belt provini tower (Calib_Params::test_model 1) is one embossed model per -// temperature range. -static std::string belt_temp_tower_asset(const Calib_Params ¶ms) -{ - const int t_start = (int) lround(params.start); - const int t_end = (int) lround(params.end); - return Slic3r::resources_dir() + "/calib/temperature_tower/belt_temp_tower_" + - std::to_string(t_start) + "_" + std::to_string(t_end) + ".stl"; -} - -void Plater::calib_temp(const Calib_Params& params) { +void Plater::calib_temp(const Calib_Params& params, bool skip_confirm) { constexpr double base_temp_tower_nozzle_diameter = 0.4; constexpr double base_temp_tower_block_height = 10.0; constexpr int base_temp_tower_temp_step = 5; @@ -17523,7 +17504,7 @@ void Plater::calib_temp(const Calib_Params& params) { } const auto calib_temp_name = _L("Nozzle temperature test"); - new_project(false, false, calib_temp_name); + new_project(skip_confirm, false, calib_temp_name); wxGetApp().mainframe->select_tab(TAB_ID_PREPARE); if (params.mode != CalibMode::Calib_Temp_Tower) return; @@ -17793,10 +17774,10 @@ void Plater::_calib_temp_belt_sectioned(const Calib_Params& params, double belt_ p->background_process.fff_print()->set_calib_params(params); } -void Plater::calib_max_vol_speed(const Calib_Params& params) +void Plater::calib_max_vol_speed(const Calib_Params& params, bool skip_confirm) { const auto calib_vol_speed_name = _L("Max volumetric speed test"); - new_project(false, false, calib_vol_speed_name); + new_project(skip_confirm, false, calib_vol_speed_name); wxGetApp().mainframe->select_tab(TAB_ID_PREPARE); if (params.mode != CalibMode::Calib_Vol_speed_Tower) return; @@ -17874,10 +17855,10 @@ void Plater::calib_max_vol_speed(const Calib_Params& params) p->background_process.fff_print()->set_calib_params(new_params); } -void Plater::calib_retraction(const Calib_Params& params) +void Plater::calib_retraction(const Calib_Params& params, bool skip_confirm) { const auto calib_retraction_name = _L("Retraction"); - new_project(false, false, calib_retraction_name); + new_project(skip_confirm, false, calib_retraction_name); wxGetApp().mainframe->select_tab(TAB_ID_PREPARE); if (params.mode != CalibMode::Calib_Retraction_tower) return; @@ -17937,10 +17918,10 @@ void Plater::calib_retraction(const Calib_Params& params) p->background_process.fff_print()->set_calib_params(params); } -void Plater::calib_VFA(const Calib_Params& params) +void Plater::calib_VFA(const Calib_Params& params, bool skip_confirm) { const auto calib_vfa_name = _L("VFA test"); - new_project(false, false, calib_vfa_name); + new_project(skip_confirm, false, calib_vfa_name); wxGetApp().mainframe->select_tab(TAB_ID_PREPARE); if (params.mode != CalibMode::Calib_VFA_Tower) return; @@ -18021,10 +18002,10 @@ void Plater::calib_VFA(const Calib_Params& params) p->background_process.fff_print()->set_calib_params(calib_params); } -void Plater::calib_input_shaping_freq(const Calib_Params& params) +void Plater::calib_input_shaping_freq(const Calib_Params& params, bool skip_confirm) { const auto calib_input_shaping_name = _L("Input shaping Frequency test"); - new_project(false, false, calib_input_shaping_name); + new_project(skip_confirm, false, calib_input_shaping_name); wxGetApp().mainframe->select_tab(TAB_ID_PREPARE); if (params.mode != CalibMode::Calib_Input_shaping_freq) return; @@ -18038,7 +18019,7 @@ void Plater::calib_input_shaping_freq(const Calib_Params& params) auto printer_config = &wxGetApp().preset_bundle->printers.get_edited_preset().config; const auto gcode_flavor_option = printer_config->option<ConfigOptionEnum<GCodeFlavor>>("gcode_flavor"); - if (has_junction_deviation(printer_config)) { + if (has_junction_deviation(*printer_config)) { printer_config->set_key_value("machine_max_junction_deviation", new ConfigOptionFloats {(std::max(printer_config->option<ConfigOptionFloats>("machine_max_junction_deviation")->values.front(), 0.25))}); set_config_values<double, ConfigOptionFloatsNullable>(print_config, "default_junction_deviation", 0); } else { @@ -18089,10 +18070,10 @@ void Plater::calib_input_shaping_freq(const Calib_Params& params) p->background_process.fff_print()->set_calib_params(params); } -void Plater::calib_input_shaping_damp(const Calib_Params& params) +void Plater::calib_input_shaping_damp(const Calib_Params& params, bool skip_confirm) { const auto calib_input_shaping_name = _L("Input shaping Damping test"); - new_project(false, false, calib_input_shaping_name); + new_project(skip_confirm, false, calib_input_shaping_name); wxGetApp().mainframe->select_tab(TAB_ID_PREPARE); if (params.mode != CalibMode::Calib_Input_shaping_damp) return; @@ -18106,7 +18087,7 @@ void Plater::calib_input_shaping_damp(const Calib_Params& params) auto printer_config = &wxGetApp().preset_bundle->printers.get_edited_preset().config; const auto gcode_flavor_option = printer_config->option<ConfigOptionEnum<GCodeFlavor>>("gcode_flavor"); - if (has_junction_deviation(printer_config)) { + if (has_junction_deviation(*printer_config)) { printer_config->set_key_value("machine_max_junction_deviation", new ConfigOptionFloats {(std::max(printer_config->option<ConfigOptionFloats>("machine_max_junction_deviation")->values.front(), 0.25))}); set_config_values<double, ConfigOptionFloatsNullable>(print_config, "default_junction_deviation", 0); } else { @@ -18156,10 +18137,10 @@ void Plater::calib_input_shaping_damp(const Calib_Params& params) p->background_process.fff_print()->set_calib_params(params); } -void Plater::Calib_Cornering(const Calib_Params& params) +void Plater::Calib_Cornering(const Calib_Params& params, bool skip_confirm) { const auto Calib_Cornering = _L("Cornering test"); - new_project(false, false, Calib_Cornering); + new_project(skip_confirm, false, Calib_Cornering); wxGetApp().mainframe->select_tab(TAB_ID_PREPARE); if (params.mode != CalibMode::Calib_Cornering) return; @@ -18175,7 +18156,7 @@ void Plater::Calib_Cornering(const Calib_Params& params) auto filament_config = &wxGetApp().preset_bundle->filaments.get_edited_preset().config; auto printer_config = &wxGetApp().preset_bundle->printers.get_edited_preset().config; - if (has_junction_deviation(printer_config)) { + if (has_junction_deviation(*printer_config)) { printer_config->set_key_value("machine_max_junction_deviation", new ConfigOptionFloats{params.end}); set_config_values<double, ConfigOptionFloatsNullable>(print_config, "default_junction_deviation", 0); } else { @@ -19498,7 +19479,7 @@ static long GetNumberFromUser( const wxString& msg, #endif } -void Plater::set_number_of_copies(/*size_t num*/) +void Plater::set_number_of_copies() { int obj_idx = p->get_selected_object_idx(); if (obj_idx == -1) @@ -19511,9 +19492,18 @@ void Plater::set_number_of_copies(/*size_t num*/) if (num < 0) return; + set_number_of_copies(num); +} + +void Plater::set_number_of_copies(int num) +{ + int obj_idx = p->get_selected_object_idx(); + if (obj_idx == -1) + return; + Plater::TakeSnapshot snapshot(this, (boost::format("Set numbers of copies to %1%")%num).str()); - int diff = num - (int)model_object->instances.size(); + int diff = num - (int)p->model.objects[obj_idx]->instances.size(); if (diff > 0) increase_instances(diff); else if (diff < 0) @@ -23292,7 +23282,6 @@ bool Plater::plugins_block_slicing() const } void Plater::open_platesettings_dialog(wxCommandEvent& evt) { - int plate_index = evt.GetInt(); PlateSettingsDialog dlg(this, _L("Plate Settings"), evt.GetString() == "only_layer_sequence"); PartPlate* curr_plate = p->partplate_list.get_curr_plate(); dlg.sync_bed_type(curr_plate->get_bed_type()); @@ -23319,51 +23308,13 @@ void Plater::open_platesettings_dialog(wxCommandEvent& evt) { dlg.sync_spiral_mode(curr_plate->get_spiral_vase_mode(), !curr_plate->has_spiral_mode_config()); - dlg.Bind(EVT_SET_BED_TYPE_CONFIRM, [this, plate_index, &dlg](wxCommandEvent& e) { - PartPlate* curr_plate = p->partplate_list.get_curr_plate(); - BedType old_bed_type = curr_plate->get_bed_type(); - auto bt_sel = dlg.get_bed_type_choice(); - if (old_bed_type != bt_sel) { - curr_plate->set_bed_type(bt_sel); - update_project_dirty_from_presets(); - set_plater_dirty(true); - } - BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format("select bed type %1% for plate %2% at plate side") % bt_sel % plate_index; - - if (dlg.get_first_layer_print_seq_choice() != 0) - curr_plate->set_first_layer_print_sequence(dlg.get_first_layer_print_seq()); - else - curr_plate->set_first_layer_print_sequence({}); - - if (dlg.get_other_layers_print_seq_choice() != 0) - curr_plate->set_other_layers_print_sequence(dlg.get_other_layers_print_seq_infos()); - else - curr_plate->set_other_layers_print_sequence({}); - - int ps_sel = dlg.get_print_seq_choice(); - if (ps_sel != 0) - curr_plate->set_print_seq(PrintSequence(ps_sel - 1)); - else - curr_plate->set_print_seq(PrintSequence::ByDefault); - - int spiral_sel = dlg.get_spiral_mode_choice(); - if (spiral_sel == 1) { - curr_plate->set_spiral_vase_mode(true, false); - } - else if (spiral_sel == 2) { - curr_plate->set_spiral_vase_mode(false, false); - } - else { - curr_plate->set_spiral_vase_mode(false, true); - } - - update_project_dirty_from_presets(); - set_plater_dirty(true); - BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format("select print sequence %1% for plate %2% at plate side") % ps_sel % plate_index; - auto plate_config = *(curr_plate->config()); - wxGetApp().plater()->config_change_notification(plate_config, std::string("print_sequence")); - update(); - wxGetApp().obj_list()->update_selections(); + dlg.Bind(EVT_SET_BED_TYPE_CONFIRM, [this, &dlg](wxCommandEvent& e) { + const int ps_sel = dlg.get_print_seq_choice(); + apply_plate_settings(p->partplate_list.get_curr_plate_index(), dlg.get_bed_type_choice(), + dlg.get_first_layer_print_seq_choice() != 0 ? dlg.get_first_layer_print_seq() : std::vector<int>(), + dlg.get_other_layers_print_seq_choice() != 0 ? dlg.get_other_layers_print_seq_infos() : + std::vector<LayerPrintSequence>(), + ps_sel != 0 ? PrintSequence(ps_sel - 1) : PrintSequence::ByDefault, dlg.get_spiral_mode_choice()); }); dlg.set_plate_name(from_u8(curr_plate->get_plate_name())); @@ -23371,6 +23322,39 @@ void Plater::open_platesettings_dialog(wxCommandEvent& evt) { rename_plate(p->partplate_list.get_curr_plate_index(), dlg.get_plate_name().ToUTF8().data()); } +void Plater::apply_plate_settings(int plate_index, BedType bed_type, const std::vector<int>& first_layer_seq, + const std::vector<LayerPrintSequence>& other_layers_seq, PrintSequence print_seq, int spiral_choice) +{ + PartPlate* plate = p->partplate_list.get_plate(plate_index); + if (plate == nullptr) + return; + if (plate->get_bed_type() != bed_type) { + plate->set_bed_type(bed_type); + update_project_dirty_from_presets(); + set_plater_dirty(true); + } + BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format("select bed type %1% for plate %2% at plate side") % bed_type % plate_index; + + plate->set_first_layer_print_sequence(first_layer_seq); + plate->set_other_layers_print_sequence(other_layers_seq); + plate->set_print_seq(print_seq); + + if (spiral_choice == 1) + plate->set_spiral_vase_mode(true, false); + else if (spiral_choice == 2) + plate->set_spiral_vase_mode(false, false); + else + plate->set_spiral_vase_mode(false, true); + + update_project_dirty_from_presets(); + set_plater_dirty(true); + BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format("select print sequence %1% for plate %2% at plate side") % int(print_seq) % plate_index; + auto plate_config = *(plate->config()); + config_change_notification(plate_config, std::string("print_sequence")); + update(); + wxGetApp().obj_list()->update_selections(); +} + void Plater::open_filament_map_setting_dialog(wxCommandEvent &evt) { PartPlate* curr_plate = p->partplate_list.get_curr_plate(); @@ -23676,7 +23660,7 @@ int Plater::select_plate_by_hover_id(int hover_id, bool right_click, bool isModi set_plater_dirty(true); update(); }); - p->view3D->get_canvas3d()->get_wxglcanvas()->PopupMenu(&menu); + popup_menu(*p->view3D->get_canvas3d()->get_wxglcanvas(), menu); ret = 1; // signal to caller: popup was shown, suppress plate context menu } else { // Left-click: always cycles mode. The IMEX ghost renderer exposes @@ -24378,7 +24362,9 @@ bool Plater::PopupMenu(wxMenu *menu, const wxPoint& pos) SuppressBackgroundProcessingUpdate sbpu; // When tracking a pop-up menu, postpone error messages from the slicing result. m_tracking_popup_menu = true; - bool out = wxGetApp().mainframe->PopupMenu(menu, pos); + // A menu built for this popup alone is freed once it has closed. + const std::unique_ptr<wxMenu> transient = p->menus.take_transient(menu); + bool out = popup_menu(*wxGetApp().mainframe, *menu, pos); m_tracking_popup_menu = false; if (! m_tracking_popup_menu_error_message.empty()) { // Don't know whether the CallAfter is necessary, but it should not hurt. diff --git a/src/slic3r/GUI/Plater.hpp b/src/slic3r/GUI/Plater.hpp index fbed476808..29e1723035 100644 --- a/src/slic3r/GUI/Plater.hpp +++ b/src/slic3r/GUI/Plater.hpp @@ -2,6 +2,7 @@ #define slic3r_Plater_hpp_ #include "libslic3r/Config.hpp" +#include "libslic3r/ParameterUtils.hpp" #include "libslic3r/PrintConfig.hpp" #include <cstddef> #include <map> @@ -409,16 +410,18 @@ public: // toolpath geometry at load time. Keeps the current layer range and only-gcode mode. // SoftFever - void calib_pa(const Calib_Params& params); + // Each test starts a new project; `skip_confirm` skips its prompts (save the project, keep or + // discard modified presets), keeping the modified presets, for a caller that has decided both. + void calib_pa(const Calib_Params& params, bool skip_confirm = false); //ORCA: Add pattern parameter to calib_flowrate - void calib_flowrate(bool is_linear, int pass, InfillPattern pattern = ipArchimedeanChords); - void calib_temp(const Calib_Params& params); - void calib_max_vol_speed(const Calib_Params& params); - void calib_retraction(const Calib_Params& params); - void calib_VFA(const Calib_Params& params); - void calib_input_shaping_freq(const Calib_Params& params); - void calib_input_shaping_damp(const Calib_Params& params); - void Calib_Cornering(const Calib_Params& params); + void calib_flowrate(bool is_linear, int pass, InfillPattern pattern = ipArchimedeanChords, bool skip_confirm = false); + void calib_temp(const Calib_Params& params, bool skip_confirm = false); + void calib_max_vol_speed(const Calib_Params& params, bool skip_confirm = false); + void calib_retraction(const Calib_Params& params, bool skip_confirm = false); + void calib_VFA(const Calib_Params& params, bool skip_confirm = false); + void calib_input_shaping_freq(const Calib_Params& params, bool skip_confirm = false); + void calib_input_shaping_damp(const Calib_Params& params, bool skip_confirm = false); + void Calib_Cornering(const Calib_Params& params, bool skip_confirm = false); BuildVolume_Type get_build_volume_type() const; @@ -562,7 +565,10 @@ public: void remove_selected(); void increase_instances(size_t num = 1); void decrease_instances(size_t num = 1); - void set_number_of_copies(/*size_t num*/); + // Asks for the selected object's number of instances. + void set_number_of_copies(); + // Gives the selected object `num` instances in one undo step; 0 deletes it, as the dialog's 0 does. + void set_number_of_copies(int num); void fill_bed_with_copies(); void fill_bed_with_instances(); bool is_selection_empty() const; @@ -638,6 +644,11 @@ public: void print_job_finished(wxCommandEvent &evt); void send_job_finished(wxCommandEvent& evt); void open_platesettings_dialog(wxCommandEvent& evt); + // What the Plate Settings dialog's OK sets on a plate: the bed type, the first and the other layers' + // filament orders (empty for Auto), the print sequence and spiral vase (0 as the global setting, + // 1 on, which asks for confirmation, 2 off), then the dirty state and the update that follow. + void apply_plate_settings(int plate_index, BedType bed_type, const std::vector<int>& first_layer_seq, + const std::vector<LayerPrintSequence>& other_layers_seq, PrintSequence print_seq, int spiral_choice); void open_filament_map_setting_dialog(wxCommandEvent &evt); void on_change_color_mode(SimpleEvent& evt); void eject_drive(); diff --git a/src/slic3r/GUI/Preferences.cpp b/src/slic3r/GUI/Preferences.cpp index b75066129a..4e502ac4ee 100644 --- a/src/slic3r/GUI/Preferences.cpp +++ b/src/slic3r/GUI/Preferences.cpp @@ -348,7 +348,7 @@ std::tuple<wxBoxSizer*, ComboBox*> PreferencesDialog::create_item_combobox_base( auto combobox = new ::ComboBox(m_parent, wxID_ANY, wxEmptyString, wxDefaultPosition, DESIGN_LARGE_COMBOBOX_SIZE, 0, nullptr, wxCB_READONLY); combobox->GetDropDown().SetUseContentWidth(true); combobox->SetToolTip(tip); - combobox->SetName(param); // select_tab() finds the row by this name + combobox->SetName(param); // select_tab() and automation find the control by its AppConfig key std::vector<wxString>::iterator iter; for (iter = vlist.begin(); iter != vlist.end(); iter++) { @@ -464,6 +464,7 @@ wxBoxSizer *PreferencesDialog::create_item_language_combobox(wxString title, wxS auto combobox = new ::ComboBox(m_parent, wxID_ANY, wxEmptyString, wxDefaultPosition, DESIGN_LARGE_COMBOBOX_SIZE, 0, nullptr, wxCB_READONLY); combobox->GetDropDown().SetUseContentWidth(true); combobox->SetToolTip(tip); + combobox->SetName(param); auto language = app_config->get(param); m_current_language_selected = -1; @@ -621,6 +622,7 @@ wxBoxSizer *PreferencesDialog::create_item_region_combobox(wxString title, wxStr auto combobox = new ::ComboBox(m_parent, wxID_ANY, wxEmptyString, wxDefaultPosition, DESIGN_LARGE_COMBOBOX_SIZE, 0, nullptr, wxCB_READONLY); combobox->GetDropDown().SetUseContentWidth(true); combobox->SetToolTip(tip); + combobox->SetName("region"); m_sizer->Add(combobox, 0, wxALIGN_CENTER); @@ -695,6 +697,7 @@ wxBoxSizer *PreferencesDialog::create_item_loglevel_combobox(wxString title, wxS auto combobox = new ::ComboBox(m_parent, wxID_ANY, wxEmptyString, wxDefaultPosition, DESIGN_COMBOBOX_SIZE, 0, nullptr, wxCB_READONLY); combobox->GetDropDown().SetUseContentWidth(true); combobox->SetToolTip(tip); + combobox->SetName("log_severity_level"); std::vector<wxString>::iterator iter; for (iter = vlist.begin(); iter != vlist.end(); iter++) { combobox->Append(*iter); } @@ -727,6 +730,7 @@ wxBoxSizer *PreferencesDialog::create_item_input(wxString title, wxString title2 wxTextValidator validator(wxFILTER_DIGITS); input->SetToolTip(tip); input->GetTextCtrl()->SetValidator(validator); + input->SetName(param); auto second_title = new wxStaticText(m_parent, wxID_ANY, title2, wxDefaultPosition, wxDefaultSize, 0); second_title->SetForegroundColour(DESIGN_GRAY900_COLOR); @@ -763,6 +767,7 @@ wxBoxSizer *PreferencesDialog::create_item_spinctrl(wxString title, wxString tit auto input = new SpinInput(m_parent, wxEmptyString, side_label, wxDefaultPosition, DESIGN_INPUT_SIZE, wxSP_ARROW_KEYS, min, max, stoi(app_config->get(param))); input->SetToolTip(tip); + input->SetName(param); // ORCA: this one is only meaningful while the dimming it controls is enabled if (param == "preview_dim_previous_layers_brightness") { @@ -821,6 +826,7 @@ wxBoxSizer *PreferencesDialog::create_camera_orbit_mult_input(wxString title, wx wxTextValidator validator(wxFILTER_NUMERIC); input->SetToolTip(tip); input->GetTextCtrl()->SetValidator(validator); + input->SetName(param); m_sizer->Add(input, 0, wxALIGN_CENTER_VERTICAL); @@ -868,6 +874,7 @@ wxBoxSizer *PreferencesDialog::create_item_decimal_input(wxString title, wxStrin wxTextValidator validator(wxFILTER_NUMERIC); input->SetToolTip(tooltip); input->GetTextCtrl()->SetValidator(validator); + input->SetName(param); m_sizer->Add(input, 0, wxALIGN_CENTER_VERTICAL); @@ -905,6 +912,7 @@ wxBoxSizer *PreferencesDialog::create_item_backup(wxString title, wxString toolt auto checkbox = new ::CheckBox(m_parent); checkbox->SetValue(app_config->get_bool("backup_switch")); checkbox->SetToolTip(tip); + checkbox->SetName("backup_switch"); checkbox->Bind(wxEVT_TOGGLEBUTTON, [this, checkbox](wxCommandEvent &e) { app_config->set_bool("backup_switch", checkbox->GetValue()); @@ -926,6 +934,7 @@ wxBoxSizer *PreferencesDialog::create_item_backup(wxString title, wxString toolt wxTextValidator validator(wxFILTER_DIGITS); input->SetToolTip(_L("The period of backup in seconds.")); input->GetTextCtrl()->SetValidator(validator); + input->SetName("backup_interval"); m_sizer->Add(checkbox, 0, wxALIGN_CENTER); m_sizer->Add(input , 0, wxALIGN_CENTER_VERTICAL | wxLEFT, FromDIP(5)); @@ -968,6 +977,7 @@ wxBoxSizer *PreferencesDialog::create_item_auto_reslice(wxString title, wxString auto checkbox = new ::CheckBox(m_parent); checkbox->SetValue(app_config->get_bool("auto_slice_after_change")); checkbox->SetToolTip(checkbox_tooltip); + checkbox->SetName("auto_slice_after_change"); wxString delay_value = app_config->get("auto_slice_change_delay_seconds"); if (delay_value.empty()) @@ -980,6 +990,7 @@ wxBoxSizer *PreferencesDialog::create_item_auto_reslice(wxString title, wxString wxTextValidator validator(wxFILTER_DIGITS); input->SetToolTip(delay_tooltip); input->GetTextCtrl()->SetValidator(validator); + input->SetName("auto_slice_change_delay_seconds"); m_sizer->Add(checkbox, 0, wxALIGN_CENTER); m_sizer->Add(input , 0, wxALIGN_CENTER_VERTICAL | wxLEFT, FromDIP(5)); @@ -1029,6 +1040,7 @@ wxBoxSizer* PreferencesDialog::create_item_darkmode(wxString title,wxString tool auto checkbox = new ::CheckBox(m_parent); checkbox->SetValue((app_config->get(param) == "1") ? true : false); checkbox->SetToolTip(tip); + checkbox->SetName(param); m_dark_mode_ckeckbox = checkbox; m_sizer->Add(checkbox, 0, wxALIGN_CENTER); @@ -1076,6 +1088,7 @@ wxBoxSizer *PreferencesDialog::create_item_checkbox(wxString title, wxString too auto checkbox = new ::CheckBox(m_parent); checkbox->SetValue(app_config->get_bool(param)); checkbox->SetToolTip(tip); + checkbox->SetName(param); if (param == "sync_user_preset") { m_sync_user_preset_checkbox = checkbox; } if (param == SETTING_OPENGL_SKIP_IDENTICAL_FRAMES) { m_skip_identical_frames_checkbox = checkbox; } @@ -1388,6 +1401,7 @@ wxBoxSizer *PreferencesDialog::create_item_mcp_server(wxString title, wxString t auto checkbox = new ::CheckBox(m_parent); checkbox->SetValue(app_config->get_bool("mcp_enabled") || (mcp != nullptr && mcp->serving())); checkbox->SetToolTip(tooltip); + checkbox->SetName("mcp_enabled"); // The dot sits on the first line, so a reason that wraps reads as one block beside it. m_mcp_status_dot = new ::Label(m_parent, wxString(wxUniChar(0x25CF))); @@ -1630,6 +1644,7 @@ wxBoxSizer *PreferencesDialog::create_item_network_plugin_version(wxString title m_network_version_combo = new ::ComboBox(m_parent, wxID_ANY, wxEmptyString, wxDefaultPosition, DESIGN_LARGE_COMBOBOX_SIZE, 0, nullptr, wxCB_READONLY); m_network_version_combo->GetDropDown().SetUseContentWidth(true); m_network_version_combo->SetToolTip(tooltip); + m_network_version_combo->SetName(SETTING_NETWORK_PLUGIN_VERSION); std::string current_version = app_config->get_network_plugin_version(); if (current_version.empty()) { @@ -1892,6 +1907,10 @@ void PreferencesDialog::select_tab(PreferencesTab tab, const std::string& option wxWindow* control = option.empty() ? nullptr : m_parent->FindWindow(wxString(option)); if (control == nullptr) return; + // An option on another tab than the one asked for is shown on its own tab, where it can be seen and used. + for (size_t i = 0; i < f_sizers.size(); ++i) + if (int(i) != m_pref_tabs->GetSelection() && f_sizers[i]->GetItem(control, true) != nullptr) + m_pref_tabs->SelectItem(int(i)); int unit = 1; m_parent->GetScrollPixelsPerUnit(nullptr, &unit); m_parent->Scroll(wxDefaultCoord, (m_parent->CalcUnscrolledPosition(control->GetPosition()).y - FromDIP(10)) / unit); @@ -2689,7 +2708,7 @@ void PreferencesDialog::create_items() ////////////////////////// //// DEVELOPER TAB ///////////////////////////////////// - m_pref_tabs->AppendItem(_L("Developer")); + m_tab_index[PreferencesTab::Developer] = m_pref_tabs->AppendItem(_L("Developer")); f_sizers.push_back(new wxFlexGridSizer(1, 1, v_gap, 0)); g_sizer = f_sizers.back(); g_sizer->AddGrowableCol(0, 1); diff --git a/src/slic3r/GUI/Preferences.hpp b/src/slic3r/GUI/Preferences.hpp index 6c3d6d36aa..0802b78bf4 100644 --- a/src/slic3r/GUI/Preferences.hpp +++ b/src/slic3r/GUI/Preferences.hpp @@ -39,8 +39,8 @@ namespace Slic3r { namespace GUI { #define DESIGN_INPUT_SIZE wxSize(FromDIP(120), -1) #define DESIGN_LEFT_MARGIN 25 -// The tabs other dialogs open Preferences on. -enum class PreferencesTab { General, Control, Graphics, Online }; +// The tabs other dialogs and the Speed Dial's open_preferences open Preferences on. +enum class PreferencesTab { General, Control, Graphics, Online, Developer }; class PreferencesDialog : public DPIDialog { @@ -74,7 +74,8 @@ public: ~PreferencesDialog(); - void select_tab(PreferencesTab tab, const std::string& option = {}); // and scrolls a combobox option's row into view, focused + // Shows `tab`, or the tab of `option` (a control named after its AppConfig key), scrolled to that control and focused. + void select_tab(PreferencesTab tab, const std::string& option = {}); wxString m_backup_interval_time; wxTimer m_filament_height_timer; diff --git a/src/slic3r/GUI/PrintHostDialogs.cpp b/src/slic3r/GUI/PrintHostDialogs.cpp index 39ddff648c..b6465f3457 100644 --- a/src/slic3r/GUI/PrintHostDialogs.cpp +++ b/src/slic3r/GUI/PrintHostDialogs.cpp @@ -15,6 +15,8 @@ #include "libslic3r/PrintConfig.hpp" #include "libslic3r/Config.hpp" #include <limits> +#include <optional> +#include <boost/cstdint.hpp> #include <wx/colour.h> #include <wx/event.h> @@ -1341,32 +1343,48 @@ PrintHostQueueDialog::PrintHostQueueDialog(wxWindow *parent) }); } -void PrintHostQueueDialog::append_job(const PrintHostJob &job) +void PrintHostQueueDialog::append_job(const std::string &host, const boost::filesystem::path &upload_path, std::optional<boost::uintmax_t> size) { - wxCHECK_RET(!job.empty(), "PrintHostQueueDialog: Attempt to append an empty job"); - wxVector<wxVariant> fields; fields.push_back(wxVariant(wxString::Format("%d", job_list->GetItemCount() + 1))); fields.push_back(wxVariant(0)); fields.push_back(wxVariant(_L("Queued"))); - fields.push_back(wxVariant(job.printhost->get_host())); - boost::system::error_code ec; - boost::uintmax_t size_i = boost::filesystem::file_size(job.upload_data.source_path, ec); + fields.push_back(wxVariant(host)); + const float size_mb = size ? (float)*size / 1024 / 1024 : 0.f; std::stringstream stream; - if (ec) { + if (size) + stream << std::fixed << std::setprecision(2) << size_mb << "MB"; + else stream << "unknown"; - size_i = 0; - BOOST_LOG_TRIVIAL(error) << ec.message(); - } else - stream << std::fixed << std::setprecision(2) << ((float)size_i / 1024 / 1024) << "MB"; fields.push_back(wxVariant(stream.str())); - fields.push_back(wxVariant(from_path(job.upload_data.upload_path))); + fields.push_back(wxVariant(from_path(upload_path))); fields.push_back(wxVariant("")); job_list->AppendItem(fields, static_cast<wxUIntPtr>(ST_NEW)); // Both strings are UTF-8 encoded. - upload_names.emplace_back(job.printhost->get_host(), job.upload_data.upload_path.string()); + upload_names.emplace_back(host, upload_path.string()); - wxGetApp().notification_manager()->push_upload_job_notification(job_list->GetItemCount(), (float)size_i / 1024 / 1024, job.upload_data.upload_path.string(), job.printhost->get_host()); + wxGetApp().notification_manager()->push_upload_job_notification(job_list->GetItemCount(), size_mb, upload_path.string(), host); +} + +size_t PrintHostQueueDialog::job_count() const +{ + return size_t(job_list->GetItemCount()); +} + +PrintHostQueueDialog::JobInfo PrintHostQueueDialog::job_info(size_t row) const +{ + // In JobState order. + static const char *const state_names[] = {"queued", "uploading", "error", "cancelling", "cancelled", "completed"}; + JobInfo info; + const auto state = static_cast<JobState>(job_list->GetItemData(job_list->RowToItem(int(row)))); + info.state = state_names[state]; + wxVariant progress; + job_list->GetValue(progress, unsigned(row), COL_PROGRESS); + info.progress = int(progress.GetLong()); + info.host = into_u8(job_list->GetTextValue(unsigned(row), COL_HOST)); + info.filename = into_u8(job_list->GetTextValue(unsigned(row), COL_FILENAME)); + info.error = into_u8(job_list->GetTextValue(unsigned(row), COL_ERRORMSG)); + return info; } void PrintHostQueueDialog::on_dpi_changed(const wxRect &suggested_rect) diff --git a/src/slic3r/GUI/PrintHostDialogs.hpp b/src/slic3r/GUI/PrintHostDialogs.hpp index b398a97eb4..30e9877f2c 100644 --- a/src/slic3r/GUI/PrintHostDialogs.hpp +++ b/src/slic3r/GUI/PrintHostDialogs.hpp @@ -3,9 +3,11 @@ #include <map> #include <cstddef> +#include <optional> #include <string> #include <utility> #include <vector> +#include <boost/cstdint.hpp> #include <boost/filesystem/path.hpp> #include <wx/colour.h> @@ -88,9 +90,23 @@ public: PrintHostQueueDialog(wxWindow *parent); - void append_job(const PrintHostJob &job); + // Adds the row and notification of a job sent to `host` as `upload_path`; `size` is the source file's size in + // bytes, if it could be read. UI thread. + void append_job(const std::string &host, const boost::filesystem::path &upload_path, std::optional<boost::uintmax_t> size); void get_active_jobs(std::vector<std::pair<std::string, std::string>>& ret); + // A row as the list shows it, for readers outside the dialog (MCP's get_state.uploads). + struct JobInfo + { + std::string state; // queued, uploading, error, cancelling, cancelled or completed + int progress = 0; + std::string host; + std::string filename; + std::string error; + }; + size_t job_count() const; + JobInfo job_info(size_t row) const; + virtual bool Show(bool show = true) override { if(!show) diff --git a/src/slic3r/GUI/PublishSettingsDialog.cpp b/src/slic3r/GUI/PublishSettingsDialog.cpp index 740f6edff6..a6e1ac69d5 100644 --- a/src/slic3r/GUI/PublishSettingsDialog.cpp +++ b/src/slic3r/GUI/PublishSettingsDialog.cpp @@ -3,6 +3,7 @@ #include "GUI_App.hpp" #include "MainFrame.hpp" #include "MsgDialog.hpp" +#include "SyntheticInput.hpp" #include "I18N.hpp" #include "Tab.hpp" #include "ConfigValueFormatter.hpp" @@ -2079,7 +2080,7 @@ void PublishSettingsDialog::show_menu(wxMouseEvent& evt) return; wxPoint screen_pos = src->ClientToScreen(evt.GetPosition()); wxPoint local_pos = ScreenToClient(screen_pos); - PopupMenu(&m, local_pos); + popup_menu(*this, m, local_pos); } void PublishSettingsDialog::apply_selection(const std::vector<std::string>& published_keys, diff --git a/src/slic3r/GUI/SavePresetDialog.cpp b/src/slic3r/GUI/SavePresetDialog.cpp index 46d7088749..966e767417 100644 --- a/src/slic3r/GUI/SavePresetDialog.cpp +++ b/src/slic3r/GUI/SavePresetDialog.cpp @@ -423,7 +423,7 @@ void SavePresetDialog::input_name_from_other(std::string new_preset_name) { void SavePresetDialog::confirm_from_other() { for (Item *item : m_items) - if (item->type() == Preset::TYPE_PRINTER) update_physical_printers(item->preset_name()); + if (item->type() == Preset::TYPE_PRINTER) update_physical_printers(m_action, item->preset_name()); } // BBS: add project relate @@ -528,22 +528,22 @@ void SavePresetDialog::on_dpi_changed(const wxRect &suggested_rect) Refresh(); } -void SavePresetDialog::update_physical_printers(const std::string &preset_name) +void SavePresetDialog::update_physical_printers(ActionType action, const std::string &preset_name) { - if (m_action == UndefAction) return; + if (action == UndefAction) return; PhysicalPrinterCollection &physical_printers = wxGetApp().preset_bundle->physical_printers; if (!physical_printers.has_selection()) return; std::string printer_preset_name = physical_printers.get_selected_printer_preset_name(); - if (m_action == Switch) + if (action == Switch) // unselect physical printer, if it was selected physical_printers.unselect_printer(); else { PhysicalPrinter printer = physical_printers.get_selected_printer(); - if (m_action == ChangePreset) printer.delete_preset(printer_preset_name); + if (action == ChangePreset) printer.delete_preset(printer_preset_name); if (printer.add_preset(preset_name)) physical_printers.save_printer(printer); @@ -554,7 +554,7 @@ void SavePresetDialog::update_physical_printers(const std::string &preset_name) void SavePresetDialog::accept(wxCommandEvent &event) { for (Item *item : m_items) - if (item->type() == Preset::TYPE_PRINTER) update_physical_printers(item->preset_name()); + if (item->type() == Preset::TYPE_PRINTER) update_physical_printers(m_action, item->preset_name()); EndModal(wxID_OK); } diff --git a/src/slic3r/GUI/SavePresetDialog.hpp b/src/slic3r/GUI/SavePresetDialog.hpp index 4a1e785999..c6ee3151a3 100644 --- a/src/slic3r/GUI/SavePresetDialog.hpp +++ b/src/slic3r/GUI/SavePresetDialog.hpp @@ -37,6 +37,9 @@ PresetNameStatus check_preset_name(const PresetCollection &presets, const std::s class SavePresetDialog : public DPIDialog { +public: + // What happens to the selected physical printer when a printer preset is saved; the dialog + // offers the first three, ChangePreset by default. enum ActionType { ChangePreset, @@ -45,6 +48,11 @@ class SavePresetDialog : public DPIDialog UndefAction }; + // Applies `action` to the selected physical printer for the printer preset saved as `preset_name`. + // The dialog's OK passes the action chosen; a save made without the dialog passes ChangePreset. + static void update_physical_printers(ActionType action, const std::string &preset_name); + +private: class Item : public wxWindow { public: @@ -130,7 +138,6 @@ protected: private: void build(std::vector<Preset::Type> types, std::string suffix = ""); void on_select_cancel(wxCommandEvent &event); - void update_physical_printers(const std::string &preset_name); void accept(wxCommandEvent &event); }; diff --git a/src/slic3r/GUI/SyntheticInput.cpp b/src/slic3r/GUI/SyntheticInput.cpp index 7955c83bc8..5825da4db8 100644 --- a/src/slic3r/GUI/SyntheticInput.cpp +++ b/src/slic3r/GUI/SyntheticInput.cpp @@ -1,10 +1,14 @@ #include "SyntheticInput.hpp" +#include <wx/gdicmn.h> #include <wx/mousestate.h> #include <wx/utils.h> +#include <wx/window.h> #include <algorithm> +#include <functional> #include <optional> +#include <utility> #include <vector> namespace Slic3r { namespace GUI { @@ -13,6 +17,7 @@ namespace { std::vector<int>& held_keys() { static std::vector<int> keys; return keys; } std::optional<wxMouseState>& held_mouse() { static std::optional<wxMouseState> mouse; return mouse; } +std::function<bool(wxMenu&, wxWindow&)>& menu_capture() { static std::function<bool(wxMenu&, wxWindow&)> capture; return capture; } // The modifier a key code stands for, so a held Shift also reads as WXK_SHIFT etc. bool same_key(int held, int asked) @@ -61,8 +66,18 @@ void clear() held_mouse().reset(); } +void set_menu_capture(std::function<bool(wxMenu& menu, wxWindow& owner)> capture) { menu_capture() = std::move(capture); } + } // namespace SyntheticInput +bool popup_menu(wxWindow& owner, wxMenu& menu, const wxPoint& pos) +{ + // A copy: the capture may run a command whose nested event loop replaces or clears it. + if (const auto capture = menu_capture(); capture && capture(menu, owner)) + return true; + return owner.PopupMenu(&menu, pos); +} + bool get_key_state(wxKeyCode key) { if (SyntheticInput::is_key_down(int(key))) diff --git a/src/slic3r/GUI/SyntheticInput.hpp b/src/slic3r/GUI/SyntheticInput.hpp index 43cbf0f6f2..c8b66e4919 100644 --- a/src/slic3r/GUI/SyntheticInput.hpp +++ b/src/slic3r/GUI/SyntheticInput.hpp @@ -1,8 +1,14 @@ #pragma once #include <wx/defs.h> +#include <wx/gdicmn.h> #include <wx/mousestate.h> +#include <functional> + +class wxMenu; +class wxWindow; + namespace Slic3r { namespace GUI { // Input state that automation (the MCP server) holds down while it synthesizes a gesture. @@ -20,8 +26,17 @@ void release_mouse(); bool is_mouse_held(); // Drops everything held, e.g. when a gesture fails half-way. void clear(); +// Popup and context menus that open while automation acts on the UI go to `capture` instead of +// being shown: a native menu loop would hold the UI thread until a person closed the menu, and on +// macOS it pauses the queued calls automation runs through. `capture` returns false to let a menu +// show. Empty unless the MCP server runs; clear() leaves it. +void set_menu_capture(std::function<bool(wxMenu& menu, wxWindow& owner)> capture); } // namespace SyntheticInput +// Shows `menu` from `owner` as wxWindow::PopupMenu() does, unless automation takes it (see +// SyntheticInput::set_menu_capture()). Every popup and context menu goes through here. +bool popup_menu(wxWindow& owner, wxMenu& menu, const wxPoint& pos = wxDefaultPosition); + // wxGetKeyState() plus the keys automation holds down. bool get_key_state(wxKeyCode key); // wxGetMouseState(), or automation's pointer while it drives one. diff --git a/src/slic3r/GUI/Tab.cpp b/src/slic3r/GUI/Tab.cpp index 94978635b5..f38dcd1599 100644 --- a/src/slic3r/GUI/Tab.cpp +++ b/src/slic3r/GUI/Tab.cpp @@ -7539,28 +7539,9 @@ bool Tab::select_preset( bool print_tab = m_presets->type() == Preset::TYPE_PRINT || m_presets->type() == Preset::TYPE_SLA_PRINT; bool printer_tab = m_presets->type() == Preset::TYPE_PRINTER; bool canceled = false; - bool no_transfer = false; + bool no_transfer = !can_transfer_changes_to(preset_name); bool technology_changed = false; m_dependent_tabs.clear(); - if ((m_presets->type() == Preset::TYPE_FILAMENT) && !preset_name.empty()) - { - Preset *to_be_selected = m_presets->find_preset(preset_name, false, true); - if (to_be_selected) { - std::string current_type, to_select_type; - ConfigOptionStrings* cur_opt = dynamic_cast <ConfigOptionStrings *>(m_presets->get_edited_preset().config.option("filament_type")); - ConfigOptionStrings* to_select_opt = dynamic_cast <ConfigOptionStrings *>(to_be_selected->config.option("filament_type")); - if (cur_opt && (cur_opt->values.size() > 0)) { - current_type = cur_opt->values[0]; - } - if (to_select_opt && (to_select_opt->values.size() > 0)) { - to_select_type = to_select_opt->values[0]; - } - if (current_type != to_select_type) - no_transfer = true; - } - } - else if (printer_tab) - no_transfer = true; if (force_no_transfer) { no_transfer = true; @@ -7817,12 +7798,56 @@ bool Tab::select_preset( return !canceled; } +bool Tab::can_transfer_changes_to(const std::string& preset_name) const +{ + if (m_presets->type() == Preset::TYPE_PRINTER) + return false; + if (m_presets->type() != Preset::TYPE_FILAMENT || preset_name.empty()) + return true; + const Preset* to_be_selected = m_presets->find_preset(preset_name, false, true); + if (to_be_selected == nullptr) + return true; + const auto first_type = [](const Preset& preset) { + const auto* opt = dynamic_cast<const ConfigOptionStrings*>(preset.config.option("filament_type")); + return opt != nullptr && !opt->values.empty() ? opt->values[0] : std::string(); + }; + return first_type(m_presets->get_edited_preset()) == first_type(*to_be_selected); +} + +// The unsaved changes UnsavedChangesDialog lists for a preset switch, all of which its Transfer moves: +// the changed options (key#index for one entry of a vector) that a settings page shows in the current mode. +static std::vector<std::string> listed_dirty_options(const PresetCollection& presets) +{ + Search::SettingsIndex& index = wxGetApp().sidebar().settings_index(); + index.sort_options_by_key(); + std::vector<std::string> listed; + for (const std::string& opt_key : presets.current_dirty_options(true)) { + int variant_index = -2; + index.get_option(opt_key, presets.type(), variant_index); + if (variant_index != -2) + listed.push_back(opt_key); + } + index.sort_options_by_label(); + return listed; +} + // If the current preset is dirty, the user is asked whether the changes may be discarded. // if the current preset was not dirty, or the user agreed to discard the changes, 1 is returned. bool Tab::may_discard_current_dirty_preset(PresetCollection *presets /*= nullptr*/, const std::string &new_printer_name /*= ""*/, bool no_transfer, bool no_transfer_variant) { if (presets == nullptr) presets = m_presets; + // An answer given ahead: Discard leaves the changes to the callers, as the dialog's Discard does, and + // Transfer moves everything the dialog would list, but only where the dialog offers Transfer. + if (m_dirty_preset_answer == DirtyPresetAnswer::Discard) + return true; + if (m_dirty_preset_answer == DirtyPresetAnswer::Transfer) { + if (no_transfer || new_printer_name.empty()) + return false; + transfer_dirty_options(presets, listed_dirty_options(*presets), no_transfer, no_transfer_variant); + return true; + } + UnsavedChangesDialog dlg(m_type, presets, new_printer_name, no_transfer); if (dlg.ShowModal() == wxID_CANCEL) return false; @@ -7863,49 +7888,54 @@ bool Tab::may_discard_current_dirty_preset(PresetCollection *presets /*= nullptr } } else if (dlg.transfer_changes()) // move selected changes - { - std::vector<std::string> selected_options = dlg.get_selected_options(); - if (!no_transfer && no_transfer_variant) { - auto & options_list = wxGetApp().get_tab(presets->type())->m_options_list; - bool has_variants = false; - for (auto &opt : selected_options) { - if (auto n = opt.find('#'); n != std::string::npos) { - auto iter = options_list.lower_bound(opt.substr(0, n)); - if (iter == options_list.end() || opt.compare(0, n, iter->first)) { - has_variants = true; - opt.clear(); - } - } - } - if (has_variants) { - auto msg = _L("Switching to a printer with different extruder types or numbers will discard or reset changes to extruder or multi-nozzle-related parameters."); - MessageDialog(wxGetApp().plater(), msg, _L("Use Modified Value"), wxOK | wxICON_WARNING).ShowModal(); - selected_options.erase(std::remove(selected_options.begin(), selected_options.end(), ""), selected_options.end()); - } - } - - if (m_type == presets->type()) // move changes for the current preset from this tab - { - if (m_type == Preset::TYPE_PRINTER) { - auto it = std::find(selected_options.begin(), selected_options.end(), "extruders_count"); - if (it != selected_options.end()) { - // erase "extruders_count" option from the list - selected_options.erase(it); - // cache the extruders count - static_cast<TabPrinter*>(this)->cache_extruder_cnt(); - } - } - - // copy selected options to the cache from edited preset - cache_config_diff(selected_options); - } - else - wxGetApp().get_tab(presets->type())->cache_config_diff(selected_options); - } + transfer_dirty_options(presets, dlg.get_selected_options(), no_transfer, no_transfer_variant); return true; } +void Tab::transfer_dirty_options(PresetCollection* presets, std::vector<std::string> selected_options, bool no_transfer, bool no_transfer_variant) +{ + if (!no_transfer && no_transfer_variant) { + auto & options_list = wxGetApp().get_tab(presets->type())->m_options_list; + bool has_variants = false; + for (auto &opt : selected_options) { + if (auto n = opt.find('#'); n != std::string::npos) { + auto iter = options_list.lower_bound(opt.substr(0, n)); + if (iter == options_list.end() || opt.compare(0, n, iter->first)) { + has_variants = true; + opt.clear(); + } + } + } + if (has_variants) { + // Only a person is told; a caller that answered ahead reads what was dropped from the presets. + if (m_dirty_preset_answer == DirtyPresetAnswer::Ask) { + auto msg = _L("Switching to a printer with different extruder types or numbers will discard or reset changes to extruder or multi-nozzle-related parameters."); + MessageDialog(wxGetApp().plater(), msg, _L("Use Modified Value"), wxOK | wxICON_WARNING).ShowModal(); + } + selected_options.erase(std::remove(selected_options.begin(), selected_options.end(), ""), selected_options.end()); + } + } + + if (m_type == presets->type()) // move changes for the current preset from this tab + { + if (m_type == Preset::TYPE_PRINTER) { + auto it = std::find(selected_options.begin(), selected_options.end(), "extruders_count"); + if (it != selected_options.end()) { + // erase "extruders_count" option from the list + selected_options.erase(it); + // cache the extruders count + static_cast<TabPrinter*>(this)->cache_extruder_cnt(); + } + } + + // copy selected options to the cache from edited preset + cache_config_diff(selected_options); + } + else + wxGetApp().get_tab(presets->type())->cache_config_diff(selected_options); +} + void Tab::clear_pages() { // invalidated highlighter, if any exists @@ -8382,7 +8412,7 @@ bool Tab::save_preset(std::string name /*= ""*/, bool detach, bool save_to_proje } // Called for a currently selected preset. -void Tab::delete_preset() +void Tab::delete_preset(bool ask) { auto current_preset = m_presets->get_selected_preset(); // Don't let the user delete the ' - default - ' configuration. @@ -8399,7 +8429,7 @@ void Tab::delete_preset() const int process_preset_num = int(m_preset_bundle->prints.get_user_presets_for_printer(current_preset.name).size()); // With nothing attached, the plain delete confirmation below is asked instead. - if (filament_preset_num + process_preset_num > 0) { + if (ask && filament_preset_num + process_preset_num > 0) { DeleteConfirmDialog dlg(parent(), wxString(SLIC3R_APP_FULL_NAME) + " - " + _L("Delete"), // TRN %1% is "N filament preset(s)", %2% is "N process preset(s)". @@ -8477,7 +8507,7 @@ void Tab::delete_preset() } wxString title = _L("Delete Preset"); - if (current_preset.is_default || !(confirm_delete_third_party_printer || + if (current_preset.is_default || !(confirm_delete_third_party_printer || !ask || //wxID_YES != wxMessageDialog(parent(), msg, title, wxYES_NO | wxNO_DEFAULT | wxICON_QUESTION).ShowModal()) wxID_YES == MessageDialog(parent(), msg, title, wxYES_NO | wxNO_DEFAULT | wxICON_QUESTION).ShowModal())) return; diff --git a/src/slic3r/GUI/Tab.hpp b/src/slic3r/GUI/Tab.hpp index 8df7d6c84c..c70a620dd4 100644 --- a/src/slic3r/GUI/Tab.hpp +++ b/src/slic3r/GUI/Tab.hpp @@ -368,6 +368,15 @@ public: // Select a new preset, possibly delete the current one. bool select_preset(std::string preset_name = "", bool delete_current = false, const std::string &last_selected_ph_printer_name = "", bool force_select = false, bool force_no_transfer = false); bool may_discard_current_dirty_preset(PresetCollection* presets = nullptr, const std::string& new_printer_name = "", bool no_transfer = false, bool no_transfer_variant = false); + // Whether the unsaved-changes prompt of a switch to `preset_name` offers Transfer for this tab's own + // changes: never on the printer tab, and not between filaments of different types. + bool can_transfer_changes_to(const std::string& preset_name) const; + + // How this tab's preset switches answer their unsaved-changes prompts: by a person in + // UnsavedChangesDialog (Ask), or with the dialog's Transfer or Discard without showing it, for a + // caller that already has the answer (MCP's select_preset). A caller sets it around one switch. + enum class DirtyPresetAnswer { Ask, Transfer, Discard }; + DirtyPresetAnswer m_dirty_preset_answer = DirtyPresetAnswer::Ask; virtual void clear_pages(); virtual void update_description_lines(); @@ -386,7 +395,9 @@ public: bool save_preset(std::string name = std::string(), bool detach = false, bool save_to_project = false, bool from_input = false, std::string input_name = "", bool plugin_warning_confirmed = false); //void save_preset(std::string name = std::string(), bool detach = false); - void delete_preset(); + // Deletes the selected preset. `ask` false skips the confirmations, for a caller that has made the + // same checks itself; the refusal for a preset other presets inherit from still shows. + void delete_preset(bool ask = true); void toggle_show_hide_incompatible(); void update_show_hide_incompatible_button(); void update_ui_from_settings(); @@ -553,6 +564,11 @@ protected: // when a built field or a group owns the option, false when the GUI edits it through a custom // widget with no group entry. bool commit_preset_config_value(const std::string& opt_key); + // The unsaved-changes prompt's Transfer: caches `selected_options` of `presets`' unsaved changes for + // the preset selected next, less the options of other extruder variants on a switch to a printer + // with other variants (`no_transfer_variant`), which a person is told about in a message box. + void transfer_dirty_options(PresetCollection* presets, std::vector<std::string> selected_options, bool no_transfer, + bool no_transfer_variant); //BBS: GUI refactor // return true if cancelled diff --git a/src/slic3r/GUI/WebViewDialog.cpp b/src/slic3r/GUI/WebViewDialog.cpp index 047bbec019..867c342b30 100644 --- a/src/slic3r/GUI/WebViewDialog.cpp +++ b/src/slic3r/GUI/WebViewDialog.cpp @@ -4,6 +4,7 @@ #include "I18N.hpp" #include "slic3r/GUI/GUI_App.hpp" #include "slic3r/GUI/MainFrame.hpp" +#include "slic3r/GUI/SyntheticInput.hpp" #include "libslic3r_version.h" #include <boost/filesystem/path.hpp> @@ -1133,7 +1134,7 @@ void WebViewPanel::OnToolsClicked(wxCommandEvent& WXUNUSED(evt)) m_dev_tools->Check(m_browser->IsAccessToDevToolsEnabled()); wxPoint position = ScreenToClient(wxGetMousePosition()); - PopupMenu(m_tools_menu, position.x, position.y); + popup_menu(*this, *m_tools_menu, position); } void WebViewPanel::RunScript(const wxString& javascript) diff --git a/src/slic3r/GUI/Widgets/CheckList.cpp b/src/slic3r/GUI/Widgets/CheckList.cpp index 447ef5a216..93bec2d575 100644 --- a/src/slic3r/GUI/Widgets/CheckList.cpp +++ b/src/slic3r/GUI/Widgets/CheckList.cpp @@ -1,6 +1,7 @@ #include "CheckList.hpp" #include "slic3r/GUI/I18N.hpp" +#include "slic3r/GUI/SyntheticInput.hpp" #include <wx/anybutton.h> #include <wx/arrstr.h> #include <wx/checklst.h> @@ -236,5 +237,5 @@ void CheckList::ShowMenu(wxMouseEvent &evt) if (!src) return; wxPoint screen_pos = src->ClientToScreen(evt.GetPosition()); wxPoint local_pos = ScreenToClient(screen_pos); - PopupMenu(&m, local_pos); + Slic3r::GUI::popup_menu(*this, m, local_pos); } diff --git a/src/slic3r/GUI/Widgets/DropDown.cpp b/src/slic3r/GUI/Widgets/DropDown.cpp index 8cca389a7f..0b548c68cf 100644 --- a/src/slic3r/GUI/Widgets/DropDown.cpp +++ b/src/slic3r/GUI/Widgets/DropDown.cpp @@ -909,6 +909,25 @@ void DropDown::sendDropDownEvent() GetEventHandler()->ProcessEvent(event); } +bool DropDown::ClickItem(int n) +{ + // A group's sublist picks through its main list, which the pick closes, as a release over the + // sublist does. + if (mainDropDown) + return mainDropDown->ClickItem(n); + if (n < 0 || n >= int(items.size()) || (items[n].style & (DD_ITEM_STYLE_DISABLED | DD_ITEM_STYLE_SPLIT_ITEM))) + return false; + if (subDropDown && subDropDown->IsShown()) + subDropDown->Dismiss(); + wxCommandEvent event(wxEVT_COMBOBOX, GetId()); + event.SetEventObject(this); + event.SetInt(n); + event.SetString(items[n].text); + GetEventHandler()->ProcessEvent(event); + DismissAndNotify(); + return true; +} + void DropDown::sendDropDownActionEvent(int index) { if (index < 0 || index >= int(items.size()) || (items[index].style & DD_ITEM_STYLE_DISABLED)) diff --git a/src/slic3r/GUI/Widgets/DropDown.hpp b/src/slic3r/GUI/Widgets/DropDown.hpp index a0821e6fff..15796a5b3a 100644 --- a/src/slic3r/GUI/Widgets/DropDown.hpp +++ b/src/slic3r/GUI/Widgets/DropDown.hpp @@ -101,6 +101,14 @@ public: wxString GetValue() const; void SetValue(const wxString &value); + // For automation, which reads and picks rows without a pointer. The items, shared with a group's + // sublist, which shows those of one group. + const std::vector<Item> &GetItems() const { return items; } + bool IsSubList() const { return mainDropDown != nullptr; } + // What a click on item `n` does: the item is picked (wxEVT_COMBOBOX) and the list closes. False for + // no item or one that can't be picked: disabled, or a separator. + bool ClickItem(int n); + public: void SetCornerRadius(double radius); diff --git a/src/slic3r/GUI/WipeTowerDialog.cpp b/src/slic3r/GUI/WipeTowerDialog.cpp index 3aa8fddccc..2bcf6de1da 100644 --- a/src/slic3r/GUI/WipeTowerDialog.cpp +++ b/src/slic3r/GUI/WipeTowerDialog.cpp @@ -270,21 +270,23 @@ bool is_flush_config_modified() return has_modify; } +void apply_flushing_volumes(const std::vector<double> &matrix, const std::vector<double> &multipliers) +{ + auto &project_config = wxGetApp().preset_bundle->project_config; + (project_config.option<ConfigOptionFloats>("flush_volumes_matrix"))->values = matrix; + (project_config.option<ConfigOptionFloats>("flush_multiplier"))->values = multipliers; + bool flushing_volume_modify = is_flush_config_modified(); + wxGetApp().sidebar().set_flushing_volume_warning(flushing_volume_modify); + wxGetApp().preset_bundle->export_selections(*wxGetApp().app_config); + wxGetApp().plater()->update_project_dirty_from_presets(); +} + void open_flushing_dialog(wxEvtHandler *parent, const wxEvent &event) { - auto &project_config = wxGetApp().preset_bundle->project_config; - WipingDialog dlg(static_cast<wxWindow *>(wxGetApp().mainframe)); dlg.ShowModal(); if (dlg.GetSubmitFlag()) { - auto matrix = dlg.GetFlattenMatrix(); - auto flush_multipliers = dlg.GetMultipliers(); - (project_config.option<ConfigOptionFloats>("flush_volumes_matrix"))->values = std::vector<double>(matrix.begin(), matrix.end()); - (project_config.option<ConfigOptionFloats>("flush_multiplier"))->values = std::vector<double>(flush_multipliers.begin(), flush_multipliers.end()); - bool flushing_volume_modify = is_flush_config_modified(); - wxGetApp().sidebar().set_flushing_volume_warning(flushing_volume_modify); - wxGetApp().preset_bundle->export_selections(*wxGetApp().app_config); - wxGetApp().plater()->update_project_dirty_from_presets(); + apply_flushing_volumes(dlg.GetFlattenMatrix(), dlg.GetMultipliers()); wxPostEvent(parent, event); } } diff --git a/src/slic3r/GUI/WipeTowerDialog.hpp b/src/slic3r/GUI/WipeTowerDialog.hpp index 6f6af5f59d..f9c236f780 100644 --- a/src/slic3r/GUI/WipeTowerDialog.hpp +++ b/src/slic3r/GUI/WipeTowerDialog.hpp @@ -48,6 +48,11 @@ private: bool is_flush_config_modified(); +// Writes the project's flushing volumes (nozzles x slots x slots in config order, every slot) and +// multipliers (one per nozzle) as the Flushing volumes dialog's OK does: the flushing button's +// warning, the selections in AppConfig and the project's modified state follow. The caller then +// schedules the background process. +void apply_flushing_volumes(const std::vector<double> &matrix, const std::vector<double> &multipliers); void open_flushing_dialog(wxEvtHandler *parent, const wxEvent &event); class WipingDialog : public wxDialog diff --git a/src/slic3r/GUI/calib_dlg.cpp b/src/slic3r/GUI/calib_dlg.cpp index 522a791922..19ed924b64 100644 --- a/src/slic3r/GUI/calib_dlg.cpp +++ b/src/slic3r/GUI/calib_dlg.cpp @@ -82,40 +82,17 @@ CheckBox* add_scale_checkbox(wxWindow* parent, wxSizer* settings_sizer) return cb; } -std::vector<std::string> get_shaper_type_values() +// The printer the tests run on: the edited printer preset, or an empty config before the presets load. +const DynamicPrintConfig& edited_printer_config() { - if (auto* preset_bundle = wxGetApp().preset_bundle) { - auto printer_config = &preset_bundle->printers.get_edited_preset().config; - const auto* gcode_flavor_option = printer_config->option<ConfigOptionEnum<GCodeFlavor>>("gcode_flavor"); - const ConfigOptionDef* def = printer_config->def()->get("input_shaping_type"); - if (gcode_flavor_option) { - auto types = input_shaper_types_for_flavor(gcode_flavor_option->value); - if (!types.empty()) { - std::vector<std::string> values; - values.reserve(types.size()); - for (InputShaperType type : types) { - if (type == InputShaperType::Disable) - continue; - const size_t idx = static_cast<size_t>(type); - if (def && idx < def->enum_values.size()) - values.push_back(def->enum_values[idx]); - else - values.push_back(std::to_string(static_cast<int>(type))); - } - if (!values.empty()) - return values; - } - } - - if (def && !def->enum_values.empty()) - return {def->enum_values.front()}; - } - return {"Default"}; + static const DynamicPrintConfig none; + const auto* preset_bundle = wxGetApp().preset_bundle; + return preset_bundle != nullptr ? preset_bundle->printers.get_edited_preset().config : none; } std::vector<wxString> make_shaper_type_labels() { - auto values = get_shaper_type_values(); + auto values = shaper_type_values(edited_printer_config()); if (values.empty()) values.emplace_back(""); @@ -141,6 +118,32 @@ bool is_belt_printer_selected() } +std::vector<std::string> shaper_type_values(const DynamicPrintConfig& printer) +{ + const ConfigOptionDef* def = printer.def()->get("input_shaping_type"); + if (const auto* gcode_flavor_option = printer.option<ConfigOptionEnum<GCodeFlavor>>("gcode_flavor")) { + auto types = input_shaper_types_for_flavor(gcode_flavor_option->value); + if (!types.empty()) { + std::vector<std::string> values; + values.reserve(types.size()); + for (InputShaperType type : types) { + if (type == InputShaperType::Disable) + continue; + const size_t idx = static_cast<size_t>(type); + if (def && idx < def->enum_values.size()) + values.push_back(def->enum_values[idx]); + else + values.push_back(std::to_string(static_cast<int>(type))); + } + if (!values.empty()) + return values; + } + } + if (def && !def->enum_values.empty()) + return {def->enum_values.front()}; + return {"Default"}; +} + PA_Calibration_Dlg::PA_Calibration_Dlg(wxWindow* parent, wxWindowID id, Plater* plater) : DPIDialog(parent, id, _L("PA Calibration"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE), m_plater(plater) { @@ -291,47 +294,15 @@ void PA_Calibration_Dlg::reset_params() { bool isDDE = m_rbExtruderType->GetSelection() == 0 ? true : false; int method = m_rbMethod->GetSelection(); - m_tiStartPA->GetTextCtrl()->SetValue(wxString::FromDouble(0.0)); - - switch (method) { - case 1: - m_params.mode = CalibMode::Calib_PA_Line; - m_tiEndPA->GetTextCtrl()->SetValue(wxString::FromDouble(0.1)); - m_tiPAStep->GetTextCtrl()->SetValue(wxString::FromDouble(0.002)); - m_cbPrintNum->SetValue(true); - m_cbPrintNum->Enable(true); - m_tiBMAccels->Enable(false); - m_tiBMSpeeds->Enable(false); - break; - case 2: - m_params.mode = CalibMode::Calib_PA_Pattern; - m_tiEndPA->GetTextCtrl()->SetValue(wxString::FromDouble(0.08)); - m_tiPAStep->GetTextCtrl()->SetValue(wxString::FromDouble(0.005)); - m_cbPrintNum->SetValue(true); - m_cbPrintNum->Enable(false); - m_tiBMAccels->Enable(true); - m_tiBMSpeeds->Enable(true); - break; - default: - m_params.mode = CalibMode::Calib_PA_Tower; - m_tiEndPA->GetTextCtrl()->SetValue(wxString::FromDouble(0.1)); - m_tiPAStep->GetTextCtrl()->SetValue(wxString::FromDouble(0.002)); - m_cbPrintNum->SetValue(false); - m_cbPrintNum->Enable(false); - m_tiBMAccels->Enable(false); - m_tiBMSpeeds->Enable(false); - break; - } - - if (!isDDE) { - m_tiEndPA->GetTextCtrl()->SetValue(wxString::FromDouble(1.0)); - - if (m_params.mode == CalibMode::Calib_PA_Pattern) { - m_tiPAStep->GetTextCtrl()->SetValue(wxString::FromDouble(0.05)); - } else { - m_tiPAStep->GetTextCtrl()->SetValue(wxString::FromDouble(0.02)); - } - } + m_params.mode = method == 1 ? CalibMode::Calib_PA_Line : method == 2 ? CalibMode::Calib_PA_Pattern : CalibMode::Calib_PA_Tower; + const Calib_Params defaults = calib_default_params(m_params.mode, edited_printer_config(), !isDDE); + m_tiStartPA->GetTextCtrl()->SetValue(wxString::FromDouble(defaults.start)); + m_tiEndPA->GetTextCtrl()->SetValue(wxString::FromDouble(defaults.end)); + m_tiPAStep->GetTextCtrl()->SetValue(wxString::FromDouble(defaults.step)); + m_cbPrintNum->SetValue(defaults.print_numbers); + m_cbPrintNum->Enable(m_params.mode == CalibMode::Calib_PA_Line); + m_tiBMAccels->Enable(m_params.mode == CalibMode::Calib_PA_Pattern); + m_tiBMSpeeds->Enable(m_params.mode == CalibMode::Calib_PA_Pattern); } void PA_Calibration_Dlg::on_start(wxCommandEvent& event) { @@ -339,11 +310,6 @@ void PA_Calibration_Dlg::on_start(wxCommandEvent& event) { read_double = m_tiStartPA->GetTextCtrl()->GetValue().ToDouble(&m_params.start); read_double = read_double && m_tiEndPA->GetTextCtrl()->GetValue().ToDouble(&m_params.end); read_double = read_double && m_tiPAStep->GetTextCtrl()->GetValue().ToDouble(&m_params.step); - if (!read_double || m_params.start < 0 || m_params.step < 10 * EPSILON || m_params.end < m_params.start + m_params.step) { - MessageDialog msg_dlg(nullptr, _L("Please input valid values:\nStart PA: >= 0.0\nEnd PA: > Start PA\nPA step: >= 0.001"), wxEmptyString, wxICON_WARNING | wxOK); - msg_dlg.ShowModal(); - return; - } switch (m_rbMethod->GetSelection()) { case 1: @@ -355,30 +321,32 @@ void PA_Calibration_Dlg::on_start(wxCommandEvent& event) { default: m_params.mode = CalibMode::Calib_PA_Tower; } + m_params.print_numbers = m_cbPrintNum->GetValue(); + ParseStringValues(m_tiBMAccels->GetTextCtrl()->GetValue().ToStdString(), m_params.accelerations); + ParseStringValues(m_tiBMSpeeds->GetTextCtrl()->GetValue().ToStdString(), m_params.speeds); + + const CalibParamsError error = read_double ? check_calib_params(m_params, edited_printer_config()) : CalibParamsError::Range; + if (error == CalibParamsError::Range) { + MessageDialog msg_dlg(nullptr, _L("Please input valid values:\nStart PA: >= 0.0\nEnd PA: > Start PA\nPA step: >= 0.001"), wxEmptyString, wxICON_WARNING | wxOK); + msg_dlg.ShowModal(); + return; + } // ORCA-Belt: backstop in case the selection slipped past the UI guards. - if (is_belt_printer_selected() && m_params.mode != CalibMode::Calib_PA_Tower) { + if (error == CalibParamsError::BeltMethod) { MessageDialog msg_dlg(nullptr, _L("PA Line and PA Pattern tests are not enabled yet on belt printers.\nPlease use the PA Tower method instead."), wxEmptyString, wxICON_WARNING | wxOK); msg_dlg.ShowModal(); return; } - m_params.print_numbers = m_cbPrintNum->GetValue(); - ParseStringValues(m_tiBMAccels->GetTextCtrl()->GetValue().ToStdString(), m_params.accelerations); - ParseStringValues(m_tiBMSpeeds->GetTextCtrl()->GetValue().ToStdString(), m_params.speeds); - - if (!m_params.accelerations.empty() && !m_params.speeds.empty()) { - // Guard against swapped inputs by ensuring acceleration magnitudes exceed speeds. - const double min_accel = *std::min_element(m_params.accelerations.begin(), m_params.accelerations.end()); - const double max_speed = *std::max_element(m_params.speeds.begin(), m_params.speeds.end()); - if (min_accel <= max_speed) { - MessageDialog msg_dlg(nullptr, - _L("Acceleration values must be greater than speed values.\nPlease verify the inputs."), - wxEmptyString, wxICON_WARNING | wxOK); - msg_dlg.ShowModal(); - return; - } + // Guards against swapped inputs: accelerations must exceed speeds. + if (error == CalibParamsError::AccelBelowSpeed) { + MessageDialog msg_dlg(nullptr, + _L("Acceleration values must be greater than speed values.\nPlease verify the inputs."), + wxEmptyString, wxICON_WARNING | wxOK); + msg_dlg.ShowModal(); + return; } m_plater->calib_pa(m_params); @@ -469,6 +437,7 @@ Temp_Calibration_Dlg::Temp_Calibration_Dlg(wxWindow* parent, wxWindowID id, Plat auto st_size = wxSize(text_max, -1); auto ti_size = FromDIP(wxSize(120, -1)); + const Calib_Params defaults = calib_default_params(CalibMode::Calib_Temp_Tower, edited_printer_config()); LabeledStaticBox* stb = new LabeledStaticBox(this, _L("Settings")); wxStaticBoxSizer* settings_sizer = new wxStaticBoxSizer(stb, wxVERTICAL); @@ -478,7 +447,7 @@ Temp_Calibration_Dlg::Temp_Calibration_Dlg(wxWindow* parent, wxWindowID id, Plat // start temp auto start_temp_sizer = new wxBoxSizer(wxHORIZONTAL); auto start_temp_text = new wxStaticText(this, wxID_ANY, start_temp_str, wxDefaultPosition, st_size, wxALIGN_LEFT); - m_tiStart = new TextInput(this, std::to_string(230), _L("\u2103" /* °C */), "", wxDefaultPosition, ti_size); + m_tiStart = new TextInput(this, wxString::FromDouble(defaults.start), _L("\u2103" /* °C */), "", wxDefaultPosition, ti_size); m_tiStart->GetTextCtrl()->SetValidator(wxTextValidator(wxFILTER_NUMERIC)); start_temp_sizer->Add(start_temp_text, 0, wxALL | wxALIGN_CENTER_VERTICAL, FromDIP(2)); start_temp_sizer->Add(m_tiStart , 0, wxALL | wxALIGN_CENTER_VERTICAL, FromDIP(2)); @@ -487,7 +456,7 @@ Temp_Calibration_Dlg::Temp_Calibration_Dlg(wxWindow* parent, wxWindowID id, Plat // end temp auto end_temp_sizer = new wxBoxSizer(wxHORIZONTAL); auto end_temp_text = new wxStaticText(this, wxID_ANY, end_temp_str, wxDefaultPosition, st_size, wxALIGN_LEFT); - m_tiEnd = new TextInput(this, std::to_string(190), _L("\u2103" /* °C */), "", wxDefaultPosition, ti_size); + m_tiEnd = new TextInput(this, wxString::FromDouble(defaults.end), _L("\u2103" /* °C */), "", wxDefaultPosition, ti_size); m_tiEnd->GetTextCtrl()->SetValidator(wxTextValidator(wxFILTER_NUMERIC)); end_temp_sizer->Add(end_temp_text, 0, wxALL | wxALIGN_CENTER_VERTICAL, FromDIP(2)); end_temp_sizer->Add(m_tiEnd , 0, wxALL | wxALIGN_CENTER_VERTICAL, FromDIP(2)); @@ -585,15 +554,15 @@ void Temp_Calibration_Dlg::on_start(wxCommandEvent& event) { read_long = m_tiStart->GetTextCtrl()->GetValue().ToULong(&start); read_long = read_long && m_tiEnd->GetTextCtrl()->GetValue().ToULong(&end); - if (!read_long || start > 500 || end < 155 || end > (start - 5)) { + m_params.start = start; + m_params.end = end; + m_params.mode = CalibMode::Calib_Temp_Tower; + if (!read_long || check_calib_params(m_params, edited_printer_config()) != CalibParamsError::None) { MessageDialog msg_dlg(nullptr, _L("Please input valid values:\nStart temp: <= 500\nEnd temp: >= 155\nStart temp >= End temp + 5"), wxEmptyString, wxICON_WARNING | wxOK); msg_dlg.ShowModal(); return; } - m_params.start = start; - m_params.end = end; m_params.nozzle_based_resize = m_cbResize->GetValue(); - m_params.mode = CalibMode::Calib_Temp_Tower; // Picker only exists on belt printers; default non-belt to the Standard model. m_params.test_model = m_rbModel ? m_rbModel->GetSelection() : 0; m_plater->calib_temp(m_params); @@ -694,7 +663,8 @@ MaxVolumetricSpeed_Test_Dlg::MaxVolumetricSpeed_Test_Dlg(wxWindow* parent, wxWin // start vol auto start_vol_sizer = new wxBoxSizer(wxHORIZONTAL); auto start_vol_text = new wxStaticText(this, wxID_ANY, start_vol_str, wxDefaultPosition, st_size, wxALIGN_LEFT); - m_tiStart = new TextInput(this, std::to_string(5), _L(u8"mm³/s"), "", wxDefaultPosition, ti_size); + const Calib_Params defaults = calib_default_params(CalibMode::Calib_Vol_speed_Tower, edited_printer_config()); + m_tiStart = new TextInput(this, wxString::FromDouble(defaults.start), _L(u8"mm³/s"), "", wxDefaultPosition, ti_size); m_tiStart->GetTextCtrl()->SetValidator(wxTextValidator(wxFILTER_NUMERIC)); start_vol_sizer->Add(start_vol_text, 0, wxALL | wxALIGN_CENTER_VERTICAL, FromDIP(2)); @@ -704,7 +674,7 @@ MaxVolumetricSpeed_Test_Dlg::MaxVolumetricSpeed_Test_Dlg(wxWindow* parent, wxWin // end vol auto end_vol_sizer = new wxBoxSizer(wxHORIZONTAL); auto end_vol_text = new wxStaticText(this, wxID_ANY, end_vol_str, wxDefaultPosition, st_size, wxALIGN_LEFT); - m_tiEnd = new TextInput(this, std::to_string(20), _L(u8"mm³/s"), "", wxDefaultPosition, ti_size); + m_tiEnd = new TextInput(this, wxString::FromDouble(defaults.end), _L(u8"mm³/s"), "", wxDefaultPosition, ti_size); m_tiEnd->GetTextCtrl()->SetValidator(wxTextValidator(wxFILTER_NUMERIC)); end_vol_sizer->Add(end_vol_text, 0, wxALL | wxALIGN_CENTER_VERTICAL, FromDIP(2)); end_vol_sizer->Add(m_tiEnd , 0, wxALL | wxALIGN_CENTER_VERTICAL, FromDIP(2)); @@ -713,7 +683,7 @@ MaxVolumetricSpeed_Test_Dlg::MaxVolumetricSpeed_Test_Dlg(wxWindow* parent, wxWin // vol step auto vol_step_sizer = new wxBoxSizer(wxHORIZONTAL); auto vol_step_text = new wxStaticText(this, wxID_ANY, vol_step_str, wxDefaultPosition, st_size, wxALIGN_LEFT); - m_tiStep = new TextInput(this, wxString::FromDouble(0.5), _L(u8"mm³/s"), "", wxDefaultPosition, ti_size); + m_tiStep = new TextInput(this, wxString::FromDouble(defaults.step), _L(u8"mm³/s"), "", wxDefaultPosition, ti_size); m_tiStep->GetTextCtrl()->SetValidator(wxTextValidator(wxFILTER_NUMERIC)); vol_step_sizer->Add(vol_step_text, 0, wxALL | wxALIGN_CENTER_VERTICAL, FromDIP(2)); vol_step_sizer->Add(m_tiStep , 0, wxALL | wxALIGN_CENTER_VERTICAL, FromDIP(2)); @@ -757,13 +727,13 @@ void MaxVolumetricSpeed_Test_Dlg::on_start(wxCommandEvent& event) { read_double = read_double && m_tiEnd->GetTextCtrl()->GetValue().ToDouble(&m_params.end); read_double = read_double && m_tiStep->GetTextCtrl()->GetValue().ToDouble(&m_params.step); - if (!read_double || m_params.start <= 0 || m_params.step <= 0 || m_params.end < (m_params.start + m_params.step)) { + m_params.mode = CalibMode::Calib_Vol_speed_Tower; + if (!read_double || check_calib_params(m_params, edited_printer_config()) != CalibParamsError::None) { MessageDialog msg_dlg(nullptr, _L("Please input valid values:\nstart > 0\nstep >= 0\nend > start + step"), wxEmptyString, wxICON_WARNING | wxOK); msg_dlg.ShowModal(); return; } - m_params.mode = CalibMode::Calib_Vol_speed_Tower; m_plater->calib_max_vol_speed(m_params); EndModal(wxID_OK); @@ -807,7 +777,8 @@ VFA_Test_Dlg::VFA_Test_Dlg(wxWindow* parent, wxWindowID id, Plater* plater) // start vol auto start_vol_sizer = new wxBoxSizer(wxHORIZONTAL); auto start_vol_text = new wxStaticText(this, wxID_ANY, start_str, wxDefaultPosition, st_size, wxALIGN_LEFT); - m_tiStart = new TextInput(this, std::to_string(40), _L("mm/s"), "", wxDefaultPosition, ti_size); + const Calib_Params defaults = calib_default_params(CalibMode::Calib_VFA_Tower, edited_printer_config()); + m_tiStart = new TextInput(this, wxString::FromDouble(defaults.start), _L("mm/s"), "", wxDefaultPosition, ti_size); m_tiStart->GetTextCtrl()->SetValidator(wxTextValidator(wxFILTER_NUMERIC)); start_vol_sizer->Add(start_vol_text, 0, wxALL | wxALIGN_CENTER_VERTICAL, FromDIP(2)); @@ -817,7 +788,7 @@ VFA_Test_Dlg::VFA_Test_Dlg(wxWindow* parent, wxWindowID id, Plater* plater) // end vol auto end_vol_sizer = new wxBoxSizer(wxHORIZONTAL); auto end_vol_text = new wxStaticText(this, wxID_ANY, end_vol_str, wxDefaultPosition, st_size, wxALIGN_LEFT); - m_tiEnd = new TextInput(this, std::to_string(200), _L("mm/s"), "", wxDefaultPosition, ti_size); + m_tiEnd = new TextInput(this, wxString::FromDouble(defaults.end), _L("mm/s"), "", wxDefaultPosition, ti_size); m_tiEnd->GetTextCtrl()->SetValidator(wxTextValidator(wxFILTER_NUMERIC)); end_vol_sizer->Add(end_vol_text, 0, wxALL | wxALIGN_CENTER_VERTICAL, FromDIP(2)); end_vol_sizer->Add(m_tiEnd , 0, wxALL | wxALIGN_CENTER_VERTICAL, FromDIP(2)); @@ -826,7 +797,7 @@ VFA_Test_Dlg::VFA_Test_Dlg(wxWindow* parent, wxWindowID id, Plater* plater) // vol step auto vol_step_sizer = new wxBoxSizer(wxHORIZONTAL); auto vol_step_text = new wxStaticText(this, wxID_ANY, vol_step_str, wxDefaultPosition, st_size, wxALIGN_LEFT); - m_tiStep = new TextInput(this, wxString::FromDouble(10), _L("mm/s"), "", wxDefaultPosition, ti_size); + m_tiStep = new TextInput(this, wxString::FromDouble(defaults.step), _L("mm/s"), "", wxDefaultPosition, ti_size); m_tiStep->GetTextCtrl()->SetValidator(wxTextValidator(wxFILTER_NUMERIC)); vol_step_sizer->Add(vol_step_text, 0, wxALL | wxALIGN_CENTER_VERTICAL, FromDIP(2)); vol_step_sizer->Add(m_tiStep , 0, wxALL | wxALIGN_CENTER_VERTICAL, FromDIP(2)); @@ -890,7 +861,8 @@ void VFA_Test_Dlg::on_start(wxCommandEvent& event) read_double = read_double && m_tiEnd->GetTextCtrl()->GetValue().ToDouble(&m_params.end); read_double = read_double && m_tiStep->GetTextCtrl()->GetValue().ToDouble(&m_params.step); - if (!read_double || m_params.start <= 10 || m_params.step <= 0 || m_params.end < (m_params.start + m_params.step)) { + m_params.mode = CalibMode::Calib_VFA_Tower; + if (!read_double || check_calib_params(m_params, edited_printer_config()) != CalibParamsError::None) { MessageDialog msg_dlg(nullptr, _L("Please input valid values:\nstart > 10\nstep >= 0\nend > start + step"), wxEmptyString, wxICON_WARNING | wxOK); msg_dlg.ShowModal(); return; @@ -903,38 +875,10 @@ void VFA_Test_Dlg::on_start(wxCommandEvent& event) m_params.nozzle_based_resize = m_cbResize->GetValue(); if (const auto* preset_bundle = wxGetApp().preset_bundle) { const auto& printer_config = preset_bundle->printers.get_edited_preset().config; - const auto& print_config = preset_bundle->prints.get_edited_preset().config; - const auto& filament_config = preset_bundle->filaments.get_edited_preset().config; - - const int extruder_id = std::max(m_params.extruder_id, 0); - auto get_at = [extruder_id](const ConfigOptionFloats* opt, double fallback) { - if (opt == nullptr || opt->values.empty()) - return fallback; - return opt->values[std::min(static_cast<size_t>(extruder_id), opt->values.size() - 1)]; - }; - - const double nozzle_diameter = get_at(printer_config.option<ConfigOptionFloats>("nozzle_diameter"), vfa_base_nozzle_diameter); - double preset_lh = nozzle_diameter / 2.0; - if (const auto* lh_opt = print_config.option<ConfigOptionFloat>("layer_height")) - if (lh_opt->value > 0.0) - preset_lh = lh_opt->value; - // Layer height the tower will actually print at: nozzle/2 when resizing, else the preset value. - const double default_lh = m_params.nozzle_based_resize ? nozzle_diameter / 2.0 : preset_lh; - const double max_vol_speed = get_at(filament_config.option<ConfigOptionFloats>("filament_max_volumetric_speed"), 0.0); - const double machine_min_lh = get_at(printer_config.option<ConfigOptionFloats>("min_layer_height"), 0.0); - const double machine_max_lh = get_at(printer_config.option<ConfigOptionFloats>("max_layer_height"), 0.0); - - double line_width = print_config.get_abs_value("outer_wall_line_width", nozzle_diameter); - if (line_width <= 0.0) - line_width = print_config.get_abs_value("line_width", nozzle_diameter); - if (line_width <= 0.0) - line_width = nozzle_diameter; - - // Max outer-wall speed printable at a given layer height without exceeding the volumetric limit. - auto speed_limit_for_lh = [&](double lh) -> double { - const double mm3_per_mm = Flow(line_width, lh, nozzle_diameter).mm3_per_mm(); - return mm3_per_mm > 0.0 ? max_vol_speed / mm3_per_mm : 1e9; - }; + const bool auto_adjust = m_cbAutoAdjust->GetValue(); + const VfaSpeedFit fit = fit_vfa_speed(m_params, printer_config, preset_bundle->prints.get_edited_preset().config, + preset_bundle->filaments.get_edited_preset().config, auto_adjust, + vfa_candidate_layer_heights(preset_bundle->prints, printer_config, m_params.extruder_id)); auto confirm_clamp = [&](const wxString& question) -> bool { MessageDialog msg_dlg(nullptr, @@ -942,91 +886,54 @@ void VFA_Test_Dlg::on_start(wxCommandEvent& event) "(%.1f mm³/s), which limits the outer wall to about %.0f mm/s at this line width and " "layer height.\n Speeds above this will be clamped, so the upper blocks of the tower " "will not print at the requested speed.\n\n%s"), - m_params.end, max_vol_speed, speed_limit_for_lh(default_lh), question), + m_params.end, fit.max_vol_speed, fit.speed_limit, question), _L("VFA test"), wxICON_WARNING | wxYES_NO | wxNO_DEFAULT); return msg_dlg.ShowModal() == wxID_YES; }; - if (max_vol_speed > 0.0 && nozzle_diameter > 0.0 && m_params.end > speed_limit_for_lh(default_lh)) { - // The layer-height auto-adjust only applies when resizing is enabled (it changes the layer height). - if (m_cbAutoAdjust->GetValue() && m_params.nozzle_based_resize) { - // Candidate layer heights are the ones actually used by the process profiles compatible with the - // current printer (clamped to the machine's layer-height limits, when set). A smaller layer height - // means a smaller cross-section, hence a higher printable speed under the volumetric limit; pick the - // largest candidate that still reaches the end speed to keep the change from the default minimal. - std::vector<double> candidates; - for (const auto& preset : preset_bundle->prints.get_presets()) { - if (!preset.is_compatible || preset.is_default) - continue; - const auto* lh_opt = preset.config.option<ConfigOptionFloat>("layer_height"); - if (lh_opt == nullptr || lh_opt->value <= 0.0) - continue; - const double lh = lh_opt->value; - if ((machine_min_lh > 0.0 && lh < machine_min_lh - 1e-6) || - (machine_max_lh > 0.0 && lh > machine_max_lh + 1e-6)) - continue; - candidates.push_back(lh); - } - std::sort(candidates.begin(), candidates.end()); - candidates.erase(std::unique(candidates.begin(), candidates.end(), - [](double a, double b) { return std::abs(a - b) < 1e-6; }), - candidates.end()); - - // Largest candidate <= the default layer height that still reaches the end speed (smallest change). - double chosen_lh = 0.0; - for (auto it = candidates.rbegin(); it != candidates.rend(); ++it) { - if (*it > default_lh + 1e-6) - continue; // never increase the layer height above the default - if (speed_limit_for_lh(*it) >= m_params.end) { chosen_lh = *it; break; } - } - - if (chosen_lh > 0.0) { - // Reducing the layer height is enough to reach the requested end speed. - m_params.vfa_layer_height = chosen_lh; - MessageDialog msg_dlg(nullptr, - wxString::Format(_L("The end speed (%.0f mm/s) exceeds the filament's maximum volumetric speed " - "(%.1f mm³/s) at the default layer height (%.2f mm).\n\n" - "The layer height has been reduced to %.2f mm (a value used by this printer's " - "profiles) so the tower can reach the requested speed."), - m_params.end, max_vol_speed, default_lh, chosen_lh), - _L("VFA test"), wxICON_INFORMATION | wxOK); - msg_dlg.ShowModal(); - } else if (!candidates.empty()) { - // Even the smallest available layer height cannot reach the end speed; propose a lower end speed - // based on that layer height, the line width and the maximum volumetric speed. - const double min_lh = candidates.front(); - const double reachable = speed_limit_for_lh(min_lh); - double new_end = std::floor(reachable / m_params.step) * m_params.step; // snap down to a step multiple - if (new_end < m_params.start + m_params.step) - new_end = m_params.start + m_params.step; - MessageDialog msg_dlg(nullptr, - wxString::Format(_L("Even at the smallest layer height used by this printer's profiles (%.2f mm) the " - "end speed (%.0f mm/s) exceeds the filament's maximum volumetric speed " - "(%.1f mm³/s).\n\n" - "The layer height will be set to %.2f mm and the end speed lowered to %.0f mm/s.\n\n" - "Continue?"), - min_lh, m_params.end, max_vol_speed, min_lh, new_end), - _L("VFA test"), wxICON_WARNING | wxYES_NO | wxNO_DEFAULT); - if (msg_dlg.ShowModal() != wxID_YES) - return; - m_params.end = new_end; - m_params.vfa_layer_height = min_lh; - } else { - // No compatible process profiles to draw layer heights from: warn and let the user decide. - if (!confirm_clamp(_L("Continue anyway?"))) - return; - } - } else { - // Auto-adjust off, or resizing disabled (which forbids changing the layer height): just warn. - if (!confirm_clamp(m_params.nozzle_based_resize - ? _L("Enable \"Auto-adjust\" to fix this automatically, or continue anyway?") - : _L("Enable \"Auto-scale for nozzle\" and \"Auto-adjust\" to fix this automatically, or continue anyway?"))) - return; - } + switch (fit.kind) { + case VfaSpeedFit::ReducedLayerHeight: { + // Reducing the layer height is enough to reach the requested end speed. + m_params.vfa_layer_height = fit.layer_height; + MessageDialog msg_dlg(nullptr, + wxString::Format(_L("The end speed (%.0f mm/s) exceeds the filament's maximum volumetric speed " + "(%.1f mm³/s) at the default layer height (%.2f mm).\n\n" + "The layer height has been reduced to %.2f mm (a value used by this printer's " + "profiles) so the tower can reach the requested speed."), + m_params.end, fit.max_vol_speed, fit.default_lh, fit.layer_height), + _L("VFA test"), wxICON_INFORMATION | wxOK); + msg_dlg.ShowModal(); + break; + } + case VfaSpeedFit::LoweredEnd: { + // Even the smallest available layer height cannot reach the end speed: propose a lower end speed. + MessageDialog msg_dlg(nullptr, + wxString::Format(_L("Even at the smallest layer height used by this printer's profiles (%.2f mm) the " + "end speed (%.0f mm/s) exceeds the filament's maximum volumetric speed " + "(%.1f mm³/s).\n\n" + "The layer height will be set to %.2f mm and the end speed lowered to %.0f mm/s.\n\n" + "Continue?"), + fit.layer_height, m_params.end, fit.max_vol_speed, fit.layer_height, fit.end), + _L("VFA test"), wxICON_WARNING | wxYES_NO | wxNO_DEFAULT); + if (msg_dlg.ShowModal() != wxID_YES) + return; + m_params.end = fit.end; + m_params.vfa_layer_height = fit.layer_height; + break; + } + case VfaSpeedFit::Clamped: + // No compatible process profiles to draw layer heights from, auto-adjust off, or resizing disabled + // (which forbids changing the layer height): warn and let the user decide. + if (!confirm_clamp(auto_adjust && m_params.nozzle_based_resize ? _L("Continue anyway?") + : m_params.nozzle_based_resize + ? _L("Enable \"Auto-adjust\" to fix this automatically, or continue anyway?") + : _L("Enable \"Auto-scale for nozzle\" and \"Auto-adjust\" to fix this automatically, or continue anyway?"))) + return; + break; + case VfaSpeedFit::Fits: break; } } - m_params.mode = CalibMode::Calib_VFA_Tower; m_plater->calib_VFA(m_params); EndModal(wxID_OK); } @@ -1069,7 +976,8 @@ Retraction_Test_Dlg::Retraction_Test_Dlg(wxWindow* parent, wxWindowID id, Plater // start length auto start_length_sizer = new wxBoxSizer(wxHORIZONTAL); auto start_length_text = new wxStaticText(this, wxID_ANY, start_length_str, wxDefaultPosition, st_size, wxALIGN_LEFT); - m_tiStart = new TextInput(this, std::to_string(0), _L("mm"), "", wxDefaultPosition, ti_size); + const Calib_Params defaults = calib_default_params(CalibMode::Calib_Retraction_tower, edited_printer_config()); + m_tiStart = new TextInput(this, wxString::FromDouble(defaults.start), _L("mm"), "", wxDefaultPosition, ti_size); m_tiStart->GetTextCtrl()->SetValidator(wxTextValidator(wxFILTER_NUMERIC)); start_length_sizer->Add(start_length_text, 0, wxALL | wxALIGN_CENTER_VERTICAL, FromDIP(2)); @@ -1079,7 +987,7 @@ Retraction_Test_Dlg::Retraction_Test_Dlg(wxWindow* parent, wxWindowID id, Plater // end length auto end_length_sizer = new wxBoxSizer(wxHORIZONTAL); auto end_length_text = new wxStaticText(this, wxID_ANY, end_length_str, wxDefaultPosition, st_size, wxALIGN_LEFT); - m_tiEnd = new TextInput(this, std::to_string(2), _L("mm"), "", wxDefaultPosition, ti_size); + m_tiEnd = new TextInput(this, wxString::FromDouble(defaults.end), _L("mm"), "", wxDefaultPosition, ti_size); m_tiEnd->GetTextCtrl()->SetValidator(wxTextValidator(wxFILTER_NUMERIC)); end_length_sizer->Add(end_length_text, 0, wxALL | wxALIGN_CENTER_VERTICAL, FromDIP(2)); end_length_sizer->Add(m_tiEnd , 0, wxALL | wxALIGN_CENTER_VERTICAL, FromDIP(2)); @@ -1088,7 +996,7 @@ Retraction_Test_Dlg::Retraction_Test_Dlg(wxWindow* parent, wxWindowID id, Plater // length step auto length_step_sizer = new wxBoxSizer(wxHORIZONTAL); auto length_step_text = new wxStaticText(this, wxID_ANY, length_step_str, wxDefaultPosition, st_size, wxALIGN_LEFT); - m_tiStep = new TextInput(this, wxString::FromDouble(0.1), _L("mm"), "", wxDefaultPosition, ti_size); + m_tiStep = new TextInput(this, wxString::FromDouble(defaults.step), _L("mm"), "", wxDefaultPosition, ti_size); m_tiStep->GetTextCtrl()->SetValidator(wxTextValidator(wxFILTER_NUMERIC)); length_step_sizer->Add(length_step_text, 0, wxALL | wxALIGN_CENTER_VERTICAL, FromDIP(2)); length_step_sizer->Add(m_tiStep , 0, wxALL | wxALIGN_CENTER_VERTICAL, FromDIP(2)); @@ -1134,13 +1042,13 @@ void Retraction_Test_Dlg::on_start(wxCommandEvent& event) { read_double = read_double && m_tiEnd->GetTextCtrl()->GetValue().ToDouble(&m_params.end); read_double = read_double && m_tiStep->GetTextCtrl()->GetValue().ToDouble(&m_params.step); - if (!read_double || m_params.start < 0 || m_params.step <= 0 || m_params.end < (m_params.start + m_params.step)) { + m_params.mode = CalibMode::Calib_Retraction_tower; + if (!read_double || check_calib_params(m_params, edited_printer_config()) != CalibParamsError::None) { MessageDialog msg_dlg(nullptr, _L("Please input valid values:\nstart > 0\nstep >= 0\nend > start + step"), wxEmptyString, wxICON_WARNING | wxOK); msg_dlg.ShowModal(); return; } - m_params.mode = CalibMode::Calib_Retraction_tower; m_plater->calib_retraction(m_params); EndModal(wxID_OK); @@ -1225,12 +1133,14 @@ Input_Shaping_Freq_Test_Dlg::Input_Shaping_Freq_Test_Dlg(wxWindow* parent, wxWin settings_sizer->AddSpacer(FromDIP(5)); + const Calib_Params defaults = calib_default_params(CalibMode::Calib_Input_shaping_freq, edited_printer_config()); + // X axis frequencies auto x_freq_sizer = new wxBoxSizer(wxHORIZONTAL); auto start_x_text = new wxStaticText(this, wxID_ANY, x_axis_str, wxDefaultPosition, st_size, wxALIGN_LEFT); - m_tiFreqStartX = new TextInput(this, std::to_string(15) , _L("Hz"), "", wxDefaultPosition, ti_size); + m_tiFreqStartX = new TextInput(this, wxString::FromDouble(defaults.freqStartX), _L("Hz"), "", wxDefaultPosition, ti_size); m_tiFreqStartX->GetTextCtrl()->SetValidator(wxTextValidator(wxFILTER_NUMERIC)); - m_tiFreqEndX = new TextInput(this, std::to_string(110), _L("Hz"), "", wxDefaultPosition, ti_size); + m_tiFreqEndX = new TextInput(this, wxString::FromDouble(defaults.freqEndX), _L("Hz"), "", wxDefaultPosition, ti_size); m_tiFreqEndX->GetTextCtrl()->SetValidator(wxTextValidator(wxFILTER_NUMERIC)); x_freq_sizer->Add(start_x_text , 0, wxALL | wxALIGN_CENTER_VERTICAL, FromDIP(2)); @@ -1241,9 +1151,9 @@ Input_Shaping_Freq_Test_Dlg::Input_Shaping_Freq_Test_Dlg(wxWindow* parent, wxWin // Y axis frequencies auto y_freq_sizer = new wxBoxSizer(wxHORIZONTAL); auto start_y_text = new wxStaticText(this, wxID_ANY, y_axis_str, wxDefaultPosition, st_size, wxALIGN_LEFT); - m_tiFreqStartY = new TextInput(this, std::to_string(15) , _L("Hz"), "", wxDefaultPosition, ti_size); + m_tiFreqStartY = new TextInput(this, wxString::FromDouble(defaults.freqStartY), _L("Hz"), "", wxDefaultPosition, ti_size); m_tiFreqStartY->GetTextCtrl()->SetValidator(wxTextValidator(wxFILTER_NUMERIC)); - m_tiFreqEndY = new TextInput(this, std::to_string(110), _L("Hz"), "", wxDefaultPosition, ti_size); + m_tiFreqEndY = new TextInput(this, wxString::FromDouble(defaults.freqEndY), _L("Hz"), "", wxDefaultPosition, ti_size); m_tiFreqEndY->GetTextCtrl()->SetValidator(wxTextValidator(wxFILTER_NUMERIC)); y_freq_sizer->Add(start_y_text , 0, wxALL | wxALIGN_CENTER_VERTICAL, FromDIP(2)); @@ -1267,7 +1177,7 @@ Input_Shaping_Freq_Test_Dlg::Input_Shaping_Freq_Test_Dlg(wxWindow* parent, wxWin wxString damping_factor_str = _L("Damp: "); auto damping_factor_sizer = new wxBoxSizer(wxHORIZONTAL); auto damping_factor_text = new wxStaticText(this, wxID_ANY, damping_factor_str, wxDefaultPosition, st_size, wxALIGN_LEFT); - m_tiDampingFactor = new TextInput(this, wxString::Format("%.3f", 0.15), "", "", wxDefaultPosition, ti_size); + m_tiDampingFactor = new TextInput(this, wxString::Format("%.3f", defaults.start), "", "", wxDefaultPosition, ti_size); m_tiDampingFactor->GetTextCtrl()->SetValidator(wxTextValidator(wxFILTER_NUMERIC)); damping_factor_sizer->Add(damping_factor_text, 0, wxALL | wxALIGN_CENTER_VERTICAL, FromDIP(2)); @@ -1337,23 +1247,21 @@ void Input_Shaping_Freq_Test_Dlg::on_start(wxCommandEvent& event) { } read_double = read_double && m_tiDampingFactor->GetTextCtrl()->GetValue().ToDouble(&m_params.start); - if (!read_double || - m_params.freqStartX < 0 || m_params.freqEndX > 500 || - (!reprap_firmware && (m_params.freqStartY < 0 || m_params.freqEndY > 500)) || - m_params.freqStartX >= m_params.freqEndX || - (!reprap_firmware && m_params.freqStartY >= m_params.freqEndY)) { + m_params.mode = CalibMode::Calib_Input_shaping_freq; + const CalibParamsError error = read_double ? check_calib_params(m_params, edited_printer_config()) : CalibParamsError::Range; + if (error == CalibParamsError::Range) { MessageDialog msg_dlg(nullptr, _L("Please input valid values:\n(0 < FreqStart < FreqEnd < 500)"), wxEmptyString, wxICON_WARNING | wxOK); msg_dlg.ShowModal(); return; } - if (m_params.start < 0 || m_params.start >= 1) { + if (error == CalibParamsError::Damping) { MessageDialog msg_dlg(nullptr, _L("Please input a valid damping factor (0 < Damping/zeta factor <= 1)"), wxEmptyString, wxICON_WARNING | wxOK); msg_dlg.ShowModal(); return; } - auto shaper_values = get_shaper_type_values(); + auto shaper_values = shaper_type_values(edited_printer_config()); int type_selection = m_rbType->GetSelection(); if (shaper_values.empty()) { m_params.shaper_type.clear(); @@ -1363,8 +1271,6 @@ void Input_Shaping_Freq_Test_Dlg::on_start(wxCommandEvent& event) { m_params.shaper_type = shaper_values[static_cast<size_t>(type_selection)]; } - m_params.mode = CalibMode::Calib_Input_shaping_freq; - // Set model type based on selection m_params.test_model = m_rbModel->GetSelection() == 0 ? 0 : 1; // 0 = Ringing Tower, 1 = Fast Tower @@ -1450,11 +1356,13 @@ Input_Shaping_Damp_Test_Dlg::Input_Shaping_Damp_Test_Dlg(wxWindow* parent, wxWin settings_sizer->AddSpacer(FromDIP(5)); + const Calib_Params defaults = calib_default_params(CalibMode::Calib_Input_shaping_damp, edited_printer_config()); + auto freq_sizer = new wxBoxSizer(wxHORIZONTAL); auto freq_text = new wxStaticText(this, wxID_ANY, freq_str, wxDefaultPosition, st_size, wxALIGN_LEFT); - m_tiFreqX = new TextInput(this, std::to_string(30), _L("Hz"), "", wxDefaultPosition, ti_size); + m_tiFreqX = new TextInput(this, wxString::FromDouble(defaults.freqStartX), _L("Hz"), "", wxDefaultPosition, ti_size); m_tiFreqX->GetTextCtrl()->SetValidator(wxTextValidator(wxFILTER_NUMERIC)); - m_tiFreqY = new TextInput(this, std::to_string(30), _L("Hz"), "", wxDefaultPosition, ti_size); + m_tiFreqY = new TextInput(this, wxString::FromDouble(defaults.freqStartY), _L("Hz"), "", wxDefaultPosition, ti_size); m_tiFreqY->GetTextCtrl()->SetValidator(wxTextValidator(wxFILTER_NUMERIC)); freq_sizer->Add(freq_text, 0, wxALL | wxALIGN_CENTER_VERTICAL, FromDIP(2)); freq_sizer->Add(m_tiFreqX, 0, wxALL | wxALIGN_CENTER_VERTICAL, FromDIP(2)); @@ -1471,9 +1379,9 @@ Input_Shaping_Damp_Test_Dlg::Input_Shaping_Damp_Test_Dlg(wxWindow* parent, wxWin // Damping Factor Start and End auto damp_sizer = new wxBoxSizer(wxHORIZONTAL); auto damp_text = new wxStaticText(this, wxID_ANY, damp_str, wxDefaultPosition, st_size, wxALIGN_LEFT); - m_tiDampingFactorStart = new TextInput(this, wxString::Format("%.3f", 0.00), "", "", wxDefaultPosition, ti_size); + m_tiDampingFactorStart = new TextInput(this, wxString::Format("%.3f", defaults.start), "", "", wxDefaultPosition, ti_size); m_tiDampingFactorStart->GetTextCtrl()->SetValidator(wxTextValidator(wxFILTER_NUMERIC)); - m_tiDampingFactorEnd = new TextInput(this, wxString::Format("%.3f", 0.40), "", "", wxDefaultPosition, ti_size); + m_tiDampingFactorEnd = new TextInput(this, wxString::Format("%.3f", defaults.end), "", "", wxDefaultPosition, ti_size); m_tiDampingFactorEnd->GetTextCtrl()->SetValidator(wxTextValidator(wxFILTER_NUMERIC)); damp_sizer->Add(damp_text , 0, wxALL | wxALIGN_CENTER_VERTICAL, FromDIP(2)); damp_sizer->Add(m_tiDampingFactorStart, 0, wxALL | wxALIGN_CENTER_VERTICAL, FromDIP(2)); @@ -1539,22 +1447,21 @@ void Input_Shaping_Damp_Test_Dlg::on_start(wxCommandEvent& event) { read_double = read_double && m_tiDampingFactorStart->GetTextCtrl()->GetValue().ToDouble(&m_params.start); read_double = read_double && m_tiDampingFactorEnd->GetTextCtrl()->GetValue().ToDouble(&m_params.end); - if (!read_double || - m_params.freqStartX < 0 || m_params.freqStartX > 500 || - (!reprap_firmware && (m_params.freqStartY < 0 || m_params.freqStartY > 500))) { + m_params.mode = CalibMode::Calib_Input_shaping_damp; + const CalibParamsError error = read_double ? check_calib_params(m_params, edited_printer_config()) : CalibParamsError::Range; + if (error == CalibParamsError::Range) { MessageDialog msg_dlg(nullptr, _L("Please input valid values:\n(0 < Freq < 500)"), wxEmptyString, wxICON_WARNING | wxOK); msg_dlg.ShowModal(); return; } - if (m_params.start < 0 || m_params.end > 1 - || m_params.start >= m_params.end) { + if (error == CalibParamsError::Damping) { MessageDialog msg_dlg(nullptr, _L("Please input a valid damping factor (0 <= DampingStart < DampingEnd <= 1)"), wxEmptyString, wxICON_WARNING | wxOK); msg_dlg.ShowModal(); return; } - auto shaper_values = get_shaper_type_values(); + auto shaper_values = shaper_type_values(edited_printer_config()); int type_selection = m_rbType->GetSelection(); if (shaper_values.empty()) { m_params.shaper_type.clear(); @@ -1564,8 +1471,6 @@ void Input_Shaping_Damp_Test_Dlg::on_start(wxCommandEvent& event) { m_params.shaper_type = shaper_values[static_cast<size_t>(type_selection)]; } - m_params.mode = CalibMode::Calib_Input_shaping_damp; - // Set model type based on selection m_params.test_model = m_rbModel->GetSelection() == 0 ? 0 : 1; // 0 = Ringing Tower, 1 = Fast Tower @@ -1615,25 +1520,12 @@ Cornering_Test_Dlg::Cornering_Test_Dlg(wxWindow* parent, wxWindowID id, Plater* ? preset_bundle->printers.get_edited_preset().config.option<ConfigOptionEnum<GCodeFlavor>>("gcode_flavor") : nullptr; - wxString start_value_str; - wxString end_value_str; - wxString units_str; - - if (gcode_flavor_option && - gcode_flavor_option->value == GCodeFlavor::gcfMarlinFirmware && - preset_bundle->printers.get_edited_preset().config.option<ConfigOptionFloats>("machine_max_junction_deviation") && - !preset_bundle->printers.get_edited_preset().config.option<ConfigOptionFloats>("machine_max_junction_deviation")->values.empty() && - preset_bundle->printers.get_edited_preset().config.option<ConfigOptionFloats>("machine_max_junction_deviation")->values[0] > 0) { - // Using Junction Deviation (mm) - start_value_str = wxString::Format("%.3f", 0.000); - end_value_str = wxString::Format("%.3f", 0.250); - units_str = "mm"; - } else { - // Using Classic Jerk (mm/s) - start_value_str = wxString::Format("%.3f", 1.0); - end_value_str = wxString::Format("%.3f", 15.0); - units_str = "mm/s"; - } + // Junction Deviation in mm, or Classic Jerk in mm/s. + const bool junction_deviation = has_junction_deviation(edited_printer_config()); + const Calib_Params defaults = calib_default_params(CalibMode::Calib_Cornering, edited_printer_config()); + const wxString start_value_str = wxString::Format("%.3f", defaults.start); + const wxString end_value_str = wxString::Format("%.3f", defaults.end); + const wxString units_str = junction_deviation ? "mm" : "mm/s"; auto st_size = wxSize(text_max, -1); auto ti_size = FromDIP(wxSize(120, -1)); @@ -1669,9 +1561,7 @@ Cornering_Test_Dlg::Cornering_Test_Dlg(wxWindow* parent, wxWindowID id, Plater* wxString note_msg_2; switch (gcode_flavor_option->value) { case GCodeFlavor::gcfMarlinFirmware: { - // Check if machine_max_junction_deviation is set and > 0 - const auto* max_jd_option = preset_bundle->printers.get_edited_preset().config.option<ConfigOptionFloats>("machine_max_junction_deviation"); - if (max_jd_option && !max_jd_option->values.empty() && max_jd_option->values[0] > 0) { + if (junction_deviation) { note_msg_2 += _L("Marlin 2 Junction Deviation detected:\nTo test Classic Jerk, set 'Maximum Junction Deviation' in Motion ability to 0."); } else { note_msg_2 += _L("Marlin 2 Classic Jerk detected:\nTo test Junction Deviation, set 'Maximum Junction Deviation' in Motion ability to a value > 0."); @@ -1729,25 +1619,11 @@ void Cornering_Test_Dlg::on_start(wxCommandEvent& event) { read_double = m_tiJDStart->GetTextCtrl()->GetValue().ToDouble(&m_params.start); read_double = read_double && m_tiJDEnd->GetTextCtrl()->GetValue().ToDouble(&m_params.end); - // Get max values based on GCode Flavor - double max_end_value = 100.0; - double warning_threshold = 20.0; - const auto* preset_bundle = wxGetApp().preset_bundle; - const auto* gcode_flavor_option = (preset_bundle != nullptr) - ? preset_bundle->printers.get_edited_preset().config.option<ConfigOptionEnum<GCodeFlavor>>("gcode_flavor") - : nullptr; + // Junction Deviation (mm) or Classic Jerk (mm/s) limits. + const auto [max_end_value, warning_threshold] = cornering_end_limits(edited_printer_config()); - if (gcode_flavor_option && - gcode_flavor_option->value == GCodeFlavor::gcfMarlinFirmware && - preset_bundle->printers.get_edited_preset().config.option<ConfigOptionFloats>("machine_max_junction_deviation") && - !preset_bundle->printers.get_edited_preset().config.option<ConfigOptionFloats>("machine_max_junction_deviation")->values.empty() && - preset_bundle->printers.get_edited_preset().config.option<ConfigOptionFloats>("machine_max_junction_deviation")->values[0] > 0) { - // Using Junction Deviation (mm) - max_end_value = 0.3; - warning_threshold = 0.25; - } - - if (!read_double || m_params.start < 0 || m_params.end > max_end_value || m_params.start >= m_params.end) { + m_params.mode = CalibMode::Calib_Cornering; + if (!read_double || check_calib_params(m_params, edited_printer_config()) != CalibParamsError::None) { wxString error_msg = wxString::Format(_L("Please input valid values:\n(0 <= Cornering <= %s)"), wxString::Format("%.3f", max_end_value)); MessageDialog msg_dlg(nullptr, error_msg, wxEmptyString, wxICON_WARNING | wxOK); msg_dlg.ShowModal(); @@ -1758,8 +1634,6 @@ void Cornering_Test_Dlg::on_start(wxCommandEvent& event) { msg_dlg.ShowModal(); } - m_params.mode = CalibMode::Calib_Cornering; - // Set model type based on selection m_params.test_model = m_rbModel->GetSelection(); diff --git a/src/slic3r/GUI/calib_dlg.hpp b/src/slic3r/GUI/calib_dlg.hpp index eb0c5c9c01..3cd0a3811c 100644 --- a/src/slic3r/GUI/calib_dlg.hpp +++ b/src/slic3r/GUI/calib_dlg.hpp @@ -19,9 +19,17 @@ #include <wx/radiobox.h> #include <wx/sizer.h> #include "libslic3r/calib.hpp" +#include "libslic3r/PrintConfig.hpp" + +#include <string> +#include <vector> namespace Slic3r { namespace GUI { +// The input shaper types the input shaping dialogs offer for the printer's firmware, as +// input_shaping_type values in the order of their radio buttons; the first is their default. +std::vector<std::string> shaper_type_values(const DynamicPrintConfig& printer); + class PA_Calibration_Dlg : public DPIDialog { public: diff --git a/src/slic3r/Utils/PrintHost.cpp b/src/slic3r/Utils/PrintHost.cpp index c595d6c73c..28dbc2a39b 100644 --- a/src/slic3r/Utils/PrintHost.cpp +++ b/src/slic3r/Utils/PrintHost.cpp @@ -13,10 +13,14 @@ #include "slic3r/GUI/GUI_App.hpp" #include <vector> #include <thread> +#include <algorithm> +#include <optional> #include <exception> #include <sstream> #include <boost/log/trivial.hpp> #include <boost/filesystem.hpp> +#include <boost/cstdint.hpp> +#include <boost/system/error_code.hpp> #include <nlohmann/json.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> @@ -25,6 +29,7 @@ #include <wx/string.h> #include <wx/app.h> #include <wx/arrstr.h> +#include <wx/debug.h> #include "libslic3r/PrintConfig.hpp" #include "libslic3r/Channel.hpp" @@ -388,7 +393,7 @@ void PrintHostJobQueue::priv::progress_fn(Http::Progress progress, bool &cancel) } if (! cancel) { - int gui_progress = progress.ultotal > 0 ? 100*progress.ulnow / progress.ultotal : 0; + int gui_progress = PrintHostJobQueue::sent_percent(progress); if (gui_progress != prev_progress) { emit_progress(gui_progress); prev_progress = gui_progress; @@ -480,6 +485,11 @@ bool PrintHostJobQueue::upload_job(PrintHostJob &job, PrintHost::ProgressFn prog return success; } +int PrintHostJobQueue::sent_percent(const Http::Progress &progress) +{ + return progress.ultotal > 0 ? int(std::min<size_t>(99, 100 * progress.ulnow / progress.ultotal)) : 0; +} + void PrintHostJobQueue::priv::perform_job(PrintHostJob the_job) { emit_progress(0); // Indicate the upload is starting @@ -501,8 +511,23 @@ void PrintHostJobQueue::priv::perform_job(PrintHostJob the_job) void PrintHostJobQueue::enqueue(PrintHostJob job) { + wxCHECK_RET(!job.empty(), "PrintHostJobQueue: Attempt to enqueue an empty job"); p->start_bg_thread(); - p->queue_dialog->append_job(job); + + // Jobs come from the background slicing thread, and the queue's rows are UI state, so the row is added on the + // UI thread. What it shows is read now, since the upload thread may finish the job and remove its source file + // first. It is posted to the dialog itself: the upload thread's progress and error events for the job go to the + // same handler after it, and one handled before its row exists would be dropped. + boost::system::error_code ec; + const boost::uintmax_t bytes = fs::file_size(job.upload_data.source_path, ec); + std::optional<boost::uintmax_t> size; + if (ec) + BOOST_LOG_TRIVIAL(error) << ec.message(); + else + size = bytes; + p->queue_dialog->CallAfter([dialog = p->queue_dialog, host = job.printhost->get_host(), path = job.upload_data.upload_path, size]() { + dialog->append_job(host, path, size); + }); p->channel_jobs.push(std::move(job)); } diff --git a/src/slic3r/Utils/PrintHost.hpp b/src/slic3r/Utils/PrintHost.hpp index af2a7d38f4..54516006ef 100644 --- a/src/slic3r/Utils/PrintHost.hpp +++ b/src/slic3r/Utils/PrintHost.hpp @@ -159,6 +159,10 @@ public: // the upload is reported through error_fn and makes the upload fail. static bool upload_job(PrintHostJob &job, PrintHost::ProgressFn progress_fn, PrintHost::ErrorFn error_fn, PrintHost::InfoFn info_fn); + // The percentage a job's row shows while its bytes go out. It stops at 99: the host may still refuse the + // file once the last byte is sent, so only an upload() that returned success completes the row. + static int sent_percent(const Http::Progress &progress); + private: struct priv; std::shared_ptr<priv> p; diff --git a/src/slic3r/plugin/host/PluginPages.cpp b/src/slic3r/plugin/host/PluginPages.cpp index 93bc8e93cd..65958ce518 100644 --- a/src/slic3r/plugin/host/PluginPages.cpp +++ b/src/slic3r/plugin/host/PluginPages.cpp @@ -5,6 +5,7 @@ #include "slic3r/GUI/Notebook.hpp" #include "slic3r/GUI/GUI_App.hpp" #include "slic3r/GUI/MainFrame.hpp" +#include "slic3r/GUI/SyntheticInput.hpp" #include "slic3r/GUI/Widgets/Button.hpp" #include "slic3r/GUI/wxExtensions.hpp" #include "slic3r/plugin/PluginManager.hpp" @@ -443,7 +444,7 @@ void PluginPages::show_overflow_menu() relayout(); m_parent->SelectPageByName(page_tab_id(*m_swapped_in_id)); }); - m_overflow_button->PopupMenu(&menu); + GUI::popup_menu(*m_overflow_button, menu); } } // namespace Slic3r diff --git a/tests/slic3rutils/CMakeLists.txt b/tests/slic3rutils/CMakeLists.txt index 5dbc7417a7..64e572e779 100644 --- a/tests/slic3rutils/CMakeLists.txt +++ b/tests/slic3rutils/CMakeLists.txt @@ -22,15 +22,18 @@ add_executable(${_TEST_NAME}_tests test_scene_raycaster.cpp test_scene_benchmark.cpp test_lazy.cpp + test_mcp_config.cpp test_mcp_core.cpp test_mcp_http.cpp test_mcp_operations.cpp test_mcp_protocol.cpp + test_mcp_scene.cpp test_mcp_script.cpp test_mcp_setup.cpp test_mcp_token.cpp test_mcp_tools.cpp test_mcp_ui.cpp + test_mcp_results.cpp test_prebuild_queue.cpp test_staged_build.cpp test_network_versions.cpp @@ -71,6 +74,8 @@ add_executable(${_TEST_NAME}_tests if (SLIC3R_CAD) target_sources(${_TEST_NAME}_tests PRIVATE test_design_sketch_tool.cpp) + # The Design tab's MCP surface (cad_call). + target_sources(${_TEST_NAME}_tests PRIVATE test_mcp_cad.cpp) endif () if (MSVC) diff --git a/tests/slic3rutils/test_mcp_cad.cpp b/tests/slic3rutils/test_mcp_cad.cpp new file mode 100644 index 0000000000..73d3213d02 --- /dev/null +++ b/tests/slic3rutils/test_mcp_cad.cpp @@ -0,0 +1,2367 @@ +// The Design tab's MCP surface (cad_call): the method table, describe_tools, the plane resolver, the +// kernel's rollback, reading and editing a feature as its card does, and the open sketch's tools +// driven on a bare sketch tool. None of it needs a wx application or a Design panel. +#include <catch2/catch_message.hpp> +#include <catch2/catch_test_macros.hpp> +#include <catch2/matchers/catch_matchers.hpp> +#include <catch2/matchers/catch_matchers_floating_point.hpp> +#include <catch2/matchers/catch_matchers_string.hpp> + +#include "libslic3r/BoundingBox.hpp" +#include "libslic3r/CAD/CadDocument.hpp" +#include "libslic3r/CAD/GeometryEngine.hpp" +#include "libslic3r/CAD/SketchEngine.hpp" +#include "libslic3r/CAD/ThreadStandards.hpp" +#include "libslic3r/Model.hpp" +#include "libslic3r/TriangleMesh.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/libslic3r.h" +#include "slic3r/GUI/CAD/DesignSketchTool.hpp" +#include "slic3r/GUI/CAD/McpControl.hpp" + +#include <TopoDS_Edge.hxx> +#include <TopoDS_Face.hxx> +#include <TopoDS_Shape.hxx> +#include <boost/filesystem/operations.hpp> +#include <boost/filesystem/path.hpp> +#include <nlohmann/json.hpp> + +#include <algorithm> +#include <cmath> +#include <cstddef> +#include <map> +#include <stdexcept> +#include <string> +#include <utility> +#include <vector> + +using namespace Slic3r; +using Catch::Matchers::ContainsSubstring; +using Catch::Matchers::WithinAbs; +using nlohmann::json; + +namespace { + +std::vector<std::string> row_names(const json& reply) +{ + std::vector<std::string> names; + for (const json& row : reply.at("tools")) names.push_back(row.at("name").get<std::string>()); + std::sort(names.begin(), names.end()); + return names; +} + +std::string error_of(const json& plane, const CadDocument& doc, bool drill = false) +{ + try { + GUI::cad_resolve_plane(plane, doc, drill); + } catch (const std::runtime_error& e) { + return e.what(); + } + return {}; +} + +// A 40 x 20 x 10 box on the XY plane through the world origin: z from 0 to 10. +void add_box(CadDocument& doc) +{ + const int sk = doc.add_sketch(SketchShape::Rectangle, SketchPlane::XY(), 40, 20, 0, "Sketch"); + doc.add_extrude(sk, 10.0, false, BooleanMode::New, "Extrude"); + REQUIRE(doc.recompute()); +} + +// The face of body 0 whose outward normal is `n`. +int face_facing(const CadDocument& doc, const Vec3d& n) +{ + const std::vector<TopoDS_Face> faces = GeometryEngine::faces_of(doc.bodies.at(0).shape); + for (int i = 0; i < int(faces.size()); ++i) + if ((GeometryEngine::face_normal_world(faces[i]) - n).norm() < 1e-6) return i; + return -1; +} + +// The message a call fails with, or "" when it does not fail. +template<class F> std::string failure(F&& call) +{ + try { + call(); + } catch (const std::runtime_error& e) { + return e.what(); + } + return {}; +} + +SketchEntity line(double x0, double y0, double x1, double y1) +{ + SketchEntity e; + e.type = SketchEntity::Type::Line; + e.p0 = Vec2d(x0, y0); + e.p1 = Vec2d(x1, y1); + return e; +} + +SketchEntityConstraintDef constraint(SketchConstraintType t, int ea, SketchPointRole ra, int eb, SketchPointRole rb, + double value = 0) +{ + SketchEntityConstraintDef c; + c.type = t; + c.ea = ea; + c.ra = ra; + c.eb = eb; + c.rb = rb; + c.value = value; + return c; +} + +// A 40 x 20 rectangle of four joined lines (line 0 constrained to 40 mm), extruded to the variable +// h = 12, with a through hole: features 0 sketch, 1 extrude, 2 hole. +void add_bound_block(CadDocument& doc) +{ + using T = SketchConstraintType; + using R = SketchPointRole; + const std::vector<SketchEntity> rect = {line(0, 0, 40, 0), line(40, 0, 40, 20), line(40, 20, 0, 20), line(0, 20, 0, 0)}; + std::vector<SketchEntityConstraintDef> cons; + for (int i = 0; i < 4; ++i) cons.push_back(constraint(T::Coincident, i, R::P1, (i + 1) % 4, R::P0)); + cons.push_back(constraint(T::Distance, 0, R::P0, 0, R::P1, 40)); + const int sk = doc.add_sketch_entities(rect, SketchPlane::XY(), "Sketch 1", cons); + const int ex = doc.add_extrude(sk, 10.0, false, BooleanMode::New, "Extrude 2"); + doc.variables["h"] = "12"; + doc.features[ex].expr["distance"] = "h"; + doc.add_hole(5, 10, true, 20, 10, SketchPlane::XY(), "Hole 3"); + REQUIRE(doc.recompute()); +} + +} // namespace + +TEST_CASE("describe_tools has a row for every dispatched method", "[Mcp][CAD]") +{ + std::vector<std::string> methods = GUI::cad_control_methods(); + std::sort(methods.begin(), methods.end()); + REQUIRE(std::adjacent_find(methods.begin(), methods.end()) == methods.end()); + CHECK(row_names(GUI::cad_describe_tools(json::object())) == methods); +} + +TEST_CASE("describe_tools rows carry a summary, params and the method's access", "[Mcp][CAD]") +{ + const json reply = GUI::cad_describe_tools(json::object()); + for (const json& row : reply.at("tools")) { + INFO(row.at("name").get<std::string>()); + CHECK_FALSE(row.value("summary", std::string()).empty()); + REQUIRE(row.at("params").is_array()); + for (const json& p : row.at("params")) { + CHECK(p.contains("name")); + CHECK(p.contains("type")); + } + const std::string access = row.value("access", std::string()); + CHECK((access == "read" || access == "change" || access == "sketch")); + } + + auto access_of = [&](const char* name) { + for (const json& row : reply.at("tools")) + if (row.at("name") == name) return row.at("access").get<std::string>(); + return std::string(); + }; + CHECK(access_of("describe_scene") == "read"); + CHECK(access_of("sketch_describe") == "read"); // reads, so it also answers under an open card + CHECK(access_of("sketch_add") == "sketch"); + CHECK(access_of("extrude") == "change"); + CHECK(access_of("run_verb") == "change"); + + // The methods this surface fails as errors are not in the legacy list; the old ones are. + const json legacy = reply.at("legacy_ok_false"); + for (const char* rewritten : {"extrude", "revolve", "hole", "hole_styled", "hole_standard", "split"}) + CHECK(std::find(legacy.begin(), legacy.end(), json(rewritten)) == legacy.end()); + CHECK(std::find(legacy.begin(), legacy.end(), json("fillet")) != legacy.end()); +} + +TEST_CASE("describe_tools narrows to the named methods or a query", "[Mcp][CAD]") +{ + CHECK(row_names(GUI::cad_describe_tools({{"method", "extrude"}})) == std::vector<std::string>{"extrude"}); + CHECK(row_names(GUI::cad_describe_tools({{"method", {"hole", "fillet"}}})) == + std::vector<std::string>{"fillet", "hole"}); + + // The query matches names and summaries in any case. + const json sketch = GUI::cad_describe_tools({{"query", "SKETCH_"}}); + const std::vector<std::string> names = row_names(sketch); + CHECK(std::find(names.begin(), names.end(), "sketch_add") != names.end()); + for (const std::string& n : names) CHECK_THAT(n, ContainsSubstring("sketch_")); + + // An empty filter is no filter, as the rows' defaults say. + CHECK(row_names(GUI::cad_describe_tools({{"method", ""}, {"query", ""}})).size() == + GUI::cad_control_methods().size()); +} + +TEST_CASE("describe_tools names close methods for an unknown one", "[Mcp][CAD]") +{ + try { + GUI::cad_describe_tools({{"method", "extrud"}}); + FAIL("an unknown method was accepted"); + } catch (const std::runtime_error& e) { + CHECK_THAT(std::string(e.what()), ContainsSubstring("extrude")); + } + CHECK_THROWS_AS(GUI::cad_describe_tools({{"method", 3}}), std::runtime_error); +} + +TEST_CASE("rollback takes back a failed edit and leaves nothing to redo", "[Mcp][CAD]") +{ + CadDocument doc; + add_box(doc); + const size_t features = doc.features.size(); + const size_t depth = doc.undo_depth(); + + doc.checkpoint(); + const int bad = doc.add_extrude(0, 5.0, false, BooleanMode::New, "Bad"); + doc.features[bad].expr["distance"] = "nosuchvar"; + REQUIRE_FALSE(doc.recompute()); + + REQUIRE(doc.rollback()); + CHECK(doc.features.size() == features); + CHECK(doc.undo_depth() == depth); + CHECK_FALSE(doc.can_redo()); + CHECK(doc.error.empty()); + CHECK(doc.bodies.size() == 1); +} + +TEST_CASE("rollback keeps the redo branch the failed edit's checkpoint cleared", "[Mcp][CAD]") +{ + CadDocument doc; + add_box(doc); + doc.checkpoint(); + doc.features[1].distance = 20.0; + REQUIRE(doc.recompute()); + REQUIRE(doc.undo()); + REQUIRE(doc.can_redo()); + + doc.checkpoint(); + doc.features[0].expr["width"] = "nosuchvar"; + REQUIRE_FALSE(doc.recompute()); + REQUIRE(doc.rollback()); + + // The edit that failed is gone, and the step undone before it can still be redone. + CHECK(doc.features[0].expr.empty()); + REQUIRE(doc.redo()); + CHECK_THAT(doc.features[1].distance, WithinAbs(20.0, 1e-9)); +} + +TEST_CASE("a hole's face plane points into the body with x along the face's long side", "[Mcp][CAD]") +{ + CadDocument doc; + add_box(doc); + const int top = face_facing(doc, Vec3d(0, 0, 1)); + REQUIRE(top >= 0); + + SketchPlane drill; + REQUIRE(doc.inward_plane_of_face(0, top, drill)); + CHECK_THAT(drill.origin.z(), WithinAbs(10.0, 1e-6)); + CHECK_THAT(drill.origin.x(), WithinAbs(0.0, 1e-6)); + CHECK_THAT(drill.normal.z(), WithinAbs(-1.0, 1e-9)); + CHECK_THAT(std::abs(drill.x_axis.x()), WithinAbs(1.0, 1e-9)); // the 40 mm side runs along X + + CHECK_FALSE(doc.inward_plane_of_face(0, 999, drill)); + CHECK_FALSE(doc.inward_plane_of_face(3, top, drill)); +} + +TEST_CASE("plane resolves base planes on the modeling origin, datums and planar faces", "[Mcp][CAD]") +{ + CadDocument doc; + doc.modeling_origin = Vec3d(100, 50, 0); + add_box(doc); + + const SketchPlane xy = GUI::cad_resolve_plane("XY", doc, false); + CHECK((xy.origin - Vec3d(100, 50, 0)).norm() < 1e-9); + CHECK((xy.normal - Vec3d(0, 0, 1)).norm() < 1e-9); + CHECK((GUI::cad_resolve_plane("XZ", doc, false).normal - Vec3d(0, 1, 0)).norm() < 1e-9); + + // A datum is named by its feature index. + const int datum = doc.add_plane(0 /*XY*/, 30.0, 0.0, 0, "Plane"); + REQUIRE(doc.recompute()); + const SketchPlane dp = GUI::cad_resolve_plane({{"datum", datum}}, doc, false); + CHECK_THAT(dp.origin.z(), WithinAbs(30.0, 1e-9)); + CHECK((dp.normal - Vec3d(0, 0, 1)).norm() < 1e-9); + + // A face gives the sketch-on-face plane, or the drilling plane, and says whose face it is. + const int top = face_facing(doc, Vec3d(0, 0, 1)); + REQUIRE(top >= 0); + int body = -1; + const SketchPlane on = GUI::cad_resolve_plane({{"body", 0}, {"face", top}}, doc, false, &body); + CHECK(body == 0); + CHECK_THAT(on.origin.z(), WithinAbs(10.0, 1e-6)); + CHECK((on.normal - Vec3d(0, 0, 1)).norm() < 1e-9); + const SketchPlane into = GUI::cad_resolve_plane({{"body", 0}, {"face", top}}, doc, true); + CHECK((into.normal - Vec3d(0, 0, -1)).norm() < 1e-9); +} + +TEST_CASE("plane refuses what is not a plane, naming why", "[Mcp][CAD]") +{ + CadDocument doc; + add_box(doc); + const int datum = doc.add_plane(0, 30.0, 0.0, 0, "Plane"); + REQUIRE(doc.recompute()); + + CHECK_THAT(error_of("Top", doc), ContainsSubstring("plane must be")); + CHECK_THAT(error_of({{"datum", "1"}}, doc), ContainsSubstring("plane must be")); + CHECK_THAT(error_of({{"datum", 0}}, doc), ContainsSubstring("is not a datum plane")); + CHECK_THAT(error_of({{"datum", 99}}, doc), ContainsSubstring("is not a feature")); + CHECK_THAT(error_of({{"body", 4}, {"face", 0}}, doc), ContainsSubstring("out of range")); + CHECK_THAT(error_of({{"body", 0}, {"face", 999}}, doc), ContainsSubstring("does not exist")); + + doc.features[datum].enabled = false; + REQUIRE(doc.recompute()); + CHECK_THAT(error_of({{"datum", datum}}, doc), ContainsSubstring("hidden")); + + // A cylinder's side is not a plane, for sketching or for drilling. + CadDocument cyl; + const int sk = cyl.add_sketch(SketchShape::Circle, SketchPlane::XY(), 0, 0, 5.0, "Sketch"); + cyl.add_extrude(sk, 10.0, false, BooleanMode::New, "Extrude"); + REQUIRE(cyl.recompute()); + const std::vector<TopoDS_Face> faces = GeometryEngine::faces_of(cyl.bodies.at(0).shape); + int side = -1; + for (int i = 0; i < int(faces.size()); ++i) + if (GeometryEngine::cylinder_of_face(faces[i]).ok) side = i; + REQUIRE(side >= 0); + CHECK_THAT(error_of({{"body", 0}, {"face", side}}, cyl), ContainsSubstring("is cylindrical")); + CHECK_THAT(error_of({{"body", 0}, {"face", side}}, cyl, true), ContainsSubstring("is cylindrical")); +} + +TEST_CASE("describe_feature reads a sketch and the extrude bound to a variable", "[Mcp][CAD]") +{ + CadDocument doc; + add_bound_block(doc); + + const json sketch = GUI::cad_feature_json(doc, 0); + CHECK(sketch.at("type") == "Sketch"); + CHECK(sketch.at("name") == "Sketch 1"); + CHECK(sketch.at("plane").at("base") == "XY"); + CHECK(sketch.at("editable").empty()); // the sketch session edits entities, not set_feature + REQUIRE(sketch.at("entities").size() == 4); + CHECK(sketch.at("entities")[0].at("type") == "line"); + const json& cons = sketch.at("constraints"); + REQUIRE(cons.size() == 5); + CHECK(cons[0].at("type") == "coincident"); + CHECK(cons[0].at("refs") == json::array({json{{"entity", 0}, {"role", "p1"}}, json{{"entity", 1}, {"role", "p0"}}})); + CHECK(cons[4].at("type") == "distance"); + CHECK_THAT(cons[4].at("value").get<double>(), WithinAbs(40.0, 1e-9)); + CHECK(sketch.at("used_by") == json::array({1})); + CHECK(sketch.at("bodies_made").empty()); + + const json extrude = GUI::cad_feature_json(doc, 1); + CHECK(extrude.at("type") == "Extrude"); + CHECK_THAT(extrude.at("params").at("distance").get<double>(), WithinAbs(12.0, 1e-9)); // the variable's value + CHECK(extrude.at("expr").at("distance") == "h"); + CHECK(extrude.at("params").at("mode") == "new"); + CHECK(extrude.at("params").at("extrude_end") == "blind"); + CHECK(extrude.at("refs").at("sketch_ref") == 0); + CHECK(extrude.at("ranges").at("distance") == json::array({-1000.0, 1000.0})); + CHECK(extrude.at("bodies_made") == json::array({0})); + CHECK_FALSE(extrude.contains("plane")); // it builds on its sketch's plane + + const json hole = GUI::cad_feature_json(doc, 2); + CHECK_THAT(hole.at("params").at("hole_x").get<double>(), WithinAbs(20.0, 1e-9)); + CHECK(hole.at("params").at("hole_through") == true); + CHECK(hole.contains("plane")); + + CHECK_THAT(failure([&] { GUI::cad_feature_json(doc, 3); }), ContainsSubstring("feature 3 is out of range")); +} + +TEST_CASE("describe_feature names constraint references as the solver reads them", "[Mcp][CAD]") +{ + using T = SketchConstraintType; + using R = SketchPointRole; + CadDocument doc; + std::vector<SketchEntityConstraintDef> cons = { + constraint(T::Parallel, 0, R::P0, 1, R::P0), + constraint(T::Angle, 0, R::P0, 1, R::P0, PI / 2), + constraint(T::Coincident, 0, R::P0, kSketchRefOrigin, R::P0), + constraint(T::PointOnLine, 1, R::P1, 0, R::P0), + }; + doc.add_sketch_entities({line(0, 0, 10, 0), line(0, 5, 10, 5)}, SketchPlane::XY(), "Sketch", cons); + + const json c = GUI::cad_feature_json(doc, 0).at("constraints"); + CHECK(c[0].at("refs") == json::array({json{{"entity", 0}}, json{{"entity", 1}}})); // whole lines, no roles + CHECK_FALSE(c[0].contains("value")); + CHECK(c[1].at("type") == "angle"); + CHECK_THAT(c[1].at("value").get<double>(), WithinAbs(90.0, 1e-9)); // degrees, as cad_call takes angles + CHECK(c[2].at("refs")[1] == json{{"entity", "origin"}}); + CHECK(c[3].at("type") == "point_on_line"); + CHECK(c[3].at("refs") == json::array({json{{"entity", 1}, {"role", "p1"}}, json{{"entity", 0}}})); +} + +TEST_CASE("describe_feature lists the features built on a datum plane", "[Mcp][CAD]") +{ + CadDocument doc; + doc.modeling_origin = Vec3d(100, 50, 0); + const int first = doc.add_plane(0 /*XY*/, 30.0, 0.0, 0, "Plane 1"); + const int second = doc.add_plane(3 /*the first datum*/, 10.0, 0.0, 0, "Plane 2"); + doc.recompute(); + + const json p = GUI::cad_feature_json(doc, first); + CHECK(p.at("used_by") == json::array({second})); + CHECK_THAT(p.at("plane").at("origin")[2].get<double>(), WithinAbs(30.0, 1e-9)); + CHECK_FALSE(p.at("plane").contains("base")); // parallel to XY but not through the modeling origin + CHECK_THAT(GUI::cad_feature_json(doc, second).at("plane").at("origin")[2].get<double>(), WithinAbs(40.0, 1e-9)); +} + +TEST_CASE("every editable field of every feature type takes back its own value", "[Mcp][CAD]") +{ + for (int t = 0; t <= int(CadFeatureType::Mate); ++t) { + CadDocument doc; + CadFeature f; + f.type = CadFeatureType(t); + if (f.type == CadFeatureType::Boolean) f.mode = BooleanMode::Cut; // a Boolean never makes a new body + doc.features.push_back(f); + const json card = GUI::cad_feature_json(doc, 0); + INFO(card.at("type").get<std::string>()); + + // A numeric field with a range is one an expression can drive too, and the card edits it. + for (const auto& [key, range] : card.at("ranges").items()) { + INFO(key); + CHECK(CadDocument::is_bindable_field(key)); + CHECK(std::find(card.at("editable").begin(), card.at("editable").end(), json(key)) != card.at("editable").end()); + CHECK(range[0].get<double>() <= card.at("params").at(key).get<double>()); + CHECK(card.at("params").at(key).get<double>() <= range[1].get<double>()); + } + for (const json& key : card.at("editable")) { + const std::string k = key.get<std::string>(); + INFO(k); + CadFeature g = doc.features[0]; + REQUIRE_NOTHROW(GUI::cad_apply_feature_fields(g, {{k, card.at("params").at(k)}})); + CadDocument after; + after.features.push_back(g); + CHECK(GUI::cad_feature_json(after, 0).at("params") == card.at("params")); + } + } +} + +TEST_CASE("set_feature writes literal fields and the card's choices", "[Mcp][CAD]") +{ + CadFeature ex; + ex.type = CadFeatureType::Extrude; + GUI::cad_apply_feature_fields(ex, {{"distance", 15}, {"mode", "subtract"}, {"flip", true}, {"extrude_end", "symmetric"}}); + CHECK(ex.distance == 15.0); + CHECK(ex.mode == BooleanMode::Cut); + CHECK(ex.flip); + CHECK(ex.extrude_end == ExtrudeEnd::Symmetric); + + CadFeature th; + th.type = CadFeatureType::Thread; + GUI::cad_apply_feature_fields(th, {{"thread_diameter", 8}}); + CHECK(th.thread_radius == 4.0); // the card's diameter, halved into the kernel's radius + + CadFeature rv; + rv.type = CadFeatureType::Revolve; + rv.revolve_axis_entity = 2; + GUI::cad_apply_feature_fields(rv, {{"revolve_axis", 1}}); + CHECK(rv.revolve_axis == 1); + CHECK(rv.revolve_axis_entity == -1); // a plane axis replaces a sketch-line axis, as on the card + + CadFeature sk; // a shape sketch, as the Sketch card makes it + GUI::cad_apply_feature_fields(sk, {{"shape", "circle"}, {"radius", 7.5}}); + CHECK(sk.shape == SketchShape::Circle); + CHECK(sk.radius == 7.5); +} + +TEST_CASE("set_feature refuses what the card would not produce, changing nothing", "[Mcp][CAD]") +{ + CadDocument doc; + add_bound_block(doc); + CadFeature ex = doc.features[1]; + ex.expr.clear(); + + CHECK_THAT(failure([&] { GUI::cad_apply_feature_fields(doc.features[1], {{"distance", 15}}); }), + ContainsSubstring("driven by the expression 'h'")); + CHECK_THAT(failure([&] { GUI::cad_apply_feature_fields(ex, {{"depth", 1}}); }), + ContainsSubstring("editable: distance, distance2, taper_deg, extrude_end, flip, mode")); + CHECK_THAT(failure([&] { GUI::cad_apply_feature_fields(ex, {{"sketch_ref", 2}}); }), + ContainsSubstring("'sketch_ref' is not an editable field")); + CHECK_THAT(failure([&] { GUI::cad_apply_feature_fields(doc.features[0], {{"width", 30}}); }), + ContainsSubstring("no field set_feature can change")); // an entity sketch + CHECK_THAT(failure([&] { GUI::cad_apply_feature_fields(ex, {{"distance", 2000}}); }), + ContainsSubstring("distance must be between -1000 and 1000")); + CHECK_THAT(failure([&] { GUI::cad_apply_feature_fields(ex, {{"distance", "15"}}); }), ContainsSubstring("must be a number")); + CHECK_THAT(failure([&] { GUI::cad_apply_feature_fields(ex, {{"mode", "add"}}); }), + ContainsSubstring("mode must be one of new, union, subtract, intersect")); + CHECK_THAT(failure([&] { GUI::cad_apply_feature_fields(ex, {{"extrude_end", "up_to_face"}}); }), + ContainsSubstring("needs a target face")); + CHECK_THAT(failure([&] { GUI::cad_apply_feature_fields(ex, json::object()); }), ContainsSubstring("fields must name")); + + CadFeature boolean; + boolean.type = CadFeatureType::Boolean; + CHECK_THAT(failure([&] { GUI::cad_apply_feature_fields(boolean, {{"mode", "new"}}); }), + ContainsSubstring("union, subtract or intersect")); + CadFeature thread; + thread.type = CadFeatureType::Thread; + thread.expr["thread_diameter"] = "d"; + CHECK_THAT(failure([&] { GUI::cad_apply_feature_fields(thread, {{"thread_radius", 3}}); }), + ContainsSubstring("thread_diameter")); // one value: a binding on either drives both + CadFeature pattern; + pattern.type = CadFeatureType::Pattern; + CHECK_THAT(failure([&] { GUI::cad_apply_feature_fields(pattern, {{"pattern_count", 2.5}}); }), + ContainsSubstring("whole number")); + + // Fields are checked before any is written: a refused one leaves the others unwritten too. + CHECK_THAT(failure([&] { GUI::cad_apply_feature_fields(ex, {{"distance", 15}, {"flip", "yes"}}); }), + ContainsSubstring("flip must be true or false")); + CHECK_THAT(ex.distance, WithinAbs(12.0, 1e-9)); +} + +TEST_CASE("a literal edit through replace_feature rebuilds, and undo takes it back", "[Mcp][CAD]") +{ + CadDocument doc; + const int sk = doc.add_sketch(SketchShape::Rectangle, SketchPlane::XY(), 20, 20, 0, "Sketch"); + const int ex = doc.add_extrude(sk, 10.0, false, BooleanMode::New, "Extrude"); + REQUIRE(doc.recompute()); + + CadFeature edited = doc.features[ex]; + GUI::cad_apply_feature_fields(edited, {{"distance", 15}}); + doc.checkpoint(); + REQUIRE(doc.replace_feature(ex, edited)); + CHECK(doc.features[ex].sketch_ref == sk); + CHECK_THAT(doc.body_mass_properties(0).volume, WithinAbs(6000.0, 1e-6)); + + REQUIRE(doc.undo()); + CHECK_THAT(doc.body_mass_properties(0).volume, WithinAbs(4000.0, 1e-6)); +} + +TEST_CASE("a refused literal edit leaves the history as it found it", "[Mcp][CAD]") +{ + CadDocument doc; + const int sk = doc.add_sketch(SketchShape::Rectangle, SketchPlane::XY(), 20, 20, 0, "Sketch"); + doc.add_extrude(sk, 10.0, false, BooleanMode::New, "Extrude"); + const int hole = doc.add_hole(4, 10, true, 0, 0, SketchPlane::XY(), "Hole"); + REQUIRE(doc.recompute()); + // An edit undone, so there is a redo branch to keep. + doc.checkpoint(); + doc.features[hole].hole_diameter = 6; + REQUIRE(doc.recompute()); + REQUIRE(doc.undo()); + const size_t depth = doc.undo_depth(); + + // set_feature's sequence for an edit the kernel refuses: a hole that misses the body. + CadFeature edited = doc.features[hole]; + GUI::cad_apply_feature_fields(edited, {{"hole_x", 500}}); + doc.checkpoint(); + REQUIRE_FALSE(doc.replace_feature(hole, edited)); + CHECK_THAT(doc.error, ContainsSubstring("no material")); + REQUIRE(doc.rollback()); + CHECK(doc.undo_depth() == depth); + CHECK(doc.features[hole].hole_x == 0.0); + REQUIRE(doc.redo()); + CHECK(doc.features[hole].hole_diameter == 6.0); +} + +TEST_CASE("variables evaluate in dependency order, and a cycle is reported", "[Mcp][CAD]") +{ + CadDocument doc; + doc.variables = {{"a", "2"}, {"b", "a * 3"}}; + std::string err; + const std::map<std::string, double> values = doc.variable_values(err); + CHECK(err.empty()); + CHECK_THAT(values.at("b"), WithinAbs(6.0, 1e-12)); + + doc.variables = {{"a", "b + 1"}, {"b", "a"}}; + CHECK(doc.variable_values(err).empty()); + CHECK_THAT(err, ContainsSubstring("cycle")); +} + +TEST_CASE("literal edits and bindings reach the same numeric fields", "[Mcp][CAD]") +{ + CadFeature f; + CadDocument::set_numeric_field(f, "hole_diameter", 7.0); + CHECK(f.hole_diameter == 7.0); + CadDocument::set_numeric_field(f, "thread_diameter", 6.0); + CHECK(f.thread_radius == 3.0); + CadDocument::set_numeric_field(f, "pattern_count", 4.4); + CHECK(f.pattern_count == 4); + CHECK_THROWS_AS(CadDocument::set_numeric_field(f, "sketch_ref", 1.0), std::runtime_error); + CHECK(CadDocument::is_bindable_field("hole_diameter")); + CHECK_FALSE(CadDocument::is_bindable_field("sketch_ref")); +} + +TEST_CASE("commit, new_design and export_step change the design or the plate, and fail as errors", "[Mcp][CAD]") +{ + const json reply = GUI::cad_describe_tools({{"method", {"commit", "new_design", "export_step"}}}); + REQUIRE(reply.at("tools").size() == 3); + for (const json& row : reply.at("tools")) CHECK(row.at("access") == "change"); + const json legacy = reply.at("legacy_ok_false"); + for (const char* name : {"commit", "new_design", "export_step"}) + CHECK(std::find(legacy.begin(), legacy.end(), json(name)) == legacy.end()); + + // export_step's path has no default, so the socket bridge makes it required. + for (const json& row : reply.at("tools")) + if (row.at("name") == "export_step") + for (const json& p : row.at("params")) + if (p.at("name") == "path") CHECK_FALSE(p.contains("default")); +} + +TEST_CASE("commit's replace takes distinct object indices that are not part of a cut", "[Mcp][CAD]") +{ + Model model; + for (int i = 0; i < 3; ++i) model.add_object()->name = "object " + std::to_string(i); + model.objects[2]->cut_id.init(); + + CHECK(GUI::cad_commit_replace(json::array(), model).empty()); + CHECK(GUI::cad_commit_replace({1, 0}, model) == std::vector<int>{0, 1}); + + auto refusal = [&](const json& replace) { return failure([&] { GUI::cad_commit_replace(replace, model); }); }; + CHECK_THAT(refusal(0), ContainsSubstring("list of object indices")); + CHECK_THAT(refusal({3}), ContainsSubstring("the project has 3 objects")); + CHECK_THAT(refusal({-1}), ContainsSubstring("out of range")); + CHECK_THAT(refusal({0, 0}), ContainsSubstring("listed twice")); + CHECK_THAT(refusal({0.5}), ContainsSubstring("not 0.5")); + CHECK_THAT(refusal({"0"}), ContainsSubstring("object indices")); + CHECK_THAT(refusal({0, 2}), ContainsSubstring("part of a cut object")); +} + +TEST_CASE("export_step's STEP file reads back with each body where the Move gizmo put it", "[Mcp][CAD]") +{ + CadDocument doc; + add_box(doc); + const GeometryEngine::MassProps box = GeometryEngine::mass_properties(doc.bodies.at(0).shape); + const boost::filesystem::path path = + boost::filesystem::temp_directory_path() / boost::filesystem::unique_path("mcp_cad_%%%%%%%%.step"); + + auto read_back = [&](const std::vector<Transform3d>& xforms) { + std::string err; + REQUIRE(doc.export_step(path.string(), xforms, err)); + CHECK(boost::filesystem::file_size(path) > 0); + const std::vector<TopoDS_Shape> solids = GeometryEngine::read_step_solids(path.string(), err); + boost::filesystem::remove(path); + REQUIRE(solids.size() == 1); + return GeometryEngine::mass_properties(solids[0]); + }; + + const GeometryEngine::MassProps same = read_back({Transform3d::Identity()}); + CHECK_THAT(same.volume, WithinAbs(box.volume, box.volume * 1e-4)); + CHECK((same.center_of_mass - box.center_of_mass).norm() < 1e-6); + + Transform3d moved = Transform3d::Identity(); + moved.translate(Vec3d(50, 0, 0)); + const GeometryEngine::MassProps shifted = read_back({moved}); + CHECK_THAT(shifted.volume, WithinAbs(box.volume, box.volume * 1e-4)); + CHECK((shifted.center_of_mass - box.center_of_mass - Vec3d(50, 0, 0)).norm() < 1e-6); +} + +TEST_CASE("undo, redo and the tree and body edits are rows with the access their gate needs", "[Mcp][CAD]") +{ + const json reply = GUI::cad_describe_tools({{"method", {"undo", "redo", "feature_delete", "feature_move", "feature_set_enabled", + "feature_rename", "body_set", "body_delete"}}}); + REQUIRE(reply.at("tools").size() == 8); + const json legacy = reply.at("legacy_ok_false"); + std::map<std::string, std::vector<std::string>> required; + for (const json& row : reply.at("tools")) { + const std::string name = row.at("name").get<std::string>(); + INFO(name); + // Undo and redo run in a sketch session too, where they act on the drawn shapes. + CHECK(row.at("access") == (name == "undo" || name == "redo" ? "sketch" : "change")); + CHECK(std::find(legacy.begin(), legacy.end(), json(name)) == legacy.end()); + for (const json& p : row.at("params")) + if (!p.contains("default")) required[name].push_back(p.at("name").get<std::string>()); + } + // The socket bridge makes a param without a default required. + CHECK(required["undo"].empty()); + CHECK(required["feature_delete"] == std::vector<std::string>{"feature"}); + CHECK(required["feature_move"] == std::vector<std::string>{"feature", "delta"}); + CHECK(required["feature_set_enabled"] == std::vector<std::string>{"feature", "enabled"}); + CHECK(required["feature_rename"] == std::vector<std::string>{"feature", "name"}); + CHECK(required["body_set"] == std::vector<std::string>{"body"}); + CHECK(required["body_delete"] == std::vector<std::string>{"body"}); +} + +TEST_CASE("abandon_checkpoint drops the refused edit's undo step and keeps what was redoable", "[Mcp][CAD]") +{ + CadDocument doc; + add_box(doc); + doc.checkpoint(); + doc.features[1].distance = 20.0; + REQUIRE(doc.recompute()); + REQUIRE(doc.undo()); + const size_t depth = doc.undo_depth(); + + doc.checkpoint(); // an edit that then put everything back itself + doc.abandon_checkpoint(); + CHECK(doc.undo_depth() == depth); + REQUIRE(doc.redo()); + CHECK_THAT(doc.features[1].distance, WithinAbs(20.0, 1e-9)); + + // With no checkpoint there is nothing to drop. + CadDocument empty; + empty.abandon_checkpoint(); + CHECK(empty.undo_depth() == 0); +} + +TEST_CASE("a tree edit the kernel refuses leaves the features and the history as they were", "[Mcp][CAD]") +{ + // As the panel's tree edits run them: one checkpoint, the kernel op, and abandon_checkpoint() + // when the op refuses. The step undone first must still be there to redo. + CadDocument doc; + const int sk = doc.add_sketch(SketchShape::Rectangle, SketchPlane::XY(), 10, 10, 0, "Sketch"); + const int ex = doc.add_extrude(sk, 5, false, BooleanMode::New, "Extrude"); + const int ch = doc.add_chamfer(1.0, FaceGroup::All, "Chamfer"); + doc.features[ch].target_body = 0; + REQUIRE(doc.recompute()); + doc.checkpoint(); + doc.features[ch].name = "Edge break"; + REQUIRE(doc.undo()); + const size_t depth = doc.undo_depth(); + + SECTION("the extrude cannot come before the sketch it extrudes") + { + doc.checkpoint(); + REQUIRE_FALSE(doc.move_feature(ex, -1)); + doc.abandon_checkpoint(); + CHECK_THAT(doc.error, ContainsSubstring("cannot come before")); + CHECK(doc.features[sk].type == CadFeatureType::Sketch); + CHECK(doc.features[ex].sketch_ref == sk); + CHECK(doc.bodies.size() == 1); + } + SECTION("the chamfer cannot be shown while the extrude that made its body is hidden") + { + REQUIRE(doc.set_feature_enabled(ch, false)); + REQUIRE(doc.set_feature_enabled(ex, false)); + doc.checkpoint(); + REQUIRE_FALSE(doc.set_feature_enabled(ch, true)); + doc.abandon_checkpoint(); + CHECK_FALSE(doc.features[ch].enabled); + CHECK(doc.bodies.empty()); + } + CHECK(doc.undo_depth() == depth); + REQUIRE(doc.redo()); + CHECK(doc.features[ch].name == "Edge break"); +} + +TEST_CASE("deleting a sketch takes the features built on it, as one undo step", "[Mcp][CAD]") +{ + CadDocument doc; + add_box(doc); + doc.checkpoint(); + REQUIRE(doc.remove_feature(0)); + CHECK(doc.features.empty()); + CHECK(doc.bodies.empty()); + REQUIRE(doc.undo()); + CHECK(doc.features.size() == 2); + CHECK(doc.bodies.size() == 1); +} + +namespace { + +SketchEntity circle(double cx, double cy, double r) +{ + SketchEntity e; + e.type = SketchEntity::Type::Circle; + e.center = e.p0 = Vec2d(cx, cy); + e.radius = r; + return e; +} + +// A shelf-pin jig plate: a 160 x 60 rectangle centred on the plane's origin with five 5.2 mm holes +// on 32 mm centres along its middle. +std::vector<SketchEntity> jig_plate() +{ + std::vector<SketchEntity> ents = {line(-80, -30, 80, -30), line(80, -30, 80, 30), line(80, 30, -80, 30), line(-80, 30, -80, -30)}; + for (int i = -2; i <= 2; ++i) ents.push_back(circle(32.0 * i, 0, 2.6)); + return ents; +} + +const double kHoleArea = PI * 2.6 * 2.6; +const double kJigVolume = (160.0 * 60.0 - 5 * kHoleArea) * 8.0; + +double body_volume(const CadDocument& doc, size_t body) { return GeometryEngine::mass_properties(doc.bodies.at(body).shape).volume; } + +// The loop that has the other loops of the jig plate inside it. +int plate_loop(const GUI::DesignSketchTool& tool, const std::vector<SketchEntity>& ents) +{ + const GUI::DesignSketchTool::LoopReport rep = tool.loop_report(ents); + for (int i = 0; i < int(rep.loops.size()); ++i) + if (rep.loops[i].holes.size() == 5) return i; + return -1; +} + +} // namespace + +TEST_CASE("a committed sketch's loops are numbered as extrude's loop takes them", "[Mcp][CAD]") +{ + CadDocument doc; + doc.modeling_origin = Vec3d(100, 50, 0); + const std::vector<SketchEntity> ents = jig_plate(); + SketchPlane plane = SketchPlane::XY(); + plane.origin += doc.modeling_origin; + const int sk = doc.add_sketch_entities(ents, plane, "Sketch 1"); + REQUIRE(doc.recompute()); + GUI::DesignSketchTool tool; + + // Six loops: the plate, which lists the five discs as its holes, and each disc. + const GUI::DesignSketchTool::LoopReport rep = tool.loop_report(ents); + REQUIRE(rep.loops.size() == 6); + const int plate = plate_loop(tool, ents); + REQUIRE(plate >= 0); + CHECK_THAT(rep.loops[plate].area, WithinAbs(160.0 * 60.0, 1e-6)); + // Each loop's entities, then its holes' entities: the list extrude {loop} hands the kernel. + const std::vector<std::vector<int>> regions = tool.region_entity_indices_with_holes(ents); + REQUIRE(regions.size() == rep.loops.size()); + for (size_t i = 0; i < regions.size(); ++i) { + std::vector<int> expect = rep.loops[i].ents; + for (int h : rep.loops[i].holes) expect.insert(expect.end(), rep.loops[h].ents.begin(), rep.loops[h].ents.end()); + CHECK(regions[i] == expect); + } + + const json described = GUI::cad_sketch_describe(doc, tool, sk); + CHECK(described.at("name") == "Sketch 1"); + CHECK(described.at("entities").size() == 9); + CHECK(described.at("constraints") == 0); + CHECK(described.at("plane").at("base") == "XY"); + CHECK(described.at("buildable") == true); + REQUIRE(described.at("closed_loops").size() == 6); + for (int i = 0; i < 6; ++i) CHECK(described.at("closed_loops")[i].at("index") == i); + CHECK(described.at("closed_loops")[plate].at("holes").size() == 5); + + // Not a sketch, or one with no entities to describe. + const int ex = doc.add_extrude(sk, 8.0, false, BooleanMode::New, "Extrude 2"); + const int box = doc.add_sketch(SketchShape::Rectangle, SketchPlane::XY(), 10, 10, 0, "Sketch 3"); + CHECK_THAT(failure([&] { GUI::cad_sketch_describe(doc, tool, ex); }), ContainsSubstring("is not a sketch")); + CHECK_THAT(failure([&] { GUI::cad_sketch_describe(doc, tool, box); }), ContainsSubstring("not drawn from entities")); + CHECK_THAT(failure([&] { GUI::cad_sketch_describe(doc, tool, 9); }), ContainsSubstring("out of range")); +} + +TEST_CASE("extrude takes a committed sketch whole, or one loop with the loops inside it", "[Mcp][CAD]") +{ + CadDocument doc; + const std::vector<SketchEntity> ents = jig_plate(); + const int sk = doc.add_sketch_entities(ents, SketchPlane::XY(), "Sketch 1"); + REQUIRE(doc.recompute()); + GUI::DesignSketchTool tool; + const int plate = plate_loop(tool, ents); + REQUIRE(plate >= 0); + + SECTION("the whole sketch is the plate with its holes, a new body as nothing is touched") + { + const int e = GUI::cad_sketch_extrude(doc, tool, {{"sketch", sk}, {"distance", 8}})("Extrude 2"); + CHECK(doc.features[e].sketch_ref == sk); + CHECK(doc.features[e].mode == BooleanMode::New); + REQUIRE(doc.recompute()); + REQUIRE(doc.bodies.size() == 1); + CHECK_THAT(body_volume(doc, 0), WithinAbs(kJigVolume, 1e-3)); + } + SECTION("the plate's loop carries its holes; a hole's loop is the disc") + { + GUI::cad_sketch_extrude(doc, tool, {{"sketch", sk}, {"loop", plate}, {"distance", 8}})("Extrude 2"); + const int disc = plate == 0 ? 1 : 0; + const json disc_only = {{"sketch", sk}, {"loop", disc}, {"distance", 8}, {"boolean", "new"}}; + const int e = GUI::cad_sketch_extrude(doc, tool, disc_only)("Extrude 3"); + CHECK(doc.features[e].sketch_ref == -1); // the loop travels with the feature + CHECK(doc.features[e].entities.size() == 1); + REQUIRE(doc.recompute()); + REQUIRE(doc.bodies.size() == 2); + CHECK_THAT(body_volume(doc, 0), WithinAbs(kJigVolume, 1e-3)); + CHECK_THAT(body_volume(doc, 1), WithinAbs(kHoleArea * 8.0, 1e-3)); + } +} + +TEST_CASE("extrude's auto boolean joins the body the sketch touches, as the card's default", "[Mcp][CAD]") +{ + CadDocument doc; + GUI::DesignSketchTool tool; + const int sk = doc.add_sketch_entities(jig_plate(), SketchPlane::XY(), "Sketch 1"); + GUI::cad_sketch_extrude(doc, tool, {{"sketch", sk}, {"distance", 8}})("Extrude 2"); + REQUIRE(doc.recompute()); + + // A lip on the plate's top joins the plate. + SketchPlane top = SketchPlane::XY(); + top.origin.z() = 8; + const int lip = doc.add_sketch_entities({line(-80, 20, 80, 20), line(80, 20, 80, 30), line(80, 30, -80, 30), line(-80, 30, -80, 20)}, + top, "Sketch 3"); + const int e = GUI::cad_sketch_extrude(doc, tool, {{"sketch", lip}, {"distance", 10}})("Extrude 4"); + CHECK(doc.features[e].mode == BooleanMode::Add); + CHECK(doc.features[e].target_body == 0); + REQUIRE(doc.recompute()); + REQUIRE(doc.bodies.size() == 1); + CHECK_THAT(body_volume(doc, 0), WithinAbs(kJigVolume + 160.0 * 10.0 * 10.0, 1e-3)); + + // A sketch in free space starts a new body, and an explicit mode is kept. + SketchPlane above = SketchPlane::XY(); + above.origin.z() = 50; + const int loose = doc.add_sketch(SketchShape::Rectangle, above, 10, 10, 0, "Sketch 5"); + CHECK(doc.features[GUI::cad_sketch_extrude(doc, tool, {{"sketch", loose}})("Extrude 6")].mode == BooleanMode::New); + const int cut = GUI::cad_sketch_extrude(doc, tool, {{"sketch", lip}, {"boolean", "subtract"}, {"distance", 2}})("Extrude 7"); + CHECK(doc.features[cut].mode == BooleanMode::Cut); + CHECK(doc.features[cut].target_body == 0); +} + +TEST_CASE("extrude refuses what the sketch fixes and what is not one of its loops, changing nothing", "[Mcp][CAD]") +{ + CadDocument doc; + GUI::DesignSketchTool tool; + const int sk = doc.add_sketch_entities(jig_plate(), SketchPlane::XY(), "Sketch 1"); + const int box = doc.add_sketch(SketchShape::Rectangle, SketchPlane::XY(), 10, 10, 0, "Sketch 2"); + const int hole = doc.add_hole(5, 5, true, 0, 0, SketchPlane::XY(), "Hole 3"); + const size_t features = doc.features.size(); + auto refusal = [&](json params) { + return failure([&] { GUI::cad_sketch_extrude(doc, tool, params); }); + }; + + for (const char* fixed : {"plane", "width", "height"}) + CHECK_THAT(refusal({{"sketch", sk}, {fixed, fixed == std::string("plane") ? json("XZ") : json(20)}}), + ContainsSubstring("cannot be given with sketch")); + CHECK_THAT(refusal({{"sketch", sk}, {"profile", {{0, 0}, {1, 0}, {0, 1}}}}), ContainsSubstring("cannot be given with sketch")); + CHECK_THAT(refusal({{"sketch", hole}}), ContainsSubstring("(Hole) is not a sketch")); + CHECK_THAT(refusal({{"sketch", 7}}), ContainsSubstring("out of range")); + CHECK_THAT(refusal({{"sketch", "0"}}), ContainsSubstring("sketch must be a feature index")); + CHECK_THAT(refusal({{"sketch", sk}, {"loop", 6}}), ContainsSubstring("loop 6 does not exist; sketch 0 has 6 closed loops")); + CHECK_THAT(refusal({{"sketch", sk}, {"loop", -1}}), ContainsSubstring("does not exist")); + CHECK_THAT(refusal({{"sketch", box}, {"loop", 0}}), ContainsSubstring("not drawn from entities")); + CHECK_THAT(refusal({{"sketch", sk}, {"boolean", "atuo"}}), ContainsSubstring("boolean must be auto, new")); + CHECK_THAT(refusal({{"sketch", sk}, {"body", 3}}), ContainsSubstring("out of range")); + CHECK_THAT(refusal({{"sketch", sk}, {"distance", 0}}), ContainsSubstring("distance must be > 0")); + CHECK_THAT(refusal({{"sketch", sk}, {"end", "up_to_vertex"}}), ContainsSubstring("end must be")); + // The row's empty profile means none. + CHECK(refusal({{"sketch", sk}, {"profile", json::array()}}).empty()); + // Checking adds nothing; only the call it returns does. + CHECK(doc.features.size() == features); +} + +TEST_CASE("revolve takes a line of the sketch, or its only centerline, as the axis", "[Mcp][CAD]") +{ + // A 10 x 10 profile 10 mm off a centerline along the XZ plane's y axis (world Z): a ring. + CadDocument doc; + SketchEntity axis_line = line(0, 0, 0, 30); + axis_line.construction = true; + std::vector<SketchEntity> ents = {line(10, 0, 20, 0), line(20, 0, 20, 10), line(20, 10, 10, 10), line(10, 10, 10, 0), axis_line}; + const int sk = doc.add_sketch_entities(ents, SketchPlane::XZ(), "Sketch 1"); + REQUIRE(doc.recompute()); + const double ring = PI * (20.0 * 20.0 - 10.0 * 10.0) * 10.0; + auto revolve = [&](json params) { + params["sketch"] = sk; + return GUI::cad_sketch_revolve(doc, params)("Revolve"); + }; + + SECTION("its only centerline by default") + { + const int r = revolve(json::object()); + CHECK(doc.features[r].revolve_axis_entity == 4); + REQUIRE(doc.recompute()); + CHECK_THAT(body_volume(doc, 0), WithinAbs(ring, ring * 1e-6)); + } + SECTION("the plane axis when one is asked for") + { + const int r = revolve({{"axis", 1}}); + CHECK(doc.features[r].revolve_axis_entity == -1); + CHECK(doc.features[r].revolve_axis == 1); + REQUIRE(doc.recompute()); + CHECK_THAT(body_volume(doc, 0), WithinAbs(ring, ring * 1e-6)); + } + SECTION("a named line, or -1 for the plane axis") + { + CHECK(doc.features[revolve({{"axis_entity", 3}})].revolve_axis_entity == 3); + CHECK(doc.features[revolve({{"axis_entity", -1}})].revolve_axis_entity == -1); + } + SECTION("no default when the sketch has two centerlines") + { + doc.features[sk].entities[0].construction = true; + CHECK(doc.features[revolve(json::object())].revolve_axis_entity == -1); + } + SECTION("refusals") + { + const size_t features = doc.features.size(); + CHECK_THAT(failure([&] { revolve({{"axis_entity", 9}}); }), ContainsSubstring("axis_entity 9 is not a line of sketch 0")); + CHECK_THAT(failure([&] { revolve({{"axis", 2}}); }), ContainsSubstring("axis must be 0")); + CHECK_THAT(failure([&] { revolve({{"boolean", "union"}}); }), ContainsSubstring("needs a body")); + CHECK_THAT(failure([&] { revolve({{"plane", "XY"}}); }), ContainsSubstring("cannot be given with sketch")); + CHECK(doc.features.size() == features); + } +} + +TEST_CASE("the sketch-to-solid rows take a sketch, and sketch_begin takes every plane form", "[Mcp][CAD]") +{ + const json reply = GUI::cad_describe_tools({{"method", {"sketch_begin", "sketch_describe", "extrude", "revolve"}}}); + std::map<std::string, std::map<std::string, json>> params; + for (const json& row : reply.at("tools")) + for (const json& p : row.at("params")) params[row.at("name").get<std::string>()][p.at("name").get<std::string>()] = p; + CHECK(params["sketch_begin"]["plane"].at("type") == "string|object"); + // Optional everywhere: the socket bridge makes a param without a default required. + CHECK(params["sketch_describe"]["sketch"].at("default").is_null()); + CHECK(params["extrude"]["sketch"].at("default").is_null()); + CHECK(params["extrude"]["loop"].at("default").is_null()); + CHECK(params["extrude"].count("body") == 1); + CHECK(params["revolve"]["sketch"].at("default").is_null()); + CHECK(params["revolve"]["axis_entity"].at("default").is_null()); + CHECK(params["revolve"].count("body") == 1); +} + +namespace { + +// The face of `body` whose outward normal is `n`. +int face_facing_on(const CadDocument& doc, int body, const Vec3d& n) +{ + const std::vector<TopoDS_Face> faces = GeometryEngine::faces_of(doc.bodies.at(body).shape); + for (int i = 0; i < int(faces.size()); ++i) + if ((GeometryEngine::face_normal_world(faces[i]) - n).norm() < 1e-6) return i; + return -1; +} + +// The circular edge of body 0 whose centre is at height z. +int circle_at(const CadDocument& doc, double z) +{ + const std::vector<TopoDS_Edge> edges = GeometryEngine::edges_of(doc.bodies.at(0).shape); + for (int i = 0; i < int(edges.size()); ++i) { + const GeometryEngine::CylinderFace c = GeometryEngine::circle_of_edge(edges[i]); + if (c.ok && std::abs(c.base.z() - z) < 1e-6) return i; + } + return -1; +} + +// The first face of body 0 that OCCT reads as a cylinder. +int cylinder_face(const CadDocument& doc) +{ + const std::vector<TopoDS_Face> faces = GeometryEngine::faces_of(doc.bodies.at(0).shape); + for (int i = 0; i < int(faces.size()); ++i) + if (GeometryEngine::cylinder_of_face(faces[i]).ok) return i; + return -1; +} + +// A cylinder of radius 10 from z 0 to 20 on the world XY plane. +void add_cylinder(CadDocument& doc) +{ + const int sk = doc.add_sketch(SketchShape::Circle, SketchPlane::XY(), 0, 0, 10.0, "Sketch"); + doc.add_extrude(sk, 20.0, false, BooleanMode::New, "Extrude"); + REQUIRE(doc.recompute()); +} + +const json& item_with(const json& list, const char* key, const json& value) +{ + for (const json& item : list) + if (item.value(key, json()) == value) return item; + FAIL("no item with " << key << " = " << value.dump()); + return list; +} + +double vec_dist(const json& a, const Vec3d& b) { return (Vec3d(a[0].get<double>(), a[1].get<double>(), a[2].get<double>()) - b).norm(); } + +} // namespace + +TEST_CASE("query_topology names a chamfer's cone and a fillet's torus, with their radii and areas", "[Mcp][CAD]") +{ + CadDocument doc; + add_cylinder(doc); + const int top = circle_at(doc, 20), bottom = circle_at(doc, 0); + REQUIRE(top >= 0); + REQUIRE(bottom >= 0); + doc.add_fillet(1.0, top, "Fillet"); + REQUIRE(doc.recompute()); + doc.add_chamfer(1.0, circle_at(doc, 0), "Chamfer"); + REQUIRE(doc.recompute()); + + const json reply = GUI::cad_query_topology(doc, {{"kinds", {"conical", "toroidal"}}}); + CHECK(reply.at("faces_total") == 2); + CHECK(reply.at("edges").empty()); // no edge filter, no adjacency + CHECK(reply.at("face_count").get<int>() > 2); + + const json& cone = item_with(reply.at("faces"), "kind", "conical"); + CHECK_THAT(cone.at("half_angle_deg").get<double>(), WithinAbs(45.0, 1e-6)); + CHECK_THAT(cone.at("radius_min").get<double>(), WithinAbs(9.0, 1e-6)); + CHECK_THAT(cone.at("radius_max").get<double>(), WithinAbs(10.0, 1e-6)); + CHECK_THAT(cone.at("area").get<double>(), WithinAbs(PI * 19.0 * std::sqrt(2.0), 1e-3)); + CHECK(cone.at("internal") == false); + // The apex lies below the chamfer, and the axis runs from it into the opening (+z). + CHECK_THAT(cone.at("apex")[2].get<double>(), WithinAbs(-9.0, 1e-6)); + CHECK_THAT(cone.at("axis")[2].get<double>(), WithinAbs(1.0, 1e-9)); + + const json& torus = item_with(reply.at("faces"), "kind", "toroidal"); + CHECK_THAT(torus.at("major_radius").get<double>(), WithinAbs(9.0, 1e-6)); + CHECK_THAT(torus.at("minor_radius").get<double>(), WithinAbs(1.0, 1e-6)); + CHECK_THAT(torus.at("area").get<double>(), WithinAbs(2 * PI * (9.0 * PI / 2 + 1.0), 1e-3)); + CHECK_THAT(torus.at("center")[2].get<double>(), WithinAbs(19.0, 1e-6)); + + // A chamfered cylinder's side is still a cylinder. + const json sides = GUI::cad_query_topology(doc, {{"kinds", {"cylindrical"}}}); + REQUIRE(sides.at("faces_total") == 1); + CHECK_THAT(sides.at("faces")[0].at("radius").get<double>(), WithinAbs(10.0, 1e-9)); + CHECK_THAT(sides.at("faces")[0].at("area").get<double>(), WithinAbs(2 * PI * 10.0 * 18.0, 1e-3)); +} + +TEST_CASE("query_topology reads a revolved half disc as a sphere", "[Mcp][CAD]") +{ + CadDocument doc; + SketchEntity arc; + arc.type = SketchEntity::Type::Arc; + arc.center = Vec2d(0, 0); + arc.radius = 10; + arc.start_angle = -PI / 2; + arc.end_angle = PI / 2; + arc.p0 = Vec2d(0, -10); + arc.p1 = Vec2d(0, 10); + const int sk = doc.add_sketch_entities({arc, line(0, 10, 0, -10)}, SketchPlane::XZ(), "Sketch"); + doc.add_revolve(sk, 360.0, 1, false, BooleanMode::New, "Revolve"); + REQUIRE(doc.recompute()); + + const json reply = GUI::cad_query_topology(doc, {{"kinds", {"spherical"}}}); + REQUIRE(reply.at("faces_total").get<int>() >= 1); + double area = 0; + for (const json& f : reply.at("faces")) { + CHECK_THAT(f.at("radius").get<double>(), WithinAbs(10.0, 1e-6)); + CHECK(vec_dist(f.at("center"), Vec3d::Zero()) < 1e-6); + CHECK(f.at("internal") == false); + area += f.at("area").get<double>(); + } + CHECK_THAT(area, WithinAbs(4 * PI * 100.0, 1e-2)); +} + +TEST_CASE("query_topology's adjacency gives each edge its faces and says which corners are inside", "[Mcp][CAD]") +{ + SECTION("a box: every edge between two faces, every face four edges, every corner outside") + { + CadDocument doc; + add_box(doc); + const json reply = GUI::cad_query_topology(doc, {{"adjacency", true}}); + REQUIRE(reply.at("faces").size() == 6); + REQUIRE(reply.at("edges").size() == 12); + for (const json& f : reply.at("faces")) CHECK(f.at("edges").size() == 4); + for (const json& e : reply.at("edges")) { + CHECK(e.at("faces").size() == 2); + CHECK(e.at("convex") == true); + } + } + SECTION("an L profile: one inside corner, and the faces on either side of it") + { + CadDocument doc; + doc.add_sketch_entities({line(0, 0, 40, 0), line(40, 0, 40, 5), line(40, 5, 5, 5), line(5, 5, 5, 30), line(5, 30, 0, 30), + line(0, 30, 0, 0)}, + SketchPlane::XY(), "Sketch"); + doc.add_extrude(0, 20.0, false, BooleanMode::New, "Extrude"); + REQUIRE(doc.recompute()); + const json concave = GUI::cad_query_topology(doc, {{"convex", false}}); + REQUIRE(concave.at("edges_total") == 1); + const json& edge = concave.at("edges")[0]; + CHECK(edge.at("kind") == "line"); + CHECK(edge.at("convex") == false); + CHECK_THAT(edge.at("p0")[0].get<double>(), WithinAbs(5.0, 1e-6)); + CHECK_THAT(edge.at("p0")[1].get<double>(), WithinAbs(5.0, 1e-6)); + // Without a face filter, the faces listed are the edge's two neighbours. + CHECK(concave.at("faces_total") == 2); + CHECK(concave.at("faces").size() == 2); + CHECK(GUI::cad_query_topology(doc, {{"convex", true}}).at("edges_total") == 17); + } + SECTION("a cylinder: its seam has one face, and the rims meet the caps in outside corners") + { + CadDocument doc; + add_cylinder(doc); + const json reply = GUI::cad_query_topology(doc, {{"adjacency", true}}); + int seams = 0; + for (const json& e : reply.at("edges")) { + if (e.at("faces").size() == 1) { + ++seams; + CHECK_FALSE(e.contains("convex")); + } else { + CHECK(e.at("kind") == "circle"); + CHECK(e.at("convex") == true); + } + } + CHECK(seams == 1); + } + SECTION("a fillet meets the faces it rounds smoothly") + { + CadDocument doc; + add_cylinder(doc); + doc.add_fillet(1.0, circle_at(doc, 20), "Fillet"); + REQUIRE(doc.recompute()); + const json torus = GUI::cad_query_topology(doc, {{"kinds", {"toroidal"}}, {"adjacency", true}}); + REQUIRE(torus.at("faces_total") == 1); + int tangent = 0; + for (const json& e : torus.at("edges")) // the torus's own edges, as neighbours + if (e.value("tangent", false)) ++tangent; + CHECK(tangent == 2); + } +} + +TEST_CASE("query_topology filters by direction, extreme and kind, and pages both lists", "[Mcp][CAD]") +{ + CadDocument doc; + add_box(doc); + const int top = face_facing(doc, Vec3d(0, 0, 1)); + + const json up = GUI::cad_query_topology(doc, {{"direction", {0, 0, 2}}}); + REQUIRE(up.at("faces_total") == 1); + CHECK(up.at("faces")[0].at("id") == top); + CHECK(up.at("edges_total") == 4); // the vertical edges, whichever way they run + for (const json& e : up.at("edges")) CHECK_THAT(e.at("length").get<double>(), WithinAbs(10.0, 1e-6)); + + const json high = GUI::cad_query_topology(doc, {{"at_extreme", "+z"}}); + REQUIRE(high.at("faces_total") == 1); + CHECK(high.at("faces")[0].at("id") == top); + CHECK(high.at("edges").empty()); + CHECK(GUI::cad_query_topology(doc, {{"at_extreme", "-x"}}).at("faces")[0].at("id") == face_facing(doc, Vec3d(-1, 0, 0))); + + const json top_edges = GUI::cad_query_topology(doc, {{"at_extreme", "+z"}, {"adjacency", true}}); + CHECK(top_edges.at("edges_total") == 4); + CHECK(GUI::cad_query_topology(doc, {{"kinds", {"planar"}}, {"adjacency", true}}).at("edges_total") == 12); + CHECK(GUI::cad_query_topology(doc, {{"edge_kinds", {"circle"}}}).at("faces").empty()); + + const json first = GUI::cad_query_topology(doc, {{"limit", 2}}); + CHECK(first.at("faces").size() == 2); + CHECK(first.at("edges").size() == 2); + CHECK(first.at("faces_total") == 6); + CHECK(first.at("edges_total") == 12); + CHECK(first.at("next_offset") == 2); + const json last = GUI::cad_query_topology(doc, {{"limit", 2}, {"offset", 10}}); + CHECK(last.at("faces").empty()); + CHECK(last.at("edges").size() == 2); + CHECK(last.at("edges")[0].at("id") == 10); + CHECK_FALSE(last.contains("next_offset")); + + CHECK_THAT(failure([&] { GUI::cad_query_topology(doc, {{"kinds", {"cone"}}}); }), ContainsSubstring("kinds must be one of planar")); + CHECK_THAT(failure([&] { GUI::cad_query_topology(doc, {{"edge_kinds", "line"}}); }), ContainsSubstring("must be a list")); + CHECK_THAT(failure([&] { GUI::cad_query_topology(doc, {{"direction", {0, 0, 0}}}); }), ContainsSubstring("must not be zero")); + CHECK_THAT(failure([&] { GUI::cad_query_topology(doc, {{"direction", {0, 1}}}); }), ContainsSubstring("[x, y, z]")); + CHECK_THAT(failure([&] { GUI::cad_query_topology(doc, {{"convex", "yes"}}); }), ContainsSubstring("convex must be")); + CHECK_THAT(failure([&] { GUI::cad_query_topology(doc, {{"at_extreme", "top"}}); }), ContainsSubstring("at_extreme must be one of")); + CHECK_THAT(failure([&] { GUI::cad_query_topology(doc, {{"limit", 0}}); }), ContainsSubstring("limit must be")); + CHECK_THAT(failure([&] { GUI::cad_query_topology(doc, {{"offset", -1}}); }), ContainsSubstring("offset must be")); + CHECK_THAT(failure([&] { GUI::cad_query_topology(doc, {{"body", 3}}); }), ContainsSubstring("out of range")); +} + +TEST_CASE("measure keeps the centroid distance and adds the minimum distance, across bodies", "[Mcp][CAD]") +{ + CadDocument doc; + add_box(doc); // body 0: z 0..10, x -20..20 + SketchPlane above = SketchPlane::XY(); + above.origin = Vec3d(30, 0, 15); + const int sk = doc.add_sketch(SketchShape::Rectangle, above, 40, 20, 0, "Sketch"); + doc.add_extrude(sk, 10.0, false, BooleanMode::New, "Extrude"); // body 1: z 15..25, x 10..50 + REQUIRE(doc.recompute()); + REQUIRE(doc.bodies.size() == 2); + const int top0 = face_facing_on(doc, 0, Vec3d(0, 0, 1)), bottom1 = face_facing_on(doc, 1, Vec3d(0, 0, -1)); + + const json gap = GUI::cad_measure(doc, {{"a", {{"face", top0}}}, {"b", {{"body", 1}, {"face", bottom1}}}}); + CHECK_THAT(gap.at("min_distance").get<double>(), WithinAbs(5.0, 1e-6)); + CHECK_THAT(gap.at("distance").get<double>(), WithinAbs(std::sqrt(30.0 * 30.0 + 5.0 * 5.0), 1e-6)); + CHECK_THAT(gap.at("parallel_gap").get<double>(), WithinAbs(5.0, 1e-6)); + CHECK_THAT(gap.at("angle_deg").get<double>(), WithinAbs(180.0, 1e-6)); + CHECK_THAT(gap.at("closest_b")[2].get<double>() - gap.at("closest_a")[2].get<double>(), WithinAbs(5.0, 1e-6)); + + // A point to a face: the perpendicular, with no angle (a point has no direction). + const json drop = GUI::cad_measure(doc, {{"a", {{"point", {0, 0, 30}}}}, {"b", {{"face", top0}}}}); + CHECK_THAT(drop.at("min_distance").get<double>(), WithinAbs(20.0, 1e-6)); + CHECK_FALSE(drop.contains("angle_deg")); + CHECK_FALSE(drop.contains("parallel_gap")); + + // Two edges of one face meet at a corner. + const json edges = GUI::cad_query_topology(doc, {{"at_extreme", "+z"}, {"adjacency", true}}); + const json& e0 = edges.at("edges")[0]; + int corner = -1; + for (const json& e : edges.at("edges")) + if (vec_dist(e.at("p0"), Vec3d(e0.at("p0")[0], e0.at("p0")[1], e0.at("p0")[2])) > 1e-6 && + std::abs(Vec3d(e.at("p1")[0].get<double>() - e.at("p0")[0].get<double>(), e.at("p1")[1].get<double>() - e.at("p0")[1].get<double>(), 0) + .normalized() + .dot(Vec3d(e0.at("p1")[0].get<double>() - e0.at("p0")[0].get<double>(), e0.at("p1")[1].get<double>() - e0.at("p0")[1].get<double>(), 0) + .normalized())) < 0.5) + corner = e.at("id"); + REQUIRE(corner >= 0); + CHECK_THAT(GUI::cad_measure(doc, {{"a", {{"edge", e0.at("id")}}}, {"b", {{"edge", corner}}}}).at("min_distance").get<double>(), + WithinAbs(0.0, 1e-6)); + + SECTION("a cylinder's axis stands for the hole") + { + doc.features[doc.add_hole(5, 10, true, 10, 0, SketchPlane::XY(), "Hole")].target_body = 0; + REQUIRE(doc.recompute()); + const int bore = cylinder_face(doc), right = face_facing_on(doc, 0, Vec3d(1, 0, 0)); + const json r = GUI::cad_measure(doc, {{"a", {{"face", bore}, {"axis", true}}}, {"b", {{"face", right}}}}); + CHECK_THAT(r.at("min_distance").get<double>(), WithinAbs(10.0, 1e-6)); + CHECK_THAT(r.at("distance").get<double>(), WithinAbs(10.0, 1e-6)); // the axis's middle is the bore's centroid + CHECK_THAT(r.at("angle_deg").get<double>(), WithinAbs(90.0, 1e-6)); + } + SECTION("refusals name the ref") + { + CHECK_THAT(failure([&] { GUI::cad_measure(doc, {{"a", {{"face", top0}}}}); }), ContainsSubstring("needs refs 'a' and 'b'")); + CHECK_THAT(failure([&] { GUI::cad_measure(doc, {{"a", {{"face", top0}, {"edge", 1}}}, {"b", {{"face", 0}}}}); }), + ContainsSubstring("could not resolve ref \"a\"")); + CHECK_THAT(failure([&] { GUI::cad_measure(doc, {{"a", {{"face", top0}}}, {"b", {{"body", 1}, {"face", 99}}}}); }), + ContainsSubstring("ref \"b\": face 99 of body 1 does not exist")); + CHECK_THAT(failure([&] { GUI::cad_measure(doc, {{"a", {{"face", top0}, {"axis", true}}}, {"b", {{"face", 0}}}}); }), + ContainsSubstring("is planar; axis takes a cylindrical face")); + CHECK_THAT(failure([&] { GUI::cad_measure(doc, {{"a", {{"body", 5}, {"edge", 0}}}, {"b", {{"face", 0}}}}); }), + ContainsSubstring("body 5 is out of range")); + CHECK_THAT(failure([&] { GUI::cad_measure(doc, {{"a", {{"point", {1, 2}}}}, {"b", {{"face", 0}}}}); }), + ContainsSubstring("point must be [x, y, z]")); + } +} + +TEST_CASE("a hole drills a face's body at a world point or on a round reference's axis", "[Mcp][CAD]") +{ + CadDocument doc; + add_box(doc); // 40 x 20 x 10, centred on the origin, z 0..10 + const int top = face_facing(doc, Vec3d(0, 0, 1)); + SketchPlane pl; + int body = -2; + + const json at = GUI::cad_hole_placement(doc, {{"plane", {{"body", 0}, {"face", top}}}, {"at", {5, 3, 12}}}, pl, body); + CHECK(body == 0); + CHECK(at.at("body") == 0); + CHECK_THAT(at.at("off_plane").get<double>(), WithinAbs(-2.0, 1e-9)); // 2 mm above, against the inward normal + const Vec3d landed = pl.origin + pl.x_axis * at.at("x").get<double>() + pl.y_axis * at.at("y").get<double>(); + CHECK((landed - Vec3d(5, 3, 10)).norm() < 1e-9); + + // x and y as given, the last body by default on a base plane. + const json xy = GUI::cad_hole_placement(doc, {{"x", 4}, {"y", -2}}, pl, body); + CHECK(body == -1); + CHECK(xy.at("body") == 0); + CHECK(xy.at("x") == 4.0); + CHECK_FALSE(xy.contains("off_plane")); + + SECTION("on the axis of a bore, whatever the bed") + { + doc.modeling_origin = Vec3d(100, 50, 0); + doc.add_hole(3, 10, true, 10, 0, SketchPlane::XY(), "Hole"); + REQUIRE(doc.recompute()); + const int bore = cylinder_face(doc), roof = face_facing(doc, Vec3d(0, 0, 1)); + const json r = GUI::cad_hole_placement(doc, {{"plane", {{"body", 0}, {"face", roof}}}, {"at", {{"body", 0}, {"face", bore}}}}, pl, body); + const Vec3d on = pl.origin + pl.x_axis * r.at("x").get<double>() + pl.y_axis * r.at("y").get<double>(); + CHECK((on - Vec3d(10, 0, 10)).norm() < 1e-6); + // A counterbore there widens the bore's top. + const double before = body_volume(doc, 0); + const int h = doc.add_hole_styled(3, 10, true, r.at("x"), r.at("y"), pl, 1, 6, 2, 0, 90, "", "Hole"); + doc.features[h].target_body = body; + REQUIRE(doc.recompute()); + CHECK_THAT(before - body_volume(doc, 0), WithinAbs(PI * (9.0 - 2.25) * 2.0, 1e-3)); + // Its rim, a circular edge, names the same axis. + const json rim = GUI::cad_query_topology(doc, {{"edge_kinds", {"circle"}}}); + int e = -1; + for (const json& c : rim.at("edges")) + if (std::abs(c.at("radius").get<double>() - 3.0) < 1e-6) e = c.at("id"); + REQUIRE(e >= 0); + const json r2 = GUI::cad_hole_placement(doc, {{"plane", {{"body", 0}, {"face", face_facing(doc, Vec3d(0, 0, 1))}}}, {"at", {{"body", 0}, {"edge", e}}}}, pl, body); + CHECK((pl.origin + pl.x_axis * r2.at("x").get<double>() + pl.y_axis * r2.at("y").get<double>() - Vec3d(10, 0, 10)).norm() < 1e-6); + } + SECTION("a countersink from a side face leaves its cone in that face") + { + const int side = face_facing(doc, Vec3d(0, 1, 0)); // y = 10, 40 x 10 + const json r = GUI::cad_hole_placement(doc, {{"plane", {{"body", 0}, {"face", side}}}}, pl, body); + CHECK(body == 0); + const int h = doc.add_hole_styled(4, 20, true, r.at("x"), r.at("y"), pl, 2, 0, 0, 8, 90, "", "Hole"); + doc.features[h].target_body = body; + REQUIRE(doc.recompute()); + // A 4 mm bore through 20 mm, and a 90 degree seat 2 mm deep from 8 mm to 4 mm. + const double removed = PI * 4.0 * 20.0 + PI * 2.0 / 3.0 * (16.0 + 8.0 + 4.0) - PI * 4.0 * 2.0; + CHECK_THAT(body_volume(doc, 0), WithinAbs(8000.0 - removed, 1e-2)); + const json cones = GUI::cad_query_topology(doc, {{"kinds", {"conical"}}}); + REQUIRE(cones.at("faces_total") == 1); + const json& cone = cones.at("faces")[0]; + CHECK(cone.at("internal") == true); + CHECK_THAT(cone.at("radius_max").get<double>(), WithinAbs(4.0, 1e-6)); + CHECK_THAT(cone.at("half_angle_deg").get<double>(), WithinAbs(45.0, 1e-6)); + CHECK_THAT(cone.at("apex")[1].get<double>(), WithinAbs(6.0, 1e-6)); // inside, below the y = 10 face + CHECK_THAT(cone.at("axis")[1].get<double>(), WithinAbs(1.0, 1e-9)); // opening out of that face + } + SECTION("refusals") + { + add_box(doc); // a second body + CHECK_THAT(failure([&] { GUI::cad_hole_placement(doc, {{"plane", {{"body", 0}, {"face", top}}}, {"body", 1}}, pl, body); }), + ContainsSubstring("the plane is a face of body 0")); + CHECK_THAT(failure([&] { GUI::cad_hole_placement(doc, {{"at", {1, 2, 3}}, {"x", 1}}, pl, body); }), ContainsSubstring("not both")); + CHECK_THAT(failure([&] { GUI::cad_hole_placement(doc, {{"at", {1, 2}}}, pl, body); }), ContainsSubstring("at must be [x, y, z]")); + CHECK_THAT(failure([&] { GUI::cad_hole_placement(doc, {{"at", {{"body", 0}, {"face", top}}}}, pl, body); }), + ContainsSubstring("is planar; \"at\" takes a cylindrical face or a circular edge")); + CHECK_THAT(failure([&] { GUI::cad_hole_placement(doc, {{"body", 7}}, pl, body); }), ContainsSubstring("out of range")); + doc.features[doc.add_hole(3, 10, true, 0, 0, SketchPlane::XY(), "Hole")].target_body = 0; + REQUIRE(doc.recompute()); + const int bore = cylinder_face(doc), side = face_facing(doc, Vec3d(1, 0, 0)); + CHECK_THAT(failure([&] { + GUI::cad_hole_placement(doc, {{"plane", {{"body", 0}, {"face", side}}}, {"at", {{"body", 0}, {"face", bore}}}}, pl, body); + }), + ContainsSubstring("is not square to the plane")); + CadDocument empty; + CHECK_THAT(failure([&] { GUI::cad_hole_placement(empty, json::object(), pl, body); }), ContainsSubstring("no body to drill")); + } +} + +TEST_CASE("extrude pushes or pulls a planar face of a body", "[Mcp][CAD]") +{ + CadDocument doc; + add_box(doc); + const int top = face_facing(doc, Vec3d(0, 0, 1)); + SketchPlane frame; + + const int e = GUI::cad_face_extrude(doc, {{"face", top}, {"distance", 5}}, frame)("Extrude"); + CHECK(doc.features[e].mode == BooleanMode::Add); // joins the face's body, as the card does + CHECK(doc.features[e].target_body == 0); + CHECK_THAT(frame.origin.z(), WithinAbs(10.0, 1e-6)); + CHECK((frame.normal - Vec3d(0, 0, 1)).norm() < 1e-9); + REQUIRE(doc.recompute()); + REQUIRE(doc.bodies.size() == 1); + CHECK_THAT(body_volume(doc, 0), WithinAbs(40.0 * 20.0 * 15.0, 1e-6)); + + // Inward and cutting: 3 mm off the new top. + const int roof = face_facing(doc, Vec3d(0, 0, 1)); + GUI::cad_face_extrude(doc, {{"face", roof}, {"distance", 3}, {"flip", true}, {"boolean", "subtract"}}, frame)("Extrude"); + REQUIRE(doc.recompute()); + CHECK_THAT(body_volume(doc, 0), WithinAbs(40.0 * 20.0 * 12.0, 1e-6)); + + const size_t features = doc.features.size(); + auto refusal = [&](json params) { + params["face"] = params.value("face", json(roof)); + return failure([&] { GUI::cad_face_extrude(doc, params, frame); }); + }; + CHECK_THAT(refusal({{"sketch", 0}}), ContainsSubstring("sketch cannot be given with face")); + CHECK_THAT(refusal({{"plane", "XY"}}), ContainsSubstring("plane cannot be given with face")); + CHECK_THAT(refusal({{"end", "two_sided"}}), ContainsSubstring("ends blind or symmetric")); + CHECK_THAT(refusal({{"taper", 5}}), ContainsSubstring("taper does not apply")); + CHECK_THAT(refusal({{"face", 99}}), ContainsSubstring("face 99 of body 0 does not exist")); + CHECK_THAT(refusal({{"face", "2"}}), ContainsSubstring("face must be a face id")); + CHECK_THAT(refusal({{"boolean", "atuo"}}), ContainsSubstring("boolean must be")); + CHECK(doc.features.size() == features); + + CadDocument cyl; + add_cylinder(cyl); + CHECK_THAT(failure([&] { GUI::cad_face_extrude(cyl, {{"face", cylinder_face(cyl)}}, frame); }), + ContainsSubstring("is cylindrical; a push/pull needs a planar face")); +} + +TEST_CASE("plane adds the datum plane each construction gives, as the Plane card does", "[Mcp][CAD]") +{ + CadDocument doc; + doc.modeling_origin = Vec3d(100, 50, 0); + add_box(doc); // centred on the world origin, z 0..10 + auto add_plane = [&](const json& params) { + const int i = GUI::cad_datum_plane(doc, params)("Plane"); + REQUIRE(doc.recompute()); + int ordinal = 0; + for (int k = 0; k < i; ++k) + if (doc.features[k].type == CadFeatureType::Plane && doc.features[k].enabled) ++ordinal; + return std::make_pair(i, doc.resolve_datum_planes().at(ordinal).second); + }; + const int top = face_facing(doc, Vec3d(0, 0, 1)), bottom = face_facing(doc, Vec3d(0, 0, -1)); + + const auto [p40, offset] = add_plane({{"offset", 40}}); + CHECK((offset.origin - Vec3d(100, 50, 40)).norm() < 1e-9); + CHECK(doc.features[p40].plane_type == PlaneType::Offset); + CHECK(doc.features[p40].plane_u_size == 60.0); + + const auto [p60, stacked] = add_plane({{"base", {{"datum", p40}}}, {"size", {30, 20}}}); // the card's 20 mm + CHECK_THAT(stacked.origin.z(), WithinAbs(60.0, 1e-9)); + CHECK(doc.features[p60].plane_base == 3); + CHECK(doc.features[p60].plane_v_size == 20.0); + + const auto [pmid, mid] = add_plane({{"type", "midplane"}, {"face_a", {{"body", 0}, {"face", top}}}, {"face_b", {{"body", 0}, {"face", bottom}}}}); + CHECK_THAT(mid.origin.z(), WithinAbs(5.0, 1e-9)); + CHECK(std::abs(mid.normal.z()) > 1 - 1e-9); + + const auto [pon, on] = add_plane({{"type", "offset"}, {"face_a", {{"body", 0}, {"face", top}}}, {"offset", 2}}); + CHECK_THAT(on.origin.z(), WithinAbs(12.0, 1e-9)); + + const auto [pxz, xz] = add_plane({{"type", "coincident"}, {"base", "XZ"}}); + CHECK((xz.normal - Vec3d(0, 1, 0)).norm() < 1e-9); + CHECK_THAT(xz.origin.y(), WithinAbs(50.0, 1e-9)); + + const json top_edges = GUI::cad_query_topology(doc, {{"at_extreme", "+z"}, {"adjacency", true}}); + const int ea = top_edges.at("edges")[0].at("id"), eb = top_edges.at("edges")[1].at("id"); + const auto [p2, two] = add_plane({{"type", "two_edges"}, {"edge_a", {{"body", 0}, {"edge", ea}}}, {"edge_b", {{"body", 0}, {"edge", eb}}}}); + CHECK_THAT(two.origin.z(), WithinAbs(10.0, 1e-9)); + CHECK(std::abs(two.normal.z()) > 1 - 1e-9); + + // An edge of the top face, tilted 90 degrees from the top: a vertical plane through it. + const auto [pang, angled] = add_plane({{"type", "angle"}, {"edge_a", {{"body", 0}, {"edge", ea}}}, {"face_a", {{"body", 0}, {"face", top}}}, {"angle", 90}}); + CHECK(std::abs(angled.normal.z()) < 1e-9); + CHECK_THAT(angled.origin.z(), WithinAbs(10.0, 1e-9)); + + CadDocument cyl; + add_cylinder(cyl); + const int i = GUI::cad_datum_plane(cyl, {{"type", "tangent"}, {"face_a", {{"body", 0}, {"face", cylinder_face(cyl)}}}})("Plane"); + REQUIRE(cyl.recompute()); + const SketchPlane touch = cyl.resolve_datum_planes().at(0).second; + CHECK(i == 2); + CHECK_THAT(std::hypot(touch.origin.x(), touch.origin.y()), WithinAbs(10.0, 1e-9)); + CHECK(std::abs(touch.normal.z()) < 1e-9); +} + +TEST_CASE("plane refuses what the card refuses, and what a construction would not use", "[Mcp][CAD]") +{ + CadDocument doc; + add_box(doc); + const int top = face_facing(doc, Vec3d(0, 0, 1)); + const json face_a = {{"body", 0}, {"face", top}}; + const size_t features = doc.features.size(); + auto refusal = [&](const json& params) { return failure([&] { GUI::cad_datum_plane(doc, params); }); }; + + CHECK_THAT(refusal({{"type", "angle"}}), ContainsSubstring("An angled plane needs an edge")); + CHECK_THAT(refusal({{"type", "midplane"}, {"face_a", face_a}}), ContainsSubstring("A midplane needs two faces")); + CHECK_THAT(refusal({{"type", "midplane"}, {"face_a", face_a}, {"face_b", face_a}}), ContainsSubstring("the same face")); + CHECK_THAT(refusal({{"type", "tangent"}, {"face_a", face_a}}), ContainsSubstring("A tangent plane needs a cylindrical face")); + CHECK_THAT(refusal({{"type", "two_edges"}, {"edge_a", {{"body", 0}, {"edge", 0}}}}), ContainsSubstring("This plane needs two edges")); + CHECK_THAT(refusal({{"type", "slanted"}}), ContainsSubstring("type must be one of offset")); + CHECK_THAT(refusal({{"type", "midplane"}, {"offset", 5}}), ContainsSubstring("offset is not used by a midplane plane")); + CHECK_THAT(refusal({{"face_a", face_a}, {"base", "XZ"}}), ContainsSubstring("base is not used by a offset plane on face_a")); + CHECK_THAT(refusal({{"type", "two_edges"}, {"face_a", face_a}}), ContainsSubstring("face_a is not used")); + CHECK_THAT(refusal({{"face_a", {{"body", 0}, {"face", 99}}}}), ContainsSubstring("face_a: face 99 of body 0 does not exist")); + CHECK_THAT(refusal({{"face_a", {{"face", top}}}}), ContainsSubstring("face_a must be {\"body\": b, \"face\": id}")); + CHECK_THAT(refusal({{"base", {{"body", 0}, {"face", top}}}}), ContainsSubstring("a face goes in face_a")); + CHECK_THAT(refusal({{"base", {{"datum", 0}}}}), ContainsSubstring("is not a datum plane")); + CHECK_THAT(refusal({{"base", "ZX"}}), ContainsSubstring("plane must be")); + CHECK_THAT(refusal({{"angle", 200}}), ContainsSubstring("angle must be a number from -180 to 180")); + CHECK_THAT(refusal({{"axis", 2}}), ContainsSubstring("axis must be 0")); + CHECK_THAT(refusal({{"size", {0, 10}}}), ContainsSubstring("size must be [u, v]")); + CHECK(doc.features.size() == features); + + // The kernel check the Plane card shares: a reference that is gone is refused, not replaced. + CadFeature stale; + stale.type = CadFeatureType::Plane; + stale.plane_type = PlaneType::Offset; + stale.plane_face_body = 0; + stale.plane_face = 99; + CHECK_THAT(doc.datum_plane_refusal(stale), ContainsSubstring("no longer on the model")); + stale.plane_face = top; + CHECK(doc.datum_plane_refusal(stale).empty()); + stale.plane_type = PlaneType::TwoEdges; + stale.plane_edge_body = stale.plane_edge2_body = 0; + stale.plane_edge = 0; + stale.plane_edge2 = 500; + CHECK_THAT(doc.datum_plane_refusal(stale), ContainsSubstring("no longer on the model")); +} + +TEST_CASE("the rows for topology, measure, holes, push/pull and plane", "[Mcp][CAD]") +{ + const json reply = GUI::cad_describe_tools({{"method", {"query_topology", "measure", "hole", "hole_styled", "hole_standard", "extrude", "plane"}}}); + std::map<std::string, json> rows; + for (const json& row : reply.at("tools")) rows[row.at("name").get<std::string>()] = row; + auto param = [&](const char* method, const char* name) { + for (const json& p : rows.at(method).at("params")) + if (p.at("name") == name) return p; + FAIL(method << " has no param " << name); + return json(); + }; + CHECK(rows.at("plane").at("access") == "change"); + CHECK(rows.at("query_topology").at("access") == "read"); + CHECK(rows.at("measure").at("access") == "read"); + const json legacy = reply.at("legacy_ok_false"); + CHECK(std::find(legacy.begin(), legacy.end(), json("plane")) == legacy.end()); + // Optional everywhere: the socket bridge makes a param without a default required. + for (const char* k : {"kinds", "edge_kinds", "direction", "at_extreme", "convex", "limit"}) + CHECK(param("query_topology", k).at("default").is_null()); + for (const char* hole : {"hole", "hole_styled", "hole_standard"}) { + CHECK(param(hole, "at").at("default").is_null()); + CHECK(param(hole, "body").at("default") == -1); + } + CHECK(param("extrude", "face").at("default").is_null()); + for (const char* k : {"face_a", "face_b", "edge_a", "edge_b"}) CHECK(param("plane", k).at("default").is_null()); + CHECK(param("plane", "type").at("enum").size() == 6); +} + +namespace { + +// The bench's M5 hex standoff: a hexagon 8 mm across flats, 15 mm tall on the world XY plane, with +// a 4.134 mm through bore (M5's tap drill) on its axis. +void add_standoff(CadDocument& doc) +{ + SketchProfile hex; + for (int i = 0; i < 6; ++i) hex.points.emplace_back(4.618802 * std::cos(PI / 3 * i), 4.618802 * std::sin(PI / 3 * i)); + hex.closed = true; + doc.add_extrude(doc.add_sketch_profile(hex, SketchPlane::XY(), "Sketch"), 15.0, false, BooleanMode::New, "Extrude"); + doc.add_hole(4.134, 15, true, 0, 0, SketchPlane::XY(), "Hole"); + REQUIRE(doc.recompute()); +} + +// The first circular edge of body 0 of radius r. +int circle_edge(const CadDocument& doc, double r) +{ + const json rims = GUI::cad_query_topology(doc, {{"edge_kinds", {"circle"}}}); + for (const json& e : rims.at("edges")) + if (std::abs(e.at("radius").get<double>() - r) < 1e-6) return e.at("id").get<int>(); + return -1; +} + +// The first straight edge of body 0. +int line_edge(const CadDocument& doc) { return GUI::cad_query_topology(doc, {{"edge_kinds", {"line"}}}).at("edges").at(0).at("id").get<int>(); } + +BoundingBoxf3 body_box(const CadDocument& doc, size_t body) { return doc.display_body_meshes.at(body).bounding_box(); } + +} // namespace + +TEST_CASE("the nearest standard thread is matched across series, a bore on its minor diameter", "[Mcp][CAD]") +{ + CHECK(nearest_thread_standard(9.9, false)->name == "M10"); + CHECK(nearest_thread_standard(4.134, true)->name == "M5"); // M5's tap drill + // Metric and UTS sizes are scanned together, as the Thread card always has: a 5 mm bore is + // nearer 1/4-20 UNC's minor diameter (4.975) than M6's (4.918). + CHECK(nearest_thread_standard(5.0, true)->name == "1/4-20 UNC"); + CHECK(nearest_thread_standard(6.35, false)->name == "1/4-20 UNC"); // the first of the equally near 1/4" sizes +} + +TEST_CASE("a thread runs on the axis of a picked bore, else of a picked rim", "[Mcp][CAD]") +{ + CadDocument doc; + add_standoff(doc); + const int bore = cylinder_face(doc), top = face_facing(doc, Vec3d(0, 0, 1)), rim = circle_edge(doc, 2.067); + REQUIRE(bore >= 0); + REQUIRE(rim >= 0); + SketchPlane pl; + GeometryEngine::CylinderFace cyl; + bool from_face = false; + + REQUIRE(doc.thread_target(0, bore, -1, pl, cyl, &from_face)); + CHECK(from_face); + CHECK(cyl.internal); + CHECK_THAT(cyl.radius, WithinAbs(2.067, 1e-9)); + CHECK_THAT(cyl.height, WithinAbs(15.0, 1e-6)); + // On the axis at the bore's base, rising along it through the part's 15 mm. + CHECK((pl.normal - cyl.axis).norm() < 1e-12); + CHECK((pl.origin - cyl.base).norm() < 1e-12); + CHECK_THAT(std::hypot(pl.origin.x(), pl.origin.y()), WithinAbs(0.0, 1e-9)); + CHECK_THAT(std::min(pl.origin.z(), (pl.origin + pl.normal * 15.0).z()), WithinAbs(0.0, 1e-6)); + CHECK_THAT(pl.x_axis.dot(pl.normal), WithinAbs(0.0, 1e-12)); + CHECK_THAT(pl.y_axis.dot(pl.x_axis), WithinAbs(0.0, 1e-12)); + + // A face that is not round falls through to the edge, as the card's pick does. + REQUIRE(doc.thread_target(0, top, rim, pl, cyl, &from_face)); + CHECK_FALSE(from_face); + CHECK_FALSE(cyl.internal); // a rim cannot tell + CHECK_THAT(cyl.height, WithinAbs(0.0, 1e-12)); + CHECK_THAT(std::hypot(pl.origin.x(), pl.origin.y()), WithinAbs(0.0, 1e-9)); + + CHECK_FALSE(doc.thread_target(0, top, -1, pl, cyl, &from_face)); + CHECK_FALSE(doc.thread_target(1, bore, -1, pl, cyl)); +} + +TEST_CASE("thread on a bore takes the nearest standard and the whole bore, as the card does", "[Mcp][CAD]") +{ + CadDocument doc; + add_standoff(doc); + json r; + const auto add = GUI::cad_thread(doc, {{"face", cylinder_face(doc)}}, r); + CHECK(r.at("designation") == "M5"); + CHECK(r.at("internal") == true); + CHECK_THAT(r.at("diameter").get<double>(), WithinAbs(5.0, 1e-12)); + CHECK_THAT(r.at("pitch").get<double>(), WithinAbs(0.8, 1e-12)); + CHECK_THAT(r.at("depth").get<double>(), WithinAbs(find_thread_standard("M5")->internal_depth_mm(), 1e-12)); + CHECK_THAT(r.at("length").get<double>(), WithinAbs(15.0, 1e-6)); + CHECK(r.at("x") == 0.0); + const int t = add("Thread"); + CHECK(doc.features[t].target_body == 0); + CHECK(doc.features[t].thread_internal); + REQUIRE(doc.recompute()); + REQUIRE(doc.bodies.size() == 1); + const double tapped = body_volume(doc, 0); + CHECK(tapped > 600.0); // the bench case's bounds + CHECK(tapped < 614.0); + + SECTION("the same thread placed on the XY plane") + { + CadDocument plane_doc; + add_standoff(plane_doc); + json r2; + GUI::cad_thread(plane_doc, {{"plane", "XY"}, {"designation", "M5"}, {"internal", true}, {"length", 15}}, r2)("Thread"); + CHECK(r2.at("body") == 0); + CHECK(r2.at("x") == 0.0); + REQUIRE(plane_doc.recompute()); + CHECK_THAT(body_volume(plane_doc, 0), WithinAbs(tapped, 1.0)); + } + SECTION("a designation and a pitch replace what was inferred") + { + json r3; + GUI::cad_thread(doc, {{"face", cylinder_face(doc)}, {"designation", "M6"}}, r3); + CHECK(r3.at("designation") == "M6"); + CHECK_THAT(r3.at("depth").get<double>(), WithinAbs(find_thread_standard("M6")->internal_depth_mm(), 1e-12)); + GUI::cad_thread(doc, {{"face", cylinder_face(doc)}, {"pitch", 0.5}}, r3); + CHECK(r3.at("designation").is_null()); // no longer the standard's + CHECK_THAT(r3.at("depth").get<double>(), WithinAbs(0.5 * 1.0825 * 0.5, 1e-12)); + } +} + +TEST_CASE("a custom thread on a plane threads a rod from nothing", "[Mcp][CAD]") +{ + CadDocument doc; + json r; + GUI::cad_thread(doc, {{"plane", "XY"}, {"internal", false}, {"diameter", 6}, {"pitch", 1}, {"length", 10}}, r)("Thread"); + CHECK(r.at("designation").is_null()); + CHECK_THAT(r.at("depth").get<double>(), WithinAbs(0.6134, 1e-12)); + REQUIRE(doc.recompute()); + REQUIRE(doc.bodies.size() == 1); + const double v = body_volume(doc, 0); + CHECK(v < PI * 9.0 * 10.0); + CHECK(v > PI * (3.0 - 0.6134) * (3.0 - 0.6134) * 10.0); +} + +TEST_CASE("thread refuses a target it cannot cut, before anything changes", "[Mcp][CAD]") +{ + CadDocument doc; + add_standoff(doc); + const int bore = cylinder_face(doc), top = face_facing(doc, Vec3d(0, 0, 1)); + const size_t n = doc.features.size(); + auto refusal = [&](const json& params) { + json r; + return failure([&] { GUI::cad_thread(doc, params, r); }); + }; + CHECK_THAT(refusal({{"face", top}}), ContainsSubstring("is planar; a thread needs a cylindrical face or a circular edge")); + CHECK_THAT(refusal({{"face", 99}}), ContainsSubstring("face 99 of body 0 does not exist")); + CHECK_THAT(refusal({{"edge", line_edge(doc)}}), ContainsSubstring("is a line; a thread needs")); + CHECK_THAT(refusal({{"face", bore}, {"edge", line_edge(doc)}}), ContainsSubstring("not both")); + CHECK_THAT(refusal({{"face", bore}, {"x", 1}}), ContainsSubstring("x cannot be given with face")); + CHECK_THAT(refusal({{"face", bore}, {"designation", "M5x1"}}), ContainsSubstring("unknown designation \"M5x1\"; close: ")); + CHECK_THAT(refusal({{"face", bore}, {"designation", "M5x1"}}), ContainsSubstring("close: M5, M8x1")); + CHECK_THAT(refusal({{"face", bore}, {"designation", "m5"}}), ContainsSubstring("\"m5\"; close: M5")); + CHECK_THAT(refusal({{"face", bore}, {"designation", "1/4-20"}}), ContainsSubstring("close: 1/4-20 UNC")); + CHECK_THAT(refusal({{"face", bore}, {"designation", 5}}), ContainsSubstring("designation must be a string")); + CHECK_THAT(refusal({{"face", bore}, {"diameter", -1}}), ContainsSubstring("diameter must be a number > 0")); + CHECK_THAT(refusal({{"face", bore}, {"internal", "yes"}}), ContainsSubstring("internal must be true or false")); + CHECK_THAT(refusal({{"edge", circle_edge(doc, 2.067)}}), ContainsSubstring("length is required for a thread on an edge")); + CHECK_THAT(refusal({{"designation", "M5"}, {"length", 15}}), ContainsSubstring("internal is required")); + CHECK_THAT(refusal({{"internal", true}, {"length", 15}}), ContainsSubstring("needs designation, or diameter and pitch")); + CHECK_THAT(refusal({{"internal", true}, {"designation", "M5"}}), ContainsSubstring("length is required for a thread on a plane")); + CHECK_THAT(refusal({{"internal", true}, {"designation", "M5"}, {"length", 5}, {"body", 3}}), ContainsSubstring("out of range")); + CHECK(doc.features.size() == n); + + CadDocument empty; + json r; + CHECK_THAT(failure([&] { GUI::cad_thread(empty, {{"internal", true}, {"designation", "M5"}, {"length", 5}}, r); }), + ContainsSubstring("needs a body to tap")); + CHECK_THAT(failure([&] { GUI::cad_thread(empty, {{"face", 0}}, r); }), ContainsSubstring("no body to thread")); +} + +TEST_CASE("a sweep along a helix keeps its profile at the same angle to the helix axis", "[Mcp][CAD]") +{ + // A spring: radius 10, pitch 5, six turns, its profile drawn on the XZ plane at the helix start. + CadDocument doc; + const int helix = doc.add_helix(SketchPlane::XY(), 10.0, 5.0, 30.0, false, 0.0, "Helix"); + const double turn = std::hypot(2.0 * PI * 10.0, 5.0), length = 6.0 * turn; + // The XZ plane is tilted off the helix's normal plane by its lead angle. + const double across = 2.0 * PI * 10.0 / turn; + + SECTION("a round wire") + { + const int s = doc.add_sketch_entities({circle(10, 0, 1.5)}, SketchPlane::XZ(), "Sketch"); + GUI::cad_sweep(doc, {{"sketch", s}, {"path", helix}})("Sweep"); + REQUIRE(doc.recompute()); + REQUIRE(doc.bodies.size() == 1); + CHECK_THAT(body_volume(doc, 0), Catch::Matchers::WithinRel(PI * 1.5 * 1.5 * across * length, 0.01)); + } + SECTION("a square wire stays square to the axis: its outer face stays at radius 11") + { + const int s = doc.add_sketch_entities({line(9, -1, 11, -1), line(11, -1, 11, 1), line(11, 1, 9, 1), line(9, 1, 9, -1)}, + SketchPlane::XZ(), "Sketch"); + GUI::cad_sweep(doc, {{"sketch", s}, {"path", helix}, {"boolean", "new"}})("Sweep"); + REQUIRE(doc.recompute()); + REQUIRE(doc.bodies.size() == 1); + CHECK_THAT(body_volume(doc, 0), Catch::Matchers::WithinRel(4.0 * across * length, 0.01)); + // A profile that turned about the path would reach out to 10 + sqrt(2) at its corners. + const BoundingBoxf3 bb = body_box(doc, 0); + CHECK_THAT(bb.max.x(), WithinAbs(11.0, 0.02)); + CHECK_THAT(bb.min.x(), WithinAbs(-11.0, 0.02)); + CHECK_THAT(bb.max.y(), WithinAbs(11.0, 0.02)); + CHECK_THAT(bb.min.y(), WithinAbs(-11.0, 0.02)); + } +} + +TEST_CASE("sweep takes a sketch or a helix as its path and refuses anything else", "[Mcp][CAD]") +{ + CadDocument doc; + const int helix = doc.add_helix(SketchPlane::XY(), 10.0, 5.0, 10.0, false, 0.0, "Helix"); + const int s = doc.add_sketch_entities({circle(10, 0, 1.5)}, SketchPlane::XZ(), "Sketch"); + const int spine = doc.add_sketch_entities({line(0, 0, 0, 30)}, SketchPlane::YZ(), "Spine"); + const size_t n = doc.features.size(); + auto refusal = [&](const json& params) { return failure([&] { GUI::cad_sweep(doc, params); }); }; + CHECK(refusal({{"sketch", s}, {"path", spine}}).empty()); + CHECK_THAT(refusal({{"sketch", s}}), ContainsSubstring("path must be the feature index of a sketch or a helix")); + CHECK_THAT(refusal({{"sketch", s}, {"path", s}}), ContainsSubstring("cannot be the profile sketch")); + CHECK_THAT(refusal({{"sketch", s}, {"path", 9}}), ContainsSubstring("out of range")); + CHECK_THAT(refusal({{"sketch", helix}, {"path", spine}}), ContainsSubstring("is not a sketch")); + CHECK_THAT(refusal({{"sketch", s}, {"path", helix}, {"boolean", "union"}}), ContainsSubstring("needs a body")); + CHECK_THAT(refusal({{"sketch", s}, {"path", helix}, {"boolean", "join"}}), ContainsSubstring("boolean must be")); + add_box(doc); + const int ex = int(doc.features.size()) - 1; + CHECK_THAT(refusal({{"sketch", s}, {"path", ex}}), ContainsSubstring("(Extrude) is not a sketch or a helix")); + CHECK(doc.features.size() == n + 2); +} + +TEST_CASE("loft skins sketches on two planes in order, and refuses what is not a sketch", "[Mcp][CAD]") +{ + CadDocument doc; + SketchPlane up = SketchPlane::XY(); + up.origin.z() = 40; + const int base = doc.add_sketch_entities({line(-10, -10, 10, -10), line(10, -10, 10, 10), line(10, 10, -10, 10), line(-10, 10, -10, -10)}, + SketchPlane::XY(), "Base"); + const int top = doc.add_sketch_entities({circle(0, 0, 8)}, up, "Top"); + const size_t n = doc.features.size(); + auto refusal = [&](const json& params) { return failure([&] { GUI::cad_loft(doc, params); }); }; + CHECK_THAT(refusal({{"profiles", json::array({base})}}), ContainsSubstring("2 or more")); + CHECK_THAT(refusal({{"profiles", base}}), ContainsSubstring("profiles must be a list")); + CHECK_THAT(refusal({{"profiles", {base, base}}}), ContainsSubstring("listed twice")); + CHECK_THAT(refusal({{"profiles", {base, "1"}}}), ContainsSubstring("profiles must hold sketch feature indices")); + CHECK_THAT(refusal({{"profiles", {base, 7}}}), ContainsSubstring("out of range")); + CHECK_THAT(refusal({{"profiles", {base, top}}, {"ruled", "yes"}}), ContainsSubstring("ruled must be true or false")); + CHECK_THAT(refusal({{"profiles", {base, top}}, {"boolean", "subtract"}}), ContainsSubstring("needs a body")); + CHECK(doc.features.size() == n); + + const int l = GUI::cad_loft(doc, {{"profiles", {base, top}}})("Loft"); + CHECK(doc.features[l].loft_profile_refs == std::vector<int>({base, top})); + REQUIRE(doc.recompute()); + REQUIRE(doc.bodies.size() == 1); + const BoundingBoxf3 bb = body_box(doc, 0); + CHECK_THAT(bb.min.z(), WithinAbs(0.0, 1e-3)); + CHECK_THAT(bb.max.z(), WithinAbs(40.0, 1e-3)); + const double v = body_volume(doc, 0); + CHECK(v > PI * 64.0 * 40.0); // between a cylinder of the top and a prism of the base + CHECK(v < 400.0 * 40.0); + CHECK_THAT(refusal({{"profiles", {base, l}}}), ContainsSubstring("is not a sketch")); +} + +TEST_CASE("split cuts a body with a plane and keeps either piece", "[Mcp][CAD]") +{ + CadDocument doc; + add_box(doc); // 40 x 20 x 10, z 0..10 + json r; + + SECTION("both pieces, the upper one in the body's place") + { + GUI::cad_split(doc, {{"plane", "XY"}, {"offset", 4}}, r)("Cut"); + CHECK(doc.features.back().type == CadFeatureType::Cut); + CHECK(r.at("upper_body") == 0); + CHECK(r.at("lower_body") == 1); + CHECK_THAT(r.at("frame").at("origin")[2].get<double>(), WithinAbs(4.0, 1e-12)); + REQUIRE(doc.recompute()); + REQUIRE(doc.bodies.size() == 2); + CHECK_THAT(body_volume(doc, 0), WithinAbs(800.0 * 6.0, 1e-6)); + CHECK_THAT(body_volume(doc, 1), WithinAbs(800.0 * 4.0, 1e-6)); + } + SECTION("flip turns the plane over") + { + GUI::cad_split(doc, {{"plane", "XY"}, {"offset", 4}, {"flip", true}}, r)("Cut"); + CHECK_THAT(r.at("frame").at("normal")[2].get<double>(), WithinAbs(-1.0, 1e-12)); + REQUIRE(doc.recompute()); + CHECK_THAT(body_volume(doc, 0), WithinAbs(800.0 * 4.0, 1e-6)); + } + SECTION("one piece") + { + GUI::cad_split(doc, {{"plane", "XY"}, {"offset", 4}, {"keep_upper", false}}, r)("Cut"); + CHECK_FALSE(r.contains("upper_body")); + CHECK(r.at("lower_body") == 0); + REQUIRE(doc.recompute()); + REQUIRE(doc.bodies.size() == 1); + CHECK_THAT(body_volume(doc, 0), WithinAbs(800.0 * 4.0, 1e-6)); + } + SECTION("a face's plane, 3 mm into the body") + { + GUI::cad_split(doc, {{"plane", {{"body", 0}, {"face", face_facing(doc, Vec3d(0, 0, 1))}}}, {"offset", -3}}, r)("Cut"); + REQUIRE(doc.recompute()); + REQUIRE(doc.bodies.size() == 2); + CHECK_THAT(body_volume(doc, 0), WithinAbs(800.0 * 3.0, 1e-6)); // outside the face's plane + } + SECTION("along a face, as before") + { + GUI::cad_split(doc, {{"face", 2}, {"keep_lower", false}}, r)("Split"); + CHECK(doc.features.back().cut_face == 2); + CHECK(doc.features.back().cut_keep_lower == false); + CHECK(r.at("upper_body") == 0); + CHECK_FALSE(r.contains("frame")); + } + SECTION("refusals") + { + const size_t n = doc.features.size(); + auto refusal = [&](const json& params) { return failure([&] { GUI::cad_split(doc, params, r); }); }; + CHECK_THAT(refusal({{"plane", "XY"}, {"face", 2}}), ContainsSubstring("not both")); + CHECK_THAT(refusal(json::object()), ContainsSubstring("split needs plane")); + CHECK_THAT(refusal({{"plane", "XY"}, {"offset", 20}}), ContainsSubstring("the plane misses body 0: all of it lies on its lower side")); + CHECK_THAT(refusal({{"plane", "XY"}}), ContainsSubstring("the plane misses body 0: all of it lies on its upper side")); + CHECK_THAT(refusal({{"plane", "XY"}, {"offset", 4}, {"keep_upper", false}, {"keep_lower", false}}), ContainsSubstring("nothing would be kept")); + CHECK_THAT(refusal({{"plane", "XY"}, {"offset", "4"}}), ContainsSubstring("offset must be a number")); + CHECK_THAT(refusal({{"plane", "XY"}, {"offset", 4}, {"face_body", 0}}), ContainsSubstring("face_body goes with face")); + CHECK_THAT(refusal({{"face", 2}, {"offset", 1}}), ContainsSubstring("offset goes with plane")); + CHECK_THAT(refusal({{"face", 99}}), ContainsSubstring("face 99 of body 0 does not exist")); + CHECK_THAT(refusal({{"plane", "XY"}, {"offset", 4}, {"body", 2}}), ContainsSubstring("out of range")); + CHECK_THAT(refusal({{"plane", "QQ"}}), ContainsSubstring("plane must be")); + CHECK(doc.features.size() == n); + CadDocument empty; + CHECK_THAT(failure([&] { GUI::cad_split(empty, {{"plane", "XY"}}, r); }), ContainsSubstring("no body to split")); + } +} + +TEST_CASE("the rows for thread, sweep, loft, split and helix", "[Mcp][CAD]") +{ + const json reply = GUI::cad_describe_tools({{"method", {"thread", "sweep", "loft", "split", "helix"}}}); + std::map<std::string, json> rows; + for (const json& row : reply.at("tools")) rows[row.at("name").get<std::string>()] = row; + REQUIRE(rows.size() == 5); + auto param = [&](const char* method, const char* name) { + for (const json& p : rows.at(method).at("params")) + if (p.at("name") == name) return p; + FAIL(method << " has no param " << name); + return json(); + }; + const json legacy = reply.at("legacy_ok_false"); + for (const char* m : {"thread", "sweep", "loft", "split"}) { + CHECK(rows.at(m).at("access") == "change"); + CHECK(std::find(legacy.begin(), legacy.end(), json(m)) == legacy.end()); + } + // Optional on the socket bridge, which makes a param without a default required. + for (const char* k : {"face", "edge", "designation", "internal", "diameter", "pitch", "depth", "length", "plane", "at"}) + CHECK(param("thread", k).at("default").is_null()); + CHECK_FALSE(param("sweep", "sketch").contains("default")); + CHECK_FALSE(param("sweep", "path").contains("default")); + CHECK_FALSE(param("loft", "profiles").contains("default")); + CHECK(param("split", "plane").at("default").is_null()); + CHECK(param("split", "face").at("default").is_null()); + CHECK(param("split", "face_body").at("default") == -1); + CHECK_THAT(rows.at("helix").at("summary").get<std::string>(), ContainsSubstring("start and tangent")); +} + +// --- The open sketch: shapes, edit ops and constraints (cad_model A5, A7, A8) ----------------- + +namespace { + +// A fresh sketch session on XY, as sketch_begin leaves it: the Select tool armed. +void begin_sketch(GUI::DesignSketchTool& tool) { tool.begin(SketchPlane::XY(), GUI::DesignSketchTool::Mode::Select); } + +json sketch(GUI::DesignSketchTool& tool, const char* method, const json& params) +{ + return GUI::cad_sketch_call(tool, method, params); +} + +// The L-bracket's profile: 40 x 30, 4 thick, its inside corner between lines 2 and 3 at (4, 4). +json l_bracket() +{ + return json::array({ + {{"type", "line"}, {"p0", {0, 0}}, {"p1", {40, 0}}}, + {{"type", "line"}, {"p0", {40, 0}}, {"p1", {40, 4}}}, + {{"type", "line"}, {"p0", {40, 4}}, {"p1", {4, 4}}}, + {{"type", "line"}, {"p0", {4, 4}}, {"p1", {4, 30}}}, + {{"type", "line"}, {"p0", {4, 30}}, {"p1", {0, 30}}}, + {{"type", "line"}, {"p0", {0, 30}}, {"p1", {0, 0}}}, + }); +} + +double only_loop_area(const GUI::DesignSketchTool& tool) +{ + const GUI::DesignSketchTool::LoopReport rep = tool.loop_report(); + REQUIRE(rep.loops.size() == 1); + CHECK(rep.open_ends.empty()); + return std::abs(rep.loops[0].area); +} + +BoundingBoxf entities_box(const std::vector<SketchEntity>& ents, size_t first, size_t count) +{ + BoundingBoxf box; + for (size_t i = first; i < first + count; ++i) { + box.merge(ents[i].p0); + box.merge(ents[i].p1); + } + return box; +} + +} // namespace + +TEST_CASE("sketch_add draws polygons, slots, ellipses and splines as their tools do", "[Mcp][CAD]") +{ + GUI::DesignSketchTool tool; + begin_sketch(tool); + using ET = SketchEntity::Type; + + // A hexagon 8 across the flats: six lines, the first edge's midpoint on +x at the apothem. + json r = sketch(tool, "sketch_add", {{"type", "polygon"}, {"center", {0, 0}}, {"sides", 6}, {"across_flats", 8}}); + CHECK(r.at("first_index") == 0); + CHECK(r.at("added") == 6); + CHECK(r.at("shapes") == json::array({{{"first", 0}, {"count", 6}}})); + const auto& ents = tool.entities(); + REQUIRE(ents.size() == 6); + for (const SketchEntity& e : ents) CHECK(e.type == ET::Line); + const Vec2d mid = 0.5 * (ents[0].p0 + ents[0].p1); + CHECK_THAT(mid.x(), WithinAbs(4.0, 1e-9)); + CHECK_THAT(mid.y(), WithinAbs(0.0, 1e-9)); + const BoundingBoxf hex = entities_box(ents, 0, 6); + CHECK_THAT(hex.size().x(), WithinAbs(8.0, 1e-9)); // opposite flats 8 apart + CHECK_THAT(hex.size().y(), WithinAbs(8.0 / std::cos(PI / 6.0), 1e-9)); + CHECK(only_loop_area(tool) > 0); + + // The inscribed form puts its first vertex at the radius, turned by angle_deg. + r = sketch(tool, "sketch_add", {{"type", "polygon"}, {"center", {50, 0}}, {"sides", 4}, {"radius", 5}, {"angle_deg", 90}}); + CHECK_THAT(ents[6].p0.x(), WithinAbs(50.0, 1e-9)); + CHECK_THAT(ents[6].p0.y(), WithinAbs(5.0, 1e-9)); + + // A slot, an ellipse and its arc, and a spline in one list, with a line between them. + tool.cancel(); + begin_sketch(tool); + r = sketch(tool, "sketch_add", + {{"entities", + {{{"type", "slot"}, {"c0", {0, 0}}, {"c1", {20, 0}}, {"width", 5}}, + {{"type", "line"}, {"p0", {0, -20}}, {"p1", {10, -20}}}, + {{"type", "ellipse"}, {"center", {40, 0}}, {"radius", 10}, {"rminor", 6}, {"rotation", 0.5236}}, + {{"type", "ellipse_arc"}, {"center", {70, 0}}, {"radius", 10}, {"rminor", 6}, {"start_angle", 0}, {"end_angle_deg", 180}}, + {{"type", "spline"}, {"ctrl", {{0, 20}, {10, 30}, {20, 20}, {30, 30}}}}}}}); + CHECK(r.at("shapes") == json::parse(R"([{"first":0,"count":4},{"first":4,"count":1},{"first":5,"count":1}, + {"first":6,"count":1},{"first":7,"count":1}])")); + CHECK(r.at("entities") == 8); + const GUI::DesignSketchTool::LoopReport rep = tool.loop_report(); + bool slot_found = false; + for (const auto& l : rep.loops) + if (l.ents.size() == 4) { + slot_found = true; + CHECK_THAT(std::abs(l.area), WithinAbs(20.0 * 5.0 + PI * 2.5 * 2.5, 1e-6)); + } + CHECK(slot_found); + const SketchEntity& el = ents[5]; + CHECK(el.type == ET::Ellipse); + CHECK_THAT(el.radius, WithinAbs(10.0, 1e-9)); + CHECK_THAT(el.rminor, WithinAbs(6.0, 1e-9)); + CHECK_THAT(el.rotation, WithinAbs(0.5236, 1e-9)); + const SketchEntity& arc = ents[6]; + CHECK(arc.type == ET::EllipseArc); + CHECK_THAT(arc.start_angle, WithinAbs(0.0, 1e-9)); + CHECK_THAT(arc.end_angle, WithinAbs(PI, 1e-9)); + CHECK_THAT((arc.p0 - Vec2d(80, 0)).norm(), WithinAbs(0.0, 1e-9)); + CHECK_THAT((arc.p1 - Vec2d(60, 0)).norm(), WithinAbs(0.0, 1e-9)); + CHECK(ents[7].type == ET::BSpline); + CHECK(ents[7].ctrl.size() == 4); + CHECK(ents[7].ctrl[3] == Vec2d(30, 30)); + + // Construction comes from the item, whatever the tool's sticky setting says. + tool.set_construction(true); + tool.set_polygon_circumscribed(true); + sketch(tool, "sketch_add", {{"type", "polygon"}, {"center", {0, 60}}, {"sides", 3}, {"radius", 5}}); + CHECK_FALSE(ents.back().construction); + CHECK_THAT((ents[8].p0 - Vec2d(5, 60)).norm(), WithinAbs(0.0, 1e-9)); // inscribed: a vertex at the radius + tool.set_tool(GUI::DesignSketchTool::Mode::Polygon); + sketch(tool, "sketch_add", {{"type", "slot"}, {"c0", {0, 80}}, {"c1", {10, 80}}, {"width", 2}, {"construction", true}}); + CHECK(ents.back().construction); + CHECK(tool.mode() == GUI::DesignSketchTool::Mode::Polygon); // the armed tool is left as it was + CHECK(tool.pending_points() == 0); + + // Refusals change nothing, even when only a later item of a list is wrong. + const size_t n = ents.size(); + auto refused = [&](const json& params) { return failure([&] { sketch(tool, "sketch_add", params); }); }; + CHECK_THAT(refused({{"type", "polygon"}, {"center", {0, 0}}, {"sides", 2}, {"radius", 5}}), ContainsSubstring("3 to 1000")); + CHECK_THAT(refused({{"type", "polygon"}, {"center", {0, 0}}, {"sides", 6}, {"radius", 5}, {"across_flats", 8}}), + ContainsSubstring("one of them")); + CHECK_THAT(refused({{"type", "polygon"}, {"sides", 6}, {"radius", 5}}), ContainsSubstring("center must be [x, y]")); + CHECK_THAT(refused({{"type", "slot"}, {"c0", {0, 0}}, {"c1", {0, 0}}, {"width", 5}}), ContainsSubstring("must be apart")); + CHECK_THAT(refused({{"type", "slot"}, {"c0", {0, 0}}, {"c1", {9, 0}}, {"width", 0}}), ContainsSubstring("at least")); + CHECK_THAT(refused({{"type", "ellipse"}, {"center", {0, 0}}, {"radius", 5}, {"rminor", 6}}), ContainsSubstring("must not exceed")); + CHECK_THAT(refused({{"type", "ellipse_arc"}, {"center", {0, 0}}, {"radius", 5}, {"rminor", 3}, {"start_angle", 0}}), + ContainsSubstring("end_angle")); + CHECK_THAT(refused({{"type", "ellipse_arc"}, {"center", {0, 0}}, {"radius", 5}, {"rminor", 3}, {"start_angle", 0}, {"end_angle", 2 * PI}}), + ContainsSubstring("whole turn")); + CHECK_THAT(refused({{"type", "arc"}, {"center", {0, 0}}, {"radius", 5}, {"start_angle", 0}, {"start_angle_deg", 0}}), + ContainsSubstring("not both")); + CHECK_THAT(refused({{"type", "spline"}, {"ctrl", {{0, 0}}}}), ContainsSubstring("2 or more poles")); + CHECK_THAT(refused({{"type", "spline"}, {"ctrl", {{0, 0}, {0, 0}}}}), ContainsSubstring("coincide")); + CHECK_THAT(refused({{"entities", {{{"type", "line"}, {"p0", {0, 0}}, {"p1", {1, 0}}}, {{"type", "gear"}}}}}), + ContainsSubstring("unknown entity type")); + CHECK_THAT(refused(json::object()), ContainsSubstring("needs")); + CHECK(ents.size() == n); + + // An arc's angles may be given in degrees too. + sketch(tool, "sketch_add", {{"type", "arc"}, {"center", {0, 0}}, {"radius", 5}, {"start_angle_deg", 0}, {"end_angle_deg", 90}}); + CHECK_THAT(ents.back().end_angle, WithinAbs(PI / 2, 1e-12)); +} + +TEST_CASE("sketch_fillet rounds an inside corner with an arc bound tangent to both legs", "[Mcp][CAD]") +{ + using T = SketchConstraintType; + GUI::DesignSketchTool tool; + begin_sketch(tool); + sketch(tool, "sketch_add", {{"entities", l_bracket()}}); + CHECK_THAT(only_loop_area(tool), WithinAbs(264.0, 1e-9)); + + const json r = sketch(tool, "sketch_fillet", {{"entities", {2, 3}}, {"radius", 3}}); + CHECK(r.at("entity") == 6); + CHECK(r.at("lines") == json::array({2, 3})); + CHECK(r.at("released_constraints") == 1); // the sharp corner's coincidence + const auto& ents = tool.entities(); + REQUIRE(ents.size() == 7); + CHECK(ents[6].type == SketchEntity::Type::Arc); + CHECK_THAT(ents[6].radius, WithinAbs(3.0, 1e-9)); + CHECK_THAT((ents[6].center - Vec2d(7, 7)).norm(), WithinAbs(0.0, 1e-9)); + // The arc's ends sit on the legs and the loop stays closed, now 9 (1 - pi/4) larger. + CHECK_THAT(only_loop_area(tool), WithinAbs(264.0 + 9.0 * (1.0 - PI / 4.0), 1e-6)); + int coincident = 0, tangent = 0; + for (const SketchEntityConstraintDef& c : tool.constraints()) + if (c.ea == 6 || c.eb == 6) { + coincident += c.type == T::Coincident; + tangent += c.type == T::Tangent; + } + CHECK(coincident == 2); + CHECK(tangent == 2); + CHECK(tool.mode() == GUI::DesignSketchTool::Mode::Select); + + // A chamfer on the outer corner between lines 0 and 1 adds a line and keeps the loop closed, + // with the person's armed tool still armed afterwards. + tool.set_tool(GUI::DesignSketchTool::Mode::Line); + const json c = sketch(tool, "sketch_chamfer", {{"entities", {0, 1}}, {"distance", 2}}); + CHECK(c.at("entity") == 7); + CHECK(tool.mode() == GUI::DesignSketchTool::Mode::Line); + CHECK_FALSE(tool.value_field_open()); + CHECK(tool.entities()[7].type == SketchEntity::Type::Line); + CHECK_THAT(only_loop_area(tool), WithinAbs(264.0 + 9.0 * (1.0 - PI / 4.0) - 2.0, 1e-6)); + + // Refusals change nothing. + const size_t n = tool.entities().size(), nc = tool.constraints().size(); + auto refused = [&](const char* m, const json& params) { return failure([&] { sketch(tool, m, params); }); }; + CHECK_THAT(refused("sketch_fillet", {{"entities", {4, 5}}, {"radius", 50}}), ContainsSubstring("overruns a leg")); + CHECK_THAT(refused("sketch_fillet", {{"entities", {0, 2}}, {"radius", 1}}), ContainsSubstring("parallel")); + CHECK_THAT(refused("sketch_fillet", {{"entities", {6, 3}}, {"radius", 1}}), ContainsSubstring("arc 6 is not a line")); + CHECK_THAT(refused("sketch_fillet", {{"entities", {4}}, {"radius", 1}}), ContainsSubstring("two lines")); + CHECK_THAT(refused("sketch_fillet", {{"entities", {4, 5}}, {"radius", -1}}), ContainsSubstring("radius must be > 0")); + CHECK_THAT(refused("sketch_fillet", {{"entities", {4, 9}}, {"radius", 1}}), ContainsSubstring("entity 9 does not exist")); + CHECK_THAT(refused("sketch_chamfer", {{"entities", {4, 5}}}), ContainsSubstring("distance must be a number")); + CHECK(tool.entities().size() == n); + CHECK(tool.constraints().size() == nc); + + // The selection stands in for entities, as the tool's picks would. + tool.select_indices({4, 5}); + CHECK(sketch(tool, "sketch_fillet", {{"radius", 1}}).at("entity") == int(n)); +} + +TEST_CASE("sketch_trim cuts a line back to a crossing and extend runs one out to the next entity", "[Mcp][CAD]") +{ + GUI::DesignSketchTool tool; + begin_sketch(tool); + sketch(tool, "sketch_add", {{"entities", + {{{"type", "line"}, {"p0", {-10, 0}}, {"p1", {10, 0}}}, + {{"type", "line"}, {"p0", {0, -10}}, {"p1", {0, 10}}}, + {{"type", "line"}, {"p0", {0, 20}}, {"p1", {10, 20}}}, + {{"type", "line"}, {"p0", {30, 15}}, {"p1", {30, 25}}}, + {{"type", "circle"}, {"center", {60, 0}}, {"radius", 3}}, + {{"type", "line"}, {"p0", {100, -50}}, {"p1", {110, -50}}}}}}); + const auto& ents = tool.entities(); + + json r = sketch(tool, "sketch_trim", {{"at", {5, 0}}}); + CHECK(r.at("entity") == 0); + CHECK(r.at("geometry").at("type") == "line"); + CHECK(ents[0].p0 == Vec2d(-10, 0)); + CHECK(ents[0].p1.norm() < 1e-9); + + r = sketch(tool, "sketch_trim", {{"at", {9, 20}}, {"extend", true}}); + CHECK(r.at("entity") == 2); + CHECK_THAT((ents[2].p1 - Vec2d(30, 20)).norm(), WithinAbs(0.0, 1e-9)); + + const std::vector<SketchEntity> before = ents; + auto refused = [&](const json& params) { return failure([&] { sketch(tool, "sketch_trim", params); }); }; + CHECK_THAT(refused({{"at", {100, 100}}}), ContainsSubstring("no sketch entity within 0.05 mm")); + CHECK_THAT(refused({{"at", {63, 0}}, {"extend", true}}), ContainsSubstring("extend works on lines and arcs; circle 4")); + CHECK_THAT(refused({{"at", {63, 0}}}), ContainsSubstring("nothing to cut on circle 4")); + CHECK_THAT(refused({{"at", {105, -50}}}), ContainsSubstring("nothing to cut on line 5")); + CHECK_THAT(refused({{"at", {5, 0}}, {"tolerance", 0}}), ContainsSubstring("tolerance must be > 0")); + CHECK_THAT(refused({{"at", 5}}), ContainsSubstring("at must be [x, y]")); + for (size_t i = 0; i < before.size(); ++i) CHECK((ents[i].p0 == before[i].p0 && ents[i].p1 == before[i].p1)); + + // A wider tolerance reaches an entity a computed point misses: line 1 loses its part below line 0. + CHECK_THAT(refused({{"at", {0.3, -5}}}), ContainsSubstring("no sketch entity")); + r = sketch(tool, "sketch_trim", {{"at", {0.3, -5}}, {"tolerance", 0.5}}); + CHECK(r.at("entity") == 1); + CHECK(ents[1].p0.norm() < 1e-9); +} + +TEST_CASE("sketch_transform moves, rotates, scales and arrays as the transform tools do", "[Mcp][CAD]") +{ + using T = SketchConstraintType; + GUI::DesignSketchTool tool; + begin_sketch(tool); + sketch(tool, "sketch_add", {{"entities", + {{{"type", "line"}, {"p0", {8, 0}}, {"p1", {12, 0}}}, + {{"type", "line"}, {"p0", {1, 0}}, {"p1", {2, 0}}}, + {{"type", "circle"}, {"center", {30, 0}}, {"radius", 2}}}}}); + const auto& ents = tool.entities(); + + // Six around the origin: five copies every 60 degrees, each bound equal in length. + json r = sketch(tool, "sketch_transform", {{"op", "polar_array"}, {"entities", {0}}, {"count", 6}, {"pivot", {0, 0}}}); + CHECK(r.at("first_index") == 3); + CHECK(r.at("added") == 5); + CHECK(r.at("bound") == 5); + CHECK(r.at("pivot") == json::array({0.0, 0.0})); + for (int k = 1; k <= 5; ++k) { + const SketchEntity& e = ents[2 + k]; + CHECK_THAT((e.p0 - 8.0 * Vec2d(std::cos(k * PI / 3), std::sin(k * PI / 3))).norm(), WithinAbs(0.0, 1e-6)); + CHECK(tool.constraints()[tool.constraints().size() - 6 + k].type == T::EqualLength); + } + + // A linear array of the circle: two copies 5 apart, each with the source's radius. + r = sketch(tool, "sketch_transform", {{"op", "array"}, {"entities", {2}}, {"dy", 5}, {"count", 3}}); + CHECK(r.at("added") == 2); + CHECK((ents[8].center - Vec2d(30, 5)).norm() < 1e-9); + CHECK((ents[9].center - Vec2d(30, 10)).norm() < 1e-9); + CHECK_FALSE(r.contains("pivot")); + + // Rotate a quarter turn about the origin, then scale twice about it, then move. + r = sketch(tool, "sketch_transform", {{"op", "rotate"}, {"entities", {1}}, {"angle_deg", 90}, {"pivot", {0, 0}}}); + CHECK(r.at("moved") == json::array({1})); + CHECK((ents[1].p0 - Vec2d(0, 1)).norm() < 1e-9); + CHECK((ents[1].p1 - Vec2d(0, 2)).norm() < 1e-9); + sketch(tool, "sketch_transform", {{"op", "scale"}, {"entities", {1}}, {"scale", 2}, {"pivot", {0, 0}}}); + CHECK((ents[1].p1 - Vec2d(0, 4)).norm() < 1e-9); + sketch(tool, "sketch_transform", {{"op", "move"}, {"entities", {1}}, {"dx", 3}}); + CHECK((ents[1].p1 - Vec2d(3, 4)).norm() < 1e-9); + // Without a pivot, rotate turns about the entities' centroid, the gizmo's pivot. + r = sketch(tool, "sketch_transform", {{"op", "rotate"}, {"entities", {1}}, {"angle", PI}}); + CHECK_THAT(r.at("pivot")[0].get<double>(), WithinAbs(3.0, 1e-9)); + CHECK_THAT(r.at("pivot")[1].get<double>(), WithinAbs(3.0, 1e-9)); + CHECK((ents[1].p1 - Vec2d(3, 2)).norm() < 1e-9); + CHECK(tool.mode() == GUI::DesignSketchTool::Mode::Select); + + const size_t n = ents.size(); + auto refused = [&](const json& params) { return failure([&] { sketch(tool, "sketch_transform", params); }); }; + CHECK_THAT(refused({{"op", "spin"}, {"entities", {1}}}), ContainsSubstring("op must be")); + CHECK_THAT(refused({{"op", "move"}, {"entities", {1}}, {"dx", 1}, {"angle", 1}}), ContainsSubstring("move takes no angle")); + CHECK_THAT(refused({{"op", "move"}, {"entities", {1}}}), ContainsSubstring("non-zero dx or dy")); + CHECK_THAT(refused({{"op", "rotate"}, {"entities", {1}}}), ContainsSubstring("non-zero angle")); + CHECK_THAT(refused({{"op", "scale"}, {"entities", {1}}, {"scale", 1}}), ContainsSubstring("other than 1")); + CHECK_THAT(refused({{"op", "polar_array"}, {"entities", {1}}, {"count", 4}}), ContainsSubstring("needs pivot")); + CHECK_THAT(refused({{"op", "array"}, {"entities", {1}}, {"dx", 1}, {"count", 1}}), ContainsSubstring("2 to 1000")); + CHECK_THAT(refused({{"op", "array"}, {"entities", {1, 1}}, {"dx", 1}, {"count", 2}}), ContainsSubstring("listed twice")); + CHECK_THAT(refused({{"op", "move"}, {"dx", 1}}), ContainsSubstring("nothing selected")); + CHECK(ents.size() == n); +} + +TEST_CASE("constraints are planned from picks as the CONSTRAIN bar does, or taken from refs as written", "[Mcp][CAD]") +{ + using T = SketchConstraintType; + using R = SketchPointRole; + // 0 and 1: two lines at 45 degrees; 2 a circle; 3 an arc; 4 a point. + std::vector<SketchEntity> ents = {line(0, 0, 10, 0), line(0, 0, 10, 10)}; + SketchEntity circ; + circ.type = SketchEntity::Type::Circle; + circ.center = circ.p0 = Vec2d(20, 0); + circ.radius = 3; + SketchEntity arc; + arc.type = SketchEntity::Type::Arc; + arc.center = Vec2d(30, 0); + arc.radius = 2; + arc.start_angle = 0; + arc.end_angle = PI; + arc.p0 = Vec2d(32, 0); + arc.p1 = Vec2d(28, 0); + SketchEntity pt; + pt.type = SketchEntity::Type::Point; + pt.p0 = Vec2d(5, 5); + ents.insert(ents.end(), {circ, arc, pt}); + auto defs = [&](const json& params, const std::vector<int>& sel = {}) { return GUI::cad_constraint_defs(params, ents, sel); }; + auto refused = [&](const json& params) { return failure([&] { defs(params); }); }; + + // Picks: the planner's points and the current value, an angle in degrees stored in radians. + auto d = defs({{"type", "angle"}, {"entities", {0, 1}}}); + REQUIRE(d.size() == 1); + CHECK(d[0].type == T::Angle); + CHECK_THAT(d[0].value, WithinAbs(PI / 4, 1e-9)); + CHECK_THAT(defs({{"type", "angle"}, {"entities", {0, 1}}, {"value", 30}})[0].value, WithinAbs(PI / 6, 1e-12)); + CHECK(defs({{"type", "parallel"}}, {0, 1})[0].eb == 1); // the selection stands in for entities + CHECK(defs({{"type", "equal"}, {"entities", {2, 3}}})[0].type == T::EqualRadius); + CHECK(defs({{"type", "equal"}, {"entities", {0, 1}}})[0].type == T::EqualLength); + d = defs({{"type", "coincident"}, {"entities", {0, 3}}}); + CHECK((d[0].ea == 0 && d[0].eb == 3)); + CHECK_THAT(defs({{"type", "radius"}, {"entities", {2}}})[0].value, WithinAbs(3.0, 1e-12)); + + // Refs: points with roles, the origin and the axes, and the types the bar has no button for. + d = defs({{"type", "coincident"}, {"refs", {{{"entity", 2}}, {{"entity", "origin"}}}}}); + CHECK((d[0].ea == 2 && d[0].ra == R::Center && d[0].eb == kSketchRefOrigin)); + d = defs({{"type", "distance"}, {"refs", {{{"entity", 0}, {"role", "p0"}}, {{"entity", 0}, {"role", "p1"}}}}, {"value", 40}}); + CHECK((d[0].type == T::Distance && d[0].ea == 0 && d[0].rb == R::P1 && d[0].value == 40.0)); + d = defs({{"type", "lock_x"}, {"refs", {{{"entity", 3}, {"role", "center"}}}}, {"value", -5}}); + CHECK((d[0].ra == R::Center && d[0].value == -5.0)); + CHECK(defs({{"type", "point_on_line"}, {"refs", {{{"entity", 4}}, {{"entity", "x_axis"}}}}})[0].value == 0.0); + d = defs({{"type", "parallel"}, {"refs", {{{"entity", 0}}, {{"entity", "y_axis"}}}}}); + CHECK(d[0].eb == kSketchRefAxisY); + d = defs({{"type", "concentric"}, {"refs", {{{"entity", 2}}, {{"entity", 3}}}}}); + CHECK((d[0].ra == R::Center && d[0].rb == R::Center)); + d = defs({{"type", "symmetric"}, {"refs", {{{"entity", 0}, {"role", "p1"}}, {{"entity", 1}, {"role", "p1"}}, {{"entity", "x_axis"}}}}}); + CHECK(d[0].ec == kSketchRefAxisX); + + CHECK_THAT(refused({{"type", "parallell"}, {"entities", {0, 1}}}), ContainsSubstring("did you mean \"parallel\"")); + CHECK_THAT(refused({{"type", "parallel"}, {"entities", {0, 2}}}), ContainsSubstring("got line 0, circle 2 (need_two_lines)")); + CHECK_THAT(refused({{"type", "distance"}, {"entities", {0, 1}}}), ContainsSubstring("(unsupported)")); + CHECK_THAT(refused({{"type", "parallel"}}), ContainsSubstring("(need_two_entities)")); + CHECK_THAT(refused({{"type", "horizontal"}, {"entities", {0, 1}}}), ContainsSubstring("takes 1 entity")); + CHECK_THAT(refused({{"type", "parallel"}, {"entities", {0, 7}}}), ContainsSubstring("entity 7 does not exist")); + CHECK_THAT(refused({{"type", "parallel"}, {"entities", {0, 1}}, {"value", 3}}), ContainsSubstring("takes no value")); + CHECK_THAT(refused({{"type", "parallel"}, {"entities", {0, 1}}, {"refs", {{{"entity", 0}}}}}), ContainsSubstring("not both")); + CHECK_THAT(refused({{"type", "distance"}, {"refs", {{{"entity", 0}, {"role", "p0"}}, {{"entity", 0}, {"role", "p1"}}}}}), + ContainsSubstring("distance needs value")); + CHECK_THAT(refused({{"type", "coincident"}, {"refs", {{{"entity", 0}, {"role", "center"}}, {{"entity", "origin"}}}}}), + ContainsSubstring("role \"center\" does not exist on line 0")); + CHECK_THAT(refused({{"type", "coincident"}, {"refs", {{{"entity", 0}}, {{"entity", "origin"}}}}}), + ContainsSubstring("needs a role: line 0 has p0, p1")); + CHECK_THAT(refused({{"type", "parallel"}, {"refs", {{{"entity", 0}, {"role", "p0"}}, {{"entity", 1}}}}}), + ContainsSubstring("takes no role")); + CHECK_THAT(refused({{"type", "parallel"}, {"refs", {{{"entity", 0}}, {{"entity", 3}}}}}), + ContainsSubstring("parallel needs two lines; arc 3 is not one")); + CHECK_THAT(refused({{"type", "tangent"}, {"refs", {{{"entity", 0}}, {{"entity", 1}}}}}), ContainsSubstring("got line 0 and line 1")); + CHECK_THAT(refused({{"type", "radius"}, {"refs", {{{"entity", 2}}}}, {"value", 0}}), ContainsSubstring("must be > 0")); + CHECK_THAT(refused({{"type", "fix"}, {"refs", {{{"entity", 4}}, {{"entity", 0}, {"role", "p0"}}}}}), + ContainsSubstring("fix takes refs: one point")); + CHECK_THAT(refused({{"type", "coincident"}, {"refs", {{{"entity", "x_axis"}}, {{"entity", 4}}}}}), + ContainsSubstring("names a point")); + + // The planner's value rule, which the panel's live and committed constraint paths share. + std::vector<SketchEntityConstraintDef> planned(2); + planned[0].type = T::Angle; + planned[1].type = T::Distance; + write_plan_value(planned, 90.0); + CHECK_THAT(planned[0].value, WithinAbs(PI / 2, 1e-12)); + CHECK(planned[1].value == 90.0); +} + +TEST_CASE("sketch_constrain solves with the new constraint or rolls it back, and sketch_unconstrain frees it", "[Mcp][CAD]") +{ + GUI::DesignSketchTool tool; + begin_sketch(tool); + sketch(tool, "sketch_add", {{"rect", {0, 0, 30, 20}}}); + const int free_dof = tool.dof(); // position, width and height + CHECK(free_dof == 4); + const size_t inferred = tool.constraints().size(); + + const json width = {{"type", "distance"}, {"refs", {{{"entity", 0}, {"role", "p0"}}, {{"entity", 0}, {"role", "p1"}}}}, {"value", 40}}; + json r = sketch(tool, "sketch_constrain", width); + CHECK(r.at("added") == json::array({int(inferred)})); + CHECK(r.at("items")[0].at("type") == "distance"); + CHECK(r.at("items")[0].at("value") == 40.0); + CHECK(r.at("dof") == free_dof - 1); + CHECK_THAT((tool.entities()[0].p1 - tool.entities()[0].p0).norm(), WithinAbs(40.0, 1e-6)); + + // A rival width cannot be met: rolled back, and the sketch is as it was. + json rival = width; + rival["value"] = 25; + CHECK_THAT(failure([&] { sketch(tool, "sketch_constrain", rival); }), ContainsSubstring("over-constrained")); + CHECK(tool.constraints().size() == inferred + 1); + CHECK(tool.dof() == free_dof - 1); + + // Pinning the corner to the origin through the CONSTRAIN bar's picks and refs. + r = sketch(tool, "sketch_constrain", {{"type", "coincident"}, {"refs", {{{"entity", 0}, {"role", "p0"}}, {{"entity", "origin"}}}}}); + CHECK(r.at("dof") == free_dof - 3); + CHECK(tool.entities()[0].p0.norm() < 1e-6); + + const json list = sketch(tool, "sketch_constraints", json::object()); + CHECK(list.at("scope") == "live"); + REQUIRE(list.at("items").size() == inferred + 2); + CHECK(list.at("items").back().at("refs")[1] == json{{"entity", "origin"}}); + + r = sketch(tool, "sketch_unconstrain", {{"index", int(inferred)}}); // the width + CHECK(r.at("removed").at("type") == "distance"); + CHECK(r.at("constraints") == int(inferred + 1)); + CHECK(r.at("dof") == free_dof - 2); + CHECK_THAT(failure([&] { sketch(tool, "sketch_unconstrain", {{"index", 99}}); }), ContainsSubstring("out of range")); + CHECK_THAT(failure([&] { sketch(tool, "sketch_unconstrain", json::object()); }), ContainsSubstring("index must be")); + CHECK_THAT(failure([&] { sketch(tool, "sketch_move", json::object()); }), ContainsSubstring("not a method of the open sketch")); +} + +TEST_CASE("the rows for the sketch's shapes, edit ops and constraints", "[Mcp][CAD]") +{ + const std::vector<const char*> methods = {"sketch_add", "sketch_fillet", "sketch_chamfer", "sketch_trim", + "sketch_transform", "sketch_constrain", "sketch_constraints", "sketch_unconstrain"}; + json names = json::array(); + for (const char* m : methods) names.push_back(m); + const json reply = GUI::cad_describe_tools({{"method", names}}); + std::map<std::string, json> rows; + for (const json& row : reply.at("tools")) rows[row.at("name").get<std::string>()] = row; + REQUIRE(rows.size() == methods.size()); + const json legacy = reply.at("legacy_ok_false"); + for (const char* m : methods) { + CHECK(rows.at(m).at("access") == (std::string(m) == "sketch_constraints" ? "read" : "sketch")); + CHECK(std::find(legacy.begin(), legacy.end(), json(m)) == legacy.end()); + } + auto param = [&](const char* method, const char* name) { + for (const json& p : rows.at(method).at("params")) + if (p.at("name") == name) return p; + FAIL(method << " has no param " << name); + return json(); + }; + // Required on the socket bridge, which makes a param without a default required. + for (const auto& [m, k] : std::vector<std::pair<const char*, const char*>>{ + {"sketch_fillet", "radius"}, {"sketch_chamfer", "distance"}, {"sketch_trim", "at"}, {"sketch_transform", "op"}, + {"sketch_constrain", "type"}, {"sketch_unconstrain", "index"}}) + CHECK_FALSE(param(m, k).contains("default")); + for (const char* k : {"angle", "scale", "count", "pivot"}) CHECK(param("sketch_transform", k).at("default").is_null()); + CHECK(param("sketch_constraints", "sketch").at("default").is_null()); + const json types = param("sketch_add", "type").at("enum"); + for (const char* t : {"polygon", "slot", "ellipse", "ellipse_arc", "spline"}) + CHECK(std::find(types.begin(), types.end(), json(t)) != types.end()); + // Every constraint type the recipe stores has its name in the enum. + const json ctypes = param("sketch_constrain", "type").at("enum"); + CHECK(ctypes.size() == size_t(SketchConstraintType::SymmetricAboutX) + 2); // and "equal" +} diff --git a/tests/slic3rutils/test_mcp_config.cpp b/tests/slic3rutils/test_mcp_config.cpp new file mode 100644 index 0000000000..7819056160 --- /dev/null +++ b/tests/slic3rutils/test_mcp_config.cpp @@ -0,0 +1,929 @@ +// McpTools.hpp reaches wx's MSW headers through GLCanvas3D.hpp after OCCT has hidden the USER and GDI +// declarations they need; the Windows headers first keep them, as in test_plugin_host_api.cpp. +#ifdef WIN32 + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #ifndef NOMINMAX + #define NOMINMAX + #endif + #include <Windows.h> + #include <CommCtrl.h> +#endif + +#include <catch2/catch_test_macros.hpp> +#include <catch2/matchers/catch_matchers.hpp> +#include <catch2/matchers/catch_matchers_string.hpp> + +#include "slic3r/GUI/Mcp/McpTools.hpp" +#include "slic3r/GUI/Mcp/McpTypes.hpp" + +#include "libslic3r/AppConfig.hpp" +#include "libslic3r/Config.hpp" +#include "libslic3r/CustomGCode.hpp" +#include "libslic3r/ExtrusionEntity.hpp" +#include "libslic3r/GCode/GCodeProcessor.hpp" +#include "libslic3r/Model.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/Preset.hpp" +#include "libslic3r/PrintConfig.hpp" +#include "libslic3r/TriangleMesh.hpp" +#include "libslic3r/calib.hpp" + +#include <nlohmann/json.hpp> + +#include <algorithm> +#include <climits> +#include <cstddef> +#include <initializer_list> +#include <string> +#include <utility> +#include <vector> + +using namespace Slic3r; +using namespace Slic3r::GUI::Mcp; +using nlohmann::json; + +namespace { + +bool has(const std::vector<std::string>& keys, const std::string& key) +{ + return std::find(keys.begin(), keys.end(), key) != keys.end(); +} + +// What SettingsFactory::get_options() returns for an FFF printer: region keys for a part or +// modifier, and object keys as well for an object. +std::vector<std::string> fff_options(bool is_part) +{ + std::vector<std::string> keys = PrintRegionConfig().keys(); + if (!is_part) { + const std::vector<std::string> object_keys = PrintObjectConfig().keys(); + keys.insert(keys.end(), object_keys.begin(), object_keys.end()); + } + return keys; +} + +// A 20 mm cube object with process wall_loops 2 and infill 15 %. +struct Scene +{ + Model model; + ModelObject* object = nullptr; + DynamicPrintConfig process; + + Scene() + { + object = model.add_object(); + object->add_volume(make_cube(20., 20., 20.)); + object->add_instance(); + process.set_key_value("wall_loops", new ConfigOptionInt(2)); + process.set_key_value("sparse_infill_density", new ConfigOptionPercent(15)); + } + + ModelVolume* add(ModelVolumeType type) + { + return object->add_volume(make_cube(5., 5., 5.), type); + } +}; + +// Process presets: a system one, user presets "Mine" (selected) and "Other", and one kept inside the project. +struct Processes +{ + PresetCollection presets{Preset::TYPE_PRINT, Preset::print_options(), static_cast<const PrintRegionConfig&>(FullPrintConfig::defaults())}; + + Processes() + { + add("0.20mm Standard").is_system = true; + add("Mine"); + add("Other"); + add("In Project").is_project_embedded = true; + presets.select_preset_by_name("Mine", true); + } + + Preset& add(const std::string& name) + { + return presets.load_preset(std::string(), name, DynamicPrintConfig(presets.default_preset().config), /*select=*/false); + } +}; + +} // namespace + +TEST_CASE("the object scope takes the settings the object list offers an object, and its filament", "[Mcp]") +{ + const std::vector<std::string> one = model_scope_options(fff_options(false), false, 1); + CHECK(has(one, "wall_loops")); + CHECK(has(one, "enable_support")); + CHECK(has(one, "fuzzy_skin")); + CHECK(has(one, "extruder")); + // Keys a person cannot add to an object, accepted while the scope took Preset::print_options(). + REQUIRE(has(Preset::print_options(), "print_extruder_id")); + REQUIRE(has(Preset::print_options(), "print_sequence")); + CHECK_FALSE(has(one, "print_extruder_id")); + CHECK_FALSE(has(one, "print_sequence")); + // Per-feature filaments are offered once there is a second filament. + CHECK_FALSE(has(one, "outer_wall_filament_id")); + CHECK(has(model_scope_options(fff_options(false), false, 2), "outer_wall_filament_id")); + CHECK(has(one, "support_filament")); +} + +TEST_CASE("the volume scope takes the settings the object list offers a part or modifier", "[Mcp]") +{ + const std::vector<std::string> part = model_scope_options(fff_options(true), true, 2); + CHECK(has(part, "wall_loops")); + CHECK(has(part, "sparse_infill_density")); + CHECK(has(part, "outer_wall_filament_id")); + CHECK(has(part, "extruder")); + // Object-wide settings stay on the object. + CHECK_FALSE(has(part, "layer_height")); + CHECK_FALSE(has(part, "enable_support")); + CHECK_FALSE(has(part, "print_extruder_id")); +} + +TEST_CASE("an object's effective value is its override, else the process's", "[Mcp]") +{ + Scene s; + s.object->config.set("wall_loops", 4); + + json e = effective_setting("wall_loops", s.process, *s.object, nullptr); + CHECK(e["effective"] == "4"); + CHECK(e["source"] == "object"); + CHECK_FALSE(e.contains("parts")); + + e = effective_setting("sparse_infill_density", s.process, *s.object, nullptr); + CHECK(e["effective"] == "15%"); + CHECK(e["source"] == "process"); + + // A key the process does not carry takes the option's default. + e = effective_setting("enable_support", s.process, *s.object, nullptr); + CHECK(e["effective"] == "0"); + CHECK(e["source"] == "default"); +} + +TEST_CASE("a modifier's override applies only inside its own volume", "[Mcp]") +{ + Scene s; + s.object->config.set("wall_loops", 4); + ModelVolume* modifier = s.add(ModelVolumeType::PARAMETER_MODIFIER); + modifier->config.set_key_value("sparse_infill_density", new ConfigOptionPercent(40)); + + // For the object: the process value, with the modifier's listed apart. + json e = effective_setting("sparse_infill_density", s.process, *s.object, nullptr); + CHECK(e["effective"] == "15%"); + CHECK(e["source"] == "process"); + REQUIRE(e["parts"].size() == 1); + CHECK(e["parts"][0]["volume"] == 1); + CHECK(e["parts"][0]["value"] == "40%"); + + // Inside the modifier: its own value, and the object's or process's for the rest. + e = effective_setting("sparse_infill_density", s.process, *s.object, modifier); + CHECK(e["effective"] == "40%"); + CHECK(e["source"] == "part"); + CHECK_FALSE(e.contains("parts")); + e = effective_setting("wall_loops", s.process, *s.object, modifier); + CHECK(e["effective"] == "4"); + CHECK(e["source"] == "object"); + + // Volumes that print nothing of their own are not listed. + s.add(ModelVolumeType::NEGATIVE_VOLUME)->config.set_key_value("sparse_infill_density", new ConfigOptionPercent(90)); + s.add(ModelVolumeType::SUPPORT_BLOCKER)->config.set_key_value("sparse_infill_density", new ConfigOptionPercent(90)); + CHECK(effective_setting("sparse_infill_density", s.process, *s.object, nullptr)["parts"].size() == 1); +} + +TEST_CASE("a filament of 0 is no filament of its own", "[Mcp]") +{ + Scene s; + json e = effective_setting("extruder", s.process, *s.object, nullptr); + CHECK(e["effective"] == "1"); + CHECK(e["source"] == "default"); + + s.object->config.set("extruder", 2); + ModelVolume* part = s.add(ModelVolumeType::MODEL_PART); + ModelVolume* modifier = s.add(ModelVolumeType::PARAMETER_MODIFIER); + part->config.set("extruder", 3); + modifier->config.set("extruder", 0); + + e = effective_setting("extruder", s.process, *s.object, nullptr); + CHECK(e["effective"] == "2"); + CHECK(e["source"] == "object"); + REQUIRE(e["parts"].size() == 1); + CHECK(e["parts"][0]["volume"] == 1); + CHECK(e["parts"][0]["value"] == "3"); + + e = effective_setting("extruder", s.process, *s.object, part); + CHECK(e["effective"] == "3"); + CHECK(e["source"] == "part"); + e = effective_setting("extruder", s.process, *s.object, modifier); + CHECK(e["effective"] == "2"); + CHECK(e["source"] == "object"); +} + +TEST_CASE("save_preset refuses the names the Save preset dialog refuses", "[Mcp]") +{ + using Catch::Matchers::ContainsSubstring; + Processes p; + CHECK_THROWS_WITH(save_preset_inside_project(p.presets, "a:b", json::object()), ContainsSubstring("illegal characters")); + CHECK_THROWS_AS(save_preset_inside_project(p.presets, "", json::object()), ToolFailure); + CHECK_THROWS_AS(save_preset_inside_project(p.presets, "Mine ", json::object()), ToolFailure); + // A system preset is never overwritten. + CHECK_THROWS_AS(save_preset_inside_project(p.presets, "0.20mm Standard", json{{"overwrite", true}}), ToolFailure); +} + +TEST_CASE("save_preset replaces another preset only with overwrite, and saves the selected one again without", "[Mcp]") +{ + using Catch::Matchers::ContainsSubstring; + Processes p; + CHECK_THROWS_WITH(save_preset_inside_project(p.presets, "Other", json::object()), ContainsSubstring("overwrite")); + CHECK_FALSE(save_preset_inside_project(p.presets, "Other", json{{"overwrite", true}})); + // The selected preset's own name is the tab's plain Save. + CHECK_FALSE(save_preset_inside_project(p.presets, "Mine", json::object())); +} + +TEST_CASE("save_preset keeps a preset where the Save preset dialog would", "[Mcp]") +{ + Processes p; + // A new name: where the edited preset is, unless inside_project says otherwise. + CHECK_FALSE(save_preset_inside_project(p.presets, "New", json::object())); + CHECK(save_preset_inside_project(p.presets, "New", json{{"inside_project", true}})); + p.presets.select_preset_by_name("In Project", true); + CHECK(save_preset_inside_project(p.presets, "New", json::object())); + CHECK_FALSE(save_preset_inside_project(p.presets, "New", json{{"inside_project", false}})); + // An existing name: where that preset is, as the dialog locks its choice. + CHECK(save_preset_inside_project(p.presets, "In Project", json::object())); + CHECK_FALSE(save_preset_inside_project(p.presets, "Mine", json{{"overwrite", true}})); + CHECK_THROWS_AS(save_preset_inside_project(p.presets, "Mine", json{{"overwrite", true}, {"inside_project", true}}), ToolFailure); +} + +namespace { + +// An X1C process: its one extruder has a Standard and a High Flow variant. +DynamicPrintConfig x1c_process() +{ + DynamicPrintConfig c; + c.set_deserialize_strict("print_extruder_id", "1,1"); + c.set_deserialize_strict("print_extruder_variant", "\"Direct Drive Standard\";\"Direct Drive High Flow\""); + c.set_deserialize_strict("outer_wall_speed", "200,350"); + c.set_deserialize_strict("inner_wall_speed", "300"); + c.set_deserialize_strict("wall_loops", "2"); + return c; +} + +const std::vector<int> one_extruder{etDirectDrive}; +const std::vector<int> standard{nvtStandard}; + +} // namespace + +TEST_CASE("an enum's meta lists the labels the GUI shows, in the order of its values", "[Mcp]") +{ + const json meta = option_meta(*print_config_def.get("fuzzy_skin")); + REQUIRE(meta["labels"].size() == meta["values"].size()); + CHECK(meta["values"][1] == "external"); + CHECK(meta["labels"][1] == "Contour"); + CHECK_FALSE(option_meta(*print_config_def.get("wall_loops")).contains("labels")); +} + +TEST_CASE("a per-variant value names its entries and the one the nozzle prints with", "[Mcp]") +{ + const DynamicPrintConfig process = x1c_process(); + json e = variant_entries("outer_wall_speed", process, one_extruder, standard); + CHECK(e["variants"] == json::array({"Direct Drive Standard", "Direct Drive High Flow"})); + CHECK(e["active"] == json::array({0})); + // A High Flow nozzle prints with the second entry. + CHECK(variant_entries("outer_wall_speed", process, one_extruder, {nvtHighFlow})["active"] == json::array({1})); + // One entry, or not a per-variant key: nothing to choose. + CHECK(variant_entries("inner_wall_speed", process, one_extruder, standard).is_null()); + CHECK(variant_entries("wall_loops", process, one_extruder, standard).is_null()); + + // Two extruders, each with both variants; the second has a High Flow nozzle. + DynamicPrintConfig dual; + dual.set_deserialize_strict("print_extruder_id", "1,1,2,2"); + dual.set_deserialize_strict("print_extruder_variant", + "\"Direct Drive Standard\";\"Direct Drive High Flow\";\"Direct Drive Standard\";\"Direct Drive High Flow\""); + dual.set_deserialize_strict("outer_wall_speed", "200,350,200,350"); + e = variant_entries("outer_wall_speed", dual, {etDirectDrive, etDirectDrive}, {nvtStandard, nvtHighFlow}); + CHECK(e["variants"][3] == "extruder 2: Direct Drive High Flow"); + CHECK(e["active"] == json::array({0, 3})); +} + +TEST_CASE("the printer's machine limits and per-extruder values name their entries", "[Mcp]") +{ + DynamicPrintConfig printer; + printer.set_deserialize_strict("printer_extruder_id", "1"); + printer.set_deserialize_strict("printer_extruder_variant", "\"Direct Drive Standard\""); + printer.set_deserialize_strict("machine_max_speed_x", "500,200"); + printer.set_deserialize_strict("nozzle_diameter", "0.4,0.6"); + json e = variant_entries("machine_max_speed_x", printer, one_extruder, standard); + CHECK(e["variants"] == json::array({"Direct Drive Standard (normal mode)", "Direct Drive Standard (silent mode)"})); + CHECK(e["active"] == json::array({0})); + e = variant_entries("nozzle_diameter", printer, {etDirectDrive, etDirectDrive}, {nvtStandard, nvtStandard}); + CHECK(e["variants"] == json::array({"extruder 1", "extruder 2"})); + CHECK_FALSE(e.contains("active")); +} + +TEST_CASE("set_settings writes a single value to the per-variant entries in use, or one entry by index", "[Mcp]") +{ + using Catch::Matchers::ContainsSubstring; + const DynamicPrintConfig process = x1c_process(); + + // Behaviour change 7. Before, the scalar was written as it was, and the vector lost its other variant. + DynamicPrintConfig collapsed = process; + collapsed.set_deserialize_strict("outer_wall_speed", to_config_string(json(250), "outer_wall_speed")); + REQUIRE(collapsed.option<ConfigOptionFloats>("outer_wall_speed")->size() == 1); + // Now it goes to the entry in use, as typing into the tab's field does; the other variant keeps its value. + CHECK(preset_setting_value("outer_wall_speed", json(250), process, one_extruder, standard) == "250,350"); + CHECK(preset_setting_value("outer_wall_speed", "250", process, one_extruder, standard) == "250,350"); + CHECK(preset_setting_value("outer_wall_speed", json(250), process, one_extruder, {nvtHighFlow}) == "200,250"); + // Another number of entries is still refused, naming the entries and the one in use; an array + // with one value is such a number, not a single value. + CHECK_THROWS_WITH(preset_setting_value("outer_wall_speed", json::array({250}), process, one_extruder, standard), + ContainsSubstring("holds 2 values")); + try { + preset_setting_value("outer_wall_speed", json::array({1, 2, 3}), process, one_extruder, standard); + FAIL("three entries were accepted"); + } catch (const ToolFailure& e) { + CHECK_THAT(e.what(), ContainsSubstring("0 = Direct Drive Standard (in use), 1 = Direct Drive High Flow")); + CHECK_THAT(e.what(), ContainsSubstring("\"index\"")); + CHECK(e.details["active"] == json::array({0})); + } + + // Every entry, or one by index. + CHECK(preset_setting_value("outer_wall_speed", json::array({220, 360}), process, one_extruder, standard) == "220,360"); + CHECK(preset_setting_value("outer_wall_speed", {{"index", 1}, {"value", 250}}, process, one_extruder, standard) == "200,250"); + CHECK(preset_setting_value("outer_wall_speed", {{"index", 0}, {"value", "210"}}, process, one_extruder, standard) == "210,350"); + CHECK_THROWS_WITH(preset_setting_value("outer_wall_speed", {{"index", 2}, {"value", 250}}, process, one_extruder, standard), + ContainsSubstring("has 2 entries")); + CHECK_THROWS_WITH(preset_setting_value("outer_wall_speed", {{"index", 1}, {"value", "250,260"}}, process, one_extruder, standard), + ContainsSubstring("takes one value")); + CHECK_THROWS_AS(preset_setting_value("outer_wall_speed", {{"index", 1}}, process, one_extruder, standard), ToolFailure); + CHECK_THROWS_AS(preset_setting_value("wall_loops", {{"index", 0}, {"value", 3}}, process, one_extruder, standard), ToolFailure); + + // Values with one entry, and settings that are not per variant, take a single value as before. + CHECK(preset_setting_value("inner_wall_speed", json(280), process, one_extruder, standard) == "280"); + CHECK(preset_setting_value("wall_loops", json(3), process, one_extruder, standard) == "3"); +} + +TEST_CASE("compare lists the settings two presets differ in, entry by entry for filaments", "[Mcp]") +{ + Preset left(Preset::TYPE_PRINT, "Left"); + left.config = x1c_process(); + left.config.set_deserialize_strict("print_settings_id", "Left"); + Preset right = left; + right.name = "Right"; + right.config.set_deserialize_strict("print_settings_id", "Right"); + right.config.set_deserialize_strict("wall_loops", "3"); + right.config.set_deserialize_strict("outer_wall_speed", "200,300"); + + const std::vector<std::string> keys{"wall_loops", "outer_wall_speed", "print_settings_id"}; + json items = preset_diff(left, right, keys); + // A process compares whole values, as the Compare presets dialog does; the bookkeeping id is left out. + REQUIRE(items.size() == 2); + CHECK(items[0] == json({{"key", "outer_wall_speed"}, {"value", "200,350"}, {"other", "200,300"}})); + CHECK(items[1] == json({{"key", "wall_loops"}, {"value", "2"}, {"other", "3"}})); + // Only the keys asked for. + CHECK(preset_diff(left, right, {"wall_loops"}).size() == 1); + CHECK(preset_diff(left, left, keys).empty()); + + // Filament vectors are compared per entry. + Preset pla(Preset::TYPE_FILAMENT, "PLA"); + pla.config.set_deserialize_strict("filament_extruder_variant", "\"Direct Drive Standard\";\"Direct Drive High Flow\""); + pla.config.set_deserialize_strict("nozzle_temperature", "220,220"); + Preset hot = pla; + hot.name = "Hot PLA"; + hot.config.set_deserialize_strict("nozzle_temperature", "220,230"); + items = preset_diff(pla, hot, {"nozzle_temperature"}); + REQUIRE(items.size() == 1); + CHECK(items[0] == json({{"key", "nozzle_temperature"}, {"index", 1}, {"value", "220"}, {"other", "230"}})); +} + +TEST_CASE("changed lists every setting a call changed, the app's own adjustments included", "[Mcp]") +{ + DynamicPrintConfig before; + before.set_deserialize_strict("spiral_mode", "0"); + before.set_deserialize_strict("wall_loops", "3"); + before.set_deserialize_strict("top_shell_layers", "5"); + before.set_deserialize_strict("sparse_infill_density", "15%"); + // Spiral vase confirmed: the key asked for, and those the spiral mode dialog adjusts. + DynamicPrintConfig after = before; + after.set_deserialize_strict("spiral_mode", "1"); + after.set_deserialize_strict("wall_loops", "1"); + after.set_deserialize_strict("top_shell_layers", "0"); + after.set_deserialize_strict("sparse_infill_density", "15%"); + CHECK(changed_settings(before, after) == json({{"spiral_mode", "1"}, {"top_shell_layers", "0"}, {"wall_loops", "1"}})); + CHECK(changed_settings(after, after).empty()); + // An override removed or added. + DynamicPrintConfig fewer = before; + fewer.erase("wall_loops"); + CHECK(changed_settings(before, fewer) == json({{"wall_loops", nullptr}})); + CHECK(changed_settings(fewer, before) == json({{"wall_loops", "3"}})); +} + +TEST_CASE("an unsaved change is discarded when the edited preset no longer holds its value", "[Mcp]") +{ + // Unsaved before a preset switch: four walls, and the High Flow entry of the outer wall speed. + const json changes{{"wall_loops", "4"}, {"outer_wall_speed#1", "300"}}; + // Discarded: the preset edited afterwards has other values. + const DynamicPrintConfig process = x1c_process(); + CHECK(discarded_changes(changes, process) == json::array({"outer_wall_speed", "wall_loops"})); + // Transferred: the preset edited afterwards holds them, whatever else differs. + DynamicPrintConfig transferred = process; + transferred.set_deserialize_strict("wall_loops", "4"); + transferred.set_deserialize_strict("outer_wall_speed", "180,300"); + CHECK(discarded_changes(changes, transferred).empty()); + // An entry the new preset does not have is gone. + transferred.set_deserialize_strict("outer_wall_speed", "300"); + CHECK(discarded_changes(changes, transferred) == json::array({"outer_wall_speed"})); +} + +namespace { + +// Adds the preset `name` to `presets`, inheriting from `inherits` and made for `printers` alone when given. +void add_preset(PresetCollection& presets, const std::string& name, const std::string& inherits = {}, + const std::vector<std::string>& printers = {}) +{ + Preset& preset = presets.load_preset(std::string(), name, DynamicPrintConfig(presets.default_preset().config), /*select=*/false); + if (!inherits.empty()) + preset.inherits() = inherits; + if (!printers.empty()) + preset.config.option<ConfigOptionStrings>("compatible_printers", true)->values = printers; +} + +} // namespace + +TEST_CASE("delete_preset refuses the presets the tab does not delete", "[Mcp]") +{ + using Catch::Matchers::ContainsSubstring; + Processes p; + add_preset(p.presets, "Mine Child", "Mine"); + add_preset(p.presets, "From Bundle"); + p.presets.find_preset("From Bundle", false, true)->bundle_id = "a bundle"; + p.presets.select_preset_by_name("Mine", true); + const PresetCollection filaments{Preset::TYPE_FILAMENT, Preset::filament_options(), + static_cast<const PrintRegionConfig&>(FullPrintConfig::defaults())}; + + // User presets and presets inside the project, with nothing deleted along with them. + CHECK(check_preset_deletable(p.presets, "Other", false, p.presets, filaments).empty()); + CHECK(check_preset_deletable(p.presets, "In Project", false, p.presets, filaments).empty()); + CHECK(check_preset_deletable(p.presets, "Mine Child", false, p.presets, filaments).empty()); + + CHECK_THROWS_WITH(check_preset_deletable(p.presets, "0.20mm Standard", false, p.presets, filaments), ContainsSubstring("system preset")); + CHECK_THROWS_WITH(check_preset_deletable(p.presets, "From Bundle", false, p.presets, filaments), ContainsSubstring("preset bundle")); + try { + check_preset_deletable(p.presets, "Other process", false, p.presets, filaments); + FAIL("an unknown name was accepted"); + } catch (const ToolFailure& e) { + CHECK(e.details["similar"].front() == "Other"); + } + // A base preset that another inherits from, the selected one included, as Tab::delete_preset() refuses it. + try { + check_preset_deletable(p.presets, "Mine", true, p.presets, filaments); + FAIL("a base preset with a child was accepted"); + } catch (const ToolFailure& e) { + CHECK_THAT(e.what(), ContainsSubstring("inherit from it")); + CHECK(e.details["inherited_by"] == json::array({"Mine Child"})); + } +} + +TEST_CASE("a custom printer's own presets are deleted with it only when asked", "[Mcp]") +{ + using Catch::Matchers::ContainsSubstring; + const auto& defaults = static_cast<const PrintRegionConfig&>(FullPrintConfig::defaults()); + PresetCollection printers{Preset::TYPE_PRINTER, Preset::printer_options(), defaults, "Default Printer"}; + PresetCollection prints{Preset::TYPE_PRINT, Preset::print_options(), defaults}; + PresetCollection filaments{Preset::TYPE_FILAMENT, Preset::filament_options(), defaults}; + add_preset(printers, "X1C"); + printers.find_preset("X1C", false, true)->is_system = true; + add_preset(printers, "My Printer"); + add_preset(printers, "My X1C", "X1C"); + add_preset(prints, "For My Printer", {}, {"My Printer"}); + add_preset(prints, "Shared", {}, {"My Printer", "X1C"}); + add_preset(filaments, "My PLA", {}, {"My Printer"}); + + // Counted as the GUI's Delete confirmation counts them, and refused without delete_attached. + const json attached{{"process", json::array({"For My Printer"})}, {"filament", json::array({"My PLA"})}}; + try { + check_preset_deletable(printers, "My Printer", false, prints, filaments); + FAIL("a custom printer with attached presets was accepted"); + } catch (const ToolFailure& e) { + CHECK_THAT(e.what(), ContainsSubstring("(process: 1, filament: 1)")); + CHECK(e.details["attached"] == attached); + } + CHECK(check_preset_deletable(printers, "My Printer", true, prints, filaments) == attached); + // A printer that inherits a system printer takes nothing with it, as in the GUI. + CHECK(check_preset_deletable(printers, "My X1C", false, prints, filaments).empty()); + CHECK_THROWS_WITH(check_preset_deletable(printers, "X1C", true, prints, filaments), ContainsSubstring("system preset")); +} + +TEST_CASE("the project scope takes one colour per slot and leaves a mixed slot's colour to its components", "[Mcp]") +{ + using Catch::Matchers::ContainsSubstring; + const std::vector<std::string> current{"#FFFFFF", "#000000", "#7F7F7F"}; + const std::vector<unsigned char> mixed{0, 0, 1}; // slot 3 mixes slots 1 and 2 + + // Stored as the colour pickers store them; unchanged entries stay as they are, in any case. + CHECK(check_filament_colours({"#ff0000", "#000000", "#7f7f7f"}, current, mixed) == + std::vector<std::string>{"#FF0000", "#000000", "#7F7F7F"}); + CHECK_THROWS_WITH(check_filament_colours({"#FF0000", "#000000"}, current, mixed), ContainsSubstring("one colour per filament slot: 3")); + CHECK_THROWS_WITH(check_filament_colours({"red", "#000000", "#7F7F7F"}, current, mixed), ContainsSubstring("is not #RRGGBB")); + CHECK_THROWS_AS(check_filament_colours({"#FF00001", "#000000", "#7F7F7F"}, current, mixed), ToolFailure); + CHECK_THROWS_WITH(check_filament_colours({"#FFFFFF", "#000000", "#FF0000"}, current, mixed), ContainsSubstring("Slot 3 is a mixed filament")); + + // One slot by index, through set_settings' entry write. + DynamicPrintConfig project; + project.set_key_value("filament_colour", new ConfigOptionStrings(current)); + CHECK(preset_setting_value("filament_colour", {{"index", 1}, {"value", "#00FF00"}}, project, {}, {}) == "#FFFFFF;#00FF00;#7F7F7F"); +} + +TEST_CASE("flush_multiplier takes one value per nozzle within the Flushing volumes dialog's range", "[Mcp]") +{ + using Catch::Matchers::ContainsSubstring; + CHECK(check_flush_multipliers({0.7}, 1) == std::vector<double>{0.7}); + CHECK(check_flush_multipliers({0.7}, 2) == std::vector<double>{0.7, 0.7}); + CHECK(check_flush_multipliers({0.5, 1.5}, 2) == std::vector<double>{0.5, 1.5}); + CHECK(check_flush_multipliers({0., 3.}, 2) == std::vector<double>{0., 3.}); + CHECK_THROWS_WITH(check_flush_multipliers({0.5, 1.5, 1.}, 2), ContainsSubstring("one value per nozzle (2)")); + CHECK_THROWS_WITH(check_flush_multipliers({3.5}, 1), ContainsSubstring("outside 0..3")); + CHECK_THROWS_AS(check_flush_multipliers({-0.1}, 1), ToolFailure); +} + +TEST_CASE("flush_volumes_matrix is slots x slots per nozzle in config order, limited as the dialog limits it", "[Mcp]") +{ + using Catch::Matchers::ContainsSubstring; + // Two physical slots and a mixed third, one nozzle: rows are "from", columns "to". + const std::vector<double> current{0, 280, 0, 320, 0, 0, 0, 0, 0}; + const std::vector<unsigned char> mixed{0, 0, 1}; + const std::vector<double> multiplier{0.3}; + + std::vector<double> matrix = current; + matrix[1] = 400; // from slot 1 to slot 2 + CHECK(check_flush_matrix(matrix, 3, multiplier, current, mixed) == matrix); + CHECK_THROWS_WITH(check_flush_matrix({0, 400, 320, 0}, 3, multiplier, current, mixed), ContainsSubstring("takes 9 values: 3x3")); + // Two nozzles take a matrix each, one after the other. + CHECK_THROWS_WITH(check_flush_matrix(matrix, 3, {1., 1.}, current, mixed), ContainsSubstring("takes 18 values")); + + std::vector<double> bad = matrix; + bad[3] = -1; + CHECK_THROWS_WITH(check_flush_matrix(bad, 3, multiplier, current, mixed), ContainsSubstring("(nozzle 1, from slot 2 to slot 1) is negative")); + bad = matrix; + bad[4] = 50; + CHECK_THROWS_WITH(check_flush_matrix(bad, 3, multiplier, current, mixed), ContainsSubstring("must be 0")); + // A mixed slot's row and column stay as they are. + bad = matrix; + bad[2] = 100; + CHECK_THROWS_WITH(check_flush_matrix(bad, 3, multiplier, current, mixed), ContainsSubstring("belongs to a mixed filament")); + + // The dialog keeps volume x multiplier within g_max_flush_volume (20000 mm3 in Orca). + std::vector<double> huge = matrix; + huge[1] = 100000; + CHECK(check_flush_matrix(huge, 3, {2.}, current, mixed)[1] == 10000.); + CHECK(check_flush_matrix(huge, 3, {0.}, current, mixed)[1] == 100000.); +} + +TEST_CASE("a plate's filament orders list every slot once, and its layer ranges start at layer 2 without overlapping", "[Mcp]") +{ + using Catch::Matchers::ContainsSubstring; + CHECK(filament_order(json::array({2, 1}), 2) == std::vector<int>{2, 1}); + CHECK_THROWS_WITH(filament_order(json::array({1, 1}), 2), ContainsSubstring("every filament slot 1..2 once")); + CHECK_THROWS_AS(filament_order(json::array({1}), 2), ToolFailure); + CHECK_THROWS_AS(filament_order(json::array({1, 2, 3}), 2), ToolFailure); + CHECK_THROWS_AS(filament_order("2,1", 2), ToolFailure); + + // Sorted by layer as the dialog sorts its rows; a range without `to` runs to the last layer ("End"). + const auto ranges = layer_sequences(json::parse(R"([{"from": 21, "order": [1, 2]}, {"from": 2, "to": 20, "order": [2, 1]}])"), 2); + REQUIRE(ranges.size() == 2); + CHECK(ranges[0].first == std::pair<int, int>{2, 20}); + CHECK(ranges[0].second == std::vector<int>{2, 1}); + CHECK(ranges[1].first == std::pair<int, int>{21, INT_MAX - 1}); + CHECK(layer_sequences_json(ranges) == json::parse(R"([{"from": 2, "to": 20, "order": [2, 1]}, {"from": 21, "order": [1, 2]}])")); + // The plate tab's own open end, INT_MAX, reads the same. + CHECK(layer_sequences_json({{{2, INT_MAX}, {1, 2}}}) == json::parse(R"([{"from": 2, "order": [1, 2]}])")); + + CHECK_THROWS_WITH(layer_sequences(json::parse(R"([{"from": 1, "order": [1, 2]}])"), 2), ContainsSubstring("start at layer 2")); + CHECK_THROWS_WITH(layer_sequences(json::parse(R"([{"from": 5, "to": 4, "order": [1, 2]}])"), 2), ContainsSubstring("ends before it starts")); + CHECK_THROWS_WITH(layer_sequences(json::parse(R"([{"from": 2, "order": [1, 2]}, {"from": 10, "to": 20, "order": [2, 1]}])"), 2), + ContainsSubstring("overlap")); + CHECK_THROWS_WITH(layer_sequences(json::parse(R"([{"from": 2, "to": 10, "order": [1, 2]}, {"from": 10, "order": [2, 1]}])"), 2), + ContainsSubstring("overlap")); + CHECK_THROWS_AS(layer_sequences(json::parse(R"([{"from": 2, "order": [1]}])"), 2), ToolFailure); + CHECK_THROWS_AS(layer_sequences(json::parse(R"([{"from": 2, "until": 5, "order": [1, 2]}])"), 2), ToolFailure); + CHECK_THROWS_AS(layer_sequences(json::array(), 2), ToolFailure); +} + +TEST_CASE("a plate's layers are numbered as the Preview's layer slider numbers them", "[Mcp]") +{ + GCodeProcessorResult result; + const auto move = [&result](EMoveType type, ExtrusionRole role, float z, unsigned int layer, float print_z = 0.f) { + GCodeProcessorResult::MoveVertex v; + v.type = type; + v.extrusion_role = role; + v.position = Vec3f(10.f, 10.f, z); + v.layer_id = layer; + v.print_z = print_z; + result.moves.push_back(v); + }; + move(EMoveType::Extrude, erExternalPerimeter, 9.f, 0); // the first move, which the viewer does not load + move(EMoveType::Extrude, erExternalPerimeter, 0.2f, 0); + move(EMoveType::Travel, erNone, 0.6f, 0); // a z hop + move(EMoveType::Extrude, erCustom, 0.5f, 0); // custom G-code's extrusion + move(EMoveType::Extrude, erPerimeter, 0.4f, 1); + move(EMoveType::Extrude, erPerimeter, 0.6f, 3); // layer ids need not be consecutive + std::vector<double> zs = gcode_layer_zs(result); + REQUIRE(zs.size() == 3); + CHECK(zs[0] == double(0.2f)); + CHECK(zs[1] == double(0.4f)); + CHECK(zs[2] == double(0.6f)); + + // A belt print labels its layers with their print Z. + for (std::size_t i = 0; i < result.moves.size(); ++i) + result.moves[i].print_z = 1.f + float(result.moves[i].layer_id); + result.belt_tilt_angle = 45.f; + CHECK(gcode_layer_zs(result) == std::vector<double>{1., 2., 4.}); +} + +TEST_CASE("a plate's layer G-codes read back by height, on the layer the Preview slider shows them", "[Mcp]") +{ + CustomGCode::Info codes; + codes.gcodes.push_back({double(5.2f), CustomGCode::PausePrint, 1, "", ""}); + codes.gcodes.push_back({double(0.6f), CustomGCode::ToolChange, 2, "#00FF00", ""}); + codes.gcodes.push_back({10.2, CustomGCode::Custom, 1, "", "M104 S215"}); + std::vector<double> zs; + for (int i = 1; i <= 30; ++i) + zs.push_back(double(0.2f * float(i))); // 0.2 mm layers up to 6 mm, as the viewer's floats + const json out = layer_gcode_json(codes, zs); + REQUIRE(out.size() == 3); + CHECK(out[0] == json{{"z", 0.6}, {"layer", 3}, {"type", "change_filament"}, {"filament", 2}, {"color", "#00FF00"}}); + CHECK(out[1] == json{{"z", 5.2}, {"layer", 26}, {"type", "pause"}}); + // Above the top layer, so on no layer of this slice. + CHECK(out[2] == json{{"z", 10.2}, {"type", "custom"}, {"gcode", "M104 S215"}}); + // Without an up-to-date slice there are no layer numbers. + CHECK_FALSE(layer_gcode_json(codes, {})[0].contains("layer")); +} + +TEST_CASE("the preferences scope reads the keys it is given, as stored, and lists none unasked", "[Mcp]") +{ + using Catch::Matchers::ContainsSubstring; + AppConfig config; + config.set("auto_calculate_flush", "disabled"); + config.set("region", ""); + config.set("presets", "filament", "Bambu PLA Basic"); // another section than the preferences' + const json out = preferences_settings(config, json{{"keys", {"auto_calculate_flush", "region", "filament", "no_such_preference"}}}); + REQUIRE(out["total"] == 2); + CHECK(out["items"][0] == json{{"key", "auto_calculate_flush"}, {"value", "disabled"}}); + // A key stored empty is known, with its empty value. + CHECK(out["items"][1] == json{{"key", "region"}, {"value", ""}}); + CHECK(out["unknown_keys"] == json{"filament", "no_such_preference"}); + CHECK_THAT(out["note"].get<std::string>(), ContainsSubstring("never changed")); + const json known = preferences_settings(config, json{{"keys", {"region"}}}); + CHECK_FALSE(known.contains("unknown_keys")); + CHECK_FALSE(known.contains("note")); + + // The app section also holds account and device state, so nothing is listed without keys. + CHECK_THROWS_WITH(preferences_settings(config, json::object()), ContainsSubstring("keys")); + CHECK_THROWS_AS(preferences_settings(config, json{{"query", "flush"}}), ToolFailure); + CHECK_THROWS_AS(preferences_settings(config, json{{"keys", {"region"}}, {"compare", ":saved"}}), ToolFailure); +} + +namespace { + +// A printer for the calibration tests: its firmware, extruder type and junction deviation (0: classic jerk). +DynamicPrintConfig calib_printer(GCodeFlavor flavor = gcfKlipper, ExtruderType extruder = etDirectDrive, double junction_deviation = 0.) +{ + DynamicPrintConfig printer = DynamicPrintConfig::full_print_config(); + printer.set_key_value("gcode_flavor", new ConfigOptionEnum<GCodeFlavor>(flavor)); + printer.set_key_value("extruder_type", new ConfigOptionEnumsGeneric{int(extruder)}); + printer.set_key_value("machine_max_junction_deviation", new ConfigOptionFloats{junction_deviation}); + printer.set_key_value("belt_printer", new ConfigOptionBool(false)); + return printer; +} + +Calib_Params calib_args(const json& args, const DynamicPrintConfig& printer = calib_printer()) +{ + std::vector<std::string> warnings; + return calib_params_from_args(args, printer, warnings); +} + +} // namespace + +TEST_CASE("calibrate arguments map to the dialog's calibration modes", "[Mcp]") +{ + for (const auto& [args, mode] : std::initializer_list<std::pair<json, CalibMode>>{ + {{{"test", "temperature"}}, CalibMode::Calib_Temp_Tower}, + {{{"test", "max_volumetric"}}, CalibMode::Calib_Vol_speed_Tower}, + {{{"test", "pressure_advance"}}, CalibMode::Calib_PA_Tower}, + {{{"test", "pressure_advance"}, {"method", "line"}}, CalibMode::Calib_PA_Line}, + {{{"test", "pressure_advance"}, {"method", "pattern"}}, CalibMode::Calib_PA_Pattern}, + {{{"test", "flow_ratio"}, {"method", "pass2"}}, CalibMode::Calib_Flow_Rate}, + {{{"test", "retraction"}}, CalibMode::Calib_Retraction_tower}, + {{{"test", "vfa"}}, CalibMode::Calib_VFA_Tower}, + {{{"test", "input_shaping_freq"}}, CalibMode::Calib_Input_shaping_freq}, + {{{"test", "input_shaping_damp"}}, CalibMode::Calib_Input_shaping_damp}, + {{{"test", "cornering"}}, CalibMode::Calib_Cornering}}) + CHECK(calib_args(args).mode == mode); + CHECK_THROWS_AS(calib_args({{"test", "pressure_advance"}, {"method", "yolo"}}), ToolFailure); + CHECK_THROWS_AS(calib_args({{"test", "flow_ratio"}, {"method", "tower"}}), ToolFailure); +} + +TEST_CASE("omitted calibrate parameters take the dialog defaults", "[Mcp]") +{ + const Calib_Params temp = calib_args({{"test", "temperature"}}); + CHECK((temp.start == 230 && temp.end == 190 && temp.nozzle_based_resize)); + const Calib_Params tower = calib_args({{"test", "pressure_advance"}}); + CHECK((tower.start == 0 && tower.end == 0.1 && tower.step == 0.002 && !tower.print_numbers)); + CHECK(calib_args({{"test", "pressure_advance"}, {"method", "line"}}).print_numbers); + const Calib_Params pattern = calib_args({{"test", "pressure_advance"}, {"method", "pattern"}}); + CHECK((pattern.end == 0.08 && pattern.step == 0.005 && pattern.accelerations.empty() && pattern.speeds.empty())); + // The dialog's Extruder type radio only switches these defaults; the printer's extruder type picks them here. + const DynamicPrintConfig bowden = calib_printer(gcfKlipper, etBowden); + const Calib_Params bowden_tower = calib_args({{"test", "pressure_advance"}}, bowden); + CHECK((bowden_tower.end == 1.0 && bowden_tower.step == 0.02)); + CHECK(calib_args({{"test", "pressure_advance"}, {"method", "pattern"}}, bowden).step == 0.05); + const Calib_Params vol = calib_args({{"test", "max_volumetric"}}); + CHECK((vol.start == 5 && vol.end == 20 && vol.step == 0.5)); + const Calib_Params retraction = calib_args({{"test", "retraction"}}); + CHECK((retraction.start == 0 && retraction.end == 2 && retraction.step == 0.1)); + const Calib_Params vfa = calib_args({{"test", "vfa"}}); + CHECK((vfa.start == 40 && vfa.end == 200 && vfa.step == 10)); + const Calib_Params freq = calib_args({{"test", "input_shaping_freq"}}); + CHECK((freq.freqStartX == 15 && freq.freqEndX == 110 && freq.start == 0.15 && freq.test_model == 0)); + CHECK(freq.shaper_type == "Default"); // the first of the radio's types on Klipper + const Calib_Params damp = calib_args({{"test", "input_shaping_damp"}}); + CHECK((damp.freqStartX == 30 && damp.freqStartY == 30 && damp.start == 0 && damp.end == 0.4)); + // Cornering is junction deviation on Marlin 2 with it set, classic jerk otherwise. + const Calib_Params jerk = calib_args({{"test", "cornering"}}, calib_printer(gcfMarlinFirmware)); + CHECK((jerk.start == 1 && jerk.end == 15)); + const Calib_Params jd = calib_args({{"test", "cornering"}}, calib_printer(gcfMarlinFirmware, etDirectDrive, 0.1)); + CHECK((jd.start == 0 && jd.end == 0.25)); + CHECK(calib_args({{"test", "cornering"}}, calib_printer(gcfKlipper, etDirectDrive, 0.1)).end == 15); +} + +TEST_CASE("calibrate refuses arguments its test does not take", "[Mcp]") +{ + using Catch::Matchers::ContainsSubstring; + CHECK_THROWS_WITH(calib_args({{"test", "pressure_advance"}, {"speeds", {100}}}), + ContainsSubstring("speeds does not apply to pressure_advance with method tower")); + CHECK_THROWS_WITH(calib_args({{"test", "temperature"}, {"step", 5}}), ContainsSubstring("step does not apply to temperature")); + CHECK_THROWS_AS(calib_args({{"test", "cornering"}, {"step", 0.01}}), ToolFailure); + CHECK_THROWS_AS(calib_args({{"test", "vfa"}, {"damping", 0.1}}), ToolFailure); + CHECK_THROWS_AS(calib_args({{"test", "pressure_advance"}, {"method", "line"}, {"accelerations", {1000}}}), ToolFailure); + CHECK_THROWS_AS(calib_args({{"test", "flow_ratio"}, {"start", 1}}), ToolFailure); + // The model picker of the temperature dialog shows on belt printers only. + CHECK_THROWS_WITH(calib_args({{"test", "temperature"}, {"test_model", "overhang"}}), ContainsSubstring("belt printers")); + CHECK_THROWS_AS(calib_args({{"test", "input_shaping_freq"}, {"test_model", "scv_v2"}}), ToolFailure); + CHECK(calib_args({{"test", "cornering"}, {"test_model", "scv_v2"}}).test_model == 2); + // The firmware's input shaper types, as the dialog's radio lists them. + CHECK_THROWS_WITH(calib_args({{"test", "input_shaping_freq"}, {"shaper_type", "EI3"}}), + ContainsSubstring("klipper firmware: Default, ZV, MZV, ZVD, EI, 2HUMP_EI, 3HUMP_EI")); + CHECK(calib_args({{"test", "input_shaping_freq"}, {"shaper_type", "EI3"}}, calib_printer(gcfRepRapFirmware)).shaper_type == "EI3"); + CHECK(calib_args({{"test", "input_shaping_damp"}}, calib_printer(gcfMarlinFirmware)).shaper_type == "ZV"); + // The values the call needs besides the test's own are not refused. + CHECK_NOTHROW(calib_args({{"test", "retraction"}, {"discard_changes", true}, {"changes", "keep"}})); +} + +TEST_CASE("the input shaping Y range defaults to the X range, and RepRapFirmware takes one range", "[Mcp]") +{ + const Calib_Params freq = calib_args({{"test", "input_shaping_freq"}, {"start", 20}, {"end", 80}}); + CHECK((freq.freqStartY == 20 && freq.freqEndY == 80)); + const Calib_Params y = calib_args({{"test", "input_shaping_freq"}, {"start", 20}, {"end", 80}, {"start_y", 30}, {"end_y", 90}}); + CHECK((y.freqStartX == 20 && y.freqStartY == 30 && y.freqEndY == 90)); + CHECK(calib_args({{"test", "input_shaping_damp"}, {"freq_x", 48}}).freqStartY == 48); + const DynamicPrintConfig rrf = calib_printer(gcfRepRapFirmware); + CHECK_THROWS_AS(calib_args({{"test", "input_shaping_freq"}, {"start_y", 30}}, rrf), ToolFailure); + CHECK_THROWS_AS(calib_args({{"test", "input_shaping_damp"}, {"freq_y", 30}}, rrf), ToolFailure); + // The dialog checks only the X range there; a Y range from another firmware's defaults does not count. + Calib_Params p = calib_default_params(CalibMode::Calib_Input_shaping_freq, rrf); + p.freqStartY = 600; + CHECK(check_calib_params(p, rrf) == CalibParamsError::None); + CHECK(check_calib_params(p, calib_printer()) == CalibParamsError::Range); +} + +TEST_CASE("calibrate clamps temperatures to 155-500 C and rounds them down to a multiple of 5, as the dialog's fields do", "[Mcp]") +{ + using Catch::Matchers::ContainsSubstring; + std::vector<std::string> warnings; + const Calib_Params p = calib_params_from_args({{"test", "temperature"}, {"start", 252}, {"end", 232}}, calib_printer(), warnings); + CHECK((p.start == 250 && p.end == 230)); + REQUIRE(warnings.size() == 2); + CHECK_THAT(warnings[0], ContainsSubstring("rounded down to 250")); + warnings.clear(); + const Calib_Params clamped = calib_params_from_args({{"test", "temperature"}, {"start", 600}, {"end", 150}}, calib_printer(), warnings); + CHECK((clamped.start == 500 && clamped.end == 155)); + REQUIRE(warnings.size() == 2); + // The dialog's message box says 170 but clamps to 155. + CHECK_THAT(warnings[0], ContainsSubstring("155-500 °C; clamped to 500")); + CHECK_THAT(warnings[1], ContainsSubstring("clamped to 155")); + CHECK_THROWS_WITH(calib_args({{"test", "temperature"}, {"start", 230}, {"end", 230}}), ContainsSubstring("start at least end + 5")); +} + +TEST_CASE("the calibration dialogs' rules refuse what the dialogs refuse", "[Mcp]") +{ + using Catch::Matchers::ContainsSubstring; + const DynamicPrintConfig printer = calib_printer(); + const auto check = [&printer](CalibMode mode, double start, double end, double step) { + Calib_Params p = calib_default_params(mode, printer); + p.start = start; + p.end = end; + p.step = step; + return check_calib_params(p, printer); + }; + using E = CalibParamsError; + CHECK(check(CalibMode::Calib_Temp_Tower, 500, 155, 0) == E::None); + CHECK(check(CalibMode::Calib_Temp_Tower, 505, 230, 0) == E::Range); + CHECK(check(CalibMode::Calib_Temp_Tower, 230, 150, 0) == E::Range); + CHECK(check(CalibMode::Calib_Temp_Tower, 230, 226, 0) == E::Range); + CHECK(check(CalibMode::Calib_Vol_speed_Tower, 0, 20, 0.5) == E::Range); + CHECK(check(CalibMode::Calib_Vol_speed_Tower, 5, 5.4, 0.5) == E::Range); + CHECK(check(CalibMode::Calib_Vol_speed_Tower, 5, 5.5, 0.5) == E::None); + CHECK(check(CalibMode::Calib_PA_Tower, -0.01, 0.1, 0.002) == E::Range); + CHECK(check(CalibMode::Calib_PA_Tower, 0, 0.1, 0.0009) == E::Range); // "PA step: >= 0.001" + CHECK(check(CalibMode::Calib_PA_Tower, 0, 0.1, 0.002) == E::None); + CHECK(check(CalibMode::Calib_Retraction_tower, 0, 2, 0) == E::Range); + CHECK(check(CalibMode::Calib_Retraction_tower, 0, 2, 0.1) == E::None); + CHECK(check(CalibMode::Calib_VFA_Tower, 10, 200, 10) == E::Range); + CHECK(check(CalibMode::Calib_VFA_Tower, 11, 200, 10) == E::None); + CHECK(check(CalibMode::Calib_Input_shaping_freq, 1, 0, 0) == E::Damping); // damping 1 is not below 1 + CHECK(check(CalibMode::Calib_Input_shaping_damp, 0.3, 0.2, 0) == E::Damping); + CHECK(check(CalibMode::Calib_Input_shaping_damp, 0, 1, 0) == E::None); + + Calib_Params pattern = calib_default_params(CalibMode::Calib_PA_Pattern, printer); + pattern.accelerations = {1000, 2000}; + pattern.speeds = {100, 1000}; + CHECK(check_calib_params(pattern, printer) == E::AccelBelowSpeed); + pattern.speeds = {100, 200}; + CHECK(check_calib_params(pattern, printer) == E::None); + DynamicPrintConfig belt = printer; + belt.set_key_value("belt_printer", new ConfigOptionBool(true)); + CHECK(check_calib_params(pattern, belt) == E::BeltMethod); + CHECK(check_calib_params(calib_default_params(CalibMode::Calib_PA_Tower, belt), belt) == E::None); + + // Cornering takes junction deviation up to 0.3 mm on Marlin 2 with it set, jerk up to 100 mm/s otherwise, and + // warns above 0.25 mm or 20 mm/s. + const DynamicPrintConfig marlin_jd = calib_printer(gcfMarlinFirmware, etDirectDrive, 0.1); + CHECK((cornering_end_limits(marlin_jd) == std::make_pair(0.3, 0.25))); + CHECK((cornering_end_limits(printer) == std::make_pair(100., 20.))); + CHECK_THROWS_WITH(calib_args({{"test", "cornering"}, {"end", 0.31}}, marlin_jd), ContainsSubstring("<= 0.3 mm (junction deviation)")); + std::vector<std::string> warnings; + calib_params_from_args({{"test", "cornering"}, {"end", 0.28}}, marlin_jd, warnings); + REQUIRE(warnings.size() == 1); + CHECK_THAT(warnings[0], ContainsSubstring("layer shifts")); + CHECK_NOTHROW(calib_args({{"test", "cornering"}, {"end", 90}})); + + // The tool states the rule with the values given. + CHECK_THROWS_WITH(calib_args({{"test", "pressure_advance"}, {"start", 0.01}, {"end", 0.05}, {"step", 0.051}}), + ContainsSubstring("needs start >= 0, step >= 0.001 and end >= start + step; got start 0.01, end 0.05, step 0.051")); + CHECK_THROWS_WITH(calib_args({{"test", "pressure_advance"}, {"method", "pattern"}, {"accelerations", {100}}, {"speeds", {200}}}), + ContainsSubstring("greater than every speed")); + CHECK_THROWS_WITH(calib_args({{"test", "pressure_advance"}, {"method", "line"}}, belt), ContainsSubstring("use method tower")); +} + +TEST_CASE("VFA's auto-adjust lowers the layer height, else the end speed, to stay within the volumetric limit", "[Mcp]") +{ + DynamicPrintConfig printer = calib_printer(); + printer.set_key_value("nozzle_diameter", new ConfigOptionFloats{0.4}); + DynamicPrintConfig print = DynamicPrintConfig::full_print_config(); + print.set_key_value("layer_height", new ConfigOptionFloat(0.2)); + print.set_key_value("outer_wall_line_width", new ConfigOptionFloatOrPercent(0.42, false)); + DynamicPrintConfig filament = DynamicPrintConfig::full_print_config(); + filament.set_key_value("filament_max_volumetric_speed", new ConfigOptionFloats{12.}); + // At 0.42 mm wide, 12 mm³/s allows about 159 mm/s at 0.2 mm, 195 at 0.16 and 254 at 0.12. + const std::vector<double> candidates{0.12, 0.16, 0.2, 0.28}; + Calib_Params p = calib_default_params(CalibMode::Calib_VFA_Tower, printer); // 40 to 200 in steps of 10 + + VfaSpeedFit fit = fit_vfa_speed(p, printer, print, filament, true, candidates); + CHECK(fit.kind == VfaSpeedFit::ReducedLayerHeight); + CHECK(fit.layer_height == 0.12); // the largest that reaches 200, never above the default 0.2 + CHECK((fit.default_lh == 0.2 && fit.speed_limit > 155 && fit.speed_limit < 165)); + + p.end = 400; + fit = fit_vfa_speed(p, printer, print, filament, true, candidates); + CHECK(fit.kind == VfaSpeedFit::LoweredEnd); + CHECK((fit.layer_height == 0.12 && fit.end == 250)); // a step multiple the smallest one reaches + + CHECK(fit_vfa_speed(p, printer, print, filament, false, candidates).kind == VfaSpeedFit::Clamped); + CHECK(fit_vfa_speed(p, printer, print, filament, true, {}).kind == VfaSpeedFit::Clamped); + p.nozzle_based_resize = false; // the layer height of an unscaled model stays the process's + CHECK(fit_vfa_speed(p, printer, print, filament, true, candidates).kind == VfaSpeedFit::Clamped); + p.end = 150; + CHECK(fit_vfa_speed(p, printer, print, filament, true, candidates).kind == VfaSpeedFit::Fits); +} + +TEST_CASE("calibrate records the parameters a test ran with, defaults included", "[Mcp]") +{ + const DynamicPrintConfig printer = calib_printer(); + const json tower = {{"test", "pressure_advance"}, {"end", 0.06}}; + CHECK(calib_params_json(tower, calib_args(tower), printer) == json{{"method", "tower"}, {"start", 0.}, {"end", 0.06}, {"step", 0.002}}); + const json line = {{"test", "pressure_advance"}, {"method", "line"}, {"print_numbers", false}}; + CHECK(calib_params_json(line, calib_args(line), printer)["print_numbers"] == false); + const json pattern = {{"test", "pressure_advance"}, {"method", "pattern"}, {"accelerations", {1000, 2000}}, {"speeds", {50}}}; + const json recorded = calib_params_json(pattern, calib_args(pattern), printer); + CHECK((recorded["accelerations"] == json{1000., 2000.} && recorded["speeds"] == json::array({50.}))); + const json flow = {{"test", "flow_ratio"}}; + CHECK(calib_params_json(flow, calib_args(flow), printer) == json{{"method", "yolo"}, {"top_surface_pattern", "archimedeanchords"}}); + const json freq = {{"test", "input_shaping_freq"}, {"start", 20}}; + CHECK(calib_params_json(freq, calib_args(freq), printer) == + json{{"start", 20.}, {"end", 110.}, {"start_y", 20.}, {"end_y", 110.}, {"damping", 0.15}, {"shaper_type", "Default"}, + {"test_model", "ringing_tower"}}); + const json rrf_damp = {{"test", "input_shaping_damp"}, {"freq_x", 40}}; + const DynamicPrintConfig rrf = calib_printer(gcfRepRapFirmware); + CHECK_FALSE(calib_params_json(rrf_damp, calib_args(rrf_damp, rrf), rrf).contains("freq_y")); + const json temp = {{"test", "temperature"}, {"start", 252}}; + CHECK(calib_params_json(temp, calib_args(temp), printer) == json{{"start", 250.}, {"end", 190.}, {"auto_scale", true}}); + const json vfa = {{"test", "vfa"}, {"auto_adjust", false}}; + CHECK(calib_params_json(vfa, calib_args(vfa), printer)["auto_adjust"] == false); +} diff --git a/tests/slic3rutils/test_mcp_core.cpp b/tests/slic3rutils/test_mcp_core.cpp index 32ad0c3261..1c9b0f936b 100644 --- a/tests/slic3rutils/test_mcp_core.cpp +++ b/tests/slic3rutils/test_mcp_core.cpp @@ -887,6 +887,7 @@ TEST_CASE("the journal records client calls in order and replays jobs with await { Journal journal; const uint64_t a = journal.begin("run_action", {{"id", "orca_command:open_preferences:orca"}}); + journal.job_started(a, "j7"); journal.end(a, ToolResult::ok({{"status", "blocked_by_dialog"}, {"job", "j7"}})); const uint64_t b = journal.begin("dialog_respond", {{"button", "close"}}); journal.end(b, ToolResult::ok()); diff --git a/tests/slic3rutils/test_mcp_results.cpp b/tests/slic3rutils/test_mcp_results.cpp new file mode 100644 index 0000000000..9a1af71e06 --- /dev/null +++ b/tests/slic3rutils/test_mcp_results.cpp @@ -0,0 +1,1555 @@ +// The GUI headers reach wx's MSW headers after OCCT has hidden the USER and GDI declarations they +// need; the Windows headers first keep them, as in test_plugin_host_api.cpp. +#ifdef WIN32 + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #ifndef NOMINMAX + #define NOMINMAX + #endif + #include <Windows.h> + #include <CommCtrl.h> +#endif + +#include <catch2/catch_message.hpp> +#include <catch2/catch_test_macros.hpp> +#include <catch2/matchers/catch_matchers.hpp> +#include <catch2/matchers/catch_matchers_floating_point.hpp> + +#include "libslic3r/ExtrusionEntity.hpp" +#include "libslic3r/GCode/GCodeProcessor.hpp" +#include "libslic3r/GCode/GCodeStatistics.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/TriangleMesh.hpp" +#include "libvgcode/include/Types.hpp" +#include "slic3r/GUI/3DScene.hpp" +#include "slic3r/GUI/GLToolbar.hpp" +#include "slic3r/GUI/IMSlider.hpp" +#include "slic3r/GUI/ImGuiWrapper.hpp" +#include "slic3r/GUI/LibVGCode/LibVGCodeWrapper.hpp" +#include "slic3r/GUI/MeshUtils.hpp" +#include "slic3r/GUI/Mcp/CanvasTarget.hpp" +#include "slic3r/GUI/Mcp/JobRegistry.hpp" +#include "slic3r/GUI/Mcp/McpCore.hpp" +#include "slic3r/GUI/Mcp/McpJournal.hpp" +#include "slic3r/GUI/Mcp/McpScript.hpp" +#include "slic3r/GUI/Mcp/McpService.hpp" +#include "slic3r/GUI/Mcp/McpServicePtr.hpp" +#include "slic3r/GUI/Mcp/McpTools.hpp" +#include "slic3r/GUI/Mcp/McpTypes.hpp" +#include "slic3r/GUI/Mcp/ModalTracker.hpp" +#include "slic3r/GUI/Mcp/UiInspector.hpp" +#include "slic3r/GUI/Mcp/UiInvoker.hpp" +#include "slic3r/GUI/Mcp/UiRefs.hpp" +#include "slic3r/GUI/NativeCommands.hpp" +#include "slic3r/GUI/PartPlate.hpp" +#include "slic3r/GUI/SceneRaycaster.hpp" +#include "slic3r/GUI/SyntheticInput.hpp" +#include "slic3r/Utils/Http.hpp" +#include "slic3r/Utils/PrintHost.hpp" + +#include <imgui/imgui.h> +#include <imgui/imgui_internal.h> +#include <nlohmann/json.hpp> + +#include <wx/app.h> +#include <wx/arrstr.h> +#include <wx/button.h> +#include <wx/checklst.h> +#include <wx/dataview.h> +#include <wx/defs.h> +#include <wx/dialog.h> +#include <wx/event.h> +#include <wx/evtloop.h> +#include <wx/frame.h> +#include <wx/gdicmn.h> +#include <wx/grid.h> +#include <wx/init.h> +#include <wx/menu.h> +#include <wx/modalhook.h> +#include <wx/msgdlg.h> +#include <wx/panel.h> +#include <wx/popupwin.h> +#include <wx/utils.h> +#include <wx/variant.h> +#include <wx/vector.h> + +#include <atomic> +#include <chrono> +#include <cstddef> +#include <cstdint> +#include <cstdlib> +#include <functional> +#include <memory> +#include <optional> +#include <set> +#include <string> +#include <thread> +#include <tuple> +#include <utility> +#include <vector> + +using namespace Slic3r; +using namespace Slic3r::GUI; +using namespace Slic3r::GUI::Mcp; + +namespace { + +// ImGui frames drawn without OpenGL, as in test_imgui_wrapper.cpp. +struct ImGuiFrames +{ + ImGuiWrapper imgui; + + ImGuiFrames() + { + imgui.set_display_size(800.f, 600.f); + unsigned char* pixels = nullptr; + int width = 0, height = 0; + ImGui::GetIO().Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); + } + + template<class Draw> void frame(Draw draw) + { + ImGui::NewFrame(); + draw(); + ImGui::EndFrame(); + } +}; + +void window(const char* name, const ImVec2& pos, const ImVec2& size, ImGuiWindowFlags flags = 0) +{ + ImGui::SetNextWindowPos(pos); + ImGui::SetNextWindowSize(size); + ImGui::Begin(name, nullptr, flags | ImGuiWindowFlags_NoResize); + ImGui::Text("text"); +} + +} // namespace + +TEST_CASE("a click goes to the frontmost ImGui window that takes mouse input at its pixel", "[Mcp]") +{ + ImGuiFrames frames; + // A gizmo panel with a child, a notification over its corner, and a full-canvas overlay drawn + // last, in front of both, that takes no mouse input. + const auto draw = [] { + window("Cut##gizmo", ImVec2(100.f, 100.f), ImVec2(200.f, 200.f)); + ImGui::BeginChild("body", ImVec2(100.f, 100.f)); + ImGui::Text("body"); + ImGui::EndChild(); + ImGui::End(); + window("!!Ntfctn1", ImVec2(250.f, 250.f), ImVec2(200.f, 100.f)); + ImGui::End(); + window("overlay", ImVec2(0.f, 0.f), ImVec2(800.f, 600.f), ImGuiWindowFlags_NoInputs); + ImGui::End(); + }; + frames.frame(draw); + frames.frame(draw); + + const ImGuiWindow* in_panel = imgui_window_at(ImVec2(280.f, 120.f)); + REQUIRE(in_panel != nullptr); + CHECK(std::string(in_panel->Name) == "Cut##gizmo"); + // The child is the window there; its panel is what owns it. + const ImGuiWindow* in_child = imgui_window_at(ImVec2(150.f, 180.f)); + REQUIRE(in_child != nullptr); + CHECK((in_child->Flags & ImGuiWindowFlags_ChildWindow) != 0); + CHECK(in_child->RootWindow == in_panel); + const ImGuiWindow* over_corner = imgui_window_at(ImVec2(275.f, 275.f)); + REQUIRE(over_corner != nullptr); + CHECK(std::string(over_corner->Name) == "!!Ntfctn1"); + // Under the overlay alone, and beside everything: the scene. + CHECK(imgui_window_at(ImVec2(500.f, 500.f)) == nullptr); + CHECK(imgui_window_at(ImVec2(50.f, 50.f)) == nullptr); + + // A window the last frame no longer drew is gone. + frames.frame([] { + window("Cut##gizmo", ImVec2(100.f, 100.f), ImVec2(200.f, 200.f)); + ImGui::End(); + }); + CHECK(std::string(imgui_window_at(ImVec2(275.f, 275.f))->Name) == "Cut##gizmo"); + CHECK(imgui_window_at(ImVec2(400.f, 300.f)) == nullptr); +} + +TEST_CASE("what covers a click is named by its title, or a notification by its text", "[Mcp]") +{ + std::vector<ImGuiWrapper::RecordedText> texts(2); + texts[0].window = "Cut##gizmo"; + texts[0].text = "Plane"; + texts[1].window = "!!Ntfctn3/##body_0A1B2C3D"; + texts[1].text = "Exported successfully\nOpen folder"; + CHECK(imgui_window_description("Cut##gizmo", texts) == "the \"Cut\" window"); + CHECK(imgui_window_description("!!Ntfctn3", texts) == "the notification \"Exported successfully\""); + CHECK(imgui_window_description("!!Ntfctn4", texts) == "a notification"); + CHECK(imgui_window_description("##overlay", texts) == "an ImGui window"); + + texts[1].text = std::string(70, 'x'); + CHECK(imgui_window_description("!!Ntfctn3", texts) == "the notification \"" + std::string(57, 'x') + "...\""); +} + +TEST_CASE("a modifier or negative part is a surface target, and see-through for other targets", "[Mcp]") +{ + // A 10 mm part, a negative part standing 5 mm out of its top, and a modifier above that. + const auto mesh = std::make_shared<const TriangleMesh>(its_make_cube(10., 10., 10.)); + GLVolume part, negative, modifier; + for (GLVolume* v : {&part, &negative, &modifier}) + v->mesh_raycaster = std::make_unique<MeshRaycaster>(mesh); + part.composite_id = GLVolume::CompositeID(0, 0, 0); + negative.composite_id = GLVolume::CompositeID(0, 1, 0); + modifier.composite_id = GLVolume::CompositeID(0, 2, 0); + negative.is_modifier = modifier.is_modifier = true; + negative.set_volume_offset(Vec3d(2.5, 2.5, 5.)); + modifier.set_volume_offset(Vec3d(2.5, 2.5, 20.)); + const std::vector<GLVolume*> volumes{&part, &negative, &modifier}; + const auto no_gizmo = [](const GLVolume*) { return false; }; + + const std::vector<SurfaceMesh> for_negative = surface_meshes(volumes, &negative, no_gizmo); + REQUIRE(for_negative.size() == 2); + CHECK_FALSE(for_negative[0].target); + CHECK(for_negative[1].target); + CHECK(for_negative[1].name == "object 0 instance 0 part 1"); + // The negative part's top, looked at from above, through the modifier. + const std::pair<Vec3d, Vec3d> down(Vec3d(7.5, 7.5, 100.), -Vec3d::UnitZ()); + CHECK(check_surface(Vec3d(7.5, 7.5, 15.), down, for_negative, nullptr, {}, 0.1).empty()); + + // For the part, both are see-through. + const std::vector<SurfaceMesh> for_part = surface_meshes(volumes, &part, no_gizmo); + REQUIRE(for_part.size() == 1); + CHECK(for_part[0].target); + CHECK(check_surface(Vec3d(7.5, 7.5, 10.), down, for_part, nullptr, {}, 0.1).empty()); + + // An inactive part is hidden unless the open gizmo draws it. + part.is_active = false; + CHECK(surface_meshes(volumes, &negative, no_gizmo).size() == 1); + CHECK(surface_meshes(volumes, &negative, [&](const GLVolume* v) { return v == ∂ }).size() == 2); +} + +TEST_CASE("a toolbar item reads the enabled state its callback gives now, not the last idle event's", "[Mcp]") +{ + GLToolbar toolbar(GLToolbar::Normal, "test"); + toolbar.set_enabled(true); // as the canvas does; a disabled toolbar finds no items + bool can_edit = false; + GLToolbarItem::Data data; + data.name = "layersediting"; + data.enabling_callback = [&can_edit] { return can_edit; }; + REQUIRE(toolbar.add_item(data)); + toolbar.update_items_state(); // the last idle event, before the selection + REQUIRE(toolbar.get_item("layersediting")->is_disabled()); + + can_edit = true; // `select` picked an object + bool changed = false; + CHECK_FALSE(toolbar_items(toolbar, &changed).front()->is_disabled()); + CHECK(changed); + toolbar_items(toolbar, &changed); + CHECK_FALSE(changed); +} + +TEST_CASE("an auto-answer rule presses a wx dialog's button, and answers a native one unseen", "[Mcp]") +{ +#if defined(__linux__) + if (!std::getenv("DISPLAY") && !std::getenv("WAYLAND_DISPLAY")) + SKIP("This test needs a display (for example, xvfb-run)."); +#endif + // A GUI app for the dialogs; wxInitializer uses one set before it, and deletes it. + if (wxTheApp == nullptr) + wxApp::SetInstance(new wxApp); + wxInitializer init; + REQUIRE(init.IsOk()); + { + ModalTracker tracker; + tracker.push_rules({make_rule("unsaved", "Transfer"), make_rule("discard", "no")}); + + // The button's handler does the dialog's work, which ShowModal() returning its id would skip. + wxDialog dialog(nullptr, wxID_ANY, "Unsaved changes"); + int transfers = 0; + auto* transfer = new wxButton(&dialog, wxID_ANY, "Transfer"); + transfer->Bind(wxEVT_BUTTON, [&transfers](wxCommandEvent&) { ++transfers; }); + CHECK(wxModalDialogHook::CallEnter(&dialog) == wxID_NONE); // it opens + CHECK(tracker.top() == &dialog); + CHECK(transfers == 0); + wxTheApp->ProcessPendingEvents(); // what its modal loop does first + CHECK(transfers == 1); + wxModalDialogHook::CallExit(&dialog); + CHECK(tracker.top() == nullptr); + CHECK(tracker.rules_json()[0]["uses"] == 1); + + // A modal opened above it before its loop ran leaves it to dialog_respond. + wxDialog above(nullptr, wxID_ANY, "Other"); + CHECK(wxModalDialogHook::CallEnter(&dialog) == wxID_NONE); + CHECK(wxModalDialogHook::CallEnter(&above) == wxID_NONE); + wxTheApp->ProcessPendingEvents(); + CHECK(transfers == 1); + wxModalDialogHook::CallExit(&above); + wxModalDialogHook::CallExit(&dialog); + + // A native dialog has no handlers: ShowModal() returns the id without showing it. + wxMessageDialog native(nullptr, "Discard the changes?", "Changes", wxYES_NO); + CHECK(wxModalDialogHook::CallEnter(&native) == wxID_NO); + CHECK(tracker.top() == nullptr); + } +} + +TEST_CASE("a plate summary lists every filament slot by use, and its totals count the flush", "[Mcp]") +{ + // Slots 1 and 3 of three print; slot 1 also prints the support. At 1.25 g/cm3, 1000 mm3 weigh 1.25 g. + GCodeProcessorResult result; + result.filaments_count = 3; + result.filament_diameters = {1.75f, 1.75f, 1.75f}; + result.filament_densities = {1.25f, 1.25f, 1.25f}; + result.filament_costs = {40.f, 40.f, 40.f}; + PrintEstimatedStatistics& stats = result.print_statistics; + stats.model_volumes_per_extruder = {{0, 1000.}, {2, 400.}}; + stats.support_volumes_per_extruder = {{0, 80.}}; + stats.wipe_tower_volumes_per_extruder = {{0, 120.}, {2, 40.}}; + stats.flush_per_filament = {{0, 200.}, {2, 160.}}; + stats.total_volumes_per_extruder = {{0, 1400.}, {2, 600.}}; + // The processor's per-role sums leave the flush out: 1640 mm3, 2.05 g. + stats.used_filaments_per_role = {{erExternalPerimeter, {0.58, 1.75}}, {erSupportMaterial, {0.03, 0.1}}, {erWipeTower, {0.07, 0.2}}}; + for (PrintEstimatedStatistics::Mode& mode : stats.modes) + mode.reset(); // PrintEstimatedStatistics::reset() resets copies + stats.modes[size_t(PrintEstimatedStatistics::ETimeMode::Normal)].time = 3725.4; + stats.modes[size_t(PrintEstimatedStatistics::ETimeMode::Stealth)].time = 4102.; + stats.total_filament_changes = 3; + // Two layers, at 0.2 and 0.4 mm. + for (const auto& [layer, z, filament] : std::vector<std::tuple<unsigned int, float, unsigned char>>{{0, 0.2f, 0}, {0, 0.2f, 2}, {1, 0.4f, 0}, {1, 0.4f, 2}}) { + GCodeProcessorResult::MoveVertex move; + move.type = EMoveType::Extrude; + move.extrusion_role = erExternalPerimeter; + move.extruder_id = filament; + move.layer_id = layer; + move.position = Vec3f(0.f, 0.f, z); + move.delta_extruder = 1.f; + move.time[0] = 1.f; + result.moves.push_back(move); + } + using Catch::Matchers::WithinAbs; + + SECTION("a printer with a silent mode, on a single nozzle") + { + const nlohmann::json summary = plate_summary(nlohmann::json::parse(gcode_statistics_json(result)), result); + CHECK(summary["time_s"] == 3725); + CHECK(summary["silent_time_s"] == 4102); + CHECK_FALSE(summary.contains("extruder_changes")); + CHECK(summary["layers"] == 2); + CHECK_THAT(summary["max_z"].get<double>(), WithinAbs(0.4, 1e-6)); + CHECK(summary["filament_changes"] == 3); + CHECK_THAT(summary["filament_cost"].get<double>(), WithinAbs(0.1, 1e-9)); + + // 2000 mm3 with the flush: 2.5 g, the per-role sums and the 0.45 g of flush. + CHECK_THAT(summary["filament_g"].get<double>(), WithinAbs(2.5, 1e-9)); + double role_grams = 0.; + for (const auto& [role, used] : stats.used_filaments_per_role) + role_grams += used.second; + CHECK_THAT(summary["filament_g"].get<double>(), WithinAbs(role_grams + 0.45, 1e-9)); + // 2000 mm3 of 1.75 mm filament are 0.83 m. + CHECK_THAT(summary["filament_m"].get<double>(), WithinAbs(0.83, 1e-9)); + + const nlohmann::json& filaments = summary["filaments"]; + REQUIRE(filaments.size() == 3); + for (size_t i = 0; i < 3; ++i) + CHECK(filaments[i]["slot"] == i + 1); + CHECK_THAT(filaments[0]["g"].get<double>(), WithinAbs(1.75, 1e-9)); + CHECK_THAT(filaments[0]["model_g"].get<double>(), WithinAbs(1.25, 1e-9)); + CHECK_THAT(filaments[0]["support_g"].get<double>(), WithinAbs(0.1, 1e-9)); + CHECK_THAT(filaments[0]["tower_g"].get<double>(), WithinAbs(0.15, 1e-9)); + CHECK_THAT(filaments[0]["flush_g"].get<double>(), WithinAbs(0.25, 1e-9)); + CHECK_THAT(filaments[0]["m"].get<double>(), WithinAbs(0.58, 1e-9)); + // An unused slot reads 0 in every use. + for (const char* key : {"m", "g", "model_g", "support_g", "flush_g", "tower_g"}) + CHECK(filaments[1][key].get<double>() == 0.); + CHECK_THAT(filaments[2]["g"].get<double>(), WithinAbs(0.75, 1e-9)); + CHECK_THAT(filaments[2]["flush_g"].get<double>(), WithinAbs(0.2, 1e-9)); + CHECK_THAT(filaments[2]["tower_g"].get<double>(), WithinAbs(0.05, 1e-9)); + } + + SECTION("a printer without a silent mode, with two nozzles") + { + stats.modes[size_t(PrintEstimatedStatistics::ETimeMode::Stealth)].time = 0.; + stats.total_extruder_changes = 2; + const nlohmann::json summary = plate_summary(nlohmann::json::parse(gcode_statistics_json(result)), result); + CHECK_FALSE(summary.contains("silent_time_s")); + CHECK(summary["extruder_changes"] == 2); + } + + SECTION("a slot past the project's count, as a G-code file's header may give") + { + result.filaments_count = 1; + const nlohmann::json summary = plate_summary(nlohmann::json::parse(gcode_statistics_json(result)), result); + REQUIRE(summary["filaments"].size() == 3); + CHECK(summary["filaments"][2]["slot"] == 3); + CHECK_THAT(summary["filaments"][2]["g"].get<double>(), WithinAbs(0.75, 1e-9)); + } +} + +namespace { + +// Three layers of moves: an object's first two at 0.2 and 0.4 mm, then the first of the next object of a +// by-object print, back at 0.2 mm. Each has a 2 s outer wall and a 1 s travel; the first also 3 s of +// sparse infill. 20 s in all, as retractions, Z moves and the prepare time count too. +void fill_preview_result(GCodeProcessorResult& result) +{ + result.filaments_count = 1; + result.filament_diameters = {1.75f}; + result.filament_densities = {1.25f}; + result.filament_costs = {20.f}; + PrintEstimatedStatistics& stats = result.print_statistics; + for (PrintEstimatedStatistics::Mode& mode : stats.modes) + mode.reset(); + stats.modes[size_t(PrintEstimatedStatistics::ETimeMode::Normal)].time = 20.; + stats.modes[size_t(PrintEstimatedStatistics::ETimeMode::Normal)].prepare_time = 2.f; + stats.total_travel_distance = 123.44f; + const auto add = [&result](unsigned int layer, float z, EMoveType type, ExtrusionRole role, float seconds) { + GCodeProcessorResult::MoveVertex move; + move.type = type; + move.extrusion_role = role; + move.layer_id = layer; + move.position = Vec3f(0.f, 0.f, z); + move.delta_extruder = type == EMoveType::Extrude ? 10.f : 0.f; + move.time[0] = seconds; + result.moves.push_back(move); + }; + for (const auto& [layer, z] : std::vector<std::pair<unsigned int, float>>{{0, 0.2f}, {1, 0.4f}, {2, 0.2f}}) { + add(layer, z, EMoveType::Extrude, erExternalPerimeter, 2.f); + if (layer == 0) + add(layer, z, EMoveType::Extrude, erInternalInfill, 3.f); + add(layer, z + 0.4f, EMoveType::Travel, erNone, 1.f); + } +} + +} // namespace + +TEST_CASE("preview features carry their share of the print time, and a travel row", "[Mcp]") +{ + using Catch::Matchers::WithinAbs; + GCodeProcessorResult result; + fill_preview_result(result); + const nlohmann::json features = preview_features(nlohmann::json::parse(gcode_statistics_json(result))); + + REQUIRE(features.size() == 3); + CHECK_THAT(features["Outer wall"]["time_s"].get<double>(), WithinAbs(6., 1e-9)); + CHECK_THAT(features["Outer wall"]["percent"].get<double>(), WithinAbs(30., 1e-9)); + CHECK_THAT(features["Sparse infill"]["time_s"].get<double>(), WithinAbs(3., 1e-9)); + CHECK_THAT(features["Sparse infill"]["percent"].get<double>(), WithinAbs(15., 1e-9)); + // Each 10 mm of 1.75 mm filament at 1.25 g/cm3 weighs 0.03 g. + CHECK_THAT(features["Outer wall"]["g"].get<double>(), WithinAbs(0.09, 1e-9)); + CHECK_THAT(features["Sparse infill"]["g"].get<double>(), WithinAbs(0.03, 1e-9)); + CHECK_THAT(features["Travel"]["time_s"].get<double>(), WithinAbs(3., 1e-9)); + CHECK_THAT(features["Travel"]["mm"].get<double>(), WithinAbs(123.4, 1e-9)); + CHECK_FALSE(features["Travel"].contains("g")); + + // A share is the row's time over the print time; the rows leave out what is neither extrusion nor travel. + double shares = 0.; + for (const auto& row : features.items()) { + CHECK_THAT(row.value()["percent"].get<double>(), WithinAbs(row.value()["time_s"].get<double>() / 20. * 100., 0.05)); + shares += row.value()["percent"].get<double>(); + } + CHECK(shares <= 100.); + CHECK_THAT(shares, WithinAbs(60., 1e-9)); +} + +TEST_CASE("preview layers count from 1, with each height above the layer below", "[Mcp]") +{ + using Catch::Matchers::WithinAbs; + GCodeProcessorResult result; + fill_preview_result(result); + const nlohmann::json statistics = nlohmann::json::parse(gcode_statistics_json(result)); + + const nlohmann::json layers = preview_layers(statistics, false); + REQUIRE(layers.size() == 3); + for (size_t i = 0; i < 3; ++i) + CHECK(layers[i]["layer"] == i + 1); + CHECK_THAT(layers[0]["z"].get<double>(), WithinAbs(0.2, 1e-6)); + CHECK_THAT(layers[0]["height"].get<double>(), WithinAbs(0.2, 1e-9)); + CHECK_THAT(layers[1]["height"].get<double>(), WithinAbs(0.2, 1e-9)); + // The next object of a by-object print starts again from the bed. + CHECK_THAT(layers[2]["z"].get<double>(), WithinAbs(0.2, 1e-6)); + CHECK_THAT(layers[2]["height"].get<double>(), WithinAbs(0.2, 1e-9)); + // A layer takes the time of all its moves, travel included. + CHECK_THAT(layers[0]["time_s"].get<double>(), WithinAbs(6., 1e-9)); + CHECK_THAT(layers[1]["time_s"].get<double>(), WithinAbs(3., 1e-9)); + CHECK_THAT(layers[0]["g"].get<double>(), WithinAbs(0.06, 1e-3)); + CHECK_FALSE(layers[0].contains("features")); + + SECTION("with each feature type's seconds") + { + const nlohmann::json with = preview_layers(statistics, true); + CHECK(with[0]["features"] == nlohmann::json{{"Outer wall", 2.}, {"Sparse infill", 3.}}); + CHECK(with[1]["features"] == nlohmann::json{{"Outer wall", 2.}}); + } + + SECTION("paged") + { + const nlohmann::json first = page(layers, {{"limit", 2}}); + CHECK(first["total"] == 3); + CHECK(first["items"].size() == 2); + CHECK(first["next_offset"] == 2); + const nlohmann::json rest = page(layers, {{"limit", 2}, {"offset", 2}}); + REQUIRE(rest["items"].size() == 1); + CHECK(rest["items"][0]["layer"] == 3); + CHECK_FALSE(rest.contains("next_offset")); + } +} + +TEST_CASE("a preview object carries its list_objects index only when its name is unique", "[Mcp]") +{ + using Catch::Matchers::WithinAbs; + GCodeProcessorResult result; + fill_preview_result(result); + // Two instances of a cube, with 0.2 g of support under the first, and a benchy. Masses are in mg. + const auto mass = [](double milligrams) { + GCodeProcessorResult::ObjectMass object; + GCodeProcessorResult::ObjectMass::Sum sum; + sum.mass = milligrams; + object.printed_up_to_layer.push_back(sum); + return object; + }; + for (const auto& [name, instance, milligrams] : std::vector<std::tuple<std::string, int, double>>{{"Cube", 0, 1500.}, {"Cube", 1, 1500.}, {"Benchy", 0, 12340.}}) { + result.object_masses.push_back(mass(milligrams)); + result.object_masses.back().name = name; + result.object_masses.back().instance = instance; + } + result.support_masses.push_back(mass(200.)); + const nlohmann::json statistics = nlohmann::json::parse(gcode_statistics_json(result)); + + const nlohmann::json objects = preview_objects(statistics, {"Benchy", "Cube"}); + REQUIRE(objects.size() == 3); + CHECK(objects[0]["name"] == "Cube"); + CHECK(objects[0]["instance"] == 0); + CHECK(objects[0]["object"] == 1); + CHECK_THAT(objects[0]["g"].get<double>(), WithinAbs(1.5, 1e-9)); + CHECK_THAT(objects[0]["support_g"].get<double>(), WithinAbs(0.2, 1e-9)); + CHECK(objects[1]["instance"] == 1); + CHECK(objects[1]["object"] == 1); + CHECK(objects[1]["support_g"].get<double>() == 0.); + CHECK(objects[2]["object"] == 0); + CHECK_THAT(objects[2]["g"].get<double>(), WithinAbs(12.34, 1e-9)); + + // Two objects named Cube, and none named Benchy: neither name says which object it is. + const nlohmann::json ambiguous = preview_objects(statistics, {"Cube", "Cube"}); + for (const nlohmann::json& object : ambiguous) + CHECK_FALSE(object.contains("object")); +} + +TEST_CASE("set_view's legend keys name one feature type or option each, as get_preview lists them", "[Mcp]") +{ + // A feature type goes by the English name of its ;FEATURE: tag, which names no other role. + std::set<std::string> features; + for (std::size_t i = 0; i < libvgcode::GCODE_EXTRUSION_ROLES_COUNT; ++i) { + const auto role = libvgcode::EGCodeExtrusionRole(i); + const std::string name = legend_feature_key(role); + CAPTURE(i, name); + CHECK_FALSE(name.empty()); + CHECK(libvgcode::convert(ExtrusionEntity::string_to_role(name)) == role); + features.insert(name); + } + CHECK(features.size() == libvgcode::GCODE_EXTRUSION_ROLES_COUNT); + + // Every option the legend can list has a key of its own, which is no feature type's name. + std::set<std::string> keys; + for (const libvgcode::EOptionType type : + {libvgcode::EOptionType::Travels, libvgcode::EOptionType::Wipes, libvgcode::EOptionType::Retractions, + libvgcode::EOptionType::Unretractions, libvgcode::EOptionType::Seams, libvgcode::EOptionType::ToolChanges, + libvgcode::EOptionType::ColorChanges, libvgcode::EOptionType::PausePrints, libvgcode::EOptionType::CustomGCodes}) { + const char* key = legend_option_key(type); + REQUIRE(key != nullptr); + CHECK(features.count(key) == 0); + keys.insert(key); + } + CHECK(keys.size() == 9); + CHECK(std::string(legend_option_key(libvgcode::EOptionType::Travels)) == "travel"); + CHECK(std::string(legend_option_key(libvgcode::EOptionType::ToolChanges)) == "filament_changes"); +} + +TEST_CASE("a height picks the first layer whose top is at or above it, as the slider places a custom G-code", "[Mcp]") +{ + // The tops of four 0.2 mm layers, as the Preview gives the layer slider. + IMSlider layers(0, 3, 0, 3); + layers.SetSliderValues({0.2, 0.4, 0.6, 0.8}); + CHECK(layers.get_tick_from_value(0.0, true) == 0); + CHECK(layers.get_tick_from_value(0.4, true) == 1); + // A height a hair above a top, from float arithmetic, is still that layer. + CHECK(layers.get_tick_from_value(0.1 + 0.2 + 0.1, true) == 1); + // Between two tops: the layer that covers that height. + CHECK(layers.get_tick_from_value(0.45, true) == 2); + CHECK(layers.get_tick_from_value(0.8, true) == 3); + // Above the top layer: no layer, which set_view refuses. + CHECK(layers.get_tick_from_value(0.81, true) == -1); +} + +namespace { + +// A popup menu as the inspector walks it: a submenu's entry before its items. +std::vector<MenuEntry> sample_menu() +{ + auto entry = [](std::string label, int parent, bool submenu = false) { + MenuEntry e; + e.label = std::move(label); + e.parent = parent; + e.submenu = submenu; + return e; + }; + std::vector<MenuEntry> entries{entry("Add Part", -1, true), entry("Cube", 0), entry("Load...", 0), + entry("Change Filament", -1, true), entry("Default", 3), entry("Generic PLA (current)", 3), + entry("Generic PLA", 3), entry("Printable", -1), entry("Fix Model", -1), + entry("Delete", -1)}; + for (int i = 0; i < int(entries.size()); ++i) + entries[i].id = 100 + i; + entries[7].checkable = entries[7].checked = true; + entries[8].enabled = false; + name_menu_entries(entries, " (current)"); + return entries; +} + +const MenuEntry* find(const std::vector<MenuEntry>& entries, const std::string& path, std::string& err) +{ + nlohmann::json details; + return find_menu_entry(entries, path, " (current)", err, details); +} + +// Runs each posted closure at once, as the UI thread would. +class InlineDispatcher final : public UiDispatcher +{ +public: + void post(std::function<void()> fn) override { fn(); } +}; + +} // namespace + +TEST_CASE("a menu item is found by its label path, case and trailing dots aside", "[Mcp]") +{ + const std::vector<MenuEntry> entries = sample_menu(); + std::string err; + const MenuEntry* e = find(entries, "add part>cube", err); + REQUIRE(e != nullptr); + CHECK(e->path == "Add Part>Cube"); + e = find(entries, "Add Part>Load", err); + REQUIRE(e != nullptr); + CHECK(e->id == 102); + CHECK(find(entries, "Add Part > Cube", err) != nullptr); + CHECK(find(entries, "Add Part>Sphere", err) == nullptr); + CHECK(err == "The menu has no item \"Add Part>Sphere\""); + CHECK(find(entries, "Cube", err) == nullptr); +} + +TEST_CASE("a repeated label is numbered #2, and the item in use is matched without its marker", "[Mcp]") +{ + const std::vector<MenuEntry> entries = sample_menu(); + CHECK(entries[5].path == "Change Filament>Generic PLA (current)"); + CHECK(entries[6].path == "Change Filament>Generic PLA #2"); + std::string err; + // A path recorded while another slot was in use still names the same items. + CHECK(find(entries, "Change Filament>Generic PLA", err) == &entries[5]); + CHECK(find(entries, "Change Filament>Generic PLA (current)", err) == &entries[5]); + CHECK(find(entries, "Change Filament>Generic PLA #2", err) == &entries[6]); + CHECK(find(entries, "change filament>generic pla (current) #2", err) == &entries[6]); + CHECK(find(entries, "Change Filament>Generic PLA #3", err) == nullptr); + // A label of its own that ends in " #2" is found by itself. + std::vector<MenuEntry> own(2); + own[0].label = "Plate #2"; + own[1].label = "Plate"; + name_menu_entries(own, " (current)"); + CHECK(find(own, "Plate #2", err) == &own[0]); +} + +TEST_CASE("a submenu path is refused and the error names its items", "[Mcp]") +{ + const std::vector<MenuEntry> entries = sample_menu(); + std::string err; + nlohmann::json details; + CHECK(find_menu_entry(entries, "Add Part", " (current)", err, details) == nullptr); + CHECK(err == "\"Add Part\" is a submenu; name one of its items"); + CHECK(details["items"] == nlohmann::json({"Add Part>Cube", "Add Part>Load..."})); +} + +TEST_CASE("a disabled item is reported as disabled, not run", "[Mcp]") +{ + const std::vector<MenuEntry> entries = sample_menu(); + std::string err; + nlohmann::json details; + CHECK(find_menu_entry(entries, "Fix Model", " (current)", err, details) == nullptr); + CHECK(err == "\"Fix Model\" is disabled here"); + CHECK(details["disabled"] == nlohmann::json({"Fix Model"})); + // Under a disabled submenu every item is disabled. + std::vector<MenuEntry> nested(2); + nested[0].label = "More"; + nested[0].submenu = true; + nested[0].enabled = false; + nested[1].label = "Export"; + nested[1].parent = 0; + nested[1].enabled = false; // as the inspector's walk sets it + name_menu_entries(nested, " (current)"); + CHECK(find_menu_entry(nested, "More>Export", " (current)", err, details) == nullptr); +} + +TEST_CASE("a menu listing names disabled and checked items apart from the item paths", "[Mcp]") +{ + const nlohmann::json listing = menu_listing(sample_menu()); + CHECK(listing["items"] == nlohmann::json({"Add Part>Cube", "Add Part>Load...", "Change Filament>Default", + "Change Filament>Generic PLA (current)", "Change Filament>Generic PLA #2", "Printable", + "Fix Model", "Delete"})); + CHECK(listing["disabled"] == nlohmann::json({"Fix Model"})); + CHECK(listing["checked"] == nlohmann::json({"Printable"})); + // Without any, the lists are left out. + std::vector<MenuEntry> plain(1); + plain[0].label = "Delete"; + name_menu_entries(plain, " (current)"); + CHECK(menu_listing(plain) == nlohmann::json({{"items", {"Delete"}}})); +} + +TEST_CASE("a click that only listed a menu is dropped from the script when the next call picks an item of it", "[Mcp]") +{ + const nlohmann::json click{{"action", "click"}, {"button", "right"}, {"at", {{"object", 0}, {"spot", "top"}}}}; + nlohmann::json pick = click; + pick["popup_item"] = "Add Modifier>Cylinder"; + const ToolResult listed = ToolResult::ok({{"popup_menu", {{"items", {"Add Modifier>Cylinder"}}}}}); + const ToolResult ran = ToolResult::ok({{"ran", "Add Modifier>Cylinder"}}); + auto steps = [](Journal& journal) { return journal.to_script("t")["steps"]; }; + + Journal journal; + journal.end(journal.begin("ui_mouse", click), listed); + journal.end(journal.begin("ui_mouse", pick), ran); + REQUIRE(steps(journal).size() == 1); + CHECK(steps(journal)[0]["args"] == pick); + + // A failed pick in between does not count; the listing click then stays, as it changed the selection. + Journal kept; + kept.end(kept.begin("ui_mouse", click), listed); + kept.end(kept.begin("ui_mouse", pick), ToolResult::error("The menu has no item")); + CHECK(steps(kept).size() == 1); + CHECK(steps(kept)[0]["args"] == click); + // Nor does a pick after another call, or one on another target. + Journal other; + other.end(other.begin("ui_mouse", click), listed); + other.end(other.begin("select", {{"objects", {0}}}), ToolResult::ok()); + other.end(other.begin("ui_mouse", pick), ran); + CHECK(steps(other).size() == 3); + nlohmann::json elsewhere = pick; + elsewhere["at"]["spot"] = "front"; + Journal moved; + moved.end(moved.begin("ui_mouse", click), listed); + moved.end(moved.begin("ui_mouse", elsewhere), ran); + CHECK(steps(moved).size() == 2); +} + +TEST_CASE("the UI activity hook brackets each closure that runs, not one its guard refuses", "[Mcp]") +{ + InlineDispatcher dispatcher; + bool modal = false; + std::vector<std::pair<std::string, bool>> seen; + UiInvoker invoker( + dispatcher, [&] { GuardState g; g.modal = modal; return g; }, {}, {}, + [&seen](const std::string& tool, bool running) { seen.emplace_back(tool, running); }); + invoker.run(GuardClass::Mutate, "ui_click", [&] { + invoker.run(GuardClass::Inspect, "get_state", [] { return nlohmann::json(); }); + return nlohmann::json(); + }); + CHECK(seen == std::vector<std::pair<std::string, bool>>{{"ui_click", true}, {"get_state", true}, {"get_state", false}, {"ui_click", false}}); + seen.clear(); + // A closure that throws still ends; one refused before it runs never starts. + CHECK_THROWS_AS(invoker.run(GuardClass::Mutate, "ui_key", []() -> nlohmann::json { throw ToolFailure("no"); }), ToolFailure); + CHECK(seen == std::vector<std::pair<std::string, bool>>{{"ui_key", true}, {"ui_key", false}}); + seen.clear(); + modal = true; + CHECK_THROWS_AS(invoker.run(GuardClass::Mutate, "select", [] { return nlohmann::json(); }), ToolFailure); + CHECK(seen.empty()); +} + +TEST_CASE("a menu opened while a call acts on the UI is listed, run by its path or closed unseen, never shown", "[Mcp]") +{ +#if defined(__linux__) + if (!std::getenv("DISPLAY") && !std::getenv("WAYLAND_DISPLAY")) + SKIP("This test needs a display (for example, xvfb-run)."); +#endif + if (wxTheApp == nullptr) + wxApp::SetInstance(new wxApp); + wxInitializer init; + REQUIRE(init.IsOk()); + { + McpServicePtr service(new McpService()); + UiInspector inspector(*service); + inspector.capture_menus(true); + + // A menu as MenuFactory builds one: handlers on the menu, item states from wxEVT_UPDATE_UI + // handlers on the window the menu pops up from. + wxFrame frame(nullptr, wxID_ANY, "menus"); + wxMenu menu; + auto* add = new wxMenu; + add->Append(1001, "Cube"); + add->Append(1002, "Cylinder"); + menu.AppendSubMenu(add, "Add &Part"); + auto* filaments = new wxMenu; + filaments->Append(1003, "Generic PLA"); + filaments->Append(1004, "Generic PLA"); + menu.AppendSubMenu(filaments, "Change Filament"); + menu.AppendCheckItem(1005, "Printable"); + menu.Check(1005, true); + menu.Append(1006, "Fix Model"); + menu.Append(1007, "Delete\tDel"); + std::vector<int> ran; + int printable = -1; + menu.Bind(wxEVT_MENU, [&ran, &printable](wxCommandEvent& e) { + ran.push_back(e.GetId()); + if (e.GetId() == 1005) + printable = e.GetInt(); + }); + frame.Bind(wxEVT_UPDATE_UI, [](wxUpdateUIEvent& e) { e.Enable(false); }, 1006); + + // A person's menu, with no call acting on the UI, is shown, not taken. + CHECK_FALSE(inspector.on_menu(menu, frame)); + + inspector.ui_activity("ui_click", true); + int token = inspector.arm_menu(""); + CHECK(popup_menu(frame, menu)); + nlohmann::json out = inspector.disarm_menu(token); + CHECK(out["popup_menu"]["items"] == nlohmann::json({"Add Part>Cube", "Add Part>Cylinder", "Change Filament>Generic PLA", + "Change Filament>Generic PLA #2", "Printable", "Fix Model", "Delete"})); + CHECK(out["popup_menu"]["disabled"] == nlohmann::json({"Fix Model"})); + CHECK(out["popup_menu"]["checked"] == nlohmann::json({"Printable"})); + CHECK(ran.empty()); + + // Run by path: the submenu's item, through the menu's handler; a check item toggles first. + token = inspector.arm_menu("change filament>generic pla #2"); + CHECK(popup_menu(frame, menu)); + CHECK(inspector.disarm_menu(token) == nlohmann::json({{"ran", "Change Filament>Generic PLA #2"}})); + CHECK(ran == std::vector<int>{1004}); + token = inspector.arm_menu("Printable"); + CHECK(popup_menu(frame, menu)); + inspector.disarm_menu(token); + CHECK(printable == 0); + CHECK_FALSE(menu.IsChecked(1005)); + + // Items it can't run, and a menu that never opened. + for (const char* path : {"Add Part", "Fix Model", "Sphere"}) { + token = inspector.arm_menu(path); + CHECK(popup_menu(frame, menu)); + CHECK_THROWS_AS(inspector.disarm_menu(token), ToolFailure); + } + token = inspector.arm_menu("Delete"); + CHECK_THROWS_AS(inspector.disarm_menu(token), ToolFailure); + CHECK(ran == std::vector<int>{1004, 1005}); + + // A second menu in one call is closed unseen and counted. + token = inspector.arm_menu(""); + CHECK(popup_menu(frame, menu)); + CHECK(popup_menu(frame, menu)); + CHECK(inspector.disarm_menu(token)["menus_closed"] == 1); + CHECK(inspector.closed_menus().size() == 1); + inspector.ui_activity("ui_click", false); + + // A menu from a call that armed nothing is closed unseen, until the first idle after the call. + inspector.ui_activity("cad_call", true); + inspector.ui_activity("cad_call", false); + CHECK(popup_menu(frame, menu)); + const nlohmann::json closed = inspector.closed_menus(); + REQUIRE(closed.size() == 2); + CHECK(closed[1]["tool"] == "cad_call"); + CHECK(closed[1]["items"].size() == 7); + wxTheApp->ProcessPendingEvents(); + wxIdleEvent idle; + wxTheApp->ProcessEvent(idle); + CHECK_FALSE(inspector.on_menu(menu, frame)); + + // Past a second a person's menu shows even when no idle came, as while events keep queuing. + inspector.ui_activity("cad_call", true); + inspector.ui_activity("cad_call", false); + wxMilliSleep(1100); + CHECK_FALSE(inspector.on_menu(menu, frame)); + + // Only menus of the event loop the call ran in are taken: a person's right click in a dialog's + // loop shows its menu. + inspector.ui_activity("ui_click", true); + { + wxEventLoop dialog_loop; + wxEventLoopActivator inside(&dialog_loop); + CHECK_FALSE(inspector.on_menu(menu, frame)); + } + CHECK(inspector.on_menu(menu, frame)); + // get_state keeps the last three. + CHECK(inspector.on_menu(menu, frame)); + CHECK(inspector.closed_menus().size() == 3); + CHECK(inspector.closed_menus()[2]["tool"] == "ui_click"); + inspector.ui_activity("ui_click", false); + inspector.capture_menus(false); + } +} + +TEST_CASE("a row locator matches the last segments of a row's path", "[Mcp]") +{ + const std::vector<std::string> path{"Plate 1", "Cube", "Cylinder"}; + CHECK(row_segments("Plate 1>Cube>Cylinder") == path); + CHECK(row_segments(nlohmann::json{"Cube", "A>B"}) == std::vector<std::string>{"Cube", "A>B"}); + CHECK_THROWS_AS(row_segments(""), ToolFailure); + CHECK_THROWS_AS(row_segments(3), ToolFailure); + + CHECK(row_matches(path, {"Cylinder"}, "")); + CHECK(row_matches(path, {"Cube", "Cylinder"}, "")); + CHECK(row_matches(path, path, "")); + CHECK_FALSE(row_matches(path, {"Plate 1", "Cylinder"}, "")); + CHECK_FALSE(row_matches(path, {"Cube"}, "")); + CHECK_FALSE(row_matches(path, {"Plate 0", "Plate 1", "Cube", "Cylinder"}, "")); + CHECK_FALSE(row_matches(path, {}, "")); + // The item in use may be named without the marker its list appends. + CHECK(row_matches({"Generic PLA (current)"}, {"Generic PLA"}, " (current)")); + CHECK(row_matches({"Generic PLA (current)"}, {"Generic PLA (current)"}, " (current)")); + CHECK_FALSE(row_matches({"Generic PLA (current)"}, {"Generic"}, " (current)")); + + // The journal writes a path whose label holds '>' as an array. + CHECK(row_locator(path) == "Plate 1>Cube>Cylinder"); + CHECK(row_locator({"Cube", "A>B"}) == nlohmann::json{"Cube", "A>B"}); +} + +TEST_CASE("snapshot text shows a row's value, check state and note", "[Mcp]") +{ + UiNode list; + list.ref = "w1"; + list.kind = "list"; + list.cls = "ObjectList"; + list.note = "columns: Name | Filament"; + UiNode cube; + cube.ref = "r2"; + cube.kind = "row"; + cube.label = "Cube"; + cube.value = "1"; + cube.note = "object 0, selected"; + cube.depth = 1; + UiNode part = cube; + part.ref = "r3"; + part.label = "Cylinder"; + part.value = ""; + part.checked = 1; + part.note = "object 0 part 1, modifier"; + part.depth = 2; + UiNode option = part; + option.ref = "r4"; + option.label = "Brim"; + option.enabled = false; + option.note = ""; + CHECK(format_snapshot({list, cube, part, option}, 0) == "[w1] list (ObjectList) [columns: Name | Filament]\n" + " [r2] row \"Cube\" = \"1\" [object 0, selected]\n" + " [r3] row \"Cylinder\" [checked] [object 0 part 1, modifier]\n" + " [r4] row \"Brim\" [checked] [disabled]\n"); +} + +namespace { + +// A GUI app for list controls; wxInitializer uses one set before it, and deletes it. Members start +// in order, so the plain wxApp is in place before wx starts: without one, wx would create the +// GUI_App that IMPLEMENT_APP names, whose destructor shuts down singletons later tests use. +struct GuiApp +{ + static bool install() + { + if (wxTheApp == nullptr) + wxApp::SetInstance(new wxApp); + return true; + } + bool installed = install(); + wxInitializer init; +}; + +ListRow row_of(wxWindow& list, const std::vector<std::string>& path, int twin = 0) +{ + for (ListRow& row : list_rows(&list)) + if (row.path == path && row.twin == twin) + return row; + FAIL("no row " << nlohmann::json(path).dump()); + return {}; +} + +} // namespace + +TEST_CASE("rows of trees, lists, checklists and tables are listed with their cells, checks and selection", "[Mcp]") +{ +#if defined(__linux__) + if (!std::getenv("DISPLAY") && !std::getenv("WAYLAND_DISPLAY")) + SKIP("This test needs a display (for example, xvfb-run)."); +#endif + GuiApp app; + REQUIRE(app.init.IsOk()); + { + wxFrame frame(nullptr, wxID_ANY, "rows", wxDefaultPosition, wxSize(640, 520)); + + // A tree, with two objects of one name on a plate: twins, told apart by their order. + auto* tree = new wxDataViewTreeCtrl(&frame, wxID_ANY, wxPoint(0, 0), wxSize(300, 200)); + const wxDataViewItem plate = tree->AppendContainer(wxDataViewItem(), "Plate 1"); + const wxDataViewItem cube = tree->AppendContainer(plate, "Cube"); + tree->AppendItem(cube, "Cylinder"); + tree->AppendItem(plate, "Cube"); + const std::vector<ListRow> tree_rows = list_rows(tree); + REQUIRE(tree_rows.size() == 4); + CHECK(tree_rows[2].path == std::vector<std::string>{"Plate 1", "Cube", "Cylinder"}); + CHECK(tree_rows[2].depth == 2); + CHECK_FALSE(tree_rows[2].shown); // its branches are collapsed + CHECK(tree_rows[3].path == std::vector<std::string>{"Plate 1", "Cube"}); + CHECK(tree_rows[3].twin == 1); + CHECK(tree_rows[3].checked == -1); + + // Labels drawn from markup, as the compare presets tree draws them outside macOS, read as they + // show; a label that only starts with "<" is kept. + auto* marked = new wxDataViewTreeCtrl(&frame, wxID_ANY, wxPoint(0, 450), wxSize(300, 60)); + const wxDataViewItem quality = marked->AppendContainer(wxDataViewItem(), "<b><span color=\"#363636\">Quality</span></b>"); + marked->AppendItem(quality, "<span color=\"#363636\">Walls & surfaces</span>"); + marked->AppendItem(wxDataViewItem(), "<untitled"); + const std::vector<ListRow> marked_rows = list_rows(marked); + REQUIRE(marked_rows.size() == 3); + CHECK(marked_rows[1].path == std::vector<std::string>{"Quality", "Walls & surfaces"}); + CHECK(marked_rows[2].path == std::vector<std::string>{"<untitled"}); + + // A list with a checkbox column first: the first text cell is the label, the others the value. + auto* options = new wxDataViewListCtrl(&frame, wxID_ANY, wxPoint(300, 0), wxSize(300, 200)); + options->AppendToggleColumn("Use"); + options->AppendTextColumn("Option"); + options->AppendTextColumn("Value"); + wxVector<wxVariant> values; + values.push_back(wxVariant(true)); + values.push_back(wxVariant("Layer height")); + values.push_back(wxVariant("0.2 | 0.12")); + options->AppendItem(values); + const std::vector<ListRow> option_rows = list_rows(options); + REQUIRE(option_rows.size() == 1); + CHECK(option_rows[0].path == std::vector<std::string>{"Layer height"}); + CHECK(option_rows[0].value == "0.2 | 0.12"); + CHECK(option_rows[0].checked == 1); + CHECK(list_columns(options) == std::vector<std::string>{"Use", "Option", "Value"}); + + wxArrayString names; + names.Add("Wall loops"); + names.Add("Sparse infill density"); + auto* checks = new wxCheckListBox(&frame, wxID_ANY, wxPoint(0, 200), wxSize(300, 100), names); + checks->Check(1); + const std::vector<ListRow> check_rows = list_rows(checks); + REQUIRE(check_rows.size() == 2); + CHECK(check_rows[0].checked == 0); + CHECK(check_rows[1].checked == 1); + CHECK(check_rows[1].index == 1); + + // A table with column labels; one that draws its titles as its first row, as the object + // settings table does, is read the same way. + auto* table = new wxGrid(&frame, wxID_ANY, wxPoint(300, 200), wxSize(300, 150)); + table->CreateGrid(2, 2); + table->SetColLabelValue(0, "Name"); + table->SetColLabelValue(1, "Walls"); + table->SetCellValue(0, 0, "Cube"); + table->SetCellValue(0, 1, "2"); + table->SetCellValue(1, 0, "Cylinder"); + table->SetCellValue(1, 1, "3"); + auto* titled = new wxGrid(&frame, wxID_ANY, wxPoint(0, 300), wxSize(300, 150)); + titled->CreateGrid(2, 3); + titled->HideColLabels(); + titled->HideRowLabels(); + titled->SetCellValue(0, 0, "Plate"); + titled->SetCellValue(0, 2, "Name"); + titled->SetCellValue(1, 0, "1"); + titled->SetCellValue(1, 1, "unseen"); + titled->SetCellValue(1, 2, "Cube"); + for (wxGrid* grid : {table, titled}) { + const std::vector<ListRow> rows = list_rows(grid); + REQUIRE_FALSE(rows.empty()); + CHECK(rows[0].path == std::vector<std::string>{"Cube"}); + } + CHECK(list_rows(table)[1].value == "Cylinder | 3"); + CHECK(list_rows(titled).size() == 1); + CHECK(list_rows(titled)[0].value == "1 | Cube"); + CHECK(list_columns(titled) == std::vector<std::string>{"Plate", "Name"}); + + // Row locators look through every shown list: a label two rows have needs an index. + frame.Show(); + CHECK(find_rows({&frame}, {"Cube"}).size() == 4); // two tree rows and a row of each table + CHECK(find_rows({&frame}, {"Plate 1", "Cube"}).size() == 2); + const auto cylinder = find_rows({&frame}, {"Cube", "Cylinder"}); + REQUIRE(cylinder.size() == 1); + CHECK(cylinder[0].first == tree); + CHECK(find_rows({&frame}, {"Sparse infill density"}).at(0).first == checks); + } +} + +TEST_CASE("a click on a row selects it as a person's does and tells its owner once", "[Mcp]") +{ +#if defined(__linux__) + if (!std::getenv("DISPLAY") && !std::getenv("WAYLAND_DISPLAY")) + SKIP("This test needs a display (for example, xvfb-run)."); +#endif + GuiApp app; + REQUIRE(app.init.IsOk()); + { + wxFrame frame(nullptr, wxID_ANY, "clicks", wxDefaultPosition, wxSize(640, 520)); + auto* tree = new wxDataViewTreeCtrl(&frame, wxID_ANY, wxPoint(0, 0), wxSize(300, 300), wxDV_MULTIPLE); + const wxDataViewItem plate = tree->AppendContainer(wxDataViewItem(), "Plate 1"); + const wxDataViewItem cube = tree->AppendContainer(plate, "Cube"); + const wxDataViewItem part = tree->AppendItem(cube, "Cylinder"); + const wxDataViewItem other = tree->AppendItem(plate, "Cube"); + frame.Show(); + // GTK lays the rows out once the shown frame has been through the event loop; a click needs + // their places, as the app's lists have long had theirs. + for (int i = 0; i < 100; ++i) { + wxTheApp->Yield(true); + if (!tree->GetItemRect(plate).IsEmpty()) + break; + wxMilliSleep(10); + } + + std::vector<wxDataViewItem> changed; + wxDataViewItem menu, activated; + tree->Bind(wxEVT_DATAVIEW_SELECTION_CHANGED, [&changed](wxDataViewEvent& e) { changed.push_back(e.GetItem()); }); + tree->Bind(wxEVT_DATAVIEW_ITEM_CONTEXT_MENU, [&menu](wxDataViewEvent& e) { menu = e.GetItem(); }); + tree->Bind(wxEVT_DATAVIEW_ITEM_ACTIVATED, [&activated](wxDataViewEvent& e) { activated = e.GetItem(); }); + + // A click opens the branches above the row and selects it alone, with one notice. + ClickOptions left; + const nlohmann::json out = click_row(*tree, row_of(*tree, {"Plate 1", "Cube", "Cylinder"}), "", left); + CHECK(out["selected"] == nlohmann::json{"Plate 1>Cube>Cylinder"}); + CHECK(tree->IsExpanded(cube)); + REQUIRE(changed.size() == 1); + CHECK(changed[0] == part); + CHECK_FALSE(SyntheticInput::is_mouse_held()); + + // Ctrl adds a row and takes it out again. + ClickOptions ctrl; + ctrl.modifiers = {"ctrl"}; + CHECK(click_row(*tree, row_of(*tree, {"Plate 1", "Cube"}, 1), "", ctrl)["selected"].size() == 2); + CHECK(changed.size() == 2); + CHECK(changed[1] == other); + CHECK(click_row(*tree, row_of(*tree, {"Plate 1", "Cube"}, 1), "", ctrl)["selected"] == nlohmann::json{"Plate 1>Cube>Cylinder"}); + + // A right click on a selected row keeps the selection and asks for its menu; on another row it + // selects that row first. + ClickOptions right; + right.button = "right"; + click_row(*tree, row_of(*tree, {"Plate 1", "Cube", "Cylinder"}), "", right); + CHECK(menu == part); + CHECK(changed.size() == 3); + click_row(*tree, row_of(*tree, {"Plate 1"}), "", right); + CHECK(menu == plate); + CHECK(changed.size() == 4); + CHECK(tree->IsSelected(plate)); + + ClickOptions twice; + twice.double_click = true; + click_row(*tree, row_of(*tree, {"Plate 1", "Cube"}), "", twice); + CHECK(activated == cube); + + ClickOptions middle; + middle.button = "middle"; + CHECK_THROWS_AS(click_row(*tree, row_of(*tree, {"Plate 1"}), "", middle), ToolFailure); + CHECK_THROWS_AS(click_row(*tree, row_of(*tree, {"Plate 1"}), "Nope", left), ToolFailure); + CHECK_THROWS_AS(input_row(*tree, row_of(*tree, {"Plate 1"}), "", true), ToolFailure); + + // A checkbox cell is set as the toggle renderer sets it, which tells the owner. + auto* options = new wxDataViewListCtrl(&frame, wxID_ANY, wxPoint(300, 0), wxSize(300, 200)); + options->AppendToggleColumn("Use"); + options->AppendTextColumn("Option"); + wxVector<wxVariant> values; + values.push_back(wxVariant(true)); + values.push_back(wxVariant("Layer height")); + options->AppendItem(values); + int value_changes = 0; + options->Bind(wxEVT_DATAVIEW_ITEM_VALUE_CHANGED, [&value_changes](wxDataViewEvent&) { ++value_changes; }); + CHECK(input_row(*options, row_of(*options, {"Layer height"}), "", false)["checked"] == false); + CHECK_FALSE(options->GetToggleValue(0, 0)); + CHECK(value_changes == 1); + CHECK(input_row(*options, row_of(*options, {"Layer height"}), "Use", "false")["checked"] == false); + CHECK(value_changes == 1); + CHECK_THROWS_AS(input_row(*options, row_of(*options, {"Layer height"}), "Option", true), ToolFailure); + + // A checklist row: ticked with its event; clicked, selected with the list box's. + wxArrayString names; + names.Add("Wall loops"); + names.Add("Sparse infill density"); + auto* checks = new wxCheckListBox(&frame, wxID_ANY, wxPoint(0, 300), wxSize(300, 100), names); + int ticks = 0, picks = 0; + checks->Bind(wxEVT_CHECKLISTBOX, [&ticks](wxCommandEvent& e) { ticks += e.GetInt() + 1; }); + checks->Bind(wxEVT_LISTBOX, [&picks](wxCommandEvent&) { ++picks; }); + CHECK(input_row(*checks, row_of(*checks, {"Sparse infill density"}), "", true)["checked"] == true); + CHECK(checks->IsChecked(1)); + CHECK(ticks == 2); + input_row(*checks, row_of(*checks, {"Sparse infill density"}), "", true); + CHECK(ticks == 2); + CHECK(click_row(*checks, row_of(*checks, {"Wall loops"}), "", left)["selected"] == nlohmann::json{"Wall loops"}); + CHECK(picks == 1); + CHECK_THROWS_AS(click_row(*checks, row_of(*checks, {"Wall loops"}), "Option", left), ToolFailure); + + // A table row's cell is made current, as a click makes it; the table is read-only. + auto* table = new wxGrid(&frame, wxID_ANY, wxPoint(300, 200), wxSize(300, 150)); + table->CreateGrid(2, 2); + table->SetColLabelValue(0, "Name"); + table->SetColLabelValue(1, "Walls"); + table->SetCellValue(1, 0, "Cylinder"); + int selects = 0; + table->Bind(wxEVT_GRID_SELECT_CELL, [&selects](wxGridEvent& e) { + ++selects; + e.Skip(); + }); + CHECK(click_row(*table, row_of(*table, {"Cylinder"}), "walls", left)["column"] == "Walls"); + CHECK(table->GetGridCursorRow() == 1); + CHECK(table->GetGridCursorCol() == 1); + CHECK(selects == 1); + CHECK_THROWS_AS(input_row(*table, row_of(*table, {"Cylinder"}), "", true), ToolFailure); + CHECK_THROWS_AS(click_row(*table, row_of(*table, {"Cylinder"}), "", right), ToolFailure); + } +} + +TEST_CASE("a widget in a popup belongs to the window the popup opened from, which lists the popup after it", "[Mcp]") +{ +#if defined(__linux__) + if (!std::getenv("DISPLAY") && !std::getenv("WAYLAND_DISPLAY")) + SKIP("This test needs a display (for example, xvfb-run)."); +#endif + GuiApp app; + REQUIRE(app.init.IsOk()); + { + wxFrame frame(nullptr, wxID_ANY, "popups"); + auto* panel = new wxPanel(&frame); + auto* popup = new wxPopupTransientWindow(panel); + auto* button = new wxButton(popup, wxID_ANY, "Export plate sliced file"); + CHECK(owning_window(button) == &frame); + CHECK(owning_window(popup) == &frame); + CHECK(owning_window(panel) == &frame); + frame.Show(); + CHECK(popups_of(&frame).empty()); // not shown + popup->Show(); + CHECK(popups_of(&frame) == std::vector<wxWindow*>{popup}); + popup->Hide(); + } +} + +TEST_CASE("a plate icon name maps to its picking action and back", "[Mcp]") +{ + const std::vector<std::string> names{"plate", "delete", "orient", "arrange", "lock", + "settings", "name", "move_to_front", "filament_map", "imex_mode"}; + REQUIRE(int(names.size()) == kPlateIconCount); + for (int action = 0; action < kPlateIconCount; ++action) { + CAPTURE(action); + CHECK(plate_icon_name(action) == names[action]); + CHECK(plate_icon_action(names[action]) == action); + } + CHECK(plate_icon_action("Lock") == -1); + CHECK(plate_icon_action("") == -1); + CHECK(plate_icon_name(-1).empty()); + CHECK(plate_icon_name(kPlateIconCount).empty()); + // The actions PartPlate names, and the count its picking ids are spaced by. + CHECK(kPlateIconCount == int(PartPlate::GRABBER_COUNT)); + CHECK(plate_icon_action("name") == int(PartPlate::PLATE_NAME_HOVER_ID)); + CHECK(plate_icon_action("filament_map") == int(PartPlate::PLATE_FILAMENT_MAP_ID)); + CHECK(plate_icon_action("imex_mode") == int(PartPlate::PLATE_IMEX_MODE_ID)); +} + +TEST_CASE("a bed picking id decodes to its plate and icon", "[Mcp]") +{ + CHECK(plate_icon_of(0) == std::pair<int, int>{0, 0}); + CHECK(plate_icon_of(4) == std::pair<int, int>{0, plate_icon_action("lock")}); + CHECK(plate_icon_of(23) == std::pair<int, int>{2, plate_icon_action("arrange")}); + // What PartPlate::picking_id_component() registers, as the scene raycaster hands it back. + SceneRaycaster scene; + const MeshRaycaster mesh(std::make_shared<const TriangleMesh>(its_make_cube(1., 1., 1.))); + for (int plate = 0; plate < int(GUI::PartPlateList::MAX_PLATES_COUNT); ++plate) + for (int action = 0; action < kPlateIconCount; ++action) + scene.add_raycaster(SceneRaycaster::EType::Bed, plate * int(PartPlate::GRABBER_COUNT) + action, mesh, Transform3d::Identity()); + const auto* items = scene.get_raycasters(SceneRaycaster::EType::Bed); + REQUIRE(items != nullptr); + REQUIRE(int(items->size()) == int(GUI::PartPlateList::MAX_PLATES_COUNT) * kPlateIconCount); + for (std::size_t i = 0; i < items->size(); ++i) { + const int plate = int(i) / kPlateIconCount, action = int(i) % kPlateIconCount; + CHECK(plate_icon_of(SceneRaycaster::decode_id(SceneRaycaster::EType::Bed, (*items)[i]->get_id())) == + std::pair<int, int>{plate, action}); + } +} + +namespace { + +// A core whose tools need no UI thread: `build` outlives its reply budget until `release` is set, +// then returns `build_result` (a slow CAD rebuild); `edit` succeeds at once; `wait` hands back a +// job's result, or reports it still running, as the real tool does. +struct JobJournal +{ + InlineDispatcher ui; + UiInvoker invoker{ui, [] { return GuardState{}; }}; + JobRegistry jobs; + Journal journal; + ToolRegistry registry; + std::atomic<bool> release{false}; + ToolResult build_result; + std::atomic<int> builds{0}; + std::atomic<int> edits{0}; + std::unique_ptr<McpCore> core; + + JobJournal() + { + ToolDef build; + build.name = "build"; + build.budget_ms = 100; + build.handler = [this](const nlohmann::json&, ToolContext&) { + ++builds; + while (!release) + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + return build_result; + }; + registry.add(build); + ToolDef edit; + edit.name = "edit"; + edit.handler = [this](const nlohmann::json&, ToolContext&) { + ++edits; + return ToolResult::ok({{"edited", true}}); + }; + registry.add(edit); + ToolDef wait; + wait.name = "wait"; + wait.guard = GuardClass::Inspect; + wait.inline_call = true; + wait.handler = [this](const nlohmann::json& args, ToolContext&) { + const std::string job = args["job"].get<std::string>(); + if (auto r = jobs.wait(job, std::chrono::milliseconds(args.value("timeout_ms", 5000)))) + return *r; + return ToolResult::ok({{"status", "running"}, {"job", job}, {"note", "Still running; wait again."}}); + }; + registry.add(wait); + core = std::make_unique<McpCore>(registry, invoker, jobs, &journal); + } + ~JobJournal() + { + release = true; + invoker.shutdown(); + jobs.wake_all(); + core->shutdown(); + } + + ToolResult call(const std::string& tool, const nlohmann::json& args = nlohmann::json::object()) + { + return core->call(*registry.find(tool), args); + } + // Starts `build`, which replies with its running job; returns the job. + std::string start_build() + { + const ToolResult started = call("build", {{"feature", "thread"}}); + REQUIRE_FALSE(started.is_error); + REQUIRE(started.data["status"] == "running"); + return started.data["job"].get<std::string>(); + } +}; + +} // namespace + +TEST_CASE("a mutation whose job fails after its reply is dropped from the script, which replays the rest", "[Mcp]") +{ + JobJournal h; + h.build_result = ToolResult::error("The thread could not be built"); + const std::string job = h.start_build(); + h.release = true; + const ToolResult failed = h.call("wait", {{"for", "job"}, {"job", job}}); + CHECK(failed.is_error); + CHECK_FALSE(h.call("edit", {{"value", 3}}).is_error); + + nlohmann::json running; + const nlohmann::json script = h.journal.to_script("t", &running); + REQUIRE(script["steps"].size() == 1); + CHECK(script["steps"][0]["tool"] == "edit"); + CHECK(script["steps"][0]["args"] == nlohmann::json{{"value", 3}}); + CHECK(running.empty()); + + // The replay runs the edit alone, as a run_script job's children. + std::string err; + const std::optional<Script> parsed = parse_script(script.dump(), err); + REQUIRE(parsed.has_value()); + const std::string parent = h.jobs.create("run_script", ""); + ScriptContext sctx; + ScriptHost host; + host.call = [&](const std::string& tool, const nlohmann::json& args) { return h.core->call_child(*h.registry.find(tool), args, parent); }; + host.wait_job = [&](const std::string& id, int timeout_s) { return h.jobs.wait(id, std::chrono::seconds(timeout_s)); }; + const nlohmann::json replay = run_script(*parsed, sctx, host); + h.jobs.finish(parent, ToolResult::ok()); + CHECK(replay["passed"] == true); + CHECK(h.builds.load() == 1); + CHECK(h.edits.load() == 2); + // A script's own steps are not journaled. + CHECK(h.journal.to_script("t")["steps"].size() == 1); +} + +TEST_CASE("an export while a mutation's job runs leaves the call out and names it, and keeps it once the job is done", "[Mcp]") +{ + JobJournal h; + h.build_result = ToolResult::ok({{"built", true}}); + const std::string job = h.start_build(); + CHECK_FALSE(h.call("edit", {{"value", 1}}).is_error); + // A wait that times out names the job too, but it is not the wait's own. + const ToolResult still = h.call("wait", {{"for", "job"}, {"job", job}, {"timeout_ms", 0}}); + CHECK(still.data["status"] == "running"); + + nlohmann::json running; + nlohmann::json steps = h.journal.to_script("t", &running)["steps"]; + REQUIRE(steps.size() == 1); + CHECK(steps[0]["tool"] == "edit"); + CHECK(running == nlohmann::json::array({{{"tool", "build"}, {"job", job}}})); + + h.release = true; + CHECK(h.call("wait", {{"for", "job"}, {"job", job}}).data["built"] == true); + steps = h.journal.to_script("t", &running)["steps"]; + CHECK(running.empty()); + REQUIRE(steps.size() == 4); + CHECK(steps[0]["tool"] == "build"); + CHECK(steps[0]["await"] == false); + CHECK(steps[0]["save_as"] == "job1"); + CHECK(steps[1]["tool"] == "edit"); + CHECK(steps[2]["args"]["job"] == "${jobs.job1}"); + CHECK_FALSE(steps[2].contains("save_as")); + CHECK(steps[3]["args"]["job"] == "${jobs.job1}"); +} + +TEST_CASE("a job that waits on a dialog stays in the script, and a call yet to reply is left out", "[Mcp]") +{ + Journal journal; + const uint64_t open = journal.begin("run_action", {{"id", "orca_command:open_preferences:orca"}}); + journal.job_started(open, "j1"); + journal.end(open, ToolResult::ok({{"status", "blocked_by_dialog"}, {"job", "j1"}, {"tool", "run_action"}})); + const uint64_t answer = journal.begin("dialog_respond", {{"button", "cancel"}}); + journal.job_started(answer, "j2"); + journal.job_ended(answer, ToolResult::ok()); + journal.end(answer, ToolResult::ok()); + const uint64_t slice = journal.begin("slice", nlohmann::json::object()); + journal.job_started(slice, "j3"); + journal.begin("screenshot", {{"target", "canvas"}}); + + nlohmann::json running; + nlohmann::json steps = journal.to_script("t", &running)["steps"]; + REQUIRE(steps.size() == 2); + CHECK(steps[0]["save_as"] == "job1"); + CHECK(steps[1]["tool"] == "dialog_respond"); + CHECK(running == nlohmann::json::array({{{"tool", "slice"}, {"job", "j3"}}, {{"tool", "screenshot"}}})); + + // The dialog's answer follows it in the script, so it stays when its job then fails. + journal.job_ended(open, ToolResult::error("Cancelled")); + // A job that ends before its reply is recorded is in the script at once. + journal.job_ended(slice, ToolResult::ok()); + steps = journal.to_script("t", &running)["steps"]; + REQUIRE(steps.size() == 3); + CHECK(steps[0]["tool"] == "run_action"); + CHECK(steps[2]["tool"] == "slice"); + CHECK_FALSE(steps[2].contains("await")); + CHECK(running == nlohmann::json::array({{{"tool", "screenshot"}}})); +} + +TEST_CASE("a job that was running when a dialog was answered stays in the script before the answer", "[Mcp]") +{ + // A script past its reply budget opens Preferences, which a later call answers. + Journal journal; + const uint64_t script = journal.begin("run_script", {{"path", "s.json"}}); + journal.job_started(script, "j1"); + journal.end(script, ToolResult::ok({{"status", "running"}, {"job", "j1"}, {"tool", "run_script"}})); + // A call still within its reply budget, whose dialog is answered before it replies. + const uint64_t open = journal.begin("run_action", {{"id", "orca_command:open_preferences:orca"}}); + journal.job_started(open, "j2"); + const uint64_t slice = journal.begin("slice", nlohmann::json::object()); + journal.job_started(slice, "j3"); + journal.end(slice, ToolResult::ok({{"status", "running"}, {"job", "j3"}, {"tool", "slice"}})); + journal.job_ended(slice, ToolResult::error("Cancelled")); + const uint64_t answer = journal.begin("dialog_respond", {{"button", "close"}}, true); + journal.job_started(answer, "j4"); + journal.job_ended(answer, ToolResult::ok()); + journal.end(answer, ToolResult::ok()); + // Input with no dialog open ties nothing to the jobs then running. + const uint64_t click = journal.begin("ui_click", {{"target", "w1"}}); + journal.job_started(click, "j5"); + journal.job_ended(click, ToolResult::ok()); + journal.end(click, ToolResult::ok()); + const uint64_t later = journal.begin("run_action", {{"id", "obj_arrange"}}); + journal.job_started(later, "j6"); + journal.end(later, ToolResult::ok({{"status", "running"}, {"job", "j6"}, {"tool", "run_action"}})); + journal.begin("ui_click", {{"target", "w2"}}); + + nlohmann::json running; + nlohmann::json steps = journal.to_script("t", &running)["steps"]; + REQUIRE(steps.size() == 5); + CHECK(steps[0]["tool"] == "run_script"); + CHECK(steps[0]["await"] == false); + CHECK(steps[1]["tool"] == "run_action"); + CHECK(steps[1]["await"] == false); + // The answer waits for its dialog, which the replayed job may open later than its reply. + CHECK(steps[2] == nlohmann::json({{"tool", "wait"}, {"args", {{"for", "dialog"}, {"timeout_s", 50}}}, {"expect", {{"/satisfied", {{"eq", true}}}}}})); + CHECK(steps[3]["tool"] == "dialog_respond"); + CHECK(steps[4]["tool"] == "ui_click"); + CHECK(running == nlohmann::json::array({{{"tool", "run_action"}, {"job", "j6"}}, {{"tool", "ui_click"}}})); + + // They stay whatever their jobs' results: the answer after them needs a dialog one of them opens. + journal.job_ended(script, ToolResult::error("Step 4 failed")); + journal.job_ended(open, ToolResult::ok()); + journal.end(open, ToolResult::ok({{"ran", "orca_command:open_preferences:orca"}})); + steps = journal.to_script("t")["steps"]; + REQUIRE(steps.size() == 5); + CHECK(steps[0]["tool"] == "run_script"); + CHECK(steps[1]["await"] == false); +} + +TEST_CASE("an exported answer to a dialog a job opens after its reply replays once the dialog is open", "[Mcp]") +{ + // A script replies running, opens Preferences later, and is answered while it keeps running. + Journal journal; + const uint64_t script = journal.begin("run_script", {{"path", "s.json"}}); + journal.job_started(script, "j1"); + journal.end(script, ToolResult::ok({{"status", "running"}, {"job", "j1"}, {"tool", "run_script"}})); + const uint64_t answer = journal.begin("dialog_respond", {{"button", "close"}}, true); + journal.job_started(answer, "j2"); + journal.job_ended(answer, ToolResult::ok()); + journal.end(answer, ToolResult::ok()); + const uint64_t waited = journal.begin("wait", {{"for", "job"}, {"job", "j1"}}); + journal.end(waited, ToolResult::ok()); + journal.job_ended(script, ToolResult::ok()); + + std::string err; + const std::optional<Script> parsed = parse_script(journal.to_script("t").dump(), err); + REQUIRE(parsed.has_value()); + // The replayed script opens its dialog 300 ms after its reply; an answer before that is refused. + std::atomic<bool> dialog{false}; + std::thread opener; + std::vector<std::string> calls; + ScriptHost host; + host.call = [&](const std::string& tool, const nlohmann::json& args) { + calls.push_back(tool); + if (tool == "run_script") { + opener = std::thread([&dialog] { + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + dialog = true; + }); + return ToolResult::ok({{"status", "running"}, {"job", "r1"}, {"tool", "run_script"}}); + } + if (tool == "wait" && args["for"] == "dialog") { + for (int i = 0; i < 100 && !dialog; ++i) + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + return ToolResult::ok({{"satisfied", dialog.load()}}); + } + if (tool == "dialog_respond") { + if (!dialog) + return ToolResult::error("No modal dialog is open"); + dialog = false; + return ToolResult::ok({{"pressed", "close"}}); + } + CHECK(args["job"] == "r1"); + return ToolResult::ok({{"done", true}}); + }; + host.wait_job = [](const std::string&, int) { return std::optional<ToolResult>(ToolResult::ok()); }; + ScriptContext sctx; + const nlohmann::json replay = run_script(*parsed, sctx, host); + opener.join(); + CHECK(replay["passed"] == true); + CHECK(calls == std::vector<std::string>{"run_script", "wait", "dialog_respond", "wait"}); +} + +TEST_CASE("an upload's row reaches 100 percent only once the host has answered", "[Mcp][PrintHost]") +{ + const std::string buffer; + auto percent = [&](size_t ulnow, size_t ultotal) { + return PrintHostJobQueue::sent_percent(Http::Progress(0, 0, ultotal, ulnow, buffer)); + }; + CHECK(percent(0, 0) == 0); + CHECK(percent(0, 4096) == 0); + CHECK(percent(2048, 4096) == 50); + CHECK(percent(4095, 4096) == 99); + // Every byte sent, the host's answer still to come: a 500 would turn the row into an error. + CHECK(percent(4096, 4096) == 99); +} + +TEST_CASE("the send command is a Slice & Export command that takes no param", "[Mcp][SpeedDial]") +{ + const NativeCommand* send = NativeCommands::find("send_gcode"); + REQUIRE(send != nullptr); + CHECK(send->title == "Send G-code to printer host"); + CHECK(send->group == "Slice & Export"); + CHECK(send->param.type == CommandParamType::None); + CHECK(send->completion == CommandCompletion::None); + CHECK(send->description.find("get_state.uploads") != std::string::npos); +} diff --git a/tests/slic3rutils/test_mcp_scene.cpp b/tests/slic3rutils/test_mcp_scene.cpp new file mode 100644 index 0000000000..1fde7e1e64 --- /dev/null +++ b/tests/slic3rutils/test_mcp_scene.cpp @@ -0,0 +1,980 @@ +// Scene tools: transform's size argument, the primitive size param, the notifications MCP +// operations raise before the 3D view has drawn, arrange's options, the admission that holds a +// UI worker job a call starts, how list_objects describes objects, instances and parts, +// add_part's type names and shape sizes, the params of the object structure commands, the height +// ranges set_layer_ranges takes and list_objects reports, and set_layer_gcode's edits of the layer slider. +// GLCanvas3D.hpp reaches wx's MSW headers after OCCT has hidden the USER and GDI declarations they need; +// the Windows headers first keep them, as in test_plugin_host_api.cpp. +#ifdef WIN32 + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #ifndef NOMINMAX + #define NOMINMAX + #endif + #include <Windows.h> + #include <CommCtrl.h> +#endif + +#include <catch2/catch_message.hpp> +#include <catch2/catch_test_macros.hpp> +#include <catch2/matchers/catch_matchers.hpp> +#include <catch2/matchers/catch_matchers_floating_point.hpp> +#include <catch2/matchers/catch_matchers_string.hpp> + +#include <imgui/imgui.h> +#include <nlohmann/json.hpp> + +#include "slic3r/GUI/GLCanvas3D.hpp" +#include "slic3r/GUI/GUI_ObjectList.hpp" +#include "slic3r/GUI/IMSlider.hpp" +#include "slic3r/GUI/ImGuiWrapper.hpp" +#include "slic3r/GUI/Mcp/JobRegistry.hpp" +#include "slic3r/GUI/Mcp/McpCore.hpp" +#include "slic3r/GUI/Mcp/McpJournal.hpp" +#include "slic3r/GUI/Mcp/McpTools.hpp" +#include "slic3r/GUI/Mcp/McpTypes.hpp" +#include "slic3r/GUI/Mcp/UiInvoker.hpp" +#include "slic3r/GUI/NativeCommands.hpp" +#include "slic3r/GUI/NotificationManager.hpp" + +#include "libslic3r/Config.hpp" +#include "libslic3r/CustomGCode.hpp" +#include "libslic3r/Model.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/Print.hpp" +#include "libslic3r/PrintConfig.hpp" +#include "libslic3r/Slicing.hpp" +#include "libslic3r/TriangleMesh.hpp" +#include "libslic3r/libslic3r.h" + +#include <algorithm> +#include <chrono> +#include <cmath> +#include <condition_variable> +#include <cstddef> +#include <deque> +#include <functional> +#include <initializer_list> +#include <iterator> +#include <memory> +#include <mutex> +#include <optional> +#include <string> +#include <thread> +#include <utility> +#include <vector> + +using namespace Slic3r; +using namespace Slic3r::GUI; +using nlohmann::json; +using namespace std::chrono_literals; +using Catch::Matchers::ContainsSubstring; +using Catch::Matchers::WithinAbs; + +TEST_CASE("size targets scale uniformly when one axis is given", "[Mcp][Scene]") +{ + const Vec3d current(60., 20., 5.); + CHECK(Mcp::size_factors(current, json::array({80, nullptr, nullptr})).isApprox(Vec3d::Constant(4. / 3.))); + CHECK(Mcp::size_factors(current, json::array({nullptr, nullptr, 10})).isApprox(Vec3d::Constant(2.))); + CHECK(Mcp::size_factors(current, json::array({80, 30, nullptr})).isApprox(Vec3d(4. / 3., 1.5, 1.))); + CHECK(Mcp::size_factors(current, json::array({30, 10, 5})).isApprox(Vec3d(0.5, 0.5, 1.))); + + CHECK_THROWS_AS(Mcp::size_factors(current, json::array({0, nullptr, nullptr})), Mcp::ToolFailure); + CHECK_THROWS_AS(Mcp::size_factors(current, json::array({-80, nullptr, nullptr})), Mcp::ToolFailure); + CHECK_THROWS_AS(Mcp::size_factors(current, json::array({80, 30})), Mcp::ToolFailure); + CHECK_THROWS_AS(Mcp::size_factors(current, json::array({nullptr, nullptr, nullptr})), Mcp::ToolFailure); + // A flat shape has no size to scale along its flat axis. + CHECK_THROWS_AS(Mcp::size_factors(Vec3d(50., 50., 0.), json::array({nullptr, nullptr, 2})), Mcp::ToolFailure); +} + +TEST_CASE("primitive size params parse numbers separated by spaces or commas", "[Mcp][Scene]") +{ + CHECK(NativeCommands::parse_sizes("90 4") == std::vector<double>{90., 4.}); + CHECK(NativeCommands::parse_sizes("90,4") == std::vector<double>{90., 4.}); + CHECK(NativeCommands::parse_sizes(" 40, 40 10.5 ") == std::vector<double>{40., 40., 10.5}); + CHECK(NativeCommands::parse_sizes("25.6") == std::vector<double>{25.6}); + + CHECK_FALSE(NativeCommands::parse_sizes("").has_value()); + CHECK_FALSE(NativeCommands::parse_sizes(" , ").has_value()); + CHECK_FALSE(NativeCommands::parse_sizes("90 x").has_value()); + CHECK_FALSE(NativeCommands::parse_sizes("90mm 4").has_value()); + CHECK_FALSE(NativeCommands::parse_sizes("90 0").has_value()); + CHECK_FALSE(NativeCommands::parse_sizes("90 -4").has_value()); +} + +// The app opens on Home, so a slice or arrange an agent starts at once updates its progress +// notification before any ImGui frame has built the font. That used to dereference a null font. +TEST_CASE("a progress notification updated before the first ImGui frame does not measure text", "[Mcp][Scene]") +{ + ImGuiWrapper imgui; // a context with no frame yet, so no current font + REQUIRE(ImGui::GetFont() == nullptr); + + NotificationManager notifications(nullptr); + notifications.init_progress_indicator(); + notifications.progress_indicator_set_status_text("Arranging"); + notifications.progress_indicator_set_status_text("Arranging done"); + CHECK(ImGui::GetFont() == nullptr); +} + +TEST_CASE("arrange options follow the Arrange options panel's rules", "[Mcp][Scene]") +{ + GLCanvas3D::ArrangeSettings settings; + settings.distance = 5.f; + settings.align_to_y_axis = true; + settings.allow_multi_materials_on_same_plate = false; + + // What is not given keeps its value. + CHECK(Mcp::apply_arrange_args(settings, {{"spacing", 10}}).empty()); + CHECK(settings.distance == 10.f); + CHECK(settings.align_to_y_axis); + CHECK_FALSE(settings.allow_multi_materials_on_same_plate); + Mcp::apply_arrange_args(settings, {{"spacing", -1}}); + CHECK(settings.distance == 0.f); + + // Rotation turns Align to Y axis off, and an align_y asked for meanwhile is reported, not applied. + CHECK(Mcp::apply_arrange_args(settings, {{"rotate", true}}).empty()); + CHECK_FALSE(settings.align_to_y_axis); + CHECK_FALSE(Mcp::apply_arrange_args(settings, {{"align_y", true}}).empty()); + CHECK_FALSE(settings.align_to_y_axis); + CHECK(Mcp::apply_arrange_args(settings, {{"rotate", false}, {"align_y", true}, {"multi_material", true}, {"spacing", 0.3}}).empty()); + CHECK(Mcp::arrange_settings_json(settings) == json{{"spacing", 0.3}, {"rotate", false}, {"align_y", true}, {"multi_material", true}}); +} + +namespace { + +// Plays the UI thread: runs posted closures in order on a thread of its own. +class UiThread final : public Mcp::UiDispatcher +{ +public: + UiThread() : m_thread([this] { loop(); }) {} + ~UiThread() override + { + { + std::lock_guard<std::mutex> lock(m_mutex); + m_stop = true; + } + m_cv.notify_all(); + m_thread.join(); + } + + void post(std::function<void()> fn) override + { + { + std::lock_guard<std::mutex> lock(m_mutex); + m_queue.push_back(std::move(fn)); + } + m_cv.notify_all(); + } + +private: + void loop() + { + for (;;) { + std::function<void()> fn; + { + std::unique_lock<std::mutex> lock(m_mutex); + m_cv.wait(lock, [this] { return m_stop || !m_queue.empty(); }); + if (m_queue.empty()) + return; + fn = std::move(m_queue.front()); + m_queue.pop_front(); + } + fn(); + } + } + + std::mutex m_mutex; + std::condition_variable m_cv; + std::deque<std::function<void()>> m_queue; + bool m_stop = false; + std::thread m_thread; +}; + +// The UI job worker: busy until its job's end, which a cancel brings forward to `cancel_delay` from +// then, as a job that notices the cancel between steps. +struct FakeWorker +{ + using Clock = std::chrono::steady_clock; + + std::mutex mutex; + Clock::time_point end; + std::chrono::milliseconds cancel_delay{0}; + int cancels = 0; + + void start(std::chrono::milliseconds length) + { + std::lock_guard<std::mutex> lock(mutex); + end = Clock::now() + length; + } + bool busy() + { + std::lock_guard<std::mutex> lock(mutex); + return Clock::now() < end; + } + void cancel() + { + std::lock_guard<std::mutex> lock(mutex); + ++cancels; + end = std::min(end, Clock::now() + cancel_delay); + } +}; + +// A core with stand-ins for the tools that start an arrange (the typed arrange, run_action +// obj_arrange, a click on a plate's Arrange icon, which queues its event), change the scene (a +// mutate tool, a key on the canvas), answer a dialog, read, and cancel. +struct Harness +{ + UiThread ui; + FakeWorker worker; + Mcp::UiInvoker invoker{ui, [] { return Mcp::GuardState{}; }}; + Mcp::JobRegistry jobs; + Mcp::Journal journal; + Mcp::ToolRegistry registry; + Mcp::CoreTiming timing; + std::chrono::milliseconds job_length{800}; + std::unique_ptr<Mcp::McpCore> core; + + Harness() + { + timing.soft_budget = 100ms; + add("arrange", Mcp::GuardClass::Mutate, [this](const json&, Mcp::ToolContext& ctx) { + ctx.run_ui([&] { + worker.start(job_length); + return json(); + }); + while (ctx.observe_ui([&] { return json(worker.busy()); }).get<bool>()) + std::this_thread::sleep_for(20ms); + return Mcp::ToolResult::ok({{"arranged", true}}); + }); + add("run_action", Mcp::GuardClass::Mutate, [this](const json&, Mcp::ToolContext& ctx) { + ctx.run_ui([&] { + worker.start(job_length); + return json(); + }); + return Mcp::ToolResult::ok({{"ran", "obj_arrange"}}); + }); + add("ui_click", Mcp::GuardClass::Recover, [this](const json&, Mcp::ToolContext& ctx) { + ctx.run_ui([&] { + core->admit({}); // the target is outside any dialog + ui.post([this] { worker.start(job_length); }); + return json(); + }); + ctx.observe_ui([] { return json(); }); // settle + return Mcp::ToolResult::ok(); + }); + add("ui_key", Mcp::GuardClass::Recover, [this](const json&, Mcp::ToolContext& ctx) { + return Mcp::ToolResult::ok(ctx.run_ui([&] { + core->admit({}); + return json("deleted"); + })); + }); + add("dialog_respond", Mcp::GuardClass::Recover, + [](const json&, Mcp::ToolContext& ctx) { return Mcp::ToolResult::ok(ctx.run_ui([] { return json("pressed"); })); }); + add("edit", Mcp::GuardClass::Mutate, + [](const json&, Mcp::ToolContext& ctx) { return Mcp::ToolResult::ok(ctx.run_ui([] { return json("edited"); })); }); + add("read", Mcp::GuardClass::Inspect, + [this](const json&, Mcp::ToolContext& ctx) { return Mcp::ToolResult::ok(ctx.run_ui([&] { return json(worker.busy()); })); }); + add("cancel", Mcp::GuardClass::Recover, [this](const json&, Mcp::ToolContext& ctx) { + return Mcp::ToolResult::ok(ctx.run_ui([&] { + for (const std::string& op : jobs.running_operations()) + if (core->cancel_worker(op)) + return json(op); + return json(); + })); + }); + } + ~Harness() + { + invoker.shutdown(); + jobs.wake_all(); + if (core) + core->shutdown(); + } + + void add(const std::string& name, Mcp::GuardClass guard, Mcp::ToolHandler handler) + { + Mcp::ToolDef d; + d.name = name; + d.guard = guard; + d.inline_call = guard == Mcp::GuardClass::Inspect; + d.allowed_during_operation = name == "cancel"; + d.budget_ms = 200; + d.handler = std::move(handler); + registry.add(std::move(d)); + } + void start() + { + core = std::make_unique<Mcp::McpCore>(registry, invoker, jobs, &journal, timing, + Mcp::WorkerHooks{[this] { return worker.busy(); }, [this] { worker.cancel(); }}); + } + Mcp::ToolResult call(const std::string& tool) { return core->call(*registry.find(tool), json::object()); } + + // Starts a worker job with `tool`, which outlives the reply budget; returns the call's job. + std::string start_job(const std::string& tool) + { + const Mcp::ToolResult started = call(tool); + REQUIRE_FALSE(started.is_error); + REQUIRE(started.data["status"] == "running"); + return started.data["job"]; + } + bool refused_by(const Mcp::ToolResult& r, const std::string& job) + { + return r.is_error && r.message.find("Busy: job " + job + " is running an operation") != std::string::npos; + } +}; + +} // namespace + +TEST_CASE("a worker job a call starts holds admission past the reply budget until the worker is idle", "[Mcp][Scene]") +{ + Harness h; + h.start(); + const std::string job = h.start_job("run_action"); + CHECK(h.refused_by(h.call("edit"), job)); + CHECK_FALSE(h.call("read").is_error); + + const auto done = h.jobs.wait(job, 5000ms); + REQUIRE(done.has_value()); + CHECK_FALSE(done->is_error); + CHECK(done->data["ran"] == "obj_arrange"); + // The job ends only once the worker is idle, so a change right after it is admitted. + CHECK_FALSE(h.worker.busy()); + CHECK_FALSE(h.call("edit").is_error); +} + +TEST_CASE("a cancelled worker job keeps admission until the worker is really idle", "[Mcp][Scene]") +{ + Harness h; + h.job_length = 10s; + h.worker.cancel_delay = 800ms; // slower than the reply budget + SECTION("cancel") + { + h.start(); + const std::string job = h.start_job("arrange"); + const Mcp::ToolResult cancel = h.call("cancel"); + REQUIRE_FALSE(cancel.is_error); + CHECK(cancel.data == job); + CHECK(h.refused_by(h.call("edit"), job)); + std::this_thread::sleep_for(300ms); + CHECK(h.worker.busy()); + CHECK(h.refused_by(h.call("edit"), job)); + + const auto done = h.jobs.wait(job, 5000ms); + REQUIRE(done.has_value()); + CHECK(done->is_error); + CHECK(done->message.find("cancelled") != std::string::npos); + } + SECTION("timeout") + { + h.timing.worker_timeout = 300ms; + h.start(); + const std::string job = h.start_job("run_action"); + std::this_thread::sleep_for(500ms); // past the timeout, before the cancelled job stops + CHECK(h.worker.cancels == 1); + CHECK(h.worker.busy()); + CHECK(h.refused_by(h.call("edit"), job)); + + const auto done = h.jobs.wait(job, 5000ms); + REQUIRE(done.has_value()); + CHECK(done->is_error); + CHECK(done->message.find("did not finish within") != std::string::npos); + } + CHECK(h.worker.cancels == 1); + CHECK_FALSE(h.worker.busy()); + CHECK_FALSE(h.call("edit").is_error); +} + +TEST_CASE("a change is refused while an arrange an MCP call started runs, however it started", "[Mcp][Scene]") +{ + // The typed arrange, run_action obj_arrange, and a recover input whose click queues the job. + for (const char* starter : {"arrange", "run_action", "ui_click"}) { + DYNAMIC_SECTION(starter) + { + Harness h; + h.start(); + const std::string job = h.start_job(starter); + CHECK(h.refused_by(h.call("edit"), job)); + const auto done = h.jobs.wait(job, 5000ms); + REQUIRE(done.has_value()); + CHECK_FALSE(done->is_error); + CHECK_FALSE(h.worker.busy()); + CHECK_FALSE(h.call("edit").is_error); + } + } +} + +TEST_CASE("a scene-changing input is refused while that job runs, and a dialog answer is not", "[Mcp][Scene]") +{ + Harness h; + h.start(); + const std::string job = h.start_job("run_action"); + CHECK(h.refused_by(h.call("ui_key"), job)); // Delete on the canvas + CHECK(h.refused_by(h.call("ui_click"), job)); // a GL toolbar item + CHECK_FALSE(h.call("dialog_respond").is_error); + REQUIRE(h.jobs.wait(job, 5000ms).has_value()); + CHECK_FALSE(h.call("ui_key").is_error); +} + +TEST_CASE("a worker job that starts between a call's closures is the call's, whoever started it", "[Mcp][Scene]") +{ + // The worker doesn't record who queued a job, so a person's job that starts while a call that + // found the worker idle is still running is claimed by that call, as one its change queued is. + Harness h; + h.add("settle", Mcp::GuardClass::Mutate, [](const json&, Mcp::ToolContext& ctx) { + ctx.run_ui([] { return json("edited"); }); + for (int i = 0; i < 10; ++i) { + ctx.observe_ui([] { return json(); }); + std::this_thread::sleep_for(20ms); + } + return Mcp::ToolResult::ok(); + }); + h.start(); + Mcp::ToolResult settled; + std::thread caller([&h, &settled] { settled = h.call("settle"); }); + std::this_thread::sleep_for(60ms); + h.ui.post([&h] { h.worker.start(h.job_length); }); // a person starts Text typing + caller.join(); + REQUIRE(settled.data["status"] == "running"); + const std::string job = settled.data["job"]; + CHECK(h.refused_by(h.call("edit"), job)); + REQUIRE(h.jobs.wait(job, 5000ms).has_value()); + CHECK_FALSE(h.worker.busy()); +} + +TEST_CASE("a worker job a person started refuses changes but not reads, and cancel leaves it", "[Mcp][Scene]") +{ + Harness h; + h.start(); + h.worker.start(800ms); // Text typing + for (const char* change : {"edit", "ui_key"}) { + const Mcp::ToolResult refused = h.call(change); + CHECK(refused.is_error); + CHECK(refused.message.find("Busy: a background job") != std::string::npos); + } + const Mcp::ToolResult read = h.call("read"); + CHECK_FALSE(read.is_error); + CHECK(read.data == true); + CHECK(h.call("cancel").data.is_null()); + CHECK(h.worker.cancels == 0); + while (h.worker.busy()) + std::this_thread::sleep_for(20ms); + CHECK_FALSE(h.call("edit").is_error); +} + +namespace { + +void check_vec3(const json& v, const Vec3d& expected) +{ + REQUIRE(v.is_array()); + for (int i = 0; i < 3; ++i) + CHECK_THAT(v[i].get<double>(), WithinAbs(expected[i], 1e-6)); +} + +} // namespace + +TEST_CASE("a part's position and bounding box are on the bed", "[Mcp][Scene]") +{ + Model model; + ModelObject* object = model.add_object(); + object->add_volume(make_cube(20., 20., 20.), ModelVolumeType::MODEL_PART, false); + ModelVolume* cylinder = object->add_volume(make_cylinder(3., 4.), ModelVolumeType::MODEL_PART, false); + cylinder->set_offset(Vec3d(5., 0., 0.)); + ModelVolume* modifier = object->add_volume(make_cube(5., 5., 5.), ModelVolumeType::PARAMETER_MODIFIER, false); + modifier->set_offset(Vec3d(50., 0., 0.)); + ModelInstance* inst = object->add_instance(); + inst->set_offset(Vec3d(100., 100., 10.)); + inst->set_rotation(Vec3d(0., 0., PI / 2.)); + + json info = Mcp::volume_info(*cylinder, 1); + check_vec3(info["position"], Vec3d(100., 105., 10.)); + check_vec3(info["bbox"]["min"], Vec3d(97., 102., 10.)); + check_vec3(info["bbox"]["max"], Vec3d(103., 108., 14.)); + // Rotation and scale are the part's own, in the object's frame. + check_vec3(info["rotation_deg"], Vec3d::Zero()); + check_vec3(info["scale"], Vec3d::Ones()); + CHECK_THAT(info["scaled_volume"].get<double>(), WithinAbs(info["mesh_volume"].get<double>(), 0.001)); + + // The instance's scale moves the part and grows its printed volume, not its mesh volume. + inst->set_scaling_factor(Vec3d::Constant(2.)); + info = Mcp::volume_info(*cylinder, 1); + check_vec3(info["position"], Vec3d(100., 110., 10.)); + CHECK_THAT(info["scaled_volume"].get<double>(), WithinAbs(8. * info["mesh_volume"].get<double>(), 0.01)); + + // Boxes of the object and its instances count model parts only: the modifier sticks out. + const json object_json = Mcp::object_info(*object, 0); + CHECK(object_json["instances"][0]["bbox"] == object_json["bbox"]); + CHECK(object_json["bbox"]["max"][1].get<double>() < 141.); + CHECK(object_json["volumes"][2]["bbox"]["max"][1].get<double>() > 200.); +} + +TEST_CASE("a mirrored copy reports mirrored", "[Mcp][Scene]") +{ + Model model; + ModelObject* object = model.add_object(); + ModelVolume* part = object->add_volume(make_cube(20., 10., 5.), ModelVolumeType::MODEL_PART, false); + object->add_volume(make_cube(5., 5., 5.), ModelVolumeType::MODEL_PART, false); + object->add_instance(); + object->add_instance()->set_mirror(Vec3d(-1., 1., 1.)); + // Mirrored in X and in Y is a half turn, not a mirror. + object->add_instance()->set_mirror(Vec3d(-1., -1., 1.)); + part->set_mirror(Vec3d(1., -1., 1.)); + + const json info = Mcp::object_info(*object, 0); + CHECK(info["instances"][0]["mirrored"] == false); + CHECK(info["instances"][1]["mirrored"] == true); + check_vec3(info["instances"][1]["scale"], Vec3d::Ones()); + CHECK(info["instances"][2]["mirrored"] == false); + CHECK(info["volumes"][0]["mirrored"] == true); + check_vec3(info["volumes"][0]["scale"], Vec3d::Ones()); + CHECK(info["volumes"][1]["mirrored"] == false); +} + +TEST_CASE("a part's filament falls back to its object's", "[Mcp][Scene]") +{ + Model model; + ModelObject* object = model.add_object(); + object->add_volume(make_cube(10., 10., 10.), ModelVolumeType::MODEL_PART, false); + object->add_volume(make_cube(10., 10., 10.), ModelVolumeType::MODEL_PART, false)->config.set("extruder", 0); + object->add_volume(make_cube(10., 10., 10.), ModelVolumeType::MODEL_PART, false)->config.set("extruder", 3); + object->add_volume(make_cube(5., 5., 5.), ModelVolumeType::PARAMETER_MODIFIER, false); + object->add_volume(make_cube(5., 5., 5.), ModelVolumeType::PARAMETER_MODIFIER, false)->config.set("extruder", 4); + object->add_volume(make_cube(5., 5., 5.), ModelVolumeType::NEGATIVE_VOLUME, false)->config.set("extruder", 2); + object->add_instance(); + + // Unset ("Default") is filament 1 on an object. + json info = Mcp::object_info(*object, 0); + CHECK(info["filament"] == 1); + CHECK(info["volumes"][0]["filament"] == 1); + + object->config.set("extruder", 2); + info = Mcp::object_info(*object, 0); + CHECK(info["filament"] == 2); + CHECK(info["volumes"][0]["filament"] == 2); + CHECK(info["volumes"][1]["filament"] == 2); + CHECK(info["volumes"][2]["filament"] == 3); + // A modifier without its own filament leaves the filament of what it covers alone. + CHECK_FALSE(info["volumes"][3].contains("filament")); + CHECK(info["volumes"][4]["filament"] == 4); + CHECK_FALSE(info["volumes"][5].contains("filament")); +} + +TEST_CASE("a precise seam reports its subtype, and an object its auto drop", "[Mcp][Scene]") +{ + Model model; + ModelObject* object = model.add_object(); + object->add_volume(make_cube(10., 10., 10.), ModelVolumeType::MODEL_PART, false); + object->add_volume(make_cube(2., 2., 2.), ModelVolumeType::PRECISE_SEAM_LEFT, false); + object->add_volume(make_cube(2., 2., 2.), ModelVolumeType::PRECISE_SEAM_NEUTRAL, false); + object->add_instance(); + object->auto_drop = false; + + const json info = Mcp::object_info(*object, 0); + CHECK(info["auto_drop"] == false); + CHECK_FALSE(info["volumes"][0].contains("subtype")); + CHECK(info["volumes"][1]["type"] == "precise_seam"); + CHECK(info["volumes"][1]["subtype"] == "left"); + CHECK(info["volumes"][2]["subtype"] == "neutral"); + CHECK_FALSE(info["volumes"][1].contains("filament")); +} + +TEST_CASE("part types round-trip between names and ModelVolumeType", "[Mcp][Scene]") +{ + for (const char* name : {"part", "negative", "modifier", "support_blocker", "support_enforcer", "precise_seam"}) + CHECK(std::string(Mcp::volume_type_name(Mcp::volume_type_from_name(name))) == name); + // The context menu's Add Precise Seam adds a Center seam; every subtype reads back as precise_seam. + CHECK(Mcp::volume_type_from_name("precise_seam") == ModelVolumeType::PRECISE_SEAM_CENTER); + for (const ModelVolumeType seam : {ModelVolumeType::PRECISE_SEAM_CENTER, ModelVolumeType::PRECISE_SEAM_LEFT, ModelVolumeType::PRECISE_SEAM_RIGHT, + ModelVolumeType::PRECISE_SEAM_ENFORCED, ModelVolumeType::PRECISE_SEAM_BLOCKED, + ModelVolumeType::PRECISE_SEAM_NEUTRAL}) + CHECK(std::string(Mcp::volume_type_name(seam)) == "precise_seam"); + CHECK(Mcp::volume_type_from_name("other") == ModelVolumeType::INVALID); + CHECK(Mcp::volume_type_from_name("Part") == ModelVolumeType::INVALID); +} + +TEST_CASE("a shape's size needs one positive number per field of the size dialog", "[Mcp][Scene]") +{ + CHECK(primitive_size_names("Cube").size() == 3); + CHECK(primitive_size_names("Cylinder").size() == 2); + CHECK(primitive_size_names("Cone").size() == 2); + CHECK(primitive_size_names("Disc").size() == 2); + CHECK(primitive_size_names("Sphere").size() == 1); + CHECK(std::string(primitive_size_names("Torus").front()) == "Inner diameter"); + CHECK(primitive_size_names("Slab").empty()); + + CHECK(Mcp::part_shape_size("cube", json::array({40, 30, 10})) == std::vector<double>{40., 30., 10.}); + CHECK(Mcp::part_shape_size("cylinder", json::array({6.2, 3.2})) == std::vector<double>{6.2, 3.2}); + CHECK(Mcp::part_shape_size("sphere", json::array({8})) == std::vector<double>{8.}); + CHECK(Mcp::part_shape_size("torus", json::array({20, 4})) == std::vector<double>{20., 4.}); + // No size: the built-in one. + CHECK(Mcp::part_shape_size("disc", json()).empty()); + + CHECK_THROWS_AS(Mcp::part_shape_size("cube", json::array({40, 30})), Mcp::ToolFailure); + CHECK_THROWS_AS(Mcp::part_shape_size("sphere", json::array({8, 8})), Mcp::ToolFailure); + CHECK_THROWS_AS(Mcp::part_shape_size("cylinder", json::array({0, 3})), Mcp::ToolFailure); + CHECK_THROWS_AS(Mcp::part_shape_size("cylinder", json::array({-6, 3})), Mcp::ToolFailure); + CHECK_THROWS_AS(Mcp::part_shape_size("cylinder", json::array({std::nan(""), 3})), Mcp::ToolFailure); + CHECK_THROWS_AS(Mcp::part_shape_size("cylinder", json::array({"6", 3})), Mcp::ToolFailure); + CHECK_THROWS_AS(Mcp::part_shape_size("cylinder", json(6)), Mcp::ToolFailure); + CHECK_THROWS_AS(Mcp::part_shape_size("slab", json()), Mcp::ToolFailure); + // The message names the fields, as the dialog does. + try { + Mcp::part_shape_size("torus", json::array({20})); + FAIL("a torus with one size was accepted"); + } catch (const Mcp::ToolFailure& e) { + CHECK(std::string(e.what()) == "A torus's size is [Inner diameter, Tube diameter] in mm, each above 0"); + } +} + +TEST_CASE("an instance count param is a whole number", "[Mcp][Scene]") +{ + CHECK(NativeCommands::parse_count("6") == 6); + CHECK(NativeCommands::parse_count(" 12 ") == 12); + CHECK(NativeCommands::parse_count("0") == 0); + CHECK(NativeCommands::parse_count("1000") == 1000); + + CHECK_FALSE(NativeCommands::parse_count("").has_value()); + CHECK_FALSE(NativeCommands::parse_count("-1").has_value()); + CHECK_FALSE(NativeCommands::parse_count("6.5").has_value()); + CHECK_FALSE(NativeCommands::parse_count("6 7").has_value()); + CHECK_FALSE(NativeCommands::parse_count("1e3").has_value()); + CHECK_FALSE(NativeCommands::parse_count("six").has_value()); + CHECK_FALSE(NativeCommands::parse_count("99999999999").has_value()); +} + +// The object list's context-menu commands are Speed Dial commands beside the other object commands, +// and a param stands in for each one's dialog. +TEST_CASE("the object structure commands take the params that replace their dialogs", "[Mcp][Scene]") +{ + const NativeCommand* peer = NativeCommands::find("obj_delete"); + REQUIRE(peer != nullptr); + struct Expected + { + const char* key; + CommandParamType param; + }; + for (const Expected& e : {Expected{"obj_type_part", CommandParamType::None}, Expected{"obj_type_negative", CommandParamType::None}, + Expected{"obj_type_modifier", CommandParamType::None}, + Expected{"obj_type_support_blocker", CommandParamType::None}, + Expected{"obj_type_support_enforcer", CommandParamType::None}, + Expected{"obj_type_precise_seam", CommandParamType::None}, Expected{"obj_rename", CommandParamType::Text}, + Expected{"obj_set_instances", CommandParamType::Index}, Expected{"obj_assemble", CommandParamType::None}, + Expected{"obj_instances_to_objects", CommandParamType::None}, + Expected{"obj_order_by_name", CommandParamType::Text}, Expected{"obj_order_by_filament", CommandParamType::Text}, + Expected{"obj_order_by_height", CommandParamType::Text}, Expected{"obj_order_by_size", CommandParamType::Text}}) { + INFO(e.key); + const NativeCommand* c = NativeCommands::find(e.key); + REQUIRE(c != nullptr); + CHECK(c->group == peer->group); + CHECK(c->param.type == e.param); + CHECK_FALSE(c->description.empty()); + CHECK(c->param.help.empty() == (e.param == CommandParamType::None)); + } +} + +namespace { + +// What the object list gives a new range: the object's layer height and its filament ("Default"). +DynamicPrintConfig new_range_config() +{ + DynamicPrintConfig config; + config.set_key_value("layer_height", new ConfigOptionFloat(0.2)); + config.set_key_value("extruder", new ConfigOptionInt(0)); + return config; +} + +// set_layer_ranges' parse on a two-filament printer whose layer heights are 0.08-0.28. +t_layer_config_ranges parse_ranges(const json& ranges) +{ + return Mcp::layer_config_ranges_from_json(ranges, new_range_config(), 2, [](int) { return std::make_pair(0.08, 0.28); }); +} + +json range(double min_z, double max_z, json values = json::object()) +{ + return {{"min_z", min_z}, {"max_z", max_z}, {"values", std::move(values)}}; +} + +} // namespace + +TEST_CASE("height ranges are checked before the object changes", "[Mcp][Scene][Layers]") +{ + // Sorted by height; touching ranges are fine; each starts from the new-range config. + const t_layer_config_ranges ranges = parse_ranges( + json::array({range(10, 20, {{"sparse_infill_density", "25%"}}), range(0, 10, {{"layer_height", 0.12}, {"extruder", "2"}})})); + REQUIRE(ranges.size() == 2); + const auto& [low, low_config] = *ranges.begin(); + const auto& [high, high_config] = *std::next(ranges.begin()); + CHECK(low == t_layer_height_range(0., 10.)); + CHECK(high == t_layer_height_range(10., 20.)); + CHECK_THAT(low_config.opt_float("layer_height"), WithinAbs(0.12, 1e-9)); + CHECK(low_config.opt_int("extruder") == 2); + CHECK_THAT(high_config.opt_float("layer_height"), WithinAbs(0.2, 1e-9)); + CHECK(high_config.opt_int("extruder") == 0); + CHECK(high_config.opt_serialize("sparse_infill_density") == "25%"); + CHECK(parse_ranges(json::array()).empty()); + + // An overlap names both ranges, whatever order they come in. + CHECK_THROWS_WITH(parse_ranges(json::array({range(12, 20), range(0, 15)})), ContainsSubstring("0-15 and 12-20 overlap")); + CHECK_THROWS_WITH(parse_ranges(json::array({range(0, 15), range(0, 15)})), ContainsSubstring("overlap")); + CHECK_THROWS_WITH(parse_ranges(json::array({range(0, 20), range(5, 10)})), ContainsSubstring("0-20 and 5-10 overlap")); + // Empty, reversed, below the bed or without a top. + CHECK_THROWS_WITH(parse_ranges(json::array({range(5, 5)})), ContainsSubstring("0 <= min_z < max_z")); + CHECK_THROWS_AS(parse_ranges(json::array({range(6, 5)})), Mcp::ToolFailure); + CHECK_THROWS_AS(parse_ranges(json::array({range(-1, 5)})), Mcp::ToolFailure); + CHECK_THROWS_AS(parse_ranges(json::array({json{{"min_z", 0}}})), Mcp::ToolFailure); + + // A layer height given is checked against the printer's, with the range's filament. + int asked = -1; + const auto bounds = [&asked](int extruder) { + asked = extruder; + return std::make_pair(0.08, 0.28); + }; + CHECK_THROWS_WITH(Mcp::layer_config_ranges_from_json(json::array({range(0, 5, {{"layer_height", 0.4}, {"extruder", 2}})}), + new_range_config(), 2, bounds), + ContainsSubstring("layer_height 0.4 is outside this printer's 0.08-0.28")); + CHECK(asked == 2); + // The object's layer height a range starts from is not checked, as the range editor checks only what is typed. + DynamicPrintConfig thick = new_range_config(); + thick.set_key_value("layer_height", new ConfigOptionFloat(0.4)); + CHECK(Mcp::layer_config_ranges_from_json(json::array({range(0, 5)}), thick, 2, bounds).size() == 1); + + // Filaments are 0 (the object's) up to the slot count. + CHECK_THROWS_WITH(parse_ranges(json::array({range(0, 5, {{"extruder", 3}})})), ContainsSubstring("1-2")); + CHECK_THROWS_AS(parse_ranges(json::array({range(0, 5, {{"extruder", -1}})})), Mcp::ToolFailure); + // Values are parsed strictly. + CHECK_THROWS_WITH(parse_ranges(json::array({range(0, 5, {{"sparse_infill_density", "lots"}})})), + ContainsSubstring("Invalid value for sparse_infill_density")); + CHECK_THROWS_AS(parse_ranges(json::array({range(0, 5, {{"wall_loops", nullptr}})})), Mcp::ToolFailure); +} + +TEST_CASE("range settings take the keys the range settings page offers", "[Mcp][Scene][Layers]") +{ + const auto has = [](const std::vector<std::string>& keys, const char* key) { return std::find(keys.begin(), keys.end(), key) != keys.end(); }; + const std::vector<std::string> two = Mcp::layer_range_option_keys(2); + for (const char* key : {"layer_height", "extruder", "sparse_infill_density", "wall_loops", "sparse_infill_filament_id"}) + CHECK(has(two, key)); + // Object-only settings, filament settings and internal options are not a range's. + for (const char* key : {"enable_support", "brim_type", "nozzle_temperature", "print_extruder_id"}) + CHECK_FALSE(has(two, key)); + // With one filament the object list offers no per-feature filament. + CHECK_FALSE(has(Mcp::layer_range_option_keys(1), "sparse_infill_filament_id")); + + try { + parse_ranges(json::array({range(0, 5, {{"enable_support", true}})})); + FAIL("an object setting was accepted for a range"); + } catch (const Mcp::ToolFailure& e) { + CHECK_THAT(e.what(), ContainsSubstring("not a height range setting")); + } + try { + parse_ranges(json::array({range(0, 5, {{"sparse_infill_dens", "20%"}})})); + FAIL("an unknown key was accepted"); + } catch (const Mcp::ToolFailure& e) { + REQUIRE(e.details.contains("similar")); + CHECK(std::find(e.details["similar"].begin(), e.details["similar"].end(), json("sparse_infill_density")) != e.details["similar"].end()); + } +} + +TEST_CASE("list_objects reports an object's height ranges", "[Mcp][Scene][Layers]") +{ + Model model; + ModelObject* object = model.add_object(); + object->add_volume(make_cube(20., 20., 30.), ModelVolumeType::MODEL_PART, false); + object->add_instance(); + CHECK_FALSE(Mcp::object_info(*object, 0).contains("layer_config_ranges")); + + object->layer_config_ranges = parse_ranges(json::array({range(15, 30, {{"sparse_infill_density", "40%"}}), range(0, 15, {{"layer_height", 0.12}})})); + const json info = Mcp::object_info(*object, 0); + REQUIRE(info["layer_config_ranges"].size() == 2); + const json& low = info["layer_config_ranges"][0]; + CHECK(low["min_z"] == 0.); + CHECK(low["max_z"] == 15.); + CHECK(low["values"] == json{{"extruder", "0"}, {"layer_height", "0.12"}}); + CHECK(info["layer_config_ranges"][1]["values"]["sparse_infill_density"] == "40%"); + // Ranges are not the object's own overrides. + CHECK(info["overrides"].empty()); + + // What list_objects shows can be given back unchanged. + const t_layer_config_ranges again = parse_ranges(info["layer_config_ranges"]); + REQUIRE(again.size() == object->layer_config_ranges.size()); + for (auto a = again.cbegin(), b = object->layer_config_ranges.cbegin(); a != again.cend(); ++a, ++b) { + CHECK(a->first == b->first); + CHECK(a->second.get() == b->second.get()); + } +} + +TEST_CASE("list_objects reports a variable layer height profile as the object list does", "[Mcp][Scene][Layers]") +{ + // [z0, h0, z1, h1, ...]: the object list marks no flat bottom-to-top pair as variable. Heights are + // rounded to 0.001 mm. + CHECK(Mcp::layer_height_profile_json({}).is_null()); + CHECK(Mcp::layer_height_profile_json({0., 0.2, 30., 0.2}).is_null()); + CHECK(Mcp::layer_height_profile_json({0., 0.2, 10., 0.1, 30., 0.2804}) == json{{"points", 3}, {"min_height", 0.1}, {"max_height", 0.28}}); + + Model model; + ModelObject* object = model.add_object(); + object->add_volume(make_sphere(10.), ModelVolumeType::MODEL_PART, false); + object->add_instance(); + object->ensure_on_bed(); + CHECK_FALSE(Mcp::object_info(*object, 0).contains("layer_height_profile")); + + const DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + const SlicingParameters params = PrintObject::slicing_parameters(config, *object, float(object->max_z()), Vec3d::Ones()); + const auto within = [¶ms](const json& profile) { + CHECK(profile["min_height"].get<double>() >= params.min_layer_height - 1e-3); + CHECK(profile["max_height"].get<double>() <= params.max_layer_height + 1e-3); + }; + + // What Adaptive stores on a sphere: thin layers near its poles, thick ones at its equator. + object->layer_height_profile.set(layer_height_profile_adaptive(params, *object, 0.5f)); + json profile = Mcp::object_info(*object, 0)["layer_height_profile"]; + CHECK(profile["points"].get<std::size_t>() == object->layer_height_profile.get().size() / 2); + CHECK(profile["min_height"].get<double>() < profile["max_height"].get<double>()); + within(profile); + + // What Smooth stores on an object without a profile: the profile its height ranges give, smoothed, + // so the ranges' heights bound it. + object->layer_height_profile.clear(); + object->layer_config_ranges = parse_ranges(json::array({range(0, 10, {{"layer_height", 0.1}}), range(10, 20, {{"layer_height", 0.25}})})); + std::vector<double> from_ranges; + PrintObject::update_layer_height_profile(*object, params, from_ranges); + object->layer_height_profile.set(smooth_height_profile(from_ranges, params, HeightProfileSmoothingParams())); + profile = Mcp::object_info(*object, 0)["layer_height_profile"]; + REQUIRE(profile.is_object()); + CHECK(profile["min_height"].get<double>() >= 0.1 - 1e-3); + CHECK(profile["max_height"].get<double>() <= 0.25 + 1e-3); + CHECK(profile["min_height"].get<double>() < profile["max_height"].get<double>()); + within(profile); +} + +TEST_CASE("layer code types have the names list_plates reads", "[Mcp][Scene][Layers]") +{ + for (const auto& [name, type] : std::vector<std::pair<std::string, CustomGCode::Type>>{{"pause", CustomGCode::PausePrint}, + {"custom", CustomGCode::Custom}, + {"template", CustomGCode::Template}, + {"change_filament", CustomGCode::ToolChange}}) { + CHECK(Mcp::custom_gcode_type_name(type) == name); + CHECK(Mcp::custom_gcode_type_from_name(name) == type); + } + // An old project's colour change is listed, but the slider adds none. + CHECK(std::string(Mcp::custom_gcode_type_name(CustomGCode::ColorChange)) == "color_change"); + CHECK(Mcp::custom_gcode_type_from_name("color_change") == CustomGCode::Unknown); + CHECK(Mcp::custom_gcode_type_from_name("Pause") == CustomGCode::Unknown); +} + +TEST_CASE("layer G-codes are edited on the layer slider as its menus edit them", "[Mcp][Scene][Layers]") +{ + // Ten 0.2 mm layers and two filaments, as the Preview loads a plate whose objects print with filament 1. + IMSlider slider(0, 9, 0, 9); + slider.SetSliderValues({0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0}); + slider.SetExtruderColors({"#FFFFFF", "#000000"}); + slider.SetManipulationMode(CustomGCode::MultiAsSingle); + // The plater's handler: the plate takes the slider's codes. + Model model; + const auto hand_over = [&] { + CHECK(slider.is_need_post_tick_event()); + // The handler invalidates the plate's slice on these types only. + const CustomGCode::Type type = slider.get_post_tick_event_type(); + CHECK((type == CustomGCode::PausePrint || type == CustomGCode::Custom || type == CustomGCode::Template || type == CustomGCode::ToolChange)); + slider.reset_post_tick_event(); + model.plates_custom_gcodes[0] = slider.GetTicksValues(); + return model.plates_custom_gcodes[0].gcodes; + }; + const auto edit = [&](const json& args, int filaments = 2, bool has_template = false, const std::string& no_change = {}) { + return Mcp::edit_layer_gcode(slider, args, filaments, has_template, no_change); + }; + const auto refused = [&](const json& args, const std::string& message, int filaments = 2, const std::string& no_change = {}) { + const CustomGCode::Info before = slider.GetTicksValues(); + CHECK_THROWS_WITH(edit(args, filaments, false, no_change), ContainsSubstring(message)); + CHECK(slider.GetTicksValues() == before); + CHECK_FALSE(slider.is_need_post_tick_event()); + }; + + // A pause by layer number and custom G-code by a height between layers, which is on the layer whose top + // is above it. + REQUIRE(edit({{"add", {{{"layer", 3}, {"type", "pause"}}, {{"z", 0.9}, {"type", "custom"}, {"gcode", "M104 S215"}}}}})); + std::vector<CustomGCode::Item> codes = hand_over(); + REQUIRE(codes.size() == 2); + CHECK_THAT(codes[0].print_z, WithinAbs(0.6, 1e-9)); + CHECK(codes[0].type == CustomGCode::PausePrint); + CHECK_THAT(codes[1].print_z, WithinAbs(1.0, 1e-9)); + CHECK(codes[1].type == CustomGCode::Custom); + CHECK(codes[1].extra == "M104 S215"); + + // The same codes again change nothing and hand nothing over. + CHECK_FALSE(edit({{"add", {{{"z", 0.6}, {"type", "pause"}}, {{"layer", 5}, {"type", "custom"}, {"gcode", "M104 S215"}}}}})); + CHECK_FALSE(slider.is_need_post_tick_event()); + + // A filament change carries the filament's colour; another filament on that layer switches it, as + // Change Filament on the tick does; new custom text replaces the old, as Edit Custom G-code does. + REQUIRE(edit({{"add", {{{"layer", 7}, {"type", "change_filament"}, {"filament", 2}}}}})); + codes = hand_over(); + REQUIRE(codes.size() == 3); + CHECK(codes[2].type == CustomGCode::ToolChange); + CHECK(codes[2].extruder == 2); + CHECK(codes[2].color == "#000000"); + REQUIRE(edit({{"add", {{{"layer", 7}, {"type", "change_filament"}, {"filament", 1}}, {{"layer", 5}, {"type", "custom"}, {"gcode", "M106 S0"}}}}})); + codes = hand_over(); + REQUIRE(codes.size() == 3); + CHECK(codes[1].extra == "M106 S0"); + CHECK(codes[2].extruder == 1); + CHECK(codes[2].color == "#FFFFFF"); + + // The slider's own add turns any code on its layer into a filament change, so a code of another type + // is refused before the slider is touched, unless the call removes it first. + refused({{"add", {{{"layer", 3}, {"type", "change_filament"}, {"filament", 2}}}}}, "layer 3 has a pause code; remove it first (remove: [{layer: 3}])"); + refused({{"add", {{{"layer", 7}, {"type", "pause"}}}}}, "layer 7 has a change_filament code"); + REQUIRE(edit({{"remove", {{{"layer", 3}}}}, {"add", {{{"layer", 3}, {"type", "custom"}, {"gcode", "M117 Magnets"}}}}})); + codes = hand_over(); + REQUIRE(codes.size() == 3); + CHECK(codes[0].type == CustomGCode::Custom); + CHECK(codes[0].extra == "M117 Magnets"); + + // Every check passes before anything changes. + refused({{"remove", {{{"layer", 9}}}}}, "No code on layer 9 (codes on layers 3, 5, 7)"); + refused({{"remove", {{{"layer", 3}}}}, {"add", {{{"layer", 4}, {"type", "pause"}}, {{"layer", 11}, {"type", "pause"}}}}}, "layer must be 1..10 (z 0.2..2)"); + refused({{"add", {{{"z", 2.1}, {"type", "pause"}}}}}, "z 2.1 is above the top layer (2 mm)"); + refused({{"add", {{{"layer", 4}, {"z", 0.8}, {"type", "pause"}}}}}, "Give layer or z for each code"); + refused({{"add", {{{"type", "pause"}}}}}, "Give layer or z for each code"); + refused({{"add", {{{"layer", 4}, {"type", "pause"}}, {{"z", 0.75}, {"type", "pause"}}}}}, "Two codes for layer 4"); + refused({{"add", {{{"layer", 4}, {"type", "pause"}, {"filament", 2}}}}}, "filament goes with type change_filament"); + refused({{"add", {{{"layer", 4}, {"type", "change_filament"}}}}}, "change_filament needs filament"); + refused({{"add", {{{"layer", 4}, {"type", "custom"}}}}}, "custom needs gcode"); + refused({{"add", {{{"layer", 4}, {"type", "custom"}, {"gcode", std::string(1024, 'G')}}}}}, "1 to 1023 bytes"); + refused({{"add", {{{"layer", 4}, {"type", "template"}}}}}, "template_custom_gcode is empty"); + refused({{"add", {{{"layer", 4}, {"type", "color_change"}}}}}, "type must be pause, custom, template or change_filament"); + refused({{"add", {{{"layer", 4}, {"type", "change_filament"}, {"filament", 3}}}}}, "filament must be 1..2"); + refused({{"add", {{{"layer", 4}, {"type", "change_filament"}, {"filament", 2}}}}}, "The filaments changed since the plate was sliced", 3); + refused({{"add", {{{"layer", 4}, {"type", "change_filament"}, {"filament", 2}}}}}, "The plate takes no filament change: spiral vase", 2, + "spiral vase (spiral_mode) is on"); + CHECK(edit({{"add", {{{"layer", 4}, {"type", "template"}}}}}, 2, true)); + codes = hand_over(); + REQUIRE(codes.size() == 4); + CHECK(codes[1].type == CustomGCode::Template); + + // Clear removes every code, then the call's adds go on the empty plate. + REQUIRE(edit({{"clear", true}, {"add", {{{"layer", 10}, {"type", "pause"}}}}})); + codes = hand_over(); + REQUIRE(codes.size() == 1); + CHECK_THAT(codes[0].print_z, WithinAbs(2.0, 1e-9)); + REQUIRE(edit({{"clear", true}})); + CHECK(hand_over().empty()); + CHECK_FALSE(edit({{"clear", true}})); + + // On one filament the menus offer no filament change. + slider.SetExtruderColors({"#FFFFFF"}); + refused({{"add", {{{"layer", 4}, {"type", "change_filament"}, {"filament", 1}}}}}, "change_filament needs two or more filaments", 1); + + // Why the occupant is checked: the slider's add switches a pause to a filament change. And without a + // layer the menus' edits act on the active thumb. + slider.SetExtruderColors({"#FFFFFF", "#000000"}); + REQUIRE(edit({{"add", {{{"layer", 2}, {"type", "pause"}}}}})); + hand_over(); + CHECK(slider.add_code_as_tick(CustomGCode::ToolChange, 2, 1)); + CHECK(hand_over()[0].type == CustomGCode::ToolChange); + CHECK_FALSE(slider.add_code_as_tick(CustomGCode::PausePrint, -1, 1)); + slider.SetHigherValue(6); + CHECK(slider.add_code_as_tick(CustomGCode::PausePrint)); + codes = hand_over(); + REQUIRE(codes.size() == 2); + CHECK_THAT(codes[1].print_z, WithinAbs(1.4, 1e-9)); +} diff --git a/tests/slic3rutils/test_mcp_tools.cpp b/tests/slic3rutils/test_mcp_tools.cpp index 7e117b4e96..46a570b2d0 100644 --- a/tests/slic3rutils/test_mcp_tools.cpp +++ b/tests/slic3rutils/test_mcp_tools.cpp @@ -1,3 +1,16 @@ +// McpTools.hpp reaches wx's MSW headers through GLCanvas3D.hpp after OCCT has hidden the USER and GDI +// declarations they need; the Windows headers first keep them, as in test_plugin_host_api.cpp. +#ifdef WIN32 + #ifndef WIN32_LEAN_AND_MEAN + #define WIN32_LEAN_AND_MEAN + #endif + #ifndef NOMINMAX + #define NOMINMAX + #endif + #include <Windows.h> + #include <CommCtrl.h> +#endif + #include <catch2/catch_test_macros.hpp> #include "slic3r/GUI/Mcp/McpTools.hpp" diff --git a/tests/slic3rutils/test_mcp_ui.cpp b/tests/slic3rutils/test_mcp_ui.cpp index 6eda74e7c3..8269792c4c 100644 --- a/tests/slic3rutils/test_mcp_ui.cpp +++ b/tests/slic3rutils/test_mcp_ui.cpp @@ -26,13 +26,23 @@ #include "slic3r/GUI/ImGuiWrapper.hpp" #include "slic3r/GUI/MeshUtils.hpp" #include "slic3r/GUI/Mcp/CanvasTarget.hpp" +#include "slic3r/GUI/Mcp/McpService.hpp" +#include "slic3r/GUI/Mcp/McpServicePtr.hpp" #include "slic3r/GUI/Mcp/UiInspector.hpp" #include "slic3r/GUI/Mcp/UiRefs.hpp" #include <nlohmann/json.hpp> +#include <wx/app.h> +#include <wx/event.h> +#include <wx/frame.h> +#include <wx/init.h> +#include <wx/panel.h> +#include <wx/window.h> + #include <cmath> #include <cstddef> +#include <cstdlib> #include <optional> #include <set> #include <string> @@ -380,8 +390,8 @@ TEST_CASE("the surface check passes a visible point and names what hides another CHECK(check_surface(Vec3d(0., 0., -40.), ray_to(Vec3d(0., 0., -40.)), covered, nullptr, {}, 0.1) == "another part or object is in front of the point"); - // The bed: in front of a part looked at from below it, and the floor under a part sunk into it. - // Slic3r:: because windows.h declares a global Polygon() as well. + // The bed: the floor under a part sunk into it, but see-through from below, as the GUI draws it and + // paints through it there. Slic3r:: because windows.h declares a global Polygon() as well. const Slic3r::Polygon bed = Slic3r::Polygon::new_scale({Vec2d(-50., -50.), Vec2d(50., -50.), Vec2d(50., 50.), Vec2d(-50., 50.)}); const std::vector<SurfaceMesh> raised{{&cube, cube_at(-1.).pretranslate(Vec3d(0., 0., 20.)), true, false}}; const CanvasView below = [&] { @@ -390,7 +400,13 @@ TEST_CASE("the surface check passes a visible point and names what hides another return v; }(); const auto from_below = [&](const Vec3d& p) { return pixel_ray(below, *project_point(below, p)); }; - CHECK(check_surface(Vec3d(0., 0., 9.), from_below(Vec3d(0., 0., 9.)), raised, nullptr, {bed}, 0.1) == "the bed is in front of the point"); + CHECK(check_surface(Vec3d(0., 0., 9.), from_below(Vec3d(0., 0., 9.)), raised, nullptr, {bed}, 0.1).empty()); + // A click beside the part, at x = 6 (pixel 112), lands on the bed looking down and on nothing + // looking up. + CHECK(check_surface(Vec3d(4.9, 0., 19.), pixel_ray(view, Vec2d(112., 100.)), raised, nullptr, {bed}, 0.1) == + "the click at the point's pixel lands on the bed beside the part"); + CHECK(check_surface(Vec3d(4.9, 0., 9.), pixel_ray(below, Vec2d(112., 100.)), raised, nullptr, {bed}, 0.1) == + "the click at the point's pixel misses the part"); const std::vector<SurfaceMesh> sunk{{&cube, cube_at(-1.), true, false}}; // its top 1 mm under the bed CHECK(check_surface(Vec3d(0., 0., -1.), ray_to(Vec3d(0., 0., -1.)), sunk, nullptr, {bed}, 0.1) == "the point is below the bed"); // Plates are separate outlines: the gap between two is no bed. @@ -499,3 +515,56 @@ TEST_CASE("the surface check judges the ray through the whole pixel a click goes CHECK(check_surface(Vec3d(-0.3, 0., -40.), pixel_ray(view, Vec2d(100., 100.)), a_alone, nullptr, {}, 0.1) == "the click at the point's pixel misses the part"); } + +TEST_CASE("a key goes to the hooks of the target and its parents before the target, as a real key press does", "[Mcp]") +{ +#if defined(__linux__) + if (!std::getenv("DISPLAY") && !std::getenv("WAYLAND_DISPLAY")) + SKIP("This test needs a display (for example, xvfb-run)."); +#endif + if (wxTheApp == nullptr) + wxApp::SetInstance(new wxApp); + wxInitializer init; + REQUIRE(init.IsOk()); + { + McpServicePtr service(new McpService()); + UiInspector inspector(*service); + + // A panel whose hook takes Escape, as the Design tab's does, in a frame with a hook of its own. + wxFrame frame(nullptr, wxID_ANY, "keys"); + auto* panel = new wxPanel(&frame); + auto* field = new wxWindow(panel, wxID_ANY); + std::vector<std::string> seen; + bool allow_next = false; + panel->Bind(wxEVT_CHAR_HOOK, [&](wxKeyEvent& e) { + seen.push_back("panel hook"); + if (e.GetKeyCode() != WXK_ESCAPE) + e.Skip(); + else if (allow_next) + e.DoAllowNextEvent(); + }); + frame.Bind(wxEVT_CHAR_HOOK, [&](wxKeyEvent& e) { + seen.push_back("frame hook"); + e.Skip(); + }); + field->Bind(wxEVT_KEY_DOWN, [&](wxKeyEvent& e) { + seen.push_back("key down"); + e.Skip(); + }); + UiTarget target; + target.window = field; + + // The panel's hook takes the key, so neither the frame nor the target sees it. + inspector.key(&target, "Escape", ""); + CHECK(seen == std::vector<std::string>{"panel hook"}); + // A key no hook takes goes up to the frame's hook, then down to the target. + seen.clear(); + inspector.key(&target, "F5", ""); + CHECK(seen == std::vector<std::string>{"panel hook", "frame hook", "key down"}); + // A hook that allows the next event lets the target have the key too. + seen.clear(); + allow_next = true; + inspector.key(&target, "Escape", ""); + CHECK(seen == std::vector<std::string>{"panel hook", "key down"}); + } +} diff --git a/tools/mcp/README.md b/tools/mcp/README.md index a38b402ecc..44006313f7 100644 --- a/tools/mcp/README.md +++ b/tools/mcp/README.md @@ -8,7 +8,7 @@ Python. It uses only the standard library. `docs/HLSD/mcp-server.md` covers the | Command | What it does | |---|---| -| `launch [--xvfb] [--printer "<model>@<nozzle>"] [--vendor V] [--filament F] [--datadir DIR] [--port N] [--bin PATH] [--print-config] [-- app args]` | Start OrcaSlicer with `--mcp`, wait until it is ready, print the session | +| `launch [--xvfb] [--cad] [--printer "<model>@<nozzle>"] [--vendor V] [--filament F] [--datadir DIR] [--port N] [--bin PATH] [--print-config] [-- app args]` | Start OrcaSlicer with `--mcp`, wait until it is ready, print the session | | `call TOOL ['<json args>'] [--wait]` | Call a tool and print its JSON result; `--wait` follows a returned job to its result | | `tools` | List the tools, with the first line of each description | | `snapshot ['<json args>']` | Print the `ui_snapshot` tree | @@ -18,7 +18,9 @@ Python. It uses only the standard library. `docs/HLSD/mcp-server.md` covers the `launch` creates a fresh temporary datadir unless you pass `--datadir`. It seeds the datadir with an `OrcaSlicer.conf` that has a finished setup wizard and one printer and filament (Bambu Lab X1 -Carbon 0.4 by default), with update checks and daily tips turned off. The token comes from +Carbon 0.4 by default), with update checks and daily tips turned off. `--cad` turns the Design +(CAD) tab on, which `cad_call` needs: it sets `enable_cad_feature` in a fresh datadir's +`OrcaSlicer.conf`, and in a reused one too, since the app reads that setting only at startup. The token comes from `ORCA_MCP_TOKEN` or is generated, and it reaches the app through the environment, not the command line. On Linux, `launch` also sets `SSL_CERT_FILE`, so a fresh datadir doesn't prompt for a CA bundle. On Windows, it gives the instance its own WebView2 profile in the datadir, apart from the one @@ -92,6 +94,160 @@ Run it at a second window size through `run_script`'s `vars`: tools/mcp/orca_mcp.py call run_script '{"path": "/abs/tools/mcp/tests/gizmos.json", "out_dir": "/tmp/gizmos-small", "vars": {"window_size": [1100, 760]}}' --wait ``` +`tests/scene.json` checks object structure and placement: `transform` on an instance (the drop after a +scale, `size`, a move to another plate), on a part, what `list_objects` reports of them (bounding boxes +on the bed, filament, the scaled volume, a mirrored part and instance), the shape commands with a size +param, `arrange` on one plate and every plate, Fill bed, the Speed Dial no-op that `run_action` +reports as an error, `add_part` (shapes at a size and a position, a model file, one undo step, +and what it refuses), and the object structure commands (Change Type, Rename, number of instances, +individual objects, Assemble, Order By and its reversal, and what each refuses). It ends with all of +them on one scene: a block with a magnet pocket and a boss, sized, moved to a second plate, copied six +times and arranged there, split into objects, one mirrored, two assembled, ordered, the plate filled +and sliced. + +`tests/layers.json` checks height range modifiers: `set_layer_ranges` with ranges given out of order, +their read-back in `list_objects`, one undo step (and none for the same ranges again), the layer count +of a slice with them, the refusals (an overlap, a layer height beyond the printer's, a missing filament, +an object setting, an empty range), a range in the second filament, a 3MF round trip, and `[]`. Then +variable layer height profiles on a Benchy with `set_layer_height_profile`: Adaptive called from the +Preview tab, its quality's effect on the point count, the layer count of a slice with it, Smooth as one +undo step, Reset and a Reset that changes nothing, the refusals (an argument of another action, the +assemble view), Smooth and Adaptive over height ranges, and a 3MF round trip. Last, layer G-codes on a +cube with `set_layer_gcode`: refused before a slice, a pause by layer and custom G-code by height called +from Prepare (it shows the Preview), the same code again changing nothing, a removal and an in-place +custom edit in one call, the refusals (a layer above the top, a code where another is, nothing to remove, +a missing filament, a missing plate, a plate changed since its slice that the Preview does not show), a +filament change, a 3MF round trip, and `clear`. + +`tests/multicolor.json` assigns filaments to objects and parts through `set_settings`' object and +volume scopes, with undo and redo, and reads them back with `get_settings`' effective values. It then +sets the project's slot colours, flushing multiplier, one flushing volume and plate type through the +project scope (in one call, the colour first), checks the refusals that leave everything as it was +(the read-only `filament_is_mixed`, a bad colour, a purge mode the printer has no button for, a non-zero +diagonal, a tower off the plate), and moves the prime tower with an undo, before slicing. + +`tests/presets.json` saves filament, process and printer presets with `save_preset` (a user preset, +one inside the project that a saved and reopened project keeps, a detached one, and the overwrite +rule), and drops unsaved edits with `set_settings {"reset_all": true}`. It reads presets that are not +selected and compares presets (`get_settings` `preset` and `compare`), writes one entry of a +per-variant value, and checks `set_settings`' `changed` after the spiral vase dialog. It reverts single +keys (`null`, `reset_to`), and answers the unsaved-changes prompts: `select_preset` without `changes` +still opens the prompt, `changes` transfers or discards without it, and `new_project` keeps modified +presets unless `changes` is `"discard"`. It ends by deleting the presets it made with `delete_preset`: +filaments the tab edits and does not, a base process and its child, and a printer once selected, with +the refusals for system presets, a preset another inherits from, unsaved changes and a printer that is +not selected. It exports a filament with the Export Preset Bundle dialog to its `out_dir` (`export_config` +with a directory), imports the archive again with `import_configs` and a path (kept while the preset +exists, imported once it is deleted) and imports `tests/fixtures/mcp_import_pla.json`. It changes a +preference in the Preferences dialog opened with `open_preferences` `control:auto_arrange`, by the +control's name, and reads it back with `get_settings {"scope": "preferences"}`. It starts from the +harness's default printer with one filament slot in Simple mode, deleting slots and selecting the mode +first, and reruns on the same datadir. + +`tests/plates.json` sets a plate type and print sequence on one plate only (with undo and redo), the +first and other layers' filament orders, spiral vase, the lock (twice, which leaves it locked) and a +name through `set_settings`' plate scope, and reads them back with `list_plates` and `get_settings`. +It brings the filament list to two slots with the `filament_add` and `filament_delete` commands first, +and ends with a mixed filament, whose slot the delete command refuses and ahead of which a new slot +goes. It reruns on the same datadir. + +`tests/calibration.json` makes every calibration test with `calibrate` (each pressure advance method, +a 2 x 2 pattern batch, the four flow ratio passes) and checks the objects it added, the parameters +it used and the presets it changed, slicing some of them. It checks the temperature rounding, the +refusals that leave the project as it was (modified presets without `changes`, an argument the test +does not take), `changes: "keep"` keeping an edit, and `new_project` dropping the test's settings. It +starts from the harness's default printer and reruns on the same datadir. + +The Design-tab scripts drive `cad_call` and need an instance launched with `--cad`. Each starts +from a new project and checks what it builds by volume and by what `cad_call` reads back; steps +marked `optional` are calls that must be refused and change nothing. + +- `tests/cad_sketch_to_solid.json` takes sketches to solids: an L-bracket profile on XZ through the + modeling origin with its inside corner filleted in the sketch (after an empty commit that must + fail and leave the sketch open), a shelf-pin jig plate whose five holes are in its sketch, a lip + sketched on the plate's top face and joined to it, one loop of the plate's sketch extruded alone, + and a ring revolved about its sketch's centerline. +- `tests/cad_sketch_edit.json` drives the sketch tools: the bench's hex standoff from a polygon 8 mm + across the flats, a trim and an extend on crossing lines, and a plate with a chamfered and a + rounded corner, two slots (one an array copy turned upright), an elliptic hole and four holes + arrayed about a point, constrained from picks and from named points, with a refused constraint + rolled back and one deleted. +- `tests/cad_topology_targets.json` builds the bench's J wall hook from what `cad_call` reads back: + its inside corners found by convexity, M4 countersinks seated on the front face on the axes of + pilot holes, the cones' kind, apex side and radii from `query_topology`, the hole heights and the + plate's thickness from `measure`, a datum plane midway through the plate and one 70 mm up with a + sketch on it, a refused tangent plane, and the back face pushed out 2 mm. +- `tests/cad_features.json` threads, sweeps, lofts and splits: the bench's M5 hex standoff tapped on + its bore (M5 inferred from the bore) and again on the XY plane, each within the bench's volume + bounds; a spring swept along a helix in round and square wire; a square-to-circle loft between XY + and a datum plane 40 mm up; the loft split by that datum and its lower half cut again by XY turned + over. +- `tests/cad_doc.json` reads and edits features as their cards do: a variable bound to an extrude, + then removed, and literal edits with `set_feature`. Then it commits the design to the plate, + recommits over the first object and undoes that in one step, exports STEP and reads it back into a + new design, and commits two bodies both ways. Last it walks the Design history (`undo` / `redo` of + an edit and of a rename), hides, moves and deletes features, names, hides and colours bodies, + commits only the shown one, and saves and reopens the project to check that a body's name and + colour were kept. +- `tests/cad_canvas.json` drives the Design view as a canvas: `set_view` shows the Design tab and + points its camera (and refuses Prepare's and Preview's fields there), canvas and widget + screenshots capture the view, a click at its centre picks the block and a right click lists the + verbs for the pick, and `ui_key` reaches the Design panel's key hook (Shift+E opens the Extrude + card, Escape with no target closes it). Last, a change made only in the Design tab marks the + project modified, and reopening the saved design-only project with `discard_changes` asks nothing + and names the project after its file. + +Two harness tests run on an instance launched with `--cad`. `test_cad_replay.py` makes calls as a +client, so they are journaled, exports the session with `export_script`, replays it into a new +project and compares the body's mass properties and the features. The session has an empty sketch +commit and a missed hole, which must fail and be left out, a legacy `fillet` answering ok false, +which stays in, and face and edge ids passed with their `generation`, which the journal drops. +`test_cad_slow_build.py` runs a long thread build (an M8 thread tapped 60 mm deep, about 8 s) and +checks that while it builds `get_state` answers, a window screenshot succeeds, `ui_snapshot` lists +the progress dialog and a screenshot of that dialog captures it, and another `cad_call` is refused. +`test_cad_failed_job.py` sweeps a coil whose every rebuild takes about 30 s (its turns sized from a +short calibration build), then a hole that misses it replies with a running job and fails after +the reply budget: an export while it runs leaves it out and names it in `left_out_running`, the +export after it has the rename made next and not the hole, and that script replays to the same coil. +It takes three to four minutes. + +`tests/dialogs_canvas_input.json` checks that an auto-answered Transfer or Discard on the +unsaved-changes dialog does its work, that a toolbar item a selection just enabled takes a click at +once, and that a negative part, and a point seen through the bed from below, are click targets. + +`tests/context_menus.json` right-clicks a cube, the empty bed and two selected objects, and clicks a +preset edit button that opens a menu: each menu is listed in the reply, or an item of it run with +`popup_item` (a modifier, a primitive, Delete), and none is ever shown, so on macOS the run finishes +with nobody pressing Escape. + +`tests/rows.json` drives rows and popups: object list rows (plates, an object and its parts, Ctrl +to add a row, the Printable column, a double click), the object's and a part's menus run from their +rows, Compare presets' rows, the object settings table, the print button's popup and the plate type +drop-down list. + +`tests/plate_icons.json` clicks the Prepare view's plate icons by `{plate_icon, plate}`: lock twice, +Plate Settings opened and cancelled, arrange of a second plate's two cubes (the reply waits for the +job), the plate menu from a right click, and move to front. + +`tests/webview_modal.json` runs scripts in the web views of modal dialogs, the preset bundle dialog +and the setup wizard, by default and by locator, and closes the bundle dialog from its page's own +button. `test_webview_modal.py` checks what that script cannot: scripts are refused in the Flushing +volumes dialog and in the Home tab's web view behind a modal, and a page that closes its dialog +replies `closed` at once. + +`tests/slice_stats.json` slices one cube, then two cubes in two colours, and checks the slice +reply's statistics: layers, max Z, filament changes, and each filament slot's model, flush and +prime tower grams. + +`tests/preview.json` slices a cube and reads it back with `get_preview` (summary, feature and layer +tables, the object, the legend's state and colour ranges) and `get_state.preview` as `set_view` +changes the layer (by number and by height), the view type, legend rows and time estimate, then +reads the cube's G-code opened for viewing the same way. Run it on a fresh datadir: modified presets +left by an earlier script make opening the G-code ask about them. `test_set_view_preview.py` checks +what that script cannot: `set_view {view_type}` acts as the legend's combo (a feature type hidden by +a click on its row shows again on Line Type, and the pick reaches the app config), and the refusals +of the preview arguments. + `test_stdio_bridge.py [--bin PATH]` checks `orca-slicer --mcp-stdio` against the launched instance: the handshake, notifications, tool calls in both protocol eras, and errors. `test_recovery_under_load.py` fills the server's connections with 32 blocked `wait` calls and 32 @@ -100,4 +256,15 @@ connection still closes it. `test_cancel_pending_slice.py` cancels a slice while the update a setting change scheduled, and checks that it never starts. `test_ref_locator_export.py` uses ImGui refs after their items changed (the Text gizmo's font button, whose label shows the font, and a Texture Displacement layer row renamed by its place when a layer before it goes) and checks -that the exported session replays. +that the exported session replays. `test_worker_admission.py` starts a long arrange three ways (the +`arrange` tool, `run_action obj_arrange`, a click on the Arrange options panel's button) and checks +that changes, canvas keys and toolbar clicks are refused while it runs, reads answer, and `cancel` +stops it. `test_export_running_job.py` exports while a call's job runs past +its reply budget (left out, named in `left_out_running`), after it ends (an `await: false` step that +replays) and while a dialog holds its call (kept); it takes about two minutes. +`test_send_gcode.py` starts an OctoPrint-compatible stub host and sends a sliced cube to it with the +Speed Dial's `send_gcode`, the Send dialog answered with `ui_input` and `dialog_respond`: the command +is refused for a Bambu network printer and one without a print host, an upload the stub accepts +reads uploading at 99 until the stub answers and then completed in `get_state.uploads`, its exported +script uploads again, and one the stub refuses with HTTP 500 never reads completed and ends as an +error whose dialog `dialog_respond` closes. diff --git a/tools/mcp/orca_mcp.py b/tools/mcp/orca_mcp.py index f14fc5deeb..39d341ff56 100644 --- a/tools/mcp/orca_mcp.py +++ b/tools/mcp/orca_mcp.py @@ -7,6 +7,7 @@ Standard library only. Two halves: * A command line that launches OrcaSlicer for an agent or a test and talks to it:: tools/mcp/orca_mcp.py launch --xvfb # fresh datadir, wait until ready, print client config + tools/mcp/orca_mcp.py launch --cad # with the Design (CAD) tab on, for cad_call tools/mcp/orca_mcp.py call get_state tools/mcp/orca_mcp.py call open_files '{"paths": ["/abs/model.stl"]}' tools/mcp/orca_mcp.py screenshot /tmp/shot.png --target canvas @@ -166,21 +167,37 @@ def find_binary(explicit): sys.exit("orca-slicer not found; pass --bin") -def seed_datadir(datadir, printer): +def write_conf(conf, data): + with open(conf, "w") as f: + json.dump(data, f, indent=2) + # On Windows the loader expects a line after the closing brace, where it keeps a checksum, and + # fails to start the app when the file ends at the brace. + f.write("\n") + + +def seed_datadir(datadir, printer, cad=False): + """Seed a fresh datadir's OrcaSlicer.conf. A datadir that has one keeps it, except that cad turns + the Design tab on there too, since the app reads that setting only at startup.""" vendor, model, nozzle, filament = printer os.makedirs(datadir, exist_ok=True) conf = os.path.join(datadir, "OrcaSlicer.conf") if os.path.exists(conf): + if cad: + with open(conf, encoding="utf-8") as f: + text = f.read() + # The app ends the file with a checksum line after the JSON; a mismatch only logs. + data = json.loads(text[:text.rfind("}") + 1]) + data.setdefault("app", {})["enable_cad_feature"] = True + write_conf(conf, data) return - with open(conf, "w") as f: - json.dump({"firstguide": {"finish": True}, - "models": [{"model": model, "nozzle_diameter": nozzle, "vendor": vendor}], - "filaments": [filament], - "presets": {"machine": f"{model} {nozzle} nozzle"}, - "app": {"check_for_updates": False, "show_daily_tips": False}}, f, indent=2) - # On Windows the loader expects a line after the closing brace, where it keeps a checksum, and - # fails to start the app when the file ends at the brace. - f.write("\n") + app = {"check_for_updates": False, "show_daily_tips": False} + if cad: + app["enable_cad_feature"] = True + write_conf(conf, {"firstguide": {"finish": True}, + "models": [{"model": model, "nozzle_diameter": nozzle, "vendor": vendor}], + "filaments": [filament], + "presets": {"machine": f"{model} {nozzle} nozzle"}, + "app": app}) def start_xvfb(width, height): @@ -236,7 +253,7 @@ def launch(args): if args.printer: model, _, nozzle = args.printer.partition("@") printer = (args.vendor, model, nozzle or "0.4", args.filament or DEFAULT_PRINTER[3]) - seed_datadir(datadir, printer) + seed_datadir(datadir, printer, args.cad) env = dict(os.environ, ORCA_MCP_TOKEN=token) xvfb_pid = None @@ -310,6 +327,7 @@ def main(): p.add_argument("--printer", help="\"<model>@<nozzle>\" for a fresh datadir, e.g. \"Bambu Lab X1 Carbon@0.4\"") p.add_argument("--vendor", default="BBL") p.add_argument("--filament") + p.add_argument("--cad", action="store_true", help="turn the Design (CAD) tab on, for cad_call") p.add_argument("--timeout", type=int, default=120) p.add_argument("--print-config", action="store_true", help="print client setup commands") p.add_argument("extra", nargs="*", help="extra orca-slicer arguments after --") diff --git a/tools/mcp/test_cad_failed_job.py b/tools/mcp/test_cad_failed_job.py new file mode 100755 index 0000000000..ae429c927c --- /dev/null +++ b/tools/mcp/test_cad_failed_job.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 +"""Checks that a Design-tab call whose job fails after its reply is left out of export_script. + + tools/mcp/orca_mcp.py launch --cad + tools/mcp/test_cad_failed_job.py + +A coil swept along a helix makes every rebuild of the design slow, so a hole that misses it, which +the kernel refuses only after the rebuild and takes back with another, replies with a running job +past the 45 s budget and then fails. An export while it runs leaves it out and names it in +left_out_running; once it has failed, a rename made after it is in the export, the hole is not, and +the script replays into a new project to the same features and coil. The coil's turns are sized +from a short calibration build, taking a build's time to grow with the cube of the turns, so the +failing call outlives the budget on a faster or slower machine; a busy machine bends that curve, so +when the hole still fails inside the budget the session is made again with a bigger coil. Takes four +to five minutes. Exits 0 when every check passes. +""" + +import json +import math +import os +import sys +import tempfile +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import orca_mcp # noqa: E402 + +# The coil's build time to aim for. The missed hole takes about as long as the build, so this is well +# past the reply budget. +REBUILD_S = 60.0 + + +def cad(client, method, **params): + return client.call("cad_call", _timeout=600, method=method, params=params) + + +def coil(client, turns): + """A new design holding one coil: a 1.2 mm wire swept along a helix of radius 10 and pitch 3.""" + cad(client, "new_design", discard_changes=True) + cad(client, "helix", radius=10, pitch=3, height=3 * turns) + cad(client, "sketch_begin", plane="XZ") + cad(client, "sketch_add", type="circle", center=[10, 0], radius=1.2) + cad(client, "sketch_commit") + start = time.time() + client.await_job(cad(client, "sweep", sketch=1, path=0)) + return time.time() - start + + +def main(): + client, _ = orca_mcp.session_client() + out_dir = tempfile.mkdtemp(prefix="orca-mcp-cad-failed-job-") + path = os.path.join(out_dir, "session.json") + checks = [] + + def check(name, ok, detail=""): + checks.append((name, bool(ok), detail)) + + client.call("new_project", discard_changes=True) + calibration = coil(client, 12) + turns = max(12, min(40, round(12 * (REBUILD_S / max(calibration, 0.5)) ** (1 / 3)))) + print(f"12 turns built in {calibration:.1f} s; the test coil has {turns}", flush=True) + + # ---- The session to export ---- + while True: + client.call("export_script", clear=True) + client.call("new_project", discard_changes=True) + coil(client, turns) + start = time.time() + try: + started = cad(client, "hole", x=500, through=True) + break + except orca_mcp.McpError as e: + if turns >= 40 or "removed no material" not in str(e): + raise + print(f"the hole failed inside the budget, in {time.time() - start:.1f} s; trying {min(40, turns + 4)} turns", + flush=True) + turns = min(40, turns + 4) + check("the missed hole replies with its running job", started.get("status") == "running", + f"{started.get('status')} after {time.time() - start:.1f} s; the coil rebuilds too fast") + during = client.call("export_script") + check("an export while it runs leaves it out and names it", + during.get("left_out_running") == [{"tool": "cad_call", "job": started.get("job")}], during.get("left_out_running")) + failure = None + try: + client.await_job(started) + except orca_mcp.McpError as e: + failure = str(e) + check("the hole then fails as an error", failure and "removed no material" in failure, + f"{failure} after {time.time() - start:.1f} s") + cad(client, "feature_rename", feature=2, name="Coil") + live_scene = cad(client, "describe_scene")["result"] + live_mass = cad(client, "mass_properties", body=0)["result"] + + after = client.call("export_script", path=path, overwrite=True) + calls = [s["args"] for s in after["script"]["steps"] if s["tool"] == "cad_call"] + methods = [c["method"] for c in calls] + check("the export leaves the failed hole out", "hole" not in methods, methods) + check("and keeps the rename made after it", "feature_rename" in methods, methods) + check("and leaves nothing out", "left_out_running" not in after, after.get("left_out_running")) + + # ---- The replay ---- + client.call("new_project", discard_changes=True) + replay = client.await_job(client.call("run_script", path=path, out_dir=out_dir), timeout=900) + check("the exported session replays", replay.get("passed") is True, + json.dumps([s for s in replay.get("steps", []) if not s.get("ok")][:1])) + scene = cad(client, "describe_scene")["result"] + mass = cad(client, "mass_properties", body=0)["result"] + # Feature names count on across projects; the renamed one keeps its name. + kinds = lambda s: [f["type"] for f in s["features"]] # noqa: E731 + check("the same features, the coil renamed", kinds(scene) == kinds(live_scene) and scene["features"][2]["name"] == "Coil", + (scene["features"], live_scene["features"])) + check("the same coil", math.isclose(mass["volume"], live_mass["volume"], rel_tol=1e-6), (mass["volume"], live_mass["volume"])) + + print(f"script and replay in {out_dir}") + failed = [c for c in checks if not c[1]] + for name, ok, detail in checks: + print(("PASS " if ok else "FAIL ") + name + ("" if ok or detail == "" else f": {detail}")) + print(f"{len(checks) - len(failed)}/{len(checks)} checks passed") + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/mcp/test_cad_replay.py b/tools/mcp/test_cad_replay.py new file mode 100755 index 0000000000..a8c280d5a5 --- /dev/null +++ b/tools/mcp/test_cad_replay.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 +"""Checks that a Design-tab session exported with export_script replays to the same part. + + tools/mcp/orca_mcp.py launch --cad + tools/mcp/test_cad_replay.py + +Records a session of cad_call client calls (script steps are not journaled) on the paths a replay +breaks on: a sketch on a base plane, which passes through modeling_origin as every plane does; an +empty sketch commit, which fails and must keep the sketch open for the next call; a rewritten +method failing as an error (a hole that misses), which export_script must leave out; a legacy +method answering ok false, which stays in and replays the same rejection; and face and edge ids +passed with the generation they were read at, which the journal drops, since the replay reaches +other generation numbers. The thread rebuilds behind the progress dialog. The exported script is +replayed into a new project in the same instance, whose generation count has moved on, and the +body's mass properties and the feature list must match. Exits 0 when all hold. +""" + +import json +import math +import os +import sys +import tempfile + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import orca_mcp # noqa: E402 + + +def cad(client, method, **params): + return client.call("cad_call", _timeout=300, method=method, params=params)["result"] + + +def refused(client, method, **params): + """The error text of a call that must fail, or None when it succeeded.""" + try: + cad(client, method, **params) + except orca_mcp.McpError as e: + return str(e) + return None + + +def record(client): + """The session to export; returns the reads the replay must match and the refusals seen.""" + client.call("export_script", clear=True) + client.call("new_project", discard_changes=True) + cad(client, "new_design", discard_changes=True) + frame = cad(client, "sketch_begin", plane="XY")["frame"] + empty_commit = refused(client, "sketch_commit") + # A 40 x 30 plate with an M5 tap-drill bore (minor diameter 4.134), 12 thick. + cad(client, "sketch_add", rect=[-20, -15, 20, 15]) + cad(client, "sketch_add", entities=[{"type": "circle", "center": [0, 0], "radius": 2.067}]) + cad(client, "sketch_commit") + cad(client, "extrude", sketch=0, distance=12) + missed_hole = refused(client, "hole", x=500, through=True) + corners = cad(client, "query_topology", body=0, edge_kinds=["line"], direction=[0, 0, 1], convex=True) + cad(client, "fillet", edge=[e["id"] for e in corners["edges"]], radius=3, body=0, + generation=corners["generation"]) + legacy = cad(client, "fillet", edge=corners["edges"][0]["id"], radius=50, body=0) + bores = cad(client, "query_topology", body=0, kinds=["cylindrical"]) + bore = next(f["id"] for f in bores["faces"] if f.get("internal")) + thread = client.await_job(client.call("cad_call", _timeout=300, method="thread", + params={"body": 0, "face": bore, "generation": bores["generation"]})) + return {"mass": cad(client, "mass_properties", body=0), "scene": cad(client, "describe_scene"), + "frame": frame, "empty_commit": empty_commit, "missed_hole": missed_hole, "legacy": legacy, + "thread": thread.get("result", {})} + + +def same(a, b, rel=1e-6): + return math.isclose(a, b, rel_tol=rel, abs_tol=1e-6) + + +def main(): + client, _ = orca_mcp.session_client() + live = record(client) + out_dir = tempfile.mkdtemp(prefix="orca-mcp-cad-replay-") + path = os.path.join(out_dir, "session.json") + client.call("export_script", path=path, overwrite=True) + with open(path) as f: + text = f.read() + steps = json.loads("\n".join(l for l in text.splitlines() if not l.lstrip().startswith("//")))["steps"] + calls = [s["args"] for s in steps if s["tool"] == "cad_call"] + methods = [c["method"] for c in calls] + + client.call("new_project", discard_changes=True) + replay = client.await_job(client.call("run_script", path=path, out_dir=out_dir), timeout=900) + mass = cad(client, "mass_properties", body=0) + scene = cad(client, "describe_scene") + kinds = lambda s: [f["type"] for f in s["features"]] # noqa: E731 (names count on across projects) + + origin = live["scene"]["modeling_origin"] + checks = [ + ("a sketch on XY and the plate are centred on modeling_origin", + live["frame"]["origin"] == origin and all(same(a, b) for a, b in zip(live["mass"]["center_of_mass"][:2], origin[:2])), + (live["frame"]["origin"], live["mass"]["center_of_mass"], origin)), + ("an empty sketch_commit fails", bool(live["empty_commit"]), live["empty_commit"]), + ("a hole that misses fails as an error", bool(live["missed_hole"]), live["missed_hole"]), + ("a legacy fillet the kernel refuses answers ok false", live["legacy"].get("ok") is False, live["legacy"]), + ("the thread is M5, inferred from the bore", live["thread"].get("designation") == "M5", live["thread"]), + ("the export leaves out the failed calls", methods.count("sketch_commit") == 1 and "hole" not in methods, methods), + ("the export keeps the legacy ok-false call", methods.count("fillet") == 2, methods), + ("the export records no generation", all("generation" not in c.get("params", {}) for c in calls), calls), + ("the exported session replays", replay.get("passed") is True, + [s for s in replay.get("steps", []) if not s.get("ok")][:1]), + ("the same features", kinds(scene) == kinds(live["scene"]), (kinds(scene), kinds(live["scene"]))), + ("the same bodies and undo depth", + len(scene["bodies"]) == len(live["scene"]["bodies"]) and scene["undo_depth"] == live["scene"]["undo_depth"], + (len(scene["bodies"]), scene["undo_depth"], live["scene"]["undo_depth"])), + ("the same volume and surface area", + same(mass["volume"], live["mass"]["volume"]) and same(mass["surface_area"], live["mass"]["surface_area"]), + (mass["volume"], live["mass"]["volume"])), + ("the same centre of mass", + all(same(a, b) for a, b in zip(mass["center_of_mass"], live["mass"]["center_of_mass"])), + (mass["center_of_mass"], live["mass"]["center_of_mass"])), + ] + print(f"volume {live['mass']['volume']:.3f} mm3; script and replay in {out_dir}") + failures = 0 + for name, ok, detail in checks: + print(("ok " if ok else "FAIL ") + name + ("" if ok else f": {detail}")) + failures += not ok + return 1 if failures else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/mcp/test_cad_slow_build.py b/tools/mcp/test_cad_slow_build.py new file mode 100755 index 0000000000..a13d54a154 --- /dev/null +++ b/tools/mcp/test_cad_slow_build.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +"""Checks that OrcaSlicer stays inspectable while a long Design-tab rebuild runs. + + tools/mcp/orca_mcp.py launch --cad + tools/mcp/test_cad_slow_build.py + +cad_call thread, sweep and loft rebuild as their cards do, off the UI thread behind the progress +dialog (DesignPanel::recompute_guarded). While a long thread builds: get_state answers, a screenshot +of the main window succeeds, ui_snapshot lists the progress dialog and a screenshot of that window +captures it (not on Windows, where the dialog is the system's task dialog), and another cad_call is refused rather than run inside the rebuild. The thread then +lands as one feature. Exits 0 when all hold. +""" + +import os +import re +import sys +import tempfile +import threading +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import orca_mcp # noqa: E402 + +# An M8 thread tapped 60 mm deep into a 30 mm square block: 48 turns, several seconds of OCCT pipe and +# boolean work (about 8 s on an M2 Mac). +BLOCK = {"width": 30, "height": 30, "distance": 60} +THREAD = {"plane": "XY", "internal": True, "designation": "M8", "length": 60} + + +def progress_dialog_ref(client): + """The ref of the rebuild's progress dialog (titled "Design") in ui_snapshot, or None.""" + _, texts = client.call_with_text("ui_snapshot") + for line in "\n".join(texts).splitlines(): + m = re.match(r'\[(w\d+)\] (?:window|dialog) "Design" \((\w+)\)', line) + if m and "Progress" in m.group(2): + return m.group(1) + return None + + +def main(): + client, _ = orca_mcp.session_client() + out = tempfile.mkdtemp(prefix="orca-mcp-slow-") + client.call("new_project", discard_changes=True) + client.call("cad_call", method="new_design", params={"discard_changes": True}) + client.call("cad_call", method="extrude", params=BLOCK) + + box = {} + + def build(): + try: + box["result"] = client.call("cad_call", _timeout=600, method="thread", params=THREAD) + except orca_mcp.McpError as e: + box["error"] = str(e) + + worker = threading.Thread(target=build) + started = time.time() + worker.start() + + # On Windows the progress dialog is the system's task dialog, on a thread of its own: no wx window + # ui_snapshot lists. There the probes start once the build has run for 2 s, past the dialog's delay. + native_dialog = sys.platform == "win32" + probed, state_ms, window_shot, dialog_shot, refused = False, None, None, None, None + while worker.is_alive() and time.time() - started < 300: + time.sleep(0.5) + if not probed: + ref = None if native_dialog else progress_dialog_ref(client) + if ref is not None or (native_dialog and time.time() - started > 2): + probed = True + t0 = time.time() + client.call("get_state") + state_ms = (time.time() - t0) * 1000 + window_shot = client.call("screenshot", target="window", include_image=False, + save_path=os.path.join(out, "window.png")) + if ref is not None: + dialog_shot = client.call("screenshot", target=ref, include_image=False, + save_path=os.path.join(out, "progress.png")) + try: + client.call("cad_call", method="describe_scene") + refused = False + except orca_mcp.McpError as e: + refused = str(e) + worker.join(600) + seconds = time.time() - started + result = client.await_job(box.get("result")) if "result" in box else None + scene = client.call("cad_call", method="describe_scene")["result"] + threads = [f for f in scene["features"] if f["type"] == "Thread"] + + print(f"build took {seconds:.1f} s; screenshots in {out}") + failures = 0 + checks = [ + ("the thread call succeeds", result is not None and result.get("result", {}).get("ok") is True, box), + ("get_state answers during the build", state_ms is not None, state_ms), + ("a window screenshot succeeds during the build", bool(window_shot and window_shot.get("width")), window_shot), + ("another cad_call is refused during the build", bool(refused) and "Busy" in refused, refused), + ("one thread feature and one body", len(threads) == 1 and len(scene["bodies"]) == 1, scene["features"]), + ] + if not native_dialog: + checks[1:1] = [ + ("the progress dialog is listed while it builds", dialog_shot is not None, "no window \"Design\" in ui_snapshot"), + ("a screenshot of the progress dialog captures it", + bool(dialog_shot and dialog_shot.get("width")) and dialog_shot.get("width") < (window_shot or {}).get("width", 0), dialog_shot), + ] + for name, ok, detail in checks: + print(("ok " if ok else "FAIL ") + name + ("" if ok else f": {detail}")) + failures += not ok + return 1 if failures else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/mcp/test_export_running_job.py b/tools/mcp/test_export_running_job.py new file mode 100755 index 0000000000..14babd27c6 --- /dev/null +++ b/tools/mcp/test_export_running_job.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python3 +"""Checks what export_script does with a call whose job outlived its reply. + + tools/mcp/orca_mcp.py launch + tools/mcp/test_export_running_job.py + +A run_script whose one step waits 48 s replies with its running job after the 45 s budget. An export +while it runs leaves it out and names it in left_out_running; an export after it succeeded has it as +an await:false step that the later wait refers to, and that script replays. A call blocked on a +dialog stays in the script while the dialog is open, since the steps after it answer the dialog. +A job that fails after its reply is dropped; no tool fails that late on demand, so the unit tests +in test_mcp_results.cpp cover it. Takes about two minutes. Exits 0 when every check passes. +""" + +import json +import os +import sys +import tempfile +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import orca_mcp # noqa: E402 + + +def main(): + client, _session = orca_mcp.session_client() + work = tempfile.mkdtemp(prefix="orca-export-running-") + checks = [] + + def check(name, ok, detail=""): + checks.append((name, bool(ok), detail)) + + def tools(script): + return [s["tool"] for s in script["steps"]] + + client.call("export_script", clear=True) + + # ---- A job past the reply budget, exported while it runs and after it ends ---- + start = time.time() + slow = {"orca_script": 1, "name": "slow", "steps": [{"tool": "wait", "args": {"for": "dialog", "timeout_s": 48}}]} + started = client.call("run_script", _timeout=120, script=slow, out_dir=os.path.join(work, "slow")) + check("the slow script replies with its running job", started.get("status") == "running", + f"{started.get('status')} after {time.time() - start:.1f} s") + job = started.get("job") + client.call("set_settings", values={"wall_loops": 3}) + during = client.call("export_script") + check("an export while it runs leaves it out", tools(during["script"]) == ["set_settings"], tools(during["script"])) + check("and names it in left_out_running", during.get("left_out_running") == [{"tool": "run_script", "job": job}], + during.get("left_out_running")) + + done = client.await_job(started) # a journaled wait on the job + check("the job then succeeds", done.get("passed") is True, done) + path = os.path.join(work, "after.json") + after = client.call("export_script", path=path, overwrite=True) + steps = after["script"]["steps"] + check("an export after it ends has it as a step", tools(after["script"]) == ["run_script", "set_settings", "wait"], + tools(after["script"])) + check("replayed with await:false", steps[0].get("await") is False and steps[0].get("save_as") == "job1", steps[0]) + check("the wait refers to it", steps[2]["args"].get("job") == "${jobs.job1}", steps[2]) + check("nothing is left out", "left_out_running" not in after, after.get("left_out_running")) + + # ---- A call blocked on a dialog stays while the dialog is open ---- + client.call("export_script", clear=True) + blocked = client.call("run_action", id="orca_command:open_preferences:orca") + check("Preferences blocks its call", blocked.get("status") == "blocked_by_dialog", blocked.get("status")) + open_export = client.call("export_script") + check("an export with the dialog open keeps the call", tools(open_export["script"]) == ["run_action"], + tools(open_export["script"])) + check("and leaves nothing out", "left_out_running" not in open_export, open_export.get("left_out_running")) + client.call("dialog_respond", button="close") + client.await_job(blocked) + + # ---- The script exported after the slow job replays ---- + replay = client.await_job(client.call("run_script", _timeout=120, path=path, out_dir=os.path.join(work, "replay"))) + check("the exported script replays", replay.get("passed") is True, + json.dumps([(s["tool"], s["ok"]) for s in replay.get("steps", [])])) + + failed = [c for c in checks if not c[1]] + for name, ok, detail in checks: + print(("PASS " if ok else "FAIL ") + name + ("" if ok or detail == "" else f": {detail}")) + print(f"{len(checks) - len(failed)}/{len(checks)} checks passed") + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/mcp/test_ref_locator_export.py b/tools/mcp/test_ref_locator_export.py index 8f6dfa3d3c..34805462e1 100755 --- a/tools/mcp/test_ref_locator_export.py +++ b/tools/mcp/test_ref_locator_export.py @@ -70,7 +70,8 @@ def main(): clicked = client.call("ui_click", target=row[0]) layers = client.call("list_objects")["items"][0]["volumes"][0]["painted"]["texture"] checks.append(("the old ref clicks the renamed row", len(layers) == 2, (clicked, len(layers)))) - client.call("ui_click", target={"imgui_name": "close"}) + # Its icon closes it: in a small window the object's info notification covers the panel's Close. + client.call("ui_click", target={"gizmo": "Texture Displacement"}) client.call("wait", **{"for": "idle"}) out_dir = tempfile.mkdtemp(prefix="orca-mcp-") diff --git a/tools/mcp/test_send_gcode.py b/tools/mcp/test_send_gcode.py new file mode 100755 index 0000000000..10ec583b53 --- /dev/null +++ b/tools/mcp/test_send_gcode.py @@ -0,0 +1,232 @@ +#!/usr/bin/env python3 +"""Checks sending G-code to a print host with the Speed Dial's send_gcode, read back through get_state.uploads. + + tools/mcp/orca_mcp.py launch + tools/mcp/test_send_gcode.py + +Starts an OctoPrint-compatible stub host on a free loopback port. The command first refuses a printer that +prints through the Bambu network (when the app starts on a Bambu printer) and one without a print host. Then +the printer points at the stub, a cube is sliced, and each send runs send_gcode, sets the file name with +ui_input and presses Upload with dialog_respond: +- the stub answers 200 a few seconds after it has the whole file: meanwhile the row reads uploading at 99, + then completed, and the stub got the file without print=true; +- the script exported from that send replays and uploads again; +- the stub answers 500 after the same pause: the row never reads completed, ends as an error naming + HTTP 500, and the error dialog the queue opens closes with dialog_respond; +- the stub answers 500 at once: the row still ends as an error rather than staying queued. +Exits 0 when every check passes. +""" + +import http.server +import json +import os +import re +import sys +import tempfile +import threading +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import orca_mcp # noqa: E402 + +MODEL = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "resources", "handy_models", "OrcaCube_v2.drc") +SEND = "orca_command:send_gcode:orca" +PAUSE_S = 3.0 + + +class StubHost: + """An OctoPrint-compatible print host: it answers the version check, and takes a file posted to + /api/files/local, answering `status` `delay` seconds after it has read the whole request.""" + + def __init__(self): + self.status = 200 + self.delay = 0.0 + self.uploads = [] # {"filename", "print"} of each file posted + stub = self + + class Handler(http.server.BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" # answers curl's Expect: 100-continue + + def log_message(self, *args): + pass + + def reply(self, status, body): + data = json.dumps(body).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def read_body(self): + if self.headers.get("Transfer-Encoding", "").lower() == "chunked": + body = b"" + while True: + size = int(self.rfile.readline().split(b";")[0], 16) + chunk = self.rfile.read(size + 2)[:size] + if size == 0: + return body + body += chunk + return self.rfile.read(int(self.headers.get("Content-Length", 0))) + + def do_GET(self): + if self.path.startswith("/api/version"): + self.reply(200, {"api": "0.1", "server": "1.10.0", "text": "OctoPrint 1.10.0"}) + else: + self.reply(404, {"error": "not found"}) + + def do_POST(self): + body = self.read_body() + if not self.path.startswith("/api/files/local"): + return self.reply(404, {"error": "not found"}) + name = re.search(rb'filename="([^"]*)"', body) + printing = re.search(rb'name="print"\r\n\r\n(\w+)', body) + stub.uploads.append({"filename": name.group(1).decode() if name else None, + "print": printing.group(1).decode() if printing else None}) + time.sleep(stub.delay) + if stub.status == 200: + self.reply(200, {"done": True}) + else: + self.reply(stub.status, {"error": "The stub host refuses the file."}) + + self.server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) + self.port = self.server.server_address[1] + threading.Thread(target=self.server.serve_forever, daemon=True).start() + + +def uploads(client): + return client.call("get_state").get("uploads", []) + + +def send(client, filename): + """Sends the current plate as `filename` through the command's dialog and returns the new row's id.""" + before = len(uploads(client)) + blocked = client.call("run_action", id=SEND) + if blocked.get("status") != "blocked_by_dialog": + raise orca_mcp.McpError(f"send_gcode did not open its dialog: {blocked}", blocked) + client.call("ui_input", target={"class": "wxTextCtrl", "within": "Send G-code to printer host"}, value=filename, submit=False) + client.call("dialog_respond", button="Upload") + client.await_job(blocked) + return before + 1 + + +def follow(client, row_id, timeout=120): + """Polls the row until it is done; returns every (state, progress) read and the last row.""" + seen, deadline = [], time.time() + timeout + while time.time() < deadline: + rows = [r for r in uploads(client) if r["id"] == row_id] + if rows: + row = rows[0] + seen.append((row["state"], row["progress"])) + if row["state"] in ("completed", "error", "cancelled"): + return seen, row + time.sleep(0.2) + return seen, None + + +def refused(client, needle): + try: + opened = client.call("run_action", id=SEND) + except orca_mcp.McpError as e: + return needle in str(e) + if opened.get("status") == "blocked_by_dialog": + client.call("dialog_respond", button="Cancel") + client.await_job(opened) + return False + + +def close_error_dialog(client): + state = client.call("wait", **{"for": "dialog", "timeout_s": 10}) + dialogs = client.call("get_state")["dialogs"] + if not state.get("satisfied") or not dialogs: + return None + client.call("dialog_respond", button="ok") + client.call("wait", **{"for": "no_dialog", "timeout_s": 10}) + return dialogs[-1] + + +def main(): + client, _session = orca_mcp.session_client() + stub = StubHost() + work = tempfile.mkdtemp(prefix="orca-send-gcode-") + checks = [] + + def check(name, ok, detail=""): + checks.append((name, bool(ok), detail)) + + client.call("dialog_auto_answer", rules=[{"match": "unsaved changes", "button": "no"}]) + client.call("new_project", discard_changes=True) + client.call("open_files", paths=[os.path.abspath(MODEL)]) + client.call("wait", **{"for": "idle"}) + + found = client.call("list_actions", query="Send G-code") + check("list_actions finds the command", any(a["id"] == SEND for a in found["actions"]), found) + + # ---- Refusals ---- + if client.call("get_state")["presets"]["printer"].startswith("Bambu Lab"): + client.call("set_settings", scope="printer", values={"bbl_use_printhost": False}) + check("a Bambu network printer is refused", refused(client, "Print plate")) + client.call("set_settings", scope="printer", values={"bbl_use_printhost": True}) + # Plain G-code, so the dialog proposes a .gcode name (a .gcode.3mf would make it confirm the suffix). + client.call("set_settings", scope="printer", values={"host_type": "octoprint", "print_host": "", "use_3mf": False}) + check("a printer without a print host is refused", refused(client, "no print host")) + + client.call("set_settings", scope="printer", values={"print_host": f"127.0.0.1:{stub.port}"}) + sliced = client.call("slice") + check("the cube slices", sliced["plates"][0]["outcome"] == "ok", sliced) + + # ---- The host answers 200 after a pause ---- + client.call("export_script", clear=True) + stub.status, stub.delay = 200, PAUSE_S + seen, row = follow(client, send(client, "mcp_send_ok.gcode")) + check("the upload completes", row is not None and row["state"] == "completed" and row["progress"] == 100, row) + check("the row reads uploading at 99 while the host has yet to answer", ("uploading", 99) in seen, seen) + check("the row names the file and the host", row is not None and row["filename"] == "mcp_send_ok.gcode" + and str(stub.port) in row["host"], row) + check("the stub got the file, not to print", stub.uploads[-1:] == [{"filename": "mcp_send_ok.gcode", "print": "false"}], + stub.uploads) + + # ---- The exported send replays ---- + path = os.path.join(work, "send.json") + exported = client.call("export_script", path=path, overwrite=True) + # Each step that acts on the dialog follows a wait for it, since the replayed command may open it late. + check("the send exports as run_action, ui_input and dialog_respond, each after a wait for the dialog, and the " + "wait for the command", + [s["tool"] + ("(dialog)" if s["tool"] == "wait" and s["args"]["for"] == "dialog" else "") + for s in exported["script"]["steps"]] == + ["run_action", "wait(dialog)", "ui_input", "wait(dialog)", "dialog_respond", "wait"], + exported["script"]) + count = len(uploads(client)) + replay = client.await_job(client.call("run_script", path=path, out_dir=os.path.join(work, "replay"))) + check("the script replays", replay.get("passed") is True, replay) + _seen, row = follow(client, count + 1) + check("and uploads again", row is not None and row["state"] == "completed" and len(stub.uploads) == 2, (row, stub.uploads)) + + # ---- The host answers 500 after a pause ---- + stub.status, stub.delay = 500, PAUSE_S + seen, row = follow(client, send(client, "mcp_send_refused.gcode")) + check("a refused upload ends as an error", row is not None and row["state"] == "error" and "HTTP 500" in row.get("error", ""), row) + check("its row never reads completed", all(s != "completed" for s, _p in seen), seen) + check("it reads uploading at 99 until the host answers", ("uploading", 99) in seen, seen) + dialog = close_error_dialog(client) + check("the queue's error dialog closes with dialog_respond", dialog is not None and not client.call("get_state")["dialogs"], dialog) + + # ---- The host answers 500 at once ---- + stub.delay = 0.0 + _seen, row = follow(client, send(client, "mcp_send_fast.gcode")) + check("an upload refused at once ends as an error", row is not None and row["state"] == "error", row) + close_error_dialog(client) + + # Leave an empty project behind, so a script run next on this app does not meet its unsaved changes. + client.call("new_project", discard_changes=True) + client.call("dialog_auto_answer", rules=[]) + stub.server.shutdown() + failed = [c for c in checks if not c[1]] + for name, ok, detail in checks: + print(("PASS " if ok else "FAIL ") + name + ("" if ok or detail == "" else f": {detail}")) + print(f"{len(checks) - len(failed)}/{len(checks)} checks passed") + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/mcp/test_set_view_preview.py b/tools/mcp/test_set_view_preview.py new file mode 100755 index 0000000000..636e350930 --- /dev/null +++ b/tools/mcp/test_set_view_preview.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +"""Checks what set_view does to the Preview of a sliced cube where a script cannot look. + + tools/mcp/orca_mcp.py launch + tools/mcp/test_set_view_preview.py + +Picking a view type is the legend combo's pick: a feature type hidden by a click on its legend row +shows again when Line Type is picked, and the pick is written to the app config for the "Last used" +preview default. The refusals: legend rows before a slice, a height above the top layer, layer with +layer_z, an unknown legend row (named with the rows the print has), a value that is not true or +false, and a silent-mode estimate the print does not have; a refused call changes nothing. Exits 0 +when every check passes. +""" + +import json +import os +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import orca_mcp # noqa: E402 + + +def main(): + client, session = orca_mcp.session_client() + conf = os.path.join(session["datadir"], "OrcaSlicer.conf") + checks = [] + + def check(name, ok, detail=""): + checks.append((name, bool(ok), detail)) + + def refusal(**args): + try: + client.call("set_view", **args) + return "" + except orca_mcp.McpError as e: + return str(e) + + def legend(): + return client.call("get_preview", include=["view"])["view"]["legend"] + + def last_view_type(expected): + # The app writes its config at an idle moment, so wait for it. + value = None + for _ in range(50): + try: + with open(conf, encoding="utf-8") as f: + text = f.read() + # The JSON is followed by a checksum line on Windows. + value = json.loads(text[:text.rfind("}") + 1])["app"].get("preview_last_view_type") + except (OSError, ValueError, KeyError): + pass + if value == expected: + break + time.sleep(0.1) + return value + + client.call("dialog_auto_answer", rules=[{"match": "Uniform scale", "button": "ok"}]) + client.call("new_project", discard_changes=True) + check("legend rows need a slice", "slice first" in refusal(legend={"travel": False})) + client.call("run_action", id="orca_command:add_primitive_cube:orca") + client.call("wait", **{"for": "idle"}) + sliced = client.await_job(client.call("slice"))["plates"][0] + client.call("set_view", view_type="feature_type", layer_range=[1, 128]) + + # A click on the legend row and get_preview's legend are one state. The snapshot draws the legend + # first, since a window the desktop hides may not have drawn it since the slice. + client.call("ui_snapshot", query="Sparse infill") + client.call("ui_click", target={"imgui_name": "Sparse infill"}) + check("a legend row's click hides its feature type", legend()["features"]["Sparse infill"] is False) + client.call("set_view", view_type="speed") + check("the pick is remembered", last_view_type("speed") == "speed", last_view_type("speed")) + check("another view type keeps it hidden", legend()["features"]["Sparse infill"] is False) + client.call("set_view", view_type="feature_type") + check("picking Line Type shows it again", legend()["features"]["Sparse infill"] is True) + check("Line Type is remembered", last_view_type("feature_type") == "feature_type", last_view_type("feature_type")) + + reply = client.call("set_view", legend={"Sparse infill": False, "travel": True}, layer_z=1.05) + check("layer_z between two tops shows up to the upper one", reply.get("layers") == [1, 6, 128] and reply.get("z") == [0.2, 1.2], reply) + check("the legend reply gives each row's state", reply.get("legend") == {"Sparse infill": False, "travel": True}, reply) + + message = refusal(layer_z=80) + check("a height above the top layer is refused", "above the top layer (25.6 mm)" in message, message) + check("layer with layer_z is refused", "not both" in refusal(layer=3, layer_z=1.0)) + message = refusal(view_type="speed", legend={"Infill": False}) + check("an unknown row is refused with the print's rows", "Sparse infill" in message and "travel" in message, message) + check("a refused call leaves the view type", client.call("get_state")["preview"]["view_type"] == "feature_type") + check("a value that is not true or false is refused", "true (show) or false (hide)" in refusal(legend={"travel": "yes"})) + if "silent_time_s" not in sliced: + message = refusal(time_mode="silent") + check("silent mode without its own estimate is refused", "no separate silent-mode estimate" in message, message) + check("normal mode is always offered", client.call("set_view", time_mode="normal").get("time_mode") == "normal") + + client.call("dialog_auto_answer", rules=[]) + client.call("new_project", discard_changes=True) + failures = 0 + for name, ok, detail in checks: + print(("ok " if ok else "FAIL ") + name + ("" if ok or detail == "" else f": {detail}")) + failures += not ok + return 1 if failures else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/mcp/test_webview_modal.py b/tools/mcp/test_webview_modal.py new file mode 100644 index 0000000000..b74474b59a --- /dev/null +++ b/tools/mcp/test_webview_modal.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python3 +"""Checks where webview_eval runs while a modal dialog is open, where a script cannot look. + + tools/mcp/orca_mcp.py launch + tools/mcp/test_webview_modal.py + +Scripts run in the web view of the topmost modal dialog only when it is the setup wizard or a preset +bundle dialog: the Flushing volumes dialog is refused by name, so is the Home tab's web view behind a +modal and the bundle dialog's own web view once the export bundle dialog is above it; the export +dialog, topmost, takes scripts. A page that closes its dialog replies closed at once, not after the +timeout. Without a modal, the Home tab's web view still takes scripts. Exits 0 when every check +passes. +""" + +import os +import sys +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import orca_mcp # noqa: E402 + + +def main(): + client, _session = orca_mcp.session_client() + checks = [] + + def check(name, ok, detail=""): + checks.append((name, bool(ok), detail)) + + def refusal(**args): + try: + client.call("webview_eval", **args) + return "" + except orca_mcp.McpError as e: + return str(e) + + def dialogs(): + return [d["title"] for d in client.call("get_state")["dialogs"]] + + def wait_dialogs(count): + for _ in range(100): + if len(dialogs()) == count: + return True + time.sleep(0.1) + return False + + def home_webview(): + snap, texts = client.call_with_text("ui_snapshot", root="main", query="webview") + for line in (texts[0] if texts else "").splitlines(): + if "webview" in line and "[" in line: + return line.split("[", 1)[1].split("]", 1)[0] + return None + + client.call("new_project", discard_changes=True) + + # ---- The Home tab's web view, without and with a modal open ---- + client.call("set_view", tab="home") + home = home_webview() + check("the Home tab shows a web view", home is not None) + try: + value = client.call("webview_eval", script="1 + 1")["result"] + except orca_mcp.McpError as e: + value = str(e) + check("without a modal, the only web view takes a script", value == 2, value) + bundle = client.call("run_action", id="orca_command:preset_bundle:orca") + check("the bundle dialog opens", wait_dialogs(1), dialogs()) + message = refusal(script="1", target=home) + check("a web view behind the modal is refused", "modal dialog is open" in message, message) + check("the bundle dialog's page takes a script", client.call("webview_eval", script="document.title")["result"] == "Preset Bundle") + + # ---- A bundle dialog under the export bundle dialog ---- + client.call("webview_eval", script="SendWXMessage(JSON.stringify({command: 'export_page'}))") + check("the export bundle dialog opens above it", wait_dialogs(2), dialogs()) + message = refusal(script="1", target={"class": "webview", "within": "Preset Bundle"}) + check("the dialog under the topmost is refused", "is under" in message, message) + url = client.call("webview_eval", script="1")["url"] + check("without a target the topmost dialog's page is used", "ExportPresetDialog" in url, url) + client.call("dialog_respond", button="close") + check("the export dialog closes", wait_dialogs(1), dialogs()) + + # ---- A page that closes its dialog replies at once ---- + start = time.time() + reply = client.call("webview_eval", script="document.getElementById('close_btn').click()") + elapsed = time.time() - start + check("closing the dialog from its page replies closed", reply.get("closed") is True, reply) + check("and does so within a second", elapsed < 1.0, f"{elapsed:.2f} s") + client.await_job(bundle) + check("no dialog is left", wait_dialogs(0), dialogs()) + + # ---- The Flushing volumes dialog is not on the list ---- + client.call("set_view", tab="prepare") + client.call("ui_click", target={"label": "Add one filament"}) + flush = client.call("ui_click", target={"label": "Flushing volumes"}) + check("the Flushing volumes dialog opens", wait_dialogs(1), dialogs()) + message = refusal(script="document.title") + check("its page is refused", "only in the setup wizard and the preset bundle dialogs" in message, message) + client.call("dialog_respond", button="close") + client.await_job(flush) + check("no dialog is left at the end", wait_dialogs(0), dialogs()) + + failed = [c for c in checks if not c[1]] + for name, ok, detail in checks: + print(("PASS " if ok else "FAIL ") + name + ("" if ok or detail == "" else f": {detail}")) + print(f"{len(checks) - len(failed)}/{len(checks)} checks passed") + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/mcp/test_worker_admission.py b/tools/mcp/test_worker_admission.py new file mode 100755 index 0000000000..d721d34743 --- /dev/null +++ b/tools/mcp/test_worker_admission.py @@ -0,0 +1,94 @@ +#!/usr/bin/env python3 +"""Checks that a background job an MCP call starts holds the project until the UI job worker is idle. + + tools/mcp/orca_mcp.py launch + tools/mcp/test_worker_admission.py + +Fills the bed with small cubes, so an arrange with rotation runs for many seconds, and starts it three +ways: the typed `arrange`, `run_action obj_arrange`, and a click on the Arrange options panel's +Arrange button, a recover input. While each runs, a `transform`, `ui_key Delete` on the canvas and a +GL toolbar click are refused and `list_objects` answers; `cancel` stops it, the call reports it +cancelled, and a change is admitted once the worker is idle. Exits 0 when every check passes. +""" + +import os +import sys +import threading +import time + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import orca_mcp # noqa: E402 + +# The typed arrange goes first: the rotation it saves, as the panel's checkbox does, makes the +# others slow too. +STARTERS = { + "arrange": ("arrange", {"rotate": True}), + "run_action": ("run_action", {"id": "orca_command:obj_arrange:orca"}), + "ui_click": ("ui_click", {"target": {"imgui": "Arrange", "window": "Arrange options"}}), +} + + +def client(): + c, _ = orca_mcp.session_client() + c.initialize() + return c + + +def attempt(c, tool, **args): + try: + return True, c.call(tool, **args) + except orca_mcp.McpError as e: + return False, str(e) + + +def main(): + c = client() + failures = [] + + def check(name, ok, detail=""): + print(("PASS " if ok else "FAIL ") + name + ("" if ok else " " + str(detail)[:300])) + if not ok: + failures.append(name) + + c.call("wait", **{"for": "ready", "timeout_s": 50}) + c.call("new_project", discard_changes=True) + c.call("set_view", tab="prepare") + for size in ["6 6 6", "4 9 5", "7 3 5"]: + c.call("select", none=True) + c.call("run_action", id="orca_command:add_primitive_cube:orca", param=size) + for o in range(3): + c.call("arrange", fill=o, spacing=0, rotate=False) + + for name, (tool, args) in STARTERS.items(): + if name == "ui_click" and c.call("ui_snapshot", query="Arrange options", include_menus=False).get("nodes", 0) == 0: + c.call("ui_click", target={"gltoolbar": "arrange"}) + out = {} + + def run(): + out["reply"] = attempt(client(), tool, **args) + + starter = threading.Thread(target=run) + starter.start() + time.sleep(2.0) + ok, reply = attempt(c, "transform", object=0, translate=[1, 0, 0]) + check(name + ": transform refused", not ok and "Busy: job" in reply, reply) + ok, reply = attempt(c, "list_objects", limit=1) + check(name + ": list_objects answers", ok, reply) + ok, reply = attempt(c, "ui_key", keys="Delete") + check(name + ": ui_key Delete refused", not ok and "Busy: job" in reply, reply) + ok, reply = attempt(c, "ui_click", target={"gltoolbar": "orient"}) + check(name + ": GL toolbar click refused", not ok and "Busy: job" in reply, reply) + ok, reply = attempt(c, "cancel") + check(name + ": cancel stops it", ok and reply.get("was_running") and reply.get("job"), reply) + starter.join(300) + ok, reply = out.get("reply", (True, None)) + check(name + ": the call reports it cancelled", not ok and "cancelled" in reply, reply) + ok, reply = attempt(c, "transform", object=0, translate=[-1, 0, 0]) + check(name + ": a change is admitted afterwards", ok, reply) + + print("%d failed" % len(failures) if failures else "all passed") + return 1 if failures else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/mcp/tests/cad_canvas.json b/tools/mcp/tests/cad_canvas.json new file mode 100644 index 0000000000..ce1511e94e --- /dev/null +++ b/tools/mcp/tests/cad_canvas.json @@ -0,0 +1,67 @@ +// The Design view as a canvas target. set_view shows the Design tab and points its camera, and +// refuses what belongs to Prepare and Preview; a canvas screenshot captures the Design view, as does +// one of its widget. A click at the view's centre picks the block, and a right click lists the verbs +// for what is picked. Keys reach the Design panel's own key hook: Shift+E opens the Extrude card and +// Escape, sent with no target, closes it, so a change is no longer refused. Then a change made only +// in the Design tab marks the project modified, and opening a design-only project with +// discard_changes asks nothing and names the project after its file. +// Needs the CAD feature on: +// tools/mcp/orca_mcp.py launch --cad +// tools/mcp/orca_mcp.py run-script tools/mcp/tests/cad_canvas.json --out /tmp/out +{ + "orca_script": 1, + "name": "cad canvas", + "steps": [ + {"tool": "wait", "args": {"for": "ready"}}, + {"tool": "new_project", "args": {"discard_changes": true}}, + {"tool": "cad_call", "args": {"method": "new_design", "params": {"discard_changes": true}}}, + {"tool": "set_view", "args": {"tab": "design", "camera": "iso", "window_size": [1200, 800]}, + "expect": {"/tab": {"eq": "design"}, "/camera": {"eq": "iso"}}}, + {"tool": "cad_call", "args": {"method": "extrude", "params": {"width": 20, "height": 20, "distance": 10}}, + "expect": {"/result/ok": {"eq": true}}}, + // The Design view has no gizmos, and a change made only in the Design tab marks the project. + {"tool": "get_state", "expect": {"/tab": {"eq": "design"}, "/gizmo": {"eq": null}, "/project/dirty": {"eq": true}}}, + // Refused: Prepare's fit to bed, a fit to the selection with nothing picked, the Preview's layers. + {"tool": "set_view", "args": {"camera": "fit_bed"}, "optional": true}, + {"tool": "set_view", "args": {"camera": "fit_selection"}, "optional": true}, + {"tool": "set_view", "args": {"tab": "design", "layer": 2}, "optional": true}, + {"tool": "set_view", "args": {"camera": "default"}, "expect": {"/camera": {"eq": "default"}}}, + {"tool": "screenshot", "args": {"target": "canvas", "include_image": false, "save_path": "${out_dir}/design_canvas.png", "overwrite": true}, + "expect": {"/source": {"eq": "canvas"}, "/approximate": {"exists": false}, "/width": {"gt": 0}}}, + {"tool": "screenshot", "args": {"target": {"class": "wxGLCanvas"}, "include_image": false, "save_path": "${out_dir}/design_view.png", "overwrite": true}, + "expect": {"/approximate": {"exists": false}, "/width": {"gt": 0}}}, + {"tool": "screenshot", "args": {"target": "window", "include_image": false, "save_path": "${out_dir}/design_window.png", "overwrite": true}, + "expect": {"/width": {"gt": 0}}}, + {"tool": "ui_snapshot", "args": {"query": "OrcaSceneCanvas"}, "expect": {"/nodes": {"eq": 1}}}, + + // A click at the view's centre picks the block; a right click away from it lists the verbs for + // the pick, without showing the menu. + {"tool": "ui_click", "args": {"target": {"class": "wxGLCanvas"}}, "expect": {"/clicked": {"eq": "canvas"}}}, + {"tool": "ui_mouse", "args": {"canvas": "design", "action": "click", "button": "right", "x": 30, "y": 30}, + "expect": {"/canvas": {"eq": "design"}, "/popup_menu/items/0": {"regex": "of Extrude"}}}, + {"tool": "set_view", "args": {"camera": "fit_selection"}, "expect": {"/camera": {"eq": "fit_selection"}}}, + // Points of the model name Prepare's objects, so the Design view takes pixels only. + {"tool": "ui_mouse", "args": {"canvas": "design", "action": "click", "at": {"object": 0, "spot": "top"}}, "optional": true}, + + // Shift+E is the Design tab's Extrude; Escape with no target closes the card it opened. + {"tool": "ui_key", "args": {"keys": "Shift+E"}}, + {"tool": "ui_snapshot", "args": {"query": "Extrude dist"}, "expect": {"/nodes": {"eq": 1}}}, + {"tool": "ui_key", "args": {"keys": "Escape"}}, + {"tool": "ui_snapshot", "args": {"query": "Extrude dist"}, "expect": {"/nodes": {"eq": 0}}}, + {"tool": "cad_call", "args": {"method": "extrude", "params": {"width": 6, "height": 6, "distance": 20}}, + "expect": {"/result/ok": {"eq": true}}}, + + // A design-only project: saved, changed in the Design tab alone, then opened again. + {"tool": "save_project", "args": {"path": "${out_dir}/design_only.3mf", "overwrite": true}}, + {"tool": "get_state", "expect": {"/project/dirty": {"eq": false}, "/project/name": {"eq": "design_only"}}}, + {"tool": "cad_call", "args": {"method": "set_variable", "params": {"name": "w", "expr": "5"}}, "expect": {"/result/ok": {"eq": true}}}, + {"tool": "get_state", "expect": {"/project/dirty": {"eq": true}}}, + {"tool": "open_files", "args": {"paths": ["${out_dir}/design_only.3mf"]}, "optional": true}, + {"tool": "open_files", "args": {"paths": ["${out_dir}/design_only.3mf"], "discard_changes": true}, + "expect": {"/opened": {"eq": "project"}, "/objects": {"eq": 0}}}, + {"tool": "get_state", "expect": {"/project/dirty": {"eq": false}, "/project/name": {"eq": "design_only"}, + "/project/path": {"regex": "design_only\\.3mf$"}, "/dialogs": {"empty": true}}}, + {"tool": "cad_call", "args": {"method": "describe_scene"}, + "expect": {"/result/variables": {"empty": true}, "/result/bodies/1": {"exists": true}}} + ] +} diff --git a/tools/mcp/tests/cad_doc.json b/tools/mcp/tests/cad_doc.json new file mode 100644 index 0000000000..68ece5fb28 --- /dev/null +++ b/tools/mcp/tests/cad_doc.json @@ -0,0 +1,148 @@ +// Reads and edits a Design-tab feature as its card does: a variable bound to an extrude, the +// binding and the variable removed, then literal edits through set_feature, checked by volume. +// Then hands the design off: Commit to Plate, a recommit that replaces the first object (one +// Prepare undo step), a STEP export read back into a new design, and two bodies committed both ways. +// Last, the Design history and the tree: undo / redo of an edit and of a rename (its own step), +// hiding, moving and deleting features, naming, hiding and colouring bodies (a hidden body stays +// off the plate, a named one names its object), and a save and reopen that keeps the colour. +// Needs the CAD feature on: +// tools/mcp/orca_mcp.py launch --cad +// tools/mcp/orca_mcp.py run-script tools/mcp/tests/cad_doc.json --out /tmp/out +{ + "orca_script": 1, + "name": "cad document", + "steps": [ + {"tool": "wait", "args": {"for": "ready"}}, + {"tool": "new_project", "args": {"discard_changes": true}}, + {"tool": "cad_call", "args": {"method": "new_design"}, "expect": {"/result/ok": {"eq": true}, "/result/cleared/features": {"eq": 0}}}, + {"tool": "cad_call", "args": {"method": "describe_tools", "params": {"method": ["describe_feature", "set_feature"]}}, + "expect": {"/result/tools/0/access": {"eq": "read"}, "/result/tools/1/access": {"eq": "change"}}}, + {"tool": "cad_call", "args": {"method": "extrude", "params": {"width": 20, "height": 20, "distance": 10}}, + "expect": {"/result/ok": {"eq": true}, "/result/extrude_index": {"eq": 1}}}, + {"tool": "cad_call", "args": {"method": "set_variable", "params": {"name": "h", "expr": "12"}}, + "expect": {"/result/ok": {"eq": true}}}, + {"tool": "cad_call", "args": {"method": "set_feature_expr", "params": {"feature": 1, "field": "distance", "expr": "h"}}, + "expect": {"/result/ok": {"eq": true}}}, + {"tool": "cad_call", "args": {"method": "describe_scene"}, + "expect": {"/result/variables/0/name": {"eq": "h"}, "/result/variables/0/value": {"eq": 12.0}, + "/result/features/1/bound/0": {"eq": "distance"}, "/result/bodies/0/source_feature": {"eq": 1}, + "/result/bodies/0/visible": {"eq": true}, "/result/bodies/0/moved": {"eq": false}, + "/result/bodies/0/color": {"regex": "^#[0-9A-F]{6}$"}, "/result/undo_depth": {"eq": 3}}}, + {"tool": "cad_call", "args": {"method": "describe_feature", "params": {"feature": 1}}, + "expect": {"/result/type": {"eq": "Extrude"}, "/result/params/distance": {"eq": 12.0}, "/result/expr/distance": {"eq": "h"}, + "/result/refs/sketch_ref": {"eq": 0}, "/result/bodies_made/0": {"eq": 0}, "/result/editable": {"contains": "distance"}}}, + {"tool": "cad_call", "args": {"method": "describe_feature", "params": {"feature": 0}}, + "expect": {"/result/type": {"eq": "Sketch"}, "/result/params/width": {"eq": 20.0}, "/result/plane/base": {"eq": "XY"}, + "/result/used_by/0": {"eq": 1}}}, + {"tool": "cad_call", "args": {"method": "set_feature_expr", "params": {"feature": 1, "field": "distance", "expr": ""}}, + "expect": {"/result/ok": {"eq": true}}}, + {"tool": "cad_call", "args": {"method": "set_variable", "params": {"name": "h", "expr": ""}}, + "expect": {"/result/ok": {"eq": true}, "/result/removed": {"eq": true}}}, + {"tool": "cad_call", "args": {"method": "describe_scene"}, + "expect": {"/result/variables": {"empty": true}, "/result/features/1/bound": {"exists": false}}}, + {"tool": "cad_call", "args": {"method": "set_feature", "params": {"feature": 1, "fields": {"distance": 15}}}, + "expect": {"/result/ok": {"eq": true}, "/result/changed/distance/0": {"eq": 12.0}, "/result/changed/distance/1": {"eq": 15.0}}}, + {"tool": "cad_call", "args": {"method": "mass_properties", "params": {"body": 0}}, + "expect": {"/result/volume": {"ge": 5999.99, "le": 6000.01}}}, + {"tool": "cad_call", "args": {"method": "set_feature", "params": {"feature": 0, "fields": {"width": 30}}}, + "expect": {"/result/changed/width/1": {"eq": 30.0}}}, + {"tool": "cad_call", "args": {"method": "mass_properties", "params": {"body": 0}}, + "expect": {"/result/volume": {"ge": 8999.99, "le": 9000.01}}}, + {"tool": "cad_call", "args": {"method": "sketch_begin", "params": {"plane": "XY"}}}, + {"tool": "cad_call", "args": {"method": "sketch_add", "params": {"rect": [40, 0, 60, 10]}}}, + {"tool": "cad_call", "args": {"method": "sketch_heal"}}, + {"tool": "cad_call", "args": {"method": "sketch_commit"}, "expect": {"/result/features": {"eq": 3}}}, + {"tool": "cad_call", "args": {"method": "describe_feature", "params": {"feature": 2}}, + "expect": {"/result/entities/0/type": {"eq": "line"}, "/result/entities/3/type": {"eq": "line"}, + "/result/editable": {"empty": true}}}, + {"tool": "cad_call", "args": {"method": "commit"}, + "expect": {"/result/objects/0/index": {"eq": 0}, "/result/objects/0/name": {"eq": "Design Body"}, + "/result/objects/0/volumes": {"eq": 1}, "/result/bodies_sent/0": {"eq": 0}, "/result/tab": {"eq": "prepare"}}}, + {"tool": "list_objects", "expect": {"/total": {"eq": 1}, "/items/0/name": {"eq": "Design Body"}, + "/items/0/bbox/size/2": {"ge": 14.99, "le": 15.01}}}, + {"tool": "cad_call", "args": {"method": "set_feature", "params": {"feature": 1, "fields": {"distance": 20}}}}, + {"tool": "cad_call", "args": {"method": "commit", "params": {"replace": [0]}}, + "expect": {"/result/objects/0/index": {"eq": 0}, "/result/replaced/0/index": {"eq": 0}, "/result/replaced/0/name": {"eq": "Design Body"}}}, + {"tool": "list_objects", "expect": {"/total": {"eq": 1}, "/items/0/bbox/size/2": {"ge": 19.99, "le": 20.01}}}, + {"tool": "run_action", "args": {"id": "orca_command:undo:orca"}}, + {"tool": "list_objects", "expect": {"/total": {"eq": 1}, "/items/0/bbox/size/2": {"ge": 14.99, "le": 15.01}}}, + {"tool": "cad_call", "args": {"method": "export_step", "params": {"path": "${out_dir}/design.step", "overwrite": true}}, + "expect": {"/result/bytes": {"gt": 0}, "/result/bodies": {"eq": 1}, "/result/moved_bodies": {"empty": true}}}, + {"tool": "cad_call", "args": {"method": "new_design", "params": {"discard_changes": true}}, + "expect": {"/result/cleared/features": {"eq": 3}, "/result/cleared/bodies": {"eq": 1}}}, + {"tool": "cad_call", "args": {"method": "import_step", "params": {"path": "${out_dir}/design.step"}}, + "expect": {"/result/ok": {"eq": true}, "/result/bodies": {"eq": 1}}}, + {"tool": "cad_call", "args": {"method": "mass_properties", "params": {"body": 0}}, + "expect": {"/result/volume": {"ge": 11998.8, "le": 12001.2}}}, + {"tool": "cad_call", "args": {"method": "extrude", "params": {"profile": [[40, 0], [50, 0], [50, 10], [40, 10]], "distance": 5}}, + "expect": {"/result/bodies": {"eq": 2}}}, + {"tool": "cad_call", "args": {"method": "commit", "params": {"mode": "bodies"}}, + "expect": {"/result/mode": {"eq": "bodies"}, "/result/objects/0/index": {"eq": 1}, "/result/objects/1/index": {"eq": 2}, + "/result/objects/1/name": {"eq": "Design Body 2"}, "/result/bodies_sent/1": {"eq": 1}, "/result/bodies_hidden": {"empty": true}}}, + {"tool": "cad_call", "args": {"method": "commit", "params": {"mode": "assembly"}}, + "expect": {"/result/objects/0/index": {"eq": 3}, "/result/objects/0/name": {"eq": "Design Assembly"}, "/result/objects/0/volumes": {"eq": 2}}}, + {"tool": "list_objects", "expect": {"/total": {"eq": 4}}}, + + {"tool": "cad_call", "args": {"method": "new_design", "params": {"discard_changes": true}}}, + {"tool": "cad_call", "args": {"method": "extrude", "params": {"width": 20, "height": 20, "distance": 10}}, + "expect": {"/result/extrude_index": {"eq": 1}}}, + {"tool": "cad_call", "args": {"method": "set_feature", "params": {"feature": 1, "fields": {"distance": 15}}}}, + {"tool": "cad_call", "args": {"method": "undo"}, + "expect": {"/result/scope": {"eq": "design"}, "/result/undo_depth": {"eq": 1}, "/result/redo_depth": {"eq": 1}}}, + {"tool": "cad_call", "args": {"method": "describe_feature", "params": {"feature": 1}}, "expect": {"/result/params/distance": {"eq": 10.0}}}, + {"tool": "cad_call", "args": {"method": "redo"}, "expect": {"/result/redo_depth": {"eq": 0}}}, + {"tool": "cad_call", "args": {"method": "describe_feature", "params": {"feature": 1}}, "expect": {"/result/params/distance": {"eq": 15.0}}}, + {"tool": "cad_call", "args": {"method": "extrude", "params": {"profile": [[40, 0], [50, 0], [50, 10], [40, 10]], "distance": 5}}, + "expect": {"/result/extrude_index": {"eq": 3}, "/result/bodies": {"eq": 2}}}, + {"tool": "cad_call", "args": {"method": "feature_rename", "params": {"feature": 1, "name": " Base "}}, + "expect": {"/result/name": {"eq": "Base"}, "/result/changed": {"eq": true}, "/result/undo_depth": {"eq": 4}}}, + {"tool": "cad_call", "args": {"method": "undo"}, "expect": {"/result/undo_depth": {"eq": 3}}}, + {"tool": "cad_call", "args": {"method": "describe_scene"}, + "expect": {"/result/features/1/name": {"regex": "^Extrude \\d+$"}, "/result/features/3": {"exists": true}, "/result/features/4": {"exists": false}}}, + {"tool": "cad_call", "args": {"method": "describe_feature", "params": {"feature": 1}}, "expect": {"/result/params/distance": {"eq": 15.0}}}, + {"tool": "cad_call", "args": {"method": "redo"}}, + {"tool": "cad_call", "args": {"method": "describe_scene"}, "expect": {"/result/features/1/name": {"eq": "Base"}}}, + {"tool": "cad_call", "args": {"method": "feature_set_enabled", "params": {"feature": 3, "enabled": false}}, + "expect": {"/result/changed": {"eq": true}, "/result/bodies": {"eq": 1}}}, + {"tool": "cad_call", "args": {"method": "feature_set_enabled", "params": {"feature": 3, "enabled": false}}, + "expect": {"/result/changed": {"eq": false}, "/result/bodies": {"eq": 1}}}, + {"tool": "cad_call", "args": {"method": "feature_set_enabled", "params": {"feature": 3, "enabled": true}}, + "expect": {"/result/bodies": {"eq": 2}}}, + {"tool": "cad_call", "args": {"method": "feature_move", "params": {"feature": 2, "delta": -1}}, + "expect": {"/result/feature": {"eq": 1}, "/result/from": {"eq": 2}, "/result/bodies": {"eq": 2}}}, + {"tool": "cad_call", "args": {"method": "describe_scene"}, + "expect": {"/result/features/1/type": {"eq": "Sketch"}, "/result/features/2/name": {"eq": "Base"}}}, + {"tool": "cad_call", "args": {"method": "undo"}}, + {"tool": "cad_call", "args": {"method": "describe_scene"}, "expect": {"/result/features/1/name": {"eq": "Base"}}}, + {"tool": "cad_call", "args": {"method": "body_set", "params": {"body": 1, "name": "Lid", "visible": false}}, + "expect": {"/result/name": {"eq": "Lid"}, "/result/visible": {"eq": false}}}, + {"tool": "cad_call", "args": {"method": "describe_scene"}, + "expect": {"/result/bodies/1/name": {"eq": "Lid"}, "/result/bodies/1/user_name": {"eq": true}, "/result/bodies/1/visible": {"eq": false}}}, + {"tool": "cad_call", "args": {"method": "commit"}, + "expect": {"/result/bodies_sent/1": {"exists": false}, "/result/bodies_sent/0": {"eq": 0}, "/result/bodies_hidden/0": {"eq": 1}}}, + {"tool": "cad_call", "args": {"method": "body_set", "params": {"body": 1, "visible": true}}, "expect": {"/result/visible": {"eq": true}}}, + {"tool": "cad_call", "args": {"method": "body_set", "params": {"body": 0, "visible": false}}}, + {"tool": "cad_call", "args": {"method": "commit", "params": {"mode": "bodies"}}, + "expect": {"/result/objects/0/name": {"eq": "Lid"}, "/result/bodies_sent/0": {"eq": 1}, "/result/bodies_hidden/0": {"eq": 0}}}, + {"tool": "cad_call", "args": {"method": "body_set", "params": {"body": 0, "visible": true}}}, + {"tool": "cad_call", "args": {"method": "body_delete", "params": {"body": 1}}, + "expect": {"/result/deleted_feature/index": {"eq": 3}, "/result/deleted_feature/type": {"eq": "Extrude"}, + "/result/removed": {"eq": 1}, "/result/features": {"eq": 3}, "/result/bodies": {"eq": 1}}}, + {"tool": "cad_call", "args": {"method": "undo"}, "expect": {"/result/bodies": {"eq": 2}}}, + {"tool": "cad_call", "args": {"method": "describe_scene"}, "expect": {"/result/bodies/1/source_feature": {"eq": 3}}}, + {"tool": "cad_call", "args": {"method": "feature_delete", "params": {"feature": 0}}, + "expect": {"/result/removed": {"eq": 2}, "/result/features": {"eq": 2}, "/result/bodies": {"eq": 1}}}, + {"tool": "cad_call", "args": {"method": "undo"}, "expect": {"/result/features": {"eq": 4}, "/result/bodies": {"eq": 2}}}, + {"tool": "cad_call", "args": {"method": "body_set", "params": {"body": 1, "name": "Lid"}}}, + {"tool": "cad_call", "args": {"method": "body_set", "params": {"body": 1, "color": "#3080ff"}}, + "expect": {"/result/color": {"eq": "#3080FF"}}}, + {"tool": "save_project", "args": {"path": "${out_dir}/design.3mf", "overwrite": true}}, + {"tool": "new_project", "args": {"discard_changes": true}}, + // Presets an earlier session modified make loading a project ask about them; the rule ends with the script. + {"tool": "dialog_auto_answer", "args": {"rules": [{"match": "Load project: unsaved changes", "button": "Discard"}]}}, + {"tool": "open_files", "args": {"paths": ["${out_dir}/design.3mf"]}}, + {"tool": "cad_call", "args": {"method": "describe_scene"}, + "expect": {"/result/features/3": {"exists": true}, "/result/features/4": {"exists": false}, "/result/bodies/1/name": {"eq": "Lid"}, + "/result/bodies/1/has_color": {"eq": true}, "/result/bodies/1/color": {"eq": "#3080FF"}}} + ] +} diff --git a/tools/mcp/tests/cad_features.json b/tools/mcp/tests/cad_features.json new file mode 100644 index 0000000000..2d90bfd2f9 --- /dev/null +++ b/tools/mcp/tests/cad_features.json @@ -0,0 +1,97 @@ +// Threads, sweeps, lofts and plane splits through cad_call. The bench's M5 hex standoff tapped on its +// bore (the size inferred from the bore, as the Thread card infers it) and again on the XY plane; a +// spring swept along a helix, round and square wire; a square-to-circle loft between the XY plane and +// a datum plane, then split by that datum and by XY turned over. Refused calls change nothing. Face +// ids are this build's; no step reads a world position that depends on the printer's bed. +// Needs the CAD feature on: +// tools/mcp/orca_mcp.py launch --cad +// tools/mcp/orca_mcp.py run-script tools/mcp/tests/cad_features.json --out /tmp/out +{ + "orca_script": 1, + "name": "cad thread sweep loft split", + "steps": [ + {"tool": "wait", "args": {"for": "ready"}}, + {"tool": "new_project", "args": {"discard_changes": true}}, + {"tool": "cad_call", "args": {"method": "new_design", "params": {"discard_changes": true}}}, + + // M5 hex standoff: 8 mm across flats, 15 long, M5's 4.134 mm tap drill through it. + {"tool": "cad_call", "args": {"method": "extrude", "params": {"distance": 15, + "profile": [[4.618802, 0], [2.309401, 4], [-2.309401, 4], [-4.618802, 0], [-2.309401, -4], [2.309401, -4]]}}, + "expect": {"/result/ok": {"eq": true}}}, + {"tool": "cad_call", "args": {"method": "hole", "params": {"diameter": 4.134, "through": true}}, "expect": {"/result/ok": {"eq": true}}}, + {"tool": "cad_call", "args": {"method": "query_topology", "params": {"kinds": ["cylindrical"]}}, + "expect": {"/result/faces_total": {"eq": 1}, "/result/faces/0/id": {"eq": 8}, "/result/faces/0/internal": {"eq": true}}}, + // A planar face cannot be threaded, and a designation not in the tables names the close ones. + {"tool": "cad_call", "args": {"method": "thread", "params": {"face": 0}}, "optional": true}, + {"tool": "cad_call", "args": {"method": "thread", "params": {"face": 8, "designation": "M5x1"}}, "optional": true}, + // The bore: M5 inferred from its 4.134 mm minor diameter, internal, the bore's whole 15 mm. + {"tool": "cad_call", "args": {"method": "thread", "params": {"face": 8}}, + "expect": {"/result/thread_index": {"eq": 3}, "/result/designation": {"eq": "M5"}, "/result/internal": {"eq": true}, + "/result/pitch": {"ge": 0.7999, "le": 0.8001}, "/result/length": {"ge": 14.9999, "le": 15.0001}, + "/result/body": {"eq": 0}, "/result/bodies": {"eq": 1}}}, + // The bench case's bounds. + {"tool": "cad_call", "args": {"method": "mass_properties", "params": {"body": 0}}, + "expect": {"/result/is_solid": {"eq": true}, "/result/volume": {"gt": 600.0, "lt": 614.0}}}, + {"tool": "cad_call", "args": {"method": "describe_scene"}, "expect": {"/result/features/3/type": {"eq": "Thread"}, "/result/undo_depth": {"eq": 3}}}, + // The same thread placed on the XY plane, on the bore's axis. + {"tool": "cad_call", "args": {"method": "undo"}, "expect": {"/result/features": {"eq": 3}}}, + {"tool": "cad_call", "args": {"method": "thread", "params": {"plane": "XY", "designation": "M5", "internal": true, "length": 15}}, + "expect": {"/result/x": {"eq": 0.0}, "/result/y": {"eq": 0.0}, "/result/body": {"eq": 0}, "/result/designation": {"eq": "M5"}}}, + {"tool": "cad_call", "args": {"method": "mass_properties", "params": {"body": 0}}, + "expect": {"/result/volume": {"gt": 600.0, "lt": 614.0}}}, + + // A spring: a helix of radius 10, pitch 5, six turns; a 1.5 mm wire drawn across its start on XZ. + {"tool": "cad_call", "args": {"method": "new_design", "params": {"discard_changes": true}}}, + {"tool": "cad_call", "args": {"method": "helix", "params": {"radius": 10, "pitch": 5, "height": 30}}, + "expect": {"/result/helix_index": {"eq": 0}, "/result/tangent/1": {"ge": 0.9968, "le": 0.9969}, "/result/tangent/2": {"ge": 0.0793, "le": 0.0794}}}, + {"tool": "cad_call", "args": {"method": "sketch_begin", "params": {"plane": "XZ"}}}, + {"tool": "cad_call", "args": {"method": "sketch_add", "params": {"type": "circle", "center": [10, 0], "radius": 1.5}}}, + {"tool": "cad_call", "args": {"method": "sketch_commit"}, "expect": {"/result/sketch_index": {"eq": 1}}}, + {"tool": "cad_call", "args": {"method": "sweep", "params": {"sketch": 1, "path": 0}}, + "expect": {"/result/sweep_index": {"eq": 2}, "/result/body": {"eq": 0}, "/result/boolean": {"eq": "new"}}}, + // pi 1.5^2 x the helix's 378.19 mm x 0.99685, the XZ plane's tilt off the helix's normal plane. + {"tool": "cad_call", "args": {"method": "mass_properties", "params": {"body": 0}}, + "expect": {"/result/is_solid": {"eq": true}, "/result/volume": {"gt": 2638.0, "lt": 2691.0}}}, + // A square wire beside it, 2 x 2. + {"tool": "cad_call", "args": {"method": "sketch_begin", "params": {"plane": "XZ"}}}, + {"tool": "cad_call", "args": {"method": "sketch_add", "params": {"rect": [9, -1, 11, 1]}}}, + {"tool": "cad_call", "args": {"method": "sketch_commit"}, "expect": {"/result/sketch_index": {"eq": 3}}}, + // A sweep is not a path. + {"tool": "cad_call", "args": {"method": "sweep", "params": {"sketch": 3, "path": 2}}, "optional": true}, + {"tool": "cad_call", "args": {"method": "sweep", "params": {"sketch": 3, "path": 0}}, + "expect": {"/result/sweep_index": {"eq": 4}, "/result/body": {"eq": 1}, "/result/bodies": {"eq": 2}}}, + {"tool": "cad_call", "args": {"method": "mass_properties", "params": {"body": 1}}, + "expect": {"/result/is_solid": {"eq": true}, "/result/volume": {"gt": 1492.0, "lt": 1524.0}}}, + + // A loft from a 20 mm square on XY to an 8 mm circle on a datum plane 40 above it. + {"tool": "cad_call", "args": {"method": "new_design", "params": {"discard_changes": true}}}, + {"tool": "cad_call", "args": {"method": "plane", "params": {"type": "offset", "base": "XY", "offset": 40}}, "expect": {"/result/plane_index": {"eq": 0}}}, + {"tool": "cad_call", "args": {"method": "sketch_begin", "params": {"plane": "XY"}}}, + {"tool": "cad_call", "args": {"method": "sketch_add", "params": {"rect": [-10, -10, 10, 10]}}}, + {"tool": "cad_call", "args": {"method": "sketch_commit"}, "expect": {"/result/sketch_index": {"eq": 1}}}, + {"tool": "cad_call", "args": {"method": "sketch_begin", "params": {"plane": {"datum": 0}}}}, + {"tool": "cad_call", "args": {"method": "sketch_add", "params": {"type": "circle", "center": [0, 0], "radius": 8}}}, + {"tool": "cad_call", "args": {"method": "sketch_commit"}, "expect": {"/result/sketch_index": {"eq": 2}}}, + {"tool": "cad_call", "args": {"method": "loft", "params": {"profiles": [1]}}, "optional": true}, + {"tool": "cad_call", "args": {"method": "loft", "params": {"profiles": [1, 0]}}, "optional": true}, + {"tool": "cad_call", "args": {"method": "loft", "params": {"profiles": [1, 2]}}, + "expect": {"/result/loft_index": {"eq": 3}, "/result/body": {"eq": 0}, "/result/bodies": {"eq": 1}}}, + {"tool": "cad_call", "args": {"method": "mass_properties", "params": {"body": 0}}, + "expect": {"/result/is_solid": {"eq": true}, "/result/volume": {"gt": 11850.0, "lt": 11861.0}}}, + + // Split by the datum plane 20 below it: the upper half stays body 0, the lower one is body 1. + {"tool": "cad_call", "args": {"method": "split", "params": {"plane": {"datum": 0}, "offset": 60}}, "optional": true}, + {"tool": "cad_call", "args": {"method": "split", "params": {"plane": {"datum": 0}, "offset": -20}}, + "expect": {"/result/split_index": {"eq": 4}, "/result/upper_body": {"eq": 0}, "/result/lower_body": {"eq": 1}, + "/result/bodies": {"eq": 2}, "/result/frame/normal/2": {"eq": 1.0}}}, + {"tool": "cad_call", "args": {"method": "describe_scene"}, + "expect": {"/result/features/4/type": {"eq": "Cut"}, "/result/bodies/0/bbox/min/2": {"ge": 19.999, "le": 20.001}, + "/result/bodies/1/bbox/max/2": {"ge": 19.999, "le": 20.001}}}, + // The lower half, by XY at 10 turned over, keeping only the side toward the bed. + {"tool": "cad_call", "args": {"method": "split", "params": {"body": 1, "plane": "XY", "offset": 10, "flip": true, "keep_lower": false}}, + "expect": {"/result/upper_body": {"eq": 1}, "/result/bodies": {"eq": 2}, "/result/frame/normal/2": {"eq": -1.0}}}, + {"tool": "cad_call", "args": {"method": "describe_scene"}, + "expect": {"/result/bodies/1/bbox/min/2": {"ge": -0.001, "le": 0.001}, "/result/bodies/1/bbox/max/2": {"ge": 9.999, "le": 10.001}, + "/result/undo_depth": {"eq": 6}}} + ] +} diff --git a/tools/mcp/tests/cad_sketch_edit.json b/tools/mcp/tests/cad_sketch_edit.json new file mode 100644 index 0000000000..4426b29509 --- /dev/null +++ b/tools/mcp/tests/cad_sketch_edit.json @@ -0,0 +1,107 @@ +// The sketch's own tools through cad_call: shapes drawn by their drawing tools (polygon, slot, +// ellipse, spline), the edit tools (trim, extend, chamfer, fillet, move, rotate, linear and polar +// arrays) and the CONSTRAIN bar (constraints from picks and from named points, one refused, one +// deleted), each read back from the sketch and from the solid it is extruded into. Sketch +// coordinates only, so it replays on any printer. Refused calls change nothing. +// Needs the CAD feature on: +// tools/mcp/orca_mcp.py launch --cad +// tools/mcp/orca_mcp.py run-script tools/mcp/tests/cad_sketch_edit.json --out /tmp/out +{ + "orca_script": 1, + "name": "cad sketch edit", + "steps": [ + {"tool": "wait", "args": {"for": "ready"}}, + {"tool": "new_project", "args": {"discard_changes": true}}, + {"tool": "cad_call", "args": {"method": "new_design", "params": {"discard_changes": true}}}, + + // The bench's M5 hex standoff from a polygon 8 across the flats and its 4.134 mm tap drill. + {"tool": "cad_call", "args": {"method": "sketch_begin", "params": {"plane": "XY"}}}, + {"tool": "cad_call", "args": {"method": "sketch_add", "params": {"entities": [ + {"type": "polygon", "center": [0, 0], "sides": 6, "across_flats": 8}, + {"type": "circle", "center": [0, 0], "radius": 2.067}]}}, + "expect": {"/result/shapes/0/count": {"eq": 6}, "/result/shapes/1/first": {"eq": 6}, "/result/entities": {"eq": 7}}}, + // The first edge is a flat 4 mm from the centre; the hexagon holds the bore as its hole. + {"tool": "cad_call", "args": {"method": "sketch_describe"}, + "expect": {"/result/entities/0/p0/0": {"ge": 3.9999, "le": 4.0001}, "/result/entities/0/p1/0": {"ge": 3.9999, "le": 4.0001}, + "/result/closed_loops/1/holes/0": {"eq": 0}, "/result/closed_loops/1/area": {"ge": 55.4256, "le": 55.4257}}}, + {"tool": "cad_call", "args": {"method": "sketch_commit"}, "expect": {"/result/buildable": {"eq": true}}}, + {"tool": "cad_call", "args": {"method": "extrude", "params": {"sketch": 0, "distance": 15}}, "expect": {"/result/body": {"eq": 0}}}, + {"tool": "cad_call", "args": {"method": "mass_properties", "params": {"body": 0}}, + "expect": {"/result/volume": {"ge": 630.0, "le": 630.1}}}, + + // Trim and extend on crossing lines. + {"tool": "cad_call", "args": {"method": "new_design", "params": {"discard_changes": true}}}, + {"tool": "cad_call", "args": {"method": "sketch_begin", "params": {"plane": "XY"}}}, + {"tool": "cad_call", "args": {"method": "sketch_add", "params": {"entities": [ + {"type": "line", "p0": [-10, 0], "p1": [10, 0]}, + {"type": "line", "p0": [0, -10], "p1": [0, 10]}, + {"type": "line", "p0": [0, 20], "p1": [10, 20]}, + {"type": "line", "p0": [30, 15], "p1": [30, 25]}]}}}, + // Line 0 is cut back from its end beyond the crossing. + {"tool": "cad_call", "args": {"method": "sketch_trim", "params": {"at": [5, 0]}}, + "expect": {"/result/entity": {"eq": 0}, "/result/geometry/p1/0": {"ge": -0.0001, "le": 0.0001}, + "/result/geometry/p0/0": {"eq": -10.0}}}, + // Nothing there to cut: refused. + {"tool": "cad_call", "args": {"method": "sketch_trim", "params": {"at": [100, 100]}}, "optional": true}, + // Line 2 runs out to line 3. + {"tool": "cad_call", "args": {"method": "sketch_trim", "params": {"at": [9, 20], "extend": true}}, + "expect": {"/result/entity": {"eq": 2}, "/result/geometry/p1/0": {"ge": 29.9999, "le": 30.0001}}}, + {"tool": "cad_call", "args": {"method": "sketch_cancel"}}, + + // A 60 x 40 plate: one corner chamfered, one rounded, two slots, an elliptic hole and four + // holes arrayed about a point, then constrained. + {"tool": "cad_call", "args": {"method": "sketch_begin", "params": {"plane": "XY"}}}, + {"tool": "cad_call", "args": {"method": "sketch_add", "params": {"rect": [-30, -20, 30, 20]}}, "expect": {"/result/dof": {"eq": 4}}}, + {"tool": "cad_call", "args": {"method": "sketch_chamfer", "params": {"entities": [0, 1], "distance": 5}}, + "expect": {"/result/entity": {"eq": 4}, "/result/released_constraints": {"eq": 1}}}, + // Too big for the 35 mm left of the bottom edge: refused. + {"tool": "cad_call", "args": {"method": "sketch_fillet", "params": {"entities": [2, 3], "radius": 100}}, "optional": true}, + {"tool": "cad_call", "args": {"method": "sketch_fillet", "params": {"entities": [2, 3], "radius": 6}}, + "expect": {"/result/entity": {"eq": 5}, "/result/entities": {"eq": 6}}}, + {"tool": "cad_call", "args": {"method": "sketch_add", "params": {"entities": [ + {"type": "slot", "c0": [-15, 0], "c1": [-5, 0], "width": 4}, + {"type": "ellipse", "center": [0, -10], "radius": 4, "rminor": 2, "rotation_deg": 0}, + {"type": "circle", "center": [11, 0], "radius": 1.5}, + {"type": "spline", "ctrl": [[-25, -15], [-20, -10], [-15, -15]], "construction": true}]}}, + "expect": {"/result/shapes/0/count": {"eq": 4}, "/result/shapes/1/first": {"eq": 10}, "/result/shapes/2/first": {"eq": 11}, + "/result/shapes/3/first": {"eq": 12}, "/result/entities": {"eq": 13}}}, + // A second slot above the first, turned upright about its own centre. + {"tool": "cad_call", "args": {"method": "sketch_transform", "params": {"op": "array", "entities": [6, 7, 8, 9], "dy": 10, "count": 2}}, + "expect": {"/result/first_index": {"eq": 13}, "/result/added": {"eq": 4}}}, + {"tool": "cad_call", "args": {"method": "sketch_transform", "params": {"op": "rotate", "entities": [13, 14, 15, 16], "angle_deg": 90}}, + "expect": {"/result/pivot/0": {"ge": -10.0001, "le": -9.9999}, "/result/pivot/1": {"ge": 9.9999, "le": 10.0001}}}, + // The hole moved 1 mm right (picked by selection), then arrayed four times about (17, 0). + {"tool": "cad_call", "args": {"method": "sketch_select", "params": {"entities": [11]}}}, + {"tool": "cad_call", "args": {"method": "sketch_transform", "params": {"op": "move", "dx": 1}}, + "expect": {"/result/moved/0": {"eq": 11}}}, + {"tool": "cad_call", "args": {"method": "sketch_transform", "params": {"op": "polar_array", "entities": [11], "pivot": [17, 0], "count": 4}}, + "expect": {"/result/first_index": {"eq": 17}, "/result/added": {"eq": 3}, "/result/bound": {"eq": 3}}}, + {"tool": "cad_call", "args": {"method": "sketch_describe"}, + "expect": {"/result/entities/18/center/0": {"ge": 21.9999, "le": 22.0001}, "/result/entities/18/center/1": {"ge": -0.0001, "le": 0.0001}, + "/result/entities/14/p0/0": {"ge": -12.0001, "le": -11.9999}, "/result/buildable": {"eq": true}}}, + + // Constraints: the hole held 12 from the origin (its current distance), the first copy kept the + // hole's size. A rival radius cannot be met and is rolled back; the distance is deleted again. + {"tool": "cad_call", "args": {"method": "sketch_constraints"}, "expect": {"/result/constraints": {"eq": 25}}}, + {"tool": "cad_call", "args": {"method": "sketch_constrain", "params": {"type": "distance", + "refs": [{"entity": 11, "role": "center"}, {"entity": "origin"}], "value": 12}}, + "expect": {"/result/added/0": {"eq": 25}, "/result/items/0/type": {"eq": "distance"}, + "/result/items/0/refs/1/entity": {"eq": "origin"}, "/result/solve_ok": {"eq": true}}}, + {"tool": "cad_call", "args": {"method": "sketch_constrain", "params": {"type": "equal", "entities": [11, 17]}}, + "expect": {"/result/items/0/type": {"eq": "equal_radius"}}}, + {"tool": "cad_call", "args": {"method": "sketch_constrain", "params": {"type": "radius", "entities": [11], "value": 2}}, "optional": true}, + {"tool": "cad_call", "args": {"method": "sketch_constraints"}, + "expect": {"/result/scope": {"eq": "live"}, "/result/constraints": {"eq": 27}, "/result/items/26/type": {"eq": "equal_radius"}}}, + {"tool": "cad_call", "args": {"method": "sketch_unconstrain", "params": {"index": 25}}, + "expect": {"/result/removed/type": {"eq": "distance"}, "/result/constraints": {"eq": 26}}}, + {"tool": "cad_call", "args": {"method": "sketch_commit"}, + "expect": {"/result/buildable": {"eq": true}, "/result/sketch_index": {"eq": 0}}}, + {"tool": "cad_call", "args": {"method": "sketch_constraints", "params": {"sketch": 0}}, + "expect": {"/result/scope": {"eq": "committed"}, "/result/constraints": {"eq": 26}}}, + {"tool": "cad_call", "args": {"method": "extrude", "params": {"sketch": 0, "distance": 5}}, "expect": {"/result/body": {"eq": 0}}}, + // 60 x 40, less the chamfer (12.5), the fillet's corner (36 (1 - pi/4)), two slots (40 + 4 pi each), + // the ellipse (8 pi) and four holes (2.25 pi each): 2221.23 mm2, 5 mm thick. + {"tool": "cad_call", "args": {"method": "mass_properties", "params": {"body": 0}}, + "expect": {"/result/volume": {"ge": 11106.1, "le": 11106.25}}} + ] +} diff --git a/tools/mcp/tests/cad_sketch_to_solid.json b/tools/mcp/tests/cad_sketch_to_solid.json new file mode 100644 index 0000000000..8bfc1eea61 --- /dev/null +++ b/tools/mcp/tests/cad_sketch_to_solid.json @@ -0,0 +1,101 @@ +// Sketch to solid through cad_call: sketches on a base plane through modeling_origin and on a +// body's face, committed and read back, then extruded whole, by loop and joined onto the body they +// touch, and revolved about the sketch's centerline. An empty sketch is refused and stays open. The +// L-bracket's inside corner is rounded in the sketch, as the Fillet tool rounds it. +// Needs the CAD feature on: +// tools/mcp/orca_mcp.py launch --cad +// tools/mcp/orca_mcp.py run-script tools/mcp/tests/cad_sketch_to_solid.json --out /tmp/out +{ + "orca_script": 1, + "name": "cad sketch to solid", + "steps": [ + {"tool": "wait", "args": {"for": "ready"}}, + {"tool": "new_project", "args": {"discard_changes": true}}, + {"tool": "cad_call", "args": {"method": "new_design", "params": {"discard_changes": true}}}, + + // An L-bracket profile on XZ, which passes through modeling_origin, not the bed corner: 40 x 30, 4 thick. + {"tool": "cad_call", "args": {"method": "sketch_begin", "params": {"plane": "XZ"}}, + "expect": {"/result/plane": {"eq": "XZ"}, "/result/frame/normal/1": {"eq": 1.0}, "/result/frame/origin/0": {"gt": 1.0}}}, + // Committing it empty fails and leaves it open: the next step reads the open sketch. + {"tool": "cad_call", "args": {"method": "sketch_commit"}, "optional": true}, + {"tool": "cad_call", "args": {"method": "sketch_describe"}, "expect": {"/result/entities": {"empty": true}}}, + {"tool": "cad_call", "args": {"method": "sketch_add", "params": {"entities": [ + {"type": "line", "p0": [0, 0], "p1": [40, 0]}, + {"type": "line", "p0": [40, 0], "p1": [40, 4]}, + {"type": "line", "p0": [40, 4], "p1": [4, 4]}, + {"type": "line", "p0": [4, 4], "p1": [4, 30]}, + {"type": "line", "p0": [4, 30], "p1": [0, 30]}, + {"type": "line", "p0": [0, 30], "p1": [0, 0]}]}}, + "expect": {"/result/entities": {"eq": 6}}}, + // The inside corner, between lines 2 and 3, rounded to 3 mm: an arc tangent to both legs. + {"tool": "cad_call", "args": {"method": "sketch_fillet", "params": {"entities": [2, 3], "radius": 3}}, + "expect": {"/result/entity": {"eq": 6}, "/result/entities": {"eq": 7}, "/result/released_constraints": {"eq": 1}, + "/result/solve_ok": {"eq": true}}}, + {"tool": "cad_call", "args": {"method": "sketch_commit"}, + "expect": {"/result/sketch_index": {"eq": 0}, "/result/name": {"regex": "^Sketch"}, "/result/features": {"eq": 1}, + "/result/buildable": {"eq": true}, "/result/closed_loops/0/index": {"eq": 0}, + "/result/closed_loops/0/area": {"ge": 265.93, "le": 265.94}}}, + {"tool": "cad_call", "args": {"method": "sketch_describe", "params": {"sketch": 0}}, + "expect": {"/result/plane/base": {"eq": "XZ"}, "/result/entities/6/type": {"eq": "arc"}, "/result/entities/6/radius": {"ge": 2.9999, "le": 3.0001}, + "/result/closed_loops/0/entities/6": {"exists": true}, "/result/buildable": {"eq": true}}}, + {"tool": "cad_call", "args": {"method": "extrude", "params": {"sketch": 0, "distance": 20}}, + "expect": {"/result/extrude_index": {"eq": 1}, "/result/sketch_index": {"eq": 0}, "/result/boolean": {"eq": "new"}, + "/result/body": {"eq": 0}, "/result/end": {"eq": "blind"}, "/result/frame/normal/1": {"eq": 1.0}}}, + {"tool": "cad_call", "args": {"method": "mass_properties", "params": {"body": 0}}, + "expect": {"/result/volume": {"gt": 5316.6, "lt": 5320.6}}}, + {"tool": "cad_call", "args": {"method": "describe_scene"}, + "expect": {"/result/bodies/0/bbox/min/0": {"gt": 1.0}, "/result/bodies/0/bbox/min/2": {"ge": -0.001, "le": 0.001}, + "/result/bodies/0/bbox/max/2": {"ge": 29.999, "le": 30.001}}}, + + // A shelf-pin jig: a 160 x 60 plate with five 5.2 mm holes on 32 mm centres, in one sketch. + {"tool": "cad_call", "args": {"method": "new_design", "params": {"discard_changes": true}}}, + {"tool": "cad_call", "args": {"method": "sketch_begin", "params": {"plane": "XY"}}}, + {"tool": "cad_call", "args": {"method": "sketch_add", "params": {"rect": [-80, -30, 80, 30]}}}, + {"tool": "cad_call", "args": {"method": "sketch_add", "params": {"entities": [ + {"type": "circle", "center": [-64, 0], "radius": 2.6}, + {"type": "circle", "center": [-32, 0], "radius": 2.6}, + {"type": "circle", "center": [0, 0], "radius": 2.6}, + {"type": "circle", "center": [32, 0], "radius": 2.6}, + {"type": "circle", "center": [64, 0], "radius": 2.6}]}}}, + // Six loops: each disc, and the plate listing the five as its holes. + {"tool": "cad_call", "args": {"method": "sketch_commit"}, + "expect": {"/result/buildable": {"eq": true}, "/result/closed_loops/5/index": {"eq": 5}, + "/result/closed_loops/5/holes/4": {"exists": true}, "/result/closed_loops/5/area": {"ge": 9599.99, "le": 9600.01}}}, + {"tool": "cad_call", "args": {"method": "extrude", "params": {"sketch": 0, "distance": 8}}, + "expect": {"/result/boolean": {"eq": "new"}, "/result/body": {"eq": 0}}}, + {"tool": "cad_call", "args": {"method": "mass_properties", "params": {"body": 0}}, + "expect": {"/result/volume": {"ge": 75950.50, "le": 75950.53}}}, + {"tool": "cad_call", "args": {"method": "query_topology", "params": {"body": 0}}, + "expect": {"/result/face_count": {"eq": 11}, "/result/faces/4/kind": {"eq": "cylindrical"}, + "/result/faces/8/kind": {"eq": "cylindrical"}, "/result/faces/10/normal/2": {"eq": 1.0}}}, + // The lip, sketched on the plate's top face: that frame's x is world -Y and its y world X. + {"tool": "cad_call", "args": {"method": "sketch_begin", "params": {"plane": {"body": 0, "face": 10}}}, + "expect": {"/result/frame/origin/2": {"ge": 7.999, "le": 8.001}, "/result/frame/x_axis/1": {"eq": -1.0}, + "/result/frame/y_axis/0": {"eq": 1.0}}}, + {"tool": "cad_call", "args": {"method": "sketch_add", "params": {"rect": [-30, -80, -20, 80]}}}, + {"tool": "cad_call", "args": {"method": "sketch_commit"}, "expect": {"/result/sketch_index": {"eq": 2}}}, + // It touches the plate, so it joins it, as the Extrude card's default does. + {"tool": "cad_call", "args": {"method": "extrude", "params": {"sketch": 2, "distance": 10}}, + "expect": {"/result/boolean": {"eq": "union"}, "/result/body": {"eq": 0}, "/result/bodies": {"eq": 1}}}, + {"tool": "cad_call", "args": {"method": "mass_properties", "params": {"body": 0}}, + "expect": {"/result/volume": {"ge": 91950.50, "le": 91950.53}}}, + {"tool": "cad_call", "args": {"method": "describe_scene"}, + "expect": {"/result/bodies/0/bbox/max/2": {"ge": 17.999, "le": 18.001}}}, + // One loop of the plate's sketch: a hole's loop is its disc. + {"tool": "cad_call", "args": {"method": "extrude", "params": {"sketch": 0, "loop": 2, "distance": 8, "boolean": "new"}}, + "expect": {"/result/loop": {"eq": 2}, "/result/body": {"eq": 1}, "/result/bodies": {"eq": 2}}}, + {"tool": "cad_call", "args": {"method": "mass_properties", "params": {"body": 1}}, + "expect": {"/result/volume": {"ge": 169.89, "le": 169.91}}}, + + // A ring: a 10 x 10 profile revolved about the sketch's only centerline. + {"tool": "cad_call", "args": {"method": "new_design", "params": {"discard_changes": true}}}, + {"tool": "cad_call", "args": {"method": "sketch_begin", "params": {"plane": "XZ"}}}, + {"tool": "cad_call", "args": {"method": "sketch_add", "params": {"rect": [10, 0, 20, 10]}}}, + {"tool": "cad_call", "args": {"method": "sketch_add", "params": {"type": "line", "p0": [0, 0], "p1": [0, 30], "construction": true}}}, + {"tool": "cad_call", "args": {"method": "sketch_commit"}, "expect": {"/result/sketch_index": {"eq": 0}}}, + {"tool": "cad_call", "args": {"method": "revolve", "params": {"sketch": 0}}, + "expect": {"/result/revolve_index": {"eq": 1}, "/result/axis_entity": {"eq": 4}, "/result/boolean": {"eq": "new"}}}, + {"tool": "cad_call", "args": {"method": "mass_properties", "params": {"body": 0}}, + "expect": {"/result/volume": {"ge": 9424.70, "le": 9424.86}}} + ] +} diff --git a/tools/mcp/tests/cad_topology_targets.json b/tools/mcp/tests/cad_topology_targets.json new file mode 100644 index 0000000000..526b7d3070 --- /dev/null +++ b/tools/mcp/tests/cad_topology_targets.json @@ -0,0 +1,93 @@ +// Reading a body's topology and building on what it finds, through cad_call. The bench's J wall +// hook: its inside corners found by convexity, M4 countersinks seated on the front face on the axes +// of pilot holes (`at` a cylindrical face), checked through query_topology's cone kinds and adjacency +// and measure's min_distance; then datum planes, a sketch on one, and a face push/pull. A refused +// datum plane changes nothing. Face and edge ids are this build's; no step reads a world position +// that depends on the printer's bed. +// Needs the CAD feature on: +// tools/mcp/orca_mcp.py launch --cad +// tools/mcp/orca_mcp.py run-script tools/mcp/tests/cad_topology_targets.json --out /tmp/out +{ + "orca_script": 1, + "name": "cad topology and targets", + "steps": [ + {"tool": "wait", "args": {"for": "ready"}}, + {"tool": "new_project", "args": {"discard_changes": true}}, + {"tool": "cad_call", "args": {"method": "new_design", "params": {"discard_changes": true}}}, + + // Back plate 60 x 5, arm 35 out, lip 15 up, 20 wide. + {"tool": "cad_call", "args": {"method": "extrude", "params": {"plane": "XZ", "distance": 20, + "profile": [[5, 0], [5, 60], [0, 60], [0, 5], [-30, 5], [-30, 15], [-35, 15], [-35, 0]]}}, + "expect": {"/result/ok": {"eq": true}, "/result/body": {"eq": 0}}}, + // Two inside corners, each with the faces on either side of it. + {"tool": "cad_call", "args": {"method": "query_topology", "params": {"convex": false}}, + "expect": {"/result/edges_total": {"eq": 2}, "/result/edges/0/id": {"eq": 7}, "/result/edges/0/kind": {"eq": "line"}, + "/result/edges/0/convex": {"eq": false}, "/result/edges/0/faces": {"contains": 2}, "/result/faces_total": {"eq": 3}}}, + {"tool": "cad_call", "args": {"method": "fillet", "params": {"edge": 7, "radius": 5}}, "expect": {"/result/ok": {"eq": true}}}, + {"tool": "cad_call", "args": {"method": "query_topology", "params": {"kinds": ["cylindrical"]}}, + "expect": {"/result/faces_total": {"eq": 1}, "/result/faces/0/radius": {"ge": 4.9999, "le": 5.0001}, "/result/faces/0/internal": {"eq": true}, + "/result/edges": {"empty": true}}}, + + // Pilot holes from the YZ plane, then countersinks seated on the front face on their axes. + {"tool": "cad_call", "args": {"method": "hole", "params": {"plane": "YZ", "x": 10, "y": 25, "diameter": 3, "through": true}}}, + {"tool": "cad_call", "args": {"method": "hole", "params": {"plane": "YZ", "x": 10, "y": 50, "diameter": 3, "through": true}}}, + {"tool": "cad_call", "args": {"method": "query_topology", "params": {"direction": [-1, 0, 0]}}, + "expect": {"/result/faces_total": {"eq": 2}, "/result/faces/0/id": {"eq": 0}, "/result/faces/0/area": {"ge": 985.86, "le": 985.87}}}, + {"tool": "cad_call", "args": {"method": "hole_standard", "params": {"designation": "M4", "style": 2, + "plane": {"body": 0, "face": 0}, "at": {"body": 0, "face": 6}}}, + "expect": {"/result/body": {"eq": 0}, "/result/off_plane": {"ge": 4.9999, "le": 5.0001}, "/result/y": {"ge": -0.0001, "le": 0.0001}, + "/result/frame/normal/0": {"eq": 1.0}}}, + {"tool": "cad_call", "args": {"method": "hole_standard", "params": {"designation": "M4", "style": 2, + "plane": {"body": 0, "face": 0}, "at": {"body": 0, "face": 5}}}, + "expect": {"/result/body": {"eq": 0}, "/result/off_plane": {"ge": 4.9999, "le": 5.0001}}}, + // Two cones, opening out of the front face (-X) from an apex inside the 5 mm plate. + {"tool": "cad_call", "args": {"method": "query_topology", "params": {"kinds": ["conical"], "adjacency": true}}, + "expect": {"/result/faces_total": {"eq": 2}, "/result/faces/0/half_angle_deg": {"ge": 44.999, "le": 45.001}, + "/result/faces/0/radius_max": {"ge": 4.4999, "le": 4.5001}, "/result/faces/0/radius_min": {"ge": 2.2499, "le": 2.2501}, + "/result/faces/0/internal": {"eq": true}, "/result/faces/0/axis/0": {"eq": -1.0}, "/result/faces/1/axis/0": {"eq": -1.0}, + "/result/edges_total": {"eq": 6}, "/result/edges/0/faces": {"contains": 0}, "/result/edges/0/convex": {"eq": true}}}, + {"tool": "cad_call", "args": {"method": "mass_properties", "params": {"body": 0}}, + "expect": {"/result/volume": {"ge": 10352.82, "le": 10352.84}}}, + {"tool": "cad_call", "args": {"method": "query_topology", "params": {"at_extreme": "-z"}}, + "expect": {"/result/faces_total": {"eq": 1}, "/result/faces/0/id": {"eq": 10}, "/result/edges": {"empty": true}}}, + // Hole heights from the bottom face and the spacing, by the bores' axes. + {"tool": "cad_call", "args": {"method": "measure", "params": {"a": {"face": 14, "axis": true}, "b": {"face": 10}}}, + "expect": {"/result/min_distance": {"ge": 24.9999, "le": 25.0001}, "/result/angle_deg": {"ge": 89.999, "le": 90.001}}}, + {"tool": "cad_call", "args": {"method": "measure", "params": {"a": {"face": 13, "axis": true}, "b": {"face": 14, "axis": true}}}, + "expect": {"/result/min_distance": {"ge": 24.9999, "le": 25.0001}, "/result/distance": {"ge": 24.9999, "le": 25.0001}}}, + // The cone touches the front face and stops 2.75 mm short of the back one. + {"tool": "cad_call", "args": {"method": "measure", "params": {"a": {"face": 6}, "b": {"face": 0}}}, + "expect": {"/result/min_distance": {"le": 0.0001}}}, + {"tool": "cad_call", "args": {"method": "measure", "params": {"a": {"face": 6}, "b": {"face": 8}}}, + "expect": {"/result/min_distance": {"ge": 2.7499, "le": 2.7501}}}, + {"tool": "cad_call", "args": {"method": "measure", "params": {"a": {"face": 0}, "b": {"face": 8}}}, + "expect": {"/result/parallel_gap": {"ge": 4.9999, "le": 5.0001}, "/result/min_distance": {"ge": 4.9999, "le": 5.0001}}}, + + // Datum planes: midway through the plate, and 70 mm above the bed with a sketch on it. + {"tool": "cad_call", "args": {"method": "plane", "params": {"type": "midplane", "face_a": {"body": 0, "face": 0}, "face_b": {"body": 0, "face": 8}}}, + "expect": {"/result/plane_index": {"eq": 7}, "/result/name": {"regex": "^Plane"}, "/result/frame/normal/0": {"eq": -1.0}}}, + {"tool": "cad_call", "args": {"method": "plane", "params": {"offset": 70}}, + "expect": {"/result/plane_index": {"eq": 8}, "/result/frame/origin/2": {"eq": 70.0}, "/result/frame/normal/2": {"eq": 1.0}}}, + // A tangent plane needs a cylindrical face: refused, and nothing changes. + {"tool": "cad_call", "args": {"method": "plane", "params": {"type": "tangent", "face_a": {"body": 0, "face": 0}}}, "optional": true}, + {"tool": "cad_call", "args": {"method": "describe_scene"}, + "expect": {"/result/features/8/type": {"eq": "Plane"}, "/result/features/9": {"exists": false}, "/result/undo_depth": {"eq": 8}, "/result/redo_depth": {"eq": 0}}}, + {"tool": "cad_call", "args": {"method": "sketch_begin", "params": {"plane": {"datum": 8}}}, + "expect": {"/result/frame/origin/2": {"eq": 70.0}}}, + {"tool": "cad_call", "args": {"method": "sketch_add", "params": {"entities": [{"type": "circle", "center": [10, 10], "radius": 5}]}}}, + {"tool": "cad_call", "args": {"method": "sketch_commit"}, "expect": {"/result/sketch_index": {"eq": 9}}}, + {"tool": "cad_call", "args": {"method": "extrude", "params": {"sketch": 9, "distance": 4}}, + "expect": {"/result/boolean": {"eq": "new"}, "/result/body": {"eq": 1}}}, + {"tool": "cad_call", "args": {"method": "describe_scene"}, + "expect": {"/result/bodies/1/bbox/min/2": {"ge": 69.999, "le": 70.001}, "/result/bodies/1/bbox/max/2": {"ge": 73.999, "le": 74.001}}}, + + // Push the plate's back face out 2 mm: it joins its own body. + {"tool": "cad_call", "args": {"method": "extrude", "params": {"face": 8, "body": 0, "distance": 2}}, + "expect": {"/result/boolean": {"eq": "union"}, "/result/body": {"eq": 0}, "/result/sketch_index": {"eq": -1}, + "/result/face": {"eq": 8}, "/result/frame/normal/0": {"eq": 1.0}}}, + {"tool": "cad_call", "args": {"method": "mass_properties", "params": {"body": 0}}, + "expect": {"/result/volume": {"ge": 12689.20, "le": 12689.22}}}, + {"tool": "cad_call", "args": {"method": "query_topology", "params": {"limit": 5}}, + "expect": {"/result/faces/4": {"exists": true}, "/result/faces/5": {"exists": false}, "/result/next_offset": {"eq": 5}}} + ] +} diff --git a/tools/mcp/tests/calibration.json b/tools/mcp/tests/calibration.json new file mode 100644 index 0000000000..bcf43cb0ce --- /dev/null +++ b/tools/mcp/tests/calibration.json @@ -0,0 +1,135 @@ +// Makes every calibration test with calibrate, as the Calibration menu's dialogs do after OK, and +// checks the objects it added, the parameters it used and the presets it changed, slicing several of +// them (not input shaping, which the X1C's Marlin flavour cannot slice). It checks that temperatures +// are rounded down to 5 °C, that the refusals leave the project as it was (modified presets without +// changes, an argument the test does not take, a value the dialog refuses, the filament tab on another +// slot's modified preset with "keep"), that "discard" points the filament tab at slot 1, that "keep" +// keeps an edit, and that new_project drops the test's settings. It starts from the harness's default +// printer (Bambu Lab X1 Carbon) and reruns on the same datadir. Run it with +// tools/mcp/orca_mcp.py run-script tools/mcp/tests/calibration.json --out /tmp/calibration +{ + "orca_script": 1, + "name": "calibration tests", + "steps": [ + {"tool": "wait", "args": {"for": "ready"}}, + {"tool": "dialog_auto_answer", "args": {"rules": [{"match": "restore", "button": "no"}]}}, + {"tool": "new_project", "args": {"discard_changes": true, "changes": "discard"}}, + {"tool": "set_view", "args": {"tab": "prepare"}}, + {"tool": "run_action", "args": {"id": "orca_command:filament_delete:orca"}, "optional": true}, + {"tool": "run_action", "args": {"id": "orca_command:filament_delete:orca"}, "optional": true}, + {"tool": "run_action", "args": {"id": "orca_command:filament_delete:orca"}, "optional": true}, + {"tool": "run_action", "args": {"id": "orca_command:filament_delete:orca"}, "optional": true}, + {"tool": "get_state", "expect": {"/presets/filaments/1": {"exists": false}}}, + + // ---- Temperature: rounded down to the tower's 5 °C blocks, written to slot 1's filament ---- + {"tool": "calibrate", "args": {"test": "temperature", "start": 252, "end": 232}, + "expect": {"/test": {"eq": "temperature"}, "/params": {"eq": {"start": 250, "end": 230, "auto_scale": true}}, + "/warnings/0": {"contains": "rounded down to 250"}, "/warnings/1": {"contains": "rounded down to 230"}, + "/objects": {"eq": 1}, "/names": {"eq": ["temperature_tower.drc"]}, + "/presets_changed/filament/filament_slot": {"eq": 1}, + "/presets_changed/filament/changes/nozzle_temperature": {"exists": true}, + "/result_keys": {"eq": {"scope": "filament", "keys": ["nozzle_temperature", "nozzle_temperature_initial_layer"]}}, + "/modified/filament/keys": {"contains": "nozzle_temperature"}}}, + {"tool": "slice", "expect": {"/status": {"eq": "done"}, "/plates/0/outcome": {"eq": "ok"}}}, + + // ---- Refused, changing nothing: modified presets without changes, an argument the test does not + // take, a value its dialog refuses ---- + {"tool": "calibrate", "args": {"test": "max_volumetric", "discard_changes": true}, "optional": true}, + {"tool": "calibrate", "args": {"test": "temperature", "step": 5, "discard_changes": true, "changes": "discard"}, "optional": true}, + {"tool": "calibrate", "args": {"test": "pressure_advance", "start": 0.01, "end": 0.05, "step": 0.051, + "discard_changes": true, "changes": "discard"}, "optional": true}, + {"tool": "list_objects", "expect": {"/total": {"eq": 1}, "/items/0/name": {"eq": "temperature_tower.drc"}}}, + {"tool": "list_presets", "args": {"type": "filament"}, + "expect": {"/items/0/name": {"eq": "Bambu PLA Basic @BBL X1C"}, "/items/0/modified": {"eq": true}}}, + + // ---- Max volumetric speed: the temperature test's settings discarded first ---- + {"tool": "calibrate", "args": {"test": "max_volumetric", "end": 15, "discard_changes": true, "changes": "discard"}, + "expect": {"/params": {"eq": {"start": 5, "end": 15, "step": 0.5}}, "/names": {"eq": ["SpeedTestStructure.drc"]}, + "/discarded/filament/keys": {"contains": "nozzle_temperature"}, + "/presets_changed/process/changes/spiral_mode": {"eq": "1"}, + "/presets_changed/filament/changes/filament_max_volumetric_speed": {"exists": true}}}, + {"tool": "slice", "expect": {"/plates/0/outcome": {"eq": "ok"}}}, + + // ---- Pressure advance: tower, line and a 2 x 2 pattern batch; the pattern's defaults read back ---- + {"tool": "calibrate", "args": {"test": "pressure_advance", "end": 0.06, "discard_changes": true, "changes": "discard"}, + "expect": {"/params": {"eq": {"method": "tower", "start": 0, "end": 0.06, "step": 0.002}}, "/names": {"eq": ["tower_with_seam.drc"]}}}, + {"tool": "slice", "expect": {"/plates/0/outcome": {"eq": "ok"}}}, + {"tool": "calibrate", "args": {"test": "pressure_advance", "method": "line", "print_numbers": false, "discard_changes": true, "changes": "discard"}, + "expect": {"/params/print_numbers": {"eq": false}, "/params/end": {"eq": 0.1}, "/names": {"eq": ["pressure_advance_test.drc"]}}}, + {"tool": "calibrate", "args": {"test": "pressure_advance", "method": "pattern", "accelerations": [1000, 2000], "speeds": [50, 100], + "discard_changes": true, "changes": "discard"}, + "expect": {"/objects": {"eq": 4}, + "/names": {"eq": ["pa_pattern_50_1000", "pa_pattern_100_1000", "pa_pattern_50_2000", "pa_pattern_100_2000"]}, + "/params/accelerations": {"eq": [1000, 2000]}, "/params/speeds": {"eq": [50, 100]}, + "/result_keys/keys": {"contains": "adaptive_pressure_advance_model"}}}, + {"tool": "slice", "expect": {"/plates/0/outcome": {"eq": "ok"}}}, + {"tool": "calibrate", "args": {"test": "pressure_advance", "method": "pattern", "discard_changes": true, "changes": "discard"}, + "expect": {"/objects": {"eq": 1}, "/params/accelerations/0": {"gt": 0}, "/params/speeds/0": {"gt": 0}}}, + + // ---- Flow ratio: the four passes ---- + {"tool": "calibrate", "args": {"test": "flow_ratio", "discard_changes": true, "changes": "discard"}, + "expect": {"/params": {"eq": {"method": "yolo", "top_surface_pattern": "archimedeanchords"}}, "/objects": {"eq": 11}, + "/names/0": {"eq": "flowrate_0"}, "/result_keys/keys": {"eq": ["filament_flow_ratio"]}}}, + {"tool": "slice", "expect": {"/plates/0/outcome": {"eq": "ok"}}}, + {"tool": "calibrate", "args": {"test": "flow_ratio", "method": "yolo_perfectionist", "discard_changes": true, "changes": "discard"}, + "expect": {"/objects": {"eq": 16}}}, + {"tool": "calibrate", "args": {"test": "flow_ratio", "method": "pass1", "discard_changes": true, "changes": "discard"}, + "expect": {"/objects": {"eq": 9}}}, + {"tool": "calibrate", "args": {"test": "flow_ratio", "method": "pass2", "top_surface_pattern": "monotonic", "discard_changes": true, "changes": "discard"}, + "expect": {"/objects": {"eq": 10}, "/names/1": {"eq": "flowrate_m1"}, "/params/top_surface_pattern": {"eq": "monotonic"}}}, + + // ---- Retraction, VFA (with its auto-adjust), input shaping and cornering ---- + {"tool": "calibrate", "args": {"test": "retraction", "end": 1, "discard_changes": true, "changes": "discard"}, + "expect": {"/params": {"eq": {"start": 0, "end": 1, "step": 0.1}}, "/names": {"eq": ["retraction_tower.drc"]}}}, + {"tool": "slice", "expect": {"/plates/0/outcome": {"eq": "ok"}}}, + {"tool": "calibrate", "args": {"test": "vfa", "discard_changes": true, "changes": "discard"}, + "expect": {"/params": {"eq": {"start": 40, "end": 200, "step": 10, "auto_scale": true, "auto_adjust": true}}, + "/adjusted": {"exists": false}, "/presets_changed/process/changes/spiral_mode": {"eq": "1"}, + "/result_keys/scope": {"eq": "printer"}}}, + {"tool": "slice", "expect": {"/plates/0/outcome": {"eq": "ok"}}}, + {"tool": "calibrate", "args": {"test": "vfa", "end": 400, "step": 20, "discard_changes": true, "changes": "discard"}, + "expect": {"/adjusted/layer_height": {"lt": 0.2}, "/params/end": {"eq": 400}}}, + {"tool": "get_settings", "args": {"scope": "object", "object": 0, "keys": ["layer_height"]}, "expect": {"/items/0/value": {"ne": "0.2"}}}, + {"tool": "calibrate", "args": {"test": "vfa", "end": 400, "auto_adjust": false, "discard_changes": true, "changes": "discard"}, + "expect": {"/adjusted": {"exists": false}, "/warnings/0": {"contains": "maximum volumetric speed"}}}, + {"tool": "calibrate", "args": {"test": "input_shaping_freq", "start": 20, "end": 80, "discard_changes": true, "changes": "discard"}, + "expect": {"/params": {"eq": {"start": 20, "end": 80, "start_y": 20, "end_y": 80, "damping": 0.15, "shaper_type": "Default", + "test_model": "ringing_tower"}}, + "/names": {"eq": ["ringing_tower.drc"]}, "/result_keys/keys": {"contains": "input_shaping_emit"}}}, + {"tool": "calibrate", "args": {"test": "input_shaping_damp", "freq_x": 48, "freq_y": 42, "test_model": "fast_tower", + "discard_changes": true, "changes": "discard"}, + "expect": {"/params/freq_y": {"eq": 42}, "/params/end": {"eq": 0.4}, "/names": {"eq": ["fast_tower_test.drc"]}}}, + {"tool": "calibrate", "args": {"test": "cornering", "test_model": "scv_v2", "end": 25, "discard_changes": true, "changes": "discard"}, + "expect": {"/params": {"eq": {"start": 1, "end": 25, "test_model": "scv_v2"}}, "/names": {"eq": ["SCV-V2.drc"]}, + "/warnings/0": {"contains": "layer shifts"}, "/result_keys/keys": {"eq": ["machine_max_jerk_x", "machine_max_jerk_y"]}}}, + {"tool": "slice", "expect": {"/plates/0/outcome": {"eq": "ok"}}}, + + // ---- The filament tab on another slot's modified preset: refused with "keep", switched with "discard" ---- + {"tool": "new_project", "args": {"discard_changes": true, "changes": "discard"}}, + {"tool": "run_action", "args": {"id": "orca_command:filament_add:orca"}, "expect": {"/message": {"eq": "Added filament slot 2."}}}, + {"tool": "set_settings", "args": {"scope": "filament", "filament_slot": 2, "values": {"filament_cost": 21}}}, + {"tool": "save_preset", "args": {"type": "filament", "name": "MCP Calib PLA", "filament_slot": 2, "overwrite": true}}, + {"tool": "select_preset", "args": {"type": "filament", "name": "Bambu PLA Basic @BBL X1C", "filament_slot": 1}}, + {"tool": "set_settings", "args": {"scope": "filament", "filament_slot": 2, "values": {"filament_cost": 22}}}, + {"tool": "calibrate", "args": {"test": "retraction", "discard_changes": true, "changes": "keep"}, "optional": true}, + {"tool": "list_objects", "expect": {"/total": {"eq": 0}}}, + {"tool": "calibrate", "args": {"test": "retraction", "discard_changes": true, "changes": "discard"}, + "expect": {"/presets_changed/filament/name": {"eq": "Bambu PLA Basic @BBL X1C"}, + "/presets_changed/filament/tab_switched_from": {"eq": "MCP Calib PLA"}, + "/discarded/filament": {"eq": {"name": "MCP Calib PLA", "keys": ["filament_cost"]}}}}, + + // ---- "keep" runs the test with an edit, which new_project with "discard" then drops ---- + {"tool": "set_settings", "args": {"scope": "filament", "values": {"slow_down_layer_time": 7}}}, + {"tool": "calibrate", "args": {"test": "retraction", "discard_changes": true, "changes": "keep"}, + "expect": {"/modified/filament/keys": {"contains": "slow_down_layer_time"}, "/discarded": {"exists": false}}}, + {"tool": "get_settings", "args": {"scope": "filament", "keys": ["slow_down_layer_time"]}, "expect": {"/items/0/value": {"eq": "7"}}}, + {"tool": "new_project", "args": {"discard_changes": true, "changes": "discard"}, + "expect": {"/discarded/filament/keys": {"contains": "slow_down_layer_time"}, "/modified": {"exists": false}}}, + {"tool": "get_settings", "args": {"scope": "filament", "keys": ["slow_down_layer_time"]}, "expect": {"/items/0/value": {"eq": "4"}}}, + + // ---- Back to one slot and no MCP presets ---- + {"tool": "run_action", "args": {"id": "orca_command:filament_delete:orca", "param": "2"}, "expect": {"/level": {"eq": "success"}}}, + {"tool": "delete_preset", "args": {"type": "filament", "name": "MCP Calib PLA"}, "expect": {"/deleted": {"eq": "MCP Calib PLA"}}}, + {"tool": "list_presets", "args": {"type": "filament"}, "expect": {"/total": {"eq": 1}, "/items/0/modified": {"exists": false}}} + ] +} diff --git a/tools/mcp/tests/context_menus.json b/tools/mcp/tests/context_menus.json new file mode 100644 index 0000000000..bd01b18de5 --- /dev/null +++ b/tools/mcp/tests/context_menus.json @@ -0,0 +1,63 @@ +// Context and button menus are listed or run by path, never shown, so the run must finish with nobody +// pressing Escape (on macOS a native menu would hold every later step). Run it on a fresh datadir set +// up with the default printer (Bambu Lab X1 Carbon 0.4): +// tools/mcp/orca_mcp.py run-script tools/mcp/tests/context_menus.json --out /tmp/menus +// Refusals (no such item, a submenu, a disabled item, a click that opened no menu) are unit tests in +// tests/slic3rutils/test_mcp_results.cpp, since a script step cannot expect an error. +{ + "orca_script": 1, + "name": "context menus", + "steps": [ + {"tool": "wait", "args": {"for": "ready"}}, + {"tool": "dialog_auto_answer", "args": {"rules": [ + {"match": "Uniform scale", "button": "ok"}, + {"match": "per-object setting mode", "button": "ok"}]}}, + {"tool": "new_project", "args": {"discard_changes": true}}, + {"tool": "set_view", "args": {"tab": "prepare", "window_size": [1440, 960]}}, + {"tool": "run_action", "args": {"id": "orca_command:add_primitive_cube:orca"}}, + {"tool": "wait", "args": {"for": "idle"}}, + {"tool": "set_view", "args": {"camera": "iso"}}, + + // ---- A right click on the cube lists the object menu; nothing is shown ---- + {"tool": "ui_mouse", "args": {"action": "click", "button": "right", "at": {"object": 0, "spot": "top"}}, + "expect": {"/popup_menu/items": {"contains": "Add Modifier>Cylinder"}, "/popup_menu/checked": {"contains": "Printable"}}}, + {"tool": "get_state", "expect": {"/dialogs": {"empty": true}}}, + + // ---- The same click runs an item: a modifier through the GUI's own command, one undo step ---- + {"tool": "ui_mouse", "args": {"action": "click", "button": "right", "at": {"object": 0, "spot": "top"}, "popup_item": "add modifier>cylinder"}, + "expect": {"/ran": {"eq": "Add Modifier>Cylinder"}}}, + {"tool": "wait", "args": {"for": "idle"}}, + {"tool": "list_objects", "expect": {"/items/0/volumes/1/type": {"eq": "modifier"}}}, + {"tool": "run_action", "args": {"id": "orca_command:undo:orca"}}, + {"tool": "list_objects", "expect": {"/items/0/volumes/1": {"exists": false}}}, + {"tool": "run_action", "args": {"id": "orca_command:redo:orca"}}, + {"tool": "list_objects", "expect": {"/items/0/volumes/1/type": {"eq": "modifier"}}}, + + // ---- Empty space with nothing selected: the default menu ---- + {"tool": "select", "args": {"none": true}}, + {"tool": "ui_mouse", "args": {"action": "click", "button": "right", "x": 1000, "y": 150}, + "expect": {"/popup_menu/items": {"contains": "Add Primitive>Cube"}}}, + {"tool": "ui_mouse", "args": {"action": "click", "button": "right", "x": 1000, "y": 150, "popup_item": "Add Primitive>Cylinder"}, + "expect": {"/ran": {"eq": "Add Primitive>Cylinder"}}}, + {"tool": "wait", "args": {"for": "idle"}}, + {"tool": "get_state", "expect": {"/objects": {"eq": 2}}}, + + // ---- A button's menu: the first edit button, the printer's (zero-sized on macOS, which froze the + // app before), or on Linux, where that one is hidden, filament 1's, which has a menu with two + // filaments ---- + {"tool": "ui_click", "args": {"target": {"label": "Add one filament"}}}, + {"tool": "ui_click", "args": {"target": {"label": "Click to edit preset", "index": 0}}, + "expect": {"/popup_menu/items": {"empty": false}}}, + {"tool": "get_state", "expect": {"/dialogs": {"empty": true}, "/tab": {"eq": "prepare"}}}, + + // ---- Two objects selected: the multi-selection menu, built for each click and freed after it ---- + {"tool": "select", "args": {"all": true}}, + {"tool": "ui_mouse", "args": {"action": "click", "button": "right", "at": {"object": 0, "spot": "top"}}, + "expect": {"/popup_menu/items": {"contains": "Align/Distribute>Align left (-X)"}}}, + {"tool": "ui_mouse", "args": {"action": "click", "button": "right", "at": {"object": 0, "spot": "top"}}, + "expect": {"/popup_menu/items": {"contains": "Delete"}}}, + {"tool": "ui_mouse", "args": {"action": "click", "button": "right", "at": {"object": 0, "spot": "top"}, "popup_item": "Delete"}, + "expect": {"/ran": {"eq": "Delete"}}}, + {"tool": "get_state", "expect": {"/objects": {"eq": 0}, "/closed_menus": {"empty": true}}} + ] +} diff --git a/tools/mcp/tests/dialogs_canvas_input.json b/tools/mcp/tests/dialogs_canvas_input.json new file mode 100644 index 0000000000..fb27ec2768 --- /dev/null +++ b/tools/mcp/tests/dialogs_canvas_input.json @@ -0,0 +1,58 @@ +// Auto-answered dialogs run their buttons' handlers, a toolbar item reads the state a selection just +// gave it, and model points on a negative part or seen through the bed from below are click targets. +// Run it on a fresh datadir set up with the default printer (Bambu Lab X1 Carbon 0.4): +// tools/mcp/orca_mcp.py run-script tools/mcp/tests/dialogs_canvas_input.json --out /tmp/dialogs +// Refusals (a point or an ImGui item under a panel or notification) are unit tests in +// tests/slic3rutils/test_mcp_results.cpp, since a script step cannot expect an error. +{ + "orca_script": 1, + "name": "auto-answers and canvas input", + "vars": {"standard": "0.20mm Standard @BBL X1C", "fine": "0.16mm High Quality @BBL X1C"}, + "steps": [ + {"tool": "wait", "args": {"for": "ready"}}, + {"tool": "dialog_auto_answer", "args": {"rules": [ + {"match": "Uniform scale", "button": "ok"}, + {"match": "unsaved changes", "button": "no"}, + {"match": "Transfer or discard", "button": "Transfer"}]}}, + {"tool": "new_project", "args": {"discard_changes": true}}, + {"tool": "set_view", "args": {"tab": "prepare", "window_size": [1440, 960]}}, + + // ---- An auto-answered Transfer keeps the edit on the newly selected process preset ---- + {"tool": "select_preset", "args": {"type": "process", "name": "${vars.standard}"}}, + {"tool": "set_settings", "args": {"scope": "print", "values": {"wall_loops": 5}}}, + {"tool": "select_preset", "args": {"type": "process", "name": "${vars.fine}"}, "expect": {"/selected": {"eq": "0.16mm High Quality @BBL X1C"}}}, + {"tool": "get_settings", "args": {"scope": "print", "keys": ["wall_loops"]}, "expect": {"/items/0/value": {"eq": "5"}}}, + // ---- An auto-answered Discard drops it ---- + {"tool": "dialog_auto_answer", "args": {"rules": [{"match": "Transfer or discard", "button": "Discard"}]}}, + {"tool": "select_preset", "args": {"type": "process", "name": "${vars.standard}"}, "expect": {"/selected": {"eq": "0.20mm Standard @BBL X1C"}}}, + {"tool": "get_settings", "args": {"scope": "print", "keys": ["wall_loops"]}, "expect": {"/items/0/value": {"ne": "5"}}}, + {"tool": "get_state", "expect": {"/project/dirty": {"eq": false}}}, + + // ---- A toolbar item a selection just enabled takes the click at once ---- + {"tool": "run_action", "args": {"id": "orca_command:add_primitive_cube:orca"}}, + {"tool": "wait", "args": {"for": "idle"}}, + {"tool": "select", "args": {"none": true}}, + {"tool": "ui_snapshot", "args": {"query": "layersediting"}}, + {"tool": "select", "args": {"objects": [0]}}, + {"tool": "ui_click", "args": {"target": {"gltoolbar": "layersediting"}}, "expect": {"/pressed": {"eq": true}}}, + {"tool": "ui_click", "args": {"target": {"gltoolbar": "layersediting"}}, "expect": {"/pressed": {"eq": false}}}, + + // ---- A negative part is a surface target (the text lands on the cube's top) ---- + {"tool": "set_view", "args": {"camera": "iso"}}, + {"tool": "set_view", "args": {"camera": "fit_objects"}}, + {"tool": "ui_click", "args": {"target": {"gizmo": "Text"}}, "expect": {"/created": {"eq": true}}}, + {"tool": "wait", "args": {"for": "idle"}}, + {"tool": "ui_click", "args": {"target": {"imgui": "Cut"}}}, + {"tool": "ui_click", "args": {"target": {"imgui": "Done"}}}, + {"tool": "list_objects", "expect": {"/items/0/volumes/1/type": {"eq": "negative"}}}, + // The text's size, and so which of its ends the cube hides, differs between platforms; the step is + // about the part resolving as a target, so it skips the visibility check. + {"tool": "ui_mouse", "args": {"action": "move", "at": {"object": 0, "volume": 1, "spot": "right"}, "check": "point"}}, + + // ---- From below, the bed hides nothing ---- + {"tool": "set_view", "args": {"camera": "bottom"}}, + {"tool": "set_view", "args": {"camera": "fit_objects"}}, + {"tool": "ui_mouse", "args": {"action": "move", "at": {"object": 0, "spot": "bottom"}}}, + {"tool": "ui_mouse", "args": {"action": "move", "at": {"object": 0, "point": [5, 5, -12.8]}}} + ] +} diff --git a/tools/mcp/tests/fixtures/mcp_import_pla.json b/tools/mcp/tests/fixtures/mcp_import_pla.json new file mode 100644 index 0000000000..f49d29f5d7 --- /dev/null +++ b/tools/mcp/tests/fixtures/mcp_import_pla.json @@ -0,0 +1,12 @@ +{ + "filament_cost": [ + "24" + ], + "filament_settings_id": [ + "MCP Import PLA" + ], + "from": "User", + "inherits": "Bambu PLA Basic @BBL X1C", + "name": "MCP Import PLA", + "version": "2.8.0.16" +} diff --git a/tools/mcp/tests/gizmos.json b/tools/mcp/tests/gizmos.json index a7626b0eb7..9691d01a3d 100644 --- a/tools/mcp/tests/gizmos.json +++ b/tools/mcp/tests/gizmos.json @@ -122,6 +122,9 @@ {"tool": "list_objects", "expect": {"/items/0/volumes/0/painted/supports/blockers": {"gt": 0}}}, {"tool": "screenshot", "args": {"target": "canvas", "save_path": "${out_dir}/supports.png", "overwrite": true, "include_image": false}}, {"tool": "ui_click", "args": {"target": {"imgui": "Done"}}}, + // Painted enforcers with support off raise a lasting warning, whose notification can cover a later + // panel's items in a small window (a click there is refused); support goes on, as it asks. + {"tool": "set_settings", "args": {"scope": "print", "values": {"enable_support": true}}}, {"tool": "transform", "args": {"object": 1, "translate": [160, 100, 12.8], "mode": "absolute"}}, // ---- Seam ---- diff --git a/tools/mcp/tests/layers.json b/tools/mcp/tests/layers.json new file mode 100644 index 0000000000..37f0756db5 --- /dev/null +++ b/tools/mcp/tests/layers.json @@ -0,0 +1,227 @@ +// Layer-based edits: height range modifiers set with set_layer_ranges, and variable layer height +// profiles set with set_layer_height_profile, read back through list_objects, undone in one step, +// sliced, and kept by a 3MF; and a plate's layer G-codes set with set_layer_gcode, read back from its +// replies, edited, sliced, and kept by a 3MF. Run on a live app: +// python3 tools/mcp/orca_mcp.py run-script tools/mcp/tests/layers.json --out <dir> +// A refusal can't be asserted directly (a failed step stops the run), so each one is an optional +// step followed by a check that nothing changed. +{ + "orca_script": 1, + "name": "layer-based edits", + "vars": {"cube": "${script_dir}/../../../resources/handy_models/OrcaCube_v2.drc", + "benchy": "${script_dir}/../../../resources/handy_models/3DBenchy.drc"}, + "steps": [ + {"tool": "wait", "args": {"for": "ready"}}, + {"tool": "new_project", "args": {"discard_changes": true}}, + {"tool": "set_view", "args": {"tab": "prepare"}}, + {"tool": "open_files", "args": {"paths": ["${vars.cube}"]}, "expect": {"/added": {"eq": 1}}}, + {"tool": "transform", "args": {"object": 0, "size": [20, 20, 20]}}, + {"tool": "set_settings", "args": {"scope": "print", "values": {"layer_height": 0.2, "initial_layer_print_height": 0.2}}}, + {"tool": "list_objects", "expect": {"/items/0/layer_config_ranges": {"exists": false}}}, + + // ---- Two ranges, given in any order: the lower half at 40 % infill, the upper half at 0.1 mm ---- + {"tool": "set_layer_ranges", + "args": {"object": 0, "layer_config_ranges": [{"min_z": 10, "max_z": 20, "values": {"layer_height": 0.1}}, + {"min_z": 0, "max_z": 10, "values": {"sparse_infill_density": "40%"}}]}, + "expect": {"/height": {"ge": 19.99, "le": 20.01}, + "/layer_config_ranges/0/max_z": {"eq": 10}, + "/layer_config_ranges/0/values/sparse_infill_density": {"eq": "40%"}, + "/layer_config_ranges/0/values/layer_height": {"eq": "0.2"}, + "/layer_config_ranges/1/min_z": {"eq": 10}, + "/layer_config_ranges/1/values/layer_height": {"eq": "0.1"}, + "/layer_config_ranges/1/values/extruder": {"eq": "0"}, + "/warnings": {"exists": false}}}, + {"tool": "list_objects", "expect": {"/items/0/layer_config_ranges/0/values/sparse_infill_density": {"eq": "40%"}, + "/items/0/layer_config_ranges/1/values/layer_height": {"eq": "0.1"}, + "/items/0/layer_config_ranges/2": {"exists": false}}}, + // Ranges are not the object's own overrides. + {"tool": "get_settings", "args": {"scope": "object", "object": 0, "keys": ["sparse_infill_density"], "include_meta": false}, + "expect": {"/items/0/value": {"eq": null}}}, + + // ---- One undo step; the same ranges again add none ---- + {"tool": "run_action", "args": {"id": "orca_command:undo:orca"}}, + {"tool": "list_objects", "expect": {"/items/0/layer_config_ranges": {"exists": false}}}, + {"tool": "run_action", "args": {"id": "orca_command:redo:orca"}}, + {"tool": "set_layer_ranges", + "args": {"object": 0, "layer_config_ranges": [{"min_z": 0, "max_z": 10, "values": {"sparse_infill_density": "40%"}}, + {"min_z": 10, "max_z": 20, "values": {"layer_height": 0.1}}]}}, + {"tool": "run_action", "args": {"id": "orca_command:undo:orca"}}, + {"tool": "list_objects", "expect": {"/items/0/layer_config_ranges": {"exists": false}}}, + {"tool": "run_action", "args": {"id": "orca_command:redo:orca"}}, + {"tool": "list_objects", "expect": {"/items/0/layer_config_ranges/1/values/layer_height": {"eq": "0.1"}}}, + + // ---- The slicer prints them: 50 layers of 0.2 mm, then 100 of 0.1 mm ---- + {"tool": "slice", "expect": {"/status": {"eq": "done"}, "/plates/0/outcome": {"eq": "ok"}}}, + {"tool": "set_view", "args": {"tab": "preview", "layer": 1}, "expect": {"/layers/2": {"ge": 149, "le": 151}}}, + + // ---- Refusals change nothing: an overlap, a layer height beyond the printer's, a filament the + // project lacks, an object setting, an empty range ---- + {"tool": "set_layer_ranges", "args": {"object": 0, "layer_config_ranges": [{"min_z": 0, "max_z": 15}, {"min_z": 12, "max_z": 20}]}, + "optional": true}, + {"tool": "set_layer_ranges", "args": {"object": 0, "layer_config_ranges": [{"min_z": 0, "max_z": 5, "values": {"layer_height": 0.5}}]}, + "optional": true}, + {"tool": "set_layer_ranges", "args": {"object": 0, "layer_config_ranges": [{"min_z": 0, "max_z": 5, "values": {"extruder": 9}}]}, + "optional": true}, + {"tool": "set_layer_ranges", "args": {"object": 0, "layer_config_ranges": [{"min_z": 0, "max_z": 5, "values": {"enable_support": true}}]}, + "optional": true}, + {"tool": "set_layer_ranges", "args": {"object": 0, "layer_config_ranges": [{"min_z": 5, "max_z": 5}]}, "optional": true}, + {"tool": "list_objects", "expect": {"/items/0/layer_config_ranges/0/max_z": {"eq": 10}, + "/items/0/layer_config_ranges/1/values/layer_height": {"eq": "0.1"}, + "/items/0/layer_config_ranges/2": {"exists": false}}}, + + // ---- A range printed with the second filament, above the object's top ---- + {"tool": "set_view", "args": {"tab": "prepare"}}, + {"tool": "ui_click", "args": {"target": {"label": "Add one filament"}}}, + {"tool": "set_layer_ranges", + "args": {"object": 0, "layer_config_ranges": [{"min_z": 0, "max_z": 10, "values": {"sparse_infill_density": "40%"}}, + {"min_z": 10, "max_z": 20, "values": {"layer_height": 0.1}}, + {"min_z": 20, "max_z": 30, "values": {"extruder": 2}}]}, + "expect": {"/height": {"le": 20.01}, "/layer_config_ranges/2/values/extruder": {"eq": "2"}}}, + + // ---- A 3MF keeps them ---- + {"tool": "save_project", "args": {"path": "${out_dir}/layers.3mf", "overwrite": true}}, + {"tool": "new_project", "args": {"discard_changes": true}}, + // Loading a project asks about preset edits an earlier script left; the project brings its own. + {"tool": "dialog_auto_answer", "args": {"rules": [{"match": "unsaved changes", "button": "Discard"}]}}, + {"tool": "open_files", "args": {"paths": ["${out_dir}/layers.3mf"], "discard_changes": true}}, + {"tool": "list_objects", "expect": {"/items/0/layer_config_ranges/0/values/sparse_infill_density": {"eq": "40%"}, + "/items/0/layer_config_ranges/1/values/layer_height": {"eq": "0.1"}, + "/items/0/layer_config_ranges/2/values/extruder": {"eq": "2"}}}, + + // ---- [] removes them all ---- + {"tool": "set_layer_ranges", "args": {"object": 0, "layer_config_ranges": []}, "expect": {"/layer_config_ranges": {"eq": []}}}, + {"tool": "list_objects", "expect": {"/items/0/layer_config_ranges": {"exists": false}}}, + {"tool": "slice", "expect": {"/status": {"eq": "done"}, "/plates/0/outcome": {"eq": "ok"}}}, + {"tool": "set_view", "args": {"tab": "preview", "layer": 1}, "expect": {"/layers/2": {"eq": 100}}}, + + // ---- Variable layer height on a Benchy (48 mm; 240 layers at 0.2 mm), called from the Preview tab ---- + {"tool": "new_project", "args": {"discard_changes": true}}, + {"tool": "open_files", "args": {"paths": ["${vars.benchy}"]}, "expect": {"/added": {"eq": 1}}}, + {"tool": "set_settings", "args": {"scope": "print", "values": {"layer_height": 0.2, "initial_layer_print_height": 0.2}}}, + {"tool": "list_objects", "expect": {"/items/0/layer_height_profile": {"exists": false}}}, + {"tool": "slice", "expect": {"/status": {"eq": "done"}, "/plates/0/outcome": {"eq": "ok"}}}, + {"tool": "set_layer_height_profile", "args": {"object": 0, "action": "adaptive"}, + "expect": {"/height": {"ge": 47.99, "le": 48.01}, + "/layer_height_profile/points": {"gt": 250}, + "/layer_height_profile/min_height": {"lt": 0.2}, + "/layer_height_profile/max_height": {"gt": 0.2}, + "/warnings": {"exists": false}}}, + {"tool": "get_state", "expect": {"/tab": {"eq": "prepare"}}}, + {"tool": "list_objects", "expect": {"/items/0/layer_height_profile/points": {"gt": 250}}}, + // Toward quality more layers, toward speed fewer. + {"tool": "set_layer_height_profile", "args": {"object": 0, "action": "adaptive", "quality": 0}, + "expect": {"/layer_height_profile/points": {"gt": 380}}}, + {"tool": "set_layer_height_profile", "args": {"object": 0, "action": "adaptive", "quality": 1}, + "expect": {"/layer_height_profile/points": {"lt": 320}}}, + // The slicer prints the profile, not 240 layers of 0.2 mm. + {"tool": "slice", "expect": {"/status": {"eq": "done"}, "/plates/0/outcome": {"eq": "ok"}}}, + {"tool": "set_view", "args": {"tab": "preview", "layer": 1}, "expect": {"/layers/2": {"gt": 245}}}, + + // ---- Smooth is one undo step; Reset removes the profile, and again changes nothing ---- + {"tool": "set_layer_height_profile", "args": {"object": 0, "action": "smooth", "radius": 10, "keep_min": true}, + "expect": {"/layer_height_profile/max_height": {"lt": 0.28}}}, + {"tool": "run_action", "args": {"id": "orca_command:undo:orca"}}, + {"tool": "list_objects", "expect": {"/items/0/layer_height_profile/max_height": {"eq": 0.28}}}, + {"tool": "run_action", "args": {"id": "orca_command:redo:orca"}}, + {"tool": "list_objects", "expect": {"/items/0/layer_height_profile/max_height": {"lt": 0.28}}}, + {"tool": "set_layer_height_profile", "args": {"object": 0, "action": "reset"}, "expect": {"/layer_height_profile": {"exists": false}}}, + {"tool": "list_objects", "expect": {"/items/0/layer_height_profile": {"exists": false}}}, + {"tool": "set_layer_height_profile", "args": {"object": 0, "action": "reset"}}, + {"tool": "run_action", "args": {"id": "orca_command:undo:orca"}}, + {"tool": "list_objects", "expect": {"/items/0/layer_height_profile/max_height": {"lt": 0.28}}}, + {"tool": "set_layer_height_profile", "args": {"object": 0, "action": "reset"}}, + + // ---- Refusals change nothing: an argument of another action, the assemble view ---- + {"tool": "set_layer_height_profile", "args": {"object": 0, "action": "smooth", "quality": 0.3}, "optional": true}, + {"tool": "set_view", "args": {"view": "assemble"}}, + {"tool": "set_layer_height_profile", "args": {"object": 0, "action": "adaptive"}, "optional": true}, + {"tool": "set_view", "args": {"view": "3d"}}, + {"tool": "list_objects", "expect": {"/items/0/layer_height_profile": {"exists": false}}}, + + // ---- With height ranges: Smooth starts from the ranges' heights, Adaptive keeps them inside each + // range, and the profile then decides ---- + {"tool": "set_layer_ranges", + "args": {"object": 0, "layer_config_ranges": [{"min_z": 0, "max_z": 20, "values": {"layer_height": 0.12}}, + {"min_z": 20, "max_z": 48, "values": {"layer_height": 0.28}}]}}, + {"tool": "set_layer_height_profile", "args": {"object": 0, "action": "smooth"}, + "expect": {"/layer_height_profile/min_height": {"eq": 0.12}, + "/layer_height_profile/max_height": {"eq": 0.28}, + "/warnings/0": {"contains": "decides its layer heights"}}}, + {"tool": "set_layer_height_profile", "args": {"object": 0, "action": "adaptive", "quality": 0}, + "expect": {"/layer_height_profile/min_height": {"eq": 0.12}}}, + {"tool": "list_objects", "expect": {"/items/0/layer_config_ranges/1/values/layer_height": {"eq": "0.28"}, + "/items/0/layer_height_profile/min_height": {"eq": 0.12}}}, + + // ---- A 3MF keeps the profile ---- + {"tool": "save_project", "args": {"path": "${out_dir}/profile.3mf", "overwrite": true}}, + {"tool": "new_project", "args": {"discard_changes": true}}, + {"tool": "open_files", "args": {"paths": ["${out_dir}/profile.3mf"], "discard_changes": true}}, + {"tool": "list_objects", "expect": {"/items/0/layer_height_profile/min_height": {"eq": 0.12}, + "/items/0/layer_height_profile/points": {"gt": 100}}}, + {"tool": "slice", "expect": {"/status": {"eq": "done"}, "/plates/0/outcome": {"eq": "ok"}}}, + + // ---- Layer G-codes on a 20 mm cube of 100 layers of 0.2 mm: none before a slice ---- + {"tool": "new_project", "args": {"discard_changes": true}}, + {"tool": "open_files", "args": {"paths": ["${vars.cube}"]}, "expect": {"/added": {"eq": 1}}}, + {"tool": "transform", "args": {"object": 0, "size": [20, 20, 20]}}, + {"tool": "set_settings", "args": {"scope": "print", "values": {"layer_height": 0.2, "initial_layer_print_height": 0.2}}}, + {"tool": "set_layer_gcode", "args": {"add": [{"layer": 26, "type": "pause"}]}, "optional": true}, + {"tool": "get_state", "expect": {"/tab": {"eq": "prepare"}, "/slicing": {"eq": false}}}, + {"tool": "slice", "expect": {"/status": {"eq": "done"}, "/plates/0/outcome": {"eq": "ok"}}}, + + // ---- From Prepare: a pause by layer and custom G-code by a height between layers, which goes on + // the layer whose top is above it; the call shows the Preview ---- + {"tool": "set_view", "args": {"tab": "prepare"}}, + {"tool": "set_layer_gcode", "args": {"add": [{"layer": 26, "type": "pause"}, {"z": 10.1, "type": "custom", "gcode": "M104 S215"}]}, + "expect": {"/plate": {"eq": 0}, "/layers": {"eq": 100}, "/changed": {"eq": true}, + "/layer_gcode/0/type": {"eq": "pause"}, "/layer_gcode/0/layer": {"eq": 26}, "/layer_gcode/0/z": {"eq": 5.2}, + "/layer_gcode/1/type": {"eq": "custom"}, "/layer_gcode/1/layer": {"eq": 51}, "/layer_gcode/1/z": {"eq": 10.2}, + "/layer_gcode/1/gcode": {"eq": "M104 S215"}, "/layer_gcode/2": {"exists": false}, + "/note": {"contains": "slice it again"}}}, + {"tool": "get_state", "expect": {"/tab": {"eq": "preview"}, "/project/dirty": {"eq": true}}}, + + // ---- The plate stays editable while the Preview shows it: the same codes change nothing, and in one + // call the pause goes (by its height) and the custom text is replaced ---- + {"tool": "set_layer_gcode", "args": {"add": [{"z": 5.2, "type": "pause"}]}, + "expect": {"/changed": {"eq": false}, "/layer_gcode/0/layer": {"eq": 26}, "/layer_gcode/1/layer": {"eq": 51}}}, + {"tool": "set_layer_gcode", "args": {"remove": [{"z": 5.2}], "add": [{"layer": 51, "type": "custom", "gcode": "M104 S220"}]}, + "expect": {"/changed": {"eq": true}, "/layer_gcode/0/layer": {"eq": 51}, "/layer_gcode/0/gcode": {"eq": "M104 S220"}, + "/layer_gcode/1": {"exists": false}}}, + + // ---- Refusals change nothing: a layer above the top, another code where one is, nothing to remove, + // a filament the project lacks (it has the two the height ranges above used), a plate it lacks ---- + {"tool": "set_layer_gcode", "args": {"add": [{"layer": 101, "type": "pause"}]}, "optional": true}, + {"tool": "set_layer_gcode", "args": {"add": [{"layer": 51, "type": "pause"}]}, "optional": true}, + {"tool": "set_layer_gcode", "args": {"remove": [{"layer": 30}]}, "optional": true}, + {"tool": "set_layer_gcode", "args": {"add": [{"layer": 30, "type": "change_filament", "filament": 9}]}, "optional": true}, + {"tool": "set_layer_gcode", "args": {"plate": 1, "add": [{"layer": 30, "type": "pause"}]}, "optional": true}, + {"tool": "set_layer_gcode", "args": {"add": [{"layer": 51, "type": "custom", "gcode": "M104 S220"}]}, + "expect": {"/changed": {"eq": false}, "/layer_gcode/0/gcode": {"eq": "M104 S220"}, "/layer_gcode/1": {"exists": false}}}, + + // ---- Changed since its slice and not shown: refused without starting a slice ---- + {"tool": "set_view", "args": {"tab": "prepare"}}, + {"tool": "set_layer_gcode", "args": {"add": [{"layer": 30, "type": "pause"}]}, "optional": true}, + {"tool": "get_state", "expect": {"/tab": {"eq": "prepare"}, "/slicing": {"eq": false}}}, + + // ---- A filament change to the second filament ---- + {"tool": "slice", "expect": {"/status": {"eq": "done"}, "/plates/0/outcome": {"eq": "ok"}}}, + {"tool": "set_layer_gcode", "args": {"add": [{"layer": 76, "type": "change_filament", "filament": 2}]}, + "expect": {"/layer_gcode/0/layer": {"eq": 51}, "/layer_gcode/1/layer": {"eq": 76}, "/layer_gcode/1/z": {"eq": 15.2}, + "/layer_gcode/1/type": {"eq": "change_filament"}, "/layer_gcode/1/filament": {"eq": 2}, + "/layer_gcode/1/color": {"exists": true}}}, + {"tool": "slice", "expect": {"/status": {"eq": "done"}, "/plates/0/outcome": {"eq": "ok"}}}, + + // ---- A 3MF keeps them ---- + {"tool": "save_project", "args": {"path": "${out_dir}/layer_gcode.3mf", "overwrite": true}}, + {"tool": "new_project", "args": {"discard_changes": true}}, + {"tool": "open_files", "args": {"paths": ["${out_dir}/layer_gcode.3mf"], "discard_changes": true}}, + {"tool": "slice", "expect": {"/status": {"eq": "done"}, "/plates/0/outcome": {"eq": "ok"}}}, + {"tool": "set_layer_gcode", "args": {"add": [{"layer": 76, "type": "change_filament", "filament": 2}]}, + "expect": {"/changed": {"eq": false}, "/layer_gcode/0/gcode": {"eq": "M104 S220"}, + "/layer_gcode/1/filament": {"eq": 2}, "/layer_gcode/2": {"exists": false}}}, + + // ---- clear removes them all ---- + {"tool": "set_layer_gcode", "args": {"clear": true}, "expect": {"/changed": {"eq": true}, "/layer_gcode": {"eq": []}}}, + {"tool": "slice", "expect": {"/status": {"eq": "done"}, "/plates/0/outcome": {"eq": "ok"}}} + ] +} diff --git a/tools/mcp/tests/multicolor.json b/tools/mcp/tests/multicolor.json new file mode 100644 index 0000000000..b7e20629d0 --- /dev/null +++ b/tools/mcp/tests/multicolor.json @@ -0,0 +1,111 @@ +// Assigns filaments to objects and parts through set_settings, as the object list's Change Filament +// does, and reads them back with get_settings' effective values; then sets the project's slot colours, +// flushing volumes, plate type and prime tower position through the project scope. Run it with +// tools/mcp/orca_mcp.py run-script tools/mcp/tests/multicolor.json --out /tmp/multicolor +{ + "orca_script": 1, + "name": "object and part filaments", + "steps": [ + {"tool": "wait", "args": {"for": "ready"}}, + {"tool": "dialog_auto_answer", "args": {"rules": [{"match": "unsaved changes", "button": "no"}, + {"match": "restore", "button": "no"}, + {"match": "Uniform scale", "button": "ok"}]}}, + {"tool": "new_project", "args": {"discard_changes": true}}, + {"tool": "set_view", "args": {"tab": "prepare"}}, + // A second filament (or one more, on a datadir an earlier run left with several). + {"tool": "ui_click", "args": {"target": {"label": "Add one filament"}}}, + {"tool": "get_state", "expect": {"/presets/filaments/1": {"exists": true}}}, + + // Object 0 a cube, object 1 a cylinder. + {"tool": "run_action", "args": {"id": "orca_command:add_primitive_cube:orca"}}, + {"tool": "wait", "args": {"for": "idle"}}, + {"tool": "select", "args": {"none": true}}, + {"tool": "run_action", "args": {"id": "orca_command:add_primitive_cylinder:orca"}}, + {"tool": "wait", "args": {"for": "idle"}}, + {"tool": "transform", "args": {"object": 0, "translate": [100, 100, 12.8], "mode": "absolute"}}, + {"tool": "transform", "args": {"object": 1, "translate": [160, 100, 12.8], "mode": "absolute"}}, + + // ---- An object's filament, read back, undone and redone ---- + {"tool": "set_settings", "args": {"scope": "object", "object": 1, "values": {"extruder": 2}}, "expect": {"/applied/extruder": {"eq": "2"}}}, + {"tool": "get_settings", "args": {"scope": "object", "object": 1, "keys": ["extruder"]}, + "expect": {"/items/0/effective": {"eq": "2"}, "/items/0/source": {"eq": "object"}}}, + {"tool": "get_settings", "args": {"scope": "object", "object": 0, "keys": ["extruder"]}, "expect": {"/items/0/effective": {"eq": "1"}}}, + {"tool": "run_action", "args": {"id": "orca_command:undo:orca"}}, + {"tool": "get_settings", "args": {"scope": "object", "object": 1, "keys": ["extruder"]}, "expect": {"/items/0/effective": {"eq": "1"}}}, + {"tool": "run_action", "args": {"id": "orca_command:redo:orca"}}, + {"tool": "get_settings", "args": {"scope": "object", "object": 1, "keys": ["extruder"]}, "expect": {"/items/0/effective": {"eq": "2"}}}, + + // ---- A single-part object's volume 0 is the object: its filament is set there ---- + {"tool": "set_settings", "args": {"scope": "volume", "object": 1, "volume": 0, "values": {"extruder": 1}}, + "expect": {"/applied/extruder": {"eq": "1"}, "/note": {"exists": true}}}, + {"tool": "get_settings", "args": {"scope": "object", "object": 1, "keys": ["extruder"]}, "expect": {"/items/0/effective": {"eq": "1"}}}, + {"tool": "set_settings", "args": {"scope": "object", "object": 1, "values": {"extruder": 2}}}, + + // ---- A text part on the cube takes filament 2; the object's reply lists it apart ---- + {"tool": "select", "args": {"objects": [0]}}, + {"tool": "ui_click", "args": {"target": {"gizmo": "Text"}}, "expect": {"/created": {"eq": true}, "/active": {"eq": true}}}, + {"tool": "wait", "args": {"for": "idle"}}, + {"tool": "ui_click", "args": {"target": {"imgui": "Done"}}}, + {"tool": "list_objects", "expect": {"/items/0/volumes/1/text": {"exists": true}}}, + {"tool": "set_settings", "args": {"scope": "volume", "object": 0, "volume": 1, "values": {"extruder": 2}}, "expect": {"/applied/extruder": {"eq": "2"}}}, + {"tool": "get_settings", "args": {"scope": "volume", "object": 0, "volume": 1, "keys": ["extruder"]}, + "expect": {"/items/0/effective": {"eq": "2"}, "/items/0/source": {"eq": "part"}, "/note": {"exists": true}}}, + {"tool": "get_settings", "args": {"scope": "object", "object": 0, "keys": ["extruder"]}, + "expect": {"/items/0/effective": {"eq": "1"}, "/items/0/parts/0/volume": {"eq": 1}, "/items/0/parts/0/value": {"eq": "2"}, "/note": {"exists": true}}}, + // Default on a part is its object's filament. + {"tool": "set_settings", "args": {"scope": "volume", "object": 0, "volume": 1, "values": {"extruder": null}}, "expect": {"/applied/extruder": {"eq": "1"}}}, + {"tool": "set_settings", "args": {"scope": "volume", "object": 0, "volume": 1, "values": {"extruder": 2}}}, + + // ---- A filament and another setting in one call are one undo step; the object's filament clears the part's ---- + {"tool": "set_settings", "args": {"scope": "object", "object": 0, "values": {"extruder": 2, "wall_loops": 5}}, + "expect": {"/applied/extruder": {"eq": "2"}, "/applied/wall_loops": {"eq": "5"}}}, + {"tool": "get_settings", "args": {"scope": "object", "object": 0, "keys": ["extruder", "wall_loops"]}, + "expect": {"/items/0/effective": {"eq": "2"}, "/items/0/parts": {"exists": false}, "/items/1/source": {"eq": "object"}}}, + {"tool": "run_action", "args": {"id": "orca_command:undo:orca"}}, + {"tool": "get_settings", "args": {"scope": "object", "object": 0, "keys": ["extruder", "wall_loops"]}, + "expect": {"/items/0/effective": {"eq": "1"}, "/items/0/parts/0/value": {"eq": "2"}, "/items/1/value": {"eq": null}, "/items/1/source": {"eq": "process"}}}, + + // ---- Project settings. Entries by index, since a reused datadir may start with more slots ---- + {"tool": "get_settings", "args": {"scope": "project", "keys": ["filament_is_mixed", "curr_bed_type", "prime_volume_mode"]}, + "expect": {"/items/0/meta/read_only": {"eq": true}, "/items/0/value": {"regex": "^0,0"}, + "/items/1/meta/offered": {"contains": "Textured PEI Plate"}, "/items/2/meta/offered": {"empty": true}}}, + {"tool": "set_settings", "args": {"scope": "project", "values": {"filament_colour": {"index": 0, "value": "#ffffff"}}}, + "expect": {"/applied/filament_colour": {"regex": "^#FFFFFF;"}}}, + // A colour, the multiplier, one matrix entry and the plate type in one call: the colour goes first, so its + // recalculated flushing volumes do not replace the entry given. + {"tool": "set_settings", "args": {"scope": "project", "values": {"filament_colour": {"index": 1, "value": "#000000"}, + "flush_multiplier": 0.7, + "flush_volumes_matrix": {"index": 1, "value": 400}, + "curr_bed_type": "Textured PEI Plate"}}, + "expect": {"/applied/filament_colour": {"regex": "^#FFFFFF;#000000"}, "/applied/flush_multiplier": {"eq": "0.7"}, + "/applied/flush_volumes_matrix": {"regex": "^0,400,"}, "/applied/curr_bed_type": {"eq": "Textured PEI Plate"}}}, + {"tool": "get_settings", "args": {"scope": "project", "keys": ["filament_colour", "flush_volumes_matrix", "flush_multiplier", "curr_bed_type"]}, + "expect": {"/items/0/value": {"regex": "^#FFFFFF;#000000"}, "/items/1/value": {"regex": "^0,400,"}, "/items/2/value": {"eq": "0.7"}, + "/items/3/value": {"eq": "Textured PEI Plate"}}}, + // Refused, and nothing changes: a mixed flag, a bad colour together with a valid multiplier, a purge mode the + // X1C has no button for, a non-zero diagonal. + {"tool": "set_settings", "args": {"scope": "project", "values": {"filament_is_mixed": "1"}}, "optional": true}, + {"tool": "set_settings", "args": {"scope": "project", "values": {"filament_colour": {"index": 0, "value": "white"}, "flush_multiplier": 0.5}}, + "optional": true}, + {"tool": "set_settings", "args": {"scope": "project", "values": {"prime_volume_mode": "Saving"}}, "optional": true}, + {"tool": "set_settings", "args": {"scope": "project", "values": {"flush_volumes_matrix": {"index": 0, "value": 10}}}, "optional": true}, + {"tool": "get_settings", "args": {"scope": "project", "keys": ["filament_colour", "flush_multiplier", "flush_volumes_matrix", "filament_is_mixed"]}, + "expect": {"/items/0/value": {"regex": "^#FFFFFF;"}, "/items/1/value": {"eq": "0.7"}, "/items/2/value": {"regex": "^0,400,"}, + "/items/3/value": {"regex": "^0,0"}}}, + // The prime tower of plate 0, moved twice; undo puts it back where the first move left it. + {"tool": "set_settings", "args": {"scope": "project", "values": {"wipe_tower_x": {"index": 0, "value": 150}, "wipe_tower_y": {"index": 0, "value": 180}}}, + "expect": {"/applied/wipe_tower_x": {"regex": "^150(,|$)"}, "/applied/wipe_tower_y": {"regex": "^180(,|$)"}}}, + {"tool": "set_settings", "args": {"scope": "project", "values": {"wipe_tower_x": {"index": 0, "value": 40}}}, + "expect": {"/applied/wipe_tower_x": {"regex": "^40(,|$)"}}}, + {"tool": "run_action", "args": {"id": "orca_command:undo:orca"}}, + {"tool": "get_settings", "args": {"scope": "project", "keys": ["wipe_tower_x", "wipe_tower_y"]}, + "expect": {"/items/0/value": {"regex": "^150(,|$)"}, "/items/1/value": {"regex": "^180(,|$)"}}}, + {"tool": "set_settings", "args": {"scope": "project", "values": {"wipe_tower_x": {"index": 0, "value": 300}}}, "optional": true}, + + {"tool": "slice", "expect": {"/status": {"eq": "done"}, "/plates/0/outcome": {"eq": "ok"}}}, + {"tool": "set_view", "args": {"tab": "prepare", "camera": "iso"}}, + {"tool": "screenshot", "args": {"target": "canvas", "save_path": "${out_dir}/filaments.png", "overwrite": true, "include_image": false}}, + // The plate type is remembered per printer; back to the bench datadir's. + {"tool": "set_settings", "args": {"scope": "project", "values": {"curr_bed_type": "Cool Plate"}}} + ] +} diff --git a/tools/mcp/tests/plate_icons.json b/tools/mcp/tests/plate_icons.json new file mode 100644 index 0000000000..380d51cc84 --- /dev/null +++ b/tools/mcp/tests/plate_icons.json @@ -0,0 +1,57 @@ +// Plate icons as targets: {plate_icon, plate} does what a click on the Prepare view's icon does. Lock +// twice, Plate Settings opened and cancelled, a second plate's two cubes spread by its arrange icon +// (the reply follows the job), the plate menu from a right click, listed and run, and move to front. +// Run it on a fresh datadir set up with the default printer (Bambu Lab X1 Carbon 0.4): +// tools/mcp/orca_mcp.py run-script tools/mcp/tests/plate_icons.json --out /tmp/plate_icons +// The name <-> picking id table is a unit test in tests/slic3rutils/test_mcp_results.cpp; the +// refusals (an icon the plate does not show, a plate that does not exist, an open gizmo, the Preview) +// can't be expected in a script. +{ + "orca_script": 1, + "name": "plate icons", + "steps": [ + {"tool": "wait", "args": {"for": "ready"}}, + {"tool": "dialog_auto_answer", "args": {"rules": [{"match": "Uniform scale", "button": "ok"}]}}, + {"tool": "new_project", "args": {"discard_changes": true}}, + {"tool": "set_view", "args": {"tab": "prepare"}}, + {"tool": "ui_snapshot", "args": {"root": "main", "query": "plate_icon"}, "expect": {"/nodes": {"ge": 7}}}, + + // ---- Lock toggles the plate's lock ---- + {"tool": "ui_click", "args": {"target": {"plate_icon": "lock", "plate": 0}}, "expect": {"/locked": {"eq": true}}}, + {"tool": "ui_click", "args": {"target": {"plate_icon": "lock", "plate": 0}}, "expect": {"/locked": {"eq": false}}}, + + // ---- Settings opens Plate Settings from a posted event; the reply names it ---- + {"tool": "ui_click", "args": {"target": {"plate_icon": "settings", "plate": 0}}, + "expect": {"/dialogs/0/title": {"contains": "Plate"}}}, + {"tool": "dialog_respond", "args": {"dialog": {"title": "Plate Settings"}, "button": "cancel"}}, + + // ---- A second plate with two cubes on one spot: its arrange icon spreads them ---- + {"tool": "ui_click", "args": {"target": {"gltoolbar": "addplate"}}}, + {"tool": "wait", "args": {"for": "idle"}}, + {"tool": "run_action", "args": {"id": "orca_command:add_primitive_cube:orca"}}, + {"tool": "select", "args": {"none": true}}, + {"tool": "run_action", "args": {"id": "orca_command:add_primitive_cube:orca"}}, + {"tool": "wait", "args": {"for": "idle"}}, + {"tool": "list_objects", "expect": {"/total": {"eq": 2}, + "/items/0/instances/0/plate": {"eq": 1}, "/items/1/instances/0/plate": {"eq": 1}, + "/items/0/instances/0/offset/1": {"eq": 128.0}, "/items/1/instances/0/offset/1": {"eq": 128.0}}}, + {"tool": "ui_click", "args": {"target": {"plate_icon": "arrange", "plate": 1}}, + "expect": {"/started": {"eq": true}, "/done": {"eq": true}}}, + {"tool": "wait", "args": {"for": "idle", "timeout_s": 2}, "expect": {"/satisfied": {"eq": true}}}, + {"tool": "list_objects", "expect": {"/items/0/instances/0/plate": {"eq": 1}, "/items/1/instances/0/plate": {"eq": 1}, + "/items/0/instances/0/offset/1": {"ne": 128.0}, "/items/1/instances/0/offset/1": {"ne": 128.0}}}, + + // ---- A right click opens the plate menu: listed, or one of its items run ---- + {"tool": "ui_click", "args": {"target": {"plate_icon": "plate", "plate": 1}, "button": "right"}, + "expect": {"/popup_menu/items": {"contains": "Edit Plate Name"}}}, + {"tool": "ui_click", "args": {"target": {"plate_icon": "plate", "plate": 1}, "button": "right", "popup_item": "Lock"}, + "expect": {"/ran": {"eq": "Lock"}}}, + {"tool": "ui_click", "args": {"target": {"plate_icon": "lock", "plate": 1}}, "expect": {"/locked": {"eq": false}}}, + + // ---- Move to front: the second plate becomes the first, with its cubes ---- + {"tool": "ui_click", "args": {"target": {"plate_icon": "move_to_front", "plate": 1}}, "expect": {"/current": {"eq": 0}}}, + {"tool": "get_state", "expect": {"/plates/current": {"eq": 0}, "/plates/count": {"eq": 2}}}, + {"tool": "list_objects", "expect": {"/items/0/instances/0/plate": {"eq": 0}, "/items/1/instances/0/plate": {"eq": 0}}}, + {"tool": "get_state", "expect": {"/dialogs": {"empty": true}, "/closed_menus": {"empty": true}}} + ] +} diff --git a/tools/mcp/tests/plates.json b/tools/mcp/tests/plates.json new file mode 100644 index 0000000000..e7c0644980 --- /dev/null +++ b/tools/mcp/tests/plates.json @@ -0,0 +1,135 @@ +// Sets plate settings through set_settings' plate scope, as the Plate Settings dialog and the plate's +// lock and name icons do, and reads them back with list_plates and get_settings: a plate type and +// print sequence on one plate only, undone and redone, the first and other layers' filament orders, +// spiral vase after its question, the lock set twice and a name. It starts by bringing the filament +// list to two slots with the filament_add and filament_delete commands, checks the refusals that leave +// everything as it was, and ends with a mixed filament: its slot cannot be deleted, a new slot goes +// ahead of it, and the custom filament orders are refused meanwhile. It starts from the harness's +// default printer (Bambu Lab X1 Carbon) and reruns on the same datadir. Run it with +// tools/mcp/orca_mcp.py run-script tools/mcp/tests/plates.json --out /tmp/plates +{ + "orca_script": 1, + "name": "plate settings and filament slots", + "steps": [ + {"tool": "wait", "args": {"for": "ready"}}, + {"tool": "dialog_auto_answer", "args": {"rules": [{"match": "unsaved changes", "button": "no"}, + {"match": "restore", "button": "no"}, + {"match": "Uniform scale", "button": "ok"}, + {"match": "Spiral mode only works", "button": "yes"}]}}, + {"tool": "new_project", "args": {"discard_changes": true}}, + {"tool": "set_view", "args": {"tab": "prepare"}}, + + // ---- Filament slots: down to one with the - button's command, then a second ---- + {"tool": "run_action", "args": {"id": "orca_command:filament_delete:orca"}}, + {"tool": "run_action", "args": {"id": "orca_command:filament_delete:orca"}}, + {"tool": "run_action", "args": {"id": "orca_command:filament_delete:orca"}}, + {"tool": "run_action", "args": {"id": "orca_command:filament_delete:orca"}}, + {"tool": "get_state", "expect": {"/presets/filaments/0": {"exists": true}, "/presets/filaments/1": {"exists": false}}}, + {"tool": "run_action", "args": {"id": "orca_command:filament_delete:orca"}, "expect": {"/level": {"eq": "info"}}}, + {"tool": "run_action", "args": {"id": "orca_command:filament_add:orca"}, + "expect": {"/level": {"eq": "success"}, "/message": {"eq": "Added filament slot 2."}}}, + {"tool": "run_action", "args": {"id": "orca_command:filament_add:orca"}, "expect": {"/message": {"eq": "Added filament slot 3."}}}, + // A slot past the last is refused; slot 2 by number. + {"tool": "run_action", "args": {"id": "orca_command:filament_delete:orca", "param": "4"}, "optional": true}, + {"tool": "run_action", "args": {"id": "orca_command:filament_delete:orca", "param": "2"}, "expect": {"/message": {"eq": "Deleted filament slot 2."}}}, + {"tool": "get_settings", "args": {"scope": "project", "keys": ["filament_is_mixed"]}, "expect": {"/items/0/value": {"eq": "0,0"}}}, + + // ---- A cube on each of two plates ---- + {"tool": "run_action", "args": {"id": "orca_command:add_primitive_cube:orca"}}, + {"tool": "wait", "args": {"for": "idle"}}, + {"tool": "run_action", "args": {"id": "orca_command:plate_add:orca"}}, + {"tool": "run_action", "args": {"id": "orca_command:plate_goto:orca", "param": "1"}}, + {"tool": "select", "args": {"none": true}}, + {"tool": "run_action", "args": {"id": "orca_command:add_primitive_cube:orca"}}, + {"tool": "wait", "args": {"for": "idle"}}, + {"tool": "list_plates", "save_as": "start", + "expect": {"/total": {"eq": 2}, "/items/0/objects/0": {"eq": [0, 0]}, "/items/1/objects/0": {"eq": [1, 0]}, + "/items/0/overrides": {"empty": true}, "/items/1/overrides": {"empty": true}, "/items/1/current": {"eq": true}, + "/items/0/locked": {"eq": false}, "/items/0/print_sequence": {"eq": "by layer"}, "/items/0/spiral_mode": {"eq": false}, + "/items/0/first_layer_print_sequence": {"eq": null}, "/items/0/layer_gcode": {"empty": true}, + "/items/0/wipe_tower": {"exists": true}}}, + + // ---- Plate 1's own plate type and print sequence; plate 0 keeps the global ones ---- + {"tool": "run_action", "args": {"id": "orca_command:plate_goto:orca", "param": "0"}}, + {"tool": "set_settings", "args": {"scope": "plate", "plate": 1, "values": {"curr_bed_type": "Textured PEI Plate", "print_sequence": "by object"}}, + "expect": {"/plate": {"eq": 1}, "/applied/curr_bed_type": {"eq": "Textured PEI Plate"}, "/applied/print_sequence": {"eq": "by object"}, + "/changed/curr_bed_type": {"eq": "Textured PEI Plate"}}}, + {"tool": "list_plates", + "expect": {"/items/1/curr_bed_type": {"eq": "Textured PEI Plate"}, "/items/1/print_sequence": {"eq": "by object"}, + "/items/1/overrides": {"eq": ["curr_bed_type", "print_sequence"]}, "/items/1/current": {"eq": true}, + "/items/0/overrides": {"empty": true}, "/items/0/print_sequence": {"eq": "by layer"}}}, + {"tool": "get_settings", "args": {"scope": "plate", "plate": 1, "keys": ["curr_bed_type", "spiral_mode"]}, + "expect": {"/plate": {"eq": 1}, "/items/0/value": {"eq": "Textured PEI Plate"}, "/items/0/meta/offered": {"contains": "Cool Plate"}, + "/items/1/value": {"eq": null}, "/items/1/effective": {"eq": false}}}, + {"tool": "run_action", "args": {"id": "orca_command:undo:orca"}}, + {"tool": "list_plates", "expect": {"/items/1/overrides": {"empty": true}}}, + {"tool": "run_action", "args": {"id": "orca_command:redo:orca"}}, + {"tool": "list_plates", "expect": {"/items/1/print_sequence": {"eq": "by object"}}}, + // null is "Same as Global". + {"tool": "set_settings", "args": {"scope": "plate", "plate": 1, "values": {"print_sequence": null}}, + "expect": {"/applied/print_sequence": {"eq": null}, "/effective/print_sequence": {"eq": "by layer"}}}, + + // ---- Refusals, each leaving the plate as it was ---- + {"tool": "set_settings", "args": {"scope": "plate", "plate": 1, "values": {"curr_bed_type": "Glass Plate", "locked": true}}, "optional": true}, + {"tool": "set_settings", "args": {"scope": "plate", "plate": 0, "values": {"first_layer_print_sequence": [1, 1]}}, "optional": true}, + {"tool": "set_settings", "args": {"scope": "plate", "plate": 0, "values": {"other_layers_print_sequence": [{"from": 2, "order": [1, 2]}, {"from": 5, "to": 9, "order": [2, 1]}]}}, "optional": true}, + {"tool": "set_settings", "args": {"scope": "plate", "plate": 0, "values": {"skirt_start_angle": 90}}, "optional": true}, + {"tool": "set_settings", "args": {"scope": "plate", "plate": 2, "values": {"locked": true}}, "optional": true}, + {"tool": "list_plates", + "expect": {"/items/1/locked": {"eq": false}, "/items/1/overrides": {"eq": ["curr_bed_type"]}, "/items/0/overrides": {"empty": true}}}, + + // ---- The first and the other layers' filament orders ---- + {"tool": "set_settings", "args": {"scope": "plate", "plate": 0, "values": { + "first_layer_print_sequence": [2, 1], + "other_layers_print_sequence": [{"from": 10, "order": [1, 2]}, {"from": 2, "to": 9, "order": [2, 1]}]}}, + "expect": {"/applied/first_layer_print_sequence": {"eq": [2, 1]}, + "/applied/other_layers_print_sequence": {"eq": [{"from": 2, "to": 9, "order": [2, 1]}, {"from": 10, "order": [1, 2]}]}}}, + {"tool": "list_plates", + "expect": {"/items/0/current": {"eq": true}, "/items/0/first_layer_print_sequence": {"eq": [2, 1]}, + "/items/0/other_layers_print_sequence/1/to": {"exists": false}, + "/items/0/overrides": {"eq": ["first_layer_print_sequence", "other_layers_print_sequence"]}}}, + {"tool": "set_settings", "args": {"scope": "plate", "values": {"first_layer_print_sequence": null, "other_layers_print_sequence": null}}, + "expect": {"/plate": {"eq": 0}, "/changed/first_layer_print_sequence": {"eq": null}}}, + + // ---- Spiral vase on one plate, after its question ---- + {"tool": "set_settings", "args": {"scope": "plate", "plate": 0, "values": {"spiral_mode": true}}, + "expect": {"/applied/spiral_mode": {"eq": true}, "/effective/spiral_mode": {"eq": true}}}, + {"tool": "list_plates", "expect": {"/items/0/spiral_mode": {"eq": true}, "/items/1/spiral_mode": {"eq": false}}}, + {"tool": "set_settings", "args": {"scope": "plate", "plate": 0, "values": {"spiral_mode": null}}, "expect": {"/applied/spiral_mode": {"eq": null}}}, + + // ---- The lock is set, not toggled: twice leaves it locked ---- + {"tool": "set_settings", "args": {"scope": "plate", "plate": 1, "values": {"locked": true}}, "expect": {"/changed/locked": {"eq": true}}}, + {"tool": "set_settings", "args": {"scope": "plate", "plate": 1, "values": {"locked": true}}, + "expect": {"/applied/locked": {"eq": true}, "/changed": {"empty": true}}}, + {"tool": "list_plates", "expect": {"/items/1/locked": {"eq": true}, "/items/0/locked": {"eq": false}}}, + {"tool": "get_settings", "args": {"scope": "plate", "plate": 1, "keys": ["locked", "name"]}, + "expect": {"/items/0/value": {"eq": true}, "/items/1/value": {"eq": ""}}}, + {"tool": "set_settings", "args": {"scope": "plate", "plate": 1, "values": {"locked": false}}, "expect": {"/changed/locked": {"eq": false}}}, + + // ---- A name without the rename dialog ---- + {"tool": "set_settings", "args": {"scope": "plate", "plate": 1, "values": {"name": "Batch"}}, "expect": {"/changed/name": {"eq": "Batch"}}}, + {"tool": "list_plates", "expect": {"/items/1/name": {"eq": "Batch"}, "/items/1/current": {"eq": true}}}, + + // ---- Sliced, with no layer G-codes ---- + {"tool": "slice", "args": {"plates": 1}, "expect": {"/plates/0/outcome": {"eq": "ok"}}}, + {"tool": "list_plates", "expect": {"/items/1/sliced": {"eq": true}, "/items/1/layer_gcode": {"empty": true}}}, + + // ---- A mixed filament: its slot is refused, a new slot goes ahead of it, custom orders wait ---- + {"tool": "ui_click", "args": {"target": {"label": "Add Mixed Filament"}}, "await": false, "save_as": "mix"}, + {"tool": "wait", "args": {"for": "dialog"}}, + {"tool": "get_state", "expect": {"/dialogs/0/title": {"eq": "Add Mixed Filament"}}}, + {"tool": "dialog_respond", "args": {"button": "OK"}}, + {"tool": "wait", "args": {"for": "job", "job": "${jobs.mix}"}}, + {"tool": "get_settings", "args": {"scope": "project", "keys": ["filament_is_mixed"]}, "expect": {"/items/0/value": {"eq": "0,0,1"}}}, + {"tool": "run_action", "args": {"id": "orca_command:filament_delete:orca", "param": "3"}, "optional": true}, + {"tool": "set_settings", "args": {"scope": "plate", "plate": 0, "values": {"first_layer_print_sequence": [2, 1]}}, "optional": true}, + {"tool": "list_plates", "expect": {"/items/0/first_layer_print_sequence": {"eq": null}}}, + {"tool": "run_action", "args": {"id": "orca_command:filament_add:orca"}, "expect": {"/message": {"eq": "Added filament slot 3."}}}, + {"tool": "get_settings", "args": {"scope": "project", "keys": ["filament_is_mixed"]}, "expect": {"/items/0/value": {"eq": "0,0,0,1"}}}, + {"tool": "run_action", "args": {"id": "orca_command:filament_delete:orca"}, "expect": {"/message": {"eq": "Deleted filament slot 3."}}}, + {"tool": "ui_click", "args": {"target": {"label": "Remove last mixed filament"}}}, + {"tool": "get_settings", "args": {"scope": "project", "keys": ["filament_is_mixed"]}, "expect": {"/items/0/value": {"eq": "0,0"}}}, + + {"tool": "new_project", "args": {"discard_changes": true}} + ] +} diff --git a/tools/mcp/tests/presets.json b/tools/mcp/tests/presets.json new file mode 100644 index 0000000000..d4f2aaac96 --- /dev/null +++ b/tools/mcp/tests/presets.json @@ -0,0 +1,337 @@ +// Saves presets with save_preset, as the tab's Save and the Save preset dialog do, and drops unsaved +// edits with set_settings reset_all, reading both back with list_presets and get_settings. It also +// reads presets that are not selected, compares presets, writes one entry of a per-variant value and +// reads the settings the app adjusts in turn (set_settings changed). It reverts single keys and answers +// the unsaved-changes prompts of a preset switch and a new project, with and without changes, and +// deletes the presets it made with delete_preset, selected or not. It exports a filament with the Export +// Preset Bundle dialog to its out_dir and imports it again with a path, and changes a preference in the +// Preferences dialog, reading it back with get_settings. It starts from the harness's default printer +// (Bambu Lab X1 Carbon, Bambu PLA Basic) with one filament slot in Simple mode; it deletes other slots and +// selects the mode first, so it also runs after scripts that leave more slots or another mode. Preset files +// stay in the datadir, so the first save of each name passes overwrite and the script reruns. Run it with +// tools/mcp/orca_mcp.py run-script tools/mcp/tests/presets.json --out /tmp/presets +{ + "orca_script": 1, + "name": "save presets and drop edits", + "steps": [ + {"tool": "wait", "args": {"for": "ready"}}, + {"tool": "dialog_auto_answer", "args": {"rules": [{"match": "restore", "button": "no"}, {"match": "Uniform scale", "button": "ok"}]}}, + // Unsaved edits a person (or an earlier run) left are dropped first, so nothing below asks about them. + {"tool": "new_project", "args": {"discard_changes": true, "changes": "discard"}}, + // The unsaved-changes prompt lists only the settings the mode shows, and Simple mode also turns + // Developer mode off, which the detach refusal below needs. + {"tool": "run_action", "args": {"id": "orca_command:mode_simple:orca"}}, + // One filament slot, as on a fresh datadir: with several, choosing a slot's filament leaves the filament + // tab where it is, so the filament prompts below would not open. + {"tool": "run_action", "args": {"id": "orca_command:filament_delete:orca"}, "optional": true}, + {"tool": "run_action", "args": {"id": "orca_command:filament_delete:orca"}, "optional": true}, + {"tool": "run_action", "args": {"id": "orca_command:filament_delete:orca"}, "optional": true}, + {"tool": "run_action", "args": {"id": "orca_command:filament_delete:orca"}, "optional": true}, + {"tool": "get_state", "expect": {"/presets/filaments/1": {"exists": false}}}, + {"tool": "select_preset", "args": {"type": "printer", "name": "Bambu Lab X1 Carbon 0.4 nozzle"}}, + {"tool": "select_preset", "args": {"type": "process", "name": "0.20mm Standard @BBL X1C"}}, + {"tool": "select_preset", "args": {"type": "filament", "name": "Bambu PLA Basic", "filament_slot": 1}}, + + // ---- A tuned filament saved as a user preset, selected in its slot ---- + // Keys with one value for every extruder variant; a scalar would collapse a per-variant one. + {"tool": "set_settings", "args": {"scope": "filament", "values": {"filament_cost": 21.5, "slow_down_layer_time": 6, "temperature_vitrification": 50}}}, + {"tool": "save_preset", "args": {"type": "filament", "name": "MCP Test PLA", "overwrite": true}, + "expect": {"/saved": {"eq": "MCP Test PLA"}, "/user": {"eq": true}, "/project": {"eq": false}, + "/inherits": {"eq": "Bambu PLA Basic @BBL X1C"}, "/selected": {"eq": true}, "/filament_slots/0": {"eq": 1}}}, + {"tool": "list_presets", "args": {"type": "filament", "query": "MCP Test PLA"}, + "expect": {"/items/0/name": {"eq": "MCP Test PLA"}, "/items/0/selected": {"eq": true}, "/items/0/modified": {"exists": false}, + "/items/0/inherits": {"eq": "Bambu PLA Basic @BBL X1C"}}}, + // Saved from a system filament, it is compatible with the selected printer only, as in the GUI. + {"tool": "get_settings", "args": {"scope": "filament", "keys": ["filament_cost", "compatible_printers"], "include_meta": false}, + "expect": {"/items/0/value": {"eq": "21.5"}, "/items/1/value": {"contains": "Bambu Lab X1 Carbon 0.4 nozzle"}}}, + // Saving the selected preset under its own name is the plain Save: no overwrite needed. + {"tool": "set_settings", "args": {"scope": "filament", "values": {"filament_cost": 22}}}, + {"tool": "save_preset", "args": {"type": "filament", "name": "MCP Test PLA"}, "expect": {"/saved": {"eq": "MCP Test PLA"}}}, + // Nothing is left unsaved; against the preset it inherits from, it differs in what was tuned. + {"tool": "get_settings", "args": {"scope": "filament", "compare": ":saved"}, "expect": {"/total": {"eq": 0}}}, + {"tool": "get_settings", "args": {"scope": "filament", "compare": ":parent", "keys": ["filament_cost", "slow_down_layer_time", "nozzle_temperature"]}, + "expect": {"/right": {"eq": "Bambu PLA Basic @BBL X1C"}, "/total": {"eq": 2}, "/items/0/key": {"eq": "filament_cost"}, + "/items/0/value": {"eq": "22"}, "/items/1/key": {"eq": "slow_down_layer_time"}}}, + + // ---- Another preset's name is replaced only with overwrite ---- + {"tool": "set_settings", "args": {"scope": "filament", "values": {"filament_cost": 23}}}, + {"tool": "save_preset", "args": {"type": "filament", "name": "MCP Test PLA 2", "overwrite": true}, "expect": {"/filament_slots/0": {"eq": 1}}}, + // Expected to fail ("already exists"); the next step checks that nothing changed. + {"tool": "save_preset", "args": {"type": "filament", "name": "MCP Test PLA"}, "optional": true}, + {"tool": "list_presets", "args": {"type": "filament", "query": "MCP Test PLA"}, + "expect": {"/items/0/selected": {"exists": false}, "/items/1/name": {"eq": "MCP Test PLA 2"}, "/items/1/selected": {"eq": true}}}, + {"tool": "save_preset", "args": {"type": "filament", "name": "MCP Test PLA", "overwrite": true}, "expect": {"/selected": {"eq": true}}}, + {"tool": "get_settings", "args": {"scope": "filament", "keys": ["filament_cost"], "include_meta": false}, "expect": {"/items/0/value": {"eq": "23"}}}, + + // ---- reset_all drops the unsaved edits, then values apply ---- + {"tool": "set_settings", "args": {"scope": "process", "values": {"wall_loops": 7, "sparse_infill_density": "37%"}}}, + {"tool": "set_settings", "args": {"scope": "process", "reset_all": true, "values": {"wall_loops": 7}}, + "expect": {"/reverted": {"contains": "sparse_infill_density"}, "/applied/wall_loops": {"eq": "7"}}}, + {"tool": "get_settings", "args": {"scope": "process", "keys": ["sparse_infill_density", "wall_loops"], "include_meta": false}, + "expect": {"/items/0/value": {"ne": "37%"}, "/items/1/value": {"eq": "7"}}}, + {"tool": "set_settings", "args": {"scope": "process", "reset_all": true}, "expect": {"/reverted": {"eq": ["wall_loops"]}}}, + {"tool": "set_settings", "args": {"scope": "process", "reset_all": true}, "expect": {"/reverted": {"empty": true}}}, + // A bad value fails before the reset, so the edit stays. + {"tool": "set_settings", "args": {"scope": "process", "values": {"wall_loops": 6}}}, + {"tool": "set_settings", "args": {"scope": "process", "reset_all": true, "values": {"wall_loops": "six"}}, "optional": true}, + {"tool": "get_settings", "args": {"scope": "process", "keys": ["wall_loops"], "include_meta": false}, "expect": {"/items/0/value": {"eq": "6"}}}, + + // ---- Presets read without selecting them, and compared ---- + {"tool": "set_settings", "args": {"scope": "process", "reset_all": true, "values": {"wall_loops": 5, "sparse_infill_density": "25%"}}, + "expect": {"/changed/wall_loops": {"eq": "5"}, "/changed/sparse_infill_density": {"eq": "25%"}}}, + // ":saved" lists exactly the unsaved edits. + {"tool": "get_settings", "args": {"scope": "process", "compare": ":saved"}, + "expect": {"/total": {"eq": 2}, "/left": {"eq": "0.20mm Standard @BBL X1C (edited)"}, "/items/0/key": {"eq": "sparse_infill_density"}, + "/items/0/value": {"eq": "25%"}, "/items/0/other": {"eq": "15%"}, "/items/1/key": {"eq": "wall_loops"}}}, + // A named preset is read as saved, without the edits and without selecting it. + {"tool": "get_settings", "args": {"scope": "process", "preset": "0.20mm Standard @BBL X1C", "keys": ["wall_loops"], "include_meta": false}, + "expect": {"/items/0/value": {"eq": "2"}}}, + {"tool": "get_settings", "args": {"scope": "process", "preset": "0.16mm Optimal @BBL X1C", "keys": ["layer_height"], "include_meta": false}, + "expect": {"/items/0/value": {"eq": "0.16"}}}, + {"tool": "get_state", "expect": {"/presets/process": {"eq": "0.20mm Standard @BBL X1C"}}}, + {"tool": "get_settings", "args": {"scope": "process", "compare": "0.16mm Optimal @BBL X1C", "keys": ["layer_height", "wall_loops"]}, + "expect": {"/right": {"eq": "0.16mm Optimal @BBL X1C"}, "/items/0/key": {"eq": "layer_height"}, "/items/0/value": {"eq": "0.2"}, + "/items/0/other": {"eq": "0.16"}, "/items/1/key": {"eq": "wall_loops"}, "/items/1/other": {"eq": "2"}}}, + // An enum's meta lists the labels the GUI shows next to its values. + {"tool": "get_settings", "args": {"scope": "process", "keys": ["fuzzy_skin"]}, + "expect": {"/items/0/meta/values/1": {"eq": "external"}, "/items/0/meta/labels/1": {"eq": "Contour"}}}, + + // ---- Per-variant values: the X1C's process and filament hold one entry per nozzle flow type ---- + {"tool": "get_settings", "args": {"scope": "process", "keys": ["outer_wall_speed"]}, + "expect": {"/items/0/meta/variants": {"eq": ["Direct Drive Standard", "Direct Drive High Flow"]}, "/items/0/meta/active": {"eq": [0]}}}, + // A single value writes the entry in use (Direct Drive Standard), as typing into the tab's field does; + // the High Flow entry keeps its value. Three entries for two are refused (expected to fail). + {"tool": "set_settings", "args": {"scope": "process", "values": {"outer_wall_speed": 250}}, + "expect": {"/applied/outer_wall_speed": {"eq": "250,350"}}}, + {"tool": "set_settings", "args": {"scope": "process", "values": {"outer_wall_speed": [1, 2, 3]}}, "optional": true}, + {"tool": "get_settings", "args": {"scope": "process", "keys": ["outer_wall_speed"], "include_meta": false}, "expect": {"/items/0/value": {"eq": "250,350"}}}, + {"tool": "set_settings", "args": {"scope": "process", "values": {"outer_wall_speed": {"index": 1, "value": 300}}}, + "expect": {"/applied/outer_wall_speed": {"eq": "250,300"}, "/changed/outer_wall_speed": {"eq": "250,300"}}}, + {"tool": "set_settings", "args": {"scope": "filament", "values": {"nozzle_temperature": {"index": 0, "value": 215}}}, + "expect": {"/applied/nozzle_temperature": {"eq": "215,220"}}}, + // Filament values are compared entry by entry, as the Compare presets dialog does. + {"tool": "get_settings", "args": {"scope": "filament", "compare": ":saved", "keys": ["nozzle_temperature"]}, + "expect": {"/total": {"eq": 1}, "/items/0/index": {"eq": 0}, "/items/0/value": {"eq": "215"}, "/items/0/other": {"eq": "220"}}}, + {"tool": "set_settings", "args": {"scope": "filament", "reset_all": true}, "expect": {"/changed/nozzle_temperature": {"eq": "220,220"}}}, + + // ---- changed shows what the app adjusts in turn: spiral vase, confirmed in its dialog ---- + {"tool": "dialog_auto_answer", "args": {"rules": [{"match": "Spiral mode only works", "button": "yes"}]}}, + {"tool": "set_settings", "args": {"scope": "process", "values": {"spiral_mode": true}}, + "expect": {"/applied/spiral_mode": {"eq": "1"}, "/changed/spiral_mode": {"eq": "1"}, "/changed/wall_loops": {"eq": "1"}, + "/changed/top_shell_layers": {"eq": "0"}, "/changed/sparse_infill_density": {"eq": "0%"}}}, + {"tool": "set_settings", "args": {"scope": "process", "reset_all": true}, "expect": {"/changed/spiral_mode": {"eq": "0"}}}, + + // ---- A process kept inside the project, saved with it and back on reopening ---- + {"tool": "save_preset", "args": {"type": "process", "name": "MCP Project Process", "inside_project": true}, + "expect": {"/project": {"eq": true}, "/user": {"eq": false}, "/inherits": {"eq": "0.20mm Standard @BBL X1C"}}}, + {"tool": "list_presets", "args": {"type": "process", "query": "MCP Project Process"}, + "expect": {"/total": {"eq": 1}, "/items/0/selected": {"eq": true}, "/items/0/user": {"eq": false}, "/items/0/project": {"eq": true}}}, + // Detach is refused outside Developer mode (expected to fail), then made there. + {"tool": "save_preset", "args": {"type": "process", "name": "MCP Detached", "detach": true}, "optional": true}, + {"tool": "list_presets", "args": {"type": "process", "query": "MCP Detached"}, "expect": {"/total": {"eq": 0}}}, + {"tool": "run_action", "args": {"id": "orca_command:toggle_developer_mode:orca"}}, + {"tool": "save_preset", "args": {"type": "process", "name": "MCP Detached", "detach": true}, + "expect": {"/project": {"eq": true}, "/inherits": {"exists": false}}}, + {"tool": "run_action", "args": {"id": "orca_command:toggle_developer_mode:orca"}}, + // A project file needs an object to open. + {"tool": "run_action", "args": {"id": "orca_command:add_primitive_cube:orca"}}, + {"tool": "wait", "args": {"for": "idle"}}, + {"tool": "save_project", "args": {"path": "${out_dir}/presets.3mf", "overwrite": true}}, + {"tool": "new_project", "args": {"discard_changes": true}}, + {"tool": "list_presets", "args": {"type": "process", "query": "MCP"}, "expect": {"/total": {"eq": 0}}}, + {"tool": "open_files", "args": {"paths": ["${out_dir}/presets.3mf"], "discard_changes": true}}, + {"tool": "list_presets", "args": {"type": "process", "query": "MCP Project Process"}, "expect": {"/total": {"eq": 1}, "/items/0/user": {"eq": false}}}, + {"tool": "list_presets", "args": {"type": "filament", "query": "MCP Test PLA"}, "expect": {"/items/0/selected": {"eq": true}, "/items/0/modified": {"exists": false}}}, + + // ---- Revert one key: null takes it back to the saved value, with reset_to parent to the parent's ---- + {"tool": "select_preset", "args": {"type": "process", "name": "0.20mm Standard @BBL X1C", "changes": "discard"}, + "expect": {"/selected": {"eq": "0.20mm Standard @BBL X1C"}}}, + {"tool": "set_settings", "args": {"scope": "process", "values": {"wall_loops": 5, "sparse_infill_density": "25%"}}}, + {"tool": "set_settings", "args": {"scope": "process", "values": {"wall_loops": null}}, + "expect": {"/applied/wall_loops": {"eq": "2"}, "/changed/wall_loops": {"eq": "2"}}}, + {"tool": "get_settings", "args": {"scope": "process", "compare": ":saved"}, + "expect": {"/total": {"eq": 1}, "/items/0/key": {"eq": "sparse_infill_density"}}}, + // reset_to without a null value is refused (expected to fail). + {"tool": "set_settings", "args": {"scope": "process", "values": {"wall_loops": 3}, "reset_to": "parent"}, "optional": true}, + {"tool": "get_settings", "args": {"scope": "process", "keys": ["wall_loops"], "include_meta": false}, "expect": {"/items/0/value": {"eq": "2"}}}, + // The user filament saved above (filament cost 23) back to the system filament it inherits from. + {"tool": "set_settings", "args": {"scope": "filament", "values": {"filament_cost": null}, "reset_to": "parent"}, + "expect": {"/applied/filament_cost": {"eq": "15.99"}}}, + {"tool": "get_settings", "args": {"scope": "filament", "compare": ":parent", "keys": ["filament_cost"]}, "expect": {"/total": {"eq": 0}}}, + {"tool": "set_settings", "args": {"scope": "filament", "values": {"filament_cost": null}}, "expect": {"/applied/filament_cost": {"eq": "23"}}}, + + // ---- select_preset: without changes the Transfer-or-discard prompt opens, as before ---- + {"tool": "select_preset", "args": {"type": "process", "name": "0.16mm Optimal @BBL X1C"}, "await": false, "save_as": "switch"}, + {"tool": "wait", "args": {"for": "dialog"}}, + {"tool": "get_state", "expect": {"/dialogs/0/title": {"eq": "Transfer or discard changes"}}}, + {"tool": "dialog_respond", "args": {"button": "Transfer"}}, + {"tool": "wait", "args": {"for": "job", "job": "${jobs.switch}"}, + "expect": {"/selected": {"eq": "0.16mm Optimal @BBL X1C"}, "/modified/process/keys": {"eq": ["sparse_infill_density"]}}}, + {"tool": "get_settings", "args": {"scope": "process", "keys": ["sparse_infill_density"], "include_meta": false}, "expect": {"/items/0/value": {"eq": "25%"}}}, + // ---- changes answers it without the prompt: transfer, then discard ---- + {"tool": "set_settings", "args": {"scope": "process", "values": {"wall_loops": 4}}}, + {"tool": "select_preset", "args": {"type": "process", "name": "0.20mm Standard @BBL X1C", "changes": "transfer"}, + "expect": {"/selected": {"eq": "0.20mm Standard @BBL X1C"}, "/discarded": {"exists": false}, + "/modified/process/keys": {"eq": ["sparse_infill_density", "wall_loops"]}}}, + {"tool": "get_settings", "args": {"scope": "process", "keys": ["sparse_infill_density", "wall_loops"], "include_meta": false}, + "expect": {"/items/0/value": {"eq": "25%"}, "/items/1/value": {"eq": "4"}}}, + // A setting Simple mode hides is not in the prompt's list, so Transfer drops it, as in the GUI. + {"tool": "set_settings", "args": {"scope": "process", "values": {"seam_slope_type": "all"}}}, + {"tool": "select_preset", "args": {"type": "process", "name": "0.16mm Optimal @BBL X1C", "changes": "transfer"}, + "expect": {"/discarded/process/name": {"eq": "0.20mm Standard @BBL X1C"}, "/discarded/process/keys": {"eq": ["seam_slope_type"]}}}, + // A modified filament that suits the new process keeps its changes whatever the answer, as in the GUI. + {"tool": "set_settings", "args": {"scope": "filament", "values": {"slow_down_layer_time": 7}}}, + {"tool": "select_preset", "args": {"type": "process", "name": "0.20mm Standard @BBL X1C", "changes": "discard"}, + "expect": {"/discarded/process/keys": {"eq": ["sparse_infill_density", "wall_loops"]}, "/modified/process": {"exists": false}, + "/modified/filament/keys": {"eq": ["slow_down_layer_time"]}}}, + {"tool": "get_settings", "args": {"scope": "process", "compare": ":saved"}, "expect": {"/total": {"eq": 0}}}, + // Transfer is refused where the prompt offers none (expected to fail): a printer's own changes, and a + // filament of another type. The steps after each check that nothing changed. + {"tool": "set_settings", "args": {"scope": "printer", "values": {"printer_notes": "MCP revert test"}}}, + {"tool": "select_preset", "args": {"type": "printer", "name": "Bambu Lab X1 Carbon 0.4 nozzle", "changes": "transfer"}, "optional": true}, + {"tool": "get_settings", "args": {"scope": "printer", "compare": ":saved"}, "expect": {"/total": {"eq": 1}, "/items/0/key": {"eq": "printer_notes"}}}, + {"tool": "select_preset", "args": {"type": "printer", "name": "Bambu Lab X1 Carbon 0.4 nozzle", "changes": "discard"}, + "expect": {"/discarded/printer/keys": {"eq": ["printer_notes"]}, "/modified/printer": {"exists": false}}}, + {"tool": "set_settings", "args": {"scope": "filament", "reset_all": true, "values": {"filament_type": "PETG"}}}, + {"tool": "save_preset", "args": {"type": "filament", "name": "MCP Test PETG", "overwrite": true}}, + {"tool": "select_preset", "args": {"type": "filament", "name": "MCP Test PLA", "filament_slot": 1}}, + {"tool": "set_settings", "args": {"scope": "filament", "values": {"slow_down_layer_time": 8}}}, + {"tool": "select_preset", "args": {"type": "filament", "name": "MCP Test PETG", "filament_slot": 1, "changes": "transfer"}, "optional": true}, + {"tool": "get_state", "expect": {"/presets/filaments/0": {"eq": "MCP Test PLA"}}}, + {"tool": "select_preset", "args": {"type": "filament", "name": "MCP Test PETG", "filament_slot": 1, "changes": "discard"}, + "expect": {"/selected": {"eq": "MCP Test PETG"}, "/discarded/filament/name": {"eq": "MCP Test PLA"}, + "/discarded/filament/keys": {"eq": ["slow_down_layer_time"]}}}, + {"tool": "select_preset", "args": {"type": "filament", "name": "MCP Test PLA", "filament_slot": 1}}, + + // ---- new_project: modified presets are kept unless changes is "discard" ---- + {"tool": "set_settings", "args": {"scope": "process", "values": {"wall_loops": 6}}}, + {"tool": "new_project", "args": {"discard_changes": true}, + "expect": {"/modified/process/keys": {"eq": ["wall_loops"]}, "/discarded": {"exists": false}}}, + {"tool": "list_presets", "args": {"type": "process", "query": "0.20mm Standard"}, "expect": {"/items/0/modified": {"eq": true}}}, + {"tool": "new_project", "args": {"discard_changes": true, "changes": "keep"}, "expect": {"/modified/process/keys": {"eq": ["wall_loops"]}}}, + {"tool": "new_project", "args": {"discard_changes": true, "changes": "discard"}, + "expect": {"/discarded/process/keys": {"eq": ["wall_loops"]}, "/modified": {"exists": false}}}, + {"tool": "list_presets", "args": {"type": "process", "query": "0.20mm Standard"}, "expect": {"/items/0/modified": {"exists": false}}}, + + // ---- delete_preset: a filament the tab does not edit, then the one it edits ---- + // A system preset is refused (expected to fail); the step after checks it is still there. + {"tool": "delete_preset", "args": {"type": "filament", "name": "Bambu PLA Basic @BBL X1C"}, "optional": true}, + {"tool": "get_settings", "args": {"scope": "filament", "preset": "Bambu PLA Basic @BBL X1C", "keys": ["filament_type"], "include_meta": false}, + "expect": {"/items/0/value": {"eq": "PLA"}}}, + {"tool": "delete_preset", "args": {"type": "filament", "name": "MCP Test PLA 2"}, + "expect": {"/deleted": {"eq": "MCP Test PLA 2"}, "/selected": {"eq": "MCP Test PLA"}, "/filaments/0": {"eq": "MCP Test PLA"}}}, + {"tool": "list_presets", "args": {"type": "filament", "query": "MCP Test PLA 2"}, "expect": {"/total": {"eq": 0}}}, + // Another filament is refused while the edited one has unsaved changes (expected to fail), which deleting would drop. + {"tool": "set_settings", "args": {"scope": "filament", "values": {"slow_down_layer_time": 11}}}, + {"tool": "delete_preset", "args": {"type": "filament", "name": "MCP Test PETG"}, "optional": true}, + {"tool": "list_presets", "args": {"type": "filament", "query": "MCP Test PETG"}, "expect": {"/total": {"eq": 1}}}, + {"tool": "get_settings", "args": {"scope": "filament", "compare": ":saved"}, "expect": {"/total": {"eq": 1}}}, + {"tool": "set_settings", "args": {"scope": "filament", "reset_all": true}}, + // The edited filament: the tab selects the preset it inherits from, and its unsaved changes go with it. + {"tool": "select_preset", "args": {"type": "filament", "name": "MCP Test PETG", "filament_slot": 1}}, + {"tool": "set_settings", "args": {"scope": "filament", "values": {"slow_down_layer_time": 11}}}, + {"tool": "delete_preset", "args": {"type": "filament", "name": "MCP Test PETG"}, + "expect": {"/deleted": {"eq": "MCP Test PETG"}, "/selected": {"eq": "Bambu PLA Basic @BBL X1C"}, "/filaments/0": {"ne": "MCP Test PETG"}, + "/discarded/filament/name": {"eq": "MCP Test PETG"}, "/discarded/filament/keys": {"eq": ["slow_down_layer_time"]}}}, + {"tool": "list_presets", "args": {"type": "filament", "query": "MCP Test PETG"}, "expect": {"/total": {"eq": 0}}}, + {"tool": "delete_preset", "args": {"type": "filament", "name": "MCP Test PLA"}, "expect": {"/selected": {"eq": "Bambu PLA Basic @BBL X1C"}}}, + {"tool": "list_presets", "args": {"type": "filament", "query": "MCP Test"}, "expect": {"/total": {"eq": 0}}}, + + // ---- delete_preset: a base process and the process inheriting from it ---- + {"tool": "run_action", "args": {"id": "orca_command:toggle_developer_mode:orca"}}, + {"tool": "save_preset", "args": {"type": "process", "name": "MCP Delete Base", "detach": true, "overwrite": true}, + "expect": {"/user": {"eq": true}, "/inherits": {"exists": false}}}, + {"tool": "run_action", "args": {"id": "orca_command:toggle_developer_mode:orca"}}, + {"tool": "set_settings", "args": {"scope": "process", "values": {"wall_loops": 3}}}, + {"tool": "save_preset", "args": {"type": "process", "name": "MCP Delete Child", "overwrite": true}, + "expect": {"/inherits": {"eq": "MCP Delete Base"}, "/selected": {"eq": true}}}, + // A preset another inherits from is refused (expected to fail), as the tab refuses it. + {"tool": "delete_preset", "args": {"type": "process", "name": "MCP Delete Base"}, "optional": true}, + {"tool": "list_presets", "args": {"type": "process", "query": "MCP Delete"}, "expect": {"/total": {"eq": 2}}}, + // Another process is refused while the edited one has unsaved changes (expected to fail). + {"tool": "select_preset", "args": {"type": "process", "name": "0.20mm Standard @BBL X1C"}}, + {"tool": "set_settings", "args": {"scope": "process", "values": {"wall_loops": 4}}}, + {"tool": "delete_preset", "args": {"type": "process", "name": "MCP Delete Child"}, "optional": true}, + {"tool": "list_presets", "args": {"type": "process", "query": "MCP Delete"}, "expect": {"/total": {"eq": 2}}}, + {"tool": "set_settings", "args": {"scope": "process", "reset_all": true}}, + // Not selected: selected, deleted, and the selection restored. + {"tool": "delete_preset", "args": {"type": "process", "name": "MCP Delete Child"}, + "expect": {"/deleted": {"eq": "MCP Delete Child"}, "/selected": {"eq": "0.20mm Standard @BBL X1C"}, "/discarded": {"exists": false}}}, + {"tool": "list_presets", "args": {"type": "process", "query": "MCP Delete"}, "expect": {"/total": {"eq": 1}}}, + // Selected, with nothing inheriting from it now: the tab moves to the next preset. + {"tool": "select_preset", "args": {"type": "process", "name": "MCP Delete Base"}}, + {"tool": "set_settings", "args": {"scope": "process", "values": {"wall_loops": 5}}}, + {"tool": "delete_preset", "args": {"type": "process", "name": "MCP Delete Base"}, + "expect": {"/selected": {"ne": "MCP Delete Base"}, "/discarded/process/name": {"eq": "MCP Delete Base"}}}, + {"tool": "list_presets", "args": {"type": "process", "query": "MCP Delete"}, "expect": {"/total": {"eq": 0}}}, + {"tool": "select_preset", "args": {"type": "process", "name": "0.20mm Standard @BBL X1C"}}, + + // ---- Presets exported with the Export Preset Bundle dialog to a directory, then imported with a path ---- + // A detached filament is listed in the dialog under its own name. A rerun finds the last run's archive, + // which the dialog asks before replacing. + {"tool": "dialog_auto_answer", "args": {"rules": [{"match": "already exists", "button": "yes"}]}}, + {"tool": "run_action", "args": {"id": "orca_command:toggle_developer_mode:orca"}}, + {"tool": "save_preset", "args": {"type": "filament", "name": "MCP Export PLA", "detach": true, "overwrite": true}, + "expect": {"/inherits": {"exists": false}}}, + {"tool": "run_action", "args": {"id": "orca_command:toggle_developer_mode:orca"}}, + {"tool": "run_action", "args": {"id": "orca_command:export_config:orca", "param": "${out_dir}"}, "await": false, "save_as": "export"}, + {"tool": "ui_click", "args": {"target": {"label": "Filament presets(.zip)", "within": "Export Preset Bundle"}}}, + {"tool": "ui_input", "args": {"target": {"name": "MCP Export PLA", "within": "Export Preset Bundle"}, "value": true}}, + {"tool": "dialog_respond", "args": {"dialog": {"title": "Export Preset Bundle"}, "button": "ok"}, "await": false, "save_as": "export_ok"}, + {"tool": "get_state", "expect": {"/dialogs/1/message": {"eq": "Export successful"}}}, + {"tool": "dialog_respond", "args": {"dialog": {"title": "Info"}, "button": "ok"}}, + {"tool": "wait", "args": {"for": "job", "job": "${jobs.export_ok}"}}, + {"tool": "wait", "args": {"for": "job", "job": "${jobs.export}"}, "expect": {"/level": {"eq": "success"}}}, + // The preset exists: the import keeps it by default, and the message names it. + {"tool": "run_action", "args": {"id": "orca_command:import_configs:orca", "param": "${out_dir}/Filament presets.zip"}, + "expect": {"/message": {"eq": "Kept the existing presets: MCP Export PLA."}}}, + {"tool": "select_preset", "args": {"type": "filament", "name": "Bambu PLA Basic", "filament_slot": 1}}, + {"tool": "delete_preset", "args": {"type": "filament", "name": "MCP Export PLA"}}, + {"tool": "run_action", "args": {"id": "orca_command:import_configs:orca", "param": "${out_dir}/Filament presets.zip"}, + "expect": {"/message": {"eq": "Imported presets: MCP Export PLA."}}}, + {"tool": "list_presets", "args": {"type": "filament", "query": "MCP Export PLA"}, "expect": {"/total": {"eq": 1}, "/items/0/user": {"eq": true}}}, + {"tool": "delete_preset", "args": {"type": "filament", "name": "MCP Export PLA"}}, + // One preset file, inheriting a system filament. + {"tool": "run_action", "args": {"id": "orca_command:import_configs:orca", "param": "${script_dir}/fixtures/mcp_import_pla.json"}, + "expect": {"/message": {"eq": "Imported presets: MCP Import PLA."}}}, + {"tool": "list_presets", "args": {"type": "filament", "query": "MCP Import PLA"}, "expect": {"/items/0/inherits": {"eq": "Bambu PLA Basic @BBL X1C"}}}, + {"tool": "get_settings", "args": {"scope": "filament", "preset": "MCP Import PLA", "keys": ["filament_cost"], "include_meta": false}, + "expect": {"/items/0/value": {"eq": "24"}}}, + {"tool": "delete_preset", "args": {"type": "filament", "name": "MCP Import PLA"}}, + {"tool": "list_presets", "args": {"type": "filament", "query": "MCP "}, "expect": {"/total": {"eq": 0}}}, + + // ---- Preferences: read by key, changed in the Preferences dialog through the control named after it ---- + {"tool": "get_settings", "args": {"scope": "preferences", "keys": ["auto_arrange", "no_such_preference"]}, + "expect": {"/items/0/key": {"eq": "auto_arrange"}, "/unknown_keys/0": {"eq": "no_such_preference"}}}, + // set_settings refuses the scope (expected to fail), and so does open_preferences an unknown tab; no dialog opens. + {"tool": "set_settings", "args": {"scope": "preferences", "values": {"auto_arrange": false}}, "optional": true}, + {"tool": "run_action", "args": {"id": "orca_command:open_preferences:orca", "param": "advanced"}, "optional": true}, + {"tool": "get_state", "expect": {"/dialogs": {"empty": true}}}, + {"tool": "run_action", "args": {"id": "orca_command:open_preferences:orca", "param": "control:auto_arrange"}, "await": false, "save_as": "prefs"}, + {"tool": "ui_input", "args": {"target": {"name": "auto_arrange", "within": "Preferences"}, "value": false}, "expect": {"/checked": {"eq": false}}}, + {"tool": "dialog_respond", "args": {"dialog": {"title": "Preferences"}, "button": "close"}}, + {"tool": "wait", "args": {"for": "job", "job": "${jobs.prefs}"}}, + {"tool": "get_settings", "args": {"scope": "preferences", "keys": ["auto_arrange"]}, "expect": {"/items/0/value": {"eq": "false"}}}, + // A key on another tab than the one named is shown on its own tab, where it can be changed. + {"tool": "run_action", "args": {"id": "orca_command:open_preferences:orca", "param": "general:auto_arrange"}, "await": false, "save_as": "prefs2"}, + {"tool": "ui_input", "args": {"target": {"name": "auto_arrange", "within": "Preferences"}, "value": true}, "expect": {"/checked": {"eq": true}}}, + {"tool": "dialog_respond", "args": {"dialog": {"title": "Preferences"}, "button": "close"}}, + {"tool": "wait", "args": {"for": "job", "job": "${jobs.prefs2}"}}, + {"tool": "get_settings", "args": {"scope": "preferences", "keys": ["auto_arrange"]}, "expect": {"/items/0/value": {"eq": "true"}}}, + + // ---- A printer preset, deleted once selected, then back to the system printer ---- + {"tool": "save_preset", "args": {"type": "printer", "name": "MCP Test Printer", "overwrite": true}, + "expect": {"/user": {"eq": true}, "/inherits": {"eq": "Bambu Lab X1 Carbon 0.4 nozzle"}, "/selected": {"eq": true}}}, + {"tool": "get_state", "expect": {"/presets/printer": {"eq": "MCP Test Printer"}}}, + {"tool": "new_project", "args": {"discard_changes": true}}, + {"tool": "select_preset", "args": {"type": "printer", "name": "Bambu Lab X1 Carbon 0.4 nozzle"}}, + // A printer that is not selected is refused (expected to fail): switching printers is no round trip. + {"tool": "delete_preset", "args": {"type": "printer", "name": "MCP Test Printer"}, "optional": true}, + {"tool": "list_presets", "args": {"type": "printer", "query": "MCP Test Printer"}, "expect": {"/total": {"eq": 1}}}, + {"tool": "select_preset", "args": {"type": "printer", "name": "MCP Test Printer"}}, + {"tool": "delete_preset", "args": {"type": "printer", "name": "MCP Test Printer"}, + "expect": {"/selected": {"eq": "Bambu Lab X1 Carbon 0.4 nozzle"}, "/attached": {"exists": false}}}, + {"tool": "list_presets", "args": {"type": "printer", "query": "MCP Test Printer"}, "expect": {"/total": {"eq": 0}}}, + {"tool": "select_preset", "args": {"type": "filament", "name": "Bambu PLA Basic", "filament_slot": 1}} + ] +} diff --git a/tools/mcp/tests/preview.json b/tools/mcp/tests/preview.json new file mode 100644 index 0000000000..23af1576d4 --- /dev/null +++ b/tools/mcp/tests/preview.json @@ -0,0 +1,143 @@ +// get_preview and get_state.preview on a sliced 25.6 mm cube: the summary, the feature and layer +// tables, the object with its list_objects index, the legend's state as set_view changes it (rows, +// time estimate, layers by height, a view type picked as the legend's combo does), and the same reads +// on the cube's G-code opened for viewing. Run it on a fresh datadir set up with the +// default printer (Bambu Lab X1 Carbon 0.4, 0.2 mm layers): +// tools/mcp/orca_mcp.py run-script tools/mcp/tests/preview.json --out /tmp/preview +// The tables' arithmetic (shares of the print time, heights, paging, the unique-name rule) is unit +// tested in tests/slic3rutils/test_mcp_results.cpp, since a script step cannot add values up, and a +// refusal cannot be expected in a script; tools/mcp/test_set_view_preview.py checks set_view's. +{ + "orca_script": 1, + "name": "preview data", + "steps": [ + {"tool": "wait", "args": {"for": "ready"}}, + // Opening a G-code file asks to save the project it replaces, discard_changes or not. + {"tool": "dialog_auto_answer", "args": {"rules": [{"match": "Uniform scale", "button": "ok"}, + {"match": "unsaved changes. Would you like to save", "button": "No"}]}}, + {"tool": "new_project", "args": {"discard_changes": true}}, + {"tool": "set_view", "args": {"tab": "prepare"}}, + {"tool": "run_action", "args": {"id": "orca_command:add_primitive_cube:orca"}}, + {"tool": "wait", "args": {"for": "idle"}}, + {"tool": "slice", "expect": {"/plates/0/outcome": {"eq": "ok"}, "/plates/0/layers": {"eq": 128}}}, + // A new result with as many layers keeps the slider and the view type, so a rerun sets both. + {"tool": "set_view", "args": {"view_type": "feature_type", "layer_range": [1, 128]}}, + + // ---- The tables, and the legend of the plate the Preview shows ---- + {"tool": "get_preview", "args": {"include": ["features", "layers", "objects", "view"], "limit": 5}, "expect": { + "/plate": {"eq": 0}, + "/summary/layers": {"eq": 128}, + "/summary/filament_g": {"gt": 0}, + "/summary/travel_mm": {"gt": 0}, + "/features/Outer wall/time_s": {"gt": 0}, + "/features/Outer wall/percent": {"gt": 0, "lt": 100}, + "/features/Outer wall/g": {"gt": 0}, + "/features/Travel/mm": {"gt": 0}, + "/layers/total": {"eq": 128}, + "/layers/next_offset": {"eq": 5}, + "/layers/items/0/layer": {"eq": 1}, + "/layers/items/0/z": {"eq": 0.2}, + "/layers/items/4/z": {"eq": 1.0}, + "/layers/items/4/height": {"eq": 0.2}, + "/layers/items/4/time_s": {"gt": 0}, + "/objects/0/object": {"eq": 0}, + "/objects/0/instance": {"eq": 0}, + "/objects/0/g": {"gt": 0}, + "/view/view_type": {"eq": "feature_type"}, + "/view/layers/0": {"eq": 1}, + "/view/layers/1": {"eq": 128}, + "/view/layer_count": {"eq": 128}, + "/view/time_mode": {"eq": "normal"}, + "/view/legend/features/Outer wall": {"eq": true}, + "/view/legend/options/travel": {"exists": true}, + "/view/ranges/height/1": {"ge": 0.2}, + "/view/ranges/volumetric_flow_rate/1": {"gt": 0}, + "/view/ranges/layer_time_linear/1": {"gt": 0}}}, + // The last page, with each layer's seconds per feature type, and no other part. + {"tool": "get_preview", "args": {"include": ["layer_features"], "offset": 127}, "expect": { + "/layers/items/0/layer": {"eq": 128}, + "/layers/items/0/z": {"eq": 25.6}, + "/layers/items/0/features/Top surface": {"gt": 0}, + "/layers/next_offset": {"exists": false}, + "/features": {"exists": false}, + "/view": {"exists": false}}}, + + // ---- set_view's legend rows, time estimate and layers by height ---- + {"tool": "set_view", "args": {"view_type": "feature_type", "legend": {"Sparse infill": false, "travel": true}, "layer_z": 1.0}, "expect": { + "/legend/Sparse infill": {"eq": false}, + "/legend/travel": {"eq": true}, + "/layers/1": {"eq": 5}, + "/z/1": {"eq": 1.0}}}, + {"tool": "get_preview", "args": {"include": ["view"]}, "expect": { + "/view/legend/features/Sparse infill": {"eq": false}, + "/view/legend/features/Outer wall": {"eq": true}, + "/view/legend/options/travel": {"eq": true}, + "/view/layers/1": {"eq": 5}}}, + // Between two layer tops a height takes the layer that covers it, as the slider places a custom G-code. + {"tool": "set_view", "args": {"layer_z": 1.05}, "expect": {"/layers/1": {"eq": 6}, "/z/1": {"eq": 1.2}}}, + {"tool": "set_view", "args": {"time_mode": "normal"}, "expect": {"/time_mode": {"eq": "normal"}}}, + // A view type is picked as in the legend's combo: Line Type shows every feature type again. + {"tool": "set_view", "args": {"view_type": "speed"}}, + {"tool": "get_preview", "args": {"include": ["view"]}, "expect": {"/view/legend/features/Sparse infill": {"eq": false}}}, + {"tool": "set_view", "args": {"view_type": "feature_type", "legend": {"travel": false}}}, + {"tool": "get_preview", "args": {"include": ["view"]}, "expect": { + "/view/legend/features/Sparse infill": {"eq": true}, + "/view/legend/options/travel": {"eq": false}}}, + {"tool": "screenshot", "args": {"target": "canvas", "save_path": "${out_dir}/legend.png", "overwrite": true, "include_image": false}}, + + // ---- get_state.preview follows set_view ---- + {"tool": "set_view", "args": {"layer": 5}}, + {"tool": "get_state", "expect": { + "/preview/plate": {"eq": 0}, + "/preview/layers/0": {"eq": 1}, + "/preview/layers/1": {"eq": 5}, + "/preview/z/1": {"eq": 1.0}, + "/preview/layer_count": {"eq": 128}}}, + {"tool": "set_view", "args": {"view_type": "fan_speed"}}, + {"tool": "get_state", "expect": {"/preview/view_type": {"eq": "fan_speed"}}}, + {"tool": "get_preview", "args": {"include": ["view"]}, "expect": { + "/view/view_type": {"eq": "fan_speed"}, + "/view/layers/1": {"eq": 5}, + "/features": {"exists": false}}}, + + // ---- A plate the Preview has not shown: the Preview loads a plate's toolpaths only while shown, + // so after another plate is selected it still holds the last one's, which no read reports as + // the selected plate's ---- + {"tool": "set_view", "args": {"tab": "prepare"}}, + {"tool": "run_action", "args": {"id": "orca_command:plate_add:orca"}}, + {"tool": "run_action", "args": {"id": "orca_command:plate_goto:orca", "param": "1"}}, + {"tool": "select", "args": {"none": true}}, + {"tool": "run_action", "args": {"id": "orca_command:add_primitive_cube:orca"}}, + {"tool": "wait", "args": {"for": "idle"}}, + {"tool": "list_plates", "expect": {"/items/1/objects/0": {"exists": true}}}, + {"tool": "slice", "args": {"plates": "all"}, "expect": {"/plates/0/outcome": {"eq": "ok"}, "/plates/1/outcome": {"eq": "ok"}}}, + // Slicing every plate leaves the Preview on its all-plates statistics; plate 0 is shown from Prepare. + {"tool": "set_view", "args": {"tab": "prepare"}}, + {"tool": "run_action", "args": {"id": "orca_command:plate_goto:orca", "param": "0"}}, + {"tool": "set_view", "args": {"tab": "preview"}}, + {"tool": "wait", "args": {"for": "idle"}}, + {"tool": "get_state", "expect": {"/plates/current": {"eq": 0}, "/preview/plate": {"eq": 0}}}, + {"tool": "set_view", "args": {"tab": "prepare"}}, + {"tool": "run_action", "args": {"id": "orca_command:plate_goto:orca", "param": "1"}}, + {"tool": "get_state", "expect": {"/plates/current": {"eq": 1}, "/preview": {"eq": null}}}, + {"tool": "get_preview", "expect": {"/plate": {"eq": 1}, "/summary/layers": {"eq": 128}, "/view": {"eq": null}, + "/note": {"contains": "has not loaded this plate's toolpaths"}}}, + {"tool": "set_view", "args": {"tab": "preview"}}, + {"tool": "wait", "args": {"for": "idle"}}, + {"tool": "get_state", "expect": {"/preview/plate": {"eq": 1}}}, + {"tool": "get_preview", "args": {"include": ["view"]}, "expect": {"/view/layer_count": {"eq": 128}, "/note": {"exists": false}}}, + + // ---- The same cube's G-code opened for viewing: its plate is never marked sliced ---- + {"tool": "export", "args": {"format": "gcode", "path": "${out_dir}/cube.gcode", "overwrite": true}}, + {"tool": "open_files", "args": {"paths": ["${out_dir}/cube.gcode"], "discard_changes": true}}, + {"tool": "wait", "args": {"for": "idle"}}, + {"tool": "get_state", "expect": {"/preview/layer_count": {"eq": 128}}}, + {"tool": "get_preview", "args": {"include": ["features", "layers", "objects", "view"]}, "expect": { + "/summary/layers": {"eq": 128}, + "/summary/filament_g": {"gt": 0}, + "/features/Outer wall/time_s": {"gt": 0}, + "/layers/total": {"eq": 128}, + "/view/layer_count": {"eq": 128}}}, + {"tool": "new_project", "args": {"discard_changes": true}} + ] +} diff --git a/tools/mcp/tests/rows.json b/tools/mcp/tests/rows.json new file mode 100644 index 0000000000..c7425797d3 --- /dev/null +++ b/tools/mcp/tests/rows.json @@ -0,0 +1,95 @@ +// Rows of lists, trees and tables as targets, and popups as snapshot roots: object list rows (plates, +// an object, its parts and the Printable column), the object's and a part's menus run from their rows, +// Compare presets' rows, the object settings table, the print button's popup and a drop-down list. Run +// it on a fresh datadir set up with the default printer (Bambu Lab X1 Carbon 0.4): +// tools/mcp/orca_mcp.py run-script tools/mcp/tests/rows.json --out /tmp/rows +// Refusals (a bad column, a row without a checkbox, two rows a locator names) and checklist rows (the +// Add Settings checklist is on no FFF menu) are unit tests in tests/slic3rutils/test_mcp_results.cpp. +{ + "orca_script": 1, + "name": "rows and popups", + "steps": [ + {"tool": "wait", "args": {"for": "ready"}}, + {"tool": "dialog_auto_answer", "args": {"rules": [ + {"match": "Uniform scale", "button": "ok"}, + {"match": "per-object setting mode", "button": "ok"}]}}, + {"tool": "new_project", "args": {"discard_changes": true}}, + {"tool": "set_view", "args": {"tab": "prepare", "window_size": [1440, 960]}}, + {"tool": "run_action", "args": {"id": "orca_command:add_primitive_cube:orca"}}, + {"tool": "wait", "args": {"for": "idle"}}, + + // ---- The object list shows while the sidebar's switch is on Objects ---- + {"tool": "ui_input", "args": {"target": {"class": "SwitchButton", "label": "Process"}, "value": true}}, + {"tool": "ui_snapshot", "args": {"root": "main", "query": "row"}, "expect": {"/nodes": {"ge": 2}}}, + + // ---- Plate rows pick the plate ---- + {"tool": "ui_click", "args": {"target": {"gltoolbar": "addplate"}}}, + {"tool": "wait", "args": {"for": "idle"}}, + {"tool": "ui_click", "args": {"target": {"row": "Plate 2"}}, "expect": {"/selected": {"eq": ["Plate 2"]}}}, + {"tool": "get_state", "expect": {"/plates/current": {"eq": 1}}}, + {"tool": "ui_click", "args": {"target": {"row": "Plate 1"}}}, + {"tool": "get_state", "expect": {"/plates/current": {"eq": 0}}}, + + // ---- An object row: selected as a click selects it, its menu listed and run ---- + {"tool": "select", "args": {"none": true}}, + {"tool": "ui_click", "args": {"target": {"row": "Cube"}}, "expect": {"/selected": {"eq": ["Plate 1>Cube"]}}}, + {"tool": "ui_click", "args": {"target": {"row": "Cube"}, "button": "right"}, + "expect": {"/popup_menu/items": {"contains": "Add Modifier>Cylinder"}}}, + {"tool": "ui_click", "args": {"target": {"row": "Cube"}, "button": "right", "popup_item": "Add Modifier>Cylinder"}, + "expect": {"/ran": {"eq": "Add Modifier>Cylinder"}}}, + {"tool": "wait", "args": {"for": "idle"}}, + {"tool": "list_objects", "expect": {"/items/0/volumes/1/type": {"eq": "modifier"}}}, + + // ---- Part rows: a click, Ctrl adds another; a right click keeps a selection it is in, so the part + // is clicked alone before its menu changes its type ---- + {"tool": "ui_click", "args": {"target": {"row": "Cube>Generic-Cylinder"}}, "expect": {"/selected": {"eq": ["Plate 1>Cube>Generic-Cylinder"]}}}, + {"tool": "ui_click", "args": {"target": {"row": "Cube>Cube"}, "modifiers": ["ctrl"]}, + "expect": {"/selected": {"eq": ["Plate 1>Cube>Cube", "Plate 1>Cube>Generic-Cylinder"]}}}, + {"tool": "ui_click", "args": {"target": {"row": "Cube>Generic-Cylinder"}}}, + {"tool": "ui_click", "args": {"target": {"row": "Cube>Generic-Cylinder"}, "button": "right", "popup_item": "Change Type>Negative Part"}, + "expect": {"/ran": {"eq": "Change Type>Negative Part"}}}, + {"tool": "list_objects", "expect": {"/items/0/volumes/1/type": {"eq": "negative"}}}, + + // ---- The Printable column acts as a click on its icon; a double click frames the object ---- + {"tool": "ui_click", "args": {"target": {"row": "Plate 1>Cube", "column": "Printable"}}}, + {"tool": "list_objects", "expect": {"/items/0/instances/0/printable": {"eq": false}}}, + {"tool": "ui_click", "args": {"target": {"row": "Plate 1>Cube", "column": "Printable"}}}, + {"tool": "list_objects", "expect": {"/items/0/instances/0/printable": {"eq": true}}}, + {"tool": "ui_click", "args": {"target": {"row": "Plate 1>Cube"}, "double": true}, "expect": {"/selected": {"eq": ["Plate 1>Cube"]}}}, + {"tool": "list_objects", "expect": {"/total": {"eq": 1}, "/items/0/instances/0/printable": {"eq": true}}}, + + // ---- Compare presets: a data view's rows, with both presets' values ---- + {"tool": "ui_click", "args": {"target": {"label": "Compare presets"}}}, + {"tool": "ui_input", "args": {"target": {"class": "PresetComboBox", "within": "Compare presets", "index": 5}, "value": "0.12mm Fine @BBL X1C"}}, + {"tool": "ui_click", "args": {"target": {"row": "Quality>Layer height>Layer height", "within": "Compare presets"}}, + "expect": {"/clicked": {"contains": "Quality>Layer height>Layer height"}}}, + {"tool": "ui_key", "args": {"target": {"class": "DiffPresetDialog"}, "keys": "Escape"}}, + + // ---- The object settings table: rows named by their Name cell, read-only ---- + {"tool": "ui_click", "args": {"target": {"row": "Plate 1>Cube"}, "button": "right", "popup_item": "Edit in Parameter Table"}, + "await": false, "save_as": "table"}, + {"tool": "wait", "args": {"for": "dialog", "timeout_s": 10}, "expect": {"/satisfied": {"eq": true}}}, + {"tool": "ui_snapshot", "args": {"root": "dialog", "query": "Generic-Cylinder"}, "expect": {"/nodes": {"eq": 1}}}, + {"tool": "ui_click", "args": {"target": {"row": "Generic-Cylinder", "within": "Object/Part Settings", "column": "Wall loops"}}, + "expect": {"/column": {"eq": "Wall loops"}}}, + {"tool": "dialog_respond", "args": {"dialog": {"title": "Object/Part Settings"}, "button": "close"}}, + {"tool": "wait", "args": {"for": "job", "job": "${jobs.table}"}}, + + // ---- The print button's popup: listed as a root, one of its buttons picked ---- + {"tool": "ui_click", "args": {"target": {"class": "SideButton", "index": 3}}}, + {"tool": "ui_snapshot", "args": {"root": "popup", "query": "Export plate sliced file"}, "expect": {"/nodes": {"eq": 1}}}, + {"tool": "ui_click", "args": {"target": {"class": "SideButton", "label": "Export plate sliced file"}}}, + {"tool": "ui_snapshot", "args": {"root": "popup"}, "expect": {"/nodes": {"eq": 0}}}, + {"tool": "ui_snapshot", "args": {"root": "main", "query": "Export plate sliced file", "include_menus": false}, "expect": {"/nodes": {"eq": 1}}}, + + // ---- A drop-down list's rows: the plate type, picked, then put back through the combo itself (a + // press within 20 ms of its list closing, which a script can make, does not reopen it) ---- + {"tool": "ui_click", "args": {"target": {"class": "ComboBox", "label": "Smooth Cool Plate"}}}, + {"tool": "ui_snapshot", "args": {"root": "popup", "query": "row"}, "expect": {"/nodes": {"ge": 2}}}, + {"tool": "ui_click", "args": {"target": {"row": "Textured PEI Plate"}}, "expect": {"/clicked": {"eq": "Textured PEI Plate"}}}, + {"tool": "ui_snapshot", "args": {"root": "main", "query": "Textured PEI Plate"}, "expect": {"/nodes": {"eq": 1}}}, + {"tool": "ui_input", "args": {"target": {"class": "ComboBox", "label": "Textured PEI Plate"}, "value": "Smooth Cool Plate"}}, + {"tool": "ui_snapshot", "args": {"root": "main", "query": "Smooth Cool Plate"}, "expect": {"/nodes": {"eq": 1}}}, + {"tool": "get_state", "expect": {"/dialogs": {"empty": true}, "/closed_menus": {"empty": true}}} + ] +} diff --git a/tools/mcp/tests/scene.json b/tools/mcp/tests/scene.json new file mode 100644 index 0000000000..9fcc6655af --- /dev/null +++ b/tools/mcp/tests/scene.json @@ -0,0 +1,329 @@ +// Object structure and scene: transform on instances, plates and parts, shapes added at a size +// without the Primitive size dialog, arrange, parts added to an object with add_part, and the object +// list's context-menu commands (Change Type, Rename, instances, Assemble, Order By), then all of them +// on one scene from start to slice. Run on a live app: +// python3 tools/mcp/orca_mcp.py run-script tools/mcp/tests/scene.json --out <dir> +// A refusal can't be asserted directly (a failed step stops the run), so each one is an optional +// step followed by a check that nothing changed. +{ + "orca_script": 1, + "name": "object structure and scene", + "vars": {"cube": "${script_dir}/../../../resources/handy_models/OrcaCube_v2.drc", + "svg": "${script_dir}/fixtures/star.svg"}, + "steps": [ + {"tool": "wait", "args": {"for": "ready"}}, + {"tool": "new_project", "args": {"discard_changes": true}}, + {"tool": "set_view", "args": {"tab": "prepare"}}, + + // ---- An instance: a scale that grows it drops it onto the bed; size keeps the proportions ---- + {"tool": "open_files", "args": {"paths": ["${vars.cube}"]}, "expect": {"/added": {"eq": 1}}}, + {"tool": "transform", "args": {"object": 0, "scale": 1.5}}, + {"tool": "list_objects", "expect": {"/items/0/bbox/min/2": {"ge": -0.001, "le": 0.001}}}, + {"tool": "transform", "args": {"object": 0, "size": [30, null, null]}}, + {"tool": "list_objects", "expect": {"/items/0/bbox/size/0": {"ge": 29.99, "le": 30.01}, + "/items/0/bbox/min/2": {"ge": -0.001, "le": 0.001}}}, + {"tool": "transform", "args": {"object": 0, "size": [30, 20, 10]}}, + {"tool": "list_objects", "expect": {"/items/0/bbox/size/1": {"ge": 19.99, "le": 20.01}, + "/items/0/bbox/size/2": {"ge": 9.99, "le": 10.01}}}, + {"tool": "transform", "args": {"object": 0, "size": [30, 30, 30]}}, + + // ---- A move to another plate registers the instance there, for list_objects and slicing ---- + {"tool": "run_action", "args": {"id": "orca_command:plate_add:orca"}}, + {"tool": "transform", "args": {"object": 0, "plate": 1}, "expect": {"/plate": {"eq": 1}}}, + {"tool": "list_objects", "args": {"plate": 1}, "expect": {"/total": {"eq": 1}, "/items/0/instances/0/plate": {"eq": 1}}}, + {"tool": "transform", "args": {"object": 0, "plate": 0}, "expect": {"/plate": {"eq": 0}}}, + {"tool": "transform", "args": {"object": 0, "translate": [100, 100, 0], "mode": "absolute"}, + "expect": {"/offset/0": {"ge": 99.99, "le": 100.01}, "/plate": {"eq": 0}}}, + + // ---- A part: the Object manipulation panel's path, measured on instance 0 ---- + {"tool": "select", "args": {"objects": [0]}}, + {"tool": "run_action", "args": {"id": "orca_command:add_primitive_svg:orca", "param": "${vars.svg}"}}, + {"tool": "wait", "args": {"for": "idle"}}, + {"tool": "ui_click", "args": {"target": {"gizmo": "SVG"}}}, + {"tool": "list_objects", "expect": {"/items/0/volumes/1/svg/path": {"contains": "star.svg"}}}, + {"tool": "transform", "args": {"object": 0, "volume": 1, "translate": [100, 100, 15], "mode": "absolute"}, + "expect": {"/volume_info/position/0": {"ge": 99.99, "le": 100.01}, "/volume_info/position/1": {"ge": 99.99, "le": 100.01}, + "/volume_info/position/2": {"ge": 14.99, "le": 15.01}, "/volume_info/type": {"eq": "part"}}}, + {"tool": "transform", "args": {"object": 0, "volume": 1, "translate": [5, 0, 0]}, + "expect": {"/volume_info/position/0": {"ge": 104.99, "le": 105.01}}}, + // one undo step per call + {"tool": "run_action", "args": {"id": "orca_command:undo:orca"}}, + {"tool": "transform", "args": {"object": 0, "volume": 1, "translate": [0, 0, 0]}, + "expect": {"/volume_info/position/0": {"ge": 99.99, "le": 100.01}}}, + {"tool": "transform", "args": {"object": 0, "volume": 1, "scale": 2, "mode": "absolute"}, + "expect": {"/volume_info/scale/0": {"ge": 1.999, "le": 2.001}, "/volume_info/scale/2": {"ge": 1.999, "le": 2.001}}}, + {"tool": "transform", "args": {"object": 0, "volume": 1, "size": [null, null, 3]}, + "expect": {"/size/2": {"ge": 2.999, "le": 3.001}}}, + {"tool": "transform", "args": {"object": 0, "volume": 1, "rotate": [0, 0, 45]}}, + // refused: an absolute rotation of a part, a part with plate, a single part + {"tool": "transform", "args": {"object": 0, "volume": 1, "rotate": [0, 0, 0], "mode": "absolute"}, "optional": true}, + {"tool": "transform", "args": {"object": 0, "volume": 1, "plate": 1}, "optional": true}, + {"tool": "list_objects", "expect": {"/items/0/instances/0/plate": {"eq": 0}}}, + + // ---- What list_objects says of the part and the instance: placement on the bed, filament, mirror ---- + // The star stands on the face the camera saw, so only orientation-free values are checked; a turn + // about Z keeps its height, and at 0.3 of its size it holds 0.027 of its mesh's volume. + {"tool": "list_objects", "expect": {"/items/0/filament": {"eq": 1}, "/items/0/auto_drop": {"eq": true}, + "/items/0/instances/0/mirrored": {"eq": false}, + "/items/0/instances/0/bbox/min/2": {"ge": -0.001, "le": 0.001}, + "/items/0/instances/0/bbox/size/0": {"ge": 29.99, "le": 30.01}, + "/items/0/volumes/1/filament": {"eq": 1}, "/items/0/volumes/1/mirrored": {"eq": false}, + "/items/0/volumes/1/position/2": {"ge": 14.99, "le": 15.01}, + "/items/0/volumes/1/bbox/min/2": {"gt": 0, "le": 15}, + "/items/0/volumes/1/bbox/max/2": {"ge": 15, "lt": 30}, + "/items/0/volumes/1/mesh_volume": {"gt": 1000}, + "/items/0/volumes/1/scaled_volume": {"gt": 0, "lt": 100}}}, + // a mirrored part is mirrored in the object's frame; an instance mirrored twice is a half turn + {"tool": "select", "args": {"volumes": [[0, 1]]}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_mirror_x:orca"}}, + {"tool": "list_objects", "expect": {"/items/0/volumes/1/mirrored": {"eq": true}, "/items/0/instances/0/mirrored": {"eq": false}}}, + {"tool": "select", "args": {"objects": [0]}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_mirror_y:orca"}}, + {"tool": "list_objects", "expect": {"/items/0/instances/0/mirrored": {"eq": true}, "/items/0/instances/0/scale/0": {"gt": 0}, + "/items/0/volumes/1/mirrored": {"eq": true}}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_mirror_x:orca"}}, + {"tool": "list_objects", "expect": {"/items/0/instances/0/mirrored": {"eq": false}}}, + + // ---- Shapes at a size, without the dialog ---- + {"tool": "select", "args": {"none": true}}, + {"tool": "run_action", "args": {"id": "orca_command:add_primitive_cube:orca", "param": "40 40 10"}}, + {"tool": "list_objects", "expect": {"/total": {"eq": 2}, "/items/1/bbox/size/0": {"ge": 39.99, "le": 40.01}, + "/items/1/bbox/size/2": {"ge": 9.99, "le": 10.01}}}, + {"tool": "transform", "args": {"object": 1, "volume": 0, "translate": [1, 0, 0]}, "optional": true}, + // a wrong count adds nothing + {"tool": "select", "args": {"none": true}}, + {"tool": "run_action", "args": {"id": "orca_command:add_primitive_cylinder:orca", "param": "1 2 3"}, "optional": true}, + {"tool": "list_objects", "expect": {"/total": {"eq": 2}}}, + // with an object selected, an error instead of a silent success + {"tool": "select", "args": {"objects": [1]}}, + {"tool": "run_action", "args": {"id": "orca_command:add_primitive_cylinder:orca", "param": "10 5"}, "optional": true}, + {"tool": "list_objects", "expect": {"/total": {"eq": 2}}}, + {"tool": "select", "args": {"none": true}}, + {"tool": "run_action", "args": {"id": "orca_command:add_primitive_cylinder:orca", "param": "10 5"}}, + {"tool": "list_objects", "expect": {"/total": {"eq": 3}}}, + + // ---- Fill bed fills the object's own plate, in one undo step ---- + // The shapes were added on the current plate, plate 1; the cube goes back to plate 0. + {"tool": "transform", "args": {"object": 1, "plate": 0}, "expect": {"/plate": {"eq": 0}}}, + {"tool": "arrange", "args": {"fill": 2}, "expect": {"/added": {"gt": 0}, "/plate": {"eq": 1}, "/off_plate": {"empty": true}}}, + {"tool": "list_objects", "expect": {"/items/2/instances/1": {"exists": true}}}, + {"tool": "run_action", "args": {"id": "orca_command:undo:orca"}}, + {"tool": "list_objects", "expect": {"/items/2/instances/1": {"exists": false}}}, + // refused: a locked plate, a plate that does not exist, fill with plates + {"tool": "run_action", "args": {"id": "orca_command:plate_goto:orca", "param": "1"}}, + {"tool": "run_action", "args": {"id": "orca_command:plate_toggle_lock:orca"}}, + {"tool": "arrange", "args": {"plates": 1}, "optional": true}, + {"tool": "run_action", "args": {"id": "orca_command:plate_toggle_lock:orca"}}, + {"tool": "arrange", "args": {"plates": 7}, "optional": true}, + {"tool": "arrange", "args": {"fill": 0, "plates": 0}, "optional": true}, + {"tool": "list_objects", "expect": {"/plates": {"eq": 2}, "/items/2/instances/0/plate": {"eq": 1}, + "/items/2/instances/1": {"exists": false}}}, + + // ---- Arrange one plate with options; the other plate keeps its object (arrange may reorder objects) ---- + {"tool": "arrange", "args": {"plates": 0, "spacing": 10, "rotate": false, "align_y": false}, + "expect": {"/off_plate": {"empty": true}, "/plates": {"eq": 2}, "/settings/spacing": {"eq": 10}, + "/settings/rotate": {"eq": false}}}, + {"tool": "list_objects", "args": {"plate": 1}, "expect": {"/total": {"eq": 1}, "/items/0/name": {"eq": "Cylinder"}}}, + {"tool": "list_objects", "args": {"plate": 0}, "expect": {"/total": {"eq": 2}}}, + // every plate with the saved options; obj_arrange runs the same job and returns once it is done + {"tool": "arrange", "expect": {"/settings/spacing": {"eq": 10}, "/off_plate": {"empty": true}}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_arrange:orca"}, "expect": {"/level": {"eq": "success"}}}, + // a Speed Dial command that does nothing (no selection) is an error step + {"tool": "select", "args": {"none": true}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_mirror_x:orca"}, "optional": true}, + + // ---- add_part: the context menu's Add items, with a size, a file or a position, one undo step each ---- + {"tool": "new_project", "args": {"discard_changes": true}}, + {"tool": "run_action", "args": {"id": "orca_command:add_primitive_cube:orca", "param": "40 40 10"}}, + {"tool": "transform", "args": {"object": 0, "translate": [100, 100, 5], "mode": "absolute"}}, + // a magnet pocket at the bottom centre + {"tool": "add_part", "args": {"object": 0, "type": "negative", "shape": "cylinder", "size": [6.2, 3.2], + "position": [100, 100, 1.6]}, + "expect": {"/volume": {"eq": 1}, "/volume_count": {"eq": 2}, "/volume_info/type": {"eq": "negative"}, + "/volume_info/position/0": {"ge": 99.99, "le": 100.01}, "/volume_info/position/1": {"ge": 99.99, "le": 100.01}, + "/volume_info/bbox/min/2": {"ge": -0.01, "le": 0.01}, "/volume_info/bbox/size/2": {"ge": 3.19, "le": 3.21}, + "/volume_info/bbox/size/0": {"ge": 6.1, "le": 6.21}}}, + {"tool": "list_objects", "expect": {"/items/0/volumes/1/mesh_volume": {"gt": 90}, + "/items/0/bbox/size/2": {"ge": 9.99, "le": 10.01}}}, + {"tool": "run_action", "args": {"id": "orca_command:undo:orca"}}, + {"tool": "list_objects", "expect": {"/items/0/volumes/1": {"exists": false}}}, + {"tool": "run_action", "args": {"id": "orca_command:redo:orca"}}, + {"tool": "list_objects", "expect": {"/items/0/volumes/1/type": {"eq": "negative"}}}, + // a modifier from a file, where Load... puts it; parts are ordered by type (part, negative, modifier) + {"tool": "add_part", "args": {"object": 0, "type": "modifier", "path": "${vars.cube}"}, + "expect": {"/volume": {"eq": 2}, "/volume_count": {"eq": 3}, "/volume_info/type": {"eq": "modifier"}, + "/volume_info/name": {"eq": "OrcaCube_v2.drc"}}}, + // a solid part at a size takes the object's filament and grows the object; the built-in size for the rest + {"tool": "add_part", "args": {"object": 0, "type": "part", "shape": "cube", "size": [10, 10, 20], "position": [125, 100, 10]}, + "expect": {"/volume": {"eq": 1}, "/volume_info/type": {"eq": "part"}, "/volume_info/filament": {"eq": 1}, + "/volume_info/bbox/size/2": {"ge": 19.99, "le": 20.01}}}, + {"tool": "add_part", "args": {"object": 0, "type": "support_blocker", "shape": "sphere", "position": [110, 110, 10]}, + "expect": {"/volume_info/type": {"eq": "support_blocker"}, "/volume_info/position/2": {"ge": 9.99, "le": 10.01}}}, + {"tool": "add_part", "args": {"object": 0, "type": "precise_seam", "shape": "cube", "size": [2, 2, 2]}, + "expect": {"/volume_info/type": {"eq": "precise_seam"}, "/volume_info/subtype": {"eq": "center"}}}, + {"tool": "list_objects", "expect": {"/items/0/volumes/2/type": {"eq": "negative"}, "/items/0/volumes/3/type": {"eq": "modifier"}, + "/items/0/volumes/5": {"exists": true}, "/items/0/volumes/6": {"exists": false}, + "/items/0/bbox/size/2": {"ge": 19.99, "le": 20.01}}}, + // refused, adding nothing: shape and path, a size with the wrong count, an SVG file, a file that is + // not a model, an object with two instances + {"tool": "add_part", "args": {"object": 0, "type": "modifier", "shape": "cube", "path": "${vars.cube}"}, "optional": true}, + {"tool": "add_part", "args": {"object": 0, "type": "modifier", "shape": "cylinder", "size": [1, 2, 3]}, "optional": true}, + {"tool": "add_part", "args": {"object": 0, "type": "part", "path": "${vars.svg}"}, "optional": true}, + {"tool": "add_part", "args": {"object": 0, "type": "modifier", "path": "${script_dir}/fixtures/heightmap.png"}, "optional": true}, + {"tool": "select", "args": {"objects": [0]}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_instances_up:orca"}}, + {"tool": "add_part", "args": {"object": 0, "type": "modifier", "shape": "cube"}, "optional": true}, + {"tool": "list_objects", "expect": {"/items/0/volumes/6": {"exists": false}, "/items/0/instances/1": {"exists": true}}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_instances_down:orca"}}, + // a shape folds the instance's scale into the parts, as the menu does + {"tool": "select", "args": {"none": true}}, + {"tool": "run_action", "args": {"id": "orca_command:add_primitive_cube:orca", "param": "20 20 20"}}, + {"tool": "transform", "args": {"object": 1, "scale": 1.5}}, + {"tool": "add_part", "args": {"object": 1, "type": "modifier", "shape": "cube"}, "expect": {"/volume": {"eq": 1}}}, + {"tool": "list_objects", "expect": {"/items/1/instances/0/scale/0": {"ge": 0.999, "le": 1.001}, + "/items/1/bbox/size/0": {"ge": 29.99, "le": 30.01}, + "/items/1/volumes/0/scale/0": {"ge": 1.499, "le": 1.501}}}, + + // ---- Object structure commands: the context menus' Change Type, Rename, number of instances, + // Set as Individual Objects and Assemble, each a run_action on what select picked ---- + {"tool": "new_project", "args": {"discard_changes": true}}, + {"tool": "run_action", "args": {"id": "orca_command:add_primitive_cube:orca", "param": "30 30 10"}}, + {"tool": "add_part", "args": {"object": 0, "type": "modifier", "shape": "cube", "size": [10, 10, 10]}, "expect": {"/volume": {"eq": 1}}}, + // Change Type, one undo step each; a seam made a part again is listed after the first part + {"tool": "select", "args": {"volumes": [[0, 1]]}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_type_negative:orca"}, "expect": {"/level": {"eq": "success"}}}, + {"tool": "list_objects", "expect": {"/items/0/volumes/1/type": {"eq": "negative"}}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_type_support_blocker:orca"}}, + {"tool": "list_objects", "expect": {"/items/0/volumes/1/type": {"eq": "support_blocker"}}}, + {"tool": "run_action", "args": {"id": "orca_command:undo:orca"}}, + {"tool": "list_objects", "expect": {"/items/0/volumes/1/type": {"eq": "negative"}}}, + {"tool": "select", "args": {"volumes": [[0, 1]]}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_type_precise_seam:orca"}}, + {"tool": "list_objects", "expect": {"/items/0/volumes/1/type": {"eq": "precise_seam"}, "/items/0/volumes/1/subtype": {"eq": "center"}}}, + {"tool": "select", "args": {"volumes": [[0, 1]]}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_type_part:orca"}}, + {"tool": "list_objects", "expect": {"/items/0/volumes/0/type": {"eq": "part"}, "/items/0/volumes/1/type": {"eq": "part"}}}, + {"tool": "select", "args": {"volumes": [[0, 1]]}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_type_modifier:orca"}}, + // refused, changing nothing: the object's last solid part, and an object's row, which is not a part + {"tool": "select", "args": {"volumes": [[0, 0]]}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_type_modifier:orca"}, "optional": true}, + {"tool": "select", "args": {"objects": [0]}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_type_part:orca"}, "optional": true}, + {"tool": "list_objects", "expect": {"/items/0/volumes/0/type": {"eq": "part"}, "/items/0/volumes/1/type": {"eq": "modifier"}}}, + // refused: an SVG part stays a part, a modifier or a negative part + {"tool": "run_action", "args": {"id": "orca_command:add_primitive_svg:orca", "param": "${vars.svg}"}}, + {"tool": "wait", "args": {"for": "idle"}}, + {"tool": "ui_click", "args": {"target": {"gizmo": "SVG"}}}, + {"tool": "list_objects", "expect": {"/items/0/volumes/1/svg/path": {"contains": "star.svg"}, "/items/0/volumes/2/type": {"eq": "modifier"}}}, + {"tool": "select", "args": {"volumes": [[0, 1]]}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_type_support_enforcer:orca"}, "optional": true}, + {"tool": "list_objects", "expect": {"/items/0/volumes/1/type": {"eq": "part"}}}, + // Rename an object and a part; refused: a name a file name cannot hold + {"tool": "select", "args": {"objects": [0]}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_rename:orca", "param": "base"}}, + {"tool": "select", "args": {"volumes": [[0, 2]]}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_rename:orca", "param": "infill zone"}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_rename:orca", "param": "a/b"}, "optional": true}, + {"tool": "list_objects", "expect": {"/items/0/name": {"eq": "base"}, "/items/0/volumes/2/name": {"eq": "infill zone"}}}, + // a number of instances in one undo step; refused: 0 and a word + {"tool": "select", "args": {"none": true}}, + {"tool": "run_action", "args": {"id": "orca_command:add_primitive_cube:orca", "param": "20 20 20"}}, + {"tool": "select", "args": {"objects": [1]}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_set_instances:orca", "param": "6"}, + "expect": {"/object": {"eq": 1}, "/instances": {"eq": 6}}}, + {"tool": "run_action", "args": {"id": "orca_command:undo:orca"}}, + {"tool": "list_objects", "expect": {"/items/1/instances/1": {"exists": false}}}, + {"tool": "select", "args": {"objects": [1]}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_set_instances:orca", "param": "3"}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_set_instances:orca", "param": "0"}, "optional": true}, + {"tool": "run_action", "args": {"id": "orca_command:obj_set_instances:orca", "param": "three"}, "optional": true}, + {"tool": "list_objects", "expect": {"/total": {"eq": 2}, "/items/1/instances/2": {"exists": true}, "/items/1/instances/3": {"exists": false}}}, + // every instance its own object (the whole object selected), then two of them assembled + {"tool": "select", "args": {"objects": [1]}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_instances_to_objects:orca"}, + "expect": {"/objects/0": {"eq": 1}, "/objects/2": {"eq": 3}}}, + {"tool": "list_objects", "expect": {"/total": {"eq": 4}, "/items/3/instances/1": {"exists": false}}}, + {"tool": "select", "args": {"objects": [1]}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_instances_to_objects:orca"}, "optional": true}, + {"tool": "select", "args": {"objects": [2, 3]}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_assemble:orca"}, "expect": {"/object": {"eq": 2}, "/name": {"eq": "Assembly"}}}, + {"tool": "list_objects", "expect": {"/total": {"eq": 3}, "/items/2/name": {"eq": "Assembly"}, "/items/2/volumes/1": {"exists": true}}}, + {"tool": "select", "args": {"objects": [0]}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_assemble:orca"}, "optional": true}, + {"tool": "list_objects", "expect": {"/total": {"eq": 3}}}, + + // ---- Order By: ascending, reversed when run again, and the reply says which ---- + {"tool": "new_project", "args": {"discard_changes": true}}, + {"tool": "run_action", "args": {"id": "orca_command:add_primitive_cube:orca", "param": "20 20 30"}}, + {"tool": "select", "args": {"none": true}}, + {"tool": "run_action", "args": {"id": "orca_command:add_primitive_cube:orca", "param": "20 20 10"}}, + {"tool": "select", "args": {"none": true}}, + {"tool": "run_action", "args": {"id": "orca_command:add_primitive_cube:orca", "param": "20 20 20"}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_order_by_height:orca"}, + "expect": {"/descending": {"eq": false}, "/order/2/object": {"eq": 2}, "/order/2/plate": {"eq": 0}}}, + {"tool": "list_objects", "expect": {"/items/0/bbox/size/2": {"ge": 9.99, "le": 10.01}, "/items/2/bbox/size/2": {"ge": 29.99, "le": 30.01}}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_order_by_height:orca"}, "expect": {"/descending": {"eq": true}}}, + {"tool": "list_objects", "expect": {"/items/0/bbox/size/2": {"ge": 29.99, "le": 30.01}}}, + // refused: an empty current plate, a param other than all; all orders every plate + {"tool": "run_action", "args": {"id": "orca_command:plate_add:orca"}}, + {"tool": "run_action", "args": {"id": "orca_command:plate_goto:orca", "param": "1"}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_order_by_size:orca"}, "optional": true}, + {"tool": "run_action", "args": {"id": "orca_command:obj_order_by_size:orca", "param": "every"}, "optional": true}, + {"tool": "list_objects", "expect": {"/items/0/bbox/size/2": {"ge": 29.99, "le": 30.01}}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_order_by_size:orca", "param": "all"}, + "expect": {"/descending": {"eq": false}, "/order/0/plate": {"eq": 0}, "/order/3": {"exists": false}}}, + {"tool": "list_objects", "expect": {"/items/0/bbox/size/2": {"ge": 9.99, "le": 10.01}}}, + + // ---- End to end: a block with a magnet pocket and a boss, sized on the bed, moved to a second + // plate, six copies arranged apart there, each made its own object, one mirrored, two assembled, + // all ordered by name, the plate filled with one of them, and the plate sliced ---- + {"tool": "new_project", "args": {"discard_changes": true}}, + {"tool": "run_action", "args": {"id": "orca_command:add_primitive_cube:orca", "param": "40 40 10"}}, + {"tool": "transform", "args": {"object": 0, "translate": [100, 100, 5], "mode": "absolute"}}, + {"tool": "add_part", "args": {"object": 0, "type": "negative", "shape": "cylinder", "size": [6.2, 3.2], + "position": [100, 100, 1.6]}, "expect": {"/volume": {"eq": 1}}}, + // a boss on top; solid parts are listed before negative ones + {"tool": "add_part", "args": {"object": 0, "type": "part", "shape": "cylinder", "size": [10, 5], "position": [100, 100, 12.5]}, + "expect": {"/volume": {"eq": 1}, "/volume_count": {"eq": 3}, "/volume_info/bbox/min/2": {"ge": 9.99, "le": 10.01}}}, + {"tool": "select", "args": {"volumes": [[0, 1]]}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_rename:orca", "param": "boss"}}, + {"tool": "transform", "args": {"object": 0, "volume": 1, "translate": [5, 0, 0]}, + "expect": {"/volume_info/name": {"eq": "boss"}, "/volume_info/position/0": {"ge": 104.99, "le": 105.01}}}, + // 50 mm wide in proportion, so 1.25 x (10 + 5) mm tall, and still on the bed + {"tool": "transform", "args": {"object": 0, "size": [50, null, null]}}, + {"tool": "list_objects", "expect": {"/items/0/bbox/size/0": {"ge": 49.99, "le": 50.01}, + "/items/0/bbox/size/2": {"ge": 18.74, "le": 18.76}, + "/items/0/bbox/min/2": {"ge": -0.001, "le": 0.001}, + "/items/0/volumes/2/type": {"eq": "negative"}}}, + {"tool": "run_action", "args": {"id": "orca_command:plate_add:orca"}}, + {"tool": "transform", "args": {"object": 0, "plate": 1}, "expect": {"/plate": {"eq": 1}}}, + // six copies, overlapping where Set Number of Instances puts them, spread out on plate 1 alone + {"tool": "select", "args": {"objects": [0]}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_set_instances:orca", "param": "6"}, "expect": {"/instances": {"eq": 6}}}, + {"tool": "arrange", "args": {"plates": 1, "spacing": 10, "rotate": false}, + "expect": {"/off_plate": {"empty": true}, "/settings/spacing": {"eq": 10}, "/plates": {"eq": 2}}}, + {"tool": "list_objects", "args": {"plate": 0}, "expect": {"/total": {"eq": 0}}}, + {"tool": "list_objects", "args": {"plate": 1}, "expect": {"/items/0/instances/5/plate": {"eq": 1}}}, + // every instance its own object (the whole object selected), each with the three parts + {"tool": "select", "args": {"objects": [0]}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_instances_to_objects:orca"}, "expect": {"/objects/5": {"eq": 5}}}, + {"tool": "list_objects", "expect": {"/total": {"eq": 6}, "/items/5/volumes/1/name": {"eq": "boss"}, + "/items/5/volumes/2/type": {"eq": "negative"}, "/items/5/instances/0/plate": {"eq": 1}}}, + {"tool": "select", "args": {"objects": [5]}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_mirror_x:orca"}}, + {"tool": "list_objects", "expect": {"/items/5/instances/0/mirrored": {"eq": true}, "/items/4/instances/0/mirrored": {"eq": false}}}, + // two assembled into one object, which goes last; the mirrored one moves up to index 3 + {"tool": "select", "args": {"objects": [0, 1]}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_assemble:orca"}, "expect": {"/object": {"eq": 4}, "/name": {"eq": "Assembly"}}}, + {"tool": "list_objects", "expect": {"/total": {"eq": 5}, "/items/4/volumes/5": {"exists": true}, + "/items/4/bbox/min/2": {"ge": -0.001, "le": 0.001}, + "/items/3/instances/0/mirrored": {"eq": true}}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_order_by_name:orca", "param": "all"}, + "expect": {"/descending": {"eq": false}, "/order/0/name": {"eq": "Assembly"}, "/order/4/plate": {"eq": 1}}}, + {"tool": "arrange", "args": {"fill": 1}, "expect": {"/added": {"gt": 0}, "/plate": {"eq": 1}, "/off_plate": {"empty": true}}}, + {"tool": "slice", "args": {"plates": 1}, "expect": {"/plates/0/outcome": {"eq": "ok"}}}, + {"tool": "set_view", "args": {"tab": "prepare"}}, + {"tool": "screenshot","args": {"target": "canvas", "save_path": "${out_dir}/scene.png", "overwrite": true, "include_image": false}} + ] +} diff --git a/tools/mcp/tests/slice_stats.json b/tools/mcp/tests/slice_stats.json new file mode 100644 index 0000000000..d9b315f321 --- /dev/null +++ b/tools/mcp/tests/slice_stats.json @@ -0,0 +1,58 @@ +// The slice reply's statistics: layers and max Z, filament changes, the totals with the flush, and +// every filament slot split into model, support, flush and prime tower. A 25.6 mm cube on filament 1 +// of two, then a second cube on filament 2, so every layer changes filament. Run it on a fresh +// datadir set up with the default printer (Bambu Lab X1 Carbon 0.4, prime tower on): +// tools/mcp/orca_mcp.py run-script tools/mcp/tests/slice_stats.json --out /tmp/slice_stats +// The sums (filament_g as the slots' g, a slot's g as its four uses) are unit tests in +// tests/slic3rutils/test_mcp_results.cpp, since a script step cannot add values up. +{ + "orca_script": 1, + "name": "slice statistics", + "steps": [ + {"tool": "wait", "args": {"for": "ready"}}, + {"tool": "dialog_auto_answer", "args": {"rules": [{"match": "Uniform scale", "button": "ok"}]}}, + {"tool": "new_project", "args": {"discard_changes": true}}, + {"tool": "set_view", "args": {"tab": "prepare"}}, + {"tool": "ui_click", "args": {"target": {"label": "Add one filament"}}}, + {"tool": "get_state", "expect": {"/presets/filaments/1": {"exists": true}}}, + {"tool": "run_action", "args": {"id": "orca_command:add_primitive_cube:orca"}}, + {"tool": "wait", "args": {"for": "idle"}}, + + // ---- One colour: no flush, tower or change; the unused slot 2 is listed with zeros ---- + {"tool": "slice", "expect": { + "/plates/0/outcome": {"eq": "ok"}, + "/plates/0/layers": {"eq": 128}, + "/plates/0/max_z": {"gt": 25.5, "lt": 25.7}, + "/plates/0/filament_changes": {"eq": 0}, + "/plates/0/filament_g": {"gt": 0}, + "/plates/0/filaments/2": {"exists": false}, + "/plates/0/filaments/0/slot": {"eq": 1}, + "/plates/0/filaments/0/model_g": {"gt": 0}, + "/plates/0/filaments/0/flush_g": {"eq": 0}, + "/plates/0/filaments/0/tower_g": {"eq": 0}, + "/plates/0/filaments/1/slot": {"eq": 2}, + "/plates/0/filaments/1/g": {"eq": 0}}}, + + // ---- Two colours: the second cube on filament 2 ---- + {"tool": "select", "args": {"none": true}}, + {"tool": "run_action", "args": {"id": "orca_command:add_primitive_cube:orca"}}, + {"tool": "wait", "args": {"for": "idle"}}, + {"tool": "run_action", "args": {"id": "orca_command:obj_arrange:orca"}}, + {"tool": "wait", "args": {"for": "idle"}}, + {"tool": "select", "args": {"objects": [1]}}, + // To the canvas by name: without a target the key goes to whatever has focus. + {"tool": "ui_key", "args": {"target": {"name": "OrcaSceneCanvas"}, "keys": "2"}, "expect": {"/to": {"eq": "wxGLCanvas"}}}, + {"tool": "select", "args": {"none": true}}, + {"tool": "slice", "expect": { + "/plates/0/outcome": {"eq": "ok"}, + "/plates/0/layers": {"eq": 128}, + "/plates/0/filament_changes": {"gt": 100}, + "/plates/0/filaments/0/model_g": {"gt": 0}, + "/plates/0/filaments/1/model_g": {"gt": 0}, + "/plates/0/filaments/0/flush_g": {"gt": 0}, + "/plates/0/filaments/1/flush_g": {"gt": 0}, + "/plates/0/filaments/0/tower_g": {"gt": 0}, + "/plates/0/filaments/1/tower_g": {"gt": 0}, + "/plates/0/filaments/1/support_g": {"eq": 0}}} + ] +} diff --git a/tools/mcp/tests/webview_modal.json b/tools/mcp/tests/webview_modal.json new file mode 100644 index 0000000000..335a02c9b6 --- /dev/null +++ b/tools/mcp/tests/webview_modal.json @@ -0,0 +1,32 @@ +// Scripts in the web views of modal dialogs, which webview_eval runs in only for the preset bundle +// dialogs and the setup wizard: by default and by locator, and the bundle dialog closed from its +// page's own button, which replies closed. Run it on a fresh datadir set up with the default printer: +// tools/mcp/orca_mcp.py run-script tools/mcp/tests/webview_modal.json --out /tmp/webview_modal +// The refusals (the Flushing volumes dialog, a web view behind a modal) are in +// tools/mcp/test_webview_modal.py. +{ + "orca_script": 1, + "name": "web views in modal dialogs", + "steps": [ + {"tool": "wait", "args": {"for": "ready"}}, + + // ---- The preset bundle dialog ---- + {"tool": "run_action", "args": {"id": "orca_command:preset_bundle:orca"}, "await": false, "save_as": "bundle"}, + {"tool": "wait", "args": {"for": "dialog", "timeout_s": 10}, "expect": {"/satisfied": {"eq": true}}}, + {"tool": "webview_eval", "args": {"script": "document.title"}, + "expect": {"/result": {"eq": "Preset Bundle"}, "/url": {"contains": "PresetBundleDialog"}}}, + {"tool": "webview_eval", "args": {"script": "!!document.getElementById('close_btn')", "target": {"class": "webview", "within": "Preset Bundle"}}, + "expect": {"/result": {"eq": true}}}, + {"tool": "webview_eval", "args": {"script": "document.getElementById('close_btn').click()"}, "expect": {"/closed": {"eq": true}}}, + {"tool": "wait", "args": {"for": "job", "job": "${jobs.bundle}"}}, + {"tool": "get_state", "expect": {"/dialogs": {"empty": true}}}, + + // ---- The setup wizard: its page is read, and the dialog only closed ---- + {"tool": "run_action", "args": {"id": "orca_command:help_setup_wizard:orca"}, "await": false, "save_as": "wizard"}, + {"tool": "wait", "args": {"for": "dialog", "timeout_s": 30}, "expect": {"/satisfied": {"eq": true}}}, + {"tool": "webview_eval", "args": {"script": "typeof document.title"}, "expect": {"/result": {"eq": "string"}, "/url": {"contains": "/guide/"}}}, + {"tool": "dialog_respond", "args": {"dialog": {"title": "Setup Wizard"}, "button": "close"}}, + {"tool": "wait", "args": {"for": "job", "job": "${jobs.wizard}"}}, + {"tool": "get_state", "expect": {"/dialogs": {"empty": true}}} + ] +}