From 23a104bc8518d23fae8e968b07467620673d671d Mon Sep 17 00:00:00 2001 From: SoftFever Date: Thu, 19 Nov 2026 22:11:04 +0800 Subject: [PATCH] Let MCP clients lay an object on a face, set its brim ears, and add text or an SVG to a named object object_lay_on_face turns an instance so that the face a direction names lies on the bed, as a click in the Lay on Face gizmo does, and object_set_brim_ears places brim ears at bed positions, or clears them, as the Brim Ears gizmo stores them; called with only their object, both open their gizmo. object_add_text and object_add_svg can name the object the part joins and make it a negative part or a modifier. The Brim Ears gizmo shows ears set this way when it next opens, rather than writing back the ones it held. --- scripts/check_operation_calls.py | 1 + src/slic3r/GUI/Gizmos/GLGizmoBrimEars.cpp | 9 +- src/slic3r/GUI/Gizmos/GLGizmoBrimEars.hpp | 13 +- src/slic3r/GUI/Mcp/McpToolsGizmos.cpp | 141 +++++++++++- src/slic3r/GUI/Mcp/McpToolsScene.cpp | 30 ++- src/slic3r/GUI/NativeCommandMenuItems.hpp | 9 +- src/slic3r/GUI/NativeCommands.cpp | 48 +++- src/slic3r/GUI/Operations/GizmoOps.cpp | 128 ++++++++++- src/slic3r/GUI/Operations/GizmoOps.hpp | 63 ++++- tests/data/command_catalog.json | 254 ++++++++++++++++++++- tests/slic3rutils/test_command_catalog.cpp | 19 +- tests/slic3rutils/test_mcp_scene.cpp | 27 ++- tests/slic3rutils/test_mcp_tools.cpp | 6 +- tests/slic3rutils/test_operations.cpp | 88 +++++++ tools/mcp/test-entries/gizmos.md | 18 +- tools/mcp/test_gizmo_commands.py | 250 +++++++++++++++++++- 16 files changed, 1044 insertions(+), 60 deletions(-) diff --git a/scripts/check_operation_calls.py b/scripts/check_operation_calls.py index 9e22744562..d2db90e65f 100644 --- a/scripts/check_operation_calls.py +++ b/scripts/check_operation_calls.py @@ -96,6 +96,7 @@ BANNED = { # The gizmo commands open their gizmo through it; a gizmo icon's click stays the GUI tools' (UiInspector.cpp). "open_gizmo": ["open_gizmo"], "cut_object": ["apply_cut_object_to_model", "perform_with_plane"], + "lay_on_face": ["flattening_rotate"], "the undo snapshot of an operation": ["take_snapshot"], } diff --git a/src/slic3r/GUI/Gizmos/GLGizmoBrimEars.cpp b/src/slic3r/GUI/Gizmos/GLGizmoBrimEars.cpp index 0501e12ff9..6e23a43d12 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoBrimEars.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoBrimEars.cpp @@ -60,8 +60,6 @@ static const ColorRGBA DEF_COLOR = {0.7f, 0.7f, 0.7f, 1.f}; static const ColorRGBA SELECTED_COLOR = {0.0f, 0.5f, 0.5f, 1.0f}; static const ColorRGBA ERR_COLOR = {1.0f, 0.3f, 0.3f, 0.5f}; static const ColorRGBA HOVER_COLOR = {0.7f, 0.7f, 0.7f, 0.5f}; -static constexpr float BRIM_EAR_RADIUS_MIN = 0.1f; -static constexpr float BRIM_EAR_RADIUS_MAX = 100.f; static ModelVolume *get_model_volume(const Selection &selection, Model &model) { @@ -875,6 +873,13 @@ void GLGizmoBrimEars::update_model_object() m_parent.post_event(SimpleEvent(EVT_GLCANVAS_SCHEDULE_BACKGROUND_PROCESS)); } +void GLGizmoBrimEars::reload_on_next_opening() +{ + // An invalid id matches no object, so set_brim_data() reloads the cache when the gizmo next turns on. + m_old_mo_id = ObjectID(); + select_point(NoPoints); +} + // switch gizmos void GLGizmoBrimEars::on_set_state() { diff --git a/src/slic3r/GUI/Gizmos/GLGizmoBrimEars.hpp b/src/slic3r/GUI/Gizmos/GLGizmoBrimEars.hpp index 35177bfac6..d94b024a53 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoBrimEars.hpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoBrimEars.hpp @@ -32,6 +32,11 @@ namespace GUI { enum class SLAGizmoEventType : unsigned char; +// The radius an ear can have, in mm: the panel's slider and field keep to it, and so does a command that sets ears +// (Ops::set_brim_ears()). +inline constexpr float BRIM_EAR_RADIUS_MIN = 0.1f; +inline constexpr float BRIM_EAR_RADIUS_MAX = 100.f; + class GLGizmoBrimEars : public GLGizmoBase { private: @@ -99,6 +104,13 @@ public: void delete_selected_points(); bool has_selected_points() const; void update_model_object(); + // For a caller that wrote the object's ears while the gizmo was closed (Ops::set_brim_ears()): the gizmo reloads its + // ears only when it opens on another object than the one it last opened on, so without this its next opening on the + // same object would show, and write back, the ears it held when it last closed. Also clears the ear selection, so + // that the reloaded ears, all unselected, and the selection a click reads agree. + void reload_on_next_opening(); + // The radius a new ear takes: eight first-layer line widths of the edited process, within the radius limits. + float get_brim_default_radius() const; //ClippingPlane get_sla_clipping_plane() const; bool is_selection_rectangle_dragging() const override { return m_selection_rectangle.is_dragging(); } @@ -195,7 +207,6 @@ protected: //void update_single_mesh_pick(GLVolume* v); void reset_all_pick(); bool add_point_to_cache(Vec3f pos, float head_radius, bool selected, Vec3f normal); - float get_brim_default_radius() const; ExPolygon make_polygon(BrimPoint point, const Geometry::Transformation &trsf); void find_single(); }; diff --git a/src/slic3r/GUI/Mcp/McpToolsGizmos.cpp b/src/slic3r/GUI/Mcp/McpToolsGizmos.cpp index 78e96b4e79..7c2fa963f5 100644 --- a/src/slic3r/GUI/Mcp/McpToolsGizmos.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsGizmos.cpp @@ -1,7 +1,8 @@ // The gizmo commands: a named target's gizmo opened on it (object_paint, object_measure, object_simplify, part_boolean, -// object_cut). A call that names only its targets opens the gizmo and the client works it with the GUI tools; a command -// whose gizmo has an entry point that asks nothing also acts from its acting arguments (gizmo_acting_args()), with no -// gizmo: object_cut's cut by a plane. +// object_cut, object_lay_on_face, object_set_brim_ears). A call that names only its targets opens the gizmo and the +// client works it with the GUI tools; a command whose gizmo has an entry point that asks nothing also acts from its +// acting arguments (gizmo_acting_args()), with no gizmo: a cut by a plane, a lay on face by a direction, brim ears by +// position. #include "McpTargets.hpp" #include "McpTools.hpp" @@ -18,6 +19,7 @@ #include "slic3r/GUI/Plater.hpp" #include "slic3r/GUI/Selection.hpp" +#include "libslic3r/BrimEarsPoint.hpp" #include "libslic3r/Model.hpp" #include "libslic3r/Point.hpp" #include "libslic3r/TriangleMesh.hpp" @@ -133,6 +135,17 @@ json piece(const Model& model, int index) return {{"index", index}, {"object_id", object.id().id}, {"name", object.name}, {"open_edges", open_edges}}; } +// The one instance a gizmo command acts on: the instance or object named (the object's first instance), else the one +// selected. +std::pair acted_on(Plater& plater, const json& args) +{ + const Ops::Outcome named = resolve_targets(plater.model(), &plater.get_view3D_canvas3D()->get_selection(), args, + kObjects | kInstances, true); + if (!named) + throw refused(named.refusal()); + return one_instance(plater.model(), named.value()).instances.front(); +} + // object_cut from its acting arguments. The arguments the Cut gizmo's panel could not set together are refused before // anything is read: z with plane, a placement for a piece not kept, and placements or one piece with Cut to parts. json cut_from_args(const json& args) @@ -166,12 +179,8 @@ json cut_from_args(const json& args) if (args.contains("lower")) op.lower = placement(args["lower"].get()); - Plater& plater = ui_plater(); - const Ops::Outcome named = resolve_targets(plater.model(), &plater.get_view3D_canvas3D()->get_selection(), args, - kObjects | kInstances, true); - if (!named) - throw refused(named.refusal()); - std::tie(op.object, op.instance) = one_instance(plater.model(), named.value()).instances.front(); + Plater& plater = ui_plater(); + std::tie(op.object, op.instance) = acted_on(plater, args); if (args.contains("z")) { // A level plane that high above the bed, through the instance. op.point = plater.model().objects[std::size_t(op.object)]->instances[std::size_t(op.instance)]->get_offset(); @@ -195,6 +204,52 @@ json cut_from_args(const json& args) return reply; } +// object_lay_on_face from its acting arguments. +json lay_from_args(const json& args) +{ + if (!args.contains("normal")) + throw refused(Ops::Refusal{Ops::RefusalKind::Precondition, "needs_normal", + L("Laying an object on a face needs the face's direction: give normal with frame.")}); + Plater& plater = ui_plater(); + Ops::LayOnFaceArgs op; + std::tie(op.object, op.instance) = acted_on(plater, args); + op.normal = to_vec3(args["normal"], "normal"); + op.world = args.value("frame", std::string("object")) == "world"; + const Ops::Outcome turned = Ops::lay_on_face(op); + if (!turned) + throw refused(turned.refusal()); + const Vec3d degrees = turned.value() * (180. / PI); + return {{"object", op.object}, {"instance", op.instance}, {"rotation", {degrees.x(), degrees.y(), degrees.z()}}}; +} + +// object_set_brim_ears from its acting arguments. +json brim_ears_from_args(const json& args) +{ + if (args.contains("points") && args.contains("clear")) + throw ToolFailure("Give points or clear, not both."); + Plater& plater = ui_plater(); + Ops::SetBrimEarsArgs op; + std::tie(op.object, op.instance) = acted_on(plater, args); + for (const json& point : args.value("points", json::array())) { + const json& at = point.at("position"); + if (!at.is_array() || at.size() != 2) + throw ToolFailure("points[].position must be [x, y]"); + Ops::BrimEar ear; + ear.position = Vec2d(at[0].get(), at[1].get()); + if (point.contains("radius")) + ear.radius = point["radius"].get(); + op.ears.push_back(ear); + } + const Ops::Outcome set = Ops::set_brim_ears(op); + if (!set) + throw refused(set.refusal()); + json ears = json::array(); + for (const BrimPoint& ear : set.value().ears) + ears.push_back({{"position", {ear.pos.x(), ear.pos.y(), ear.pos.z()}}, {"radius", ear.head_front_radius}}); + return {{"object", op.object}, {"ears", std::move(ears)}, {"brim_type", set.value().brim_type}, + {"takes_effect", set.value().takes_effect}}; +} + NativeCommand gizmo_command(std::string name, std::string title, std::string description, json schema, EType type, GizmoTargets reading, json examples) { @@ -219,7 +274,9 @@ const std::vector& gizmo_acting_args(const std::string& command) // The gizmo commands' acting arguments: a call with any of them does the job and opens no gizmo. static const std::map> acting{ {"object_paint", {}}, {"object_measure", {}}, {"object_simplify", {}}, {"part_boolean", {}}, - {"object_cut", {"z", "plane", "keep", "upper", "lower", "to_parts"}}}; + {"object_cut", {"z", "plane", "keep", "upper", "lower", "to_parts"}}, + {"object_lay_on_face", {"normal", "frame"}}, + {"object_set_brim_ears", {"points", "clear"}}}; static const std::vector none; const auto found = acting.find(command); return found != acting.end() ? found->second : none; @@ -324,6 +381,70 @@ void register_gizmo_tools(CommandCatalog& catalog) {"title": "Keep the part of object 1 above a tilted plane", "calls": [ {"tool": "object_cut", "args": {"object": 1, "plane": {"point": [100, 100, 10], "normal": [1, 0, 1]}, "keep": "upper"}}]}])json"); catalog.add(reaching({"open_gizmo", "cut_object"}, std::move(cut))); + + NativeCommand lay = with_expected_ids(mutate_tool( + "object_lay_on_face", L("Lay on face"), + std::string( + "Lay an object's instance, the first unless instance is given, on one of its faces, as a click on that face in " + "the Lay on Face gizmo does. Acts from arguments: normal, frame. With none of them it opens the Lay on Face " + "gizmo. normal is the direction the face points out to: in the object's own frame (frame object, the default, " + "where [0, 0, -1] is the face that was its bottom) or in the 3D view's (frame world, where the face points now). " + "The instance turns so that face lies on the bed and drops onto it, one undo step; the object's other instances " + "turn with it. No flat face is looked for: the direction is laid down as given. A call that acts replies object, " + "instance and rotation, the instance's rotation in degrees as object_list gives it.") + + kWorkTheGizmo, + with_targets(object_schema({{"normal", array_prop({{"type", "number"}}, "[x, y, z]: the direction the face to lay on the bed " + "points out to; any length but zero.")}, + {"frame", enum_prop({"object", "world"}, "The frame normal is in: the object's own (default) or " + "the 3D view's. Needs normal.")}}), + kObjects | kInstances, true), + [](const json& args, ToolContext& ctx) { + json out = ctx.run_ui([&] { + return acts(args, "object_lay_on_face") ? lay_from_args(args) : + open_on(args, EType::Flatten, {kObjects | kInstances, true, one_instance}); + }); + settle(ctx); + return ToolResult::ok(out); + })); + lay.examples = json::parse(R"json([ + {"title": "Lay object 0 on the face that points down in its own frame", "calls": [ + {"tool": "object_lay_on_face", "args": {"object": 0, "normal": [0, 0, -1]}}]}, + {"title": "Lay object 0 on the face that now points to +X", "calls": [ + {"tool": "object_lay_on_face", "args": {"object": 0, "normal": [1, 0, 0], "frame": "world"}}]}])json"); + catalog.add(reaching({"open_gizmo", "lay_on_face"}, std::move(lay))); + + json ear = object_schema({{"position", array_prop({{"type", "number"}}, "[x, y] mm: where on the bed.")}, + {"radius", prop("number", "mm. Default: the gizmo's, eight first-layer line widths.")}}, + {"position"}); + NativeCommand brim = with_expected_ids(mutate_tool( + "object_set_brim_ears", L("Brim ears"), + std::string( + "Set an object's brim ears from positions on the bed, as the Brim Ears gizmo places them, through the instance " + "named, the first unless instance is given. Acts from arguments: points, clear. With none of them it opens the " + "Brim Ears gizmo. points replaces the object's ears with those given, each at a bed position, with a radius " + "from 0.1 to 100 mm or the gizmo's default; clear removes them all. The ears are taken on the bed and stored in " + "the object's coordinates, so they are the object's, shared by its instances. One undo step. They print only " + "with the painted brim type: settings_set on the object sets brim_type. A call that acts replies object, ears " + "as stored ({position: [x, y, z] in the object's coordinates, radius}), brim_type, the brim type the object " + "prints with, and takes_effect, whether that is painted.") + + kWorkTheGizmo, + with_targets(object_schema({{"points", array_prop(std::move(ear), "The ears, in place of the object's.")}, + {"clear", {{"type", "boolean"}, {"enum", {true}}, {"description", "Remove every ear. Not with points."}}}}), + kObjects | kInstances, true), + [](const json& args, ToolContext& ctx) { + json out = ctx.run_ui([&] { + return acts(args, "object_set_brim_ears") ? brim_ears_from_args(args) : + open_on(args, EType::BrimEars, {kObjects | kInstances, true, one_instance}); + }); + settle(ctx); + return ToolResult::ok(out); + })); + brim.examples = json::parse(R"json([ + {"title": "Two ears at the front corners of object 0", "calls": [ + {"tool": "object_set_brim_ears", "args": {"object": 0, "points": [{"position": [90, 90], "radius": 3}, {"position": [110, 90]}]}}, + {"tool": "settings_set", "args": {"target": "object", "object": 0, "values": {"brim_type": "painted"}}}]}, + {"title": "Remove object 1's ears", "calls": [{"tool": "object_set_brim_ears", "args": {"object": 1, "clear": true}}]}])json"); + catalog.add(reaching({"open_gizmo", "set_brim_ears"}, std::move(brim))); } }}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpToolsScene.cpp b/src/slic3r/GUI/Mcp/McpToolsScene.cpp index 4afae80b58..778039f633 100644 --- a/src/slic3r/GUI/Mcp/McpToolsScene.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsScene.cpp @@ -1695,23 +1695,37 @@ void register_object_menu_commands(CommandCatalog& catalog) return MenuItems::add_handy(std::size_t(it - all.begin())); })); + // What a text or an SVG takes beyond the action's form: the object it becomes a part of, and the part's type. + const auto part_props = [](std::initializer_list own) { + json schema = object_schema(own); + schema["properties"]["type"] = enum_prop({"part", "negative", "modifier"}, + "The part's type, as the object's Add menu offers it. Default part. Without " + "object, on the selected object."); + return with_targets(std::move(schema), kObjects, true); + }; const std::string text = "Add a text: a part on the selected object, or a new object when nothing is selected. It is created " "in the background (app_wait {for: \"idle\"} waits for it), and the Text gizmo opens on it."; - catalog.add(menu_command("object_add_text", L("Text"), text, object_schema({}), - json::array({action("add_primitive_text", L("Text"), L("Add Primitive"), "menu_obj_text", json::object(), - text)}), - [](const json&) { return MenuItems::add_primitive_text(); })); + catalog.add(with_expected_ids(menu_command( + "object_add_text", L("Text"), + text + " With object, the text becomes a part of that object, which is selected first; type makes it a negative part " + "or a modifier, as the object's Add menu does.", + part_props({}), + json::array({action("add_primitive_text", L("Text"), L("Add Primitive"), "menu_obj_text", json::object(), text)}), + [](const json& args) { return MenuItems::add_primitive_text(args); }))); - catalog.add(menu_command( + catalog.add(with_expected_ids(menu_command( "object_add_svg", L("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 (app_wait {for: \"idle\"} waits for it), and the SVG gizmo opens on it.", - object_schema({{"path", MenuItems::input_file("an .svg file")}}), + "part is created in the background (app_wait {for: \"idle\"} waits for it), and the SVG gizmo opens on it. With " + "object, the SVG becomes a part of that object, which is selected first; type makes it a negative part or a modifier, " + "as the object's Add menu does. Without path the file dialog opens, as the action's does, and the object and type " + "apply to the file picked there.", + part_props({{"path", MenuItems::input_file("an .svg file")}}), json::array({action("add_primitive_svg", L("SVG"), L("Add Primitive"), "menu_obj_svg", json::object(), "Add an SVG as a new object, or as a part of the selected object, from the file a dialog asks for; " "object_add_svg with a path uses that file without one. The part is created in the background " "(app_wait {for: \"idle\"} waits for it), and the SVG gizmo opens on it.")}), - [](const json& args) { return MenuItems::add_primitive_svg(args); })); + [](const json& args) { return MenuItems::add_primitive_svg(args); }))); // ---- Object ---- (the object's context menu and the Edit menu) NativeCommand del = menu_command( diff --git a/src/slic3r/GUI/NativeCommandMenuItems.hpp b/src/slic3r/GUI/NativeCommandMenuItems.hpp index 33ddc1977f..b2c0fcc01f 100644 --- a/src/slic3r/GUI/NativeCommandMenuItems.hpp +++ b/src/slic3r/GUI/NativeCommandMenuItems.hpp @@ -42,9 +42,12 @@ AppActionRunResult export_toolpaths_obj(); // ---- Objects and parts ---- // Handy model `index` of MenuFactory::handy_models(). AppActionRunResult add_handy(std::size_t index); -AppActionRunResult add_primitive_text(); -// An SVG as a new object, or a part of the selected object: with no arguments from the file a dialog asks for, -// else from the file `args` names ({"path"}). +// A text as a new object, or a part of the selected object; with object_add_text's arguments ({object?, object_id?, +// type?}) a part of `type` on the object named, which is selected first, or with `type` alone on the selected one. +AppActionRunResult add_primitive_text(const nlohmann::json& args); +// An SVG as a new object, or a part of the selected object, from the file a dialog asks for; with object_add_svg's +// arguments ({path?, object?, object_id?, type?}) from the file `path` names, and as a part of `type` on the object named +// or with `type` alone on the selected one, as add_primitive_text() takes them. AppActionRunResult add_primitive_svg(const nlohmann::json& args); AppActionRunResult obj_arrange(); diff --git a/src/slic3r/GUI/NativeCommands.cpp b/src/slic3r/GUI/NativeCommands.cpp index 6bbdecf553..31840602a5 100644 --- a/src/slic3r/GUI/NativeCommands.cpp +++ b/src/slic3r/GUI/NativeCommands.cpp @@ -20,6 +20,7 @@ #include "RunScriptPanel.hpp" #include "NetworkTestDialog.hpp" #include "Operations/ExportOps.hpp" +#include "Operations/ObjectOps.hpp" #include "Operations/Outcome.hpp" #include "Operations/PlateOps.hpp" #include "Operations/PluginOps.hpp" @@ -36,6 +37,7 @@ #include "Mcp/McpPaths.hpp" #include "Mcp/McpPersonContext.hpp" #include "Mcp/McpRecorder.hpp" +#include "Mcp/McpTargets.hpp" #include "Mcp/AutomationRuntime.hpp" #include "Mcp/McpTools.hpp" #ifdef SLIC3R_CAD @@ -524,14 +526,45 @@ AppActionRunResult MenuItems::calib(CalibKind kind) { return calib_command(kind) AppActionRunResult MenuItems::obj_arrange() { return arrange_all(wxGetApp().plater()); } // ---- Add Primitive ---- (the Add > Add Primitive submenu's Text and SVG) -AppActionRunResult MenuItems::add_primitive_text() +namespace { + +// The part type object_add_text and object_add_svg pass where the action passes ModelVolumeType::INVALID, which adds a +// part to the selected object, or a new object when nothing is selected. A call that names an object selects it first, +// as a click would, and adds a part of `type` to it (a part when left out); `type` alone adds to the selected object and +// is refused with nothing selected, since a new object has no part type. +Ops::Outcome part_type(Plater& plater, const json& args) +{ + const bool named = Mcp::names_targets(args); + if (!named && !args.contains("type")) + return ModelVolumeType::INVALID; + const std::string type = args.value("type", std::string("part")); + if (named) { + const Ops::Outcome object = Mcp::resolve_targets(plater.model(), nullptr, args, Mcp::kObjects, true); + if (!object) + return object.refusal(); + // Adding the part is the call's undo step; selecting its object is not a step of its own. + Plater::SuppressSnapshots quiet(&plater); + Ops::select_targets(object.value()); + } else if (Ops::shown_prepare_canvas().get_selection().is_empty()) + return Ops::nothing_selected(); + return type == "negative" ? ModelVolumeType::NEGATIVE_VOLUME : + type == "modifier" ? ModelVolumeType::PARAMETER_MODIFIER : + ModelVolumeType::MODEL_PART; +} + +} // namespace + +AppActionRunResult MenuItems::add_primitive_text(const json& args) { Plater* plater = wxGetApp().plater(); if (plater) { ensure_3d_view(plater); + const Ops::Outcome type = part_type(*plater, args); + if (!type) + return refused(type.refusal()); if (GLCanvas3D* canvas = plater->canvas3D()) canvas->clear_popup_menu_position(); - MenuFactory::add_text_volume(ModelVolumeType::INVALID); + MenuFactory::add_text_volume(type.value()); } return AppActionRunResult{AppActionRunResult::Level::Succeeded}; } @@ -545,8 +578,12 @@ AppActionRunResult MenuItems::add_primitive_svg(const json& args) GLCanvas3D* canvas = plater->canvas3D(); if (canvas != nullptr) canvas->clear_popup_menu_position(); - if (Mcp::person_form(args)) { - MenuFactory::add_svg_volume(ModelVolumeType::INVALID); + const Ops::Outcome type = part_type(*plater, args); + if (!type) + return refused(type.refusal()); + // Without a path the file dialog asks for the file, as the action does; the object and type named still apply. + if (!args.contains("path")) { + MenuFactory::add_svg_volume(type.value()); return AppActionRunResult{AppActionRunResult::Level::Succeeded}; } // What the dialog path does once a file is picked: a new object with nothing selected, else @@ -556,7 +593,8 @@ AppActionRunResult MenuItems::add_primitive_svg(const json& args) if (!path) return fail; auto* svg = canvas != nullptr ? dynamic_cast(canvas->get_gizmos_manager().get_gizmo(GLGizmosManager::Svg)) : nullptr; - if (svg == nullptr || !svg->create_volume(into_u8(from_path(*path)), ModelVolumeType::MODEL_PART)) + const ModelVolumeType volume_type = type.value() == ModelVolumeType::INVALID ? ModelVolumeType::MODEL_PART : type.value(); + if (svg == nullptr || !svg->create_volume(into_u8(from_path(*path)), volume_type)) return AppActionRunResult{AppActionRunResult::Level::Error, _L("The SVG file could not be added.")}; return AppActionRunResult{AppActionRunResult::Level::Succeeded}; } diff --git a/src/slic3r/GUI/Operations/GizmoOps.cpp b/src/slic3r/GUI/Operations/GizmoOps.cpp index a9dd8091c8..1944f0366a 100644 --- a/src/slic3r/GUI/Operations/GizmoOps.cpp +++ b/src/slic3r/GUI/Operations/GizmoOps.cpp @@ -5,19 +5,24 @@ #include "PlateOps.hpp" #include "slic3r/GUI/3DScene.hpp" +#include "slic3r/GUI/Event.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/GUI_App.hpp" #include "slic3r/GUI/GUI_ObjectList.hpp" #include "slic3r/GUI/Gizmos/GLGizmoBase.hpp" +#include "slic3r/GUI/Gizmos/GLGizmoBrimEars.hpp" #include "slic3r/GUI/Gizmos/GLGizmoCut.hpp" #include "slic3r/GUI/Gizmos/GLGizmosManager.hpp" +#include "slic3r/GUI/Gizmos/GizmoObjectManipulation.hpp" #include "slic3r/GUI/I18N.hpp" #include "slic3r/GUI/Plater.hpp" #include "slic3r/GUI/Selection.hpp" #include "libslic3r/AppConfig.hpp" +#include "libslic3r/BrimEarsPoint.hpp" #include "libslic3r/CutUtils.hpp" #include "libslic3r/Geometry.hpp" +#include "libslic3r/LocalesUtils.hpp" #include "libslic3r/Model.hpp" #include "libslic3r/ObjectID.hpp" #include "libslic3r/Point.hpp" @@ -190,6 +195,21 @@ bool plane_misses(const ModelObject& object, int instance, const Vec3d& point, c return true; } +// Why `object` and `instance` name no instance of the model, or none. The command layer has checked them +// (Mcp::resolve_targets()); an operation checks again for its other callers. +std::optional no_such_instance(const Model& model, int object, int instance) +{ + if (object < 0 || std::size_t(object) >= model.objects.size()) + // TRN %1% is the object index asked for, %2% the index of the project's last object. + return Refusal{RefusalKind::Precondition, "no_such_object", L("Object %1% does not exist (the project has objects 0..%2%)"), + {std::to_string(object), std::to_string(int(model.objects.size()) - 1)}}; + const ModelObject& named = *model.objects[std::size_t(object)]; + if (instance < 0 || std::size_t(instance) >= named.instances.size()) + // TRN %1% is an object's name, %2% an instance's index. + return Refusal{RefusalKind::Precondition, "no_such_instance", L("\"%1%\" has no instance %2%."), {named.name, std::to_string(instance)}}; + return std::nullopt; +} + } // namespace std::optional gizmo_refusal(GLGizmosManager::EType type, const GizmoFacts& facts, bool activable) @@ -338,15 +358,9 @@ Outcome cut_object(const CutObjectArgs& args) assert(wxThread::IsMain()); Plater& plater = *wxGetApp().plater(); Model& model = plater.model(); - if (args.object < 0 || std::size_t(args.object) >= model.objects.size()) - // TRN %1% is the object index asked for, %2% the index of the project's last object. - return Refusal{RefusalKind::Precondition, "no_such_object", L("Object %1% does not exist (the project has objects 0..%2%)"), - {std::to_string(args.object), std::to_string(int(model.objects.size()) - 1)}}; + if (std::optional missing = no_such_instance(model, args.object, args.instance)) + return *missing; ModelObject* object = model.objects[std::size_t(args.object)]; - if (args.instance < 0 || std::size_t(args.instance) >= object->instances.size()) - // TRN %1% is an object's name, %2% an instance's index. - return Refusal{RefusalKind::Precondition, "no_such_instance", L("\"%1%\" has no instance %2%."), - {object->name, std::to_string(args.instance)}}; if (std::optional refused = cut_refusal(*object, args.instance, args.point, args.normal)) return *refused; @@ -382,4 +396,102 @@ Outcome cut_object(const CutObjectArgs& args) return out; } +Vec3d flatten_normal(const ModelInstance& instance, const Vec3d& normal, bool world) +{ + if (!world) + return normal.normalized(); + return (instance.get_matrix_no_offset().linear().transpose() * normal).normalized(); +} + +Outcome lay_on_face(const LayOnFaceArgs& args) +{ + assert(wxThread::IsMain()); + Plater& plater = *wxGetApp().plater(); + Model& model = plater.model(); + if (std::optional missing = no_such_instance(model, args.object, args.instance)) + return *missing; + if (args.normal.norm() < EPSILON) + return refusal("zero_normal", L("The normal is zero: give the direction the face to lay on the bed points to.")); + const ModelInstance& instance = *model.objects[std::size_t(args.object)]->instances[std::size_t(args.instance)]; + const Vec3d normal = flatten_normal(instance, args.normal, args.world); + + close_open_gizmo(); + GLCanvas3D& canvas = shown_prepare_canvas(); + { + // The turn is the call's undo step; selecting the instance to turn is not a step of its own. + Plater::SuppressSnapshots quiet(&plater); + Targets one; + one.instances = {{args.object, args.instance}}; + select_targets(one); + } + // What a click on a face of the Flatten gizmo does (GLGizmoFlatten::on_mouse()), once the click that selected the + // instance has set up the selection's cache. + Selection& sel = canvas.get_selection(); + sel.setup_cache(); + sel.flattening_rotate(normal); + canvas.do_rotate(L("Gizmo-Place on Face")); + wxGetApp().obj_manipul()->set_dirty(); + return instance.get_rotation(); +} + +Outcome> brim_points_from_bed(const ModelObject& object, int instance, const std::vector& ears, + float default_radius) +{ + const Transform3d to_object = object.instances[std::size_t(instance)]->get_matrix().inverse(); + std::vector points; + points.reserve(ears.size()); + for (const BrimEar& ear : ears) { + const float radius = ear.radius.value_or(default_radius); + if (radius < BRIM_EAR_RADIUS_MIN || radius > BRIM_EAR_RADIUS_MAX) { + const std::string low = float_to_string_decimal_point(BRIM_EAR_RADIUS_MIN); + const std::string high = float_to_string_decimal_point(BRIM_EAR_RADIUS_MAX); + // TRN %1% and %2% are the smallest and the largest radius of a brim ear, in mm. + return Refusal{RefusalKind::Precondition, "radius_out_of_range", L("A brim ear's radius is from %1% to %2% mm."), + {low, high}, {low, high}}; + } + // Where Auto-generate puts an ear for a point of the bed: just under the bed, in the object's coordinates. + const Vec3d on_object = to_object * Vec3d(ear.position.x(), ear.position.y(), -0.0001); + points.emplace_back(on_object.cast(), radius); + } + return points; +} + +Outcome set_brim_ears(const SetBrimEarsArgs& args) +{ + assert(wxThread::IsMain()); + Plater& plater = *wxGetApp().plater(); + Model& model = plater.model(); + if (std::optional missing = no_such_instance(model, args.object, args.instance)) + return *missing; + GLCanvas3D& canvas = *plater.get_view3D_canvas3D(); + GLGizmoBrimEars* brim_ears = dynamic_cast(canvas.get_gizmos_manager().get_gizmo(GLGizmosManager::BrimEars)); + if (brim_ears == nullptr) + return Refusal{RefusalKind::Failed, "no_brim_ears_gizmo", L("The Brim Ears gizmo is not available.")}; + ModelObject& object = *model.objects[std::size_t(args.object)]; + const Outcome> points = brim_points_from_bed(object, args.instance, args.ears, + brim_ears->get_brim_default_radius()); + if (!points) + return points.refusal(); + + close_open_gizmo(); + { + Plater::TakeSnapshot snapshot(&plater, _u8L("Set brim ears")); + object.brim_points = points.value(); + // What GLGizmoBrimEars::update_model_object() does after it writes the ears. + plater.set_plater_dirty(true); + canvas.post_event(SimpleEvent(EVT_GLCANVAS_SCHEDULE_BACKGROUND_PROCESS)); + } + // The closed gizmo still holds the ears it had; its next opening reloads them from the object instead. + brim_ears->reload_on_next_opening(); + + BrimEarsSet out; + out.ears = object.brim_points; + out.brim_type = object.config.has("brim_type") ? + object.config.get().opt_serialize("brim_type") : + wxGetApp().preset_bundle->prints.get_edited_preset().config.opt_serialize("brim_type"); + // Brim ears print only with the painted brim type; the others ignore them. + out.takes_effect = out.brim_type == "painted"; + return out; +} + }}} // namespace Slic3r::GUI::Ops diff --git a/src/slic3r/GUI/Operations/GizmoOps.hpp b/src/slic3r/GUI/Operations/GizmoOps.hpp index 76e4a17556..b575cf4c8f 100644 --- a/src/slic3r/GUI/Operations/GizmoOps.hpp +++ b/src/slic3r/GUI/Operations/GizmoOps.hpp @@ -5,15 +5,19 @@ #include "slic3r/GUI/Gizmos/GLGizmosManager.hpp" +#include "libslic3r/BrimEarsPoint.hpp" #include "libslic3r/Point.hpp" #include "libslic3r/enum_bitmask.hpp" #include +#include +#include // Declared rather than included, as the other operation headers declare them: Model.hpp reaches OCCT, which switches // parts of windows.h off (NOUSER, NOGDI) for whatever includes windows.h after it, as wx does in a file built without // the precompiled header, such as a unit test. namespace Slic3r { +class ModelInstance; class ModelObject; enum class ModelObjectCutAttribute : int; // CutUtils.hpp } // namespace Slic3r @@ -22,7 +26,8 @@ enum class ModelObjectCutAttribute : int; // CutUtils.hpp // object_measure, object_simplify, part_boolean, and the openings of the commands that also act from arguments) share. // No gizmo behaves differently for being opened here: the operation selects as a click on the model would, asks the gizmo // whether it can open, and opens it as its toolbar icon does. The jobs a gizmo command does from arguments with no gizmo -// (object_cut's cut by a plane) are here too, each doing what the gizmo's own button does, through the same functions. +// (object_cut's cut by a plane, object_lay_on_face's turn, object_set_brim_ears's ears) are here too, each doing what the +// gizmo's own button or click does, through the same functions. namespace Slic3r { namespace GUI { namespace Ops { struct OpenGizmoArgs @@ -106,4 +111,60 @@ Transform3d cut_matrix(const ModelObject& object, int instance, const Vec3d& poi // to_parts the one object and its parts. UI thread. Outcome cut_object(const CutObjectArgs& args); +// ---- Lay on face from a direction, as a click on a face of the Flatten gizmo does it ---- + +// What Selection::flattening_rotate() takes for the face to lay down: `normal` in the object's frame, normalized, or with +// `world` a direction in the 3D view brought into the object's frame. flattening_rotate() turns its normal into the view by +// the inverse transpose of the instance's matrix without its offset, M, so a view direction w is Mᵀw there, which holds +// for an instance scaled unevenly or mirrored. Pure. +Vec3d flatten_normal(const ModelInstance& instance, const Vec3d& normal, bool world); + +struct LayOnFaceArgs +{ + int object = 0, instance = 0; + Vec3d normal = -Vec3d::UnitZ(); // the outward normal of the face to lay on the bed + bool world = false; // normal is in the 3D view's frame, else in the object's +}; + +// Turns the instance so that the face `normal` points out of faces the bed, as a click on that face of the Flatten gizmo +// does: the open gizmo closed, the instance selected, flattening_rotate(), then one undo step "Gizmo-Place on Face" that +// drops it onto the bed. The object's other instances turn with it; no flat face is looked for. Refuses zero_normal. +// Returns the instance's rotation afterwards, in radians. UI thread. +Outcome lay_on_face(const LayOnFaceArgs& args); + +// ---- Brim ears by position, as the Brim Ears gizmo places them ---- + +// An ear asked for on the bed: where, and its radius in mm, else the gizmo's default. +struct BrimEar +{ + Vec2d position = Vec2d::Zero(); + std::optional radius; +}; + +// The ears as the Brim Ears gizmo stores them: each bed position at z -0.0001 brought through the inverse of the +// instance's transformation into the object's coordinates, as Auto-generate places one, and a radius left out +// `default_radius`. Refuses radius_out_of_range for a radius outside BRIM_EAR_RADIUS_MIN to BRIM_EAR_RADIUS_MAX +// (GLGizmoBrimEars.hpp), which the gizmo's slider cannot set. Pure. +Outcome> brim_points_from_bed(const ModelObject& object, int instance, const std::vector& ears, + float default_radius); + +struct SetBrimEarsArgs +{ + int object = 0, instance = 0; + std::vector ears; // none: the object's ears are cleared +}; + +struct BrimEarsSet +{ + std::vector ears; // the object's ears as stored, read back after the write + std::string brim_type; // the brim type the object prints with: its own, else the process's + bool takes_effect = false; // whether that type is painted, the one brim type that prints the ears +}; + +// Replaces the object's brim ears, which its instances share. The ears are converted and checked first, so that a +// refused call leaves an open gizmo open: the Brim Ears gizmo writes its own ears to the object as it closes. Then the +// open gizmo is closed, one undo step "Set brim ears" taken, the ears written as the gizmo writes them, and the gizmo +// told to reload them when it next opens (GLGizmoBrimEars::reload_on_next_opening()). UI thread. +Outcome set_brim_ears(const SetBrimEarsArgs& args); + }}} // namespace Slic3r::GUI::Ops diff --git a/tests/data/command_catalog.json b/tests/data/command_catalog.json index 2f6e0126b9..fa5d1ddd43 100644 --- a/tests/data/command_catalog.json +++ b/tests/data/command_catalog.json @@ -1838,7 +1838,7 @@ } ], "completion": "immediate", - "description": "Add a text: a part on the selected object, or a new object when nothing is selected. It is created in the background (app_wait {for: \"idle\"} waits for it), and the Text gizmo opens on it.", + "description": "Add a text: a part on the selected object, or a new object when nothing is selected. It is created in the background (app_wait {for: \"idle\"} waits for it), and the Text gizmo opens on it. With object, the text becomes a part of that object, which is selected first; type makes it a negative part or a modifier, as the object's Add menu does.", "destructive": false, "group": "Objects", "guard": "mutate", @@ -1846,7 +1846,27 @@ "idempotent": false, "input_schema": { "additionalProperties": false, - "properties": {}, + "properties": { + "object": { + "description": "Object index (object_list).", + "minimum": 0, + "type": "integer" + }, + "object_id": { + "description": "The id object_list reports for this object: the call is refused when the index names another one now.", + "minimum": 0, + "type": "integer" + }, + "type": { + "description": "The part's type, as the object's Add menu offers it. Default part. Without object, on the selected object.", + "enum": [ + "part", + "negative", + "modifier" + ], + "type": "string" + } + }, "type": "object" }, "key": "object_add_text", @@ -1868,7 +1888,7 @@ } ], "completion": "immediate", - "description": "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 (app_wait {for: \"idle\"} waits for it), and the SVG gizmo opens on it.", + "description": "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 (app_wait {for: \"idle\"} waits for it), and the SVG gizmo opens on it. With object, the SVG becomes a part of that object, which is selected first; type makes it a negative part or a modifier, as the object's Add menu does. Without path the file dialog opens, as the action's does, and the object and type apply to the file picked there.", "destructive": false, "group": "Objects", "guard": "mutate", @@ -1877,9 +1897,28 @@ "input_schema": { "additionalProperties": false, "properties": { + "object": { + "description": "Object index (object_list).", + "minimum": 0, + "type": "integer" + }, + "object_id": { + "description": "The id object_list reports for this object: the call is refused when the index names another one now.", + "minimum": 0, + "type": "integer" + }, "path": { "description": "Absolute path of an .svg file.", "type": "string" + }, + "type": { + "description": "The part's type, as the object's Add menu offers it. Default part. Without object, on the selected object.", + "enum": [ + "part", + "negative", + "modifier" + ], + "type": "string" } }, "type": "object" @@ -3595,6 +3634,215 @@ "read_only": false, "title": "Cut" }, + { + "completion": "immediate", + "description": "Lay an object's instance, the first unless instance is given, on one of its faces, as a click on that face in the Lay on Face gizmo does. Acts from arguments: normal, frame. With none of them it opens the Lay on Face gizmo. normal is the direction the face points out to: in the object's own frame (frame object, the default, where [0, 0, -1] is the face that was its bottom) or in the 3D view's (frame world, where the face points now). The instance turns so that face lies on the bed and drops onto it, one undo step; the object's other instances turn with it. No flat face is looked for: the direction is laid down as given. A call that acts replies object, instance and rotation, the instance's rotation in degrees as object_list gives it. Read the gizmo's panel with widget_list {include_imgui: true}, set its fields with widget_set_value, press its buttons with widget_click, and click or drag on the model with mouse_gesture; object_select {none: true} closes it. The gizmo already open on the same target stays open. Reply: gizmo (its name, as app_state.gizmo gives it), active, and what is selected (objects, instances, parts).", + "destructive": false, + "examples": [ + { + "calls": [ + { + "args": { + "normal": [ + 0, + 0, + -1 + ], + "object": 0 + }, + "tool": "object_lay_on_face" + } + ], + "title": "Lay object 0 on the face that points down in its own frame" + }, + { + "calls": [ + { + "args": { + "frame": "world", + "normal": [ + 1, + 0, + 0 + ], + "object": 0 + }, + "tool": "object_lay_on_face" + } + ], + "title": "Lay object 0 on the face that now points to +X" + } + ], + "group": "Objects", + "guard": "mutate", + "has_own_action": false, + "idempotent": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "frame": { + "description": "The frame normal is in: the object's own (default) or the 3D view's. Needs normal.", + "enum": [ + "object", + "world" + ], + "type": "string" + }, + "instance": { + "description": "An instance of the object (object_list).", + "minimum": 0, + "type": "integer" + }, + "normal": { + "description": "[x, y, z]: the direction the face to lay on the bed points out to; any length but zero.", + "items": { + "type": "number" + }, + "type": "array" + }, + "object": { + "description": "Object index (object_list).", + "minimum": 0, + "type": "integer" + }, + "object_id": { + "description": "The id object_list reports for this object: the call is refused when the index names another one now.", + "minimum": 0, + "type": "integer" + } + }, + "type": "object" + }, + "key": "object_lay_on_face", + "listed": true, + "open_world": false, + "operations": [ + "open_gizmo", + "lay_on_face" + ], + "read_only": false, + "title": "Lay on face" + }, + { + "completion": "immediate", + "description": "Set an object's brim ears from positions on the bed, as the Brim Ears gizmo places them, through the instance named, the first unless instance is given. Acts from arguments: points, clear. With none of them it opens the Brim Ears gizmo. points replaces the object's ears with those given, each at a bed position, with a radius from 0.1 to 100 mm or the gizmo's default; clear removes them all. The ears are taken on the bed and stored in the object's coordinates, so they are the object's, shared by its instances. One undo step. They print only with the painted brim type: settings_set on the object sets brim_type. A call that acts replies object, ears as stored ({position: [x, y, z] in the object's coordinates, radius}), brim_type, the brim type the object prints with, and takes_effect, whether that is painted. Read the gizmo's panel with widget_list {include_imgui: true}, set its fields with widget_set_value, press its buttons with widget_click, and click or drag on the model with mouse_gesture; object_select {none: true} closes it. The gizmo already open on the same target stays open. Reply: gizmo (its name, as app_state.gizmo gives it), active, and what is selected (objects, instances, parts).", + "destructive": false, + "examples": [ + { + "calls": [ + { + "args": { + "object": 0, + "points": [ + { + "position": [ + 90, + 90 + ], + "radius": 3 + }, + { + "position": [ + 110, + 90 + ] + } + ] + }, + "tool": "object_set_brim_ears" + }, + { + "args": { + "object": 0, + "target": "object", + "values": { + "brim_type": "painted" + } + }, + "tool": "settings_set" + } + ], + "title": "Two ears at the front corners of object 0" + }, + { + "calls": [ + { + "args": { + "clear": true, + "object": 1 + }, + "tool": "object_set_brim_ears" + } + ], + "title": "Remove object 1's ears" + } + ], + "group": "Objects", + "guard": "mutate", + "has_own_action": false, + "idempotent": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "clear": { + "description": "Remove every ear. Not with points.", + "enum": [ + true + ], + "type": "boolean" + }, + "instance": { + "description": "An instance of the object (object_list).", + "minimum": 0, + "type": "integer" + }, + "object": { + "description": "Object index (object_list).", + "minimum": 0, + "type": "integer" + }, + "object_id": { + "description": "The id object_list reports for this object: the call is refused when the index names another one now.", + "minimum": 0, + "type": "integer" + }, + "points": { + "description": "The ears, in place of the object's.", + "items": { + "additionalProperties": false, + "properties": { + "position": { + "description": "[x, y] mm: where on the bed.", + "items": { + "type": "number" + }, + "type": "array" + }, + "radius": { + "description": "mm. Default: the gizmo's, eight first-layer line widths.", + "type": "number" + } + }, + "required": [ + "position" + ], + "type": "object" + }, + "type": "array" + } + }, + "type": "object" + }, + "key": "object_set_brim_ears", + "listed": true, + "open_world": false, + "operations": [ + "open_gizmo", + "set_brim_ears" + ], + "read_only": false, + "title": "Brim ears" + }, { "completion": "immediate", "description": "Replace an object's height range modifiers (Height Range Modifier in the object list): Z ranges in mm, each printed with its own layer_height, filament and process settings, which settings_get and settings_set read and write with the target height_range. A range given with the min_z and max_z of one the object has keeps its settings; a new one starts from the object's layer height and filament. Ranges may touch but not overlap; [] removes them all. The object is the one named, else the one selected in the Prepare view. One undo step; the object is selected. Reply: the object (objects, object), its height and its ranges as object_list shows them, with their settings, and warnings, such as a variable layer height profile deciding the layer heights instead.", diff --git a/tests/slic3rutils/test_command_catalog.cpp b/tests/slic3rutils/test_command_catalog.cpp index bb5b402f09..167ec64a9f 100644 --- a/tests/slic3rutils/test_command_catalog.cpp +++ b/tests/slic3rutils/test_command_catalog.cpp @@ -143,12 +143,12 @@ std::string first_difference(const std::string& actual, const std::string& expec } // The design's command set outside the Design tab, heading by heading in the order tools/list gives them, Driving the -// GUI last, after the Design tab's commands: the 123 commands of the catalog, its typed tools, the commands made from +// GUI last, after the Design tab's commands: the 125 commands of the catalog, its typed tools, the commands made from // menu items, the seven Parts 4a to 4c add (Printable, Fix Model, Auto Drop, Clone, Reload from disk, Replace 3D file, // Add Mixed Filament), the three of Part 5a (the Printer Selection dialog's list, install and uninstall), the two of // Part 5b (the System Filaments dialog's install and uninstall), Part 5c's write of the Preferences dialog's preferences -// and the four of Part 5d (the Plugins window's list, a switch, Delete or Unsubscribe, and Reload), and the five gizmo -// commands (Paint, Measure, Simplify, Mesh Boolean and Cut). +// and the four of Part 5d (the Plugins window's list, a switch, Delete or Unsubscribe, and Reload), and the seven gizmo +// commands (Paint, Measure, Simplify, Mesh Boolean, Cut, Lay on Face and Brim Ears). // A part that adds a command adds it here. const std::vector>> kPlaces{ {"Tools and actions", {"tool_search", "tool_call", "action_search", "action_run"}}, @@ -162,7 +162,8 @@ const std::vector>> kPlaces{ "object_delete", "object_rename", "object_set_instances", "object_separate_instances", "object_split", "object_assemble", "object_order", "object_transform", "object_drop", "object_mirror", "object_center", "object_scale_to_fit", "object_arrange", "object_auto_orient", "object_set_variable_layer_height", "object_set_height_ranges", "object_set_printable", "object_fix", - "object_set_auto_drop", "object_clone", "object_reload_from_disk", "object_paint", "object_measure", "object_simplify", "object_cut"}}, + "object_set_auto_drop", "object_clone", "object_reload_from_disk", "object_paint", "object_measure", "object_simplify", "object_cut", + "object_lay_on_face", "object_set_brim_ears"}}, {"Parts", {"part_add", "part_change_type", "part_replace", "part_boolean"}}, {"Plates", {"plate_list", "plate_get_settings", "plate_set_settings", "plate_add", "plate_delete", "plate_duplicate", "plate_rename", @@ -448,8 +449,8 @@ TEST_CASE("outside the Design tab the catalog has its commands and 129 actions", CHECK(c.action_group == section.at(c.key)); } // The commands outside the Design tab: the typed tools, the commands made from menu items, the seven Parts 4a to 4c - // add, Part 5a's three, Part 5b's two, Part 5c's one, Part 5d's four and the five gizmo commands. - CHECK(commands == 123); + // add, Part 5a's three, Part 5b's two, Part 5c's one, Part 5d's four and the seven gizmo commands. + CHECK(commands == 125); // The eight commands named as their menu items keep an action of their own; the other 121 actions are items. CHECK(own == std::set{"plate_add", "plate_delete", "plate_duplicate", "plate_rename", "filament_add", "filament_delete", "undo", "redo"}); @@ -476,7 +477,7 @@ TEST_CASE("the commands outside the Design tab are the design's, under its headi commands += keys.size(); } CHECK(by_heading.size() == kPlaces.size()); - CHECK(commands == 123); + CHECK(commands == 125); // tool_search's group says which there are. const NativeCommand* search = NativeCommands::find("tool_search"); @@ -517,8 +518,8 @@ TEST_CASE("every command that runs from arguments is in the tool list, by place" // The three menu items with no argument form, which tool_search finds and tool_call runs. CHECK(unlisted == std::set{"window_save_screenshot", "script_toggle_panel", "settings_toggle_developer_mode"}); // Task 3's 98, the seven Parts 4a to 4c add, Part 5a's three, Part 5b's two, Part 5c's one, Part 5d's four and the - // five gizmo commands. - CHECK(listed.size() == 120); + // seven gizmo commands. + CHECK(listed.size() == 122); // The search, the generic call and the app's state first; then each heading's commands together, in the // design's order, Driving the GUI last. diff --git a/tests/slic3rutils/test_mcp_scene.cpp b/tests/slic3rutils/test_mcp_scene.cpp index 2c2283d50e..5666a28180 100644 --- a/tests/slic3rutils/test_mcp_scene.cpp +++ b/tests/slic3rutils/test_mcp_scene.cpp @@ -27,6 +27,7 @@ #include #include +#include "slic3r/GUI/CommandCatalog.hpp" #include "slic3r/GUI/CommandTypes.hpp" #include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/GUI_ObjectList.hpp" @@ -1701,7 +1702,8 @@ TEST_CASE("layer G-codes are edited on the layer slider as its menus edit them", // The gizmo commands, each with the place its name gives it. const std::vector> kGizmoCommands{ - {"object_paint", "Objects"}, {"object_measure", "Objects"}, {"object_simplify", "Objects"}, {"part_boolean", "Parts"}, {"object_cut", "Objects"}}; + {"object_paint", "Objects"}, {"object_measure", "Objects"}, {"object_simplify", "Objects"}, {"part_boolean", "Parts"}, {"object_cut", "Objects"}, + {"object_lay_on_face", "Objects"}, {"object_set_brim_ears", "Objects"}}; TEST_CASE("the gizmo commands are listed under their places and take no silent", "[Mcp][Gizmos]") { @@ -1755,3 +1757,26 @@ TEST_CASE("a gizmo command's acting arguments are schema properties its descript // A command that is not a gizmo command has none. CHECK(Mcp::gizmo_acting_args("object_list").empty()); } + +TEST_CASE("text and SVG take the object they become a part of and the part's type, and their actions stay as they were", + "[Mcp][Gizmos]") +{ + for (const auto& [key, action_id] : std::vector>{{"object_add_text", "add_primitive_text"}, + {"object_add_svg", "add_primitive_svg"}}) { + INFO(key); + const NativeCommand* command = NativeCommands::find(key); + REQUIRE(command != nullptr); + const json& properties = command->input_schema.at("properties"); + CHECK(properties.contains("object")); + CHECK(properties.contains("object_id")); + CHECK(properties.at("type").at("enum") == json::array({"part", "negative", "modifier"})); + // An object's id is checked against its index, and left out of the journal. + CHECK(std::find(command->id_args.begin(), command->id_args.end(), "object_id") != command->id_args.end()); + // The Speed Dial's action is the menu item as it was: it takes no arguments. + const auto [owner, action] = Slic3r::GUI::find_command_action(NativeCommands::instance(), action_id); + CHECK(owner == command); + REQUIRE(action != nullptr); + CHECK(action->at("args") == json::object()); + } + CHECK(NativeCommands::find("object_add_svg")->input_schema.at("properties").contains("path")); +} diff --git a/tests/slic3rutils/test_mcp_tools.cpp b/tests/slic3rutils/test_mcp_tools.cpp index 508c5cfb42..3a350a931d 100644 --- a/tests/slic3rutils/test_mcp_tools.cpp +++ b/tests/slic3rutils/test_mcp_tools.cpp @@ -650,14 +650,14 @@ TEST_CASE("a tool of the old vocabulary is no command", "[Mcp]") CHECK(first_sentence(command->description) == r.first_sentence); } - // Outside the Design group 120 commands are listed: every one that runs from its arguments, all but the three menu + // Outside the Design group 122 commands are listed: every one that runs from its arguments, all but the three menu // items that take none (Task 3's 98, the seven Parts 4a to 4c add, Part 5a's three, Part 5b's two, Part 5c's one, - // Part 5d's four and the five gizmo commands). + // Part 5d's four and the seven gizmo commands). std::size_t listed = 0; for (const NativeCommand& c : catalog.commands()) if (c.listed && c.group != Slic3r::GUI::kDesignGroup) ++listed; - CHECK(listed == 120); + CHECK(listed == 122); } TEST_CASE("opening a project and importing models are two commands", "[Mcp]") diff --git a/tests/slic3rutils/test_operations.cpp b/tests/slic3rutils/test_operations.cpp index 37a5fa5487..f5f834a421 100644 --- a/tests/slic3rutils/test_operations.cpp +++ b/tests/slic3rutils/test_operations.cpp @@ -23,7 +23,9 @@ #include "slic3r/plugin/PluginDescriptor.hpp" #include "libslic3r/AppConfig.hpp" +#include "libslic3r/BrimEarsPoint.hpp" #include "libslic3r/CutUtils.hpp" +#include "libslic3r/Geometry.hpp" #include "libslic3r/Model.hpp" #include "libslic3r/Point.hpp" #include "libslic3r/TextConfiguration.hpp" @@ -35,6 +37,7 @@ #include #include +#include #include #include #include @@ -2052,6 +2055,7 @@ const std::set kOperations = { "printer_models", "install_printers", "uninstall_printers", "install_filaments", "uninstall_filaments", "set_preferences", "set_plugin_enabled", "uninstall_plugin", "reload_plugin", "start_plugin_refresh", "reorder_objects", "sync_filaments_from_ams", "open_gizmo", "cut_object", + "lay_on_face", "set_brim_ears", }; // What an exception is, so that the reason reads the same for every entry of a kind. @@ -2428,3 +2432,87 @@ TEST_CASE("a cut's matrix places the plane as the Cut gizmo places it", "[Operat same(down.linear() * Slic3r::Vec3d::UnitX(), Slic3r::Vec3d::UnitX()); CHECK_THAT(down.linear().determinant(), WithinAbs(1., 1e-12)); } + + +TEST_CASE("a direction in the 3D view becomes the normal flattening_rotate() takes", "[Operations][Gizmos]") +{ + // flattening_rotate() turns its normal into the 3D view by the inverse transpose of the instance's matrix without its + // offset; the normal of a view direction must come back to that direction there. + const auto in_view = [](const Slic3r::ModelInstance& instance, const Slic3r::Vec3d& normal) { + return (instance.get_matrix_no_offset().linear().inverse().transpose() * normal).normalized().eval(); + }; + const auto same = [](const Slic3r::Vec3d& got, const Slic3r::Vec3d& want) { + INFO("got " << got.transpose() << ", expected " << want.transpose()); + CHECK((got - want).norm() < 1e-9); + }; + Slic3r::Model model; + + // Turned 30 degrees about X: the face that was its bottom points along (0, 0.5, -0.866) in the view. + Slic3r::ModelInstance& turned = *placed_cube(model)->instances.front(); + turned.set_rotation(Slic3r::Vec3d(Slic3r::Geometry::deg2rad(30.), 0., 0.)); + const Slic3r::Vec3d bottom_in_view(0., 0.5, -std::sqrt(3.) / 2.); + same(flatten_normal(turned, bottom_in_view, true), -Slic3r::Vec3d::UnitZ()); + same(in_view(turned, -Slic3r::Vec3d::UnitZ()), bottom_in_view); + + // In the object's own frame the normal is taken as given, of any length. + same(flatten_normal(turned, Slic3r::Vec3d(0., 0., -2.), false), -Slic3r::Vec3d::UnitZ()); + + // Scaled unevenly and turned, and mirrored: a view direction comes back to itself, though the object's normal is + // not the view direction turned back. + Slic3r::ModelInstance& scaled = *placed_cube(model)->instances.front(); + scaled.set_rotation(Slic3r::Vec3d(Slic3r::Geometry::deg2rad(30.), 0., Slic3r::Geometry::deg2rad(45.))); + scaled.set_scaling_factor(Slic3r::Vec3d(2., 1., 0.5)); + Slic3r::ModelInstance& mirrored = *placed_cube(model)->instances.front(); + mirrored.set_rotation(Slic3r::Vec3d(0., Slic3r::Geometry::deg2rad(20.), 0.)); + mirrored.set_mirror(Slic3r::Vec3d(-1., 1., 1.)); + for (const Slic3r::ModelInstance* instance : {&scaled, &mirrored}) + for (const Slic3r::Vec3d& direction : std::vector{Slic3r::Vec3d(1., 0., 0.), Slic3r::Vec3d(0., -1., -1.).normalized(), + Slic3r::Vec3d(0.3, 0.4, -0.866).normalized()}) + same(in_view(*instance, flatten_normal(*instance, direction, true)), direction); + const Slic3r::Vec3d along_x = flatten_normal(scaled, Slic3r::Vec3d::UnitX(), true); + CHECK((along_x - scaled.get_matrix_no_offset().linear().inverse() * Slic3r::Vec3d::UnitX()).norm() > 1e-3); +} + +TEST_CASE("brim ears asked for on the bed are stored in the object's coordinates", "[Operations][Gizmos]") +{ + using Catch::Matchers::WithinAbs; + Slic3r::Model model; + Slic3r::ModelObject& cube = *placed_cube(model); + Slic3r::ModelInstance& instance = *cube.instances.front(); + // Moved to (100, 100, 10) and turned 90 degrees about Z: a bed point 10 mm to the right of its centre is 10 mm along + // the object's -Y, and one 10 mm in front of it 10 mm along its -X; both just under the bed, 10.0001 mm below its + // centre. + instance.set_rotation(Slic3r::Vec3d(0., 0., Slic3r::Geometry::deg2rad(90.))); + std::vector ears(2); + ears[0].position = Slic3r::Vec2d(110., 100.); + ears[0].radius = 3.f; + ears[1].position = Slic3r::Vec2d(100., 90.); + const Outcome> points = brim_points_from_bed(cube, 0, ears, 4.f); + REQUIRE(points); + REQUIRE(points.value().size() == 2); + const std::vector stored{{0., -10., -10.0001}, {-10., 0., -10.0001}}; + for (std::size_t i = 0; i < 2; ++i) { + INFO(i); + CHECK((points.value()[i].pos.cast() - stored[i]).norm() < 1e-4); + } + // A radius given is kept, and one left out is the default. + CHECK_THAT(points.value()[0].head_front_radius, WithinAbs(3., 1e-6)); + CHECK_THAT(points.value()[1].head_front_radius, WithinAbs(4., 1e-6)); + + // The radius a gizmo's slider can set: from 0.1 to 100 mm. + for (const float radius : {0.1f, 100.f}) { + INFO(radius); + CHECK(brim_points_from_bed(cube, 0, {BrimEar{Slic3r::Vec2d(100., 90.), radius}}, 4.f)); + } + for (const float radius : {0.05f, 150.f}) { + INFO(radius); + const Outcome> refused = brim_points_from_bed(cube, 0, {BrimEar{Slic3r::Vec2d(100., 90.), radius}}, 4.f); + REQUIRE_FALSE(refused); + CHECK(std::string(refused.refusal().code) == "radius_out_of_range"); + CHECK(refused.refusal().names == std::vector{"0.1", "100"}); + } + // No ears clear them. + const Outcome> none = brim_points_from_bed(cube, 0, {}, 4.f); + REQUIRE(none); + CHECK(none.value().empty()); +} diff --git a/tools/mcp/test-entries/gizmos.md b/tools/mcp/test-entries/gizmos.md index ba492e4093..fc3634245e 100644 --- a/tools/mcp/test-entries/gizmos.md +++ b/tools/mcp/test-entries/gizmos.md @@ -425,7 +425,7 @@ counts a brush stroke gives, the Measure distance, the reverted font and where a are checked by a tolerance or a property, as the app works them out. ## `test_gizmo_commands` -`test_gizmo_commands.py` · Python, 277 checks · in `sweep.json` as `{"path": "test_gizmo_commands.py"}` +`test_gizmo_commands.py` · Python, 421 checks · in `sweep.json` as `{"path": "test_gizmo_commands.py"}` **Tests:** The commands that open a gizmo on a named target, and the ones among them that do the gizmo's job from arguments with no gizmo: `object_paint`, `object_measure`, `object_simplify`, `part_boolean`, `object_cut`, @@ -564,7 +564,7 @@ asked for at bed position (x, y) is stored at (x - 100, y - 100, -10.0001) in A' |---|---|---|---| | 0 | start | `brim_ears` 0; `setting(0, "brim_type")` value null, effective `auto_brim` | `settings_get` of the process's `initial_layer_line_width` "0.5" | | 1 | `object_set_brim_ears {object: 0}` | as after 0 | reply `gizmo` "Brim Ears"; `gizmo()` Brim Ears | -| 2 | `object_set_brim_ears {object: 0, points: [{position: [90, 90], radius: 3}, {position: [110, 90]}]}` | `brim_ears` 2 | `gizmo()` none; reply `ears` [(-10, -10, -10.0001) 3, (10, -10, -10.0001) 4], `brim_type` `auto_brim`, `takes_effect` false; undo steps ["Set brim ears"] | +| 2 | `object_set_brim_ears {object: 0, points: [{position: [90, 90], radius: 3}, {position: [110, 90]}]}` | `brim_ears` 2 | `gizmo()` none; reply `ears` [(-10, -10, -10.0001) 3, (10, -10, -10.0001) 4], `brim_type` `auto_brim`, `takes_effect` false; undo steps ["Brim ears edit", "Leaving Brim Ears", "Set brim ears"]: the two steps the Brim Ears gizmo records as it closes, then the call's | | 3 | `undo` | `brim_ears` 0 | | | 4 | `redo` | `brim_ears` 2 | | | 5 | `settings_set {target: "object", object: 0, values: {brim_type: "painted"}}`, then step 2's call again | `brim_ears` 2; `brim_type` `painted` from `object` | reply `ears` as in 2, `brim_type` `painted`, `takes_effect` true | @@ -572,7 +572,7 @@ asked for at bed position (x, y) is stored at (x - 100, y - 100, -10.0001) in A' | 7 | `project_new {discard_changes: true}`, `project_open` of the file | `brim_ears` 2; `brim_type` `painted` | | | 8 | `object_set_brim_ears {object: 0, clear: true}` | `brim_ears` 0 | reply `ears` [] | | 9 | `object_set_brim_ears {object: 0}`, then `object_set_brim_ears {object: 0, points: [{position: [100, 90], radius: 5}]}` | `brim_ears` 1 | after the first, `gizmo()` Brim Ears; after the second, `gizmo()` none, and after `project_save` to a new file, `brim_file()` {1: [(0, -10, -10.0001) 5]}: the call's ear, not what the gizmo held | -| 10 | `object_set_brim_ears {object: 0, points: [{position: [90, 90], radius: 3}, {position: [110, 90], radius: 3}]}`, then `object_set_brim_ears {object: 0}` | `brim_ears` 2 | `gizmo()` Brim Ears | +| 10 | `object_set_brim_ears {object: 0, points: [{position: [90, 90], radius: 3}, {position: [110, 90], radius: 3}]}`, then `object_set_brim_ears {object: 0}` | `brim_ears` 2 | `gizmo()` Brim Ears; the opening keeps the two ears the call set with the gizmo closed, though the gizmo was last open on A holding none (D9: `reload_on_next_opening()`) | | 11 | `object_set_brim_ears {object: 0, points: [{position: [100, 90], radius: 150}]}` | as after 10 | refused `radius_out_of_range`; `gizmo()` Brim Ears: a refused call leaves the gizmo open; no undo step | | 12 | `object_set_brim_ears {object: 0, points: [{position: [100, 90]}], clear: true}` | as after 10 | refused, the words "points or clear, not both"; `gizmo()` Brim Ears | | 13 | `object_select {none: true}` | `brim_ears` 2 | `gizmo()` none | @@ -582,14 +582,15 @@ asked for at bed position (x, y) is stored at (x - 100, y - 100, -10.0001) in A' A 20 mm cube A at (100, 100) and a 20 mm cube B at (150, 100), B selected (`object_select {objects: [1]}`). `star.svg` is `tools/mcp/tests/fixtures/star.svg`, as in `test_gizmos`. Each step that adds a part is followed by `app_wait {for: "idle"}`. A's parts are written as their `type` and, for a text, its `text.text`, for an SVG, its -`svg.path` as the file's name. +`svg.path` as the file's name. An object keeps its parts first, then its negative parts, then its modifiers +(`ModelObject::sort_volumes`), so a part added after a negative part comes before it. | # | Step | A's parts after | Also checked | |---|---|---|---| | 0 | start | part | B one part; `selection()` objects [1] | | 1 | `object_add_text {object: 0}` | part · part "Embossed text" | `gizmo()` Text; B one part | | 2 | `object_select {none: true}`, then `object_add_text {object: 0, type: "negative"}` | as after 1 · negative "Embossed text" | `gizmo()` Text | -| 3 | `object_select {objects: [1]}`, then `object_add_svg {object: 0, path: star.svg}` | as after 2 · part star.svg | `gizmo()` SVG; B one part | +| 3 | `object_select {objects: [1]}`, then `object_add_svg {object: 0, path: star.svg}` | part · part "Embossed text" · part star.svg · negative "Embossed text" | `gizmo()` SVG; B one part | | 4 | `object_select {none: true}`, then `object_add_svg {object: 0, type: "modifier", path: star.svg}` | as after 3 · modifier star.svg | `gizmo()` SVG | | 5 | `object_select {none: true}`, `undo` | as after 3 | adding the part is one undo step | | 6 | `redo` | as after 4 | | @@ -606,6 +607,13 @@ A 20 mm cube A at (100, 100) and a 20 mm cube B at (150, 100), B selected (`obje - Variable layer height editing, under which the Cut gizmo does not open (`layers_editing_on`), and a printer that is not FFF (`needs_fff_printer`): unit cases of `gizmo_refusal()`. - How the ears are drawn, and what they do to a slice. +- The ears an undo brings back. With the Brim Ears gizmo closed, an undo restores an object's ears, but the gizmo keeps + the ears it held and brings them back on its next opening. A person's own edit does the same (an ear clicked on, + the gizmo closed, the ear undone, the gizmo opened: the ear is back), so it is the gizmo's behaviour, which the + command leaves as it is (D9). +- That no ear is selected once the gizmo opens after a call: a check needs an ear selected first, by a click on its + grabber at the bed under the object's edge, and the panel shows no state of it (`has_selected_points()` reads the + ears, not the flag a click reads). `reload_on_next_opening()` clears it with the gizmo's own `select_point(NoPoints)`. - `object_id` and `part_id` in replies. **Strength:** Strong — every opening is read back from `app_state`, every acting call's model from `object_list` diff --git a/tools/mcp/test_gizmo_commands.py b/tools/mcp/test_gizmo_commands.py index 800acdd465..29e621174e 100644 --- a/tools/mcp/test_gizmo_commands.py +++ b/tools/mcp/test_gizmo_commands.py @@ -14,13 +14,17 @@ every check passes. Scenario names given on the command line run those scenarios """ import os +import shutil import sys import tempfile +import zipfile sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import orca_mcp # noqa: E402 from checks import Checks, run, selection, slots, undo_steps, wait # noqa: E402 +STAR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "tests", "fixtures", "star.svg") + class GizmoCommandsTest: def __init__(self, client, folder): @@ -343,11 +347,255 @@ class GizmoCommandsTest: self.t.equal(f"{s} {row}: no gizmo open", self.gizmo(), None) self.t.equal(f"{s} {row}: the undo steps", undo_steps(self.c), []) + # ---- Lay on face, brim ears, text and SVG ---- + + def instances(self, obj=0): + """Object `obj`'s instances from object_list, each as {offset, rotation_deg, min, size}.""" + o = self.listed()[obj] + return [{"offset": i["offset"], "rotation_deg": i["rotation_deg"], "min": i["bbox"]["min"], "size": i["bbox"]["size"]} + for i in o["instances"]] + + def turned(self, label, want): + """Checks object 0's instances against `want`, a list of {offset?, rotation, size?}: offsets and sizes to 0.01 mm, + angles to 0.01 degrees, and every instance resting on the bed.""" + got = self.instances() + if not self.t.equal(f"{label}: the instances", len(got), len(want)): + return + for k, (g, w) in enumerate(zip(got, want)): + self.t.near(f"{label}: i{k}'s rotation", g["rotation_deg"], w["rotation"], 0.01) + self.t.near(f"{label}: i{k} rests on the bed", g["min"][2], 0, 0.01) + if "offset" in w: + self.t.near(f"{label}: i{k}'s offset", g["offset"], w["offset"], 0.01) + if "size" in w: + self.t.near(f"{label}: i{k}'s size", g["size"], w["size"], 0.01) + + def lay_on_face(self): + s = "lay on face from a direction" + self.start(s) + self.cube([100, 100], name="A") + self.run("object_transform", object=0, rotate=[30, 0, 0], mode="absolute") + self.run("object_select", none=True) + tilted = {"offset": [100, 100, 13.66], "rotation": [30, 0, 0], "size": [20, 27.32, 27.32]} + flat = {"offset": [100, 100, 10], "rotation": [0, 0, 0], "size": [20, 20, 20]} + self.turned(f"{s} 0", [tilted]) + + reply = self.run("object_lay_on_face", object=0) + self.t.equal(f"{s} 1: the reply", (reply.get("gizmo"), reply.get("active")), ("Flatten", True)) + self.t.equal(f"{s} 1: Lay on Face open", self.gizmo(), {"name": "Flatten", "canvas": "3d"}) + self.turned(f"{s} 1", [tilted]) + + undo_steps(self.c) + reply = self.run("object_lay_on_face", object=0, normal=[0, 0, -1]) + self.turned(f"{s} 2", [flat]) + self.t.equal(f"{s} 2: Lay on Face was closed first", self.gizmo(), None) + self.t.equal(f"{s} 2: the reply", (reply.get("object"), reply.get("instance")), (0, 0)) + self.t.near(f"{s} 2: the reply's rotation", reply.get("rotation"), [0, 0, 0], 0.01) + self.t.equal(f"{s} 2: the undo steps", undo_steps(self.c), ["Gizmo-Place on Face"]) + self.undo() + self.turned(f"{s} 3", [tilted]) + self.redo() + self.turned(f"{s} 4", [flat]) + self.undo() + self.turned(f"{s} 5", [tilted]) + + self.run("object_lay_on_face", object=0, normal=[0, 0.5, -0.866], frame="world") + self.turned(f"{s} 6: the world direction of A's -Z face gives the same turn", [flat]) + self.undo() + self.turned(f"{s} 7", [tilted]) + + self.run("object_set_instances", object=0, count=2) + self.turned(f"{s} 8: the new instance copies i0's turn", [tilted, {"rotation": [30, 0, 0]}]) + self.run("object_lay_on_face", object=0, instance=0, normal=[0, 0, -1]) + self.turned(f"{s} 9: the other instance turns with it", [flat, {"rotation": [0, 0, 0]}]) + self.save_and_reopen("lay.3mf") + self.turned(f"{s} 10: saved and reopened", [flat, {"rotation": [0, 0, 0]}]) + + def brim_file(self, path): + """The saved project's Metadata/brim_ear_points.txt as {object_id: [(x, y, z, r), ...]}.""" + with zipfile.ZipFile(path) as z: + text = z.read("Metadata/brim_ear_points.txt").decode("utf-8") + out = {} + for line in text.splitlines(): + if not line.startswith("object_id="): + continue + head, values = line.split("|", 1) + numbers = [float(v) for v in values.split()] + out[int(head.split("=", 1)[1])] = [tuple(numbers[i:i + 4]) for i in range(0, len(numbers), 4)] + return out + + def ears_near(self, label, got, want): + """Ears, each (x, y, z, r), against `want` to 0.001.""" + if self.t.equal(f"{label}: the ears' count", len(got), len(want)): + for k, (g, w) in enumerate(zip(got, want)): + self.t.near(f"{label}: ear {k}", list(g), list(w), 0.001) + + @staticmethod + def reply_ears(reply): + return [tuple(e["position"]) + (e["radius"],) for e in reply.get("ears", [])] + + def brim_ears(self): + return self.listed()[0]["brim_ears"] + + def setting(self, obj, key): + item = self.c.call("settings_get", target="object", object=obj, keys=[key])["items"][0] + return {"value": item.get("value"), "effective": item.get("effective")} + + def ears(self): + s = "brim ears from positions" + self.start(s) + self.cube([100, 100], name="A") + self.run("object_select", none=True) + two = [(-10, -10, -10.0001, 3), (10, -10, -10.0001, 4)] + self.t.equal(f"{s} 0: no ears", self.brim_ears(), 0) + self.t.equal(f"{s} 0: the object's brim type", self.setting(0, "brim_type"), {"value": None, "effective": "auto_brim"}) + line = self.c.call("settings_get", type="process", keys=["initial_layer_line_width"])["items"][0]["value"] + self.t.equal(f"{s} 0: the first layer's line width", line, "0.5") + + reply = self.run("object_set_brim_ears", object=0) + self.t.equal(f"{s} 1: the reply", (reply.get("gizmo"), reply.get("active")), ("Brim Ears", True)) + self.t.equal(f"{s} 1: Brim Ears open", self.gizmo(), {"name": "Brim Ears", "canvas": "3d"}) + self.t.equal(f"{s} 1: no ears", self.brim_ears(), 0) + + points = [{"position": [90, 90], "radius": 3}, {"position": [110, 90]}] + undo_steps(self.c) + reply = self.run("object_set_brim_ears", object=0, points=points) + self.t.equal(f"{s} 2: two ears", self.brim_ears(), 2) + self.t.equal(f"{s} 2: Brim Ears was closed first", self.gizmo(), None) + self.ears_near(f"{s} 2: the reply", self.reply_ears(reply), two) + self.t.equal(f"{s} 2: the reply's brim type", (reply.get("brim_type"), reply.get("takes_effect")), ("auto_brim", False)) + # The two steps the Brim Ears gizmo records as it closes, then the call's. + self.t.equal(f"{s} 2: the undo steps", undo_steps(self.c), ["Brim ears edit", "Leaving Brim Ears", "Set brim ears"]) + self.undo() + self.t.equal(f"{s} 3: no ears", self.brim_ears(), 0) + self.redo() + self.t.equal(f"{s} 4: two ears", self.brim_ears(), 2) + + self.run("settings_set", target="object", object=0, values={"brim_type": "painted"}) + reply = self.run("object_set_brim_ears", object=0, points=points) + self.t.equal(f"{s} 5: two ears", self.brim_ears(), 2) + self.t.equal(f"{s} 5: the object's brim type", self.setting(0, "brim_type"), {"value": "painted", "effective": "painted"}) + self.ears_near(f"{s} 5: the reply", self.reply_ears(reply), two) + self.t.equal(f"{s} 5: the reply's brim type", (reply.get("brim_type"), reply.get("takes_effect")), ("painted", True)) + + path = os.path.join(self.folder, "ears.3mf") + self.run("project_save", path=path, overwrite=True) + self.t.equal(f"{s} 6: two ears", self.brim_ears(), 2) + saved = self.brim_file(path) + self.t.equal(f"{s} 6: the file's objects", sorted(saved), [1]) + self.ears_near(f"{s} 6: the file", saved.get(1, []), two) + self.run("project_new", discard_changes=True) + self.run("project_open", path=path) + self.idle() + self.t.equal(f"{s} 7: two ears", self.brim_ears(), 2) + self.t.equal(f"{s} 7: the object's brim type", self.setting(0, "brim_type")["value"], "painted") + + reply = self.run("object_set_brim_ears", object=0, clear=True) + self.t.equal(f"{s} 8: no ears", self.brim_ears(), 0) + self.t.equal(f"{s} 8: the reply", reply.get("ears"), []) + + self.run("object_set_brim_ears", object=0) + self.t.equal(f"{s} 9: Brim Ears open", self.gizmo(), {"name": "Brim Ears", "canvas": "3d"}) + self.run("object_set_brim_ears", object=0, points=[{"position": [100, 90], "radius": 5}]) + self.t.equal(f"{s} 9: one ear", self.brim_ears(), 1) + self.t.equal(f"{s} 9: Brim Ears was closed first", self.gizmo(), None) + path = os.path.join(self.folder, "ear.3mf") + self.run("project_save", path=path, overwrite=True) + saved = self.brim_file(path) + self.t.equal(f"{s} 9: the file's objects", sorted(saved), [1]) + self.ears_near(f"{s} 9: the call's ear, not what the gizmo held", saved.get(1, []), [(0, -10, -10.0001, 5)]) + + self.run("object_set_brim_ears", object=0, points=[{"position": [90, 90], "radius": 3}, {"position": [110, 90], "radius": 3}]) + self.run("object_set_brim_ears", object=0) + self.t.equal(f"{s} 10: two ears", self.brim_ears(), 2) + self.t.equal(f"{s} 10: Brim Ears open", self.gizmo(), {"name": "Brim Ears", "canvas": "3d"}) + undo_steps(self.c) + self.t.refused(f"{s} 11: refused", + lambda: self.c.call("object_set_brim_ears", object=0, points=[{"position": [100, 90], "radius": 150}]), + code="radius_out_of_range") + self.t.equal(f"{s} 11: two ears", self.brim_ears(), 2) + self.t.equal(f"{s} 11: a refused call leaves the gizmo open", self.gizmo(), {"name": "Brim Ears", "canvas": "3d"}) + self.t.equal(f"{s} 11: the undo steps", undo_steps(self.c), []) + self.t.refused(f"{s} 12: refused", + lambda: self.c.call("object_set_brim_ears", object=0, points=[{"position": [100, 90]}], clear=True), + words="points or clear, not both") + self.t.equal(f"{s} 12: two ears", self.brim_ears(), 2) + self.t.equal(f"{s} 12: Brim Ears stays open", self.gizmo(), {"name": "Brim Ears", "canvas": "3d"}) + self.run("object_select", none=True) + self.t.equal(f"{s} 13: two ears", self.brim_ears(), 2) + self.t.equal(f"{s} 13: no gizmo open", self.gizmo(), None) + + def a_parts(self): + """A's parts as (type, its text's text or its SVG's file name, else None). A text read back from a project file + has an svg entry too, with no file, so its text comes first.""" + out = [] + for p in self.listed()[0]["parts"]: + name = (p.get("text") or {}).get("text") + if name is None and p.get("svg"): + name = os.path.basename(p["svg"].get("path") or "") + out.append((p["type"], name)) + return out + + def text_and_svg(self): + s = "text and SVG as a part of a named object" + self.start(s) + self.cube([100, 100], name="A") + self.cube([150, 100], name="B") + self.run("object_select", objects=[1]) + star = os.path.join(self.folder, "star.svg") + shutil.copyfile(STAR, star) + + def state(label, parts, gizmo=None): + self.t.equal(f"{label}: A's parts", self.a_parts(), parts) + self.t.equal(f"{label}: B has one part", len(self.listed()[1]["parts"]), 1) + if gizmo is not None: + self.t.equal(f"{label}: the gizmo open", self.gizmo(), {"name": gizmo, "canvas": "3d"}) + + state(f"{s} 0", [("part", None)]) + self.t.equal(f"{s} 0: B selected", self.selected(), {"objects": [1], "instances": [[1, 0]]}) + after1 = [("part", None), ("part", "Embossed text")] + after2 = after1 + [("negative", "Embossed text")] + # An object keeps its parts before its negative parts and its modifiers (ModelObject::sort_volumes). + after3 = after1 + [("part", "star.svg"), ("negative", "Embossed text")] + after4 = after3 + [("modifier", "star.svg")] + + self.run("object_add_text", object=0) + self.idle() + state(f"{s} 1", after1, "Text") + self.run("object_select", none=True) + self.run("object_add_text", object=0, type="negative") + self.idle() + state(f"{s} 2", after2, "Text") + self.run("object_select", objects=[1]) + self.run("object_add_svg", object=0, path=star) + self.idle() + state(f"{s} 3", after3, "SVG") + self.run("object_select", none=True) + self.run("object_add_svg", object=0, type="modifier", path=star) + self.idle() + state(f"{s} 4", after4, "SVG") + self.run("object_select", none=True) + self.undo() + state(f"{s} 5: adding the part is one undo step", after3) + self.redo() + state(f"{s} 6", after4) + + self.run("dialog_auto_answer", rules=[{"match": ".", "button": "ok", "path": star}]) + self.run("object_add_svg", object=0, type="modifier") + self.idle() + rules = self.c.call("app_state")["auto_answer_rules"] + self.t.equal(f"{s} 7: the file picker opened", [r.get("uses") for r in rules], [1]) + state(f"{s} 7: nothing was added", after4) + self.run("dialog_auto_answer", rules=[]) + self.save_and_reopen("parts.3mf") + state(f"{s} 8: saved and reopened", after4) + def run_all(self, only=()): self.run("action_run", id="orca_command:mode_expert:orca") self.t.equal("Expert mode", self.c.call("app_state")["mode"], "expert") scenarios = [("opening a gizmo on a target", self.opening), ("openings refused", self.refused_openings), - ("cut from arguments", self.cut), ("cuts refused", self.refused_cuts)] + ("cut from arguments", self.cut), ("cuts refused", self.refused_cuts), + ("lay on face from a direction", self.lay_on_face), ("brim ears from positions", self.ears), + ("text and SVG as a part of a named object", self.text_and_svg)] for name, scenario in scenarios: if not only or name in only: self.t.scenario(name, scenario)