From 4f6821f059983e73ee24178077f4502dcb2be3aa Mon Sep 17 00:00:00 2001 From: SoftFever Date: Thu, 19 Nov 2026 20:49:40 +0800 Subject: [PATCH] Let MCP clients cut an object along a plane with object_cut object_cut cuts an object at a height or along any plane, keeping either piece or both, laid where the Cut gizmo would lay them or kept as two parts of one object, in one undo step, as the gizmo's Perform cut does. Named with only its object it opens the Cut gizmo on it, for connectors, the dovetail and cuts along a contour. A plane that misses the object, or an object with connectors, is refused with the model left as it was. --- scripts/check_operation_calls.py | 1 + src/slic3r/GUI/Gizmos/GLGizmoCut.hpp | 6 + src/slic3r/GUI/Mcp/McpToolsGizmos.cpp | 151 +++++++++++++++++- src/slic3r/GUI/Operations/GizmoOps.cpp | 143 +++++++++++++++++- src/slic3r/GUI/Operations/GizmoOps.hpp | 52 ++++++- tests/data/command_catalog.json | 139 +++++++++++++++++ tests/slic3rutils/test_command_catalog.cpp | 18 +-- tests/slic3rutils/test_mcp_scene.cpp | 2 +- tests/slic3rutils/test_mcp_tools.cpp | 6 +- tests/slic3rutils/test_operations.cpp | 128 +++++++++++++++- tools/mcp/test-entries/gizmos.md | 6 +- tools/mcp/test_gizmo_commands.py | 168 +++++++++++++++++++-- 12 files changed, 783 insertions(+), 37 deletions(-) diff --git a/scripts/check_operation_calls.py b/scripts/check_operation_calls.py index 397a4235d3..9e22744562 100644 --- a/scripts/check_operation_calls.py +++ b/scripts/check_operation_calls.py @@ -95,6 +95,7 @@ BANNED = { "reorder_objects": ["move_object"], # 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"], "the undo snapshot of an operation": ["take_snapshot"], } diff --git a/src/slic3r/GUI/Gizmos/GLGizmoCut.hpp b/src/slic3r/GUI/Gizmos/GLGizmoCut.hpp index ed834d6150..6148f8a4ad 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoCut.hpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoCut.hpp @@ -8,6 +8,7 @@ #include "libslic3r/TriangleMesh.hpp" #include "libslic3r/Model.hpp" #include "libslic3r/CutUtils.hpp" +#include "libslic3r/ObjectID.hpp" #include "imgui/imgui.h" #include "libslic3r/Point.hpp" #include "slic3r/GUI/MeshUtils.hpp" @@ -407,6 +408,11 @@ private: void apply_cut_connectors(ModelObject* mo, const std::string& connector_name); }; +// What Perform cut does to the cut object's cut id before it cuts, and to the model's other pieces of the same cut after +// it, which a cut made from arguments (Ops::cut_object()) does as well. +void update_object_cut_id(CutObjectBase& cut_id, ModelObjectCutAttributes attributes, const int dowels_count); +void synchronize_model_after_cut(Model& model, const CutObjectBase& cut_id); + } // namespace GUI } // namespace Slic3r diff --git a/src/slic3r/GUI/Mcp/McpToolsGizmos.cpp b/src/slic3r/GUI/Mcp/McpToolsGizmos.cpp index 6a8aa9dff2..78e96b4e79 100644 --- a/src/slic3r/GUI/Mcp/McpToolsGizmos.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsGizmos.cpp @@ -1,6 +1,7 @@ -// The gizmo commands: a named target's gizmo opened on it (object_paint, object_measure, object_simplify, part_boolean). -// 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. +// 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. #include "McpTargets.hpp" #include "McpTools.hpp" @@ -8,20 +9,26 @@ #include "slic3r/GUI/CommandCatalog.hpp" #include "slic3r/GUI/CommandTypes.hpp" +#include "slic3r/GUI/GLCanvas3D.hpp" #include "slic3r/GUI/Gizmos/GLGizmosManager.hpp" #include "slic3r/GUI/I18N.hpp" #include "slic3r/GUI/Operations/GizmoOps.hpp" #include "slic3r/GUI/Operations/ObjectOps.hpp" #include "slic3r/GUI/Operations/Outcome.hpp" #include "slic3r/GUI/Plater.hpp" +#include "slic3r/GUI/Selection.hpp" #include "libslic3r/Model.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/TriangleMesh.hpp" +#include "libslic3r/libslic3r.h" #include #include #include #include +#include #include #include @@ -94,6 +101,100 @@ const char* const kWorkTheGizmo = "The gizmo already open on the same target stays open. Reply: gizmo (its name, as app_state.gizmo gives it), active, " "and what is selected (objects, instances, parts)."; +// Whether a call of `command` gives one of its acting arguments, and so does the job with no gizmo. +bool acts(const json& args, const std::string& command) +{ + for (const std::string& name : gizmo_acting_args(command)) + if (args.contains(name)) + return true; + return false; +} + +Vec3d to_vec3(const json& v, const char* what) +{ + if (!v.is_array() || v.size() != 3) + throw ToolFailure(std::string(what) + " must be [x, y, z]"); + return {v[0].get(), v[1].get(), v[2].get()}; +} + +Ops::CutPlacement placement(const std::string& name) +{ + return name == "as_cut" ? Ops::CutPlacement::AsCut : name == "flip" ? Ops::CutPlacement::Flip : Ops::CutPlacement::PlaceOnCut; +} + +// What an object of the model is in a cut's reply: its index, id and name, and the open edges its parts have, which +// object_fix repairs. +json piece(const Model& model, int index) +{ + const ModelObject& object = *model.objects[std::size_t(index)]; + std::size_t open_edges = 0; + for (const ModelVolume* volume : object.volumes) + open_edges += its_num_open_edges(volume->mesh().its); + return {{"index", index}, {"object_id", object.id().id}, {"name", object.name}, {"open_edges", open_edges}}; +} + +// object_cut from its acting arguments. The arguments the Cut gizmo's panel could not set together are refused before +// anything is read: z with plane, a placement for a piece not kept, and placements or one piece with Cut to parts. +json cut_from_args(const json& args) +{ + if (args.contains("z") && args.contains("plane")) + throw ToolFailure("Give z or plane, not both."); + if (!args.contains("z") && !args.contains("plane")) + throw refused(Ops::Refusal{Ops::RefusalKind::Precondition, "needs_plane", + L("A cut needs its plane: give z or plane with keep, upper, lower or to_parts.")}); + Ops::CutObjectArgs op; + if (args.contains("plane")) { + op.point = to_vec3(args["plane"]["point"], "plane.point"); + op.normal = to_vec3(args["plane"]["normal"], "plane.normal"); + if (op.normal.norm() < EPSILON) + throw ToolFailure("plane.normal is zero: give the direction the upper piece lies in."); + } + const std::string keep = args.value("keep", std::string("both")); + op.keep_upper = keep != "lower"; + op.keep_lower = keep != "upper"; + if (args.contains("upper") && !op.keep_upper) + throw ToolFailure("upper places the upper piece, but the upper piece is not kept (keep \"lower\")."); + if (args.contains("lower") && !op.keep_lower) + throw ToolFailure("lower places the lower piece, but the lower piece is not kept (keep \"upper\")."); + op.to_parts = args.value("to_parts", false); + if (op.to_parts && keep != "both") + throw ToolFailure("to_parts keeps both pieces, as two parts of one object; leave keep out."); + if (op.to_parts && (args.contains("upper") || args.contains("lower"))) + throw ToolFailure("to_parts places no piece: both stay as cut; leave upper and lower out."); + if (args.contains("upper")) + op.upper = placement(args["upper"].get()); + if (args.contains("lower")) + op.lower = placement(args["lower"].get()); + + Plater& plater = ui_plater(); + 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(); + if (args.contains("z")) { + // A level plane that high above the bed, through the instance. + op.point = plater.model().objects[std::size_t(op.object)]->instances[std::size_t(op.instance)]->get_offset(); + op.point.z() = args["z"].get(); + op.normal = Vec3d::UnitZ(); + } + + const Ops::Outcome cut = Ops::cut_object(op); + if (!cut) + throw refused(cut.refusal()); + const Model& model = plater.model(); + json reply; + if (op.to_parts) { + reply["object"] = piece(model, cut.value().objects.front()); + reply["parts"] = targets_reply(model, cut.value()).value("parts", json::array()); + } else { + reply["pieces"] = json::array(); + for (int index : cut.value().objects) + reply["pieces"].push_back(piece(model, index)); + } + return reply; +} + NativeCommand gizmo_command(std::string name, std::string title, std::string description, json schema, EType type, GizmoTargets reading, json examples) { @@ -117,7 +218,8 @@ 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_paint", {}}, {"object_measure", {}}, {"object_simplify", {}}, {"part_boolean", {}}, + {"object_cut", {"z", "plane", "keep", "upper", "lower", "to_parts"}}}; static const std::vector none; const auto found = acting.find(command); return found != acting.end() ? found->second : none; @@ -181,6 +283,47 @@ void register_gizmo_tools(CommandCatalog& catalog) json::parse(R"json([ {"title": "Open Mesh Boolean on object 0", "calls": [{"tool": "part_boolean", "args": {"object": 0}}]}, {"title": "Open Mesh Boolean on the selected object", "calls": [{"tool": "part_boolean", "args": {}}]}])json"))); + + const std::vector placements{"as_cut", "place_on_cut", "flip"}; + json point = array_prop({{"type", "number"}}, "[x, y, z] mm: a point of the plane, in the 3D view's coordinates."); + json normal = array_prop({{"type", "number"}}, "[x, y, z]: the direction the upper piece lies in; any length but zero."); + point["minItems"] = normal["minItems"] = 3; + json plane = object_schema({{"point", std::move(point)}, {"normal", std::move(normal)}}, {"point", "normal"}); + plane["description"] = "Cut along this plane. Not with z."; + NativeCommand cut = with_expected_ids(mutate_tool( + "object_cut", L("Cut"), + std::string( + "Cut an object's instance, the first unless instance is given, along a plane, as the Cut gizmo's Perform cut does. " + "Acts from arguments: z, plane, keep, upper, lower, to_parts. With none of them it opens the Cut gizmo. z cuts " + "level, that many mm above the bed; plane {point, normal} cuts along any plane, the upper piece being the one " + "the normal points into. keep: both (default), upper or lower. upper and lower place a kept piece: as_cut, " + "place_on_cut (laid on its cut face) or flip; by default the upper piece is laid on its cut face and the lower " + "one stays as cut. to_parts keeps both pieces as two parts of one object, with no placement. A cut is one undo " + "step and replaces the object: its pieces go to the end of the object list, upper first, and the reply gives " + "them as pieces [{index, object_id, name, open_edges}], or with to_parts the object and its parts. A piece with " + "open edges is repaired by object_fix. Connectors, the dovetail and a cut along a contour are left to the gizmo: " + "open it with object_cut naming only the object.") + + kWorkTheGizmo, + with_targets(object_schema({{"z", prop("number", "mm above the bed: cut level at this height. Not with plane.")}, + {"plane", std::move(plane)}, + {"keep", enum_prop({"both", "upper", "lower"}, "The pieces kept. Default both.")}, + {"upper", enum_prop(placements, "Where the upper piece goes. Default place_on_cut.")}, + {"lower", enum_prop(placements, "Where the lower piece goes. Default as_cut.")}, + {"to_parts", prop("boolean", "Keep both pieces as two parts of one object, as the gizmo's " + "Cut to parts does. Default false.")}}), + kObjects | kInstances, true), + [](const json& args, ToolContext& ctx) { + json out = ctx.run_ui([&] { + return acts(args, "object_cut") ? cut_from_args(args) : open_on(args, EType::Cut, {kObjects | kInstances, true, one_instance}); + }); + settle(ctx); + return ToolResult::ok(out); + })); + cut.examples = json::parse(R"json([ + {"title": "Cut object 0 in two, 10 mm above the bed", "calls": [{"tool": "object_cut", "args": {"object": 0, "z": 10}}]}, + {"title": "Keep the part of object 1 above a tilted plane", "calls": [ + {"tool": "object_cut", "args": {"object": 1, "plane": {"point": [100, 100, 10], "normal": [1, 0, 1]}, "keep": "upper"}}]}])json"); + catalog.add(reaching({"open_gizmo", "cut_object"}, std::move(cut))); } }}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Operations/GizmoOps.cpp b/src/slic3r/GUI/Operations/GizmoOps.cpp index 54c9e419c5..a9dd8091c8 100644 --- a/src/slic3r/GUI/Operations/GizmoOps.cpp +++ b/src/slic3r/GUI/Operations/GizmoOps.cpp @@ -9,20 +9,33 @@ #include "slic3r/GUI/GUI_App.hpp" #include "slic3r/GUI/GUI_ObjectList.hpp" #include "slic3r/GUI/Gizmos/GLGizmoBase.hpp" +#include "slic3r/GUI/Gizmos/GLGizmoCut.hpp" #include "slic3r/GUI/Gizmos/GLGizmosManager.hpp" #include "slic3r/GUI/I18N.hpp" #include "slic3r/GUI/Plater.hpp" #include "slic3r/GUI/Selection.hpp" +#include "libslic3r/AppConfig.hpp" +#include "libslic3r/CutUtils.hpp" +#include "libslic3r/Geometry.hpp" #include "libslic3r/Model.hpp" +#include "libslic3r/ObjectID.hpp" +#include "libslic3r/Point.hpp" #include "libslic3r/Preset.hpp" #include "libslic3r/PresetBundle.hpp" #include "libslic3r/PrintConfig.hpp" +#include "libslic3r/TriangleMesh.hpp" +#include "libslic3r/enum_bitmask.hpp" +#include "libslic3r/libslic3r.h" + +#include +#include #include #include #include #include +#include #include #include #include @@ -44,7 +57,7 @@ Refusal layers_editing_on() } Refusal dowel_alone() { - return refusal("dowel_alone", L("The Cut gizmo does not open on a cut object that is left as a single dowel connector.")); + return refusal("dowel_alone", L("A cut object left as a single dowel connector cannot be cut: the Cut gizmo does not open on it.")); } Refusal needs_fff_printer() { return refusal("needs_fff_printer", L("Painting on the model is for FFF printers only.")); } Refusal needs_two_filaments() { return refusal("needs_two_filaments", L("Color Painting needs at least two filaments.")); } @@ -146,6 +159,37 @@ bool one_volume(const Selection& sel, const Targets& targets) return targets.objects.empty() && targets.instances.empty() && targets.parts.size() == 1; } +// A cut object left as one dowel connector, on which the Cut gizmo does not open, as GLGizmoCut3D::on_is_activable() +// reads it. +bool is_dowel_alone(const ModelObject& object) +{ + return object.is_cut() && object.volumes.size() == 1 && object.volumes[0]->is_cut_connector() && + object.volumes[0]->cut_info.connector_type == CutConnectorType::Dowel; +} + +// Whether no vertex of the instance's parts lies on one side of the plane, so that a cut would leave the object whole. +// Modifiers and negative parts are cut with the object but make no piece of their own. A NaN distance, from a zero +// normal, lies on neither side. +bool plane_misses(const ModelObject& object, int instance, const Vec3d& point, const Vec3d& normal) +{ + const Transform3d placed = object.instances[std::size_t(instance)]->get_matrix(); + const Vec3d unit = normal.normalized(); + bool above = false, below = false; + for (const ModelVolume* volume : object.volumes) { + if (!volume->is_model_part()) + continue; + const Transform3d to_view = placed * volume->get_matrix(); + for (const stl_vertex& vertex : volume->mesh().its.vertices) { + const double distance = unit.dot(to_view * vertex.cast() - point); + above = above || distance > EPSILON; + below = below || distance < -EPSILON; + if (above && below) + return false; + } + } + return true; +} + } // namespace std::optional gizmo_refusal(GLGizmosManager::EType type, const GizmoFacts& facts, bool activable) @@ -189,11 +233,8 @@ GizmoFacts gizmo_facts() facts.filaments = wxGetApp().filaments_cnt(); facts.layers_editing = canvas.is_layers_editing_enabled(); // As GLGizmoCut3D::on_is_activable() reads it. - if (const int object = canvas.get_selection().get_object_idx(); object >= 0 && std::size_t(object) < plater.model().objects.size()) { - const ModelObject* mo = plater.model().objects[std::size_t(object)]; - facts.dowel_alone = mo->is_cut() && mo->volumes.size() == 1 && mo->volumes[0]->is_cut_connector() && - mo->volumes[0]->cut_info.connector_type == CutConnectorType::Dowel; - } + if (const int object = canvas.get_selection().get_object_idx(); object >= 0 && std::size_t(object) < plater.model().objects.size()) + facts.dowel_alone = is_dowel_alone(*plater.model().objects[std::size_t(object)]); return facts; } @@ -251,4 +292,94 @@ Outcome open_gizmo(const OpenGizmoArgs& args) return OpenedGizmo{args.type, named ? args.targets : selected(sel)}; } +enum_bitmask cut_attributes(const CutObjectArgs& args, bool keep_painting, bool has_cut_id) +{ + using Attribute = ModelObjectCutAttribute; + // Checking Cut to parts keeps both pieces and clears each piece's placement, which the gizmo then greys out. + const bool placed = !args.to_parts; + return only_if(args.to_parts || args.keep_upper, Attribute::KeepUpper) | + only_if(args.to_parts || args.keep_lower, Attribute::KeepLower) | only_if(args.to_parts, Attribute::KeepAsParts) | + only_if(placed && args.upper == CutPlacement::PlaceOnCut, Attribute::PlaceOnCutUpper) | + only_if(placed && args.lower == CutPlacement::PlaceOnCut, Attribute::PlaceOnCutLower) | + only_if(placed && args.upper == CutPlacement::Flip, Attribute::FlipUpper) | + only_if(placed && args.lower == CutPlacement::Flip, Attribute::FlipLower) | + only_if(!has_cut_id, Attribute::InvalidateCutInfo) | only_if(keep_painting, Attribute::KeepPaint); +} + +std::optional cut_refusal(const ModelObject& object, int instance, const Vec3d& point, const Vec3d& normal) +{ + if (!object.cut_connectors.empty()) + return refusal("has_connectors", L("The object has cut connectors, which only the Cut gizmo cuts: cut it there.")); + if (is_dowel_alone(object)) + return dowel_alone(); + if (plane_misses(object, instance, point, normal)) + return refusal("plane_misses_object", L("The cut plane does not cross the object: all of it lies on one side of the plane.")); + return std::nullopt; +} + +Transform3d cut_matrix(const ModelObject& object, int instance, const Vec3d& point, const Vec3d& normal, double sla_shift_z) +{ + Vec3d from_instance = point - object.instances[std::size_t(instance)]->get_offset(); + from_instance.z() -= sla_shift_z; + const Vec3d unit = normal.normalized(); + // The gizmo's plane starts level, facing +Z, and turns from there. A turn to straight down is the gizmo's Flip, which + // fixes the turn about the normal that Eigen would otherwise pick for opposite vectors; it decides how a piece laid on + // its cut face is turned on the bed. + Transform3d turn = Transform3d::Identity(); + if (unit.z() < -1. + EPSILON) + turn = Geometry::rotation_transform(PI * Vec3d::UnitX()); + else + turn.linear() = Eigen::Quaterniond::FromTwoVectors(Vec3d::UnitZ(), unit).toRotationMatrix(); + return Geometry::translation_transform(from_instance) * turn; +} + +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)}}; + 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; + + // The open gizmo writes its own state to the model as it closes, so it closes before the object is read for the cut. + close_open_gizmo(); + // The plane is the 3D view's, which lifts an SLA object off the bed; the gizmo reads that lift from its selected + // volume, the instance's first volume in the scene. + double sla_shift_z = 0.; + for (const GLVolume* volume : plater.get_view3D_canvas3D()->get_volumes().volumes) + if (volume->object_idx() == args.object && volume->instance_idx() == args.instance) { + sla_shift_z = volume->get_sla_shift_z(); + break; + } + + Plater::TakeSnapshot snapshot(&plater, _u8L("Cut by Plane")); + const ModelObjectCutAttributes attributes = cut_attributes(args, wxGetApp().app_config->get_bool("keep_painting"), + !object->cut_id.id().invalid()); + update_object_cut_id(object->cut_id, attributes, 0); + Cut cut(object, args.instance, cut_matrix(*object, args.instance, args.point, args.normal, sla_shift_z), attributes); + const ModelObjectPtrs& pieces = cut.perform_with_plane(); + const CutObjectBase cut_id = object->cut_id; + plater.apply_cut_object_to_model(std::size_t(args.object), pieces); + synchronize_model_after_cut(model, cut_id); + + // The pieces are added at the end of the object list, upper first. + Targets out; + const int first = int(model.objects.size() - pieces.size()); + for (int index = first; index < int(model.objects.size()); ++index) + out.objects.push_back(index); + if (args.to_parts && out.objects.size() == 1) + for (std::size_t part = 0; part < model.objects.back()->volumes.size(); ++part) + out.parts.emplace_back(out.objects.front(), int(part)); + return out; +} + }}} // namespace Slic3r::GUI::Ops diff --git a/src/slic3r/GUI/Operations/GizmoOps.hpp b/src/slic3r/GUI/Operations/GizmoOps.hpp index 640520d8a5..76e4a17556 100644 --- a/src/slic3r/GUI/Operations/GizmoOps.hpp +++ b/src/slic3r/GUI/Operations/GizmoOps.hpp @@ -5,12 +5,24 @@ #include "slic3r/GUI/Gizmos/GLGizmosManager.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/enum_bitmask.hpp" + #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 ModelObject; +enum class ModelObjectCutAttribute : int; // CutUtils.hpp +} // namespace Slic3r + // Opening a gizmo of the Prepare view on what a command names: the operation the gizmo commands (object_paint, // 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. +// 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. namespace Slic3r { namespace GUI { namespace Ops { struct OpenGizmoArgs @@ -56,4 +68,42 @@ std::optional gizmo_refusal(GLGizmosManager::EType type, const GizmoFac // does before it cuts (GLCanvas3D::reset_all_gizmos()). UI thread. void close_open_gizmo(); +// ---- A cut by a plane, as the Cut gizmo's Perform cut does it for an object with no connectors ---- + +// Where a kept piece goes: left as cut, laid on its cut face, or turned upside down (the gizmo's three choices per piece). +enum class CutPlacement { AsCut, PlaceOnCut, Flip }; + +struct CutObjectArgs +{ + int object = 0, instance = 0; + Vec3d point = Vec3d::Zero(); // a point of the plane, in the 3D view's coordinates + Vec3d normal = Vec3d::UnitZ(); // the plane's normal; the upper piece is the one it points into + bool keep_upper = true, keep_lower = true; + // The gizmo's defaults: the upper piece laid on its cut face, the lower one as cut. + CutPlacement upper = CutPlacement::PlaceOnCut, lower = CutPlacement::AsCut; + bool to_parts = false; // Cut to parts: both pieces stay, as two parts of one object, with no placement +}; + +// What Perform cut builds for `args`: the pieces kept and placed, KeepPaint with the keep_painting preference, and +// InvalidateCutInfo for an object that has no cut id (`has_cut_id` false). Pure. +// The type is ModelObjectCutAttributes (CutUtils.hpp). +enum_bitmask cut_attributes(const CutObjectArgs& args, bool keep_painting, bool has_cut_id); + +// Why the instance cannot be cut along the plane, or none: has_connectors (connectors are placed in the Cut gizmo, which +// cuts them), dowel_alone (a cut object left as one dowel connector, which the gizmo does not open on), and +// plane_misses_object (no vertex of the instance's parts on one side of the plane, which a zero normal meets too). The +// plane is in the model's coordinates, which are the 3D view's for an FFF printer. Pure. +std::optional cut_refusal(const ModelObject& object, int instance, const Vec3d& point, const Vec3d& normal); + +// What GLGizmoCut3D::get_cut_matrix() gives for the plane: the translation to `point` from the instance's offset, less +// the SLA elevation `sla_shift_z`, times the turn of +Z to `normal`; a normal facing straight down is the gizmo's +// Flip, a half turn about X. Pure. +Transform3d cut_matrix(const ModelObject& object, int instance, const Vec3d& point, const Vec3d& normal, double sla_shift_z); + +// Cuts the instance along the plane as Perform cut does: the refusals first, then the open gizmo closed, one undo step +// "Cut by Plane", and the object replaced by its pieces at the end of the object list, upper first. It asks nothing +// about the open edges a cut may leave (Perform cut offers to repair them). Returns the pieces' indices, or with +// to_parts the one object and its parts. UI thread. +Outcome cut_object(const CutObjectArgs& args); + }}} // namespace Slic3r::GUI::Ops diff --git a/tests/data/command_catalog.json b/tests/data/command_catalog.json index 88c1280797..2f6e0126b9 100644 --- a/tests/data/command_catalog.json +++ b/tests/data/command_catalog.json @@ -3456,6 +3456,145 @@ "read_only": false, "title": "Simplify Model" }, + { + "completion": "immediate", + "description": "Cut an object's instance, the first unless instance is given, along a plane, as the Cut gizmo's Perform cut does. Acts from arguments: z, plane, keep, upper, lower, to_parts. With none of them it opens the Cut gizmo. z cuts level, that many mm above the bed; plane {point, normal} cuts along any plane, the upper piece being the one the normal points into. keep: both (default), upper or lower. upper and lower place a kept piece: as_cut, place_on_cut (laid on its cut face) or flip; by default the upper piece is laid on its cut face and the lower one stays as cut. to_parts keeps both pieces as two parts of one object, with no placement. A cut is one undo step and replaces the object: its pieces go to the end of the object list, upper first, and the reply gives them as pieces [{index, object_id, name, open_edges}], or with to_parts the object and its parts. A piece with open edges is repaired by object_fix. Connectors, the dovetail and a cut along a contour are left to the gizmo: open it with object_cut naming only the object. 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, + "z": 10 + }, + "tool": "object_cut" + } + ], + "title": "Cut object 0 in two, 10 mm above the bed" + }, + { + "calls": [ + { + "args": { + "keep": "upper", + "object": 1, + "plane": { + "normal": [ + 1, + 0, + 1 + ], + "point": [ + 100, + 100, + 10 + ] + } + }, + "tool": "object_cut" + } + ], + "title": "Keep the part of object 1 above a tilted plane" + } + ], + "group": "Objects", + "guard": "mutate", + "has_own_action": false, + "idempotent": false, + "input_schema": { + "additionalProperties": false, + "properties": { + "instance": { + "description": "An instance of the object (object_list).", + "minimum": 0, + "type": "integer" + }, + "keep": { + "description": "The pieces kept. Default both.", + "enum": [ + "both", + "upper", + "lower" + ], + "type": "string" + }, + "lower": { + "description": "Where the lower piece goes. Default as_cut.", + "enum": [ + "as_cut", + "place_on_cut", + "flip" + ], + "type": "string" + }, + "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" + }, + "plane": { + "additionalProperties": false, + "description": "Cut along this plane. Not with z.", + "properties": { + "normal": { + "description": "[x, y, z]: the direction the upper piece lies in; any length but zero.", + "items": { + "type": "number" + }, + "minItems": 3, + "type": "array" + }, + "point": { + "description": "[x, y, z] mm: a point of the plane, in the 3D view's coordinates.", + "items": { + "type": "number" + }, + "minItems": 3, + "type": "array" + } + }, + "required": [ + "point", + "normal" + ], + "type": "object" + }, + "to_parts": { + "description": "Keep both pieces as two parts of one object, as the gizmo's Cut to parts does. Default false.", + "type": "boolean" + }, + "upper": { + "description": "Where the upper piece goes. Default place_on_cut.", + "enum": [ + "as_cut", + "place_on_cut", + "flip" + ], + "type": "string" + }, + "z": { + "description": "mm above the bed: cut level at this height. Not with plane.", + "type": "number" + } + }, + "type": "object" + }, + "key": "object_cut", + "listed": true, + "open_world": false, + "operations": [ + "open_gizmo", + "cut_object" + ], + "read_only": false, + "title": "Cut" + }, { "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 00e628a176..bb5b402f09 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 122 commands of the catalog, its typed tools, the commands made from +// GUI last, after the Design tab's commands: the 123 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 four gizmo -// commands that only open their gizmo (Paint, Measure, Simplify, Mesh Boolean). +// 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). // 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,7 @@ 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_set_auto_drop", "object_clone", "object_reload_from_disk", "object_paint", "object_measure", "object_simplify", "object_cut"}}, {"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 +448,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 four gizmo commands that only open. - CHECK(commands == 122); + // 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); // 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 +476,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 == 122); + CHECK(commands == 123); // tool_search's group says which there are. const NativeCommand* search = NativeCommands::find("tool_search"); @@ -517,8 +517,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 - // four gizmo commands that only open. - CHECK(listed.size() == 119); + // five gizmo commands. + CHECK(listed.size() == 120); // 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 51d04d613b..2c2283d50e 100644 --- a/tests/slic3rutils/test_mcp_scene.cpp +++ b/tests/slic3rutils/test_mcp_scene.cpp @@ -1701,7 +1701,7 @@ 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_paint", "Objects"}, {"object_measure", "Objects"}, {"object_simplify", "Objects"}, {"part_boolean", "Parts"}, {"object_cut", "Objects"}}; TEST_CASE("the gizmo commands are listed under their places and take no silent", "[Mcp][Gizmos]") { diff --git a/tests/slic3rutils/test_mcp_tools.cpp b/tests/slic3rutils/test_mcp_tools.cpp index ae08fb354e..508c5cfb42 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 119 commands are listed: every one that runs from its arguments, all but the three menu + // Outside the Design group 120 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 four gizmo commands that only open). + // Part 5d's four and the five gizmo commands). std::size_t listed = 0; for (const NativeCommand& c : catalog.commands()) if (c.listed && c.group != Slic3r::GUI::kDesignGroup) ++listed; - CHECK(listed == 119); + CHECK(listed == 120); } 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 91f45e7f4b..37a5fa5487 100644 --- a/tests/slic3rutils/test_operations.cpp +++ b/tests/slic3rutils/test_operations.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include "slic3r/GUI/CommandCatalog.hpp" @@ -22,7 +23,9 @@ #include "slic3r/plugin/PluginDescriptor.hpp" #include "libslic3r/AppConfig.hpp" +#include "libslic3r/CutUtils.hpp" #include "libslic3r/Model.hpp" +#include "libslic3r/Point.hpp" #include "libslic3r/TextConfiguration.hpp" #include "libslic3r/TriangleMesh.hpp" @@ -2048,7 +2051,7 @@ const std::set kOperations = { "add_filament_slot", "delete_filament_slot", "add_mixed_filament", "sync_presets", "export_toolpaths_obj", "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", + "reorder_objects", "sync_filaments_from_ams", "open_gizmo", "cut_object", }; // What an exception is, so that the reason reads the same for every entry of a kind. @@ -2302,3 +2305,126 @@ TEST_CASE("every gizmo a command opens says why it stays closed", "[Operations][ CHECK(gizmo_refusal_code(reads_none, every_fact_fails, true).empty()); CHECK(gizmo_refusal_code(GLGizmosManager::Cut, GizmoFacts{false, 1, false, false}, true).empty()); } + +namespace { + +// A 20 mm cube centred on its own origin, its instance's centre at (100, 100, 10), as object_add_primitive places one +// on the bed. +Slic3r::ModelObject* placed_cube(Slic3r::Model& model) +{ + Slic3r::ModelObject* object = model.add_object(); + Slic3r::TriangleMesh mesh = Slic3r::make_cube(20., 20., 20.); + mesh.translate(-10.f, -10.f, -10.f); + object->add_volume(std::move(mesh)); + object->add_instance()->set_offset(Slic3r::Vec3d(100., 100., 10.)); + return object; +} + +// The code cut_refusal() gives, or "" for none. +std::string cut_refusal_code(const Slic3r::ModelObject& object, const Slic3r::Vec3d& point, const Slic3r::Vec3d& normal) +{ + const std::optional refusal = cut_refusal(object, 0, point, normal); + return refusal ? std::string(refusal->code) : std::string(); +} + +} // namespace + +TEST_CASE("a cut from arguments builds the attributes the Cut gizmo builds", "[Operations][Gizmos]") +{ + using Attribute = Slic3r::ModelObjectCutAttribute; + // The gizmo's defaults on an object never cut: both pieces kept, the upper one laid on its cut face, and the cut + // information left out, since the object has no cut id to carry on. + const CutObjectArgs defaults; + CHECK(cut_attributes(defaults, false, false) == + (Attribute::KeepUpper | Attribute::KeepLower | Attribute::PlaceOnCutUpper | Attribute::InvalidateCutInfo)); + // The keep_painting preference keeps the painting. + CHECK(cut_attributes(defaults, true, false) == + (Attribute::KeepUpper | Attribute::KeepLower | Attribute::PlaceOnCutUpper | Attribute::InvalidateCutInfo | Attribute::KeepPaint)); + + CutObjectArgs upper_only; + upper_only.keep_lower = false; + CHECK(cut_attributes(upper_only, false, false) == (Attribute::KeepUpper | Attribute::PlaceOnCutUpper | Attribute::InvalidateCutInfo)); + + CutObjectArgs flipped; + flipped.upper = CutPlacement::Flip; + flipped.lower = CutPlacement::PlaceOnCut; + CHECK(cut_attributes(flipped, false, false) == + (Attribute::KeepUpper | Attribute::KeepLower | Attribute::FlipUpper | Attribute::PlaceOnCutLower | Attribute::InvalidateCutInfo)); + + // Cut to parts keeps both pieces and drops the placements, the upper piece's default among them. + CutObjectArgs to_parts; + to_parts.keep_lower = false; + to_parts.to_parts = true; + CHECK(cut_attributes(to_parts, false, false) == + (Attribute::KeepUpper | Attribute::KeepLower | Attribute::KeepAsParts | Attribute::InvalidateCutInfo)); + + // An object cut before keeps its cut id, so its pieces stay one cut with the earlier ones. + CHECK(cut_attributes(defaults, false, true) == (Attribute::KeepUpper | Attribute::KeepLower | Attribute::PlaceOnCutUpper)); +} + +TEST_CASE("a cut is refused where the plane misses the object or the object has connectors", "[Operations][Gizmos]") +{ + Slic3r::Model model; + const Slic3r::ModelObject& cube = *placed_cube(model); + const Slic3r::Vec3d up = Slic3r::Vec3d::UnitZ(); + // Through the cube, level or tilted. + CHECK(cut_refusal_code(cube, {100., 100., 10.}, up).empty()); + CHECK(cut_refusal_code(cube, {100., 100., 10.}, {1., 0., 1.}).empty()); + // Above it, below it, and on its top and bottom faces, all of it lies on one side. + CHECK(cut_refusal_code(cube, {100., 100., 50.}, up) == "plane_misses_object"); + CHECK(cut_refusal_code(cube, {100., 100., -5.}, up) == "plane_misses_object"); + CHECK(cut_refusal_code(cube, {100., 100., 20.}, up) == "plane_misses_object"); + CHECK(cut_refusal_code(cube, {100., 100., 0.}, up) == "plane_misses_object"); + // A plane beside it, upright. + CHECK(cut_refusal_code(cube, {130., 100., 10.}, Slic3r::Vec3d::UnitX()) == "plane_misses_object"); + // A zero normal gives no plane. + CHECK(cut_refusal_code(cube, {100., 100., 10.}, Slic3r::Vec3d::Zero()) == "plane_misses_object"); + + // Connectors are placed and cut in the Cut gizmo, whatever the plane. + Slic3r::ModelObject& with_connectors = *placed_cube(model); + with_connectors.cut_connectors.emplace_back(); + CHECK(cut_refusal_code(with_connectors, {100., 100., 10.}, up) == "has_connectors"); + + // A cut object left as one dowel connector, on which the Cut gizmo does not open. + Slic3r::ModelObject& dowel = *placed_cube(model); + dowel.cut_id.init(); + dowel.volumes.front()->cut_info = Slic3r::ModelVolume::CutInfo(Slic3r::CutConnectorType::Dowel, 0.f, 0.f, true); + CHECK(cut_refusal_code(dowel, {100., 100., 10.}, up) == "dowel_alone"); + + // Each refusal is one whole sentence a person can read. + const std::optional misses = cut_refusal(cube, 0, {100., 100., 50.}, up); + REQUIRE(misses.has_value()); + CHECK_FALSE(misses->msgid.empty()); +} + +TEST_CASE("a cut's matrix places the plane as the Cut gizmo places it", "[Operations][Gizmos]") +{ + using Catch::Matchers::WithinAbs; + Slic3r::Model model; + const Slic3r::ModelObject& cube = *placed_cube(model); + const auto same = [](const Slic3r::Vec3d& got, const Slic3r::Vec3d& want) { + INFO("got " << got.transpose() << ", expected " << want.transpose()); + CHECK((got - want).norm() < 1e-9); + }; + + // A level plane 12 mm above the bed: 2 mm above the instance's centre, and no turn. + const Slic3r::Transform3d level = cut_matrix(cube, 0, {100., 100., 12.}, Slic3r::Vec3d::UnitZ(), 0.); + same(level.translation(), {0., 0., 2.}); + CHECK(level.linear().isIdentity(1e-12)); + + // A plane through the centre facing (1, 0, 1): no translation, and the plane's +Z turned to the normal, about Y. + const Slic3r::Transform3d tilted = cut_matrix(cube, 0, {100., 100., 10.}, {1., 0., 1.}, 0.); + same(tilted.translation(), Slic3r::Vec3d::Zero()); + same(tilted.linear() * Slic3r::Vec3d::UnitZ(), Slic3r::Vec3d(1., 0., 1.).normalized()); + same(tilted.linear() * Slic3r::Vec3d::UnitY(), Slic3r::Vec3d::UnitY()); + + // An SLA object stands raised in the 3D view; its plane is lowered by the lift. + const Slic3r::Transform3d lifted = cut_matrix(cube, 0, {100., 100., 12.}, Slic3r::Vec3d::UnitZ(), 5.); + same(lifted.translation(), {0., 0., -3.}); + + // A plane facing straight down is the gizmo's Flip, a half turn about X. + const Slic3r::Transform3d down = cut_matrix(cube, 0, {100., 100., 10.}, -Slic3r::Vec3d::UnitZ(), 0.); + same(down.linear() * Slic3r::Vec3d::UnitY(), -Slic3r::Vec3d::UnitY()); + same(down.linear() * Slic3r::Vec3d::UnitX(), Slic3r::Vec3d::UnitX()); + CHECK_THAT(down.linear().determinant(), WithinAbs(1., 1e-12)); +} diff --git a/tools/mcp/test-entries/gizmos.md b/tools/mcp/test-entries/gizmos.md index 677ecf8fb1..ba492e4093 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, 87 checks · in `sweep.json` as `{"path": "test_gizmo_commands.py"}` +`test_gizmo_commands.py` · Python, 277 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`, @@ -504,8 +504,8 @@ upper first (`Plater::apply_cut_object_to_model`), each named as the object was. | # | Step | Objects after | Also checked | |---|---|---|---| | 0 | start | A (100, 100, 10) size [20, 20, 20], one part 8000 | | -| 1 | `object_cut {object: 0}` | as after 0 | reply `gizmo` "Cut", `active` true; `gizmo()` Cut; no undo step | -| 2 | `object_cut {object: 0, z: 10}` | A [20, 20, 10] 4000 · A [20, 20, 10] 4000, both `bbox` x and y 90–110 | `gizmo()` none: the open Cut gizmo was closed first; reply `pieces` [{index 0, name "A", open_edges 0}, {index 1, name "A", open_edges 0}]; undo steps ["Cut by Plane"] | +| 1 | `object_cut {object: 0}` | as after 0 | reply `gizmo` "Cut", `active` true; `gizmo()` Cut; undo steps ["Entering Cut gizmo"], the step the Cut gizmo records as it opens, as for a click on its icon | +| 2 | `object_cut {object: 0, z: 10}` | A [20, 20, 10] 4000 · A [20, 20, 10] 4000, both `bbox` x and y 90–110 | `gizmo()` none: the open Cut gizmo was closed first; reply `pieces` [{index 0, name "A", open_edges 0}, {index 1, name "A", open_edges 0}]; undo steps ["Leaving Cut gizmo", "Cut by Plane"]: the gizmo's own step as it closes, then the cut's | | 3 | `undo` | as after 0 | | | 4 | `redo` | as after 2 | | | 5 | `undo` | as after 0 | | diff --git a/tools/mcp/test_gizmo_commands.py b/tools/mcp/test_gizmo_commands.py index ecd3fa2d4e..800acdd465 100644 --- a/tools/mcp/test_gizmo_commands.py +++ b/tools/mcp/test_gizmo_commands.py @@ -6,10 +6,11 @@ tools/mcp/test-entries/gizmos.md designs them. tools/mcp/test_gizmo_commands.py [scenario ...] A call that names only its target opens the gizmo on it, and the same call again leaves it open; a refused opening -leaves the model, the gizmo and the selection as it found them. After every step the test reads the state back through -another tool (object_list, app_state) and compares it with the values the entry writes out. It runs on the harness's -default printer, the Bambu Lab X1 Carbon 0.4, and exits 0 when every check passes. Scenario names given on the command -line run those scenarios alone. +leaves the model, the gizmo and the selection as it found them. A call with an acting argument (object_cut's plane) +closes the open gizmo and does the job as the gizmo's own button would, one undo step. After every step the test reads +the state back through another tool (object_list, app_state, the undo log, the saved project) and compares it with the +values the entry writes out. It runs on the harness's default printer, the Bambu Lab X1 Carbon 0.4, and exits 0 when +every check passes. Scenario names given on the command line run those scenarios alone. """ import os @@ -56,11 +57,24 @@ class GizmoCommandsTest: def scene(self): """Each object of object_list in index order as {name, offset, parts}: its instance 0's offset, its parts' count.""" - listing = self.c.call("object_list", limit=500) - objs = sorted([o for p in listing["plates"] for o in p["objects"]] + listing.get("outside", []), - key=lambda o: o["index"]) return [{"name": o["name"], "offset": [round(v, 3) for v in o["instances"][0]["offset"]], "parts": len(o["parts"])} - for o in objs] + for o in self.listed()] + + def listed(self): + """object_list's objects, on the plates and outside them, in index order.""" + listing = self.c.call("object_list", limit=500) + return sorted([o for p in listing["plates"] for o in p["objects"]] + listing.get("outside", []), + key=lambda o: o["index"]) + + def shapes(self): + """Each object in index order as {name, offset, min, max, size, parts}: its instance 0's offset and bbox, and its + parts as (type, mesh_volume).""" + out = [] + for o in self.listed(): + inst = o["instances"][0] + out.append({"name": o["name"], "offset": inst["offset"], "min": inst["bbox"]["min"], "max": inst["bbox"]["max"], + "size": inst["bbox"]["size"], "parts": [(p["type"], p["mesh_volume"]) for p in o["parts"]]}) + return out def gizmo(self): g = self.c.call("app_state").get("gizmo") @@ -194,10 +208,146 @@ class GizmoCommandsTest: refused(5, {"objects": [1], "instances": [[1, 0]]}, "part_boolean", {"object": 0}, "needs_two_parts", before_gizmo={"name": "FdmSupports", "canvas": "3d"}, steps=["Leaving Paint-on supports"]) + # ---- Cut ---- + + def undo(self): + self.run("undo", history="project") + + def redo(self): + self.run("redo", history="project") + + def save_and_reopen(self, name): + path = os.path.join(self.folder, name) + self.run("project_save", path=path, overwrite=True) + self.run("project_new", discard_changes=True) + self.run("project_open", path=path) + self.idle() + + def piece(self, label, o, volumes, size=None, height=None, xy=None, x=None): + """Checks one object of shapes(): its parts' types and mesh volumes (to 1 mm³), that it rests on the bed, and + when given its bbox size, its height, its x and y range [x0, y0, x1, y1], or its x range [x0, x1] (to 0.01).""" + self.t.equal(f"{label}: the parts' types", [t for t, _ in o["parts"]], ["part"] * len(volumes)) + self.t.near(f"{label}: the parts' mesh volumes", [v for _, v in o["parts"]], list(volumes), 1) + self.t.near(f"{label}: rests on the bed", o["min"][2], 0, 0.01) + if size is not None: + self.t.near(f"{label}: the size", o["size"], size, 0.01) + if height is not None: + self.t.near(f"{label}: the height", o["size"][2], height, 0.01) + if xy is not None: + self.t.near(f"{label}: the x and y range", [o["min"][0], o["min"][1], o["max"][0], o["max"][1]], xy, 0.01) + if x is not None: + self.t.near(f"{label}: the x range", [o["min"][0], o["max"][0]], x, 0.01) + + def whole(self, label): + """The 20 mm cube A at (100, 100), as after the cut scenarios' row 0.""" + objs = self.shapes() + if self.t.equal(f"{label}: the objects", [o["name"] for o in objs], ["A"]): + self.t.near(f"{label}: A's offset", objs[0]["offset"], [100, 100, 10], 0.01) + self.piece(f"{label}: A", objs[0], [8000], size=[20, 20, 20]) + + def halves(self, label): + """A cut level at z 10: two pieces 10 mm high where A stood, upper first.""" + objs = self.shapes() + if self.t.equal(f"{label}: the objects", [o["name"] for o in objs], ["A", "A"]): + for o, which in zip(objs, ("upper", "lower")): + self.piece(f"{label}: the {which} piece", o, [4000], size=[20, 20, 10], xy=[90, 90, 110, 110]) + + @staticmethod + def pieces_reply(reply): + return [{k: p.get(k) for k in ("index", "name", "open_edges")} for p in reply.get("pieces", [])] + + def cut(self): + s = "cut from arguments" + self.start(s) + self.cube([100, 100], name="A") + self.run("object_select", none=True) + self.whole(f"{s} 0") + + undo_steps(self.c) + reply = self.run("object_cut", object=0) + self.t.equal(f"{s} 1: the reply", (reply.get("gizmo"), reply.get("active")), ("Cut", True)) + self.t.equal(f"{s} 1: the Cut gizmo open", self.gizmo(), {"name": "Cut", "canvas": "3d"}) + # The Cut gizmo records a step of its own as it opens, as for a click on its icon. + self.t.equal(f"{s} 1: the undo steps", undo_steps(self.c), ["Entering Cut gizmo"]) + self.whole(f"{s} 1") + + reply = self.run("object_cut", object=0, z=10) + self.halves(f"{s} 2") + self.t.equal(f"{s} 2: the open Cut gizmo was closed first", self.gizmo(), None) + self.t.equal(f"{s} 2: the reply", self.pieces_reply(reply), + [{"index": 0, "name": "A", "open_edges": 0}, {"index": 1, "name": "A", "open_edges": 0}]) + # The gizmo's own step as it closes, then the cut's. + self.t.equal(f"{s} 2: the undo steps", undo_steps(self.c), ["Leaving Cut gizmo", "Cut by Plane"]) + self.undo() + self.whole(f"{s} 3") + self.redo() + self.halves(f"{s} 4") + self.undo() + self.whole(f"{s} 5") + + reply = self.run("object_cut", object=0, plane={"point": [100, 100, 10], "normal": [1, 0, 1]}) + objs = self.shapes() + if self.t.equal(f"{s} 6: the objects", [o["name"] for o in objs], ["A", "A"]): + # The plane x + z = 110 halves the cube into two prisms: the upper one lies on its cut face, its far edge + # 10√2 mm above it; the lower one stays as cut. + self.piece(f"{s} 6: the upper piece", objs[0], [4000], height=14.14) + self.piece(f"{s} 6: the lower piece", objs[1], [4000], size=[20, 20, 20], x=[90, 110]) + self.t.equal(f"{s} 6: the reply", [(p["index"], p["open_edges"]) for p in self.pieces_reply(reply)], [(0, 0), (1, 0)]) + self.undo() + self.whole(f"{s} 7") + + reply = self.run("object_cut", object=0, z=10, keep="upper") + objs = self.shapes() + if self.t.equal(f"{s} 8: the objects", [o["name"] for o in objs], ["A"]): + self.piece(f"{s} 8: the upper piece", objs[0], [4000], size=[20, 20, 10]) + self.t.equal(f"{s} 8: the reply", self.pieces_reply(reply), [{"index": 0, "name": "A", "open_edges": 0}]) + self.undo() + self.whole(f"{s} 9") + + reply = self.run("object_cut", object=0, z=10, to_parts=True) + objs = self.shapes() + if self.t.equal(f"{s} 10: the objects", [o["name"] for o in objs], ["A"]): + self.piece(f"{s} 10: A", objs[0], [4000, 4000], size=[20, 20, 20], xy=[90, 90, 110, 110]) + self.t.equal(f"{s} 10: the reply's object", {k: reply.get("object", {}).get(k) for k in ("index", "name")}, + {"index": 0, "name": "A"}) + self.t.equal(f"{s} 10: the reply's parts", len(reply.get("parts", [])), 2) + self.undo() + self.whole(f"{s} 11") + + self.run("object_cut", object=0, z=10) + self.halves(f"{s} 12") + self.save_and_reopen("cut.3mf") + self.halves(f"{s} 13: saved and reopened") + + def refused_cuts(self): + s = "cuts refused" + self.start(s) + self.cube([100, 100], name="A") + self.run("object_select", none=True) + self.whole(f"{s} 0") + plane = {"point": [100, 100, 10], "normal": [0, 0, 1]} + rows = [ + (1, {"z": 50}, "plane_misses_object", None), + (2, {"keep": "upper"}, "needs_plane", None), + (3, {"z": 10, "plane": plane}, None, "z or plane, not both"), + (4, {"plane": {"point": [100, 100, 10], "normal": [0, 0, 0]}}, None, "normal is zero"), + (5, {"z": 10, "keep": "upper", "lower": "flip"}, None, "the lower piece is not kept"), + (6, {"z": 10, "keep": "upper", "to_parts": True}, None, "to_parts keeps both pieces"), + (7, {"z": 10, "to_parts": True, "upper": "flip"}, None, "to_parts places no piece"), + ] + for row, args, code, words in rows: + undo_steps(self.c) + self.t.refused(f"{s} {row}: refused", lambda: self.c.call("object_cut", object=0, **args), code=code, + words=words) + self.whole(f"{s} {row}") + 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), []) + 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)] + scenarios = [("opening a gizmo on a target", self.opening), ("openings refused", self.refused_openings), + ("cut from arguments", self.cut), ("cuts refused", self.refused_cuts)] for name, scenario in scenarios: if not only or name in only: self.t.scenario(name, scenario)