From 19a454746ac588094514fa3a590ddb94489f0b8b Mon Sep 17 00:00:00 2001 From: Harry-Loud Date: Thu, 21 May 2026 11:11:32 +0100 Subject: [PATCH 01/38] Add multiple and height-aware bed exclusion volumes Extend bed exclusion handling so the existing bed_exclude_area field can express multiple independent exclusion regions and optional Z-limited volumes while keeping the original XxY polygon syntax backward compatible. The parser now accepts | separated regions and ZMIN..ZMAX; prefixed polygons. Legacy 2D regions are normalized internally as full-height exclusion volumes, and Z bounds may be omitted to default to the bed surface or printable height. Collision handling now uses a broad 2D convex-hull footprint check as a cheap initiator, followed by direct model-triangle clipping against triangulated exclusion prisms. This removes false positives where a model shadow overlaps an exclusion footprint but the mesh does not intersect the configured Z range. The plater preview renders bed-level regions with the existing grey floor preview, above-bed volumes with an inset grey outline, contextual translucent prism previews, and red mesh highlights for exact intersecting triangles. Preview cache keys include Z ranges and instance transforms so Z-only edits update correctly. --- src/libslic3r/Config.hpp | 103 +++++- src/libslic3r/GCode.cpp | 3 + src/libslic3r/GCode/GCodeProcessor.cpp | 2 +- src/libslic3r/Model.cpp | 236 ++++++++++++- src/libslic3r/Model.hpp | 1 + src/libslic3r/Preset.cpp | 7 +- src/libslic3r/Print.cpp | 72 ++-- src/libslic3r/PrintConfig.cpp | 219 +++++++++++- src/libslic3r/PrintConfig.hpp | 11 + src/slic3r/GUI/ConfigValueFormatter.cpp | 2 +- src/slic3r/GUI/ConfigWizard.cpp | 2 +- src/slic3r/GUI/Field.cpp | 28 +- src/slic3r/GUI/GLCanvas3D.cpp | 4 + src/slic3r/GUI/GUI.cpp | 12 + src/slic3r/GUI/OptionsGroup.cpp | 4 +- src/slic3r/GUI/PartPlate.cpp | 452 +++++++++++++++++++++++- src/slic3r/GUI/PartPlate.hpp | 12 + src/slic3r/GUI/Plater.cpp | 12 +- 18 files changed, 1102 insertions(+), 80 deletions(-) diff --git a/src/libslic3r/Config.hpp b/src/libslic3r/Config.hpp index ea85cda1e7..675bf54275 100644 --- a/src/libslic3r/Config.hpp +++ b/src/libslic3r/Config.hpp @@ -27,6 +27,7 @@ #include #include +#include #include // The serialize() members below archive ConfigOption hierarchies through // cereal::base_class, whose registration machinery lives in polymorphic.hpp. @@ -1546,14 +1547,34 @@ public: ConfigOptionType type() const override { return static_type(); } ConfigOption* clone() const override { return new ConfigOptionPoints(*this); } ConfigOptionPoints& operator= (const ConfigOption *opt) { this->set(opt); return *this; } - using ConfigOptionVector::operator==; - bool operator==(const ConfigOptionPoints &rhs) const throw() { return this->values == rhs.values; } + bool operator==(const ConfigOptionPoints &rhs) const throw() { return this->values == rhs.values && m_serialized_override == rhs.m_serialized_override; } + bool operator==(const ConfigOption &rhs) const override + { + if (rhs.type() != this->type()) + throw ConfigurationError("ConfigOptionPoints: Comparing incompatible types"); + assert(dynamic_cast(&rhs)); + const ConfigOptionPoints *other = static_cast(&rhs); + return this->values == other->values && m_serialized_override == other->m_serialized_override; + } bool operator< (const ConfigOptionPoints &rhs) const throw() { return std::lexicographical_compare(this->values.begin(), this->values.end(), rhs.values.begin(), rhs.values.end(), [](const auto &l, const auto &r){ return l < r; }); } bool is_nil(size_t) const override { return false; } + void set(const ConfigOption *rhs) override + { + if (rhs->type() != this->type()) + throw ConfigurationError("ConfigOptionPoints: Assigning an incompatible type"); + assert(dynamic_cast(rhs)); + const ConfigOptionPoints *other = static_cast(rhs); + this->values = other->values; + m_serialized_override = other->m_serialized_override; + } + std::string serialize() const override { + if (! m_serialized_override.empty()) + return m_serialized_override; + std::ostringstream ss; for (Pointfs::const_iterator it = this->values.begin(); it != this->values.end(); ++it) { if (it - this->values.begin() != 0) ss << ","; @@ -1566,6 +1587,9 @@ public: std::vector vserialize() const override { + if (! m_serialized_override.empty()) + return { m_serialized_override }; + std::vector vv; for (Pointfs::const_iterator it = this->values.begin(); it != this->values.end(); ++it) { std::ostringstream ss; @@ -1581,9 +1605,32 @@ public: bool deserialize(const std::string &str, bool append = false) override { - if (! append) + if (! append) { this->values.clear(); - std::istringstream is(str); + m_serialized_override.clear(); + } + + const bool has_z_volume_syntax = str.find("..") != std::string::npos && str.find(';') != std::string::npos; + if (has_z_volume_syntax && ! append) + m_serialized_override = str; + + std::string points_str = str; + if (has_z_volume_syntax) { + std::ostringstream points; + std::istringstream regions(str); + std::string region; + while (std::getline(regions, region, '|')) { + const size_t sep = region.find(';'); + if (sep == std::string::npos) + continue; + if (points.tellp() > 0) + points << ","; + points << region.substr(sep + 1); + } + points_str = points.str(); + } + + std::istringstream is(points_str); std::string point_str; while (std::getline(is, point_str, ',')) { Vec2d point(Vec2d::Zero()); @@ -1600,21 +1647,45 @@ public: return true; } + size_t hash() const throw() override + { + size_t seed = 0; + std::hash point_hasher; + std::hash string_hasher; + for (const Vec2d &point : this->values) + boost::hash_combine(seed, point_hasher(point)); + boost::hash_combine(seed, string_hasher(m_serialized_override)); + return seed; + } + private: - friend class cereal::access; - template void save(Archive& archive) const { - size_t cnt = this->values.size(); - archive(cnt); - archive.saveBinary((const char*)this->values.data(), sizeof(Vec2d) * cnt); - } - template void load(Archive& archive) { - size_t cnt; - archive(cnt); - this->values.assign(cnt, Vec2d()); - archive.loadBinary((char*)this->values.data(), sizeof(Vec2d) * cnt); - } + std::string m_serialized_override; + + friend class cereal::access; + template void save(Archive& archive, const std::uint32_t /* version */) const { + size_t cnt = this->values.size(); + archive(cnt); + archive.saveBinary((const char*)this->values.data(), sizeof(Vec2d) * cnt); + archive(m_serialized_override); + } + template void load(Archive& archive, const std::uint32_t version) { + size_t cnt; + archive(cnt); + this->values.assign(cnt, Vec2d()); + archive.loadBinary((char*)this->values.data(), sizeof(Vec2d) * cnt); + if (version >= 1) + archive(m_serialized_override); + else + m_serialized_override.clear(); + } }; +} // namespace Slic3r + +CEREAL_CLASS_VERSION(Slic3r::ConfigOptionPoints, 1); + +namespace Slic3r { + class ConfigOptionPoint3 : public ConfigOptionSingle { public: diff --git a/src/libslic3r/GCode.cpp b/src/libslic3r/GCode.cpp index 4aa45a60ed..5e93ec7eb0 100644 --- a/src/libslic3r/GCode.cpp +++ b/src/libslic3r/GCode.cpp @@ -246,6 +246,9 @@ static std::vector get_path_of_change_filament(const Print& print) Vec2d end_point = points[1]; // the cutter area size(18, 28) + if (has_bed_exclusion_volume_syntax(print.config().bed_exclude_area)) + return out_points; + Pointfs excluse_area = print.config().bed_exclude_area.values; if (excluse_area.size() != 4) return out_points; diff --git a/src/libslic3r/GCode/GCodeProcessor.cpp b/src/libslic3r/GCode/GCodeProcessor.cpp index e4da19cd73..0a65508350 100644 --- a/src/libslic3r/GCode/GCodeProcessor.cpp +++ b/src/libslic3r/GCode/GCodeProcessor.cpp @@ -3165,7 +3165,7 @@ void GCodeProcessor::apply_config(const DynamicPrintConfig& config) //BBS: add bed_exclude_area const ConfigOptionPoints* bed_exclude_area = config.option("bed_exclude_area"); - if (bed_exclude_area != nullptr) + if (bed_exclude_area != nullptr && !has_bed_exclusion_volume_syntax(*bed_exclude_area)) m_result.bed_exclude_area = bed_exclude_area->values; const ConfigOptionPoints* wrapping_exclude_area = config.option("wrapping_exclude_area"); diff --git a/src/libslic3r/Model.cpp b/src/libslic3r/Model.cpp index 714d45ad9b..65479806d0 100644 --- a/src/libslic3r/Model.cpp +++ b/src/libslic3r/Model.cpp @@ -13,6 +13,7 @@ #include "TriangleMeshSlicer.hpp" #include "TriangleSelector.hpp" #include "MaterialType.hpp" +#include "Tesselate.hpp" #include "Format/AMF.hpp" #include "Format/svg.hpp" @@ -22,6 +23,7 @@ #include "FaceDetector.hpp" #include "libslic3r/Geometry/ConvexHull.hpp" +#include "ClipperUtils.hpp" #include @@ -33,6 +35,7 @@ #include "SVG.hpp" #include +#include #include #include "GCodeWriter.hpp" @@ -3101,7 +3104,7 @@ void Model::setPrintSpeedTable(const DynamicPrintConfig& config, const PrintConf //auto print_config = print.config(); //printSpeedMap.bed_poly.points = get_bed_shape(*(wxGetApp().plater()->config())); printSpeedMap.bed_poly.points = get_bed_shape(config); - Pointfs excluse_area_points = print_config.bed_exclude_area.values; + Pointfs excluse_area_points = has_bed_exclusion_volume_syntax(print_config.bed_exclude_area) ? Pointfs{} : print_config.bed_exclude_area.values; Polygons exclude_polys; Polygon exclude_poly; for (int i = 0; i < excluse_area_points.size(); i++) { @@ -3112,7 +3115,8 @@ void Model::setPrintSpeedTable(const DynamicPrintConfig& config, const PrintConf exclude_poly.points.clear(); } } - printSpeedMap.bed_poly = diff({ printSpeedMap.bed_poly }, exclude_polys)[0]; + if (!exclude_polys.empty()) + printSpeedMap.bed_poly = diff({ printSpeedMap.bed_poly }, exclude_polys)[0]; } // find temperature of heatend and bed and matierial of an given extruder @@ -3408,6 +3412,234 @@ Polygon ModelInstance::convex_hull_2d() return convex_hull; } +namespace { + +struct ExclusionPrismFootprintTriangle +{ + std::array vertices; + Vec2d min = Vec2d::Zero(); + Vec2d max = Vec2d::Zero(); +}; + +static double cross_2d(const Vec2d &a, const Vec2d &b) +{ + return a.x() * b.y() - a.y() * b.x(); +} + +template +static std::vector clip_polygon_by_signed_distance(const std::vector &input, DistanceFn distance) +{ + constexpr double clip_epsilon = 1e-8; + constexpr double duplicate_epsilon_sq = 1e-16; + + std::vector output; + if (input.empty()) + return output; + + auto append_point = [&output, duplicate_epsilon_sq](const Vec3d &point) { + if (output.empty() || (output.back() - point).squaredNorm() > duplicate_epsilon_sq) + output.emplace_back(point); + }; + + Vec3d prev = input.back(); + double prev_distance = distance(prev); + bool prev_inside = prev_distance >= -clip_epsilon; + for (const Vec3d &curr : input) { + const double curr_distance = distance(curr); + const bool curr_inside = curr_distance >= -clip_epsilon; + + if (curr_inside != prev_inside) { + const double denom = prev_distance - curr_distance; + if (std::abs(denom) > clip_epsilon) { + const double t = prev_distance / denom; + append_point(prev + t * (curr - prev)); + } + } + if (curr_inside) + append_point(curr); + + prev = curr; + prev_distance = curr_distance; + prev_inside = curr_inside; + } + + if (output.size() > 1 && (output.front() - output.back()).squaredNorm() <= duplicate_epsilon_sq) + output.pop_back(); + + return output; +} + +static std::vector triangulated_prism_footprints(const Polygon &polygon) +{ + std::vector out; + if (polygon.points.size() < 3) + return out; + + ExPolygon expolygon; + expolygon.contour = polygon; + expolygon.contour.make_counter_clockwise(); + + std::vector triangles = triangulate_expolygon_2d(expolygon, NORMALS_UP); + if (triangles.empty()) { + triangles.reserve((polygon.points.size() - 2) * 3); + const Vec2d first(unscale(polygon.points.front().x()), unscale(polygon.points.front().y())); + for (size_t i = 1; i + 1 < polygon.points.size(); ++i) { + triangles.emplace_back(first); + triangles.emplace_back(unscale(polygon.points[i].x()), unscale(polygon.points[i].y())); + triangles.emplace_back(unscale(polygon.points[i + 1].x()), unscale(polygon.points[i + 1].y())); + } + } + + out.reserve(triangles.size() / 3); + for (size_t i = 0; i + 2 < triangles.size(); i += 3) { + ExclusionPrismFootprintTriangle tri; + tri.vertices = { triangles[i], triangles[i + 1], triangles[i + 2] }; + + const double area = cross_2d(tri.vertices[1] - tri.vertices[0], tri.vertices[2] - tri.vertices[0]); + if (std::abs(area) <= EPSILON) + continue; + if (area < 0.0) + std::swap(tri.vertices[1], tri.vertices[2]); + + tri.min = tri.vertices[0].cwiseMin(tri.vertices[1]).cwiseMin(tri.vertices[2]); + tri.max = tri.vertices[0].cwiseMax(tri.vertices[1]).cwiseMax(tri.vertices[2]); + out.emplace_back(std::move(tri)); + } + + return out; +} + +static bool triangle_bbox_intersects_prism_footprint(const Vec3d &p0, const Vec3d &p1, const Vec3d &p2, const ExclusionPrismFootprintTriangle &footprint) +{ + constexpr double bbox_epsilon = 1e-8; + const double tri_min_x = std::min({ p0.x(), p1.x(), p2.x() }); + const double tri_max_x = std::max({ p0.x(), p1.x(), p2.x() }); + const double tri_min_y = std::min({ p0.y(), p1.y(), p2.y() }); + const double tri_max_y = std::max({ p0.y(), p1.y(), p2.y() }); + + return tri_max_x >= footprint.min.x() - bbox_epsilon && + tri_min_x <= footprint.max.x() + bbox_epsilon && + tri_max_y >= footprint.min.y() - bbox_epsilon && + tri_min_y <= footprint.max.y() + bbox_epsilon; +} + +static std::vector clip_model_triangle_to_prism( + const Vec3d &p0, + const Vec3d &p1, + const Vec3d &p2, + const double z_min, + const double z_max, + const ExclusionPrismFootprintTriangle &footprint) +{ + std::vector clipped = { p0, p1, p2 }; + clipped = clip_polygon_by_signed_distance(clipped, [z_min](const Vec3d &p) { return p.z() - z_min; }); + clipped = clip_polygon_by_signed_distance(clipped, [z_max](const Vec3d &p) { return z_max - p.z(); }); + + for (size_t i = 0; i < footprint.vertices.size() && clipped.size() >= 3; ++i) { + const Vec2d &a = footprint.vertices[i]; + const Vec2d &b = footprint.vertices[(i + 1) % footprint.vertices.size()]; + const Vec2d edge = b - a; + clipped = clip_polygon_by_signed_distance(clipped, [a, edge](const Vec3d &p) { + return cross_2d(edge, Vec2d(p.x() - a.x(), p.y() - a.y())); + }); + } + + return clipped; +} + +static double polygon_3d_area2(const std::vector &polygon) +{ + if (polygon.size() < 3) + return 0.0; + + Vec3d normal = Vec3d::Zero(); + for (size_t i = 1; i + 1 < polygon.size(); ++i) + normal += (polygon[i] - polygon.front()).cross(polygon[i + 1] - polygon.front()); + return normal.norm(); +} + +static void append_clipped_polygon(indexed_triangle_set &out, const std::vector &polygon) +{ + if (polygon.size() < 3) + return; + + const int base = int(out.vertices.size()); + out.vertices.reserve(out.vertices.size() + polygon.size()); + for (const Vec3d &point : polygon) + out.vertices.emplace_back(point.cast()); + + out.indices.reserve(out.indices.size() + polygon.size() - 2); + for (size_t i = 1; i + 1 < polygon.size(); ++i) { + stl_triangle_vertex_indices tri; + tri << base, base + int(i), base + int(i + 1); + out.indices.emplace_back(tri); + } +} + +} // namespace + +bool ModelInstance::intersects_bed_exclude_region(const BedExcludeRegion ®ion, indexed_triangle_set *intersection_mesh) const +{ + if (intersection_mesh != nullptr) + intersection_mesh->clear(); + + if (region.polygon.points.size() < 3) + return false; + + double z_min = region.z_min; + double z_max = region.z_max; + if (z_min > z_max) + std::swap(z_min, z_max); + if (z_max <= z_min + EPSILON) + return false; + + const std::vector footprints = triangulated_prism_footprints(region.polygon); + if (footprints.empty()) + return false; + + bool intersects = false; + const ModelObject *model_object = get_object(); + const Transform3d instance_matrix = get_matrix(); + + for (const ModelVolume *volume : model_object->volumes) { + if (! volume->is_model_part()) + continue; + + const indexed_triangle_set &its = volume->mesh().its; + if (its.vertices.empty() || its.indices.empty()) + continue; + + const Transform3d volume_matrix = instance_matrix * volume->get_matrix(); + for (const stl_triangle_vertex_indices &face : its.indices) { + const Vec3d p0 = volume_matrix * its.vertices[face[0]].cast(); + const Vec3d p1 = volume_matrix * its.vertices[face[1]].cast(); + const Vec3d p2 = volume_matrix * its.vertices[face[2]].cast(); + + const double tri_min_z = std::min({ p0.z(), p1.z(), p2.z() }); + const double tri_max_z = std::max({ p0.z(), p1.z(), p2.z() }); + if (tri_max_z < z_min || tri_min_z > z_max) + continue; + + for (const ExclusionPrismFootprintTriangle &footprint : footprints) { + if (! triangle_bbox_intersects_prism_footprint(p0, p1, p2, footprint)) + continue; + + std::vector clipped = clip_model_triangle_to_prism(p0, p1, p2, z_min, z_max, footprint); + if (polygon_3d_area2(clipped) <= 1e-8) + continue; + + intersects = true; + if (intersection_mesh == nullptr) + return true; + + append_clipped_polygon(*intersection_mesh, clipped); + } + } + } + + return intersects; +} + //BBS: invalidate instance's convex_hull_2d void ModelInstance::invalidate_convex_hull_2d() { diff --git a/src/libslic3r/Model.hpp b/src/libslic3r/Model.hpp index 8da1340fa9..2af1150e30 100644 --- a/src/libslic3r/Model.hpp +++ b/src/libslic3r/Model.hpp @@ -1366,6 +1366,7 @@ public: double get_auto_brim_width() const; // BBS Polygon convex_hull_2d(); + bool intersects_bed_exclude_region(const BedExcludeRegion ®ion, indexed_triangle_set *intersection_mesh = nullptr) const; void invalidate_convex_hull_2d(); // Getting the input polygon for arrange diff --git a/src/libslic3r/Preset.cpp b/src/libslic3r/Preset.cpp index e974ffd7f8..27d953791a 100644 --- a/src/libslic3r/Preset.cpp +++ b/src/libslic3r/Preset.cpp @@ -1439,8 +1439,9 @@ static std::vector s_Preset_machine_limits_options { static std::vector s_Preset_printer_options { "printer_technology", - "printable_area", "extruder_printable_area", "support_parallel_printheads", "parallel_printheads_count", "parallel_printheads_bed_exclude_areas", "bed_exclude_area","bed_custom_texture", "bed_custom_model", "gcode_flavor", - "gcode_skip_config_block", "fan_kickstart", "part_cooling_fan_min_pwm", "fan_speedup_time", "fan_speedup_overhangs", + "printable_area", "extruder_printable_area", "support_parallel_printheads", "parallel_printheads_count", "parallel_printheads_bed_exclude_areas", + "bed_exclude_area", "bed_exclude_area_3d", "bed_custom_texture", "bed_custom_model", "gcode_flavor", + "gcode_skip_config_block", "fan_kickstart", "part_cooling_fan_min_pwm", "fan_speedup_time", "fan_speedup_overhangs", "single_extruder_multi_material", "manual_filament_change", "file_start_gcode", "machine_start_gcode", "machine_end_gcode", "before_layer_change_gcode", "printing_by_object_gcode", "layer_change_gcode", "time_lapse_gcode", "wrapping_detection_gcode", "change_filament_gcode", "change_extrusion_role_gcode", "printer_model", "printer_variant", "printer_extruder_id", "printer_extruder_variant", "extruder_variant_list", "default_nozzle_volume_type", "printable_height", "extruder_printable_height", "extruder_clearance_radius", "extruder_clearance_height_to_lid", "extruder_clearance_height_to_rod", @@ -3621,7 +3622,7 @@ inline t_config_option_keys deep_diff(const ConfigBase &config_this, const Confi if (this_opt != nullptr && other_opt != nullptr && *this_opt != *other_opt) { //BBS: add bed_exclude_area - if (opt_key == "printable_area" || opt_key == "bed_exclude_area" || opt_key == "compatible_prints" || opt_key == "compatible_printers" || opt_key == "thumbnails" || opt_key == "wrapping_exclude_area" || opt_key == "slicing_pipeline_plugin") { + if (opt_key == "printable_area" || opt_key == "bed_exclude_area" || opt_key == "bed_exclude_area_3d" || opt_key == "compatible_prints" || opt_key == "compatible_printers" || opt_key == "thumbnails" || opt_key == "wrapping_exclude_area" || opt_key == "slicing_pipeline_plugin") { // Scalar variable, or a vector variable, which is independent from number of extruders, // thus the vector is presented to the user as a single input. diff.emplace_back(opt_key); diff --git a/src/libslic3r/Print.cpp b/src/libslic3r/Print.cpp index 60f747ce04..8f0fb4dbfd 100644 --- a/src/libslic3r/Print.cpp +++ b/src/libslic3r/Print.cpp @@ -66,6 +66,43 @@ template class PrintState; PrintRegion::PrintRegion(const PrintRegionConfig &config) : PrintRegion(config, config.hash()) {} PrintRegion::PrintRegion(PrintRegionConfig &&config) : PrintRegion(std::move(config), config.hash()) {} +static std::vector translated_bed_exclusion_volumes(const Print &print) +{ + std::vector regions = get_bed_excluded_regions(print.config()); + const Point print_origin(scale_(print.get_plate_origin().x()), scale_(print.get_plate_origin().y())); + + for (BedExcludeRegion ®ion : regions) + region.polygon.translate(print_origin); + + return regions; +} + +static bool intersects_bed_exclusion_volume(const ModelInstance &instance, const std::vector ®ions) +{ + if (regions.empty()) + return false; + + Polygon hull = const_cast(instance).convex_hull_2d(); + for (const BedExcludeRegion ®ion : regions) { + if (intersection(Polygons{ region.polygon }, Polygons{ hull }).empty()) + continue; + + if (instance.intersects_bed_exclude_region(region)) + return true; + } + + return false; +} + +static Polygons full_height_bed_exclusion_polygons(const std::vector ®ions) +{ + Polygons out; + for (const BedExcludeRegion ®ion : regions) + if (! region.has_z_range) + out.emplace_back(region.polygon); + return out; +} + //BBS // ORCA: Now this is a parameter //float Print::min_skirt_length = 0; @@ -118,6 +155,7 @@ bool Print::invalidate_state_by_config_options(const ConfigOptionResolver & /* n "printable_area", //BBS: add bed_exclude_area "bed_exclude_area", + "bed_exclude_area_3d", "thumbnail_size", "before_layer_change_gcode", "enable_pressure_advance", @@ -648,10 +686,8 @@ StringObjectException Print::sequential_print_clearance_valid(const Print &print { StringObjectException single_object_exception; const auto& print_config = print.config(); - Polygons exclude_polys = get_bed_excluded_area(print_config); const Vec3d print_origin = print.get_plate_origin(); - std::for_each(exclude_polys.begin(), exclude_polys.end(), - [&print_origin](Polygon& p) { p.translate(scale_(print_origin.x()), scale_(print_origin.y())); }); + const std::vector exclusion_volumes = translated_bed_exclusion_volumes(print); struct print_instance_info { @@ -702,22 +738,17 @@ StringObjectException Print::sequential_print_clearance_valid(const Print &print // Convert the shift from the PrintObject's coordinates into ModelObject's coordinates by removing the centering offset. convex_hull.translate(instance.shift - print_object->center_offset()); } - convex_hull_no_offset.translate(instance.shift - print_object->center_offset()); - //juedge the exclude area - if (!intersection(exclude_polys, convex_hull_no_offset).empty()) { + if (intersects_bed_exclusion_volume(*instance.model_instance, exclusion_volumes)) { if (single_object_exception.string.empty()) { - single_object_exception.string = (boost::format(L("%1% is too close to exclusion area. There may be collisions when printing.")) %instance.model_instance->get_object()->name).str(); + single_object_exception.string = (boost::format(L("%1% is too close to exclusion volume, there may be collisions when printing.")) %instance.model_instance->get_object()->name).str(); // single_object_exception.object = instance.model_instance->get_object(); //ORCA: Pass ModelInstance instead of ModelObject single_object_exception.object = instance.model_instance; } else { - single_object_exception.string += "\n"+(boost::format(L("%1% is too close to exclusion area. There may be collisions when printing.")) %instance.model_instance->get_object()->name).str(); + single_object_exception.string += "\n" + (boost::format(L("%1% is too close to exclusion volume, there may be collisions when printing.")) % instance.model_instance->get_object()->name).str(); single_object_exception.object = nullptr; } - //if (polygons) { - // intersecting_idxs.emplace_back(convex_hulls_other.size()); - //} } // if output needed, collect indices (inside convex_hulls_other) of intersecting hulls @@ -970,10 +1001,9 @@ static StringObjectException layered_print_cleareance_valid(const Print &print, return {}; const auto& print_config = print.config(); - Polygons exclude_polys = get_bed_excluded_area(print_config); const Vec3d print_origin = print.get_plate_origin(); - std::for_each(exclude_polys.begin(), exclude_polys.end(), - [&print_origin](Polygon& p) { p.translate(scale_(print_origin.x()), scale_(print_origin.y())); }); + const std::vector exclusion_volumes = translated_bed_exclusion_volumes(print); + const Polygons prime_tower_exclude_polys = full_height_bed_exclusion_polygons(exclusion_volumes); Pointfs wrapping_detection_area = print_config.wrapping_exclude_area.values; Polygon wrapping_poly; @@ -993,14 +1023,6 @@ static StringObjectException layered_print_cleareance_valid(const Print &print, inst->model_instance->get_scaling_factor(), inst->model_instance->get_mirror())); volume_hull.translate(inst->shift - inst->print_object->center_offset()); - if (!intersection(exclude_polys, volume_hull).empty()) { - // return {inst->model_instance->get_object()->name + L(" is too close to exclusion area, there may be collisions when printing.") + "\n", - // inst->model_instance->get_object()}; - //ORCA: Pass ModelInstance instead of ModelObject - return {inst->model_instance->get_object()->name + L(" is too close to exclusion area, there may be collisions when printing.") + "\n", - inst->model_instance}; - } - if (print_config.enable_wrapping_detection.value && !intersection(wrapping_poly, volume_hull).empty()) { // return {inst->model_instance->get_object()->name + L(" is too close to clumping detection area, there may be collisions when printing.") + "\n", // inst->model_instance->get_object()}; @@ -1010,6 +1032,8 @@ static StringObjectException layered_print_cleareance_valid(const Print &print, } current_instance_hulls.emplace_back(volume_hull); } + if (intersects_bed_exclusion_volume(*inst->model_instance, exclusion_volumes)) + return {inst->model_instance->get_object()->name + L(" is too close to exclusion volume, there may be collisions when printing.") + "\n", inst->model_instance}; if (!intersection(convex_hulls_other, current_instance_hulls).empty()) { if (warning) { @@ -1093,13 +1117,13 @@ static StringObjectException layered_print_cleareance_valid(const Print &print, warning->string += L("Prime Tower") + L(" is too close to others, and collisions may be caused.\n"); } } - if (!intersection(exclude_polys, tower_polys_checked).empty()) { + if (!intersection(prime_tower_exclude_polys, tower_polys_checked).empty()) { return {L("Prime Tower") + L(" is too close to an exclusion area, and collisions will be caused.\n")}; } if (print_config.enable_wrapping_detection.value && !intersection({wrapping_poly}, tower_polys_checked).empty()) { return {L("Prime Tower") + L(" is too close to clumping detection area, and collisions will be caused.\n")}; } - if (warning && !intersection(exclude_polys, tower_polys_estimated).empty()) { + if (warning && !intersection(prime_tower_exclude_polys, tower_polys_estimated).empty()) { warning->string += L("Prime Tower") + L(" is too close to exclusion area, there may be collisions when printing.") + "\n"; } if (warning && print_config.enable_wrapping_detection.value && !intersection({wrapping_poly}, tower_polys_estimated).empty()) { diff --git a/src/libslic3r/PrintConfig.cpp b/src/libslic3r/PrintConfig.cpp index e8ac749bd3..ed3822f1a4 100644 --- a/src/libslic3r/PrintConfig.cpp +++ b/src/libslic3r/PrintConfig.cpp @@ -8,7 +8,10 @@ #include "format.hpp" #include "GCode/Thumbnails.hpp" +#include #include +#include +#include #include #include #include @@ -875,11 +878,21 @@ void PrintConfigDef::init_common_params() def = this->add("bed_exclude_area", coPoints); def->label = L("Excluded bed area"); def->tooltip = L("Unprintable area in XY plane. For example, X1 Series printers use the front left corner to cut filament during filament change. " - "The area is expressed as polygon by points in following format: \"XxY, XxY, ...\""); + "The area is expressed as polygon by points in following format: \"XxY, XxY, ...\". " + "Use \"ZMIN..ZMAX;XxY, XxY, ...\" for a 3D Z-limited exclusion volume. " + "Separate multiple areas or volumes with \"|\". "); def->mode = comAdvanced; def->gui_type = ConfigOptionDef::GUIType::one_string; def->set_default_value(new ConfigOptionPoints{ Vec2d(0, 0) }); + def = this->add("bed_exclude_area_3d", coString); + def->label = L("Bed exclusion volume"); + def->tooltip = L("Z-limited unprintable volumes. Use: \"ZMIN..ZMAX;XxY,XxY,...\". Separate multiple regions with \"|\". " + "Missing Z bounds default to the bed surface or printable height."); + def->mode = comAdvanced; + def->gui_type = ConfigOptionDef::GUIType::one_string; + def->set_default_value(new ConfigOptionString()); + def = this->add("bed_custom_texture", coString); def->label = L("Bed custom texture"); def->mode = comAdvanced; @@ -12725,8 +12738,212 @@ Points get_bed_shape(const PrintConfig &cfg, bool use_share) Points get_bed_shape(const SLAPrinterConfig &cfg) { return to_points(make_counter_clockwise(cfg.printable_area.values)); } +namespace { + +static bool is_bed_exclusion_volume_syntax(const std::string &value) +{ + return value.find("..") != std::string::npos && value.find(';') != std::string::npos; +} + +static bool parse_double_token(const std::string &text, double &out) +{ + std::string token = text; + boost::trim(token); + if (token.empty()) + return false; + + try { + size_t parsed = 0; + out = std::stod(token, &parsed); + return parsed == token.size(); + } catch (...) { + return false; + } +} + +static bool parse_z_range_token( + const std::string &token_in, + const double printable_height, + double &z_min, + double &z_max, + bool &has_z) +{ + std::string token = token_in; + boost::trim(token); + if (token.empty()) + return false; + + size_t range_pos = token.find(".."); + if (range_pos == std::string::npos) + return false; + + std::string min_token = token.substr(0, range_pos); + std::string max_token = token.substr(range_pos + 2); + boost::trim(min_token); + boost::trim(max_token); + + double parsed_min = 0.0; + double parsed_max = printable_height; + if (! min_token.empty() && ! parse_double_token(min_token, parsed_min)) + return false; + if (! max_token.empty() && ! parse_double_token(max_token, parsed_max)) + return false; + + z_min = std::clamp(parsed_min, 0.0, printable_height); + z_max = std::clamp(parsed_max, 0.0, printable_height); + has_z = true; + return z_min <= z_max; +} + +static std::optional parse_exclude_polygon_points(const std::string &points_str) +{ + ConfigOptionPoints points; + if (! points.deserialize(points_str) || points.values.size() < 3) + return std::nullopt; + + Polygon polygon; + polygon.points.reserve(points.values.size()); + for (const Vec2d &pt : points.values) + polygon.points.emplace_back(scale_(pt.x()), scale_(pt.y())); + polygon.make_counter_clockwise(); + return polygon; +} + +static void append_legacy_bed_exclude_regions( + std::vector &out, + const Pointfs &legacy_points, + const double printable_height) +{ + if (legacy_points.size() < 3) + return; + + Polygon polygon; + polygon.points.reserve(legacy_points.size()); + for (const Vec2d &pt : legacy_points) + polygon.points.emplace_back(scale_(pt.x()), scale_(pt.y())); + polygon.make_counter_clockwise(); + + out.push_back({ std::move(polygon), 0.0, printable_height, false, false }); +} + +static void append_bed_exclusion_volume_regions( + std::vector &out, + const std::string ®ion_specs_raw, + const double printable_height) +{ + std::vector region_specs; + boost::split(region_specs, region_specs_raw, boost::is_any_of("|\n")); + + for (const std::string &spec_raw : region_specs) { + std::string spec = spec_raw; + boost::trim(spec); + if (spec.empty()) + continue; + + std::vector fields; + boost::split(fields, spec, boost::is_any_of(";")); + + double z_min = 0.0; + double z_max = printable_height; + bool has_z_range = false; + std::string points_field; + bool invalid_z = false; + + for (std::string field : fields) { + boost::trim(field); + if (field.empty()) + continue; + + bool parsed_z_range = parse_z_range_token(field, printable_height, z_min, z_max, has_z_range); + if (parsed_z_range) + continue; + + if (field.find("..") != std::string::npos && field.find('x') == std::string::npos) { + invalid_z = true; + break; + } + + if (boost::algorithm::istarts_with(field, "points=")) + field = field.substr(std::string("points=").size()); + else if (boost::algorithm::istarts_with(field, "polygon=")) + field = field.substr(std::string("polygon=").size()); + + points_field = field; + } + + if (invalid_z) + continue; + + if (! has_z_range) { + z_min = 0.0; + z_max = printable_height; + } + + if (z_min > z_max) + continue; + + std::optional polygon = parse_exclude_polygon_points(points_field); + if (! polygon) + continue; + + out.push_back({ std::move(*polygon), z_min, z_max, true, has_z_range }); + } +} + +static std::vector get_bed_excluded_regions_impl( + const Pointfs &legacy_points, + const std::string ®ion_specs, + const double printable_height) +{ + std::vector regions; + const double height = std::max(0.0, printable_height); + append_legacy_bed_exclude_regions(regions, legacy_points, height); + append_bed_exclusion_volume_regions(regions, region_specs, height); + return regions; +} + +} // namespace + +std::vector get_bed_excluded_regions(const DynamicPrintConfig& cfg) +{ + const ConfigOptionPoints *legacy = cfg.opt("bed_exclude_area"); + const ConfigOptionString *regions = cfg.opt("bed_exclude_area_3d"); + const ConfigOptionFloat *height = cfg.opt("printable_height"); + const std::string bed_exclude_area = legacy != nullptr ? legacy->serialize() : std::string{}; + const bool volume_syntax = is_bed_exclusion_volume_syntax(bed_exclude_area); + + return get_bed_excluded_regions_impl( + volume_syntax || legacy == nullptr ? Pointfs{} : legacy->values, + volume_syntax ? bed_exclude_area : (regions != nullptr ? regions->value : std::string{}), + height != nullptr ? height->value : 0.0); +} + +std::vector get_bed_excluded_regions(const PrintConfig& cfg) +{ + const std::string bed_exclude_area = cfg.bed_exclude_area.serialize(); + const bool volume_syntax = is_bed_exclusion_volume_syntax(bed_exclude_area); + + return get_bed_excluded_regions_impl( + volume_syntax ? Pointfs{} : cfg.bed_exclude_area.values, + volume_syntax ? bed_exclude_area : cfg.bed_exclude_area_3d.value, + cfg.printable_height.value); +} + +bool has_bed_exclusion_volume_syntax(const ConfigOptionPoints& bed_exclude_area) +{ + return is_bed_exclusion_volume_syntax(bed_exclude_area.serialize()); +} + Polygons get_bed_excluded_area(const PrintConfig& cfg) { + if (is_bed_exclusion_volume_syntax(cfg.bed_exclude_area.serialize())) + return {}; + const std::vector regions = get_bed_excluded_regions(cfg); + if (std::any_of(regions.begin(), regions.end(), [](const BedExcludeRegion ®ion) { + return region.from_3d_config && region.has_z_range; + })) + return {}; + const Pointfs exclude_area_points = cfg.bed_exclude_area.values; Polygon exclude_poly; diff --git a/src/libslic3r/PrintConfig.hpp b/src/libslic3r/PrintConfig.hpp index 18e66adb34..a258c86206 100644 --- a/src/libslic3r/PrintConfig.hpp +++ b/src/libslic3r/PrintConfig.hpp @@ -1758,6 +1758,7 @@ PRINT_CONFIG_CLASS_DERIVED_DEFINE( ((ConfigOptionStrings, parallel_printheads_bed_exclude_areas)) //BBS: add bed_exclude_area ((ConfigOptionPoints, bed_exclude_area)) + ((ConfigOptionString, bed_exclude_area_3d)) ((ConfigOptionPoints, head_wrap_detect_zone)) // BBS ((ConfigOptionString, bed_custom_texture)) @@ -2303,6 +2304,16 @@ Polygon get_shared_poly(const std::vector& extruder_polys); Points get_bed_shape(const DynamicPrintConfig &cfg, bool use_share = true); Points get_bed_shape(const PrintConfig &cfg, bool use_share = false); Points get_bed_shape(const SLAPrinterConfig &cfg); +struct BedExcludeRegion { + Polygon polygon; + double z_min { 0.0 }; + double z_max { 0.0 }; + bool from_3d_config { false }; + bool has_z_range { false }; +}; +std::vector get_bed_excluded_regions(const DynamicPrintConfig& cfg); +std::vector get_bed_excluded_regions(const PrintConfig& cfg); +bool has_bed_exclusion_volume_syntax(const ConfigOptionPoints& bed_exclude_area); Slic3r::Polygons get_bed_excluded_area(const PrintConfig& cfg); Slic3r::Polygon get_bed_shape_with_excluded_area(const PrintConfig& cfg, bool use_share = false); bool has_skirt(const DynamicPrintConfig& cfg); diff --git a/src/slic3r/GUI/ConfigValueFormatter.cpp b/src/slic3r/GUI/ConfigValueFormatter.cpp index 6f9128841b..2f4d5e73c2 100644 --- a/src/slic3r/GUI/ConfigValueFormatter.cpp +++ b/src/slic3r/GUI/ConfigValueFormatter.cpp @@ -224,7 +224,7 @@ wxString get_string_value(const std::string& opt_key, const DynamicPrintConfig& return get_thumbnails_string(points.values); } else if (pure_key == "bed_exclude_area") { - return get_thumbnails_string(config.option(pure_key)->values); + return from_u8(config.option(pure_key)->serialize()); } else if (pure_key == "head_wrap_detect_zone") { return get_thumbnails_string(config.option(pure_key)->values); diff --git a/src/slic3r/GUI/ConfigWizard.cpp b/src/slic3r/GUI/ConfigWizard.cpp index 412df19091..c13486e554 100644 --- a/src/slic3r/GUI/ConfigWizard.cpp +++ b/src/slic3r/GUI/ConfigWizard.cpp @@ -2637,7 +2637,7 @@ ConfigWizard::ConfigWizard(wxWindow *parent) p->load_vendors(); //BBS: add bed exclude areas p->custom_config.reset(DynamicPrintConfig::new_from_defaults_keys({ - "gcode_flavor", "printable_area", "bed_exclude_area", "bed_custom_texture", "bed_custom_model", "nozzle_diameter", "filament_diameter", "thumbnails" + "gcode_flavor", "printable_area", "bed_exclude_area", "bed_exclude_area_3d", "bed_custom_texture", "bed_custom_model", "nozzle_diameter", "filament_diameter", "thumbnails" //, "nozzle_temperature", "bed_temperature" })); diff --git a/src/slic3r/GUI/Field.cpp b/src/slic3r/GUI/Field.cpp index 74ef3f87c8..de991ed116 100644 --- a/src/slic3r/GUI/Field.cpp +++ b/src/slic3r/GUI/Field.cpp @@ -734,11 +734,27 @@ void Field::get_value_by_opt_type(wxString& str, const bool check_value/* = true case coPoints: { std::vector out_values; str.Replace(" ", wxEmptyString, true); + const bool bed_exclusion_volume_syntax = m_opt_id == "bed_exclude_area" && str.Find("..") != wxNOT_FOUND && str.Find(";") != wxNOT_FOUND; + const wxString raw_str = str; + if (bed_exclusion_volume_syntax) { + wxString points; + wxStringTokenizer regions(str, "|"); + while (regions.HasMoreTokens()) { + wxString region = regions.GetNextToken(); + const int sep = region.Find(";"); + if (sep == wxNOT_FOUND) + continue; + if (! points.empty()) + points += ","; + points += region.Mid(sep + 1); + } + str = points; + } if (!str.IsEmpty()) { bool invalid_val = false; - wxStringTokenizer thumbnails(str, ","); - while (thumbnails.HasMoreTokens()) { - wxString token = thumbnails.GetNextToken(); + wxStringTokenizer points(str, ","); + while (points.HasMoreTokens()) { + wxString token = points.GetNextToken(); double x, y; wxStringTokenizer thumbnail(token, "x"); if (thumbnail.HasMoreTokens()) { @@ -757,14 +773,14 @@ void Field::get_value_by_opt_type(wxString& str, const bool check_value/* = true if (invalid_val) { wxString text_value; - if (!m_value.empty()) + if (!m_value.empty() && boost::any_cast>(&m_value) != nullptr) text_value = get_thumbnails_string(boost::any_cast>(m_value)); set_value(text_value, true); - show_error(m_parent, format_wxstr(_L("Invalid format. Expected vector format: \"%1%\""),"XxY, XxY, ..." )); + show_error(m_parent, format_wxstr(_L("Invalid format. Expected vector format: \"%1%\""), m_opt_id == "bed_exclude_area" ? "XxY, XxY, ... or ZMIN..ZMAX;XxY, XxY, ..." : "XxY, XxY, ...")); } } - m_value = out_values; + m_value = bed_exclusion_volume_syntax ? boost::any(into_u8(raw_str)) : boost::any(out_values); break; } default: diff --git a/src/slic3r/GUI/GLCanvas3D.cpp b/src/slic3r/GUI/GLCanvas3D.cpp index e63501eec1..e48192ba23 100644 --- a/src/slic3r/GUI/GLCanvas3D.cpp +++ b/src/slic3r/GUI/GLCanvas3D.cpp @@ -4316,6 +4316,8 @@ void GLCanvas3D::on_mouse(wxMouseEvent& evt) // It should be detection of volume change // Not only detection of some modifiers !!! if (evt.Dragging()) { + if (PartPlate *plate = wxGetApp().plater()->get_partplate_list().get_curr_plate()) + plate->clear_exclusion_volume_intersections(); GLGizmosManager::EType c = m_gizmos.get_current_type(); if (current_printer_technology() == ptFFF && (fff_print()->config().print_sequence == PrintSequence::ByObject)) { @@ -4516,6 +4518,8 @@ void GLCanvas3D::on_mouse(wxMouseEvent& evt) if (!m_mouse.drag.move_requires_threshold) { m_mouse.dragging = true; + if (PartPlate *plate = wxGetApp().plater()->get_partplate_list().get_curr_plate()) + plate->clear_exclusion_volume_intersections(); Vec3d cur_pos = m_mouse.drag.start_position_3D; // we do not want to translate objects if the user just clicked on an object while pressing shift to remove it from the selection and then drag if (m_selection.contains_volume(get_first_hover_volume_idx())) { diff --git a/src/slic3r/GUI/GUI.cpp b/src/slic3r/GUI/GUI.cpp index 78a511c90c..0838649d27 100644 --- a/src/slic3r/GUI/GUI.cpp +++ b/src/slic3r/GUI/GUI.cpp @@ -238,8 +238,20 @@ void change_opt_value(DynamicPrintConfig& config, const t_config_option_key& opt } break; case coPoints:{ + if (opt_key == "bed_exclude_area" && boost::any_cast(&value) != nullptr) { + config.option(opt_key)->deserialize(boost::any_cast(value)); + if (config.has("bed_exclude_area_3d")) + config.set_key_value("bed_exclude_area_3d", new ConfigOptionString()); + break; + } if (opt_key == "printable_area" || opt_key == "bed_exclude_area" || opt_key == "thumbnails" || opt_key == "wrapping_exclude_area" ) { config.option(opt_key)->values = boost::any_cast>(value); + if (opt_key == "bed_exclude_area") { + ConfigOptionPoints normalized(boost::any_cast>(value)); + config.option(opt_key)->deserialize(normalized.serialize()); + if (config.has("bed_exclude_area_3d")) + config.set_key_value("bed_exclude_area_3d", new ConfigOptionString()); + } break; } auto vec_new = std::make_unique(boost::any_cast(value)); diff --git a/src/slic3r/GUI/OptionsGroup.cpp b/src/slic3r/GUI/OptionsGroup.cpp index 99151ca599..1ca757eedc 100644 --- a/src/slic3r/GUI/OptionsGroup.cpp +++ b/src/slic3r/GUI/OptionsGroup.cpp @@ -1173,7 +1173,7 @@ boost::any ConfigOptionsGroup::get_config_value(const DynamicPrintConfig& config if (opt_key == "printable_area") ret = get_thumbnails_string(config.option(opt_key)->values); else if (opt_key == "bed_exclude_area") - ret = get_thumbnails_string(config.option(opt_key)->values); + ret = from_u8(config.option(opt_key)->serialize()); else if (opt_key == "wrapping_exclude_area") ret = get_thumbnails_string(config.option(opt_key)->values); else @@ -1284,7 +1284,7 @@ boost::any ConfigOptionsGroup::get_config_value2(const DynamicPrintConfig& confi if (opt_key == "printable_area") ret = get_thumbnails_string(config.option(opt_key)->values); else if (opt_key == "bed_exclude_area") - ret = get_thumbnails_string(config.option(opt_key)->values); + ret = from_u8(config.option(opt_key)->serialize()); else if (opt_key == "wrapping_exclude_area") ret = get_thumbnails_string(config.option(opt_key)->values); else diff --git a/src/slic3r/GUI/PartPlate.cpp b/src/slic3r/GUI/PartPlate.cpp index 893260f934..daa2d0f71c 100644 --- a/src/slic3r/GUI/PartPlate.cpp +++ b/src/slic3r/GUI/PartPlate.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include "libslic3r/MultiNozzleUtils.hpp" #include "libslic3r/FilamentMixer.hpp" #include @@ -23,6 +24,7 @@ #include "libslic3r/libslic3r.h" #include "libslic3r/Polygon.hpp" #include "libslic3r/GCode/WipeTowerEstimate.hpp" +#include "libslic3r/Polyline.hpp" #include "libslic3r/ClipperUtils.hpp" #include "libslic3r/BoundingBox.hpp" #include "libslic3r/Geometry.hpp" @@ -523,6 +525,144 @@ static bool init_model_from_lines(GLModel &model, const Lines3 &lines) return true; } +static ExPolygon expolygon_from_polygon(const Polygon &polygon) +{ + ExPolygon expolygon; + expolygon.contour = polygon; + expolygon.contour.make_counter_clockwise(); + return expolygon; +} + +static void append_expolygon_triangles(GLModel::Geometry &init_data, const ExPolygon &expolygon, float z) +{ + const std::vector triangles = triangulate_expolygon_2f(expolygon, NORMALS_UP); + if (triangles.empty() || triangles.size() % 3 != 0) + return; + + Vec2f min = triangles.front(); + Vec2f max = min; + for (const Vec2f &v : triangles) { + min = min.cwiseMin(v).eval(); + max = max.cwiseMax(v).eval(); + } + + const Vec2f size = max - min; + if (size.x() <= 0.0f || size.y() <= 0.0f) + return; + + Vec2f inv_size = size.cwiseInverse(); + inv_size.y() *= -1.0f; + + init_data.reserve_vertices(init_data.vertices_count() + triangles.size()); + init_data.reserve_indices(init_data.indices_count() + triangles.size()); + for (const Vec2f &v : triangles) { + init_data.add_vertex(Vec3f(v.x(), v.y(), z), (Vec2f)(v - min).cwiseProduct(inv_size).eval()); + const unsigned int vertices_counter = (unsigned int)init_data.vertices_count(); + if (vertices_counter % 3 == 0) + init_data.add_triangle(vertices_counter - 3, vertices_counter - 2, vertices_counter - 1); + } +} + +static bool init_model_from_polygons(GLModel &model, const Polygons &polygons, float z) +{ + model.reset(); + if (polygons.empty()) + return true; + + GLModel::Geometry init_data; + init_data.format = { GLModel::Geometry::EPrimitiveType::Triangles, GLModel::Geometry::EVertexLayout::P3T2 }; + + for (const Polygon &polygon : polygons) { + if (polygon.points.size() < 3) + continue; + + append_expolygon_triangles(init_data, expolygon_from_polygon(polygon), z); + } + + if (!init_data.is_empty()) + model.init_from(std::move(init_data)); + + return true; +} + +static bool init_model_from_expolygons(GLModel &model, const ExPolygons &expolygons, float z) +{ + model.reset(); + if (expolygons.empty()) + return true; + + GLModel::Geometry init_data; + init_data.format = { GLModel::Geometry::EPrimitiveType::Triangles, GLModel::Geometry::EVertexLayout::P3T2 }; + + for (const ExPolygon &expolygon : expolygons) { + if (expolygon.contour.points.size() < 3) + continue; + + append_expolygon_triangles(init_data, expolygon, z); + } + + if (!init_data.is_empty()) + model.init_from(std::move(init_data)); + + return true; +} + +struct ExclusionVolumePrismPreview +{ + Polygon footprint; + double z_min { 0.0 }; + double z_max { 0.0 }; +}; + +static bool init_exclusion_volume_prism_model(GLModel &model, const std::vector &prisms) +{ + model.reset(); + if (prisms.empty()) + return true; + + GLModel::Geometry init_data; + init_data.format = { GLModel::Geometry::EPrimitiveType::Triangles, GLModel::Geometry::EVertexLayout::P3 }; + + for (const ExclusionVolumePrismPreview &prism : prisms) { + const Polygon &polygon = prism.footprint; + const float z_min = static_cast(prism.z_min); + const float z_max = static_cast(prism.z_max); + if (polygon.points.size() < 3 || z_max <= z_min) + continue; + + init_data.reserve_vertices(init_data.vertices_count() + 4 * polygon.points.size()); + init_data.reserve_indices(init_data.indices_count() + 6 * polygon.points.size()); + for (size_t i = 0; i < polygon.points.size(); ++i) { + const Point &p0 = polygon.points[i]; + const Point &p1 = polygon.points[(i + 1) % polygon.points.size()]; + + init_data.add_vertex(Vec3f(unscale(p0.x()), unscale(p0.y()), z_min)); + init_data.add_vertex(Vec3f(unscale(p1.x()), unscale(p1.y()), z_min)); + init_data.add_vertex(Vec3f(unscale(p1.x()), unscale(p1.y()), z_max)); + init_data.add_vertex(Vec3f(unscale(p0.x()), unscale(p0.y()), z_max)); + + const unsigned int base = (unsigned int)init_data.vertices_count() - 4; + init_data.add_triangle(base, base + 1, base + 2); + init_data.add_triangle(base, base + 2, base + 3); + } + + const ExPolygon expolygon = expolygon_from_polygon(polygon); + const std::vector triangles = triangulate_expolygon_2f(expolygon, NORMALS_UP); + init_data.reserve_vertices(init_data.vertices_count() + triangles.size()); + init_data.reserve_indices(init_data.indices_count() + triangles.size()); + const unsigned int cap_base = (unsigned int)init_data.vertices_count(); + for (const Vec2f &v : triangles) + init_data.add_vertex(Vec3f(v.x(), v.y(), z_max)); + for (size_t i = 0; i + 2 < triangles.size(); i += 3) + init_data.add_triangle(cap_base + (unsigned int)i, cap_base + (unsigned int)i + 1, cap_base + (unsigned int)i + 2); + } + + if (!init_data.is_empty()) + model.init_from(std::move(init_data)); + + return true; +} + static void init_raycaster_from_model(PickingModel& model) { assert(model.mesh_raycaster == nullptr); @@ -966,6 +1106,259 @@ void PartPlate::render_exclude_area(bool force_default_color) { glsafe(::glDepthMask(GL_TRUE)); } +double PartPlate::max_broad_phase_intersecting_object_height(const Polygons& regions) const +{ + if (m_model == nullptr) + return 0.0; + + double max_height = 0.0; + + for (const std::pair &object_instance : obj_to_instance_set) { + const int obj_id = object_instance.first; + const int instance_id = object_instance.second; + if (obj_id < 0 || obj_id >= int(m_model->objects.size())) + continue; + + ModelObject *object = m_model->objects[obj_id]; + if (instance_id < 0 || instance_id >= int(object->instances.size())) + continue; + + ModelInstance *instance = object->instances[instance_id]; + if (!instance->printable) + continue; + + Polygon hull = instance->convex_hull_2d(); + bool intersects_region = false; + for (const Polygon ®ion : regions) { + if (!intersection(Polygons{ region }, Polygons{ hull }).empty()) { + intersects_region = true; + break; + } + } + + if (!intersects_region) + continue; + + const BoundingBoxf3 instance_box = object->instance_convex_hull_bounding_box(instance_id); + max_height = std::max(max_height, instance_box.max.z()); + } + + return max_height; +} + +std::string PartPlate::exclusion_volume_preview_cache_key(const std::vector ®ions) const +{ + std::ostringstream key; + key << std::setprecision(17); + key << "plate:" << m_origin.x() << ',' << m_origin.y() << ',' << m_height << ';'; + + key << "regions:" << regions.size() << ';'; + for (const BedExcludeRegion ®ion : regions) { + key << region.z_min << ".." << region.z_max << ':' + << region.from_3d_config << ':' << region.has_z_range << ':' + << region.polygon.points.size(); + for (const Point &point : region.polygon.points) + key << ',' << point.x() << 'x' << point.y(); + key << ';'; + } + + key << "instances:" << obj_to_instance_set.size() << ';'; + if (m_model != nullptr) { + for (const std::pair &object_instance : obj_to_instance_set) { + const int obj_id = object_instance.first; + const int instance_id = object_instance.second; + key << obj_id << ':' << instance_id << ':'; + if (obj_id < 0 || obj_id >= int(m_model->objects.size())) { + key << "invalid;"; + continue; + } + + const ModelObject *object = m_model->objects[obj_id]; + if (instance_id < 0 || instance_id >= int(object->instances.size())) { + key << "invalid;"; + continue; + } + + const ModelInstance *instance = object->instances[instance_id]; + key << static_cast(object) << ':' << static_cast(instance) << ':' + << object->volumes.size() << ':' << instance->printable << ':'; + + const Transform3d instance_matrix = instance->get_matrix(); + for (int r = 0; r < int(instance_matrix.matrix().rows()); ++r) + for (int c = 0; c < int(instance_matrix.matrix().cols()); ++c) + key << instance_matrix.matrix()(r, c) << ','; + + for (const ModelVolume *volume : object->volumes) { + key << static_cast(volume) << ':'; + const Transform3d volume_matrix = volume->get_matrix(); + for (int r = 0; r < int(volume_matrix.matrix().rows()); ++r) + for (int c = 0; c < int(volume_matrix.matrix().cols()); ++c) + key << volume_matrix.matrix()(r, c) << ','; + } + key << ';'; + } + } + + return key.str(); +} + +void PartPlate::update_exclusion_volume_preview_models() +{ + const DynamicPrintConfig *config = m_plater != nullptr ? m_plater->config() : nullptr; + if (config == nullptr) { + m_exclusion_volume_preview_cache_key.clear(); + m_exclusion_volume_floor_triangles.reset(); + m_exclusion_volume_border_triangles.reset(); + m_active_exclusion_volume_prisms.reset(); + m_exclusion_volume_intersection_triangles.reset(); + return; + } + + std::vector regions = get_bed_excluded_regions(*config); + const std::string cache_key = exclusion_volume_preview_cache_key(regions); + if (cache_key == m_exclusion_volume_preview_cache_key) + return; + m_exclusion_volume_preview_cache_key = cache_key; + + m_exclusion_volume_floor_triangles.reset(); + m_exclusion_volume_border_triangles.reset(); + m_active_exclusion_volume_prisms.reset(); + m_exclusion_volume_intersection_triangles.reset(); + + const Point plate_offset(scale_(m_origin.x()), scale_(m_origin.y())); + Polygons floor_regions; + ExPolygons border_regions; + const coord_t ribbon_width = scale_(1.6); + std::vector> preview_regions; + Polygons preview_footprints; + std::vector active_prisms; + + for (const BedExcludeRegion ®ion_src : regions) { + Polygon region = region_src.polygon; + region.translate(plate_offset); + region.make_counter_clockwise(); + BedExcludeRegion translated_region = region_src; + translated_region.polygon = region; + preview_regions.emplace_back(std::move(translated_region), region); + preview_footprints.emplace_back(region); + + if (region_src.from_3d_config) { + if (!region_src.has_z_range || region_src.z_min <= EPSILON) { + floor_regions.emplace_back(region); + } else { + const Polygons inner = offset(Polygons{ region }, -ribbon_width, jtMiter, 2.0); + ExPolygons border = inner.empty() ? ExPolygons{ expolygon_from_polygon(region) } : diff_ex(Polygons{ region }, inner); + border_regions.insert(border_regions.end(), border.begin(), border.end()); + } + } + } + + const double preview_height = max_broad_phase_intersecting_object_height(preview_footprints); + if (preview_height > EPSILON) { + for (const std::pair &preview_region : preview_regions) { + const BedExcludeRegion ®ion_src = preview_region.first; + const double z_min = region_src.has_z_range ? region_src.z_min : 0.0; + const double z_max = std::min(region_src.z_max, preview_height); + if (z_max > z_min + EPSILON) + active_prisms.push_back({ preview_region.second, z_min, z_max }); + } + } + + indexed_triangle_set intersection_triangles; + if (m_model != nullptr && !preview_regions.empty()) { + for (const std::pair &object_instance : obj_to_instance_set) { + const int obj_id = object_instance.first; + const int instance_id = object_instance.second; + if (obj_id < 0 || obj_id >= int(m_model->objects.size())) + continue; + + ModelObject *object = m_model->objects[obj_id]; + if (instance_id < 0 || instance_id >= int(object->instances.size())) + continue; + + ModelInstance *instance = object->instances[instance_id]; + if (!instance->printable) + continue; + + Polygon hull = instance->convex_hull_2d(); + const BoundingBoxf3 instance_box = object->instance_convex_hull_bounding_box(instance_id); + for (const std::pair &preview_region : preview_regions) { + const BedExcludeRegion ®ion = preview_region.first; + if (intersection(Polygons{ preview_region.second }, Polygons{ hull }).empty()) + continue; + if (instance_box.max.z() < region.z_min || instance_box.min.z() > region.z_max) + continue; + + indexed_triangle_set region_intersections; + if (instance->intersects_bed_exclude_region(region, ®ion_intersections) && !region_intersections.empty()) + its_merge(intersection_triangles, region_intersections); + } + } + } + + if (!floor_regions.empty() && !init_model_from_polygons(m_exclusion_volume_floor_triangles, floor_regions, GROUND_Z + 0.01f)) + BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << ":Unable to create exclusion volume floor preview triangles\n"; + + if (!border_regions.empty() && !init_model_from_expolygons(m_exclusion_volume_border_triangles, border_regions, GROUND_Z + 0.018f)) + BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << ":Unable to create exclusion volume preview border\n"; + + if (!active_prisms.empty() && !init_exclusion_volume_prism_model(m_active_exclusion_volume_prisms, active_prisms)) + BOOST_LOG_TRIVIAL(error) << __FUNCTION__ << ":Unable to create active exclusion volume preview prisms\n"; + + if (!intersection_triangles.empty()) + m_exclusion_volume_intersection_triangles.init_from(intersection_triangles); +} + +void PartPlate::render_exclusion_volume_previews(bool force_default_color) +{ + if (force_default_color) + return; + + update_exclusion_volume_preview_models(); + + const ColorRGBA floor_color = m_selected ? ColorRGBA{ .86f, .86f, .86f, .70f } : ColorRGBA{ .60f, .60f, .60f, .30f }; + const ColorRGBA ribbon_color{ .60f, .60f, .60f, .70f }; + const ColorRGBA prism_color{ .52f, .52f, .52f, .38f }; + + glsafe(::glDepthMask(GL_FALSE)); + + m_exclusion_volume_floor_triangles.set_color(floor_color); + m_exclusion_volume_floor_triangles.render(); + + m_exclusion_volume_border_triangles.set_color(ribbon_color); + m_exclusion_volume_border_triangles.render(); + + m_active_exclusion_volume_prisms.set_color(prism_color); + m_active_exclusion_volume_prisms.render(); + + render_exclusion_volume_intersections(); + + glsafe(::glLineWidth(1.0f * m_scale_factor)); + glsafe(::glDepthMask(GL_TRUE)); +} + +void PartPlate::render_exclusion_volume_intersections() +{ + if (!m_exclusion_volume_intersection_triangles.is_initialized()) + return; + + const ColorRGBA intersection_color{ .68f, .02f, .02f, .58f }; + + glsafe(::glEnable(GL_POLYGON_OFFSET_FILL)); + glsafe(::glPolygonOffset(-1.0f, -1.0f)); + + m_exclusion_volume_intersection_triangles.set_color(intersection_color); + m_exclusion_volume_intersection_triangles.render(); + + glsafe(::glDisable(GL_POLYGON_OFFSET_FILL)); +} + +void PartPlate::clear_exclusion_volume_intersections() +{ + m_exclusion_volume_intersection_triangles.reset(); +} + + /*void PartPlate::render_background_for_picking(const ColorRGBA render_color) const { unsigned int triangles_vcount = m_triangles.get_vertices_count(); @@ -2781,7 +3174,6 @@ bool PartPlate::check_outside(int obj_id, int instance_id, BoundingBoxf3* boundi ModelInstance* instance = object->instances[instance_id]; BoundingBoxf3 instance_box = bounding_box? *bounding_box: object->instance_convex_hull_bounding_box(instance_id); - Polygon hull = instance->convex_hull_2d(); BoundingBoxf3 plate_box = get_plate_box(); if (instance_box.max.z() > plate_box.min.z()) plate_box.min.z() += instance_box.min.z(); // not considering outsize if sinking @@ -2799,24 +3191,45 @@ bool PartPlate::check_outside(int obj_id, int instance_id, BoundingBoxf3* boundi else if (plate_box.contains(instance_box)) { - if (m_exclude_bounding_box.size() > 0) - { - Polygon hull = instance->convex_hull_2d(); - int index; - for (index = 0; index < m_exclude_bounding_box.size(); index ++) - { - Polygon p = m_exclude_bounding_box[index].polygon(true); // instance convex hull is scaled, so we need to scale here - if (intersection({ p }, { hull }).empty() == false) - //if (m_exclude_bounding_box[index].intersects(instance_box)) - { - break; - } - } - if (index >= m_exclude_bounding_box.size()) - outside = false; - } - else - outside = false; + outside = false; + const DynamicPrintConfig *config = m_plater != nullptr ? m_plater->config() : nullptr; + bool checked_config_regions = false; + if (config != nullptr) { + const std::vector regions = get_bed_excluded_regions(*config); + checked_config_regions = !regions.empty(); + const Point plate_offset(scale_(m_origin.x()), scale_(m_origin.y())); + Polygon hull = instance->convex_hull_2d(); + + for (const BedExcludeRegion ®ion_src : regions) { + Polygon region = region_src.polygon; + region.translate(plate_offset); + region.make_counter_clockwise(); + + if (intersection(Polygons{ region }, Polygons{ hull }).empty()) + continue; + + if (instance_box.max.z() < region_src.z_min || instance_box.min.z() > region_src.z_max) + continue; + + BedExcludeRegion translated_region = region_src; + translated_region.polygon = region; + if (instance->intersects_bed_exclude_region(translated_region)) { + outside = true; + break; + } + } + } + + if (!checked_config_regions && m_exclude_bounding_box.size() > 0) { + Polygon hull = instance->convex_hull_2d(); + for (const BoundingBoxf3 &exclude_box : m_exclude_bounding_box) { + Polygon p = exclude_box.polygon(true); // instance convex hull is scaled, so we need to scale here + if (!intersection({ p }, { hull }).empty()) { + outside = true; + break; + } + } + } } return outside; @@ -3536,6 +3949,7 @@ void PartPlate::render(const Transform3d& view_matrix, const Transform3d& projec } render_wrapping_detection_area(force_background_color); } + render_exclusion_volume_previews(force_background_color); } render_height_limit(mode); diff --git a/src/slic3r/GUI/PartPlate.hpp b/src/slic3r/GUI/PartPlate.hpp index e913ebaabf..a4679db69a 100644 --- a/src/slic3r/GUI/PartPlate.hpp +++ b/src/slic3r/GUI/PartPlate.hpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include @@ -133,6 +134,11 @@ private: PickingModel m_triangles; GLModel m_exclude_triangles; GLModel m_wrapping_detection_triangles; + GLModel m_exclusion_volume_floor_triangles; + GLModel m_exclusion_volume_border_triangles; + GLModel m_active_exclusion_volume_prisms; + GLModel m_exclusion_volume_intersection_triangles; + std::string m_exclusion_volume_preview_cache_key; GLModel m_logo_triangles; GLModel m_gridlines; GLModel m_gridlines_bolder; @@ -186,6 +192,11 @@ private: void render_logo(bool bottom, bool render_cali = true); void render_logo_texture(GLTexture &logo_texture, GLModel &logo_buffer, bool bottom); void render_exclude_area(bool force_default_color); + void render_exclusion_volume_previews(bool force_default_color); + void render_exclusion_volume_intersections(); + void update_exclusion_volume_preview_models(); + std::string exclusion_volume_preview_cache_key(const std::vector ®ions) const; + double max_broad_phase_intersecting_object_height(const Polygons& regions) const; //void render_background_for_picking(const ColorRGBA render_color) const; void render_grid(bool bottom); void render_wrapping_detection_area(bool force_default_color); @@ -381,6 +392,7 @@ public: //check whether instance is outside the plate or not bool check_outside(int obj_id, int instance_id, BoundingBoxf3* bounding_box = nullptr); + void clear_exclusion_volume_intersections(); //judge whether instance is intesected with plate or not bool intersect_instance(int obj_id, int instance_id, BoundingBoxf3* bounding_box = nullptr); diff --git a/src/slic3r/GUI/Plater.cpp b/src/slic3r/GUI/Plater.cpp index 0fdb9dcd94..e885b3a041 100644 --- a/src/slic3r/GUI/Plater.cpp +++ b/src/slic3r/GUI/Plater.cpp @@ -7331,7 +7331,7 @@ Plater::priv::priv(Plater *q, MainFrame *main_frame) , main_frame(main_frame) //BBS: add bed_exclude_area , config(Slic3r::DynamicPrintConfig::new_from_defaults_keys({ - "printable_area", "bed_exclude_area", "wrapping_exclude_area", "extruder_printable_area", "bed_custom_texture", "bed_custom_model", "print_sequence", + "printable_area", "bed_exclude_area", "bed_exclude_area_3d", "wrapping_exclude_area", "extruder_printable_area", "bed_custom_texture", "bed_custom_model", "print_sequence", "extruder_clearance_radius", "extruder_clearance_height_to_lid", "extruder_clearance_height_to_rod", "nozzle_height", "skirt_type", "skirt_loops", "skirt_speed","min_skirt_length", "skirt_distance", "skirt_start_angle", @@ -20090,7 +20090,7 @@ void Plater::on_config_change(const DynamicPrintConfig &config) p->partplate_list.invalid_all_slice_result(); } //BBS: add bed_exclude_area - else if (opt_key == "printable_area" || opt_key == "bed_exclude_area" + else if (opt_key == "printable_area" || opt_key == "bed_exclude_area" || opt_key == "bed_exclude_area_3d" || opt_key == "bed_custom_texture" || opt_key == "bed_custom_model" || opt_key == "extruder_clearance_height_to_lid" || opt_key == "extruder_clearance_height_to_rod") { @@ -20141,8 +20141,11 @@ void Plater::on_config_change(const DynamicPrintConfig &config) } } - if (bed_shape_changed) + if (bed_shape_changed) { set_bed_shape(); + get_current_canvas3D()->requires_check_outside_state(); + get_current_canvas3D()->request_extra_frame(); + } config_change_notification(config, std::string("print_sequence")); @@ -20213,9 +20216,10 @@ void Plater::set_bed_shape() const } } } + const ConfigOptionPoints *bed_exclude_area = p->config->option("bed_exclude_area"); set_bed_shape(p->config->option("printable_area")->values, //BBS: add bed exclude areas - p->config->option("bed_exclude_area")->values, + has_bed_exclusion_volume_syntax(*bed_exclude_area) ? Pointfs{} : bed_exclude_area->values, p->config->option("wrapping_exclude_area")->values, p->config->option("printable_height")->value, p->config->option("extruder_printable_area")->values, From ee593c2d5a02619dd32fb7a986132296ceffb0a1 Mon Sep 17 00:00:00 2001 From: Harry-Loud Date: Thu, 21 May 2026 11:32:56 +0100 Subject: [PATCH 02/38] Fix pipe-separated exclusion areas Treat pipe-separated bed_exclude_area strings as extended exclusion syntax even when no Z range is present. ConfigOptionPoints now preserves and parses plain multi-region strings like XxY,...|XxY,... instead of flattening them into a single polygon. Remove the stale bed_exclude_area_3d config option and related preset/UI plumbing now that Z-limited and multi-region exclusions are represented through the existing bed_exclude_area field. --- src/libslic3r/Config.hpp | 10 ++++------ src/libslic3r/Preset.cpp | 4 ++-- src/libslic3r/Print.cpp | 1 - src/libslic3r/PrintConfig.cpp | 15 +++------------ src/libslic3r/PrintConfig.hpp | 1 - src/slic3r/GUI/ConfigWizard.cpp | 2 +- src/slic3r/GUI/Field.cpp | 7 +++---- src/slic3r/GUI/GUI.cpp | 4 ---- src/slic3r/GUI/Plater.cpp | 4 ++-- 9 files changed, 15 insertions(+), 33 deletions(-) diff --git a/src/libslic3r/Config.hpp b/src/libslic3r/Config.hpp index 675bf54275..67c237d430 100644 --- a/src/libslic3r/Config.hpp +++ b/src/libslic3r/Config.hpp @@ -1610,22 +1610,20 @@ public: m_serialized_override.clear(); } - const bool has_z_volume_syntax = str.find("..") != std::string::npos && str.find(';') != std::string::npos; - if (has_z_volume_syntax && ! append) + const bool has_extended_bed_exclusion_syntax = str.find('|') != std::string::npos || (str.find("..") != std::string::npos && str.find(';') != std::string::npos); + if (has_extended_bed_exclusion_syntax && ! append) m_serialized_override = str; std::string points_str = str; - if (has_z_volume_syntax) { + if (has_extended_bed_exclusion_syntax) { std::ostringstream points; std::istringstream regions(str); std::string region; while (std::getline(regions, region, '|')) { const size_t sep = region.find(';'); - if (sep == std::string::npos) - continue; if (points.tellp() > 0) points << ","; - points << region.substr(sep + 1); + points << (sep == std::string::npos ? region : region.substr(sep + 1)); } points_str = points.str(); } diff --git a/src/libslic3r/Preset.cpp b/src/libslic3r/Preset.cpp index 27d953791a..0f5b30fb59 100644 --- a/src/libslic3r/Preset.cpp +++ b/src/libslic3r/Preset.cpp @@ -1440,7 +1440,7 @@ static std::vector s_Preset_machine_limits_options { static std::vector s_Preset_printer_options { "printer_technology", "printable_area", "extruder_printable_area", "support_parallel_printheads", "parallel_printheads_count", "parallel_printheads_bed_exclude_areas", - "bed_exclude_area", "bed_exclude_area_3d", "bed_custom_texture", "bed_custom_model", "gcode_flavor", + "bed_exclude_area", "bed_custom_texture", "bed_custom_model", "gcode_flavor", "gcode_skip_config_block", "fan_kickstart", "part_cooling_fan_min_pwm", "fan_speedup_time", "fan_speedup_overhangs", "single_extruder_multi_material", "manual_filament_change", "file_start_gcode", "machine_start_gcode", "machine_end_gcode", "before_layer_change_gcode", "printing_by_object_gcode", "layer_change_gcode", "time_lapse_gcode", "wrapping_detection_gcode", "change_filament_gcode", "change_extrusion_role_gcode", "printer_model", "printer_variant", "printer_extruder_id", "printer_extruder_variant", "extruder_variant_list", "default_nozzle_volume_type", @@ -3622,7 +3622,7 @@ inline t_config_option_keys deep_diff(const ConfigBase &config_this, const Confi if (this_opt != nullptr && other_opt != nullptr && *this_opt != *other_opt) { //BBS: add bed_exclude_area - if (opt_key == "printable_area" || opt_key == "bed_exclude_area" || opt_key == "bed_exclude_area_3d" || opt_key == "compatible_prints" || opt_key == "compatible_printers" || opt_key == "thumbnails" || opt_key == "wrapping_exclude_area" || opt_key == "slicing_pipeline_plugin") { + if (opt_key == "printable_area" || opt_key == "bed_exclude_area" || opt_key == "compatible_prints" || opt_key == "compatible_printers" || opt_key == "thumbnails" || opt_key == "wrapping_exclude_area" || opt_key == "slicing_pipeline_plugin") { // Scalar variable, or a vector variable, which is independent from number of extruders, // thus the vector is presented to the user as a single input. diff.emplace_back(opt_key); diff --git a/src/libslic3r/Print.cpp b/src/libslic3r/Print.cpp index 8f0fb4dbfd..bd953f1929 100644 --- a/src/libslic3r/Print.cpp +++ b/src/libslic3r/Print.cpp @@ -155,7 +155,6 @@ bool Print::invalidate_state_by_config_options(const ConfigOptionResolver & /* n "printable_area", //BBS: add bed_exclude_area "bed_exclude_area", - "bed_exclude_area_3d", "thumbnail_size", "before_layer_change_gcode", "enable_pressure_advance", diff --git a/src/libslic3r/PrintConfig.cpp b/src/libslic3r/PrintConfig.cpp index ed3822f1a4..8018b0fdf3 100644 --- a/src/libslic3r/PrintConfig.cpp +++ b/src/libslic3r/PrintConfig.cpp @@ -885,14 +885,6 @@ void PrintConfigDef::init_common_params() def->gui_type = ConfigOptionDef::GUIType::one_string; def->set_default_value(new ConfigOptionPoints{ Vec2d(0, 0) }); - def = this->add("bed_exclude_area_3d", coString); - def->label = L("Bed exclusion volume"); - def->tooltip = L("Z-limited unprintable volumes. Use: \"ZMIN..ZMAX;XxY,XxY,...\". Separate multiple regions with \"|\". " - "Missing Z bounds default to the bed surface or printable height."); - def->mode = comAdvanced; - def->gui_type = ConfigOptionDef::GUIType::one_string; - def->set_default_value(new ConfigOptionString()); - def = this->add("bed_custom_texture", coString); def->label = L("Bed custom texture"); def->mode = comAdvanced; @@ -12742,7 +12734,7 @@ namespace { static bool is_bed_exclusion_volume_syntax(const std::string &value) { - return value.find("..") != std::string::npos && value.find(';') != std::string::npos; + return value.find('|') != std::string::npos || (value.find("..") != std::string::npos && value.find(';') != std::string::npos); } static bool parse_double_token(const std::string &text, double &out) @@ -12907,14 +12899,13 @@ static std::vector get_bed_excluded_regions_impl( std::vector get_bed_excluded_regions(const DynamicPrintConfig& cfg) { const ConfigOptionPoints *legacy = cfg.opt("bed_exclude_area"); - const ConfigOptionString *regions = cfg.opt("bed_exclude_area_3d"); const ConfigOptionFloat *height = cfg.opt("printable_height"); const std::string bed_exclude_area = legacy != nullptr ? legacy->serialize() : std::string{}; const bool volume_syntax = is_bed_exclusion_volume_syntax(bed_exclude_area); return get_bed_excluded_regions_impl( volume_syntax || legacy == nullptr ? Pointfs{} : legacy->values, - volume_syntax ? bed_exclude_area : (regions != nullptr ? regions->value : std::string{}), + volume_syntax ? bed_exclude_area : std::string{}, height != nullptr ? height->value : 0.0); } @@ -12925,7 +12916,7 @@ std::vector get_bed_excluded_regions(const PrintConfig& cfg) return get_bed_excluded_regions_impl( volume_syntax ? Pointfs{} : cfg.bed_exclude_area.values, - volume_syntax ? bed_exclude_area : cfg.bed_exclude_area_3d.value, + volume_syntax ? bed_exclude_area : std::string{}, cfg.printable_height.value); } diff --git a/src/libslic3r/PrintConfig.hpp b/src/libslic3r/PrintConfig.hpp index a258c86206..2a1a8063de 100644 --- a/src/libslic3r/PrintConfig.hpp +++ b/src/libslic3r/PrintConfig.hpp @@ -1758,7 +1758,6 @@ PRINT_CONFIG_CLASS_DERIVED_DEFINE( ((ConfigOptionStrings, parallel_printheads_bed_exclude_areas)) //BBS: add bed_exclude_area ((ConfigOptionPoints, bed_exclude_area)) - ((ConfigOptionString, bed_exclude_area_3d)) ((ConfigOptionPoints, head_wrap_detect_zone)) // BBS ((ConfigOptionString, bed_custom_texture)) diff --git a/src/slic3r/GUI/ConfigWizard.cpp b/src/slic3r/GUI/ConfigWizard.cpp index c13486e554..412df19091 100644 --- a/src/slic3r/GUI/ConfigWizard.cpp +++ b/src/slic3r/GUI/ConfigWizard.cpp @@ -2637,7 +2637,7 @@ ConfigWizard::ConfigWizard(wxWindow *parent) p->load_vendors(); //BBS: add bed exclude areas p->custom_config.reset(DynamicPrintConfig::new_from_defaults_keys({ - "gcode_flavor", "printable_area", "bed_exclude_area", "bed_exclude_area_3d", "bed_custom_texture", "bed_custom_model", "nozzle_diameter", "filament_diameter", "thumbnails" + "gcode_flavor", "printable_area", "bed_exclude_area", "bed_custom_texture", "bed_custom_model", "nozzle_diameter", "filament_diameter", "thumbnails" //, "nozzle_temperature", "bed_temperature" })); diff --git a/src/slic3r/GUI/Field.cpp b/src/slic3r/GUI/Field.cpp index de991ed116..68a4b87ddd 100644 --- a/src/slic3r/GUI/Field.cpp +++ b/src/slic3r/GUI/Field.cpp @@ -734,7 +734,8 @@ void Field::get_value_by_opt_type(wxString& str, const bool check_value/* = true case coPoints: { std::vector out_values; str.Replace(" ", wxEmptyString, true); - const bool bed_exclusion_volume_syntax = m_opt_id == "bed_exclude_area" && str.Find("..") != wxNOT_FOUND && str.Find(";") != wxNOT_FOUND; + const bool bed_exclusion_volume_syntax = m_opt_id == "bed_exclude_area" && + (str.Find("|") != wxNOT_FOUND || (str.Find("..") != wxNOT_FOUND && str.Find(";") != wxNOT_FOUND)); const wxString raw_str = str; if (bed_exclusion_volume_syntax) { wxString points; @@ -742,11 +743,9 @@ void Field::get_value_by_opt_type(wxString& str, const bool check_value/* = true while (regions.HasMoreTokens()) { wxString region = regions.GetNextToken(); const int sep = region.Find(";"); - if (sep == wxNOT_FOUND) - continue; if (! points.empty()) points += ","; - points += region.Mid(sep + 1); + points += sep == wxNOT_FOUND ? region : region.Mid(sep + 1); } str = points; } diff --git a/src/slic3r/GUI/GUI.cpp b/src/slic3r/GUI/GUI.cpp index 0838649d27..cfeb9d80ce 100644 --- a/src/slic3r/GUI/GUI.cpp +++ b/src/slic3r/GUI/GUI.cpp @@ -240,8 +240,6 @@ void change_opt_value(DynamicPrintConfig& config, const t_config_option_key& opt case coPoints:{ if (opt_key == "bed_exclude_area" && boost::any_cast(&value) != nullptr) { config.option(opt_key)->deserialize(boost::any_cast(value)); - if (config.has("bed_exclude_area_3d")) - config.set_key_value("bed_exclude_area_3d", new ConfigOptionString()); break; } if (opt_key == "printable_area" || opt_key == "bed_exclude_area" || opt_key == "thumbnails" || opt_key == "wrapping_exclude_area" ) { @@ -249,8 +247,6 @@ void change_opt_value(DynamicPrintConfig& config, const t_config_option_key& opt if (opt_key == "bed_exclude_area") { ConfigOptionPoints normalized(boost::any_cast>(value)); config.option(opt_key)->deserialize(normalized.serialize()); - if (config.has("bed_exclude_area_3d")) - config.set_key_value("bed_exclude_area_3d", new ConfigOptionString()); } break; } diff --git a/src/slic3r/GUI/Plater.cpp b/src/slic3r/GUI/Plater.cpp index e885b3a041..e1fa2b5004 100644 --- a/src/slic3r/GUI/Plater.cpp +++ b/src/slic3r/GUI/Plater.cpp @@ -7331,7 +7331,7 @@ Plater::priv::priv(Plater *q, MainFrame *main_frame) , main_frame(main_frame) //BBS: add bed_exclude_area , config(Slic3r::DynamicPrintConfig::new_from_defaults_keys({ - "printable_area", "bed_exclude_area", "bed_exclude_area_3d", "wrapping_exclude_area", "extruder_printable_area", "bed_custom_texture", "bed_custom_model", "print_sequence", + "printable_area", "bed_exclude_area", "wrapping_exclude_area", "extruder_printable_area", "bed_custom_texture", "bed_custom_model", "print_sequence", "extruder_clearance_radius", "extruder_clearance_height_to_lid", "extruder_clearance_height_to_rod", "nozzle_height", "skirt_type", "skirt_loops", "skirt_speed","min_skirt_length", "skirt_distance", "skirt_start_angle", @@ -20090,7 +20090,7 @@ void Plater::on_config_change(const DynamicPrintConfig &config) p->partplate_list.invalid_all_slice_result(); } //BBS: add bed_exclude_area - else if (opt_key == "printable_area" || opt_key == "bed_exclude_area" || opt_key == "bed_exclude_area_3d" + else if (opt_key == "printable_area" || opt_key == "bed_exclude_area" || opt_key == "bed_custom_texture" || opt_key == "bed_custom_model" || opt_key == "extruder_clearance_height_to_lid" || opt_key == "extruder_clearance_height_to_rod") { From 0b258b4c07c14910c491667583e059ba5d5e6b49 Mon Sep 17 00:00:00 2001 From: Harry-Loud Date: Thu, 21 May 2026 12:07:12 +0100 Subject: [PATCH 03/38] Return bed-level exclusion footprints for 2D helpers Build get_bed_excluded_area from the unified bed exclusion region parser and filter it to regions that touch the bed surface. This preserves legacy 2D consumers for plain pipe-separated regions and bed-starting Z ranges while keeping elevated-only volumes out of bed-shape calculations. --- src/libslic3r/PrintConfig.cpp | 23 +++++++++-------------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/src/libslic3r/PrintConfig.cpp b/src/libslic3r/PrintConfig.cpp index 8018b0fdf3..be7bbac24e 100644 --- a/src/libslic3r/PrintConfig.cpp +++ b/src/libslic3r/PrintConfig.cpp @@ -12927,25 +12927,20 @@ bool has_bed_exclusion_volume_syntax(const ConfigOptionPoints& bed_exclude_area) Polygons get_bed_excluded_area(const PrintConfig& cfg) { - if (is_bed_exclusion_volume_syntax(cfg.bed_exclude_area.serialize())) - return {}; const std::vector regions = get_bed_excluded_regions(cfg); - if (std::any_of(regions.begin(), regions.end(), [](const BedExcludeRegion ®ion) { - return region.from_3d_config && region.has_z_range; - })) - return {}; + Polygons excluded_polygons; + excluded_polygons.reserve(regions.size()); - const Pointfs exclude_area_points = cfg.bed_exclude_area.values; + for (const BedExcludeRegion ®ion : regions) { + if (region.has_z_range && region.z_min > EPSILON) + continue; + if (region.z_max <= EPSILON) + continue; - Polygon exclude_poly; - for (int i = 0; i < exclude_area_points.size(); i++) { - auto pt = exclude_area_points[i]; - exclude_poly.points.emplace_back(scale_(pt.x()), scale_(pt.y())); + excluded_polygons.emplace_back(region.polygon); } - exclude_poly.make_counter_clockwise(); - - return {exclude_poly}; + return excluded_polygons; } Polygon get_bed_shape_with_excluded_area(const PrintConfig& cfg, bool use_share) From e76255e0a7b8f48fd8e8352f73ce9a3a5d3337ca Mon Sep 17 00:00:00 2001 From: Harry-Loud Date: Thu, 21 May 2026 14:34:44 +0100 Subject: [PATCH 04/38] Cache exclusion volume previews behind dirty state Avoid rebuilding the exclusion-volume preview cache key from the render path on every frame. The preview now refreshes only after relevant plate, config, object membership, or drag-completion changes while still clearing stale red intersections during active dragging. --- src/slic3r/GUI/GLCanvas3D.cpp | 5 +++++ src/slic3r/GUI/PartPlate.cpp | 26 +++++++++++++++++++++++++- src/slic3r/GUI/PartPlate.hpp | 5 +++++ 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/slic3r/GUI/GLCanvas3D.cpp b/src/slic3r/GUI/GLCanvas3D.cpp index e48192ba23..40d4bcd0bc 100644 --- a/src/slic3r/GUI/GLCanvas3D.cpp +++ b/src/slic3r/GUI/GLCanvas3D.cpp @@ -5598,6 +5598,11 @@ void GLCanvas3D::set_cursor(ECursorType type) void GLCanvas3D::mouse_up_cleanup() { + if (m_mouse.dragging) { + if (PartPlate *plate = wxGetApp().plater()->get_partplate_list().get_curr_plate()) + plate->invalidate_exclusion_volume_preview(); + } + m_moving = false; m_camera_movement = false; m_mouse.drag.move_volume_idx = -1; diff --git a/src/slic3r/GUI/PartPlate.cpp b/src/slic3r/GUI/PartPlate.cpp index daa2d0f71c..e83e1003f4 100644 --- a/src/slic3r/GUI/PartPlate.cpp +++ b/src/slic3r/GUI/PartPlate.cpp @@ -1204,6 +1204,10 @@ std::string PartPlate::exclusion_volume_preview_cache_key(const std::vectorconfig() : nullptr; if (config == nullptr) { m_exclusion_volume_preview_cache_key.clear(); @@ -1211,14 +1215,16 @@ void PartPlate::update_exclusion_volume_preview_models() m_exclusion_volume_border_triangles.reset(); m_active_exclusion_volume_prisms.reset(); m_exclusion_volume_intersection_triangles.reset(); + m_exclusion_volume_intersections_cleared = false; return; } std::vector regions = get_bed_excluded_regions(*config); const std::string cache_key = exclusion_volume_preview_cache_key(regions); - if (cache_key == m_exclusion_volume_preview_cache_key) + if (cache_key == m_exclusion_volume_preview_cache_key && !m_exclusion_volume_intersections_cleared) return; m_exclusion_volume_preview_cache_key = cache_key; + m_exclusion_volume_intersections_cleared = false; m_exclusion_volume_floor_triangles.reset(); m_exclusion_volume_border_triangles.reset(); @@ -1356,6 +1362,12 @@ void PartPlate::render_exclusion_volume_intersections() void PartPlate::clear_exclusion_volume_intersections() { m_exclusion_volume_intersection_triangles.reset(); + m_exclusion_volume_intersections_cleared = true; +} + +void PartPlate::invalidate_exclusion_volume_preview() +{ + m_exclusion_volume_preview_dirty = true; } @@ -2858,6 +2870,7 @@ void PartPlate::clear(bool clear_sliced_result) { obj_to_instance_set.clear(); instance_outside_set.clear(); + invalidate_exclusion_volume_preview(); if (clear_sliced_result) { m_ready_for_slice = true; update_slice_result_valid_state(false); @@ -2937,6 +2950,7 @@ void PartPlate::set_pos_and_size(Vec3d& origin, int width, int depth, double hei m_width = width; m_depth = depth; m_height = height; + invalidate_exclusion_volume_preview(); if (with_instance_move && m_plater) m_plater->mark_plate_toolbar_image_dirty(); @@ -3057,6 +3071,7 @@ void PartPlate::set_print(PrintBase* print, GCodeResult* result, int index) m_print_index = index; m_print->set_plate_origin(m_origin); + invalidate_exclusion_volume_preview(); return; } @@ -3295,6 +3310,7 @@ int PartPlate::add_instance(int obj_id, int instance_id, bool move_position, Bou std::pair pair(obj_id, instance_id); obj_to_instance_set.insert(pair); + invalidate_exclusion_volume_preview(); BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << boost::format(": plate_id %1%, add instance obj_id %2%, instance_id %3%, move_position %4%") % m_plate_index % obj_id % instance_id % move_position; @@ -3337,6 +3353,7 @@ int PartPlate::remove_instance(int obj_id, int instance_id) it = obj_to_instance_set.find(std::pair(obj_id, instance_id)); if (it != obj_to_instance_set.end()) { obj_to_instance_set.erase(it); + invalidate_exclusion_volume_preview(); BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << boost::format(":plate_id %1%, found obj_id %2%, instance_id %3%") % m_plate_index % obj_id % instance_id; result = 0; } @@ -3396,6 +3413,7 @@ void PartPlate::translate_all_instance(Vec3d position) } } } + invalidate_exclusion_volume_preview(); return; } @@ -3430,6 +3448,7 @@ void PartPlate::duplicate_all_instance(unsigned int dup_count, bool need_skip, s for ( size_t new_instance_id = 0; new_instance_id < newObj->instances.size(); new_instance_id++ ) { obj_to_instance_set.emplace(std::pair(new_obj_id, new_instance_id)); + invalidate_exclusion_volume_preview(); BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format(": duplicate object into plate: index_pair [%1%,%2%], obj_id %3%") % new_obj_id % new_instance_id % newObj->id().id; } } @@ -3473,6 +3492,7 @@ void PartPlate::update_instance_exclude_status(int obj_id, int instance_id, Boun std::set>::iterator it; outside = check_outside(obj_id, instance_id, bounding_box); + invalidate_exclusion_volume_preview(); it = instance_outside_set.find(std::pair(obj_id, instance_id)); if (it == instance_outside_set.end()) { @@ -3500,6 +3520,7 @@ void PartPlate::update_object_index(int obj_idx_removed, int obj_idx_max) } obj_to_instance_set.clear(); obj_to_instance_set = temp_set; + invalidate_exclusion_volume_preview(); //update the instance_outside_set temp_set.clear(); @@ -3755,6 +3776,8 @@ void PartPlate::generate_exclude_polygon(ExPolygon &exclude_polygon) bool PartPlate::set_shape(const Pointfs& shape, const Pointfs& exclude_areas, const std::vector& extruder_areas, const std::vector& extruder_heights, Vec2d position, float height_to_lid, float height_to_rod) { + invalidate_exclusion_volume_preview(); + Pointfs new_shape, new_exclude_areas; m_extruder_heights = extruder_heights; for (const Vec2d& p : shape) { @@ -5186,6 +5209,7 @@ int PartPlateList::duplicate_plate(int index) // go over the instances and pair with the object for (size_t new_instance_id = 0; new_instance_id < object_copy->instances.size(); new_instance_id++){ new_plate->obj_to_instance_set.emplace(std::pair(new_obj_id, new_instance_id)); + new_plate->invalidate_exclusion_volume_preview(); BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << boost::format(": duplicate object into plate: index_pair [%1%,%2%], obj_id %3%") % new_obj_id % new_instance_id % object_copy->id().id; } } diff --git a/src/slic3r/GUI/PartPlate.hpp b/src/slic3r/GUI/PartPlate.hpp index a4679db69a..a533191860 100644 --- a/src/slic3r/GUI/PartPlate.hpp +++ b/src/slic3r/GUI/PartPlate.hpp @@ -139,6 +139,8 @@ private: GLModel m_active_exclusion_volume_prisms; GLModel m_exclusion_volume_intersection_triangles; std::string m_exclusion_volume_preview_cache_key; + bool m_exclusion_volume_preview_dirty { true }; + bool m_exclusion_volume_intersections_cleared { false }; GLModel m_logo_triangles; GLModel m_gridlines; GLModel m_gridlines_bolder; @@ -393,6 +395,7 @@ public: //check whether instance is outside the plate or not bool check_outside(int obj_id, int instance_id, BoundingBoxf3* bounding_box = nullptr); void clear_exclusion_volume_intersections(); + void invalidate_exclusion_volume_preview(); //judge whether instance is intesected with plate or not bool intersect_instance(int obj_id, int instance_id, BoundingBoxf3* bounding_box = nullptr); @@ -572,6 +575,8 @@ public: for (std::vector>::iterator it = instances_outside.begin(); it != instances_outside.end(); ++it) instance_outside_set.insert(std::pair(it->first, it->second)); + + invalidate_exclusion_volume_preview(); } template void save(Archive& ar) const { std::vector> objects_and_instances; From e81ec0ffc237060a12ff36086654f79e7f0dbccf Mon Sep 17 00:00:00 2001 From: Harry-Loud Date: Thu, 21 May 2026 17:13:05 +0100 Subject: [PATCH 05/38] Avoid pathological exclusion preview mesh growth Grow clipped exclusion-intersection preview buffers geometrically instead of reserving the exact next size for each clipped polygon. This avoids repeated reallocation and copying when high-poly meshes produce many red preview fragments. --- src/libslic3r/Model.cpp | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/libslic3r/Model.cpp b/src/libslic3r/Model.cpp index 65479806d0..fde8ad9b9a 100644 --- a/src/libslic3r/Model.cpp +++ b/src/libslic3r/Model.cpp @@ -3563,12 +3563,18 @@ static void append_clipped_polygon(indexed_triangle_set &out, const std::vector< if (polygon.size() < 3) return; + auto reserve_geometric = [](auto &container, size_t wanted) { + if (wanted <= container.capacity()) + return; + container.reserve(std::max(wanted, std::max(16, container.capacity() * 2))); + }; + const int base = int(out.vertices.size()); - out.vertices.reserve(out.vertices.size() + polygon.size()); + reserve_geometric(out.vertices, out.vertices.size() + polygon.size()); for (const Vec3d &point : polygon) out.vertices.emplace_back(point.cast()); - out.indices.reserve(out.indices.size() + polygon.size() - 2); + reserve_geometric(out.indices, out.indices.size() + polygon.size() - 2); for (size_t i = 1; i + 1 < polygon.size(); ++i) { stl_triangle_vertex_indices tri; tri << base, base + int(i), base + int(i + 1); From 1acd9ce1d2942ff369103a9fef03cb5be4620d12 Mon Sep 17 00:00:00 2001 From: Harry-Loud Date: Thu, 21 May 2026 17:26:42 +0100 Subject: [PATCH 06/38] Document exclusion intersection preview modes Clarify that exclusion intersection checks run as either boolean early-out tests or full clipped-mesh collection for the red GUI preview. Also document why clipped preview buffers use geometric growth. --- src/libslic3r/Model.cpp | 5 +++++ src/slic3r/GUI/PartPlate.cpp | 2 ++ 2 files changed, 7 insertions(+) diff --git a/src/libslic3r/Model.cpp b/src/libslic3r/Model.cpp index fde8ad9b9a..74b55bb99e 100644 --- a/src/libslic3r/Model.cpp +++ b/src/libslic3r/Model.cpp @@ -3563,6 +3563,8 @@ static void append_clipped_polygon(indexed_triangle_set &out, const std::vector< if (polygon.size() < 3) return; + // Preview meshes may contain many clipped fragments, so grow geometrically + // instead of reserving the exact next size for every appended polygon. auto reserve_geometric = [](auto &container, size_t wanted) { if (wanted <= container.capacity()) return; @@ -3586,6 +3588,9 @@ static void append_clipped_polygon(indexed_triangle_set &out, const std::vector< bool ModelInstance::intersects_bed_exclude_region(const BedExcludeRegion ®ion, indexed_triangle_set *intersection_mesh) const { + // With no output mesh this is a fast yes/no test and returns on the first + // hit. With an output mesh it collects all clipped fragments for the red + // GUI intersection preview. if (intersection_mesh != nullptr) intersection_mesh->clear(); diff --git a/src/slic3r/GUI/PartPlate.cpp b/src/slic3r/GUI/PartPlate.cpp index e83e1003f4..363bf982df 100644 --- a/src/slic3r/GUI/PartPlate.cpp +++ b/src/slic3r/GUI/PartPlate.cpp @@ -1295,6 +1295,8 @@ void PartPlate::update_exclusion_volume_preview_models() if (instance_box.max.z() < region.z_min || instance_box.min.z() > region.z_max) continue; + // The preview path intentionally requests the full clipped mesh. + // Boolean-only placement checks call this without an output mesh. indexed_triangle_set region_intersections; if (instance->intersects_bed_exclude_region(region, ®ion_intersections) && !region_intersections.empty()) its_merge(intersection_triangles, region_intersections); From e21bd886eb4e9d42823202c06d9ebbf941c845ff Mon Sep 17 00:00:00 2001 From: Harry-Loud Date: Fri, 22 May 2026 11:01:57 +0100 Subject: [PATCH 07/38] Let vector growth handle exclusion preview fragments Remove the manual geometric reserve helper from clipped exclusion preview mesh accumulation. The append path now avoids exact per-fragment reserve calls and relies on std::vector amortized growth through emplace_back, matching standard container guidance. --- src/libslic3r/Model.cpp | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/src/libslic3r/Model.cpp b/src/libslic3r/Model.cpp index 74b55bb99e..83f4e4464f 100644 --- a/src/libslic3r/Model.cpp +++ b/src/libslic3r/Model.cpp @@ -3563,20 +3563,12 @@ static void append_clipped_polygon(indexed_triangle_set &out, const std::vector< if (polygon.size() < 3) return; - // Preview meshes may contain many clipped fragments, so grow geometrically - // instead of reserving the exact next size for every appended polygon. - auto reserve_geometric = [](auto &container, size_t wanted) { - if (wanted <= container.capacity()) - return; - container.reserve(std::max(wanted, std::max(16, container.capacity() * 2))); - }; - + // Do not reserve exact capacity here. This helper may be called for many + // clipped fragments, so let std::vector grow amortized through emplace_back. const int base = int(out.vertices.size()); - reserve_geometric(out.vertices, out.vertices.size() + polygon.size()); for (const Vec3d &point : polygon) out.vertices.emplace_back(point.cast()); - reserve_geometric(out.indices, out.indices.size() + polygon.size() - 2); for (size_t i = 1; i + 1 < polygon.size(); ++i) { stl_triangle_vertex_indices tri; tri << base, base + int(i), base + int(i + 1); From dbae4151270c4d1cc3bd4f8357025424bc40cbb2 Mon Sep 17 00:00:00 2001 From: Harry Loud Date: Wed, 15 Jul 2026 07:43:26 +0100 Subject: [PATCH 08/38] Add multi-nozzle exclusion volume modes --- src/libslic3r/Model.cpp | 30 +++ src/libslic3r/Model.hpp | 1 + src/libslic3r/Preset.cpp | 2 +- src/libslic3r/Print.cpp | 71 ++++-- src/libslic3r/Print.hpp | 1 + src/libslic3r/PrintConfig.cpp | 223 +++++++++++++++++-- src/libslic3r/PrintConfig.hpp | 15 ++ src/libslic3r/PrintObject.cpp | 35 +++ src/slic3r/GUI/ConfigWizard.cpp | 3 +- src/slic3r/GUI/Field.cpp | 9 + src/slic3r/GUI/PartPlate.cpp | 56 ++++- src/slic3r/GUI/PartPlate.hpp | 2 + src/slic3r/GUI/Plater.cpp | 6 +- src/slic3r/GUI/Tab.cpp | 33 +++ tests/fff_print/test_print.cpp | 37 +++ tests/libslic3r/CMakeLists.txt | 1 + tests/libslic3r/test_bed_exclude_regions.cpp | 93 ++++++++ 17 files changed, 578 insertions(+), 40 deletions(-) create mode 100644 tests/libslic3r/test_bed_exclude_regions.cpp diff --git a/src/libslic3r/Model.cpp b/src/libslic3r/Model.cpp index 83f4e4464f..94c192ec66 100644 --- a/src/libslic3r/Model.cpp +++ b/src/libslic3r/Model.cpp @@ -3643,6 +3643,36 @@ bool ModelInstance::intersects_bed_exclude_region(const BedExcludeRegion ®ion return intersects; } +bool ModelInstance::intersects_bed_exclude_regions( + const std::vector ®ions, + indexed_triangle_set *intersection_mesh) const +{ + if (intersection_mesh != nullptr) + intersection_mesh->clear(); + if (regions.empty()) + return false; + + const Polygon hull = const_cast(this)->convex_hull_2d(); + bool intersects = false; + for (const BedExcludeRegion ®ion : regions) { + if (intersection(Polygons{ region.polygon }, Polygons{ hull }).empty()) + continue; + + if (intersection_mesh == nullptr) { + if (intersects_bed_exclude_region(region)) + return true; + continue; + } + + indexed_triangle_set region_intersection; + if (intersects_bed_exclude_region(region, ®ion_intersection) && !region_intersection.empty()) { + intersects = true; + its_merge(*intersection_mesh, region_intersection); + } + } + return intersects; +} + //BBS: invalidate instance's convex_hull_2d void ModelInstance::invalidate_convex_hull_2d() { diff --git a/src/libslic3r/Model.hpp b/src/libslic3r/Model.hpp index 2af1150e30..525eb820f1 100644 --- a/src/libslic3r/Model.hpp +++ b/src/libslic3r/Model.hpp @@ -1367,6 +1367,7 @@ public: // BBS Polygon convex_hull_2d(); bool intersects_bed_exclude_region(const BedExcludeRegion ®ion, indexed_triangle_set *intersection_mesh = nullptr) const; + bool intersects_bed_exclude_regions(const std::vector ®ions, indexed_triangle_set *intersection_mesh = nullptr) const; void invalidate_convex_hull_2d(); // Getting the input polygon for arrange diff --git a/src/libslic3r/Preset.cpp b/src/libslic3r/Preset.cpp index 0f5b30fb59..e98e459162 100644 --- a/src/libslic3r/Preset.cpp +++ b/src/libslic3r/Preset.cpp @@ -1440,7 +1440,7 @@ static std::vector s_Preset_machine_limits_options { static std::vector s_Preset_printer_options { "printer_technology", "printable_area", "extruder_printable_area", "support_parallel_printheads", "parallel_printheads_count", "parallel_printheads_bed_exclude_areas", - "bed_exclude_area", "bed_custom_texture", "bed_custom_model", "gcode_flavor", + "bed_exclude_area_mode", "bed_exclude_area", "extruder_bed_exclude_area", "bed_custom_texture", "bed_custom_model", "gcode_flavor", "gcode_skip_config_block", "fan_kickstart", "part_cooling_fan_min_pwm", "fan_speedup_time", "fan_speedup_overhangs", "single_extruder_multi_material", "manual_filament_change", "file_start_gcode", "machine_start_gcode", "machine_end_gcode", "before_layer_change_gcode", "printing_by_object_gcode", "layer_change_gcode", "time_lapse_gcode", "wrapping_detection_gcode", "change_filament_gcode", "change_extrusion_role_gcode", "printer_model", "printer_variant", "printer_extruder_id", "printer_extruder_variant", "extruder_variant_list", "default_nozzle_volume_type", diff --git a/src/libslic3r/Print.cpp b/src/libslic3r/Print.cpp index bd953f1929..d4a421303f 100644 --- a/src/libslic3r/Print.cpp +++ b/src/libslic3r/Print.cpp @@ -31,6 +31,7 @@ #include #include #include +#include #include #include #include @@ -77,21 +78,42 @@ static std::vector translated_bed_exclusion_volumes(const Prin return regions; } -static bool intersects_bed_exclusion_volume(const ModelInstance &instance, const std::vector ®ions) +static std::vector> translated_bed_exclusion_volumes_by_extruder(const Print &print) { - if (regions.empty()) - return false; + std::vector> regions_by_extruder = get_bed_excluded_regions_by_extruder(print.config()); + const Point print_origin(scale_(print.get_plate_origin().x()), scale_(print.get_plate_origin().y())); + for (std::vector ®ions : regions_by_extruder) + for (BedExcludeRegion ®ion : regions) + region.polygon.translate(print_origin); + return regions_by_extruder; +} - Polygon hull = const_cast(instance).convex_hull_2d(); - for (const BedExcludeRegion ®ion : regions) { - if (intersection(Polygons{ region.polygon }, Polygons{ hull }).empty()) - continue; +static std::optional colliding_bed_exclusion_extruder( + const Print &print, + const PrintObject &print_object, + const ModelInstance &instance, + const std::vector> ®ions_by_extruder) +{ + if (regions_by_extruder.empty()) + return std::nullopt; - if (instance.intersects_bed_exclude_region(region)) - return true; + if (is_auto_filament_map_mode(print.get_filament_map_mode())) { + std::optional first_collision; + for (size_t extruder_id = 0; extruder_id < regions_by_extruder.size(); ++extruder_id) { + if (!instance.intersects_bed_exclude_regions(regions_by_extruder[extruder_id])) + return std::nullopt; + if (!first_collision.has_value()) + first_collision = extruder_id; + } + return first_collision; } - return false; + for (const unsigned int filament_id : print_object.printing_extruders()) { + const size_t extruder_id = std::min(print.get_extruder_id(filament_id), regions_by_extruder.size() - 1); + if (instance.intersects_bed_exclude_regions(regions_by_extruder[extruder_id])) + return extruder_id; + } + return std::nullopt; } static Polygons full_height_bed_exclusion_polygons(const std::vector ®ions) @@ -154,7 +176,10 @@ bool Print::invalidate_state_by_config_options(const ConfigOptionResolver & /* n "max_travel_detour_distance", "printable_area", //BBS: add bed_exclude_area + "bed_exclude_area_mode", "bed_exclude_area", + "extruder_bed_exclude_area", + "extruder_offset", "thumbnail_size", "before_layer_change_gcode", "enable_pressure_advance", @@ -686,7 +711,7 @@ StringObjectException Print::sequential_print_clearance_valid(const Print &print StringObjectException single_object_exception; const auto& print_config = print.config(); const Vec3d print_origin = print.get_plate_origin(); - const std::vector exclusion_volumes = translated_bed_exclusion_volumes(print); + const std::vector> exclusion_volumes = translated_bed_exclusion_volumes_by_extruder(print); struct print_instance_info { @@ -737,15 +762,20 @@ StringObjectException Print::sequential_print_clearance_valid(const Print &print // Convert the shift from the PrintObject's coordinates into ModelObject's coordinates by removing the centering offset. convex_hull.translate(instance.shift - print_object->center_offset()); } - if (intersects_bed_exclusion_volume(*instance.model_instance, exclusion_volumes)) { + const std::optional collision_extruder = colliding_bed_exclusion_extruder( + print, *print_object, *instance.model_instance, exclusion_volumes); + if (collision_extruder.has_value()) { + const std::string collision_message = is_auto_filament_map_mode(print.get_filament_map_mode()) ? + (boost::format(L("%1% intersects exclusion volumes for every available extruder.")) % instance.model_instance->get_object()->name).str() : + (boost::format(L("%1% intersects an exclusion volume for extruder %2%.")) % instance.model_instance->get_object()->name % (*collision_extruder + 1)).str(); if (single_object_exception.string.empty()) { - single_object_exception.string = (boost::format(L("%1% is too close to exclusion volume, there may be collisions when printing.")) %instance.model_instance->get_object()->name).str(); + single_object_exception.string = collision_message; // single_object_exception.object = instance.model_instance->get_object(); //ORCA: Pass ModelInstance instead of ModelObject single_object_exception.object = instance.model_instance; } else { - single_object_exception.string += "\n" + (boost::format(L("%1% is too close to exclusion volume, there may be collisions when printing.")) % instance.model_instance->get_object()->name).str(); + single_object_exception.string += "\n" + collision_message; single_object_exception.object = nullptr; } } @@ -1001,8 +1031,8 @@ static StringObjectException layered_print_cleareance_valid(const Print &print, const auto& print_config = print.config(); const Vec3d print_origin = print.get_plate_origin(); - const std::vector exclusion_volumes = translated_bed_exclusion_volumes(print); - const Polygons prime_tower_exclude_polys = full_height_bed_exclusion_polygons(exclusion_volumes); + const std::vector> exclusion_volumes = translated_bed_exclusion_volumes_by_extruder(print); + const Polygons prime_tower_exclude_polys = full_height_bed_exclusion_polygons(translated_bed_exclusion_volumes(print)); Pointfs wrapping_detection_area = print_config.wrapping_exclude_area.values; Polygon wrapping_poly; @@ -1031,8 +1061,13 @@ static StringObjectException layered_print_cleareance_valid(const Print &print, } current_instance_hulls.emplace_back(volume_hull); } - if (intersects_bed_exclusion_volume(*inst->model_instance, exclusion_volumes)) - return {inst->model_instance->get_object()->name + L(" is too close to exclusion volume, there may be collisions when printing.") + "\n", inst->model_instance}; + if (const std::optional collision_extruder = colliding_bed_exclusion_extruder( + print, *inst->print_object, *inst->model_instance, exclusion_volumes); collision_extruder.has_value()) { + const std::string message = is_auto_filament_map_mode(print.get_filament_map_mode()) ? + (boost::format(L("%1% intersects exclusion volumes for every available extruder.")) % inst->model_instance->get_object()->name).str() : + (boost::format(L("%1% intersects an exclusion volume for extruder %2%.")) % inst->model_instance->get_object()->name % (*collision_extruder + 1)).str(); + return {message + "\n", inst->model_instance}; + } if (!intersection(convex_hulls_other, current_instance_hulls).empty()) { if (warning) { diff --git a/src/libslic3r/Print.hpp b/src/libslic3r/Print.hpp index 9822c5520c..4d01e64580 100644 --- a/src/libslic3r/Print.hpp +++ b/src/libslic3r/Print.hpp @@ -460,6 +460,7 @@ public: // returns 0-based indices of extruders used to print the object (without brim, support and other helper extrusions) std::vector object_extruders() const; + std::vector printing_extruders() const; // Called by make_perimeters() void slice(); diff --git a/src/libslic3r/PrintConfig.cpp b/src/libslic3r/PrintConfig.cpp index be7bbac24e..039efbae04 100644 --- a/src/libslic3r/PrintConfig.cpp +++ b/src/libslic3r/PrintConfig.cpp @@ -9,6 +9,7 @@ #include "GCode/Thumbnails.hpp" #include +#include #include #include #include @@ -640,6 +641,13 @@ static const t_config_enum_values s_keys_map_FilamentMapMode = { }; CONFIG_OPTION_ENUM_DEFINE_STATIC_MAPS(FilamentMapMode) +static const t_config_enum_values s_keys_map_BedExcludeAreaMode = { + { "shared", int(BedExcludeAreaMode::Shared) }, + { "toolhead_offset", int(BedExcludeAreaMode::ToolheadOffset) }, + { "per_extruder", int(BedExcludeAreaMode::PerExtruder) } +}; +CONFIG_OPTION_ENUM_DEFINE_STATIC_MAPS(BedExcludeAreaMode) + // PrimeVolumeMode. Serialized string keys must stay stable; they round-trip through .3mf. static const t_config_enum_values s_keys_map_PrimeVolumeMode = { { "Default", pvmDefault }, @@ -874,6 +882,15 @@ void PrintConfigDef::init_common_params() def->mode = comAdvanced; def->set_default_value(new ConfigOptionStrings()); + def = this->add("bed_exclude_area_mode", coEnum); + def->label = L("Exclusion volume behaviour"); + def->tooltip = L("Choose whether all nozzles use the same exclusion volumes, derive toolhead-relative volumes from each nozzle's XY offset, or configure independent volumes for every extruder."); + def->enum_keys_map = &ConfigOptionEnum::get_enum_values(); + def->enum_values = { "shared", "toolhead_offset", "per_extruder" }; + def->enum_labels = { L("Shared"), L("Toolhead-relative (nozzle offsets)"), L("Individual per extruder") }; + def->mode = comAdvanced; + def->set_default_value(new ConfigOptionEnum(BedExcludeAreaMode::Shared)); + //BBS: add "bed_exclude_area" def = this->add("bed_exclude_area", coPoints); def->label = L("Excluded bed area"); @@ -885,6 +902,13 @@ void PrintConfigDef::init_common_params() def->gui_type = ConfigOptionDef::GUIType::one_string; def->set_default_value(new ConfigOptionPoints{ Vec2d(0, 0) }); + def = this->add("extruder_bed_exclude_area", coStrings); + def->label = L("Extruder exclusion volumes"); + def->tooltip = L("Exclusion volumes used only by this extruder in individual mode. Use the same polygon and optional Z-range format as the shared excluded bed area. Leave empty for no exclusion volumes on this extruder."); + def->mode = comAdvanced; + def->gui_type = ConfigOptionDef::GUIType::one_string; + def->set_default_value(new ConfigOptionStrings{ "" }); + def = this->add("bed_custom_texture", coString); def->label = L("Bed custom texture"); def->mode = comAdvanced; @@ -8212,6 +8236,7 @@ void PrintConfigDef::init_extruder_option_keys() "default_filament_profile", "default_nozzle_volume_type", "deretraction_speed", + "extruder_bed_exclude_area", "extruder_colour", "extruder_offset", "extruder_printable_height", @@ -9382,6 +9407,7 @@ std::set printer_extruder_options = { "nozzle_diameter", "default_nozzle_volume_type", "extruder_printable_area", + "extruder_bed_exclude_area", "extruder_printable_height", "min_layer_height", "max_layer_height", @@ -11550,6 +11576,23 @@ std::map validate(const FullPrintConfig &cfg, bool und break; } + if (cfg.bed_exclude_area_mode.value == BedExcludeAreaMode::ToolheadOffset && + cfg.extruder_offset.size() < cfg.nozzle_diameter.size()) { + error_message.emplace("extruder_offset", L("A nozzle offset is required for every extruder when toolhead-relative exclusion volumes are enabled.")); + } + if (cfg.bed_exclude_area_mode.value == BedExcludeAreaMode::PerExtruder) { + if (cfg.extruder_bed_exclude_area.size() < cfg.nozzle_diameter.size()) { + error_message.emplace("extruder_bed_exclude_area", L("An exclusion-volume entry is required for every extruder. An entry may be empty when that extruder has no exclusion volumes.")); + } else { + for (const std::string &entry : cfg.extruder_bed_exclude_area.values) { + if (!is_valid_bed_exclude_area_string(entry, cfg.printable_height.value)) { + error_message.emplace("extruder_bed_exclude_area", L("Invalid per-extruder exclusion volume definition.")); + break; + } + } + } + } + // --perimeters if (cfg.wall_loops.value < 0) { error_message.emplace("wall_loops", L("invalid value ") + std::to_string(cfg.wall_loops.value)); @@ -12894,30 +12937,155 @@ static std::vector get_bed_excluded_regions_impl( return regions; } -} // namespace - -std::vector get_bed_excluded_regions(const DynamicPrintConfig& cfg) +static std::vector parse_master_bed_excluded_regions( + const ConfigOptionPoints *option, + const double printable_height) { - const ConfigOptionPoints *legacy = cfg.opt("bed_exclude_area"); - const ConfigOptionFloat *height = cfg.opt("printable_height"); - const std::string bed_exclude_area = legacy != nullptr ? legacy->serialize() : std::string{}; - const bool volume_syntax = is_bed_exclusion_volume_syntax(bed_exclude_area); + if (option == nullptr) + return {}; + const std::string serialized = option->serialize(); + const bool volume_syntax = is_bed_exclusion_volume_syntax(serialized); return get_bed_excluded_regions_impl( - volume_syntax || legacy == nullptr ? Pointfs{} : legacy->values, - volume_syntax ? bed_exclude_area : std::string{}, - height != nullptr ? height->value : 0.0); + volume_syntax ? Pointfs{} : option->values, + volume_syntax ? serialized : std::string{}, + printable_height); } -std::vector get_bed_excluded_regions(const PrintConfig& cfg) +static std::vector resolve_bed_excluded_regions( + const std::vector &master_regions, + const BedExcludeAreaMode mode, + const std::vector &per_extruder_specs, + const std::vector &extruder_offsets, + const size_t reference_extruder, + const size_t extruder_id, + const double printable_height) { - const std::string bed_exclude_area = cfg.bed_exclude_area.serialize(); - const bool volume_syntax = is_bed_exclusion_volume_syntax(bed_exclude_area); + if (mode == BedExcludeAreaMode::Shared) + return master_regions; - return get_bed_excluded_regions_impl( - volume_syntax ? Pointfs{} : cfg.bed_exclude_area.values, - volume_syntax ? bed_exclude_area : std::string{}, - cfg.printable_height.value); + if (mode == BedExcludeAreaMode::PerExtruder) { + if (extruder_id >= per_extruder_specs.size() || per_extruder_specs[extruder_id].empty()) + return {}; + + std::vector regions; + append_bed_exclusion_volume_regions(regions, per_extruder_specs[extruder_id], std::max(0.0, printable_height)); + return regions; + } + + std::vector regions = master_regions; + if (extruder_id >= extruder_offsets.size() || extruder_offsets.empty()) + return regions; + + const size_t clamped_reference = std::min(reference_extruder, extruder_offsets.size() - 1); + // A model-space point is emitted as model_position - extruder_offset. Therefore a + // carriage/toolhead obstacle described through the reference nozzle appears in another + // nozzle's model space translated by (other_offset - reference_offset). + const Vec2d delta = extruder_offsets[extruder_id] - extruder_offsets[clamped_reference]; + const Point translation(scale_(delta.x()), scale_(delta.y())); + for (BedExcludeRegion ®ion : regions) + region.polygon.translate(translation); + return regions; +} + +static size_t bed_exclusion_extruder_count( + const size_t nozzle_count, + const size_t offset_count, + const size_t per_extruder_count) +{ + return std::max(1, std::max({ nozzle_count, offset_count, per_extruder_count })); +} + +static std::vector flatten_bed_excluded_regions( + const BedExcludeAreaMode mode, + std::vector> regions_by_extruder) +{ + if (regions_by_extruder.empty()) + return {}; + if (mode == BedExcludeAreaMode::Shared) + return std::move(regions_by_extruder.front()); + + size_t total = 0; + for (const std::vector ®ions : regions_by_extruder) + total += regions.size(); + + std::vector flattened; + flattened.reserve(total); + for (std::vector ®ions : regions_by_extruder) + flattened.insert(flattened.end(), std::make_move_iterator(regions.begin()), std::make_move_iterator(regions.end())); + return flattened; +} + +} // namespace + +std::vector> get_bed_excluded_regions_by_extruder(const DynamicPrintConfig &cfg) +{ + const ConfigOptionFloat *height_option = cfg.opt("printable_height"); + const double printable_height = height_option != nullptr ? height_option->value : 0.0; + const std::vector master_regions = parse_master_bed_excluded_regions( + cfg.opt("bed_exclude_area"), printable_height); + + const ConfigOptionEnum *mode_option = cfg.opt>("bed_exclude_area_mode"); + const BedExcludeAreaMode mode = mode_option != nullptr ? mode_option->value : BedExcludeAreaMode::Shared; + const ConfigOptionStrings *per_extruder_option = cfg.opt("extruder_bed_exclude_area"); + const ConfigOptionPoints *offset_option = cfg.opt("extruder_offset"); + const ConfigOptionFloats *nozzle_option = cfg.opt("nozzle_diameter"); + const ConfigOptionInt *reference_option = cfg.opt("master_extruder_id"); + + const std::vector per_extruder_specs = per_extruder_option != nullptr ? per_extruder_option->values : std::vector{}; + const std::vector offsets = offset_option != nullptr ? offset_option->values : std::vector{}; + const size_t count = bed_exclusion_extruder_count( + nozzle_option != nullptr ? nozzle_option->size() : 0, + offsets.size(), per_extruder_specs.size()); + const size_t reference = reference_option != nullptr && reference_option->value > 0 ? size_t(reference_option->value - 1) : 0; + + std::vector> result; + result.reserve(count); + for (size_t extruder_id = 0; extruder_id < count; ++extruder_id) + result.emplace_back(resolve_bed_excluded_regions(master_regions, mode, per_extruder_specs, offsets, reference, extruder_id, printable_height)); + return result; +} + +std::vector> get_bed_excluded_regions_by_extruder(const PrintConfig &cfg) +{ + const double printable_height = cfg.printable_height.value; + const std::vector master_regions = parse_master_bed_excluded_regions(&cfg.bed_exclude_area, printable_height); + const size_t count = bed_exclusion_extruder_count( + cfg.nozzle_diameter.size(), cfg.extruder_offset.size(), cfg.extruder_bed_exclude_area.size()); + const size_t reference = cfg.master_extruder_id.value > 0 ? size_t(cfg.master_extruder_id.value - 1) : 0; + + std::vector> result; + result.reserve(count); + for (size_t extruder_id = 0; extruder_id < count; ++extruder_id) { + result.emplace_back(resolve_bed_excluded_regions( + master_regions, cfg.bed_exclude_area_mode.value, cfg.extruder_bed_exclude_area.values, + cfg.extruder_offset.values, reference, extruder_id, printable_height)); + } + return result; +} + +std::vector get_bed_excluded_regions(const DynamicPrintConfig &cfg, const size_t extruder_id) +{ + std::vector> regions = get_bed_excluded_regions_by_extruder(cfg); + return extruder_id < regions.size() ? std::move(regions[extruder_id]) : std::vector{}; +} + +std::vector get_bed_excluded_regions(const PrintConfig &cfg, const size_t extruder_id) +{ + std::vector> regions = get_bed_excluded_regions_by_extruder(cfg); + return extruder_id < regions.size() ? std::move(regions[extruder_id]) : std::vector{}; +} + +std::vector get_bed_excluded_regions(const DynamicPrintConfig &cfg) +{ + const ConfigOptionEnum *mode_option = cfg.opt>("bed_exclude_area_mode"); + const BedExcludeAreaMode mode = mode_option != nullptr ? mode_option->value : BedExcludeAreaMode::Shared; + return flatten_bed_excluded_regions(mode, get_bed_excluded_regions_by_extruder(cfg)); +} + +std::vector get_bed_excluded_regions(const PrintConfig &cfg) +{ + return flatten_bed_excluded_regions(cfg.bed_exclude_area_mode.value, get_bed_excluded_regions_by_extruder(cfg)); } bool has_bed_exclusion_volume_syntax(const ConfigOptionPoints& bed_exclude_area) @@ -12925,6 +13093,27 @@ bool has_bed_exclusion_volume_syntax(const ConfigOptionPoints& bed_exclude_area) return is_bed_exclusion_volume_syntax(bed_exclude_area.serialize()); } +bool is_valid_bed_exclude_area_string(const std::string &value, const double printable_height) +{ + if (value.empty()) + return true; + + std::vector specs; + boost::split(specs, value, boost::is_any_of("|\n")); + bool found_nonempty = false; + for (std::string spec : specs) { + boost::trim(spec); + if (spec.empty()) + continue; + found_nonempty = true; + std::vector parsed; + append_bed_exclusion_volume_regions(parsed, spec, std::max(0.0, printable_height)); + if (parsed.size() != 1) + return false; + } + return found_nonempty; +} + Polygons get_bed_excluded_area(const PrintConfig& cfg) { const std::vector regions = get_bed_excluded_regions(cfg); diff --git a/src/libslic3r/PrintConfig.hpp b/src/libslic3r/PrintConfig.hpp index 2a1a8063de..758399af31 100644 --- a/src/libslic3r/PrintConfig.hpp +++ b/src/libslic3r/PrintConfig.hpp @@ -530,6 +530,14 @@ enum FilamentMapMode { fmmDefault }; +// Defines how bed exclusion volumes are resolved for printers with multiple +// independently positioned nozzles/toolheads. +enum class BedExcludeAreaMode { + Shared = 0, + ToolheadOffset, + PerExtruder +}; + // All auto modes are ordered before fmmManual (see the enum ordering note above). inline bool is_auto_filament_map_mode(FilamentMapMode mode) { return mode < fmmManual; @@ -1757,7 +1765,9 @@ PRINT_CONFIG_CLASS_DERIVED_DEFINE( ((ConfigOptionInt, parallel_printheads_count)) ((ConfigOptionStrings, parallel_printheads_bed_exclude_areas)) //BBS: add bed_exclude_area + ((ConfigOptionEnum, bed_exclude_area_mode)) ((ConfigOptionPoints, bed_exclude_area)) + ((ConfigOptionStrings, extruder_bed_exclude_area)) ((ConfigOptionPoints, head_wrap_detect_zone)) // BBS ((ConfigOptionString, bed_custom_texture)) @@ -2312,7 +2322,12 @@ struct BedExcludeRegion { }; std::vector get_bed_excluded_regions(const DynamicPrintConfig& cfg); std::vector get_bed_excluded_regions(const PrintConfig& cfg); +std::vector get_bed_excluded_regions(const DynamicPrintConfig &cfg, size_t extruder_id); +std::vector get_bed_excluded_regions(const PrintConfig &cfg, size_t extruder_id); +std::vector> get_bed_excluded_regions_by_extruder(const DynamicPrintConfig &cfg); +std::vector> get_bed_excluded_regions_by_extruder(const PrintConfig &cfg); bool has_bed_exclusion_volume_syntax(const ConfigOptionPoints& bed_exclude_area); +bool is_valid_bed_exclude_area_string(const std::string &value, double printable_height); Slic3r::Polygons get_bed_excluded_area(const PrintConfig& cfg); Slic3r::Polygon get_bed_shape_with_excluded_area(const PrintConfig& cfg, bool use_share = false); bool has_skirt(const DynamicPrintConfig& cfg); diff --git a/src/libslic3r/PrintObject.cpp b/src/libslic3r/PrintObject.cpp index 54378b3b16..8d94eae593 100644 --- a/src/libslic3r/PrintObject.cpp +++ b/src/libslic3r/PrintObject.cpp @@ -308,6 +308,23 @@ std::vector> PrintObject::detect_extruder_geometric_unprintables() std::vector> geometric_unprintables(extruder_size); // the container to return + std::vector> exclusion_regions = get_bed_excluded_regions_by_extruder(m_print->config()); + exclusion_regions.resize(extruder_size); + const Point plate_origin(scale_(m_print->get_plate_origin().x()), scale_(m_print->get_plate_origin().y())); + for (std::vector ®ions : exclusion_regions) + for (BedExcludeRegion ®ion : regions) + region.polygon.translate(plate_origin); + + const std::vector used_filaments = printing_extruders(); + for (size_t extruder_id = 0; extruder_id < exclusion_regions.size(); ++extruder_id) { + const bool collision = std::any_of(m_instances.begin(), m_instances.end(), [&](const PrintInstance &instance) { + return instance.model_instance != nullptr && + instance.model_instance->intersects_bed_exclude_regions(exclusion_regions[extruder_id]); + }); + if (collision) + geometric_unprintables[extruder_id].insert(used_filaments.begin(), used_filaments.end()); + } + std::vector printable_height_per_extruder = m_print->config().extruder_printable_height.values; assert(printable_height_per_extruder.size() == extruder_size); @@ -4042,6 +4059,24 @@ std::vector PrintObject::object_extruders() const return extruders; } +std::vector PrintObject::printing_extruders() const +{ + std::vector extruders = object_extruders(); + if (has_support_material()) { + const size_t filament_count = print()->config().filament_diameter.size(); + auto append_fixed_filament = [&](const int filament_id) { + if (filament_id > 0) + extruders.emplace_back(std::min(size_t(filament_id - 1), filament_count > 0 ? filament_count - 1 : 0)); + }; + append_fixed_filament(config().support_filament.value); + append_fixed_filament(config().support_interface_filament.value); + } + if (extruders.empty()) + extruders.emplace_back(0); + sort_remove_duplicates(extruders); + return extruders; +} + bool PrintObject::update_layer_height_profile(const ModelObject &model_object, const SlicingParameters &slicing_parameters, std::vector &layer_height_profile) { bool updated = false; diff --git a/src/slic3r/GUI/ConfigWizard.cpp b/src/slic3r/GUI/ConfigWizard.cpp index 412df19091..c9255da2b2 100644 --- a/src/slic3r/GUI/ConfigWizard.cpp +++ b/src/slic3r/GUI/ConfigWizard.cpp @@ -2637,7 +2637,8 @@ ConfigWizard::ConfigWizard(wxWindow *parent) p->load_vendors(); //BBS: add bed exclude areas p->custom_config.reset(DynamicPrintConfig::new_from_defaults_keys({ - "gcode_flavor", "printable_area", "bed_exclude_area", "bed_custom_texture", "bed_custom_model", "nozzle_diameter", "filament_diameter", "thumbnails" + "gcode_flavor", "printable_area", "bed_exclude_area_mode", "bed_exclude_area", "extruder_bed_exclude_area", + "bed_custom_texture", "bed_custom_model", "nozzle_diameter", "filament_diameter", "thumbnails" //, "nozzle_temperature", "bed_temperature" })); diff --git a/src/slic3r/GUI/Field.cpp b/src/slic3r/GUI/Field.cpp index 68a4b87ddd..a4146f33a0 100644 --- a/src/slic3r/GUI/Field.cpp +++ b/src/slic3r/GUI/Field.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -683,6 +684,14 @@ void Field::get_value_by_opt_type(wxString& str, const bool check_value/* = true m_value = into_u8(str); } break; + } else if (m_opt.opt_key == "extruder_bed_exclude_area") { + const std::string definition = into_u8(str); + if (!is_valid_bed_exclude_area_string(definition, std::numeric_limits::max())) { + show_error(m_parent, _L("Invalid exclusion volume format. Use XxY, XxY, ... or ZMIN..ZMAX;XxY, XxY, ... and separate multiple volumes with |.")); + const std::string old_value = m_value.empty() ? std::string{} : boost::any_cast(m_value); + set_value(from_u8(old_value), true); + break; + } } else if (m_opt.opt_key == "extra_solid_infills") { string ustr(str.utf8_string()); // New rule: accept either interval form (N or N#K) or explicit list (e.g. 1,7,9), with optional quotes. diff --git a/src/slic3r/GUI/PartPlate.cpp b/src/slic3r/GUI/PartPlate.cpp index 363bf982df..404352747c 100644 --- a/src/slic3r/GUI/PartPlate.cpp +++ b/src/slic3r/GUI/PartPlate.cpp @@ -1213,14 +1213,31 @@ void PartPlate::update_exclusion_volume_preview_models() m_exclusion_volume_preview_cache_key.clear(); m_exclusion_volume_floor_triangles.reset(); m_exclusion_volume_border_triangles.reset(); + m_extruder_exclusion_volume_borders.clear(); m_active_exclusion_volume_prisms.reset(); m_exclusion_volume_intersection_triangles.reset(); m_exclusion_volume_intersections_cleared = false; return; } + const std::vector> regions_by_extruder = get_bed_excluded_regions_by_extruder(*config); std::vector regions = get_bed_excluded_regions(*config); - const std::string cache_key = exclusion_volume_preview_cache_key(regions); + const BedExcludeAreaMode mode = config->opt_enum("bed_exclude_area_mode"); + std::ostringstream grouped_key; + grouped_key << exclusion_volume_preview_cache_key(regions) << "mode:" << int(mode) << ";groups:"; + for (const std::vector &group : regions_by_extruder) + grouped_key << group.size() << ','; + const std::vector filament_colors = m_plater->get_extruder_colors_from_plater_config(); + std::vector preview_colors(regions_by_extruder.size()); + const ConfigOptionInts *filament_map = wxGetApp().preset_bundle->project_config.opt("filament_map"); + for (size_t filament_id = 0; filament_id < filament_colors.size(); ++filament_id) { + const int mapped_extruder = filament_map != nullptr && filament_id < filament_map->size() ? filament_map->values[filament_id] - 1 : int(filament_id); + if (mapped_extruder >= 0 && size_t(mapped_extruder) < preview_colors.size() && preview_colors[mapped_extruder].empty()) + preview_colors[mapped_extruder] = filament_colors[filament_id]; + } + for (const std::string &color : preview_colors) + grouped_key << color << ','; + const std::string cache_key = grouped_key.str(); if (cache_key == m_exclusion_volume_preview_cache_key && !m_exclusion_volume_intersections_cleared) return; m_exclusion_volume_preview_cache_key = cache_key; @@ -1228,6 +1245,7 @@ void PartPlate::update_exclusion_volume_preview_models() m_exclusion_volume_floor_triangles.reset(); m_exclusion_volume_border_triangles.reset(); + m_extruder_exclusion_volume_borders.clear(); m_active_exclusion_volume_prisms.reset(); m_exclusion_volume_intersection_triangles.reset(); @@ -1239,6 +1257,37 @@ void PartPlate::update_exclusion_volume_preview_models() Polygons preview_footprints; std::vector active_prisms; + if (mode != BedExcludeAreaMode::Shared) { + static const std::array fallback_colors = { + ColorRGBA{ .18f, .52f, .95f, .92f }, ColorRGBA{ .95f, .35f, .22f, .92f }, + ColorRGBA{ .25f, .72f, .38f, .92f }, ColorRGBA{ .72f, .34f, .88f, .92f }, + ColorRGBA{ .95f, .68f, .16f, .92f }, ColorRGBA{ .18f, .76f, .78f, .92f } + }; + const coord_t tool_border_width = scale_(0.55); + for (size_t extruder_id = 0; extruder_id < regions_by_extruder.size(); ++extruder_id) { + ColorRGBA color = fallback_colors[extruder_id % fallback_colors.size()]; + if (extruder_id < preview_colors.size()) { + ColorRGBA decoded; + if (decode_color(preview_colors[extruder_id], decoded)) { + color = decoded; + color.a(0.92f); + } + } + + for (const BedExcludeRegion ®ion_src : regions_by_extruder[extruder_id]) { + Polygon footprint = region_src.polygon; + footprint.translate(plate_offset); + footprint.make_counter_clockwise(); + const Polygons inner = offset(Polygons{ footprint }, -tool_border_width, jtMiter, 2.0); + const ExPolygons border = inner.empty() ? ExPolygons{ expolygon_from_polygon(footprint) } : diff_ex(Polygons{ footprint }, inner); + auto model = std::make_unique(); + const float border_z = static_cast(std::max(GROUND_Z + 0.026, region_src.has_z_range ? region_src.z_min + 0.026 : GROUND_Z + 0.026)); + if (init_model_from_expolygons(*model, border, border_z) && model->is_initialized()) + m_extruder_exclusion_volume_borders.emplace_back(std::move(model), color); + } + } + } + for (const BedExcludeRegion ®ion_src : regions) { Polygon region = region_src.polygon; region.translate(plate_offset); @@ -1336,6 +1385,11 @@ void PartPlate::render_exclusion_volume_previews(bool force_default_color) m_exclusion_volume_border_triangles.set_color(ribbon_color); m_exclusion_volume_border_triangles.render(); + for (auto &colored_border : m_extruder_exclusion_volume_borders) { + colored_border.first->set_color(colored_border.second); + colored_border.first->render(); + } + m_active_exclusion_volume_prisms.set_color(prism_color); m_active_exclusion_volume_prisms.render(); diff --git a/src/slic3r/GUI/PartPlate.hpp b/src/slic3r/GUI/PartPlate.hpp index a533191860..28fae20668 100644 --- a/src/slic3r/GUI/PartPlate.hpp +++ b/src/slic3r/GUI/PartPlate.hpp @@ -7,6 +7,7 @@ #include #include #include +#include #include "libslic3r/ObjectID.hpp" #include "libslic3r/GCode/GCodeProcessor.hpp" @@ -136,6 +137,7 @@ private: GLModel m_wrapping_detection_triangles; GLModel m_exclusion_volume_floor_triangles; GLModel m_exclusion_volume_border_triangles; + std::vector, ColorRGBA>> m_extruder_exclusion_volume_borders; GLModel m_active_exclusion_volume_prisms; GLModel m_exclusion_volume_intersection_triangles; std::string m_exclusion_volume_preview_cache_key; diff --git a/src/slic3r/GUI/Plater.cpp b/src/slic3r/GUI/Plater.cpp index e1fa2b5004..02565296fe 100644 --- a/src/slic3r/GUI/Plater.cpp +++ b/src/slic3r/GUI/Plater.cpp @@ -7331,7 +7331,8 @@ Plater::priv::priv(Plater *q, MainFrame *main_frame) , main_frame(main_frame) //BBS: add bed_exclude_area , config(Slic3r::DynamicPrintConfig::new_from_defaults_keys({ - "printable_area", "bed_exclude_area", "wrapping_exclude_area", "extruder_printable_area", "bed_custom_texture", "bed_custom_model", "print_sequence", + "printable_area", "bed_exclude_area_mode", "bed_exclude_area", "extruder_bed_exclude_area", "extruder_offset", + "wrapping_exclude_area", "extruder_printable_area", "bed_custom_texture", "bed_custom_model", "print_sequence", "extruder_clearance_radius", "extruder_clearance_height_to_lid", "extruder_clearance_height_to_rod", "nozzle_height", "skirt_type", "skirt_loops", "skirt_speed","min_skirt_length", "skirt_distance", "skirt_start_angle", @@ -20090,7 +20091,8 @@ void Plater::on_config_change(const DynamicPrintConfig &config) p->partplate_list.invalid_all_slice_result(); } //BBS: add bed_exclude_area - else if (opt_key == "printable_area" || opt_key == "bed_exclude_area" + else if (opt_key == "printable_area" || opt_key == "bed_exclude_area_mode" || opt_key == "bed_exclude_area" + || opt_key == "extruder_bed_exclude_area" || opt_key == "extruder_offset" || opt_key == "bed_custom_texture" || opt_key == "bed_custom_model" || opt_key == "extruder_clearance_height_to_lid" || opt_key == "extruder_clearance_height_to_rod") { diff --git a/src/slic3r/GUI/Tab.cpp b/src/slic3r/GUI/Tab.cpp index 914e4cc7bb..fdaadda0fd 100644 --- a/src/slic3r/GUI/Tab.cpp +++ b/src/slic3r/GUI/Tab.cpp @@ -32,6 +32,7 @@ #include "wxExtensions.hpp" #include "PresetComboBoxes.hpp" #include +#include #include "GUI_App.hpp" #include "GUI_ObjectList.hpp" @@ -1826,6 +1827,26 @@ void Tab::on_value_change(const std::string& opt_key, const boost::any& value) printer_tab->on_gcode_flavor_changed(); } + if (opt_key == "bed_exclude_area_mode" && m_type == Preset::TYPE_PRINTER && + m_config->opt_enum("bed_exclude_area_mode") == BedExcludeAreaMode::PerExtruder) { + auto *per_extruder = m_config->option("extruder_bed_exclude_area"); + const auto *shared = m_config->option("bed_exclude_area"); + const size_t extruder_count = m_config->option("nozzle_diameter")->size(); + const bool definitions_empty = per_extruder == nullptr || + std::all_of(per_extruder->values.begin(), per_extruder->values.end(), [](const std::string &entry) { return entry.empty(); }); + + if (definitions_empty && shared != nullptr && extruder_count > 0) { + const std::string serialized = shared->serialize(); + const bool valid_shared_definition = shared->values.size() >= 3 || + (has_bed_exclusion_volume_syntax(*shared) && + is_valid_bed_exclude_area_string(serialized, std::numeric_limits::max())); + DynamicPrintConfig new_conf = *m_config; + new_conf.set_key_value("extruder_bed_exclude_area", + new ConfigOptionStrings(std::vector(extruder_count, valid_shared_definition ? serialized : std::string{}))); + m_config_manipulation.apply(m_config, &new_conf); + } + } + if (opt_key == "compatible_prints") this->compatible_widget_reload(m_compatible_prints); if (opt_key == "compatible_printers") @@ -5002,6 +5023,7 @@ void TabPrinter::build_fff() return create_bed_shape_widget(parent); }); optgroup->append_single_option_line("parallel_printheads_count"); + optgroup->append_single_option_line("bed_exclude_area_mode"); Option option = optgroup->get_option("bed_exclude_area"); option.opt.full_width = true; optgroup->append_single_option_line(option, "printer_basic_information_printable_space#excluded-bed-area"); @@ -5638,6 +5660,10 @@ if (is_marlin_flavor) option.opt.full_width = true; optgroup->append_single_option_line(option, "printer_extruder_basic_information#extruder-offset-position"); + Option exclusion_option = optgroup->get_option("extruder_bed_exclude_area", extruder_idx); + exclusion_option.opt.full_width = true; + optgroup->append_single_option_line(exclusion_option, "printer_basic_information_printable_space#excluded-bed-area"); + optgroup->m_on_change = [this, extruder_idx](const t_config_option_key& opt_key, boost::any value) { bool is_SEMM = m_config->opt_bool("single_extruder_multi_material"); @@ -6065,6 +6091,11 @@ void TabPrinter::toggle_options() const bool support_parallel_printheads = printer_cfg.opt_bool("support_parallel_printheads"); toggle_line("parallel_printheads_count", support_parallel_printheads); + const size_t exclusion_extruder_count = m_preset_bundle->get_printer_extruder_count(); + const BedExcludeAreaMode exclusion_mode = m_config->opt_enum("bed_exclude_area_mode"); + toggle_line("bed_exclude_area_mode", exclusion_extruder_count > 1); + toggle_line("bed_exclude_area", exclusion_extruder_count <= 1 || exclusion_mode != BedExcludeAreaMode::PerExtruder); + toggle_line("fan_direction", m_config->opt_bool("auxiliary_fan")); // The cooling filter and air filtration are alternative accessories: show only the one the printer supports. @@ -6122,6 +6153,8 @@ void TabPrinter::toggle_options() toggle_option("extruder_printable_area", false, i); // disable toggle_line("extruder_printable_area", m_preset_bundle->get_printer_extruder_count() == 2, i); //hide + const bool per_extruder_exclusions = m_config->opt_enum("bed_exclude_area_mode") == BedExcludeAreaMode::PerExtruder; + toggle_line("extruder_bed_exclude_area", m_preset_bundle->get_printer_extruder_count() > 1 && per_extruder_exclusions, i); toggle_option("extruder_printable_height", false, i); toggle_line("extruder_printable_height", m_preset_bundle->get_printer_extruder_count() == 2, i); diff --git a/tests/fff_print/test_print.cpp b/tests/fff_print/test_print.cpp index 6bff945fc3..9ef63dff02 100644 --- a/tests/fff_print/test_print.cpp +++ b/tests/fff_print/test_print.cpp @@ -119,6 +119,23 @@ size_t count_opt_key(const std::vector& warnings, const s [&](const StringObjectException& w) { return w.opt_key == key; }); } +DynamicPrintConfig dual_extruder_exclusion_config(FilamentMapMode map_mode, int mapped_extruder) +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_num_extruders(2); + config.set_key_value("nozzle_diameter", new ConfigOptionFloats{ 0.4, 0.4 }); + config.set_key_value("extruder_offset", new ConfigOptionPoints{ Vec2d::Zero(), Vec2d(20.0, 0.0) }); + config.set_key_value("extruder_printable_height", new ConfigOptionFloatsNullable{ 256.0, 256.0 }); + config.set_key_value("bed_exclude_area_mode", new ConfigOptionEnum(BedExcludeAreaMode::PerExtruder)); + config.set_key_value("extruder_bed_exclude_area", new ConfigOptionStrings{ + "0..256;-100x-100,300x-100,300x300,-100x300", + "" + }); + config.set_key_value("filament_map_mode", new ConfigOptionEnum(map_mode)); + config.set_key_value("filament_map", new ConfigOptionInts{ mapped_extruder }); + return config; +} + // Make `default_acceleration` exceed the machine's extruding-acceleration limit. void trigger_acceleration_warning(DynamicPrintConfig& c) { @@ -145,6 +162,26 @@ void trigger_precise_wall_warning(DynamicPrintConfig& c) } // namespace +TEST_CASE("Print validation applies exclusion volumes to the relevant extruder", "[Print][BedExclude][MultiNozzle]") +{ + std::vector warnings; + + SECTION("manual mapping rejects the colliding extruder") { + const StringObjectException error = validate_cubes(dual_extruder_exclusion_config(fmmManual, 1), warnings); + CHECK(error.string.find("extruder 1") != std::string::npos); + } + + SECTION("manual mapping accepts a clear extruder") { + const StringObjectException error = validate_cubes(dual_extruder_exclusion_config(fmmManual, 2), warnings); + CHECK(error.string.empty()); + } + + SECTION("automatic mapping remains valid when at least one extruder is clear") { + const StringObjectException error = validate_cubes(dual_extruder_exclusion_config(fmmAutoForMatch, 1), warnings); + CHECK(error.string.empty()); + } +} + // --------------------------------------------------------------------------- // {first_object_name} filename placeholder // --------------------------------------------------------------------------- diff --git a/tests/libslic3r/CMakeLists.txt b/tests/libslic3r/CMakeLists.txt index 2f859f46fe..187bb8e019 100644 --- a/tests/libslic3r/CMakeLists.txt +++ b/tests/libslic3r/CMakeLists.txt @@ -9,6 +9,7 @@ add_executable(${_TEST_NAME}_tests test_arrange.cpp test_bambu_networking.cpp test_buildvolume.cpp + test_bed_exclude_regions.cpp test_calib.cpp test_clipper_offset.cpp test_clipper_utils.cpp diff --git a/tests/libslic3r/test_bed_exclude_regions.cpp b/tests/libslic3r/test_bed_exclude_regions.cpp new file mode 100644 index 0000000000..ff61f404d4 --- /dev/null +++ b/tests/libslic3r/test_bed_exclude_regions.cpp @@ -0,0 +1,93 @@ +#include + +#include "libslic3r/PrintConfig.hpp" + +using namespace Slic3r; + +namespace { + +DynamicPrintConfig two_extruder_config() +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_key_value("nozzle_diameter", new ConfigOptionFloats{ 0.4, 0.4 }); + config.set_key_value("extruder_offset", new ConfigOptionPoints{ Vec2d(0.0, 0.0), Vec2d(20.0, 5.0) }); + config.set_key_value("master_extruder_id", new ConfigOptionInt(1)); + config.set_key_value("printable_height", new ConfigOptionFloat(200.0)); + config.set_deserialize_strict("bed_exclude_area", "10..30;0x0,10x0,10x10,0x10"); + return config; +} + +BoundingBox region_bounds(const BedExcludeRegion ®ion) +{ + return get_extents(region.polygon); +} + +} // namespace + +TEST_CASE("Shared exclusion volumes resolve identically for every extruder", "[PrintConfig][BedExclude]") +{ + DynamicPrintConfig config = two_extruder_config(); + config.set_key_value("bed_exclude_area_mode", new ConfigOptionEnum(BedExcludeAreaMode::Shared)); + + const auto groups = get_bed_excluded_regions_by_extruder(config); + REQUIRE(groups.size() == 2); + REQUIRE(groups[0].size() == 1); + REQUIRE(groups[1].size() == 1); + CHECK(groups[0][0].polygon.points == groups[1][0].polygon.points); + CHECK(groups[0][0].z_min == Catch::Approx(10.0)); + CHECK(groups[0][0].z_max == Catch::Approx(30.0)); + + // The global compatibility view returns a shared definition only once. + CHECK(get_bed_excluded_regions(config).size() == 1); +} + +TEST_CASE("Toolhead-relative exclusion volumes follow nozzle offset deltas", "[PrintConfig][BedExclude]") +{ + DynamicPrintConfig config = two_extruder_config(); + config.set_key_value("bed_exclude_area_mode", new ConfigOptionEnum(BedExcludeAreaMode::ToolheadOffset)); + + const auto groups = get_bed_excluded_regions_by_extruder(config); + REQUIRE(groups.size() == 2); + REQUIRE(groups[0].size() == 1); + REQUIRE(groups[1].size() == 1); + + const BoundingBox reference = region_bounds(groups[0][0]); + const BoundingBox offset = region_bounds(groups[1][0]); + CHECK(unscale(offset.min.x() - reference.min.x()) == Catch::Approx(20.0)); + CHECK(unscale(offset.min.y() - reference.min.y()) == Catch::Approx(5.0)); + CHECK(groups[1][0].z_min == Catch::Approx(groups[0][0].z_min)); + CHECK(groups[1][0].z_max == Catch::Approx(groups[0][0].z_max)); +} + +TEST_CASE("Individual exclusion volumes are authoritative per extruder", "[PrintConfig][BedExclude]") +{ + DynamicPrintConfig config = two_extruder_config(); + config.set_key_value("bed_exclude_area_mode", new ConfigOptionEnum(BedExcludeAreaMode::PerExtruder)); + config.set_key_value("extruder_bed_exclude_area", new ConfigOptionStrings{ + "0..25;0x0,8x0,8x8,0x8|40..60;20x20,30x20,30x30,20x30", + "" + }); + + const auto groups = get_bed_excluded_regions_by_extruder(config); + REQUIRE(groups.size() == 2); + CHECK(groups[0].size() == 2); + CHECK(groups[1].empty()); + CHECK(groups[0][0].z_min == Catch::Approx(0.0)); + CHECK(groups[0][0].z_max == Catch::Approx(25.0)); + CHECK(groups[0][1].z_min == Catch::Approx(40.0)); + CHECK(groups[0][1].z_max == Catch::Approx(60.0)); +} + +TEST_CASE("Offset mode honours a non-zero reference extruder", "[PrintConfig][BedExclude]") +{ + DynamicPrintConfig config = two_extruder_config(); + config.set_key_value("master_extruder_id", new ConfigOptionInt(2)); + config.set_key_value("bed_exclude_area_mode", new ConfigOptionEnum(BedExcludeAreaMode::ToolheadOffset)); + + const auto groups = get_bed_excluded_regions_by_extruder(config); + REQUIRE(groups.size() == 2); + const BoundingBox first = region_bounds(groups[0][0]); + const BoundingBox reference = region_bounds(groups[1][0]); + CHECK(unscale(first.min.x() - reference.min.x()) == Catch::Approx(-20.0)); + CHECK(unscale(first.min.y() - reference.min.y()) == Catch::Approx(-5.0)); +} From 21760cc979538720268a139852e80e02ef2f62cc Mon Sep 17 00:00:00 2001 From: Harry Loud Date: Wed, 15 Jul 2026 20:28:57 +0100 Subject: [PATCH 09/38] Fix multi-nozzle exclusion collision mapping --- src/libslic3r/Print.cpp | 21 ++- src/libslic3r/PrintConfig.cpp | 24 +++ src/libslic3r/PrintConfig.hpp | 6 + src/slic3r/GUI/3DScene.cpp | 71 ++++++-- src/slic3r/GUI/3DScene.hpp | 2 +- src/slic3r/GUI/GLCanvas3D.cpp | 35 ++-- src/slic3r/GUI/PartPlate.cpp | 315 +++++++++++++++++++++++++++++----- src/slic3r/GUI/PartPlate.hpp | 13 ++ src/slic3r/GUI/Plater.cpp | 12 +- 9 files changed, 428 insertions(+), 71 deletions(-) diff --git a/src/libslic3r/Print.cpp b/src/libslic3r/Print.cpp index d4a421303f..8d7a8ec225 100644 --- a/src/libslic3r/Print.cpp +++ b/src/libslic3r/Print.cpp @@ -97,7 +97,13 @@ static std::optional colliding_bed_exclusion_extruder( if (regions_by_extruder.empty()) return std::nullopt; - if (is_auto_filament_map_mode(print.get_filament_map_mode())) { + const bool automatic = is_auto_filament_map_mode(print.get_filament_map_mode()); + if (automatic && print.is_BBL_printer()) { + // Bambu automatic grouping owns the concrete filament assignment and + // the config starts with a non-authoritative [1, 1, ...] seed. Its + // geometric-unprintable input steers individual filaments away from + // colliding nozzles; validation only blocks an object when no nozzle + // can print it. std::optional first_collision; for (size_t extruder_id = 0; extruder_id < regions_by_extruder.size(); ++extruder_id) { if (!instance.intersects_bed_exclude_regions(regions_by_extruder[extruder_id])) @@ -109,7 +115,12 @@ static std::optional colliding_bed_exclusion_extruder( } for (const unsigned int filament_id : print_object.printing_extruders()) { - const size_t extruder_id = std::min(print.get_extruder_id(filament_id), regions_by_extruder.size() - 1); + const int resolved_extruder = bed_exclusion_extruder_for_filament( + filament_id, print.get_filament_maps(), print.get_filament_map_mode(), print.is_BBL_printer(), + true, regions_by_extruder.size()); + if (resolved_extruder < 0) + continue; + const size_t extruder_id = size_t(resolved_extruder); if (instance.intersects_bed_exclude_regions(regions_by_extruder[extruder_id])) return extruder_id; } @@ -765,7 +776,8 @@ StringObjectException Print::sequential_print_clearance_valid(const Print &print const std::optional collision_extruder = colliding_bed_exclusion_extruder( print, *print_object, *instance.model_instance, exclusion_volumes); if (collision_extruder.has_value()) { - const std::string collision_message = is_auto_filament_map_mode(print.get_filament_map_mode()) ? + const std::string collision_message = + is_auto_filament_map_mode(print.get_filament_map_mode()) && print.is_BBL_printer() ? (boost::format(L("%1% intersects exclusion volumes for every available extruder.")) % instance.model_instance->get_object()->name).str() : (boost::format(L("%1% intersects an exclusion volume for extruder %2%.")) % instance.model_instance->get_object()->name % (*collision_extruder + 1)).str(); if (single_object_exception.string.empty()) { @@ -1063,7 +1075,8 @@ static StringObjectException layered_print_cleareance_valid(const Print &print, } if (const std::optional collision_extruder = colliding_bed_exclusion_extruder( print, *inst->print_object, *inst->model_instance, exclusion_volumes); collision_extruder.has_value()) { - const std::string message = is_auto_filament_map_mode(print.get_filament_map_mode()) ? + const std::string message = + is_auto_filament_map_mode(print.get_filament_map_mode()) && print.is_BBL_printer() ? (boost::format(L("%1% intersects exclusion volumes for every available extruder.")) % inst->model_instance->get_object()->name).str() : (boost::format(L("%1% intersects an exclusion volume for extruder %2%.")) % inst->model_instance->get_object()->name % (*collision_extruder + 1)).str(); return {message + "\n", inst->model_instance}; diff --git a/src/libslic3r/PrintConfig.cpp b/src/libslic3r/PrintConfig.cpp index 039efbae04..58c9c7f5df 100644 --- a/src/libslic3r/PrintConfig.cpp +++ b/src/libslic3r/PrintConfig.cpp @@ -13018,6 +13018,30 @@ static std::vector flatten_bed_excluded_regions( } // namespace +int bed_exclusion_extruder_for_filament( + const size_t filament_id, const std::vector &configured_map, const FilamentMapMode map_mode, + const bool is_bambu, const bool automatic_map_resolved, const size_t extruder_count) +{ + if (extruder_count == 0) + return -1; + + const bool automatic = is_auto_filament_map_mode(map_mode); + if (automatic && is_bambu && !automatic_map_resolved) + return -1; + + // Generic multi-tool printers use filament ids as tool ids. Their global + // filament_map still carries the Bambu grouping seed [1, 1, ...], which is + // not a meaningful assignment for these machines. + if (automatic && !is_bambu && filament_id < extruder_count) + return int(filament_id); + + if (filament_id < configured_map.size() && configured_map[filament_id] > 0 && + size_t(configured_map[filament_id]) <= extruder_count) + return configured_map[filament_id] - 1; + + return filament_id < extruder_count ? int(filament_id) : -1; +} + std::vector> get_bed_excluded_regions_by_extruder(const DynamicPrintConfig &cfg) { const ConfigOptionFloat *height_option = cfg.opt("printable_height"); diff --git a/src/libslic3r/PrintConfig.hpp b/src/libslic3r/PrintConfig.hpp index 758399af31..109d1544ad 100644 --- a/src/libslic3r/PrintConfig.hpp +++ b/src/libslic3r/PrintConfig.hpp @@ -2326,6 +2326,12 @@ std::vector get_bed_excluded_regions(const DynamicPrintConfig std::vector get_bed_excluded_regions(const PrintConfig &cfg, size_t extruder_id); std::vector> get_bed_excluded_regions_by_extruder(const DynamicPrintConfig &cfg); std::vector> get_bed_excluded_regions_by_extruder(const PrintConfig &cfg); +// Resolve the nozzle whose exclusion regions apply to a filament. Filament +// and return ids are 0-based. Returns -1 while Bambu automatic grouping has +// no concrete assignment. +int bed_exclusion_extruder_for_filament(size_t filament_id, const std::vector &configured_map, + FilamentMapMode map_mode, bool is_bambu, bool automatic_map_resolved, + size_t extruder_count); bool has_bed_exclusion_volume_syntax(const ConfigOptionPoints& bed_exclude_area); bool is_valid_bed_exclude_area_string(const std::string &value, double printable_height); Slic3r::Polygons get_bed_excluded_area(const PrintConfig& cfg); diff --git a/src/slic3r/GUI/3DScene.cpp b/src/slic3r/GUI/3DScene.cpp index 6dbea1272a..5d272bb86b 100644 --- a/src/slic3r/GUI/3DScene.cpp +++ b/src/slic3r/GUI/3DScene.cpp @@ -1355,10 +1355,21 @@ bool GLVolumeCollection::check_outside_state(const BuildVolume &build_volume, Mo BuildVolume plate_build_volume(pp_bed_shape, build_volume.printable_height(), build_volume.extruder_areas(), build_volume.extruder_heights()); const std::vector& exclude_areas = curr_plate->get_exclude_areas(); + std::vector> exclusion_regions = + get_bed_excluded_regions_by_extruder(*GUI::wxGetApp().plater()->config()); + const Vec3d plate_origin = curr_plate->get_origin(); + const Point exclusion_offset(scale_(plate_origin.x()), scale_(plate_origin.y())); + for (std::vector ®ions : exclusion_regions) + for (BedExcludeRegion ®ion : regions) + region.polygon.translate(exclusion_offset); + std::map>> objects_unprintable_filaments; - int extruder_count = build_volume.get_extruder_area_count(); + const DynamicPrintConfig &plate_project_config = GUI::wxGetApp().preset_bundle->project_config; + const int build_volume_extruder_count = build_volume.get_extruder_area_count(); + const int extruder_count = std::max(build_volume_extruder_count, int(exclusion_regions.size())); std::vector> unprintable_filament_ids(extruder_count, std::set()); std::set partly_objects_set; + std::map, std::vector> instance_inside_exclusion_regions; const ModelObjectPtrs &model_objects = model.objects; for (GLVolume* volume : this->volumes) { @@ -1373,7 +1384,7 @@ bool GLVolumeCollection::check_outside_state(const BuildVolume &build_volume, Mo //FIXME this test does not evaluate collision of a build volume bounding box with non-convex objects. const BoundingBoxf3& bb = volume_bbox(*volume); state = plate_build_volume.volume_state_bbox(bb); - if ((state == BuildVolume::ObjectState::Inside) && (extruder_count > 1)) + if ((state == BuildVolume::ObjectState::Inside) && (build_volume_extruder_count > 1)) { state = plate_build_volume.check_volume_bbox_state_with_extruder_areas(bb, inside_extruders); } @@ -1387,7 +1398,7 @@ bool GLVolumeCollection::check_outside_state(const BuildVolume &build_volume, Mo const indexed_triangle_set& convex_mesh_it = volume_convex_mesh(*volume).its; const Transform3f trafo = volume->world_matrix().cast(); state = plate_build_volume.object_state(convex_mesh_it, trafo, volume_sinking(*volume)); - if ((state == BuildVolume::ObjectState::Inside) && (extruder_count > 1)) + if ((state == BuildVolume::ObjectState::Inside) && (build_volume_extruder_count > 1)) { state = plate_build_volume.check_object_state_with_extruder_areas(convex_mesh_it, trafo, inside_extruders); } @@ -1400,12 +1411,52 @@ bool GLVolumeCollection::check_outside_state(const BuildVolume &build_volume, Mo } assert(state != BuildVolume::ObjectState::Below); + // Preserve Orca's native printable-area result separately. + // Exclusion collisions have current-map semantics and must not + // leak into the later "unprintable on every possible nozzle" + // aggregation used by automatic printable-area assignment. + const std::vector printable_area_inside_extruders = inside_extruders; + + // Newer Orca resolves live multi-nozzle placement through this + // per-extruder state vector. Merge exclusion-volume collisions + // into the same source of truth instead of relying only on the + // legacy PartPlate::check_outside() path. + if ((state == BuildVolume::ObjectState::Inside || state == BuildVolume::ObjectState::Limited) && + volume->object_idx() >= 0 && volume->object_idx() < int(model_objects.size()) && + volume->instance_idx() >= 0 && + volume->instance_idx() < int(model_objects[volume->object_idx()]->instances.size())) { + inside_extruders.resize(extruder_count, true); + + const std::pair instance_key{ volume->object_idx(), volume->instance_idx() }; + auto [cache_it, inserted] = instance_inside_exclusion_regions.emplace( + instance_key, std::vector(extruder_count, true)); + if (inserted) { + const ModelInstance *instance = model_objects[volume->object_idx()]->instances[volume->instance_idx()]; + for (size_t extruder_id = 0; extruder_id < exclusion_regions.size(); ++extruder_id) { + if (instance->intersects_bed_exclude_regions(exclusion_regions[extruder_id])) + cache_it->second[extruder_id] = false; + } + } + + bool exclusion_limited = false; + for (size_t extruder_id = 0; extruder_id < cache_it->second.size(); ++extruder_id) { + if (!cache_it->second[extruder_id]) { + inside_extruders[extruder_id] = false; + exclusion_limited = true; + } + } + + if (exclusion_limited && state == BuildVolume::ObjectState::Inside) + state = extruder_count > 1 ? BuildVolume::ObjectState::Limited : BuildVolume::ObjectState::Colliding; + + } + if (state == BuildVolume::ObjectState::Limited) { //unprintable_filament_ids.resize(inside_extruders.size()); ModelObject *model_object = model_objects[volume->object_idx()]; ModelVolume *model_volume = model_object->volumes[volume->volume_idx()]; - for (size_t i = 0; i < inside_extruders.size(); ++i) { - if (!inside_extruders[i]) { + for (size_t i = 0; i < printable_area_inside_extruders.size(); ++i) { + if (!printable_area_inside_extruders[i]) { std::vector filaments = model_volume->get_extruders(); unprintable_filament_ids[i].insert(filaments.begin(), filaments.end()); if (object_results) { @@ -1480,8 +1531,7 @@ bool GLVolumeCollection::check_outside_state(const BuildVolume &build_volume, Mo //check per-object error for extruder areas if (object_results && (extruder_count > 1)) { - const auto& project_config = Slic3r::GUI::wxGetApp().preset_bundle->project_config; - object_results->mode = curr_plate->get_real_filament_map_mode(project_config); + object_results->mode = curr_plate->get_real_filament_map_mode(plate_project_config); if (object_results->mode < FilamentMapMode::fmmManual) { std::vector conflict_filament_vector; @@ -1543,8 +1593,7 @@ bool GLVolumeCollection::check_outside_state(const BuildVolume &build_volume, Mo else { std::set conflict_filaments_set; - const auto& project_config = Slic3r::GUI::wxGetApp().preset_bundle->project_config; - std::vector filament_maps = curr_plate->get_real_filament_maps(project_config); + std::vector filament_maps = curr_plate->get_real_filament_maps(plate_project_config); for (auto& object_map: objects_unprintable_filaments) { ModelObject *model_object = object_map.first; @@ -1559,7 +1608,8 @@ bool GLVolumeCollection::check_outside_state(const BuildVolume &build_volume, Mo for (int filament: filaments_set) { - if (filament_maps[filament - 1] == extruder_id) + if (filament > 0 && size_t(filament) <= filament_maps.size() && + filament_maps[filament - 1] == extruder_id) { object_filament_info.manual_filaments.emplace(filament, extruder_id); object_results->filament_maps[filament] = extruder_id; @@ -1576,6 +1626,7 @@ bool GLVolumeCollection::check_outside_state(const BuildVolume &build_volume, Mo object_results->filaments = std::vector(conflict_filaments_set.begin(), conflict_filaments_set.end()); } } + } /*for (GLVolume* volume : this->volumes) diff --git a/src/slic3r/GUI/3DScene.hpp b/src/slic3r/GUI/3DScene.hpp index 1217d32182..44da9ceed1 100644 --- a/src/slic3r/GUI/3DScene.hpp +++ b/src/slic3r/GUI/3DScene.hpp @@ -60,7 +60,7 @@ enum ModelInstanceEPrintVolumeState : unsigned char; using ModelObjectPtrs = std::vector; struct ObjectFilamentInfo { - ModelObject* object; + ModelObject* object { nullptr }; std::map manual_filaments; //manual mode: filament id -> extruder id can not be printed std::vector auto_filaments; //auto mode: filaments in all extruder's outside area diff --git a/src/slic3r/GUI/GLCanvas3D.cpp b/src/slic3r/GUI/GLCanvas3D.cpp index 40d4bcd0bc..2f36ea40a8 100644 --- a/src/slic3r/GUI/GLCanvas3D.cpp +++ b/src/slic3r/GUI/GLCanvas3D.cpp @@ -1435,27 +1435,31 @@ static std::pair construct_extruder_unprintable_error(ObjectFilament auto mode = object_result.mode; for (auto& obj_filament : object_result.object_filaments) { + bool found_left = false; + bool found_right = false; + if (mode == FilamentMapMode::fmmManual) { for (auto& elem : obj_filament.manual_filaments) { - bool found_left = false, found_right = false; - int filamnet_id = elem.first; int extruder_id = elem.second; - if (extruder_id == 1 && !found_left) { + if (extruder_id == 1) { found_left = true; - left_unprintable_objects.emplace_back(obj_filament); } - if (extruder_id == 2 && !found_right) { + if (extruder_id == 2) { found_right = true; - right_unprintable_objects.emplace_back(obj_filament); } } } else { if (!obj_filament.auto_filaments.empty()) { - left_unprintable_objects.emplace_back(obj_filament); - right_unprintable_objects.emplace_back(obj_filament); + found_left = true; + found_right = true; } } + + if (found_left) + left_unprintable_objects.emplace_back(obj_filament); + if (found_right) + right_unprintable_objects.emplace_back(obj_filament); } Preset &preset = GUI::wxGetApp().preset_bundle->printers.get_edited_preset(); @@ -1491,7 +1495,7 @@ static std::pair construct_extruder_unprintable_error(ObjectFilament model_prefix = (boost::format(_u8L("The position or size of some models exceeds the %s's printable range.")) % nozzle_name).str(); else model_prefix = (boost::format(_u8L("The position or size of the model %s exceeds the %s's printable range.")) - %object_result.object_filaments.front().object->name % nozzle_name).str(); + %unprintable_objs.front().object->name % nozzle_name).str(); tips[idx] += model_prefix; tips[idx] += (boost::format(_u8L(" Please check and adjust the part's position or size to fit the printable range:\n"))).str(); @@ -2061,6 +2065,9 @@ void GLCanvas3D::render(bool only_init) // Depth pass for object-on-object and self shadows; consumed by the gouraud shader below. _render_shadows(camera.get_view_matrix(), camera.get_projection_matrix()); _render_objects(GLVolumeCollection::ERenderType::Opaque, !m_gizmos.is_running()); + if (!no_partplate) + wxGetApp().plater()->get_partplate_list().render_exclusion_volume_intersections( + camera.get_view_matrix(), camera.get_projection_matrix()); _render_sla_slices(); _render_selection(); _render_objects(GLVolumeCollection::ERenderType::Transparent, !m_gizmos.is_running()); @@ -5598,10 +5605,12 @@ void GLCanvas3D::set_cursor(ECursorType type) void GLCanvas3D::mouse_up_cleanup() { - if (m_mouse.dragging) { - if (PartPlate *plate = wxGetApp().plater()->get_partplate_list().get_curr_plate()) - plate->invalidate_exclusion_volume_preview(); - } + // Both direct dragging and gizmo manipulation clear the expensive red + // exclusion-intersection mesh while moving. Gizmo drags do not always set + // m_mouse.dragging, so every completed mouse operation must allow the + // cached preview to restore/recompute that mesh. + if (PartPlate *plate = wxGetApp().plater()->get_partplate_list().get_curr_plate()) + plate->invalidate_exclusion_volume_preview(); m_moving = false; m_camera_movement = false; diff --git a/src/slic3r/GUI/PartPlate.cpp b/src/slic3r/GUI/PartPlate.cpp index 404352747c..f32869689e 100644 --- a/src/slic3r/GUI/PartPlate.cpp +++ b/src/slic3r/GUI/PartPlate.cpp @@ -1087,6 +1087,15 @@ void PartPlate::render_exclude_area(bool force_default_color) { if (force_default_color) //for thumbnail case return; + // Non-shared modes are rendered from their resolved per-extruder regions in + // render_exclusion_volume_previews(). The legacy model only represents the + // master area and would otherwise fill that one region twice while leaving + // the other extruders' regions hollow. + const DynamicPrintConfig *config = m_plater != nullptr ? m_plater->config() : nullptr; + if (config != nullptr && + config->opt_enum("bed_exclude_area_mode") != BedExcludeAreaMode::Shared) + return; + ColorRGBA select_color{ .9f, .86f, .82f, .7f }; // ORCA ColorRGBA unselect_color{ .6f, .6f, .6f, .3f }; // ORCA //ColorRGBA default_color{ 0.9f, 0.9f, 0.9f, 1.0f }; @@ -1190,6 +1199,8 @@ std::string PartPlate::exclusion_volume_preview_cache_key(const std::vectorvolumes) { key << static_cast(volume) << ':'; + for (const int filament_id : volume->get_extruders()) + key << 'f' << filament_id << ','; const Transform3d volume_matrix = volume->get_matrix(); for (int r = 0; r < int(volume_matrix.matrix().rows()); ++r) for (int c = 0; c < int(volume_matrix.matrix().cols()); ++c) @@ -1221,7 +1232,9 @@ void PartPlate::update_exclusion_volume_preview_models() } const std::vector> regions_by_extruder = get_bed_excluded_regions_by_extruder(*config); - std::vector regions = get_bed_excluded_regions(*config); + std::vector regions; + for (const std::vector &extruder_regions : regions_by_extruder) + regions.insert(regions.end(), extruder_regions.begin(), extruder_regions.end()); const BedExcludeAreaMode mode = config->opt_enum("bed_exclude_area_mode"); std::ostringstream grouped_key; grouped_key << exclusion_volume_preview_cache_key(regions) << "mode:" << int(mode) << ";groups:"; @@ -1229,12 +1242,41 @@ void PartPlate::update_exclusion_volume_preview_models() grouped_key << group.size() << ','; const std::vector filament_colors = m_plater->get_extruder_colors_from_plater_config(); std::vector preview_colors(regions_by_extruder.size()); - const ConfigOptionInts *filament_map = wxGetApp().preset_bundle->project_config.opt("filament_map"); + + // Use the same effective filament-to-nozzle policy as collision checks so + // the coloured border never implies a mapping the validator does not use. + const DynamicPrintConfig &project_config = wxGetApp().preset_bundle->project_config; + const std::vector filament_map = get_effective_exclusion_filament_maps( + project_config, filament_colors.size(), regions_by_extruder.size()); + grouped_key << "map:"; + for (const int extruder_id : filament_map) + grouped_key << extruder_id << ','; + grouped_key << ';'; + grouped_key << "object_maps:"; + if (m_model != nullptr) { + for (const std::pair &object_instance : obj_to_instance_set) { + const int object_id = object_instance.first; + if (object_id < 0 || object_id >= int(m_model->objects.size())) + continue; + grouped_key << object_id << ':'; + for (const auto &[filament_id, extruder_id] : get_object_filament_extruders( + *m_model->objects[object_id], project_config, regions_by_extruder.size())) + grouped_key << filament_id << '>' << extruder_id << ','; + grouped_key << ';'; + } + } for (size_t filament_id = 0; filament_id < filament_colors.size(); ++filament_id) { - const int mapped_extruder = filament_map != nullptr && filament_id < filament_map->size() ? filament_map->values[filament_id] - 1 : int(filament_id); + const int mapped_extruder = filament_id < filament_map.size() ? filament_map[filament_id] - 1 : int(filament_id); if (mapped_extruder >= 0 && size_t(mapped_extruder) < preview_colors.size() && preview_colors[mapped_extruder].empty()) preview_colors[mapped_extruder] = filament_colors[filament_id]; } + + if (const ConfigOptionStrings *extruder_colors = config->opt("extruder_colour"); + extruder_colors != nullptr) { + for (size_t extruder_id = 0; extruder_id < preview_colors.size() && extruder_id < extruder_colors->size(); ++extruder_id) + if (preview_colors[extruder_id].empty()) + preview_colors[extruder_id] = extruder_colors->values[extruder_id]; + } for (const std::string &color : preview_colors) grouped_key << color << ','; const std::string cache_key = grouped_key.str(); @@ -1253,7 +1295,12 @@ void PartPlate::update_exclusion_volume_preview_models() Polygons floor_regions; ExPolygons border_regions; const coord_t ribbon_width = scale_(1.6); - std::vector> preview_regions; + struct PreviewRegion { + BedExcludeRegion region; + Polygon footprint; + size_t extruder_id; + }; + std::vector preview_regions; Polygons preview_footprints; std::vector active_prisms; @@ -1288,34 +1335,44 @@ void PartPlate::update_exclusion_volume_preview_models() } } - for (const BedExcludeRegion ®ion_src : regions) { - Polygon region = region_src.polygon; - region.translate(plate_offset); - region.make_counter_clockwise(); - BedExcludeRegion translated_region = region_src; - translated_region.polygon = region; - preview_regions.emplace_back(std::move(translated_region), region); - preview_footprints.emplace_back(region); + for (size_t extruder_id = 0; extruder_id < regions_by_extruder.size(); ++extruder_id) { + // Shared regions are identical for every nozzle. Keeping one copy + // avoids duplicate floor, prism and intersection geometry. + if (mode == BedExcludeAreaMode::Shared && extruder_id > 0) + break; - if (region_src.from_3d_config) { - if (!region_src.has_z_range || region_src.z_min <= EPSILON) { - floor_regions.emplace_back(region); - } else { - const Polygons inner = offset(Polygons{ region }, -ribbon_width, jtMiter, 2.0); - ExPolygons border = inner.empty() ? ExPolygons{ expolygon_from_polygon(region) } : diff_ex(Polygons{ region }, inner); - border_regions.insert(border_regions.end(), border.begin(), border.end()); + for (const BedExcludeRegion ®ion_src : regions_by_extruder[extruder_id]) { + Polygon region = region_src.polygon; + region.translate(plate_offset); + region.make_counter_clockwise(); + BedExcludeRegion translated_region = region_src; + translated_region.polygon = region; + preview_regions.push_back({ std::move(translated_region), region, extruder_id }); + preview_footprints.emplace_back(region); + + // In non-shared modes these resolved regions are the authoritative bed + // preview, including legacy master polygons duplicated by nozzle offset. + // Shared legacy polygons continue to use m_exclude_triangles above. + if (region_src.from_3d_config || mode != BedExcludeAreaMode::Shared) { + if (!region_src.has_z_range || region_src.z_min <= EPSILON) { + floor_regions.emplace_back(region); + } else { + const Polygons inner = offset(Polygons{ region }, -ribbon_width, jtMiter, 2.0); + ExPolygons border = inner.empty() ? ExPolygons{ expolygon_from_polygon(region) } : diff_ex(Polygons{ region }, inner); + border_regions.insert(border_regions.end(), border.begin(), border.end()); + } } } } const double preview_height = max_broad_phase_intersecting_object_height(preview_footprints); if (preview_height > EPSILON) { - for (const std::pair &preview_region : preview_regions) { - const BedExcludeRegion ®ion_src = preview_region.first; + for (const PreviewRegion &preview_region : preview_regions) { + const BedExcludeRegion ®ion_src = preview_region.region; const double z_min = region_src.has_z_range ? region_src.z_min : 0.0; const double z_max = std::min(region_src.z_max, preview_height); if (z_max > z_min + EPSILON) - active_prisms.push_back({ preview_region.second, z_min, z_max }); + active_prisms.push_back({ preview_region.footprint, z_min, z_max }); } } @@ -1335,11 +1392,22 @@ void PartPlate::update_exclusion_volume_preview_models() if (!instance->printable) continue; + std::set relevant_extruders; + if (mode != BedExcludeAreaMode::Shared) { + for (const auto &mapping : get_object_filament_extruders( + *object, project_config, regions_by_extruder.size())) + relevant_extruders.emplace(mapping.second); + } + Polygon hull = instance->convex_hull_2d(); const BoundingBoxf3 instance_box = object->instance_convex_hull_bounding_box(instance_id); - for (const std::pair &preview_region : preview_regions) { - const BedExcludeRegion ®ion = preview_region.first; - if (intersection(Polygons{ preview_region.second }, Polygons{ hull }).empty()) + for (const PreviewRegion &preview_region : preview_regions) { + if (mode != BedExcludeAreaMode::Shared && + relevant_extruders.find(preview_region.extruder_id) == relevant_extruders.end()) + continue; + + const BedExcludeRegion ®ion = preview_region.region; + if (intersection(Polygons{ preview_region.footprint }, Polygons{ hull }).empty()) continue; if (instance_box.max.z() < region.z_min || instance_box.min.z() > region.z_max) continue; @@ -1393,8 +1461,6 @@ void PartPlate::render_exclusion_volume_previews(bool force_default_color) m_active_exclusion_volume_prisms.set_color(prism_color); m_active_exclusion_volume_prisms.render(); - render_exclusion_volume_intersections(); - glsafe(::glLineWidth(1.0f * m_scale_factor)); glsafe(::glDepthMask(GL_TRUE)); } @@ -2466,6 +2532,122 @@ int PartPlate::get_logical_extruder_by_filament_id(const DynamicConfig& g_config return filament_map[idx - 1] - 1; } +std::vector PartPlate::get_effective_exclusion_filament_maps( + const DynamicConfig &g_config, const size_t filament_count, const size_t extruder_count) const +{ + std::vector result(filament_count, 0); + if (extruder_count == 0) + return result; + + const std::vector configured_map = get_real_filament_maps(g_config); + const FilamentMapMode map_mode = get_real_filament_map_mode(g_config); + PresetBundle *preset_bundle = wxGetApp().preset_bundle; + const bool is_bambu = preset_bundle != nullptr && preset_bundle->is_bbl_vendor(); + const bool automatic = is_auto_filament_map_mode(map_mode); + const bool automatic_map_resolved = !automatic || !get_filament_maps().empty(); + for (size_t filament_id = 0; filament_id < filament_count; ++filament_id) { + const int extruder_id = bed_exclusion_extruder_for_filament( + filament_id, configured_map, map_mode, is_bambu, automatic_map_resolved, extruder_count); + if (extruder_id >= 0) + result[filament_id] = extruder_id + 1; + } + return result; +} + +std::map PartPlate::get_object_filament_extruders( + const ModelObject &object, const DynamicConfig &g_config, const size_t extruder_count) const +{ + std::set filament_ids; + const DynamicPrintConfig &process_config = wxGetApp().preset_bundle->prints.get_edited_preset().config; + const auto effective_option = [&object, &process_config](const char *key) -> const ConfigOption * { + if (const ConfigOption *option = object.config.option(key); option != nullptr) + return option; + return process_config.option(key); + }; + const auto effective_int = [&effective_option](const char *key) { + const ConfigOption *option = effective_option(key); + return option != nullptr ? option->getInt() : 0; + }; + const auto effective_float = [&effective_option](const char *key) { + const ConfigOption *option = effective_option(key); + return option != nullptr ? option->getFloat() : 0.0; + }; + const auto effective_bool = [&effective_option](const char *key) { + const ConfigOption *option = effective_option(key); + return option != nullptr && option->getBool(); + }; + + const bool has_brim = effective_int("brim_type") != int(BrimType::btNoBrim) && effective_float("brim_width") > 0.0; + const int wall_loops = effective_int("wall_loops"); + const double sparse_infill_density = effective_float("sparse_infill_density"); + const int top_shell_layers = effective_int("top_shell_layers"); + const int bottom_shell_layers = effective_int("bottom_shell_layers"); + const std::array, 6> feature_filament_keys = { + std::pair{ "outer_wall_filament_id", wall_loops > 0 || has_brim }, + std::pair{ "inner_wall_filament_id", wall_loops > 1 }, + std::pair{ "sparse_infill_filament_id", sparse_infill_density > 0.0 }, + std::pair{ "internal_solid_filament_id", sparse_infill_density > 0.0 || top_shell_layers > 0 || bottom_shell_layers > 0 }, + std::pair{ "top_surface_filament_id", top_shell_layers > 0 }, + std::pair{ "bottom_surface_filament_id", bottom_shell_layers > 0 } + }; + auto collect_config_filaments = [&filament_ids, &feature_filament_keys](const DynamicConfig &config) { + for (const auto &[key, active] : feature_filament_keys) { + if (active) { + if (const ConfigOption *option = config.option(key); option != nullptr && option->getInt() > 0) + filament_ids.emplace(option->getInt()); + } + } + if (const ConfigOption *option = config.option("extruder"); option != nullptr && option->getInt() > 0) + filament_ids.emplace(option->getInt()); + }; + + for (const ModelVolume *volume : object.volumes) { + const std::vector volume_filaments = volume->get_extruders(); + filament_ids.insert(volume_filaments.begin(), volume_filaments.end()); + collect_config_filaments(volume->config.get()); + } + collect_config_filaments(object.config.get()); + for (const auto &layer_range : object.layer_config_ranges) + collect_config_filaments(layer_range.second.get()); + + // Process-level feature assignments also apply when the object has no + // override. This mirrors the relevant parts of PrintObject::printing_extruders() + // closely enough for an unsliced placement preview. + for (const auto &[key, active] : feature_filament_keys) { + if (active && !object.config.has(key) && process_config.has(key) && process_config.opt_int(key) > 0) + filament_ids.emplace(process_config.opt_int(key)); + } + + const bool has_support = effective_bool("enable_support") || effective_int("raft_layers") > 0; + if (has_support) { + const int support_filament = effective_int("support_filament"); + const int interface_filament = effective_int("support_interface_filament"); + if (support_filament > 0) + filament_ids.emplace(support_filament); + if (interface_filament > 0) + filament_ids.emplace(interface_filament); + } + + // Match Orca's normal fallback for an unassigned object. + if (filament_ids.empty()) + filament_ids.emplace(1); + + const size_t required_filament_count = filament_ids.empty() ? 0 : size_t(*filament_ids.rbegin()); + const std::vector filament_map = get_effective_exclusion_filament_maps( + g_config, required_filament_count, extruder_count); + std::map result; + for (const int filament_id : filament_ids) { + if (filament_id <= 0) + continue; + + const int mapped_extruder = size_t(filament_id) <= filament_map.size() && filament_map[filament_id - 1] > 0 ? + filament_map[filament_id - 1] - 1 : -1; + if (mapped_extruder >= 0 && size_t(mapped_extruder) < extruder_count) + result.emplace(filament_id, size_t(mapped_extruder)); + } + return result; +} + std::vector PartPlate::get_used_filaments() { std::vector used_filaments; @@ -3266,28 +3448,41 @@ bool PartPlate::check_outside(int obj_id, int instance_id, BoundingBoxf3* boundi const DynamicPrintConfig *config = m_plater != nullptr ? m_plater->config() : nullptr; bool checked_config_regions = false; if (config != nullptr) { - const std::vector regions = get_bed_excluded_regions(*config); - checked_config_regions = !regions.empty(); + const std::vector> regions_by_extruder = + get_bed_excluded_regions_by_extruder(*config); + const BedExcludeAreaMode mode = config->opt_enum("bed_exclude_area_mode"); + // The legacy outside flag has no filament/nozzle context. Keep it + // authoritative for the shared mode, but let the newer per-extruder + // placement pipeline handle offset/individual modes so a collision + // belonging to an unused nozzle does not block the whole plate. + checked_config_regions = mode != BedExcludeAreaMode::Shared; const Point plate_offset(scale_(m_origin.x()), scale_(m_origin.y())); Polygon hull = instance->convex_hull_2d(); - for (const BedExcludeRegion ®ion_src : regions) { - Polygon region = region_src.polygon; - region.translate(plate_offset); - region.make_counter_clockwise(); + const size_t groups_to_check = mode == BedExcludeAreaMode::Shared && !regions_by_extruder.empty() ? 1 : 0; + for (size_t group_id = 0; group_id < groups_to_check; ++group_id) { + const std::vector &extruder_regions = regions_by_extruder[group_id]; + checked_config_regions = checked_config_regions || !extruder_regions.empty(); + for (const BedExcludeRegion ®ion_src : extruder_regions) { + Polygon region = region_src.polygon; + region.translate(plate_offset); + region.make_counter_clockwise(); - if (intersection(Polygons{ region }, Polygons{ hull }).empty()) - continue; + if (intersection(Polygons{ region }, Polygons{ hull }).empty()) + continue; - if (instance_box.max.z() < region_src.z_min || instance_box.min.z() > region_src.z_max) - continue; + if (instance_box.max.z() < region_src.z_min || instance_box.min.z() > region_src.z_max) + continue; - BedExcludeRegion translated_region = region_src; - translated_region.polygon = region; - if (instance->intersects_bed_exclude_region(translated_region)) { - outside = true; - break; + BedExcludeRegion translated_region = region_src; + translated_region.polygon = std::move(region); + if (instance->intersects_bed_exclude_region(translated_region)) { + outside = true; + break; + } } + if (outside) + break; } } @@ -4457,6 +4652,7 @@ void PartPlate::set_filament_map_mode(const FilamentMapMode& mode) clear_filament_map_mode(); else m_config.option>("filament_map_mode", true)->value = mode; + invalidate_exclusion_volume_preview(); } std::vector PartPlate::get_filament_maps() const @@ -4471,12 +4667,14 @@ std::vector PartPlate::get_filament_maps() const void PartPlate::set_filament_maps(const std::vector& f_maps) { m_config.option("filament_map", true)->values = f_maps; + invalidate_exclusion_volume_preview(); } void PartPlate::clear_filament_map() { if (m_config.has("filament_map")) m_config.erase("filament_map"); + invalidate_exclusion_volume_preview(); } std::vector PartPlate::get_filament_volume_maps() const @@ -5164,6 +5362,39 @@ void PartPlateList::update_plates() set_shapes(m_shape, m_exclude_areas, m_wrapping_exclude_areas, m_extruder_areas, m_extruder_heights, m_logo_texture_filename, m_height_to_lid, m_height_to_rod); } +void PartPlateList::invalidate_exclusion_volume_previews() +{ + for (PartPlate *plate : m_plate_list) + if (plate != nullptr) + plate->invalidate_exclusion_volume_preview(); +} + +void PartPlateList::render_exclusion_volume_intersections( + const Transform3d &view_matrix, + const Transform3d &projection_matrix) +{ + GLShaderProgram *shader = wxGetApp().get_shader("flat"); + if (shader == nullptr) + return; + + shader->start_using(); + shader->set_uniform("view_model_matrix", view_matrix); + shader->set_uniform("projection_matrix", projection_matrix); + + glsafe(::glEnable(GL_DEPTH_TEST)); + glsafe(::glEnable(GL_BLEND)); + glsafe(::glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)); + glsafe(::glDepthMask(GL_FALSE)); + + for (PartPlate *plate : m_plate_list) + if (plate != nullptr) + plate->render_exclusion_volume_intersections(); + + glsafe(::glDepthMask(GL_TRUE)); + glsafe(::glDisable(GL_BLEND)); + shader->stop_using(); +} + int PartPlateList::create_plate(bool adjust_position) { PartPlate* plate = NULL; diff --git a/src/slic3r/GUI/PartPlate.hpp b/src/slic3r/GUI/PartPlate.hpp index 28fae20668..d900140172 100644 --- a/src/slic3r/GUI/PartPlate.hpp +++ b/src/slic3r/GUI/PartPlate.hpp @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -373,6 +374,16 @@ public: const std::vector& get_slice_filaments_info() const { return slice_filaments_info; } int get_physical_extruder_by_filament_id(const DynamicConfig& g_config, int idx) const; int get_logical_extruder_by_filament_id(const DynamicConfig& g_config, int idx) const; + // Resolve the mapping policy used specifically by exclusion regions. + // Values are 1-based nozzle ids; 0 means automatic Bambu mapping has not + // produced a concrete plate-local assignment yet. + std::vector get_effective_exclusion_filament_maps(const DynamicConfig &g_config, size_t filament_count, + size_t extruder_count) const; + // 1-based filament id -> 0-based nozzle/exclusion-region id for the + // object's current plate mapping. Includes every filament referenced by + // any model volume (including painted facets). + std::map get_object_filament_extruders(const ModelObject &object, const DynamicConfig &g_config, + size_t extruder_count) const; bool check_filament_printable(const DynamicPrintConfig & config, wxString& error_message); bool check_tpu_printable_status(const DynamicPrintConfig & config, const std::vector &tpu_filaments); bool check_mixture_of_pla_and_petg(const DynamicPrintConfig & config); @@ -753,6 +764,8 @@ public: // Pantheon: update plates after moving plate to the front void update_plates(); + void invalidate_exclusion_volume_previews(); + void render_exclusion_volume_intersections(const Transform3d &view_matrix, const Transform3d &projection_matrix); /*basic plate operations*/ //create an empty plate and return its index diff --git a/src/slic3r/GUI/Plater.cpp b/src/slic3r/GUI/Plater.cpp index 02565296fe..dc243ac1a0 100644 --- a/src/slic3r/GUI/Plater.cpp +++ b/src/slic3r/GUI/Plater.cpp @@ -20057,6 +20057,7 @@ void Plater::on_config_change(const DynamicPrintConfig &config) if (update_filament_colors_in_full_config()) { p->sidebar->update_mixed_filament_list(); + p->partplate_list.invalidate_exclusion_volume_previews(); p->sidebar->obj_list()->update_filament_colors(); p->sidebar->update_dynamic_filament_list(); continue; @@ -20114,6 +20115,7 @@ void Plater::on_config_change(const DynamicPrintConfig &config) } else if(opt_key == "extruder_colour") { update_scheduled = true; + p->partplate_list.invalidate_exclusion_volume_previews(); //p->sidebar->obj_list()->update_extruder_colors(); } else if (opt_key == "printable_height") { @@ -20138,8 +20140,12 @@ void Plater::on_config_change(const DynamicPrintConfig &config) else if (opt_key == "support_interface_filament" || opt_key == "support_filament" || opt_key == "outer_wall_filament_id" || opt_key == "inner_wall_filament_id" || opt_key == "sparse_infill_filament_id" || opt_key == "internal_solid_filament_id" || - opt_key == "top_surface_filament_id" || opt_key == "bottom_surface_filament_id") { + opt_key == "top_surface_filament_id" || opt_key == "bottom_surface_filament_id" || + opt_key == "enable_support" || opt_key == "raft_layers" || opt_key == "wall_loops" || + opt_key == "sparse_infill_density" || opt_key == "top_shell_layers" || + opt_key == "bottom_shell_layers" || opt_key == "brim_type" || opt_key == "brim_width") { update_scheduled = true; + p->partplate_list.invalidate_exclusion_volume_previews(); } } @@ -20462,6 +20468,7 @@ void Plater::set_global_filament_map(const std::vector& filament_map) { auto& project_config = wxGetApp().preset_bundle->project_config; project_config.option("filament_map")->values = filament_map; + p->partplate_list.invalidate_exclusion_volume_previews(); } void Plater::set_global_filament_volume_map(const std::vector& filament_volume_map) @@ -20684,6 +20691,7 @@ void Plater::changed_mesh(int obj_idx) void Plater::changed_object(ModelObject &object){ assert(object.get_model() == &p->model); // is object from same model? object.invalidate_bounding_box(); + p->partplate_list.invalidate_exclusion_volume_previews(); // recenter and re - align to Z = 0 object.ensure_on_bed(p->printer_technology != ptSLA); @@ -20717,6 +20725,8 @@ void Plater::changed_objects(const std::vector& object_idxs) if (object_idxs.empty()) return; + p->partplate_list.invalidate_exclusion_volume_previews(); + for (size_t obj_idx : object_idxs) { if (obj_idx < p->model.objects.size()) { if (p->model.objects[obj_idx]->min_z() >= SINKING_Z_THRESHOLD) From 785aa2637bdb405085bbad50085437c7c595663d Mon Sep 17 00:00:00 2001 From: Harry Loud Date: Thu, 16 Jul 2026 00:17:09 +0100 Subject: [PATCH 10/38] Add exclusion-aware arrange and fill --- .../libnest2d/include/libnest2d/nester.hpp | 6 + .../include/libnest2d/placers/nfpplacer.hpp | 31 +++-- src/OrcaSlicer.cpp | 19 ++- src/libslic3r/Arrange.cpp | 79 +++++++++++ src/libslic3r/Arrange.hpp | 16 +++ src/libslic3r/ModelArrange.cpp | 7 +- src/libslic3r/PrintConfig.cpp | 8 +- src/slic3r/GUI/Jobs/ArrangeJob.cpp | 75 ++++++++++- src/slic3r/GUI/Jobs/ArrangeJob.hpp | 9 +- src/slic3r/GUI/Jobs/FillBedJob.cpp | 127 ++++++++++++------ src/slic3r/GUI/PartPlate.cpp | 48 ++++++- src/slic3r/GUI/PartPlate.hpp | 3 +- src/slic3r/GUI/Plater.cpp | 33 ++++- src/slic3r/GUI/Plater.hpp | 4 +- 14 files changed, 386 insertions(+), 79 deletions(-) diff --git a/deps_src/libnest2d/include/libnest2d/nester.hpp b/deps_src/libnest2d/include/libnest2d/nester.hpp index 13281c389b..f1852478d2 100644 --- a/deps_src/libnest2d/include/libnest2d/nester.hpp +++ b/deps_src/libnest2d/include/libnest2d/nester.hpp @@ -78,6 +78,12 @@ public: std::vector extrude_ids; int filament_temp_type = -1; // -1 means unset. otherwise should be {0,1,2} double height{ 0 }; + double z_min{ 0 }; + double z_max{ 0 }; + bool has_z_range{ false }; + bool is_bed_exclusion{ false }; + std::vector bed_exclusion_extruder_ids; + int bed_exclusion_extruder_id{ -1 }; double print_temp{ 0 }; double bed_temp{ 0 }; double vitrify_temp{ 0 }; // vitrify temperature diff --git a/deps_src/libnest2d/include/libnest2d/placers/nfpplacer.hpp b/deps_src/libnest2d/include/libnest2d/placers/nfpplacer.hpp index dc7733ebd6..9d8c04d063 100644 --- a/deps_src/libnest2d/include/libnest2d/placers/nfpplacer.hpp +++ b/deps_src/libnest2d/include/libnest2d/placers/nfpplacer.hpp @@ -123,6 +123,10 @@ struct NfpPConfig { std::function on_preload; + // Return false when a packed item does not constrain this candidate. + // By default every pair participates in the 2D collision calculation. + std::function&, const _Item&)> should_check_collision; + //BBS: sort function for selector std::function& i1, _Item& i2)> sortfunc; //BBS: excluded region for V4 bed @@ -579,7 +583,14 @@ private: { using namespace nfp; - Shapes nfps(items_.size()); + std::vector collision_items; + collision_items.reserve(items_.size()); + for (Item &item : items_) { + if (!config_.should_check_collision || config_.should_check_collision(trsh, item)) + collision_items.emplace_back(&item); + } + + Shapes nfps(collision_items.size()); // ///////////////////////////////////////////////////////////////////// // TODO: this is a workaround and should be solved in Item with mutexes @@ -590,21 +601,21 @@ private: trsh.rightmostTopVertex(); trsh.leftmostBottomVertex(); - for(Item& itm : items_) { - itm.transformedShape(); - itm.referenceVertex(); - itm.rightmostTopVertex(); - itm.leftmostBottomVertex(); + for (Item *item : collision_items) { + item->transformedShape(); + item->referenceVertex(); + item->rightmostTopVertex(); + item->leftmostBottomVertex(); } // ///////////////////////////////////////////////////////////////////// - __parallel::enumerate(items_.begin(), items_.end(), - [&nfps, &trsh](const Item& sh, size_t n) + __parallel::enumerate(collision_items.begin(), collision_items.end(), + [&nfps, &trsh](Item *const &sh, size_t n) { - auto& fixedp = sh.transformedShape(); + auto& fixedp = sh->transformedShape(); auto& orbp = trsh.transformedShape(); auto subnfp_r = noFitPolygon(fixedp, orbp); - correctNfpPosition(subnfp_r, sh, trsh); + correctNfpPosition(subnfp_r, *sh, trsh); nfps[n] = subnfp_r.first; }); diff --git a/src/OrcaSlicer.cpp b/src/OrcaSlicer.cpp index b75c653eda..2d6fe873b7 100644 --- a/src/OrcaSlicer.cpp +++ b/src/OrcaSlicer.cpp @@ -5120,7 +5120,7 @@ int CLI::run(int argc, char **argv) } // add the virtual object into unselect list if has - partplate_list.preprocess_exclude_areas(unselected, enable_wrapping_detect, i + 1); + partplate_list.preprocess_exclude_areas(unselected, m_print_config, enable_wrapping_detect, i + 1); if (avoid_extrusion_cali_region) partplate_list.preprocess_nonprefered_areas(unselected, i + 1); @@ -5150,7 +5150,10 @@ int CLI::run(int argc, char **argv) beds = get_shrink_bedpts(&m_print_config, arrange_cfg); - partplate_list.preprocess_exclude_areas(arrange_cfg.excluded_regions, enable_wrapping_detect, 1, scale_(1)); + partplate_list.preprocess_exclude_areas( + arrange_cfg.excluded_regions, m_print_config, enable_wrapping_detect, 1, scale_(1)); + if (has_bed_exclusion_regions(arrange_cfg.excluded_regions)) + arrange_cfg.do_final_align = false; { BOOST_LOG_TRIVIAL(debug) << "arrange bedpts:" << beds[0].transpose() << ", " << beds[1].transpose() << ", " << beds[2].transpose() << ", " << beds[3].transpose(); @@ -5170,6 +5173,7 @@ int CLI::run(int argc, char **argv) //Step-3:do the arrange BOOST_LOG_TRIVIAL(info) << boost::format("start plate %1%'s arranging...") % (i + 1); arrangement::arrange(selected, unselected, beds, arrange_cfg); + invalidate_bed_exclusion_conflicts(selected, unselected); //arrangement::arrange(unprintable, {}, beds, arrange_cfg); BOOST_LOG_TRIVIAL(info) << boost::format("finished plate %1%'s arranging") % (i + 1); @@ -5359,7 +5363,7 @@ int CLI::run(int argc, char **argv) } //add the virtual object into unselect list if has - partplate_list.preprocess_exclude_areas(unselected, enable_wrapping_detect); + partplate_list.preprocess_exclude_areas(unselected, m_print_config, enable_wrapping_detect); if (used_filament_set.size() > 0) { @@ -5570,7 +5574,8 @@ int CLI::run(int argc, char **argv) } // add the virtual object into unselect list if has - partplate_list.preprocess_exclude_areas(unselected, enable_wrapping_detect, plate_to_slice); + partplate_list.preprocess_exclude_areas( + unselected, m_print_config, enable_wrapping_detect, plate_to_slice); } @@ -5600,7 +5605,10 @@ int CLI::run(int argc, char **argv) beds=get_shrink_bedpts(&m_print_config, arrange_cfg); - partplate_list.preprocess_exclude_areas(arrange_cfg.excluded_regions, enable_wrapping_detect, 1, scale_(1)); + partplate_list.preprocess_exclude_areas( + arrange_cfg.excluded_regions, m_print_config, enable_wrapping_detect, 1, scale_(1)); + if (has_bed_exclusion_regions(arrange_cfg.excluded_regions)) + arrange_cfg.do_final_align = false; { BOOST_LOG_TRIVIAL(debug) << "arrange bedpts:" << beds[0].transpose() << ", " << beds[1].transpose() << ", " << beds[2].transpose() << ", " << beds[3].transpose(); @@ -5620,6 +5628,7 @@ int CLI::run(int argc, char **argv) //Step-3:do the arrange BOOST_LOG_TRIVIAL(info) << boost::format("start %1% th arranging...")%arrange_count; arrangement::arrange(selected, unselected, beds, arrange_cfg); + invalidate_bed_exclusion_conflicts(selected, unselected); arrangement::arrange(unprintable, {}, beds, arrange_cfg); BOOST_LOG_TRIVIAL(info) << boost::format("finished %1% th arranging...")%arrange_count; diff --git a/src/libslic3r/Arrange.cpp b/src/libslic3r/Arrange.cpp index fd496537f4..d2dcf0d3a9 100644 --- a/src/libslic3r/Arrange.cpp +++ b/src/libslic3r/Arrange.cpp @@ -82,6 +82,71 @@ using ItemGroup = std::vector>; const double BIG_ITEM_TRESHOLD = 0.02; #define VITRIFY_TEMP_DIFF_THRSH 15 // bed temp can be higher than vitrify temp, but not higher than this thresh +static bool z_ranges_overlap(double first_min, double first_max, double second_min, double second_max) +{ + if (first_min > first_max) + std::swap(first_min, first_max); + if (second_min > second_max) + std::swap(second_min, second_max); + + // Touching a volume is treated as a collision. Arrangement may leave some + // usable space empty, but it must not create a marginally unsafe placement. + return first_max >= second_min - EPSILON && second_max >= first_min - EPSILON; +} + +template +static bool bed_exclusion_applies_impl(const T &item, const T &fixed_item) +{ + if (!fixed_item.is_bed_exclusion) + return false; + if (item.has_z_range && fixed_item.has_z_range && + !z_ranges_overlap(item.z_min, item.z_max, fixed_item.z_min, fixed_item.z_max)) + return false; + + // Shared volumes and unresolved object mappings apply conservatively to + // every nozzle. Otherwise only the owning physical nozzle participates. + return fixed_item.bed_exclusion_extruder_id < 0 || item.bed_exclusion_extruder_ids.empty() || + std::find(item.bed_exclusion_extruder_ids.begin(), item.bed_exclusion_extruder_ids.end(), + fixed_item.bed_exclusion_extruder_id) != item.bed_exclusion_extruder_ids.end(); +} + +bool has_bed_exclusion_regions(const ArrangePolygons &polygons) +{ + return std::any_of(polygons.begin(), polygons.end(), [](const ArrangePolygon &polygon) { + return polygon.is_bed_exclusion; + }); +} + +bool bed_exclusion_applies(const ArrangePolygon &item, const ArrangePolygon &fixed_item) +{ + return bed_exclusion_applies_impl(item, fixed_item); +} + +void invalidate_bed_exclusion_conflicts(ArrangePolygons &items, const ArrangePolygons &fixed_items, + const Vec2crd fixed_items_offset) +{ + for (ArrangePolygon &item : items) { + if (item.bed_idx < 0) + continue; + + BoundingBox item_bbox = get_extents(item.transformed_poly()); + item_bbox.offset(std::max(0, item.inflation)); + + for (const ArrangePolygon &fixed : fixed_items) { + if (fixed.bed_idx != item.bed_idx || !bed_exclusion_applies(item, fixed)) + continue; + + BoundingBox exclusion_bbox = get_extents(fixed.transformed_poly()); + exclusion_bbox.offset(std::max(0, fixed.inflation)); + exclusion_bbox.translate(fixed_items_offset.x(), fixed_items_offset.y()); + if (item_bbox.overlap(exclusion_bbox)) { + item.bed_idx = UNARRANGED; + break; + } + } + } +} + void update_arrange_params(ArrangeParams& params, const DynamicPrintConfig* print_cfg, const ArrangePolygons& selected) { double skirt_distance = get_real_skirt_dist(*print_cfg); @@ -305,6 +370,14 @@ void fill_config(PConf& pcfg, const ArrangeParams ¶ms) { // Allow parallel execution. pcfg.parallel = params.parallel; + pcfg.should_check_collision = [](const Item &candidate, const Item &packed) { + if (packed.is_bed_exclusion) + return bed_exclusion_applies_impl(candidate, packed); + if (candidate.is_bed_exclusion) + return bed_exclusion_applies_impl(packed, candidate); + return true; + }; + // BBS: excluded regions in BBS bed for (auto& poly : params.excluded_regions) process_arrangeable(poly, pcfg.m_excluded_regions); @@ -1074,6 +1147,12 @@ static void process_arrangeable(const ArrangePolygon &arrpoly, item.itemId(arrpoly.itemid); item.extrude_ids = arrpoly.extrude_ids; item.height = arrpoly.height; + item.z_min = arrpoly.z_min; + item.z_max = arrpoly.z_max; + item.has_z_range = arrpoly.has_z_range; + item.is_bed_exclusion = arrpoly.is_bed_exclusion; + item.bed_exclusion_extruder_ids = arrpoly.bed_exclusion_extruder_ids; + item.bed_exclusion_extruder_id = arrpoly.bed_exclusion_extruder_id; item.name = arrpoly.name; //BBS: add virtual object logic item.is_virt_object = arrpoly.is_virt_object; diff --git a/src/libslic3r/Arrange.hpp b/src/libslic3r/Arrange.hpp index ad125aee7d..8f3098c38b 100644 --- a/src/libslic3r/Arrange.hpp +++ b/src/libslic3r/Arrange.hpp @@ -72,6 +72,17 @@ struct ArrangePolygon { int itemid{ 0 }; // item id in the vector, used for accessing all possible params like extrude_id int is_applied{ 0 }; // transform has been applied double height{ 0 }; // item height + double z_min{ 0 }; // lowest occupied Z coordinate + double z_max{ 0 }; // highest occupied Z coordinate + bool has_z_range{ false }; // whether z_min / z_max are authoritative + bool is_bed_exclusion{ false }; // conditional bed-exclusion obstacle + // Physical nozzle ids used only for per-nozzle exclusion checks. These are + // deliberately separate from extrude_ids, which contains logical filament + // ids used by Orca's normal material-aware arrangement. Empty is treated + // conservatively as unresolved and therefore applicable to every nozzle. + std::vector bed_exclusion_extruder_ids{}; + // Zero-based nozzle owning an exclusion obstacle; -1 means shared. + int bed_exclusion_extruder_id{ -1 }; double brim_width{ 0 }; // brim width std::string name; @@ -185,6 +196,11 @@ void update_unselected_items_inflation(ArrangePolygons& unselected, const Dynami void update_selected_items_axis_align(ArrangePolygons& selected, const DynamicPrintConfig* print_cfg, const ArrangeParams& params); +bool has_bed_exclusion_regions(const ArrangePolygons& polygons); +bool bed_exclusion_applies(const ArrangePolygon& item, const ArrangePolygon& fixed_item); +void invalidate_bed_exclusion_conflicts(ArrangePolygons& items, const ArrangePolygons& fixed_items, + Vec2crd fixed_items_offset = Vec2crd::Zero()); + Points get_shrink_bedpts(const DynamicPrintConfig* print_cfg, const ArrangeParams& params); /** diff --git a/src/libslic3r/ModelArrange.cpp b/src/libslic3r/ModelArrange.cpp index 95167565aa..4d7a2c6756 100644 --- a/src/libslic3r/ModelArrange.cpp +++ b/src/libslic3r/ModelArrange.cpp @@ -180,8 +180,11 @@ ArrangePolygon get_instance_arrange_poly(ModelInstance* instance, const Slic3r:: ap.has_tree_support = true; } - auto size = obj->instance_convex_hull_bounding_box(instance).size(); - ap.height = size.z(); + const BoundingBoxf3 bbox = obj->instance_convex_hull_bounding_box(instance); + ap.height = bbox.size().z(); + ap.z_min = bbox.min.z(); + ap.z_max = bbox.max.z(); + ap.has_z_range = bbox.defined; ap.name = obj->name; return ap; } diff --git a/src/libslic3r/PrintConfig.cpp b/src/libslic3r/PrintConfig.cpp index 58c9c7f5df..a5a8076a1a 100644 --- a/src/libslic3r/PrintConfig.cpp +++ b/src/libslic3r/PrintConfig.cpp @@ -13049,8 +13049,8 @@ std::vector> get_bed_excluded_regions_by_extruder( const std::vector master_regions = parse_master_bed_excluded_regions( cfg.opt("bed_exclude_area"), printable_height); - const ConfigOptionEnum *mode_option = cfg.opt>("bed_exclude_area_mode"); - const BedExcludeAreaMode mode = mode_option != nullptr ? mode_option->value : BedExcludeAreaMode::Shared; + const BedExcludeAreaMode mode = cfg.has("bed_exclude_area_mode") ? + cfg.opt_enum("bed_exclude_area_mode") : BedExcludeAreaMode::Shared; const ConfigOptionStrings *per_extruder_option = cfg.opt("extruder_bed_exclude_area"); const ConfigOptionPoints *offset_option = cfg.opt("extruder_offset"); const ConfigOptionFloats *nozzle_option = cfg.opt("nozzle_diameter"); @@ -13102,8 +13102,8 @@ std::vector get_bed_excluded_regions(const PrintConfig &cfg, c std::vector get_bed_excluded_regions(const DynamicPrintConfig &cfg) { - const ConfigOptionEnum *mode_option = cfg.opt>("bed_exclude_area_mode"); - const BedExcludeAreaMode mode = mode_option != nullptr ? mode_option->value : BedExcludeAreaMode::Shared; + const BedExcludeAreaMode mode = cfg.has("bed_exclude_area_mode") ? + cfg.opt_enum("bed_exclude_area_mode") : BedExcludeAreaMode::Shared; return flatten_bed_excluded_regions(mode, get_bed_excluded_regions_by_extruder(cfg)); } diff --git a/src/slic3r/GUI/Jobs/ArrangeJob.cpp b/src/slic3r/GUI/Jobs/ArrangeJob.cpp index c0cc7bdb5a..df11be8563 100644 --- a/src/slic3r/GUI/Jobs/ArrangeJob.cpp +++ b/src/slic3r/GUI/Jobs/ArrangeJob.cpp @@ -21,6 +21,58 @@ namespace Slic3r { namespace GUI { using ArrangePolygon = arrangement::ArrangePolygon; +void set_arrange_polygon_bed_exclusion_extruders(ArrangePolygon &polygon, const ModelObject &object, + const PartPlate &plate, const DynamicPrintConfig &config) +{ + polygon.bed_exclusion_extruder_ids.clear(); + if (config.opt_enum("bed_exclude_area_mode") == BedExcludeAreaMode::Shared) + return; + + const ConfigOptionFloats *nozzle_diameters = config.opt("nozzle_diameter"); + const size_t extruder_count = nozzle_diameters != nullptr ? nozzle_diameters->size() : 0; + if (extruder_count == 0) + return; + + PresetBundle *preset_bundle = wxGetApp().preset_bundle; + if (preset_bundle == nullptr) + return; + + const DynamicPrintConfig &project_config = preset_bundle->project_config; + // Automatic Bambu mapping may be recalculated after arrangement or differ + // between destination plates. Leave it unresolved so every nozzle volume + // is checked rather than embedding a temporary assignment in the item. + if (preset_bundle->is_bbl_vendor() && + is_auto_filament_map_mode(plate.get_real_filament_map_mode(project_config))) + return; + + std::set extruder_ids; + for (const auto &mapping : plate.get_object_filament_extruders(object, project_config, extruder_count)) + extruder_ids.emplace(int(mapping.second)); + polygon.bed_exclusion_extruder_ids.assign(extruder_ids.begin(), extruder_ids.end()); +} + +static void set_arrange_polygon_bed_exclusion_extruders_for_all_plates(ArrangePolygon &polygon, + const ModelObject &object, + PartPlateList &plate_list, + const DynamicPrintConfig &config) +{ + polygon.bed_exclusion_extruder_ids.clear(); + if (config.opt_enum("bed_exclude_area_mode") == BedExcludeAreaMode::Shared) + return; + + std::set extruder_ids; + for (int plate_index = 0; plate_index < plate_list.get_plate_count(); ++plate_index) { + ArrangePolygon mapped = polygon; + set_arrange_polygon_bed_exclusion_extruders(mapped, object, *plate_list.get_plate(plate_index), config); + if (mapped.bed_exclusion_extruder_ids.empty()) { + polygon.bed_exclusion_extruder_ids.clear(); + return; + } + extruder_ids.insert(mapped.bed_exclusion_extruder_ids.begin(), mapped.bed_exclusion_extruder_ids.end()); + } + polygon.bed_exclusion_extruder_ids.assign(extruder_ids.begin(), extruder_ids.end()); +} + // Cache the wti info class WipeTower: public GLCanvas3D::WipeTowerInfo { public: @@ -100,11 +152,14 @@ void ArrangeJob::clear_input() current_plate_index = 0; } -ArrangePolygon ArrangeJob::prepare_arrange_polygon(void* model_instance) +ArrangePolygon ArrangeJob::prepare_arrange_polygon(void *model_instance, const PartPlate *mapping_plate) { ModelInstance* instance = (ModelInstance*)model_instance; const Slic3r::DynamicPrintConfig& config = wxGetApp().preset_bundle->full_config(); - return get_instance_arrange_poly(instance, config); + ArrangePolygon polygon = get_instance_arrange_poly(instance, config); + if (mapping_plate != nullptr) + set_arrange_polygon_bed_exclusion_extruders(polygon, *instance->get_object(), *mapping_plate, config); + return polygon; } void ArrangeJob::prepare_selected() { @@ -138,6 +193,8 @@ void ArrangeJob::prepare_selected() { for (size_t i = 0; i < inst_sel.size(); ++i) { ModelInstance* mi = mo->instances[i]; ArrangePolygon&& ap = prepare_arrange_polygon(mo->instances[i]); + set_arrange_polygon_bed_exclusion_extruders_for_all_plates( + ap, *mo, plate_list, wxGetApp().preset_bundle->full_config()); //BBS: partplate_list preprocess //remove the locked plate's instances, neither in selected, nor in un-selected bool locked = plate_list.preprocess_arrange_polygon(oidx, i, ap, inst_sel[i]); @@ -210,6 +267,8 @@ void ArrangeJob::prepare_all() { for (size_t i = 0; i < mo->instances.size(); ++i) { ModelInstance * mi = mo->instances[i]; ArrangePolygon&& ap = prepare_arrange_polygon(mo->instances[i]); + set_arrange_polygon_bed_exclusion_extruders_for_all_plates( + ap, *mo, plate_list, wxGetApp().preset_bundle->full_config()); //BBS: partplate_list preprocess //remove the locked plate's instances, neither in selected, nor in un-selected bool locked = plate_list.preprocess_arrange_polygon(oidx, i, ap, true); @@ -251,7 +310,7 @@ void ArrangeJob::prepare_all() { bool enable_wrapping = current_config.option("enable_wrapping_detection")->value; // add the virtual object into unselect list if has - plate_list.preprocess_exclude_areas(m_unselected, enable_wrapping, MAX_NUM_PLATES); + plate_list.preprocess_exclude_areas(m_unselected, wxGetApp().preset_bundle->full_config(), enable_wrapping, MAX_NUM_PLATES); } arrangement::ArrangePolygon estimate_wipe_tower_info(int plate_index, std::set& extruder_ids) @@ -396,7 +455,7 @@ void ArrangeJob::prepare_partplate() { for (size_t inst_idx = 0; inst_idx < mo->instances.size(); ++inst_idx) { bool in_plate = plate->contain_instance(oidx, inst_idx) || plate->intersect_instance(oidx, inst_idx); - ArrangePolygon&& ap = prepare_arrange_polygon(mo->instances[inst_idx]); + ArrangePolygon&& ap = prepare_arrange_polygon(mo->instances[inst_idx], plate); ArrangePolygons& cont = mo->instances[inst_idx]->printable ? (in_plate ? m_selected : m_unselected) : @@ -427,7 +486,8 @@ void ArrangeJob::prepare_partplate() { bool enable_wrapping = current_config.option("enable_wrapping_detection")->value; // add the virtual object into unselect list if has - plate_list.preprocess_exclude_areas(m_unselected, enable_wrapping, current_plate_index + 1); + plate_list.preprocess_exclude_areas( + m_unselected, wxGetApp().preset_bundle->full_config(), enable_wrapping, current_plate_index + 1); } //BBS: add partplate logic @@ -540,7 +600,9 @@ void ArrangeJob::process(Ctl &ctl) Points bedpts = get_shrink_bedpts(m_plater->config(),params); bool enable_wrapping = global_config.option("enable_wrapping_detection")->value; - partplate_list.preprocess_exclude_areas(params.excluded_regions, enable_wrapping, 1, scale_(1)); + partplate_list.preprocess_exclude_areas(params.excluded_regions, global_config, enable_wrapping, 1, scale_(1)); + if (has_bed_exclusion_regions(params.excluded_regions)) + params.do_final_align = false; BOOST_LOG_TRIVIAL(debug) << "arrange bedpts:" << bedpts[0].transpose() << ", " << bedpts[1].transpose() << ", " << bedpts[2].transpose() << ", " << bedpts[3].transpose(); @@ -564,6 +626,7 @@ void ArrangeJob::process(Ctl &ctl) } arrangement::arrange(m_selected, m_unselected, bedpts, params); + invalidate_bed_exclusion_conflicts(m_selected, m_unselected); // sort by item id std::sort(m_selected.begin(), m_selected.end(), [](auto a, auto b) {return a.itemid < b.itemid; }); diff --git a/src/slic3r/GUI/Jobs/ArrangeJob.hpp b/src/slic3r/GUI/Jobs/ArrangeJob.hpp index 0c9f03de01..bae886b298 100644 --- a/src/slic3r/GUI/Jobs/ArrangeJob.hpp +++ b/src/slic3r/GUI/Jobs/ArrangeJob.hpp @@ -10,10 +10,17 @@ namespace Slic3r { class ModelInstance; +class ModelObject; namespace GUI { class Plater; +class PartPlate; + +void set_arrange_polygon_bed_exclusion_extruders(arrangement::ArrangePolygon &polygon, + const ModelObject &object, + const PartPlate &plate, + const DynamicPrintConfig &config); class ArrangeJob : public Job { @@ -47,7 +54,7 @@ class ArrangeJob : public Job void prepare_partplate(); void prepare_wipe_tower(); - ArrangePolygon prepare_arrange_polygon(void* instance); + ArrangePolygon prepare_arrange_polygon(void *instance, const PartPlate *mapping_plate = nullptr); protected: diff --git a/src/slic3r/GUI/Jobs/FillBedJob.cpp b/src/slic3r/GUI/Jobs/FillBedJob.cpp index 5364cb5648..4e105c51ac 100644 --- a/src/slic3r/GUI/Jobs/FillBedJob.cpp +++ b/src/slic3r/GUI/Jobs/FillBedJob.cpp @@ -55,6 +55,7 @@ void FillBedJob::prepare() bool selected = (oidx == m_object_idx); ArrangePolygon ap = get_instance_arrange_poly(mo->instances[inst_idx], global_config); + set_arrange_polygon_bed_exclusion_extruders(ap, *mo, *plate, global_config); BoundingBox ap_bb = ap.transformed_poly().contour.bounding_box(); ap.name = mo->name; @@ -122,8 +123,8 @@ void FillBedJob::prepare() bool enable_wrapping = global_config.option("enable_wrapping_detection")->value; //add the virtual object into unselect list if has double scaled_exclusion_gap = scale_(1); - plate_list.preprocess_exclude_areas(params.excluded_regions, enable_wrapping, 1, scaled_exclusion_gap); - plate_list.preprocess_exclude_areas(m_unselected, enable_wrapping); + plate_list.preprocess_exclude_areas(params.excluded_regions, global_config, enable_wrapping, 1, scaled_exclusion_gap); + plate_list.preprocess_exclude_areas(m_unselected, global_config, enable_wrapping); m_bedpts = get_bed_shape(*m_plater->config()); @@ -149,11 +150,14 @@ void FillBedJob::prepare() auto polys = offset_ex(m_selected.front().poly, params.min_obj_distance / 2); ExPolygon poly = polys.empty() ? m_selected.front().poly : polys.front(); double poly_area = poly.area() / sc; + const ArrangePolygon &fill_template = m_selected.front(); double unsel_area = std::accumulate(m_unselected.begin(), m_unselected.end(), 0., - [cur_plate_index](double s, const auto &ap) { + [cur_plate_index, &fill_template](double s, const auto &ap) { //BBS: m_unselected instance is in the same partplate - return s + (ap.bed_idx == cur_plate_index) * ap.poly.area(); + const bool exclusion_applies = !ap.is_bed_exclusion || + bed_exclusion_applies(fill_template, ap); + return s + (ap.bed_idx == cur_plate_index && exclusion_applies) * ap.poly.area(); //return s + (ap.bed_idx == 0) * ap.poly.area(); }) / sc; @@ -168,36 +172,24 @@ void FillBedJob::prepare() //sel_id = std::max(sel_id, 0); ModelInstance *mi = model_object->instances[sel_id]; ArrangePolygon template_ap = get_instance_arrange_poly(mi, global_config); + set_arrange_polygon_bed_exclusion_extruders(template_ap, *model_object, *plate, global_config); - int obj_idx; - double offset_base, offset; - bool was_one_instance; - if (m_instances) { - obj_idx = m_plater->get_selected_object_idx(); - offset_base = m_plater->canvas3D()->get_size_proportional_to_max_bed_size(0.05); - offset = offset_base; - was_one_instance = model_object->instances.size()==1; - } - - for (int i = 0; i < needed_items; ++i, offset += offset_base) { + for (int i = 0; i < needed_items; ++i) { ArrangePolygon ap = template_ap; ap.poly = m_selected.front().poly; ap.bed_idx = PartPlateList::MAX_PLATES_COUNT; ap.itemid = -1; - ap.setter = [this, offset](const ArrangePolygon &p) { + ap.setter = [this, mi](const ArrangePolygon &p) { ModelObject *mo = m_plater->model().objects[m_object_idx]; - ModelObject *obj; if (m_instances) { - ModelInstance* model_instance = mo->instances.back(); - Vec3d offset_vec = model_instance->get_offset() + Vec3d(offset, offset, 0.0); - mo->add_instance(offset_vec, model_instance->get_scaling_factor(), model_instance->get_rotation(), model_instance->get_mirror()); - obj = mo; + ModelInstance *new_instance = mo->add_instance(*mi); + new_instance->apply_arrange_result(p.translation.cast(), p.rotation); } else { ModelObject* newObj = m_plater->model().add_object(*mo); newObj->name = mo->name +" "+ std::to_string(p.itemid); - obj = newObj; + for (ModelInstance *new_instance : newObj->instances) + new_instance->apply_arrange_result(p.translation.cast(), p.rotation); } - for (ModelInstance *newInst : obj->instances) { newInst->apply_arrange_result(p.translation.cast(), p.rotation); } //m_plater->sidebar().obj_list()->paste_objects_into_list({m_plater->model().objects.size()-1}); }; m_selected.emplace_back(ap); @@ -252,22 +244,71 @@ void FillBedJob::process(Ctl &ctl) }; // final align用的是凸包,在有fixed item的情况下可能找到的参考点位置是错的,这里就不做了。见STUDIO-3265 params.do_final_align = !is_bbl; + if (has_bed_exclusion_regions(params.excluded_regions)) + params.do_final_align = false; - if (m_selected.size() > 100){ + if (m_selected.size() > 100) { // too many items, just find grid empty cells to put them - Vec2f step = unscaled(get_extents(m_selected.front().poly).size()) + Vec2f(m_selected.front().brim_width, m_selected.front().brim_width); - std::vector empty_cells = Plater::get_empty_cells(step); - size_t n=std::min(m_selected.size(), empty_cells.size()); - for (size_t i = 0; i < n; i++) { - m_selected[i].translation = scaled(empty_cells[i]); - m_selected[i].bed_idx= 0; + std::vector occupied_boxes; + for (const ArrangePolygon &fixed : m_unselected) { + if (fixed.bed_idx != 0 || fixed.is_extrusion_cali_object) + continue; + + if (fixed.is_bed_exclusion) { + const bool relevant = std::any_of( + m_selected.begin(), m_selected.end(), [&fixed](const ArrangePolygon &item) { + return bed_exclusion_applies(item, fixed); + }); + if (!relevant) + continue; + } + + BoundingBox bbox = get_extents(fixed.transformed_poly()); + bbox.offset(std::max(0, fixed.inflation)); + occupied_boxes.emplace_back(unscale(bbox.min), unscale(bbox.max)); } - for (size_t i = n; i < m_selected.size(); i++) { - m_selected[i].bed_idx = -1; + + // Fill the remaining space without disturbing instances which are + // already placed. Besides matching the meaning of "Fill bed", this + // also prevents candidates rejected by the grid from remaining under + // newly placed copies at their old positions. + const Vec3d plate_origin = partplate_list.get_curr_plate()->get_origin(); + for (const ArrangePolygon &existing : m_selected) { + if (existing.priority == 0 || existing.bed_idx != 0) + continue; + + BoundingBox bbox = get_extents(existing.transformed_poly()); + bbox.offset(std::max(0, existing.inflation)); + BoundingBoxf local_box(unscale(bbox.min), unscale(bbox.max)); + local_box.translate(Vec2d(-plate_origin.x(), -plate_origin.y())); + occupied_boxes.emplace_back(std::move(local_box)); } - } - else + + const Vec2f step = unscaled(get_extents(m_selected.front().poly).size()) + + Vec2f(m_selected.front().brim_width, m_selected.front().brim_width); + const bool has_conditional_exclusions = has_bed_exclusion_regions(m_unselected); + const std::vector empty_cells = + Plater::get_empty_cells(step, occupied_boxes, !has_conditional_exclusions); + + size_t cell_index = 0; + for (ArrangePolygon &item : m_selected) { + if (item.priority != 0) + continue; + + if (cell_index < empty_cells.size()) { + item.translation = scaled(empty_cells[cell_index++]); + item.bed_idx = 0; + } else { + item.bed_idx = arrangement::UNARRANGED; + } + } + + invalidate_bed_exclusion_conflicts( + m_selected, m_unselected, Vec2crd(scale_(plate_origin.x()), scale_(plate_origin.y()))); + } else { arrangement::arrange(m_selected, m_unselected, m_bedpts, params); + invalidate_bed_exclusion_conflicts(m_selected, m_unselected); + } // finalize just here. ctl.update_status(100, ctl.was_canceled() ? @@ -332,6 +373,17 @@ void FillBedJob::finalize(bool canceled, std::exception_ptr &eptr) obj_list->update_printable_state(i, 0); } + if (m_instances && model_object->instances.size() > inst_cnt) { + const size_t new_instance_count = model_object->instances.size() - inst_cnt; + // Match the normal add-instance flow: update the scene before the + // object tree starts referring to the newly created instances. + m_plater->update(); + // A single-instance object has no instance children in the object + // tree yet, so the first refresh must add the original as well. + obj_list->increase_object_instances( + m_object_idx, inst_cnt == 1 ? new_instance_count + 1 : new_instance_count); + } + BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << ": paste_objects_into_list"; /*for (ArrangePolygon& ap : m_selected) { @@ -342,10 +394,9 @@ void FillBedJob::finalize(bool canceled, std::exception_ptr &eptr) //model_object->ensure_on_bed(); //BOOST_LOG_TRIVIAL(debug) << __FUNCTION__ << ": model_object->ensure_on_bed()"; - if (m_instances) {// && wxGetApp().app_config->get("auto_arrange") == "true") { - m_plater->set_prepare_state(Job::PREPARE_STATE_MENU); - m_plater->arrange(); - } + // FillBedJob has already computed and validated the final positions. + // The instance tree is synchronized above, so rerunning the general + // arranger here would only risk discarding a valid fill result. m_plater->update(); } diff --git a/src/slic3r/GUI/PartPlate.cpp b/src/slic3r/GUI/PartPlate.cpp index f32869689e..eb8a3d7153 100644 --- a/src/slic3r/GUI/PartPlate.cpp +++ b/src/slic3r/GUI/PartPlate.cpp @@ -1328,7 +1328,9 @@ void PartPlate::update_exclusion_volume_preview_models() const Polygons inner = offset(Polygons{ footprint }, -tool_border_width, jtMiter, 2.0); const ExPolygons border = inner.empty() ? ExPolygons{ expolygon_from_polygon(footprint) } : diff_ex(Polygons{ footprint }, inner); auto model = std::make_unique(); - const float border_z = static_cast(std::max(GROUND_Z + 0.026, region_src.has_z_range ? region_src.z_min + 0.026 : GROUND_Z + 0.026)); + // Nozzle colours identify the bed footprint, not the volume's + // vertical position, so keep this border with the grey preview. + const float border_z = GROUND_Z + 0.026f; if (init_model_from_expolygons(*model, border, border_z) && model->is_initialized()) m_extruder_exclusion_volume_borders.emplace_back(std::move(model), color); } @@ -6452,7 +6454,8 @@ bool PartPlateList::preprocess_arrange_polygon_other_locked(int obj_index, int i return locked; } -bool PartPlateList::preprocess_exclude_areas(arrangement::ArrangePolygons &unselected, bool enable_wrapping_detect, int num_plates, float inflation) +bool PartPlateList::preprocess_exclude_areas(arrangement::ArrangePolygons &unselected, const DynamicPrintConfig &config, + bool enable_wrapping_detect, int num_plates, float inflation) { bool added = false; @@ -6484,10 +6487,45 @@ bool PartPlateList::preprocess_exclude_areas(arrangement::ArrangePolygons &unsel } added = true; } + const BedExcludeAreaMode mode = config.opt_enum("bed_exclude_area_mode"); + const ConfigOptionPoints *configured_areas = config.opt("bed_exclude_area"); + const bool use_resolved_regions = mode != BedExcludeAreaMode::Shared || + (configured_areas != nullptr && has_bed_exclusion_volume_syntax(*configured_areas)); - // excluded area - if (m_exclude_areas.size() > 0) - { + if (use_resolved_regions) { + const std::vector> regions_by_extruder = + get_bed_excluded_regions_by_extruder(config); + const size_t extruder_count = mode == BedExcludeAreaMode::Shared ? + std::min(1, regions_by_extruder.size()) : regions_by_extruder.size(); + + for (size_t extruder_id = 0; extruder_id < extruder_count; ++extruder_id) { + for (size_t region_id = 0; region_id < regions_by_extruder[extruder_id].size(); ++region_id) { + const BedExcludeRegion ®ion = regions_by_extruder[extruder_id][region_id]; + const BoundingBox bbox = region.polygon.bounding_box(); + if (!bbox.defined || (region.has_z_range && region.z_max <= region.z_min + EPSILON)) + continue; + + for (int plate_idx = 0; plate_idx < num_plates; ++plate_idx) { + arrangement::ArrangePolygon blocker; + blocker.poly.contour = bbox.polygon(); + blocker.translation = Vec2crd::Zero(); + blocker.rotation = 0.0; + blocker.is_virt_object = true; + blocker.is_bed_exclusion = true; + blocker.bed_exclusion_extruder_id = mode == BedExcludeAreaMode::Shared ? -1 : int(extruder_id); + blocker.bed_idx = plate_idx; + blocker.height = std::max(0.0, region.z_max - region.z_min); + blocker.z_min = region.z_min; + blocker.z_max = region.z_max; + blocker.has_z_range = region.has_z_range; + blocker.name = "BedExclusionVolume" + std::to_string(extruder_id) + "_" + std::to_string(region_id); + blocker.inflation = inflation; + unselected.emplace_back(std::move(blocker)); + } + added = true; + } + } + } else if (!m_exclude_areas.empty()) { //has exclude areas PartPlate *plate = m_plate_list[0]; diff --git a/src/slic3r/GUI/PartPlate.hpp b/src/slic3r/GUI/PartPlate.hpp index d900140172..866e2711b9 100644 --- a/src/slic3r/GUI/PartPlate.hpp +++ b/src/slic3r/GUI/PartPlate.hpp @@ -877,7 +877,8 @@ public: //preprocess an arrangement::ArrangePolygon, return true if it is in a locked plate bool preprocess_arrange_polygon(int obj_index, int instance_index, arrangement::ArrangePolygon& arrange_polygon, bool selected); bool preprocess_arrange_polygon_other_locked(int obj_index, int instance_index, arrangement::ArrangePolygon& arrange_polygon, bool selected); - bool preprocess_exclude_areas(arrangement::ArrangePolygons& unselected, bool enable_wrapping_detect, int num_plates = 16, float inflation = 0); + bool preprocess_exclude_areas(arrangement::ArrangePolygons &unselected, const DynamicPrintConfig &config, + bool enable_wrapping_detect, int num_plates = 16, float inflation = 0); bool preprocess_nonprefered_areas(arrangement::ArrangePolygons& regions, int num_plates = 1, float inflation=0); void postprocess_bed_index_for_selected(arrangement::ArrangePolygon& arrange_polygon); diff --git a/src/slic3r/GUI/Plater.cpp b/src/slic3r/GUI/Plater.cpp index dc243ac1a0..7c52c7f81c 100644 --- a/src/slic3r/GUI/Plater.cpp +++ b/src/slic3r/GUI/Plater.cpp @@ -20040,6 +20040,7 @@ void Plater::on_config_change(const DynamicPrintConfig &config) { bool update_scheduled = false; bool bed_shape_changed = false; + bool exclusion_preview_changed = false; //bool print_sequence_changed = false; t_config_option_keys diff_keys = p->config->diff(config); @@ -20081,6 +20082,12 @@ void Plater::on_config_change(const DynamicPrintConfig &config) } p->config->set_key_value(opt_key, config.option(opt_key)->clone()); + if (opt_key == "bed_exclude_area_mode" || opt_key == "bed_exclude_area" || + opt_key == "extruder_bed_exclude_area" || opt_key == "extruder_offset" || + opt_key == "master_extruder_id" || opt_key == "nozzle_diameter" || + opt_key == "printable_height" || opt_key == "extruder_colour") + exclusion_preview_changed = true; + if (opt_key == "printer_technology") { this->set_printer_technology(config.opt_enum(opt_key)); // print technology is changed, so we should to update a search list @@ -20152,9 +20159,14 @@ void Plater::on_config_change(const DynamicPrintConfig &config) if (bed_shape_changed) { set_bed_shape(); get_current_canvas3D()->requires_check_outside_state(); - get_current_canvas3D()->request_extra_frame(); } + if (exclusion_preview_changed) + p->partplate_list.invalidate_exclusion_volume_previews(); + + if (bed_shape_changed || exclusion_preview_changed) + get_current_canvas3D()->request_extra_frame(); + config_change_notification(config, std::string("print_sequence")); if (update_scheduled) @@ -20895,7 +20907,9 @@ void Plater::clone_selection() dlg.ShowModal(); } -std::vector Plater::get_empty_cells(const Vec2f step) +std::vector Plater::get_empty_cells(const Vec2f step, + const std::vector &local_exclude_boxes, + bool include_plate_exclude_areas) { PartPlate* plate = wxGetApp().plater()->get_partplate_list().get_curr_plate(); BoundingBoxf3 build_volume = plate->get_build_volume(true); @@ -20904,11 +20918,18 @@ std::vector Plater::get_empty_cells(const Vec2f step) std::vector cells; auto min_x = step(0)/2;// start_point.x() - step(0) * int((start_point.x() - bbox.min.x()) / step(0)); auto min_y = step(1)/2;// start_point.y() - step(1) * int((start_point.y() - bbox.min.y()) / step(1)); - auto& exclude_box3s = plate->get_exclude_areas(); std::vector exclude_boxs; - for (auto& box : exclude_box3s) { - Vec2d vmin(box.min.x(), box.min.y()), vmax(box.max.x(), box.max.y()); - exclude_boxs.emplace_back(vmin, vmax); + if (include_plate_exclude_areas) { + const auto &exclude_box3s = plate->get_exclude_areas(); + for (const auto &box : exclude_box3s) { + Vec2d vmin(box.min.x(), box.min.y()), vmax(box.max.x(), box.max.y()); + exclude_boxs.emplace_back(vmin, vmax); + } + } + const Vec3d plate_origin = plate->get_origin(); + for (BoundingBoxf box : local_exclude_boxes) { + box.translate(Vec2d(plate_origin.x(), plate_origin.y())); + exclude_boxs.emplace_back(std::move(box)); } for (float x = min_x + bbox.min.x(); x < bbox.max.x() - step(0) / 2; x += step(0)) for (float y = min_y + bbox.min.y(); y < bbox.max.y() - step(1) / 2; y += step(1)) { diff --git a/src/slic3r/GUI/Plater.hpp b/src/slic3r/GUI/Plater.hpp index 84e64acea0..5b8c658068 100644 --- a/src/slic3r/GUI/Plater.hpp +++ b/src/slic3r/GUI/Plater.hpp @@ -699,7 +699,9 @@ public: void split_volume(); void optimize_rotation(); // find all empty cells on the plate and won't overlap with exclusion areas - static std::vector get_empty_cells(const Vec2f step); + static std::vector get_empty_cells(const Vec2f step, + const std::vector &local_exclude_boxes = {}, + bool include_plate_exclude_areas = true); //BBS: void fill_color(int extruder_id); From 11906bd670e1b69209bf76096d2a6527bdc10e75 Mon Sep 17 00:00:00 2001 From: Harry Loud Date: Thu, 16 Jul 2026 01:03:44 +0100 Subject: [PATCH 11/38] Add multi-nozzle exclusion volume G-code checks --- src/libslic3r/CMakeLists.txt | 2 + src/libslic3r/GCode.cpp | 13 + .../GCode/ExclusionVolumePathCheck.cpp | 224 ++++++++++++++++++ .../GCode/ExclusionVolumePathCheck.hpp | 89 +++++++ src/libslic3r/GCode/GCodeProcessor.cpp | 131 ++++++++++ src/libslic3r/GCode/GCodeProcessor.hpp | 41 ++++ src/libslic3r/Print.cpp | 1 + src/libslic3r/PrintBase.hpp | 3 +- 8 files changed, 503 insertions(+), 1 deletion(-) create mode 100644 src/libslic3r/GCode/ExclusionVolumePathCheck.cpp create mode 100644 src/libslic3r/GCode/ExclusionVolumePathCheck.hpp diff --git a/src/libslic3r/CMakeLists.txt b/src/libslic3r/CMakeLists.txt index ffc6b5cee6..af1ef8e4db 100644 --- a/src/libslic3r/CMakeLists.txt +++ b/src/libslic3r/CMakeLists.txt @@ -232,6 +232,8 @@ set(lisbslic3r_sources GCode/ConflictChecker.hpp GCode/CoolingBuffer.cpp GCode/CoolingBuffer.hpp + GCode/ExclusionVolumePathCheck.cpp + GCode/ExclusionVolumePathCheck.hpp GCode/TimelapsePosPicker.cpp GCode/TimelapsePosPicker.hpp GCode.cpp diff --git a/src/libslic3r/GCode.cpp b/src/libslic3r/GCode.cpp index 5e93ec7eb0..23f7a47188 100644 --- a/src/libslic3r/GCode.cpp +++ b/src/libslic3r/GCode.cpp @@ -2582,6 +2582,18 @@ void GCode::do_export(Print* print, const char* path, GCodeProcessorResult* resu m_processor.result().nozzle_group_result = m_print->get_layered_nozzle_group_result(); m_processor.finalize(true); + if (m_processor.get_result().exclusion_volume_path_conflict) { + const int extruder_id = m_processor.get_result().exclusion_volume_conflict_extruder_id; + const std::string warning = extruder_id >= 0 ? + Slic3r::format( + _(L("A G-code move intersects an exclusion volume for extruder %1%. This may cause a printer collision.")), + std::to_string(extruder_id + 1)) : + _(L("A G-code move intersects an exclusion volume. This may cause a printer collision.")); + print->active_step_add_warning( + PrintStateBase::WarningLevel::CRITICAL, + warning, + PrintStateBase::SlicingExclusionVolumeToolpath); + } // DoExport::update_print_estimated_times_stats(m_processor, print->m_print_statistics); DoExport::update_print_estimated_stats(m_processor, m_writer.extruders(), print->m_print_statistics, print->config()); // Printed-mass safety check. Flushed filament leaves the bed, so subtract it @@ -2644,6 +2656,7 @@ namespace DoExport { processor.initialize_from_context(nozzle_group_result); processor.initialize_result_moves(); processor.apply_config(config); + processor.configure_exclusion_volume_path_check(config); processor.enable_stealth_time_estimator(silent_time_estimator_enabled); } diff --git a/src/libslic3r/GCode/ExclusionVolumePathCheck.cpp b/src/libslic3r/GCode/ExclusionVolumePathCheck.cpp new file mode 100644 index 0000000000..f2f3bb9cbe --- /dev/null +++ b/src/libslic3r/GCode/ExclusionVolumePathCheck.cpp @@ -0,0 +1,224 @@ +#include "ExclusionVolumePathCheck.hpp" + +#include "libslic3r/Polygon.hpp" +#include "libslic3r/libslic3r.h" + +#include +#include +#include + +namespace Slic3r { + +namespace { + +constexpr double Z_EPSILON_MM = 1e-6; + +Point scaled_point(const Vec3d &point) +{ + return { scale_(point.x()), scale_(point.y()) }; +} + +BoundingBox line_bbox(const Point &a, const Point &b) +{ + BoundingBox bbox; + bbox.merge(a); + bbox.merge(b); + bbox.offset(SCALED_EPSILON); + return bbox; +} + +bool intervals_overlap(coord_t a_min, coord_t a_max, coord_t b_min, coord_t b_max) +{ + if (a_min > a_max) + std::swap(a_min, a_max); + if (b_min > b_max) + std::swap(b_min, b_max); + return std::max(a_min, b_min) <= std::min(a_max, b_max); +} + +bool collinear_segments_overlap(const Line &a, const Line &b) +{ + const Vec2crd a_dir = a.b - a.a; + if (a_dir == Vec2crd::Zero()) + return a.a == b.a || a.a == b.b; + + if (cross2(a_dir, b.a - a.a) != 0 || cross2(a_dir, b.b - a.a) != 0) + return false; + + return std::abs(a_dir.x()) >= std::abs(a_dir.y()) ? + intervals_overlap(a.a.x(), a.b.x(), b.a.x(), b.b.x()) : + intervals_overlap(a.a.y(), a.b.y(), b.a.y(), b.b.y()); +} + +bool overlaps_collinear_boundary(const Line &line, const Lines &edges) +{ + const BoundingBox line_bounds = line_bbox(line.a, line.b); + for (const Line &edge : edges) { + if (line_bounds.overlap(line_bbox(edge.a, edge.b)) && collinear_segments_overlap(line, edge)) + return true; + } + return false; +} + +bool clip_segment_to_z_range( + const Vec3d &from, + const Vec3d &to, + double z_min, + double z_max, + Vec3d &out_from, + Vec3d &out_to) +{ + const double segment_min_z = std::min(from.z(), to.z()); + const double segment_max_z = std::max(from.z(), to.z()); + if (segment_max_z < z_min - Z_EPSILON_MM || segment_min_z > z_max + Z_EPSILON_MM) + return false; + + double t0 = 0.0; + double t1 = 1.0; + const double dz = to.z() - from.z(); + if (std::abs(dz) < Z_EPSILON_MM) { + if (from.z() < z_min - Z_EPSILON_MM || from.z() > z_max + Z_EPSILON_MM) + return false; + } else { + const double z0 = (z_min - from.z()) / dz; + const double z1 = (z_max - from.z()) / dz; + t0 = std::max(t0, std::min(z0, z1)); + t1 = std::min(t1, std::max(z0, z1)); + if (t0 > t1 + Z_EPSILON_MM) + return false; + } + + t0 = std::clamp(t0, 0.0, 1.0); + t1 = std::clamp(t1, 0.0, 1.0); + const Vec3d delta = to - from; + out_from = from + t0 * delta; + out_to = from + t1 * delta; + return true; +} + +} // namespace + +void ExclusionVolumePathChecker::configure(const PrintConfig &config) +{ + clear(); + m_configured = true; + m_extruder_offsets = config.extruder_offset.values; + + const std::vector> regions = + get_bed_excluded_regions_by_extruder(config); + m_regions_by_extruder.resize(regions.size()); + if (m_extruder_offsets.size() < regions.size()) + m_extruder_offsets.resize(regions.size(), Vec2d::Zero()); + + for (size_t extruder_id = 0; extruder_id < regions.size(); ++extruder_id) { + std::vector &prepared = m_regions_by_extruder[extruder_id]; + prepared.reserve(regions[extruder_id].size()); + for (const BedExcludeRegion ®ion : regions[extruder_id]) { + if (region.polygon.points.size() < 3 || region.z_max < region.z_min) + continue; + + PreparedRegion item; + item.region = region; + item.bbox = BoundingBox(region.polygon.points); + item.bbox.offset(SCALED_EPSILON); + item.edge_tree = AABBTreeLines::LinesDistancer(to_lines(region.polygon)); + prepared.emplace_back(std::move(item)); + } + } +} + +void ExclusionVolumePathChecker::clear() +{ + m_configured = false; + m_extruder_offsets.clear(); + m_regions_by_extruder.clear(); + m_result = {}; +} + +bool ExclusionVolumePathChecker::segment_intersects_region( + const Vec3d &from, + const Vec3d &to, + const bool z_known, + const PreparedRegion ®ion) const +{ + Vec3d clipped_from = from; + Vec3d clipped_to = to; + if (z_known && !clip_segment_to_z_range( + from, to, region.region.z_min, region.region.z_max, clipped_from, clipped_to)) + return false; + + const Point a = scaled_point(clipped_from); + const Point b = scaled_point(clipped_to); + if (!line_bbox(a, b).overlap(region.bbox)) + return false; + + if (region.region.polygon.contains(a) || region.region.polygon.contains(b)) + return true; + if (a == b) + return false; + + const Line line(a, b); + if (!region.edge_tree.intersections_with_line(line).empty()) + return true; + + // The line tree intentionally omits collinear intersections. + return overlaps_collinear_boundary(line, region.edge_tree.get_lines()); +} + +void ExclusionVolumePathChecker::check_motion( + const Vec3d &from, + const Vec3d &to, + const bool start_xy_known, + const bool end_xy_known, + const bool start_z_known, + const bool end_z_known, + const int active_extruder_id, + const ExclusionVolumeMotionType motion_type, + const unsigned char source_move_type, + const unsigned int gcode_id, + const size_t move_id) +{ + if (!m_configured || m_result.has_any_conflict || !start_xy_known || !end_xy_known || + m_regions_by_extruder.empty()) + return; + + const bool z_known = start_z_known && end_z_known; + const bool active_extruder_valid = + active_extruder_id >= 0 && size_t(active_extruder_id) < m_regions_by_extruder.size(); + const size_t first_extruder = active_extruder_valid ? size_t(active_extruder_id) : 0; + const size_t last_extruder = active_extruder_valid ? first_extruder + 1 : m_regions_by_extruder.size(); + + for (size_t extruder_id = first_extruder; extruder_id < last_extruder; ++extruder_id) { + const Vec2d offset = extruder_id < m_extruder_offsets.size() ? + m_extruder_offsets[extruder_id] : Vec2d::Zero(); + Vec3d model_from = from; + Vec3d model_to = to; + model_from.head<2>() += offset; + model_to.head<2>() += offset; + + const std::vector ®ions = m_regions_by_extruder[extruder_id]; + for (size_t region_id = 0; region_id < regions.size(); ++region_id) { + if (!segment_intersects_region(model_from, model_to, z_known, regions[region_id])) + continue; + + m_result.has_any_conflict = true; + m_result.has_travel_conflict = motion_type == ExclusionVolumeMotionType::Travel; + m_result.has_extrusion_conflict = motion_type == ExclusionVolumeMotionType::Extrude; + m_result.has_other_motion_conflict = motion_type == ExclusionVolumeMotionType::Other; + m_result.first_hit = ExclusionVolumePathHit{ + move_id, + gcode_id, + motion_type, + source_move_type, + int(extruder_id), + region_id, + model_from, + model_to, + !z_known + }; + return; + } + } +} + +} // namespace Slic3r diff --git a/src/libslic3r/GCode/ExclusionVolumePathCheck.hpp b/src/libslic3r/GCode/ExclusionVolumePathCheck.hpp new file mode 100644 index 0000000000..b04db406dc --- /dev/null +++ b/src/libslic3r/GCode/ExclusionVolumePathCheck.hpp @@ -0,0 +1,89 @@ +#pragma once + +#include "libslic3r/AABBTreeLines.hpp" +#include "libslic3r/BoundingBox.hpp" +#include "libslic3r/Line.hpp" +#include "libslic3r/PrintConfig.hpp" + +#include +#include +#include + +namespace Slic3r { + +enum class ExclusionVolumeMotionType : unsigned char +{ + Travel, + Extrude, + Other +}; + +struct ExclusionVolumePathHit +{ + size_t move_id { 0 }; + unsigned int gcode_id { 0 }; + ExclusionVolumeMotionType motion_type { ExclusionVolumeMotionType::Other }; + unsigned char source_move_type { 0 }; + int extruder_id { -1 }; + size_t region_id { 0 }; + Vec3d from { Vec3d::Zero() }; + Vec3d to { Vec3d::Zero() }; + bool used_unknown_z { false }; +}; + +struct ExclusionVolumePathCheckResult +{ + bool has_any_conflict { false }; + bool has_travel_conflict { false }; + bool has_extrusion_conflict { false }; + bool has_other_motion_conflict { false }; + std::optional first_hit; +}; + +// Checks G-code coordinates as they are parsed. Exclusion regions are expressed +// in nozzle/model space, so each candidate physical extruder offset is applied +// before testing a motion. This keeps the checker independent of preview +// vertices, whose extruder_id field represents a filament rather than a nozzle. +class ExclusionVolumePathChecker +{ +public: + void configure(const PrintConfig &config); + void clear(); + + bool configured() const { return m_configured; } + const ExclusionVolumePathCheckResult &result() const { return m_result; } + + void check_motion( + const Vec3d &from, + const Vec3d &to, + bool start_xy_known, + bool end_xy_known, + bool start_z_known, + bool end_z_known, + int active_extruder_id, + ExclusionVolumeMotionType motion_type, + unsigned char source_move_type, + unsigned int gcode_id, + size_t move_id); + +private: + struct PreparedRegion + { + BedExcludeRegion region; + BoundingBox bbox; + AABBTreeLines::LinesDistancer edge_tree; + }; + + bool segment_intersects_region( + const Vec3d &from, + const Vec3d &to, + bool z_known, + const PreparedRegion ®ion) const; + + bool m_configured { false }; + std::vector m_extruder_offsets; + std::vector> m_regions_by_extruder; + ExclusionVolumePathCheckResult m_result; +}; + +} // namespace Slic3r diff --git a/src/libslic3r/GCode/GCodeProcessor.cpp b/src/libslic3r/GCode/GCodeProcessor.cpp index 0a65508350..eb05146892 100644 --- a/src/libslic3r/GCode/GCodeProcessor.cpp +++ b/src/libslic3r/GCode/GCodeProcessor.cpp @@ -2528,6 +2528,17 @@ void GCodeProcessorResult::reset() { wrapping_exclude_area = Pointfs(); //BBS: add toolpath_outside toolpath_outside = false; + exclusion_volume_path_checked = false; + exclusion_volume_path_conflict = false; + exclusion_volume_travel_conflict = false; + exclusion_volume_extrusion_conflict = false; + exclusion_volume_other_motion_conflict = false; + exclusion_volume_conflict_gcode_id = 0; + exclusion_volume_conflict_move_id = 0; + exclusion_volume_conflict_move_type = EMoveType::Noop; + exclusion_volume_conflict_extruder_id = -1; + exclusion_volume_conflict_region_id = 0; + exclusion_volume_conflict_used_unknown_z = false; //BBS: add label_object_enabled label_object_enabled = false; long_retraction_when_cut = false; @@ -3485,6 +3496,10 @@ void GCodeProcessor::reset() m_start_position = { 0.0f, 0.0f, 0.0f, 0.0f }; m_end_position = { 0.0f, 0.0f, 0.0f, 0.0f }; m_origin = { 0.0f, 0.0f, 0.0f, 0.0f }; + m_axis_position_known = { false, false, false }; + m_axis_origin_known = { true, true, true }; + m_processing_homing_move = false; + m_exclusion_volume_path_checker.clear(); m_cached_position.reset(); m_wiping = false; m_flushing = false; @@ -3692,6 +3707,40 @@ void GCodeProcessor::process_buffer(const std::string &buffer) }); } +void GCodeProcessor::configure_exclusion_volume_path_check(const PrintConfig &config) +{ + m_exclusion_volume_path_checker.configure(config); +} + +GCodeProcessor::PositionState GCodeProcessor::get_current_position() const +{ + PositionState state; + state.position = Vec3d(m_end_position[X], m_end_position[Y], m_end_position[Z]); + state.axis_known = m_axis_position_known; + return state; +} + +void GCodeProcessor::update_exclusion_volume_path_check_result() +{ + m_result.exclusion_volume_path_checked = m_exclusion_volume_path_checker.configured(); + const ExclusionVolumePathCheckResult &check = m_exclusion_volume_path_checker.result(); + m_result.exclusion_volume_path_conflict = check.has_any_conflict; + m_result.exclusion_volume_travel_conflict = check.has_travel_conflict; + m_result.exclusion_volume_extrusion_conflict = check.has_extrusion_conflict; + m_result.exclusion_volume_other_motion_conflict = check.has_other_motion_conflict; + + if (!check.first_hit) + return; + + const ExclusionVolumePathHit &hit = *check.first_hit; + m_result.exclusion_volume_conflict_gcode_id = hit.gcode_id; + m_result.exclusion_volume_conflict_move_id = hit.move_id; + m_result.exclusion_volume_conflict_move_type = static_cast(hit.source_move_type); + m_result.exclusion_volume_conflict_extruder_id = hit.extruder_id; + m_result.exclusion_volume_conflict_region_id = hit.region_id; + m_result.exclusion_volume_conflict_used_unknown_z = hit.used_unknown_z; +} + void GCodeProcessor::finalize(bool post_process) { m_result.z_offset = m_z_offset; @@ -3731,6 +3780,7 @@ void GCodeProcessor::finalize(bool post_process) if (m_enable_pre_heating) run_second_pass_injection(); } + update_exclusion_volume_path_check_result(); //BBS: update slice warning update_slice_warnings(); } @@ -4857,6 +4907,30 @@ void GCodeProcessor::process_G0(const GCodeReader::GCodeLine& line) process_G1(line); } +void GCodeProcessor::update_position_known_from_move( + const std::array, 4> &axes, + const G1DiscretizationOrigin origin) +{ + if (origin != G1DiscretizationOrigin::G1 || m_global_positioning_type != EPositioningType::Absolute) + return; + + for (unsigned char axis = X; axis <= Z; ++axis) { + if (axes[axis].has_value()) + m_axis_position_known[axis] = m_axis_origin_known[axis]; + } +} + +void GCodeProcessor::update_position_known_from_move(const GCodeReader::GCodeLine &line) +{ + if (m_global_positioning_type != EPositioningType::Absolute) + return; + + for (unsigned char axis = X; axis <= Z; ++axis) { + if (line.has(static_cast(axis))) + m_axis_position_known[axis] = m_axis_origin_known[axis]; + } +} + void GCodeProcessor::process_G1(const GCodeReader::GCodeLine& line, const std::optional& remaining_internal_g1_lines) { std::array, 4> g1_axes = { std::nullopt, std::nullopt, std::nullopt, std::nullopt }; @@ -4872,6 +4946,7 @@ void GCodeProcessor::process_G1(const GCodeReader::GCodeLine& line, const std::o void GCodeProcessor::process_G1(const std::array, 4>& axes, const std::optional& feedrate, G1DiscretizationOrigin origin, const std::optional& remaining_internal_g1_lines) { + const std::array start_axis_known = m_axis_position_known; int filament_id = get_filament_id(); int last_filament_id = get_last_filament_id(); float filament_diameter = (static_cast(filament_id) < m_result.filament_diameters.size()) ? m_result.filament_diameters[filament_id] : m_result.filament_diameters.back(); @@ -4921,6 +4996,7 @@ void GCodeProcessor::process_G1(const std::array, 4>& axes for (unsigned char a = X; a <= E; ++a) { m_end_position[a] = extract_absolute_position_on_axis((Axis)a, axes[a], double(area_filament_cross_section)); } + update_position_known_from_move(axes, origin); // updates feedrate from line, if present if (feedrate.has_value()) @@ -4942,6 +5018,40 @@ void GCodeProcessor::process_G1(const std::array, 4>& axes const float delta_xyz = std::sqrt(sqr(delta_pos[X]) + sqr(delta_pos[Y]) + sqr(delta_pos[Z])); m_travel_dist = delta_xyz; + if (!m_processing_homing_move) { + std::optional exclusion_motion_type; + switch (type) { + case EMoveType::Travel: + exclusion_motion_type = ExclusionVolumeMotionType::Travel; + break; + case EMoveType::Extrude: + case EMoveType::Wipe: + exclusion_motion_type = ExclusionVolumeMotionType::Extrude; + break; + case EMoveType::Retract: + case EMoveType::Unretract: + exclusion_motion_type = ExclusionVolumeMotionType::Other; + break; + default: + break; + } + + if (exclusion_motion_type) { + m_exclusion_volume_path_checker.check_motion( + Vec3d(m_start_position[X], m_start_position[Y], m_start_position[Z]), + Vec3d(m_end_position[X], m_end_position[Y], m_end_position[Z]), + start_axis_known[X] && start_axis_known[Y], + m_axis_position_known[X] && m_axis_position_known[Y], + start_axis_known[Z], + m_axis_position_known[Z], + get_extruder_id(false), + *exclusion_motion_type, + static_cast(type), + m_line_id, + m_result.moves.size()); + } + } + if (type == EMoveType::Extrude) { float volume_extruded_filament = area_filament_cross_section * delta_pos[E]; float area_toolpath_cross_section = volume_extruded_filament / delta_xyz; @@ -5925,6 +6035,10 @@ void GCodeProcessor::process_G2_G3(const GCodeReader::GCodeLine& line, bool cloc m_start_position = m_end_position; // this is required because we are skipping the call to process_gcode_line() internal_only_g1_line(adjust_target(end_position, prev_target), arc.delta_z() != 0.0, (segments == 1) ? feedrate : std::nullopt, extrusion); } + + // Internal linearized arc segments inherit the arc's starting certainty. + // Only the original absolute command may establish a newly known endpoint. + update_position_known_from_move(line); } //BBS @@ -6024,7 +6138,19 @@ void GCodeProcessor::process_G28(const GCodeReader::GCodeLine& line) GCodeReader::GCodeLine new_gline; GCodeReader reader; reader.parse_line(new_line_raw, [&](GCodeReader& reader, const GCodeReader::GCodeLine& gline) { new_gline = gline; }); + m_processing_homing_move = true; process_G1(new_gline); + m_processing_homing_move = false; + + // G28's physical endpoint is printer-specific even though the preview uses + // zero. Wait for a subsequent explicit absolute coordinate before checking + // a path from any homed axis. + for (unsigned char axis = X; axis <= Z; ++axis) { + if (!found || line.has(static_cast(axis))) { + m_axis_position_known[axis] = false; + m_axis_origin_known[axis] = true; + } + } } void GCodeProcessor::process_G90(const GCodeReader::GCodeLine& line) @@ -6043,16 +6169,19 @@ void GCodeProcessor::process_G92(const GCodeReader::GCodeLine& line) bool any_found = false; if (line.has_x()) { + m_axis_origin_known[X] = m_axis_position_known[X]; m_origin[X] = m_end_position[X] - line.x() * lengths_scale_factor; any_found = true; } if (line.has_y()) { + m_axis_origin_known[Y] = m_axis_position_known[Y]; m_origin[Y] = m_end_position[Y] - line.y() * lengths_scale_factor; any_found = true; } if (line.has_z()) { + m_axis_origin_known[Z] = m_axis_position_known[Z]; m_origin[Z] = m_end_position[Z] - line.z() * lengths_scale_factor; any_found = true; } @@ -6070,6 +6199,8 @@ void GCodeProcessor::process_G92(const GCodeReader::GCodeLine& line) // The G92 may be called for axes that PrusaSlicer does not recognize, for example see GH issue #3510, // where G92 A0 B0 is called although the extruder axis is till E. for (unsigned char a = X; a <= E; ++a) { + if (a <= Z) + m_axis_origin_known[a] = m_axis_position_known[a]; m_origin[a] = m_end_position[a]; } } diff --git a/src/libslic3r/GCode/GCodeProcessor.hpp b/src/libslic3r/GCode/GCodeProcessor.hpp index 0f211f133e..b169c976d4 100644 --- a/src/libslic3r/GCode/GCodeProcessor.hpp +++ b/src/libslic3r/GCode/GCodeProcessor.hpp @@ -7,6 +7,7 @@ #include "libslic3r/PrintConfig.hpp" #include "libslic3r/CustomGCode.hpp" #include "libslic3r/MultiNozzleUtils.hpp" +#include "libslic3r/GCode/ExclusionVolumePathCheck.hpp" #include #include @@ -268,6 +269,17 @@ class Print; std::vector extruder_heights; //BBS: add toolpath_outside bool toolpath_outside; + bool exclusion_volume_path_checked { false }; + bool exclusion_volume_path_conflict { false }; + bool exclusion_volume_travel_conflict { false }; + bool exclusion_volume_extrusion_conflict { false }; + bool exclusion_volume_other_motion_conflict { false }; + unsigned int exclusion_volume_conflict_gcode_id { 0 }; + size_t exclusion_volume_conflict_move_id { 0 }; + EMoveType exclusion_volume_conflict_move_type { EMoveType::Noop }; + int exclusion_volume_conflict_extruder_id { -1 }; + size_t exclusion_volume_conflict_region_id { 0 }; + bool exclusion_volume_conflict_used_unknown_z { false }; //BBS: add object_label_enabled bool label_object_enabled; //BBS : extra retraction when change filament,experiment func @@ -333,6 +345,17 @@ class Print; bed_exclude_area = other.bed_exclude_area; wrapping_exclude_area = other.wrapping_exclude_area; toolpath_outside = other.toolpath_outside; + exclusion_volume_path_checked = other.exclusion_volume_path_checked; + exclusion_volume_path_conflict = other.exclusion_volume_path_conflict; + exclusion_volume_travel_conflict = other.exclusion_volume_travel_conflict; + exclusion_volume_extrusion_conflict = other.exclusion_volume_extrusion_conflict; + exclusion_volume_other_motion_conflict = other.exclusion_volume_other_motion_conflict; + exclusion_volume_conflict_gcode_id = other.exclusion_volume_conflict_gcode_id; + exclusion_volume_conflict_move_id = other.exclusion_volume_conflict_move_id; + exclusion_volume_conflict_move_type = other.exclusion_volume_conflict_move_type; + exclusion_volume_conflict_extruder_id = other.exclusion_volume_conflict_extruder_id; + exclusion_volume_conflict_region_id = other.exclusion_volume_conflict_region_id; + exclusion_volume_conflict_used_unknown_z = other.exclusion_volume_conflict_used_unknown_z; label_object_enabled = other.label_object_enabled; long_retraction_when_cut = other.long_retraction_when_cut; timelapse_warning_code = other.timelapse_warning_code; @@ -1070,6 +1093,10 @@ class Print; AxisCoords m_start_position; // mm AxisCoords m_end_position; // mm AxisCoords m_origin; // mm + std::array m_axis_position_known { false, false, false }; + std::array m_axis_origin_known { true, true, true }; + bool m_processing_homing_move { false }; + ExclusionVolumePathChecker m_exclusion_volume_path_checker; CachedPosition m_cached_position; bool m_wiping; bool m_flushing; // mark a section with real flush @@ -1206,6 +1233,15 @@ class Print; static unsigned int s_result_id; public: + struct PositionState + { + Vec3d position { Vec3d::Zero() }; + std::array axis_known { false, false, false }; + + bool has_known_xy() const { return axis_known[X] && axis_known[Y]; } + bool has_known_z() const { return axis_known[Z]; } + }; + GCodeProcessor(); void init_filament_maps_and_nozzle_type_when_import_only_gcode(); // Reprocessing an already-generated g-code (from-previous / imported g-code) does not rebuild @@ -1223,6 +1259,7 @@ class Print; const std::vector &filament_map, const std::vector>& unprintable_filament_types ); void apply_config(const PrintConfig& config); + void configure_exclusion_volume_path_check(const PrintConfig &config); void set_print(Print* print) { m_print = print; } // Hand the nozzle grouping context to the estimator BEFORE the streaming replay, so the // per-slot machine-limit resolution can follow the active nozzle. Null is fine (slot 0). @@ -1242,6 +1279,7 @@ class Print; const GCodeProcessorResult& get_result() const { return m_result; } GCodeProcessorResult& result() { return m_result; } GCodeProcessorResult&& extract_result() { return std::move(m_result); } + PositionState get_current_position() const; // Load a G-code into a stand-alone G-code viewer. // throws CanceledException through print->throw_if_canceled() (sent by the caller as callback). @@ -1300,6 +1338,9 @@ class Print; void process_G1(const std::array, 4>& axes = { std::nullopt, std::nullopt, std::nullopt, std::nullopt }, const std::optional& feedrate = std::nullopt, G1DiscretizationOrigin origin = G1DiscretizationOrigin::G1, const std::optional& remaining_internal_g1_lines = std::nullopt); + void update_position_known_from_move(const std::array, 4> &axes, G1DiscretizationOrigin origin); + void update_position_known_from_move(const GCodeReader::GCodeLine &line); + void update_exclusion_volume_path_check_result(); // Arc Move void process_G2_G3(const GCodeReader::GCodeLine& line, bool clockwise); diff --git a/src/libslic3r/Print.cpp b/src/libslic3r/Print.cpp index 8d7a8ec225..42021d3090 100644 --- a/src/libslic3r/Print.cpp +++ b/src/libslic3r/Print.cpp @@ -4601,6 +4601,7 @@ void Print::export_gcode_from_previous_file(const std::string& file, GCodeProces // (via ensure_nozzle_group_result), so the multi-nozzle send/monitor mapping survives here. if (result != nullptr && result->nozzle_group_result) processor.initialize_from_context(result->nozzle_group_result); + processor.configure_exclusion_volume_path_check(this->config()); //processor.enable_producers(true); processor.process_file(file); diff --git a/src/libslic3r/PrintBase.hpp b/src/libslic3r/PrintBase.hpp index d4f99c764e..f73626241f 100644 --- a/src/libslic3r/PrintBase.hpp +++ b/src/libslic3r/PrintBase.hpp @@ -62,7 +62,8 @@ public: SlicingReplaceInitEmptyLayers, SlicingNeedSupportOn, SlicingEmptyGcodeLayers, - SlicingGcodeOverlap + SlicingGcodeOverlap, + SlicingExclusionVolumeToolpath }; typedef size_t TimeStamp; From 333a9be86e707fbbd09fc137c21b4fa0feccddc1 Mon Sep 17 00:00:00 2001 From: Harry Loud Date: Thu, 16 Jul 2026 11:01:15 +0100 Subject: [PATCH 12/38] Add multi-nozzle exclusion volume travel routing --- src/libslic3r/CMakeLists.txt | 2 + src/libslic3r/GCode.cpp | 122 +++- src/libslic3r/GCode.hpp | 18 +- .../GCode/ExclusionVolumeTravelAvoidance.cpp | 592 ++++++++++++++++++ .../GCode/ExclusionVolumeTravelAvoidance.hpp | 79 +++ 5 files changed, 802 insertions(+), 11 deletions(-) create mode 100644 src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.cpp create mode 100644 src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.hpp diff --git a/src/libslic3r/CMakeLists.txt b/src/libslic3r/CMakeLists.txt index af1ef8e4db..ce3fd8476c 100644 --- a/src/libslic3r/CMakeLists.txt +++ b/src/libslic3r/CMakeLists.txt @@ -234,6 +234,8 @@ set(lisbslic3r_sources GCode/CoolingBuffer.hpp GCode/ExclusionVolumePathCheck.cpp GCode/ExclusionVolumePathCheck.hpp + GCode/ExclusionVolumeTravelAvoidance.cpp + GCode/ExclusionVolumeTravelAvoidance.hpp GCode/TimelapsePosPicker.cpp GCode/TimelapsePosPicker.hpp GCode.cpp diff --git a/src/libslic3r/GCode.cpp b/src/libslic3r/GCode.cpp index 23f7a47188..f31c0ed2c5 100644 --- a/src/libslic3r/GCode.cpp +++ b/src/libslic3r/GCode.cpp @@ -2435,6 +2435,8 @@ void GCode::do_export(Print* print, const char* path, GCodeProcessorResult* resu // BBS m_curr_print = print; m_skirt_group_done.clear(); + m_pending_start_gcode_position.reset(); + m_exclusion_volume_travel_avoidance.init(print->config(), print->get_plate_origin()); GCodeWriter::full_gcode_comment = print->config().gcode_comments; CNumericLocalesSetter locales_setter; @@ -3776,6 +3778,17 @@ void GCode::_do_export(Print& print, GCodeOutputStream &file, ThumbnailsGenerato file.write(this->set_extruder(initial_extruder_id, 0.)); } + // Direct output writes are parsed synchronously. Preserve the startup + // endpoint before the generator establishes its first model-space point, + // so that first travel can be planned from the position the G-code actually + // left the machine at rather than the default last_pos value. + GCodeProcessor::PositionState startup_position = m_processor.get_current_position(); + const Vec2f plate_offset = m_writer.get_xy_offset(); + startup_position.position.x() += plate_offset.x(); + startup_position.position.y() += plate_offset.y(); + m_pending_start_gcode_position = !m_last_pos_defined && startup_position.has_known_xy() ? + std::optional(startup_position) : std::nullopt; + this->m_objsWithBrim.clear(); m_brim_done = false; @@ -8888,10 +8901,17 @@ std::string GCode::_encode_label_ids_to_base64(std::vector ids) // This method accepts &point in print coordinates. std::string GCode::travel_to(const Point& point, ExtrusionRole role, std::string comment, double z/* = DBL_MAX*/) { + const std::optional start_gcode_position = + !m_exclusion_volume_travel_avoidance.empty() && !m_last_pos_defined && + !m_writer.is_current_position_clear() && m_pending_start_gcode_position.has_value() ? + m_pending_start_gcode_position : std::nullopt; + /* Define the travel move as a line between current position and the taget point. This is expressed in print coordinates, so it will need to be translated by this->origin in order to get G-code coordinates. */ - Polyline travel { this->last_pos(), point }; + const Point travel_start = start_gcode_position ? + this->gcode_to_point(to_2d(start_gcode_position->position)) : this->last_pos(); + Polyline travel { travel_start, point }; // check whether a straight travel move would need retraction LiftType lift_type = LiftType::SpiralLift; @@ -8901,6 +8921,57 @@ std::string GCode::travel_to(const Point& point, ExtrusionRole role, std::string // Save state of use_external_mp_once for the case that will be needed to call twice m_avoid_crossing_perimeters.travel_to. const bool used_external_mp_once = m_avoid_crossing_perimeters.used_external_mp_once(); std::string gcode; + bool exclusion_volume_travel_rerouted = false; + + const auto active_extruder_id = [this]() { + if (m_writer.filament() == nullptr) + return -1; + const size_t id = m_writer.filament()->extruder_id(); + return id < m_config.nozzle_diameter.size() ? int(id) : -1; + }; + const auto to_gcode_point = [this](const Point &local_point) { + const Vec2d point = this->point_to_gcode(local_point); + return Point(scale_(point.x()), scale_(point.y())); + }; + const auto to_local_point = [this](const Point &gcode_point) { + return this->gcode_to_point(unscaled(gcode_point)); + }; + const auto to_gcode_polyline = [&to_gcode_point](const Polyline &local_path) { + Polyline result; + result.points.reserve(local_path.points.size()); + for (const Point &local_point : local_path.points) + result.append(to_gcode_point(local_point)); + return result; + }; + const auto to_local_polyline = [&to_local_point](const Polyline &gcode_path) { + Polyline result; + result.points.reserve(gcode_path.points.size()); + for (const Point &gcode_point : gcode_path.points) + result.append(to_local_point(gcode_point)); + return result; + }; + const auto nominal_writer_z = [this]() { + return m_writer.get_position().z() - m_writer.get_zhop(); + }; + const auto route_around_exclusion_volumes = [&]( + Polyline &path, + const std::optional &start_z_override) { + if (m_exclusion_volume_travel_avoidance.empty() || path.size() < 2) + return false; + + const double target_z = z == DBL_MAX ? m_nominal_z : z; + const ExclusionVolumeTravelAvoidance::Result result = + m_exclusion_volume_travel_avoidance.route( + to_gcode_polyline(path), + start_z_override.value_or(nominal_writer_z()), + target_z, + active_extruder_id()); + if (!result.rerouted()) + return false; + + path = to_local_polyline(result.path); + return true; + }; // Orca: we don't need to optimize the Klipper as only set once double jerk_to_set = 0.0; @@ -8965,6 +9036,14 @@ std::string GCode::travel_to(const Point& point, ExtrusionRole role, std::string //if (needs_retraction && m_layer_index > 1) exit(0); } + const std::optional start_gcode_z = + start_gcode_position && start_gcode_position->has_known_z() ? + std::optional(start_gcode_position->position.z()) : std::nullopt; + if (route_around_exclusion_volumes(travel, start_gcode_z)) { + exclusion_volume_travel_rerouted = true; + needs_retraction = this->needs_retraction(travel, role, lift_type); + } + // Re-allow reduce_crossing_wall for the next travel moves m_avoid_crossing_perimeters.reset_once_modifiers(); @@ -8980,15 +9059,22 @@ std::string GCode::travel_to(const Point& point, ExtrusionRole role, std::string // When "Wipe while retracting" is enabled, then extruder moves to another position, and travel from this position can cross perimeters. // Because of it, it is necessary to call avoid crossing perimeters again with new starting point after calling retraction() // FIXME Lukas H.: Try to predict if this second calling of avoid crossing perimeters will be needed or not. It could save computations. - if (last_post_before_retract != this->last_pos() && m_config.reduce_crossing_wall) { - // If in the previous call of m_avoid_crossing_perimeters.travel_to was use_external_mp_once set to true restore this value for next call. - if (used_external_mp_once) - m_avoid_crossing_perimeters.use_external_mp_once(); - travel = m_avoid_crossing_perimeters.travel_to(*this, point); - // If state of use_external_mp_once was changed reset it to right value. - if (used_external_mp_once) - m_avoid_crossing_perimeters.reset_once_modifiers(); + if (last_post_before_retract != this->last_pos()) { + travel = Polyline { this->last_pos(), point }; + if (m_config.reduce_crossing_wall) { + // If in the previous call of m_avoid_crossing_perimeters.travel_to was use_external_mp_once set to true restore this value for next call. + if (used_external_mp_once) + m_avoid_crossing_perimeters.use_external_mp_once(); + travel = m_avoid_crossing_perimeters.travel_to(*this, point); + // If state of use_external_mp_once was changed reset it to right value. + if (used_external_mp_once) + m_avoid_crossing_perimeters.reset_once_modifiers(); + } } + + exclusion_volume_travel_rerouted = + route_around_exclusion_volumes(travel, std::nullopt) || + (last_post_before_retract == this->last_pos() && exclusion_volume_travel_rerouted); } else { // Reset the wipe path when traveling, so one would not wipe along an old path. m_wipe.reset_path(); @@ -9020,6 +9106,24 @@ std::string GCode::travel_to(const Point& point, ExtrusionRole role, std::string Vec3d dest3d(dest2d(0), dest2d(1), z == DBL_MAX ? m_nominal_z : z); gcode += m_writer.travel_to_xyz(dest3d, comment, m_need_change_layer_lift_z); m_need_change_layer_lift_z = false; + } else if (exclusion_volume_travel_rerouted && z != DBL_MAX) { + // Preserve the original sloped-Z move over the longer detour. + // The router activates every volume touched by the complete Z + // range, so this interpolation remains conservative. + const double start_z = m_writer.get_position().z(); + const double total_length = std::max(travel.length(), 1.0); + double traveled = 0.0; + for (size_t i = 1; i < travel.size(); ++i) { + traveled += (travel.points[i] - travel.points[i - 1]).cast().norm(); + const Vec2d dest2d = this->point_to_gcode(travel.points[i]); + const Vec3d dest3d( + dest2d.x(), + dest2d.y(), + start_z + (z - start_z) * std::min(1.0, traveled / total_length)); + gcode += m_writer.travel_to_xyz(dest3d, comment, i == 1 && m_need_change_layer_lift_z); + if (i == 1) + m_need_change_layer_lift_z = false; + } } else { // Extra movements emitted by avoid_crossing_perimeters, lift the z to normal height at the beginning, then apply the z // ratio at the last point diff --git a/src/libslic3r/GCode.hpp b/src/libslic3r/GCode.hpp index 990bf0fee7..acc6a56a0e 100644 --- a/src/libslic3r/GCode.hpp +++ b/src/libslic3r/GCode.hpp @@ -10,6 +10,7 @@ #include "PrintConfig.hpp" #include "GCode/AvoidCrossingPerimeters.hpp" #include "GCode/CoolingBuffer.hpp" +#include "GCode/ExclusionVolumeTravelAvoidance.hpp" #include "GCode/FanMover.hpp" #include "GCode/RetractWhenCrossingPerimeters.hpp" #include "GCode/SpiralVase.hpp" @@ -413,8 +414,16 @@ private: size_t get_extruder_id(unsigned int filament_id) const; void update_placeholder_parser_with_variant_params(); - void set_last_pos(const Point &pos) { m_last_pos = Point3(pos, 0); m_last_pos_defined = true; } - void set_last_pos(const Point3 &pos) { m_last_pos = pos; m_last_pos_defined = true; } + void set_last_pos(const Point &pos) { + m_last_pos = Point3(pos, 0); + m_last_pos_defined = true; + m_pending_start_gcode_position.reset(); + } + void set_last_pos(const Point3 &pos) { + m_last_pos = pos; + m_last_pos_defined = true; + m_pending_start_gcode_position.reset(); + } bool last_pos_defined() const { return m_last_pos_defined; } void set_extruders(const std::vector &extruder_ids); std::string preamble(); @@ -622,6 +631,7 @@ private: OozePrevention m_ooze_prevention; Wipe m_wipe; AvoidCrossingPerimeters m_avoid_crossing_perimeters; + ExclusionVolumeTravelAvoidance m_exclusion_volume_travel_avoidance; RetractWhenCrossingPerimeters m_retract_when_crossing_perimeters; TimelapsePosPicker m_timelapse_pos_picker; @@ -739,6 +749,10 @@ private: // Processor GCodeProcessor m_processor; + // Command-space endpoint after startup G-code. The processor sees direct + // file writes synchronously, while the generator has not established its + // first model-space point yet. + std::optional m_pending_start_gcode_position; //some post-processing on the file, with their data class std::unique_ptr m_fan_mover; diff --git a/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.cpp b/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.cpp new file mode 100644 index 0000000000..3a7f308f49 --- /dev/null +++ b/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.cpp @@ -0,0 +1,592 @@ +#include "ExclusionVolumeTravelAvoidance.hpp" + +#include "libslic3r/ClipperUtils.hpp" +#include "libslic3r/Line.hpp" +#include "libslic3r/Polygon.hpp" + +#include +#include +#include +#include + +namespace Slic3r { + +namespace { + +constexpr double Z_EPSILON_MM = 1e-6; +constexpr double T_EPSILON = 1e-9; +constexpr size_t MAX_REROUTE_ITERATIONS = 16; + +struct SegmentIntersection +{ + double t { 0.0 }; + Point point; + size_t edge_idx { 0 }; +}; + +double boundary_epsilon() +{ + return std::max(SCALED_EPSILON, scale_(0.005)); +} + +bool z_ranges_overlap(double a_min, double a_max, double b_min, double b_max) +{ + return a_max >= b_min - Z_EPSILON_MM && a_min <= b_max + Z_EPSILON_MM; +} + +bool line_intersection_t( + const Point &a, + const Point &b, + const Point &c, + const Point &d, + double &t, + Point &intersection) +{ + const Vec2d p = a.cast(); + const Vec2d r = (b - a).cast(); + const Vec2d q = c.cast(); + const Vec2d s = (d - c).cast(); + const double denominator = cross2(r, s); + if (std::abs(denominator) < T_EPSILON) + return false; + + const Vec2d qp = q - p; + const double candidate_t = cross2(qp, s) / denominator; + const double u = cross2(qp, r) / denominator; + if (candidate_t < -T_EPSILON || candidate_t > 1.0 + T_EPSILON || + u < -T_EPSILON || u > 1.0 + T_EPSILON) + return false; + + t = std::clamp(candidate_t, 0.0, 1.0); + intersection = (p + t * r).cast(); + return true; +} + +template +void for_each_expolygon_contour(const ExPolygon &expolygon, Fn &&fn) +{ + fn(expolygon.contour); + for (const Polygon &hole : expolygon.holes) + fn(hole); +} + +void add_unique_param(std::vector ¶ms, double t) +{ + const double clamped = std::clamp(t, 0.0, 1.0); + if (std::none_of(params.begin(), params.end(), [clamped](double value) { + return std::abs(value - clamped) < T_EPSILON; + })) + params.emplace_back(clamped); +} + +std::vector contour_intersections( + const Point &a, + const Point &b, + const Polygon &polygon) +{ + std::vector intersections; + if (polygon.points.size() < 2) + return intersections; + + intersections.reserve(4); + for (size_t edge_idx = 0; edge_idx < polygon.points.size(); ++edge_idx) { + const Point &c = polygon.points[edge_idx]; + const Point &d = polygon.points[(edge_idx + 1) % polygon.points.size()]; + double t = 0.0; + Point point; + if (line_intersection_t(a, b, c, d, t, point) && + std::none_of(intersections.begin(), intersections.end(), [t](const SegmentIntersection &other) { + return std::abs(other.t - t) < T_EPSILON; + })) + intersections.push_back({ t, point, edge_idx }); + } + + std::sort(intersections.begin(), intersections.end(), [](const SegmentIntersection &lhs, const SegmentIntersection &rhs) { + return lhs.t < rhs.t; + }); + return intersections; +} + +bool point_in_expolygons(const ExPolygons &expolygons, const Point &point, bool border_result) +{ + return std::any_of(expolygons.begin(), expolygons.end(), [&point, border_result](const ExPolygon &expolygon) { + return expolygon.contains(point, border_result); + }); +} + +bool point_on_expolygon_boundary(const ExPolygon &expolygon, const Point &point) +{ + const double epsilon = boundary_epsilon(); + if (expolygon.contour.on_boundary(point, epsilon)) + return true; + return std::any_of(expolygon.holes.begin(), expolygon.holes.end(), [&point, epsilon](const Polygon &hole) { + return hole.on_boundary(point, epsilon); + }); +} + +bool point_on_expolygons_boundary(const ExPolygons &expolygons, const Point &point) +{ + return std::any_of(expolygons.begin(), expolygons.end(), [&point](const ExPolygon &expolygon) { + return point_on_expolygon_boundary(expolygon, point); + }); +} + +bool point_in_expolygons_interior(const ExPolygons &expolygons, const Point &point) +{ + return point_in_expolygons(expolygons, point, false) && + !point_on_expolygons_boundary(expolygons, point); +} + +std::vector boundary_params_for_segment( + const Point &a, + const Point &b, + const ExPolygons &expolygons) +{ + std::vector params { 0.0, 1.0 }; + for (const ExPolygon &expolygon : expolygons) { + for_each_expolygon_contour(expolygon, [&](const Polygon &contour) { + for (const SegmentIntersection &intersection : contour_intersections(a, b, contour)) + add_unique_param(params, intersection.t); + }); + } + std::sort(params.begin(), params.end()); + return params; +} + +Point interpolate(const Point &a, const Point &b, double t) +{ + return (a.cast() + t * (b - a).cast()).cast(); +} + +bool segment_enters_expolygons_interior( + const Point &a, + const Point &b, + const ExPolygons &expolygons) +{ + if (expolygons.empty()) + return false; + if (point_in_expolygons_interior(expolygons, a) || point_in_expolygons_interior(expolygons, b)) + return true; + + const std::vector params = boundary_params_for_segment(a, b, expolygons); + for (size_t idx = 1; idx < params.size(); ++idx) { + const double low = params[idx - 1]; + const double high = params[idx]; + if (high - low < T_EPSILON) + continue; + if (point_in_expolygons_interior(expolygons, interpolate(a, b, 0.5 * (low + high)))) + return true; + } + return false; +} + +std::optional first_interior_param_for_segment( + const Point &a, + const Point &b, + const ExPolygons &expolygons) +{ + if (expolygons.empty()) + return std::nullopt; + if (point_in_expolygons_interior(expolygons, a)) + return 0.0; + + const std::vector params = boundary_params_for_segment(a, b, expolygons); + for (size_t idx = 1; idx < params.size(); ++idx) { + const double low = params[idx - 1]; + const double high = params[idx]; + if (high - low < T_EPSILON) + continue; + if (point_in_expolygons_interior(expolygons, interpolate(a, b, 0.5 * (low + high)))) + return low; + } + + return point_in_expolygons_interior(expolygons, b) ? std::optional(1.0) : std::nullopt; +} + +bool segment_inside_bed(const Point &a, const Point &b, const ExPolygons &valid_bed) +{ + if (valid_bed.empty()) + return true; + if (!point_in_expolygons(valid_bed, a, true) || !point_in_expolygons(valid_bed, b, true)) + return false; + + const std::vector params = boundary_params_for_segment(a, b, valid_bed); + for (size_t idx = 1; idx < params.size(); ++idx) { + const double low = params[idx - 1]; + const double high = params[idx]; + if (high - low < T_EPSILON) + continue; + if (!point_in_expolygons(valid_bed, interpolate(a, b, 0.5 * (low + high)), false)) + return false; + } + return true; +} + +double polyline_length(const Polyline &polyline) +{ + double length = 0.0; + for (size_t idx = 1; idx < polyline.points.size(); ++idx) + length += (polyline.points[idx] - polyline.points[idx - 1]).cast().norm(); + return length; +} + +bool points_near(const Point &lhs, const Point &rhs) +{ + const double epsilon = boundary_epsilon(); + return (lhs - rhs).cast().squaredNorm() <= epsilon * epsilon; +} + +bool replacement_matches_original_segment(const Polyline &replacement, const Point &a, const Point &b) +{ + return replacement.points.size() == 2 && + points_near(replacement.points.front(), a) && points_near(replacement.points.back(), b); +} + +void append_point(Points &points, const Point &point) +{ + if (points.empty() || points.back() != point) + points.emplace_back(point); +} + +Polyline make_forward_detour( + const Point &a, + const Point &b, + const Polygon &contour, + const SegmentIntersection &entry, + const SegmentIntersection &exit) +{ + Points points; + append_point(points, a); + append_point(points, entry.point); + + const size_t count = contour.points.size(); + for (size_t idx = (entry.edge_idx + 1) % count; idx != (exit.edge_idx + 1) % count; idx = (idx + 1) % count) + append_point(points, contour.points[idx]); + + append_point(points, exit.point); + append_point(points, b); + return Polyline(std::move(points)); +} + +Polyline make_backward_detour( + const Point &a, + const Point &b, + const Polygon &contour, + const SegmentIntersection &entry, + const SegmentIntersection &exit) +{ + Points points; + append_point(points, a); + append_point(points, entry.point); + + const size_t count = contour.points.size(); + const size_t last_vertex = (exit.edge_idx + 1) % count; + for (size_t idx = entry.edge_idx;; idx = idx == 0 ? count - 1 : idx - 1) { + append_point(points, contour.points[idx]); + if (idx == last_vertex) + break; + } + + append_point(points, exit.point); + append_point(points, b); + return Polyline(std::move(points)); +} + +bool polyline_inside_bed(const Polyline &polyline, const ExPolygons &valid_bed) +{ + for (size_t idx = 1; idx < polyline.points.size(); ++idx) + if (!segment_inside_bed(polyline.points[idx - 1], polyline.points[idx], valid_bed)) + return false; + return true; +} + +bool polyline_intersects_obstacles(const Polyline &polyline, const ExPolygons &obstacles) +{ + for (size_t idx = 1; idx < polyline.points.size(); ++idx) + if (segment_enters_expolygons_interior(polyline.points[idx - 1], polyline.points[idx], obstacles)) + return true; + return false; +} + +std::optional first_intersected_obstacle( + const Point &a, + const Point &b, + const ExPolygons &obstacles) +{ + std::optional best_idx; + double best_t = std::numeric_limits::infinity(); + for (size_t idx = 0; idx < obstacles.size(); ++idx) { + const ExPolygons single { obstacles[idx] }; + if (const std::optional t = first_interior_param_for_segment(a, b, single); t && *t < best_t) { + best_t = *t; + best_idx = idx; + } + } + return best_idx; +} + +std::optional detour_around_obstacle( + const Point &a, + const Point &b, + const ExPolygon &obstacle, + const ExPolygons &obstacles, + const ExPolygons &valid_bed) +{ + const std::vector intersections = contour_intersections(a, b, obstacle.contour); + if (intersections.size() < 2) + return std::nullopt; + + const SegmentIntersection &entry = intersections.front(); + const SegmentIntersection &exit = intersections.back(); + const Polyline forward = make_forward_detour(a, b, obstacle.contour, entry, exit); + const Polyline backward = make_backward_detour(a, b, obstacle.contour, entry, exit); + + const bool forward_bed_valid = polyline_inside_bed(forward, valid_bed); + const bool backward_bed_valid = polyline_inside_bed(backward, valid_bed); + const bool forward_clear = forward_bed_valid && !polyline_intersects_obstacles(forward, obstacles); + const bool backward_clear = backward_bed_valid && !polyline_intersects_obstacles(backward, obstacles); + + if (forward_clear || backward_clear) { + if (forward_clear && !backward_clear) + return forward; + if (!forward_clear && backward_clear) + return backward; + return polyline_length(forward) <= polyline_length(backward) ? forward : backward; + } + + // If another obstacle blocks both immediate choices, retain the valid local + // detour and let the outer repair loop address the next crossing. + if (!forward_bed_valid && !backward_bed_valid) + return std::nullopt; + if (forward_bed_valid && !backward_bed_valid) + return forward; + if (!forward_bed_valid && backward_bed_valid) + return backward; + return polyline_length(forward) <= polyline_length(backward) ? forward : backward; +} + +void replace_segment(Polyline &path, size_t segment_idx, const Polyline &replacement) +{ + Points points; + points.reserve(path.points.size() + replacement.points.size()); + for (size_t idx = 0; idx < segment_idx; ++idx) + append_point(points, path.points[idx]); + for (const Point &point : replacement.points) + append_point(points, point); + for (size_t idx = segment_idx + 2; idx < path.points.size(); ++idx) + append_point(points, path.points[idx]); + path.points = std::move(points); +} + +Polyline simplify_path(const Polyline &path, const ExPolygons &obstacles, const ExPolygons &valid_bed) +{ + if (path.points.size() <= 2) + return path; + + Points simplified; + simplified.reserve(path.points.size()); + size_t current = 0; + append_point(simplified, path.points.front()); + while (current + 1 < path.points.size()) { + size_t next = path.points.size() - 1; + for (; next > current + 1; --next) { + if (segment_inside_bed(path.points[current], path.points[next], valid_bed) && + !segment_enters_expolygons_interior(path.points[current], path.points[next], obstacles)) + break; + } + append_point(simplified, path.points[next]); + current = next; + } + return Polyline(std::move(simplified)); +} + +} // namespace + +void ExclusionVolumeTravelAvoidance::init(const PrintConfig &config, const Vec3d &plate_origin) +{ + clear(); + + std::vector> regions_by_extruder = + get_bed_excluded_regions_by_extruder(config); + m_spaces.resize(regions_by_extruder.size()); + + const Polygon base_bed_shape(get_bed_shape(config)); + const Vec2d plate_xy = plate_origin.head<2>(); + for (size_t extruder_id = 0; extruder_id < regions_by_extruder.size(); ++extruder_id) { + RoutingSpace &space = m_spaces[extruder_id]; + space.regions = std::move(regions_by_extruder[extruder_id]); + + const Vec2d extruder_offset = extruder_id < config.extruder_offset.values.size() ? + config.extruder_offset.values[extruder_id] : Vec2d::Zero(); + // Resolved regions are in nozzle/model space. The generator routes in + // emitted G-code space (model - active nozzle offset), before the writer + // subtracts the plate origin, so transform both obstacles and bed alike. + const Vec2d translation_mm = plate_xy - extruder_offset; + const Point translation = scaled(translation_mm); + for (BedExcludeRegion ®ion : space.regions) + region.polygon.translate(translation); + + space.bed_shape = base_bed_shape; + space.bed_shape.translate(translation); + space.bed_shape.make_counter_clockwise(); + } + + double max_nozzle_diameter = 0.0; + for (double diameter : config.nozzle_diameter.values) + max_nozzle_diameter = std::max(max_nozzle_diameter, diameter); + + // This is a numerical/perimeter-walk clearance, not a hidden toolhead + // footprint. The exact configured volume remains Stage 2's source of truth. + const coord_t minimum_clearance = static_cast(SCALED_EPSILON); + const coord_t configured_clearance = + static_cast(scale_(std::max(0.05, 0.1 * max_nozzle_diameter))); + m_clearance = std::max(minimum_clearance, configured_clearance); +} + +void ExclusionVolumeTravelAvoidance::clear() +{ + m_spaces.clear(); + m_clearance = static_cast(SCALED_EPSILON); +} + +bool ExclusionVolumeTravelAvoidance::empty() const +{ + return std::all_of(m_spaces.begin(), m_spaces.end(), [](const RoutingSpace &space) { + return space.regions.empty(); + }); +} + +std::optional +ExclusionVolumeTravelAvoidance::active_obstacles( + const RoutingSpace &space, + double z_min, + double z_max) const +{ + Polygons active_polygons; + active_polygons.reserve(space.regions.size()); + for (const BedExcludeRegion ®ion : space.regions) + if (z_ranges_overlap(z_min, z_max, region.z_min, region.z_max)) + active_polygons.emplace_back(region.polygon); + + if (active_polygons.empty()) + return std::nullopt; + + ActiveObstacles active; + active.obstacles = union_ex(expand(active_polygons, float(m_clearance))); + if (space.bed_shape.points.size() >= 3) { + active.valid_bed = offset_ex(space.bed_shape, -float(m_clearance)); + if (active.valid_bed.empty()) + active.valid_bed = union_ex(Polygons { space.bed_shape }); + } + return active; +} + +ExclusionVolumeTravelAvoidance::Result ExclusionVolumeTravelAvoidance::route( + const Polyline &travel, + double start_z, + double end_z, + int extruder_id) const +{ + Result result; + result.path = travel; + if (travel.points.size() < 2) + return result; + if (extruder_id < 0 || size_t(extruder_id) >= m_spaces.size()) { + result.status = Status::Failed; + result.detail = Detail::UnknownExtruder; + return result; + } + + const RoutingSpace &space = m_spaces[size_t(extruder_id)]; + if (space.regions.empty()) { + result.detail = Detail::NoActiveObstacles; + return result; + } + + const double z_min = std::min(start_z, end_z); + const double z_max = std::max(start_z, end_z); + const std::optional active = active_obstacles(space, z_min, z_max); + if (!active || active->obstacles.empty()) { + result.detail = Detail::NoActiveObstacles; + return result; + } + result.active_obstacles = active->obstacles.size(); + + const Point &start = travel.points.front(); + const Point &end = travel.points.back(); + const std::optional start_obstacles = active_obstacles(space, start_z, start_z); + const std::optional end_obstacles = active_obstacles(space, end_z, end_z); + if ((start_obstacles && point_in_expolygons_interior(start_obstacles->obstacles, start)) || + (end_obstacles && point_in_expolygons_interior(end_obstacles->obstacles, end))) { + result.status = Status::EndpointInside; + result.detail = Detail::EndpointInside; + return result; + } + + bool needs_reroute = false; + for (size_t idx = 1; idx < travel.points.size(); ++idx) { + if (segment_enters_expolygons_interior(travel.points[idx - 1], travel.points[idx], active->obstacles)) { + needs_reroute = true; + break; + } + } + if (!needs_reroute) { + result.detail = Detail::NoIntersection; + return result; + } + + Polyline path = travel; + bool rerouted = false; + for (size_t iteration = 0; iteration < MAX_REROUTE_ITERATIONS; ++iteration) { + result.iterations = iteration + 1; + bool changed = false; + for (size_t segment_idx = 0; segment_idx + 1 < path.points.size(); ++segment_idx) { + const Point &a = path.points[segment_idx]; + const Point &b = path.points[segment_idx + 1]; + if (!segment_inside_bed(a, b, active->valid_bed)) { + result.status = Status::Failed; + result.detail = Detail::SegmentOutsideBed; + return result; + } + + const std::optional obstacle_idx = first_intersected_obstacle(a, b, active->obstacles); + if (!obstacle_idx) + continue; + + const std::optional detour = detour_around_obstacle( + a, b, active->obstacles[*obstacle_idx], active->obstacles, active->valid_bed); + if (!detour) { + result.status = Status::Failed; + result.detail = Detail::DetourFailed; + return result; + } + if (replacement_matches_original_segment(*detour, a, b)) + continue; + + replace_segment(path, segment_idx, *detour); + changed = true; + rerouted = true; + break; + } + + if (!changed) { + path = simplify_path(path, active->obstacles, active->valid_bed); + if (!polyline_inside_bed(path, active->valid_bed) || + polyline_intersects_obstacles(path, active->obstacles)) { + result.status = Status::Failed; + result.detail = Detail::FinalPathInvalid; + return result; + } + result.path = std::move(path); + result.status = rerouted ? Status::Rerouted : Status::Unchanged; + result.detail = rerouted ? Detail::None : Detail::NoIntersection; + return result; + } + } + + result.status = Status::Failed; + result.detail = Detail::IterationLimit; + return result; +} + +} // namespace Slic3r diff --git a/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.hpp b/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.hpp new file mode 100644 index 0000000000..27b3318039 --- /dev/null +++ b/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.hpp @@ -0,0 +1,79 @@ +#pragma once + +#include "libslic3r/ExPolygon.hpp" +#include "libslic3r/Polyline.hpp" +#include "libslic3r/PrintConfig.hpp" + +#include +#include +#include + +namespace Slic3r { + +class ExclusionVolumeTravelAvoidance +{ +public: + enum class Status : unsigned char + { + Unchanged, + Rerouted, + EndpointInside, + Failed + }; + + enum class Detail : unsigned char + { + None, + UnknownExtruder, + NoActiveObstacles, + NoIntersection, + EndpointInside, + SegmentOutsideBed, + DetourFailed, + FinalPathInvalid, + IterationLimit + }; + + struct Result + { + Status status { Status::Unchanged }; + Detail detail { Detail::None }; + Polyline path; + size_t active_obstacles { 0 }; + size_t iterations { 0 }; + + bool rerouted() const { return status == Status::Rerouted; } + }; + + void init(const PrintConfig &config, const Vec3d &plate_origin); + void clear(); + + bool empty() const; + + // Input and output are scaled XY points in the active nozzle's generated + // G-code coordinates before GCodeWriter subtracts the plate offset. + Result route(const Polyline &travel, double start_z, double end_z, int extruder_id) const; + +private: + struct RoutingSpace + { + std::vector regions; + Polygon bed_shape; + }; + + struct ActiveObstacles + { + ExPolygons obstacles; + ExPolygons valid_bed; + }; + + std::optional active_obstacles( + const RoutingSpace &space, + double z_min, + double z_max) const; + + std::vector m_spaces; + coord_t m_clearance { 0 }; +}; + +} // namespace Slic3r From 0804b849a9dba26ff7dcb664a327246db07f08a4 Mon Sep 17 00:00:00 2001 From: Harry Loud Date: Thu, 16 Jul 2026 11:54:26 +0100 Subject: [PATCH 13/38] Make generated brims avoid exclusion volumes --- src/libslic3r/Brim.cpp | 96 ++++++++++++++++--- src/libslic3r/CMakeLists.txt | 2 + src/libslic3r/ExclusionVolumeGeometry.cpp | 92 ++++++++++++++++++ src/libslic3r/ExclusionVolumeGeometry.hpp | 33 +++++++ .../GCode/ExclusionVolumeTravelAvoidance.cpp | 21 +--- 5 files changed, 215 insertions(+), 29 deletions(-) create mode 100644 src/libslic3r/ExclusionVolumeGeometry.cpp create mode 100644 src/libslic3r/ExclusionVolumeGeometry.hpp diff --git a/src/libslic3r/Brim.cpp b/src/libslic3r/Brim.cpp index 9cee5a0e4b..9fb1ccf519 100644 --- a/src/libslic3r/Brim.cpp +++ b/src/libslic3r/Brim.cpp @@ -1,5 +1,6 @@ #include "ClipperUtils.hpp" #include "EdgeGrid.hpp" +#include "ExclusionVolumeGeometry.hpp" #include "Layer.hpp" #include "Print.hpp" #include "ShortestPath.hpp" @@ -10,6 +11,7 @@ #include #include #include +#include #include #include @@ -24,6 +26,51 @@ namespace Slic3r { +static std::vector brim_physical_extruders( + const Print &print, + const size_t filament_id, + const size_t physical_extruder_count) +{ + if (physical_extruder_count == 0) + return {}; + + if (const auto grouping = print.get_layered_nozzle_group_result()) { + if (const auto nozzle = grouping->get_nozzle_for_filament(int(filament_id), 0); + nozzle.has_value() && nozzle->extruder_id >= 0 && + size_t(nozzle->extruder_id) < physical_extruder_count) + return { size_t(nozzle->extruder_id) }; + } + + const bool automatic_mapping_resolved = + !is_auto_filament_map_mode(print.get_filament_map_mode()) || !print.is_BBL_printer() || + print.get_nozzle_group_result() != nullptr; + const int resolved = bed_exclusion_extruder_for_filament( + filament_id, print.get_filament_maps(), print.get_filament_map_mode(), print.is_BBL_printer(), + automatic_mapping_resolved, physical_extruder_count); + if (resolved >= 0) + return { size_t(resolved) }; + + // Generated geometry must remain safe if a late automatic assignment has + // not selected a physical nozzle yet. + std::vector candidates(physical_extruder_count); + std::iota(candidates.begin(), candidates.end(), size_t(0)); + return candidates; +} + +static coord_t brim_exclusion_clearance(const Flow &flow) +{ + const coord_t width_spacing_delta = std::max(0, flow.scaled_width() - flow.scaled_spacing()); + return (width_spacing_delta + 1) / 2 + coord_t(SCALED_EPSILON); +} + +static bool combine_object_brims(const Print &print) +{ + const bool has_per_object_skirt_or_shield = print.config().skirt_type == stPerObject && + (print.has_skirt() || print.has_infinite_skirt()); + return print.config().combine_brims.value && !has_per_object_skirt_or_shield && + print.config().print_sequence != PrintSequence::ByObject; +} + static void append_and_translate(ExPolygons &dst, const ExPolygons &src, const PrintInstance &instance) { size_t dst_idx = dst.size(); expolygons_append(dst, src); @@ -419,6 +466,14 @@ static ExPolygons outer_inner_brim_area(const Print& print, { unsigned int support_material_extruder = printExtruders.front() + 1; Flow flow = print.brim_flow(); + const std::vector> exclusion_regions_by_extruder = + get_bed_excluded_regions_by_extruder(print.config()); + const double first_layer_top_z = std::max(0.0, print.skirt_first_layer_height()); + const coord_t exclusion_clearance = brim_exclusion_clearance(flow); + std::vector combined_brim_physical_extruders; + if (combine_object_brims(print) && !printExtruders.empty()) + combined_brim_physical_extruders = brim_physical_extruders( + print, printExtruders.front(), exclusion_regions_by_extruder.size()); ExPolygons brim_area; ExPolygons no_brim_area; @@ -617,8 +672,6 @@ static ExPolygons outer_inner_brim_area(const Print& print, if (extruder_unprintable_area.empty()) { extruder_unprintable_area.resize(extruder_nums, Polygons{Model::getBedPolygon()}); } - std::vector filament_map = print.get_filament_maps(); - if (print.has_wipe_tower() && !print.get_fake_wipe_tower().outer_wall.empty()) { ExPolygons expolyFromLines{}; for (auto polyline : print.get_fake_wipe_tower().outer_wall.begin()->second) { @@ -634,22 +687,39 @@ static ExPolygons outer_inner_brim_area(const Print& print, auto iter = std::find_if(objPrintVec.begin(), objPrintVec.end(), [object](const std::pair& item) { return item.first == object->id(); }); + std::vector object_physical_extruders; - if (iter != objPrintVec.end()) { - int extruder_id = filament_map[iter->second - 1] - 1; - auto bedPoly = extruder_unprintable_area[extruder_id]; - auto bedExPoly = diff_ex((offset(bedPoly, scale_(30.), jtRound, SCALED_RESOLUTION)), {bedPoly}); - if (!bedExPoly.empty()) { - extruder_no_brim_area.push_back(bedExPoly.front()); + if (iter != objPrintVec.end() && iter->second > 0) { + object_physical_extruders = brim_physical_extruders( + print, size_t(iter->second - 1), exclusion_regions_by_extruder.size()); + object_physical_extruders.insert( + object_physical_extruders.end(), + combined_brim_physical_extruders.begin(), combined_brim_physical_extruders.end()); + for (const size_t extruder_id : object_physical_extruders) { + if (extruder_id >= extruder_unprintable_area.size()) + continue; + const Polygons &bed_poly = extruder_unprintable_area[extruder_id]; + ExPolygons bed_exterior = diff_ex( + offset(bed_poly, scale_(30.), jtRound, SCALED_RESOLUTION), bed_poly); + expolygons_append(extruder_no_brim_area, std::move(bed_exterior)); } //extruder_no_brim_area = offset2_ex(extruder_no_brim_area, scaled_flow_width, -scaled_flow_width); // connect scattered small areas to prevent generating very small brims - } - for (auto& [key, areas] : brimAreaMap) - if (key.object_id == object->id()) - areas = diff_ex(areas, extruder_no_brim_area); - + if (object_physical_extruders.empty()) { + object_physical_extruders.resize(exclusion_regions_by_extruder.size()); + std::iota(object_physical_extruders.begin(), object_physical_extruders.end(), size_t(0)); + } + const ExPolygons exclusions = active_bed_exclusion_footprints( + exclusion_regions_by_extruder, object_physical_extruders, + 0.0, first_layer_top_z, Point(0, 0), exclusion_clearance); + for (auto& [key, areas] : brimAreaMap) { + if (key.object_id != object->id()) + continue; + areas = diff_ex(areas, extruder_no_brim_area); + if (!exclusions.empty()) + areas = diff_ex(areas, exclusions); + } } brim_area.clear(); diff --git a/src/libslic3r/CMakeLists.txt b/src/libslic3r/CMakeLists.txt index ce3fd8476c..dbf0d0469f 100644 --- a/src/libslic3r/CMakeLists.txt +++ b/src/libslic3r/CMakeLists.txt @@ -114,6 +114,8 @@ set(lisbslic3r_sources Emboss.hpp EmbossShape.hpp enum_bitmask.hpp + ExclusionVolumeGeometry.cpp + ExclusionVolumeGeometry.hpp Execution/Execution.hpp Execution/ExecutionSeq.hpp Execution/ExecutionTBB.hpp diff --git a/src/libslic3r/ExclusionVolumeGeometry.cpp b/src/libslic3r/ExclusionVolumeGeometry.cpp new file mode 100644 index 0000000000..32365b8d41 --- /dev/null +++ b/src/libslic3r/ExclusionVolumeGeometry.cpp @@ -0,0 +1,92 @@ +#include "ExclusionVolumeGeometry.hpp" + +#include "ClipperUtils.hpp" + +#include +#include + +namespace Slic3r { + +namespace { + +constexpr double Z_EPSILON_MM = 1e-6; + +void append_active_footprints( + Polygons &out, + const std::vector ®ions, + const double z_min, + const double z_max, + const Point &translation) +{ + for (const BedExcludeRegion ®ion : regions) { + if (region.polygon.points.size() < 3 || region.z_max < region.z_min || + !bed_exclusion_z_ranges_overlap(z_min, z_max, region.z_min, region.z_max)) + continue; + + Polygon footprint = region.polygon; + footprint.translate(translation); + out.emplace_back(std::move(footprint)); + } +} + +ExPolygons union_active_footprints(Polygons footprints, const coord_t clearance) +{ + if (footprints.empty()) + return {}; + + ExPolygons result = union_ex(footprints); + if (clearance > 0) + result = offset_ex(result, float(clearance)); + return result; +} + +} // namespace + +bool bed_exclusion_z_ranges_overlap( + double first_min, + double first_max, + double second_min, + double second_max) +{ + if (first_min > first_max) + std::swap(first_min, first_max); + if (second_min > second_max) + std::swap(second_min, second_max); + return first_max >= second_min - Z_EPSILON_MM && first_min <= second_max + Z_EPSILON_MM; +} + +ExPolygons active_bed_exclusion_footprints( + const std::vector ®ions, + const double z_min, + const double z_max, + const Point &translation, + const coord_t clearance) +{ + Polygons footprints; + footprints.reserve(regions.size()); + append_active_footprints(footprints, regions, z_min, z_max, translation); + return union_active_footprints(std::move(footprints), clearance); +} + +ExPolygons active_bed_exclusion_footprints( + const std::vector> ®ions_by_extruder, + const std::vector &physical_extruders, + const double z_min, + const double z_max, + const Point &translation, + const coord_t clearance) +{ + Polygons footprints; + std::vector visited(regions_by_extruder.size(), false); + for (const size_t extruder_id : physical_extruders) { + if (extruder_id >= regions_by_extruder.size() || visited[extruder_id]) + continue; + visited[extruder_id] = true; + const std::vector ®ions = regions_by_extruder[extruder_id]; + footprints.reserve(footprints.size() + regions.size()); + append_active_footprints(footprints, regions, z_min, z_max, translation); + } + return union_active_footprints(std::move(footprints), clearance); +} + +} // namespace Slic3r diff --git a/src/libslic3r/ExclusionVolumeGeometry.hpp b/src/libslic3r/ExclusionVolumeGeometry.hpp new file mode 100644 index 0000000000..b72868d76b --- /dev/null +++ b/src/libslic3r/ExclusionVolumeGeometry.hpp @@ -0,0 +1,33 @@ +#pragma once + +#include "ExPolygon.hpp" +#include "Point.hpp" +#include "PrintConfig.hpp" + +#include +#include + +namespace Slic3r { + +bool bed_exclusion_z_ranges_overlap(double first_min, double first_max, double second_min, double second_max); + +// Return the union of exclusion footprints intersecting the requested extrusion +// slab. Regions are already resolved into physical-nozzle/model coordinates by +// PrintConfig; callers only provide the physical nozzles that may emit the +// generated geometry and the translation into the caller's coordinate space. +ExPolygons active_bed_exclusion_footprints( + const std::vector ®ions, + double z_min, + double z_max, + const Point &translation = Point(0, 0), + coord_t clearance = 0); + +ExPolygons active_bed_exclusion_footprints( + const std::vector> ®ions_by_extruder, + const std::vector &physical_extruders, + double z_min, + double z_max, + const Point &translation = Point(0, 0), + coord_t clearance = 0); + +} // namespace Slic3r diff --git a/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.cpp b/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.cpp index 3a7f308f49..5fb7ca6b8b 100644 --- a/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.cpp +++ b/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.cpp @@ -1,6 +1,7 @@ #include "ExclusionVolumeTravelAvoidance.hpp" #include "libslic3r/ClipperUtils.hpp" +#include "libslic3r/ExclusionVolumeGeometry.hpp" #include "libslic3r/Line.hpp" #include "libslic3r/Polygon.hpp" @@ -13,7 +14,6 @@ namespace Slic3r { namespace { -constexpr double Z_EPSILON_MM = 1e-6; constexpr double T_EPSILON = 1e-9; constexpr size_t MAX_REROUTE_ITERATIONS = 16; @@ -29,11 +29,6 @@ double boundary_epsilon() return std::max(SCALED_EPSILON, scale_(0.005)); } -bool z_ranges_overlap(double a_min, double a_max, double b_min, double b_max) -{ - return a_max >= b_min - Z_EPSILON_MM && a_min <= b_max + Z_EPSILON_MM; -} - bool line_intersection_t( const Point &a, const Point &b, @@ -462,17 +457,11 @@ ExclusionVolumeTravelAvoidance::active_obstacles( double z_min, double z_max) const { - Polygons active_polygons; - active_polygons.reserve(space.regions.size()); - for (const BedExcludeRegion ®ion : space.regions) - if (z_ranges_overlap(z_min, z_max, region.z_min, region.z_max)) - active_polygons.emplace_back(region.polygon); - - if (active_polygons.empty()) - return std::nullopt; - ActiveObstacles active; - active.obstacles = union_ex(expand(active_polygons, float(m_clearance))); + active.obstacles = active_bed_exclusion_footprints( + space.regions, z_min, z_max, Point(0, 0), m_clearance); + if (active.obstacles.empty()) + return std::nullopt; if (space.bed_shape.points.size() >= 3) { active.valid_bed = offset_ex(space.bed_shape, -float(m_clearance)); if (active.valid_bed.empty()) From 7ad51860af234bbc18cf67792a86f5f1a189a249 Mon Sep 17 00:00:00 2001 From: Harry Loud Date: Thu, 16 Jul 2026 13:15:13 +0100 Subject: [PATCH 14/38] Fix exclusion routing after nozzle changes --- src/libslic3r/GCode.cpp | 96 +++++++++++++++++++++++++++++++++++++++++ src/libslic3r/GCode.hpp | 13 ++++++ 2 files changed, 109 insertions(+) diff --git a/src/libslic3r/GCode.cpp b/src/libslic3r/GCode.cpp index f31c0ed2c5..b2bdc99192 100644 --- a/src/libslic3r/GCode.cpp +++ b/src/libslic3r/GCode.cpp @@ -11,6 +11,7 @@ #include "EdgeGrid.hpp" #include "Geometry/ConvexHull.hpp" #include "GCode/PrintExtents.hpp" +#include "GCodeReader.hpp" #include "GCode/Thumbnails.hpp" #include "GCode/WipeTower.hpp" #include "GCode/WipeTower2.hpp" @@ -86,6 +87,53 @@ using namespace std::literals::string_view_literals; namespace Slic3r { +namespace { + +// Follow XY commands in a generated G-code block. This deliberately handles +// only standard motion/modal commands: an opaque macro that moves the head is +// already outside the position guarantees made by GCodeWriter. +std::optional emitted_xy_after_gcode(const std::string &gcode, const Vec2d &initial_xy) +{ + Vec2d position = initial_xy; + bool absolute = true; + bool coordinate_frame_known = true; + + GCodeReader reader; + reader.parse_buffer(gcode, [&position, &absolute, &coordinate_frame_known](GCodeReader &, const GCodeReader::GCodeLine &line) { + if (line.cmd_is("G90")) { + absolute = true; + return; + } + if (line.cmd_is("G91")) { + absolute = false; + return; + } + + const bool is_motion = line.cmd_is("G0") || line.cmd_is("G1") || line.cmd_is("G2") || line.cmd_is("G3"); + if (is_motion) { + if (line.has_x()) + position.x() = absolute ? line.x() : position.x() + line.x(); + if (line.has_y()) + position.y() = absolute ? line.y() : position.y() + line.y(); + return; + } + + // G92 changes the coordinate system without moving the machine, and + // G28 moves to a firmware-defined position. Do not invent a position + // if either command affects XY. + if (line.cmd_is("G92")) { + coordinate_frame_known = coordinate_frame_known && !line.has_x() && !line.has_y(); + } else if (line.cmd_is("G28")) { + const bool homes_all = !line.has_x() && !line.has_y() && !line.has_z(); + coordinate_frame_known = coordinate_frame_known && !homes_all && !line.has_x() && !line.has_y(); + } + }); + + return coordinate_frame_known ? std::optional(position) : std::nullopt; +} + +} // namespace + //! macro used to mark string used at localization, //! return same string #define L(s) (s) @@ -970,6 +1018,9 @@ static std::vector get_path_of_change_filament(const Print& print) if (new_filament_id != -1 && new_filament_id != tcr.new_tool) throw Slic3r::InvalidArgument("Error: WipeTowerIntegration::append_tcr was asked to do a toolchange it didn't expect."); + const std::optional position_before_toolchange = + gcodegen.capture_toolchange_position(); + int new_extruder_id = get_extruder_index(*m_print_config, new_filament_id); // Logical nozzle grouping for this print (null on paths that don't populate it). @@ -1465,6 +1516,8 @@ static std::vector get_path_of_change_filament(const Print& print) // Let the planner know we are traveling between objects. gcodegen.m_avoid_crossing_perimeters.use_external_mp_once(); + if (position_before_toolchange) + gcodegen.synchronize_toolchange_position(*position_before_toolchange, gcode); return gcode; } @@ -1476,6 +1529,9 @@ static std::vector get_path_of_change_filament(const Print& print) if (new_extruder_id != -1 && new_extruder_id != tcr.new_tool) throw Slic3r::InvalidArgument("Error: WipeTowerIntegration::append_tcr was asked to do a toolchange it didn't expect."); + const std::optional position_before_toolchange = + gcodegen.capture_toolchange_position(); + std::string gcode; // Toolchangeresult.gcode assumes the wipe tower corner is at the origin (except for priming lines) @@ -1792,6 +1848,8 @@ static std::vector get_path_of_change_filament(const Print& print) // Let the planner know we are traveling between objects. gcodegen.m_avoid_crossing_perimeters.use_external_mp_once(); + if (position_before_toolchange) + gcodegen.synchronize_toolchange_position(*position_before_toolchange, gcode); return gcode; } @@ -7144,6 +7202,37 @@ void GCode::set_extruders(const std::vector &extruder_ids) } } +std::optional GCode::capture_toolchange_position() +{ + if (m_exclusion_volume_travel_avoidance.empty() || !m_last_pos_defined || m_writer.filament() == nullptr) + return std::nullopt; + + const Vec2d plate_offset = m_writer.get_xy_offset().cast(); + return ToolchangePositionState{ + int(m_writer.filament()->extruder_id()), + this->point_to_gcode(m_last_pos.to_point()) - plate_offset + }; +} + +void GCode::synchronize_toolchange_position(const ToolchangePositionState &before, const std::string &emitted_gcode) +{ + if (m_writer.filament() == nullptr || int(m_writer.filament()->extruder_id()) == before.physical_extruder_id) + return; + + const std::optional emitted_xy = emitted_xy_after_gcode(emitted_gcode, before.emitted_xy); + if (!emitted_xy) + return; + + // GCodeWriter stores coordinates before applying the per-plate output + // offset. Convert the parsed file coordinates back into that space, then + // into model space using the newly active nozzle offset. + const Vec2d writer_xy = *emitted_xy + m_writer.get_xy_offset().cast(); + Vec3d writer_position = m_writer.get_position(); + writer_position.head<2>() = writer_xy; + m_writer.set_position(writer_position); + this->set_last_pos(this->gcode_to_point(writer_xy)); +} + void GCode::set_origin(const Vec2d &pointf) { // if origin increases (goes towards right), last_pos decreases because it goes towards left @@ -9441,6 +9530,9 @@ std::string GCode::set_extruder(unsigned int new_filament_id, double print_z, bo if (!m_writer.need_toolchange(new_filament_id)) return ""; + const std::optional position_before_toolchange = + this->capture_toolchange_position(); + // if we are running a single-extruder setup, just set the extruder and return nothing if (!m_writer.multiple_extruders) { this->placeholder_parser().set("current_extruder", new_filament_id); @@ -9485,6 +9577,8 @@ std::string GCode::set_extruder(unsigned int new_filament_id, double print_z, bo gcode += m_writer.toolchange(new_filament_id, new_extruder_id); if (Extruder *fil = m_writer.filament()) fil->set_config_index((int)get_filament_config_index((int)fil->id())); + if (position_before_toolchange) + this->synchronize_toolchange_position(*position_before_toolchange, gcode); return gcode; } @@ -9877,6 +9971,8 @@ std::string GCode::set_extruder(unsigned int new_filament_id, double print_z, bo } //Orca: tool changer or IDEX's firmware may change Z position, so we set it to unknown/undefined m_last_pos_defined = false; + if (position_before_toolchange) + this->synchronize_toolchange_position(*position_before_toolchange, gcode); return gcode; } diff --git a/src/libslic3r/GCode.hpp b/src/libslic3r/GCode.hpp index acc6a56a0e..561c8b77c9 100644 --- a/src/libslic3r/GCode.hpp +++ b/src/libslic3r/GCode.hpp @@ -715,6 +715,19 @@ private: Point3 m_last_pos; bool m_last_pos_defined; + struct ToolchangePositionState + { + int physical_extruder_id{-1}; + Vec2d emitted_xy{Vec2d::Zero()}; + }; + + // Capture and restore the actual command-space position around a physical + // nozzle change. Model-space m_last_pos is tied to the active nozzle offset, + // while the machine position itself does not change when Tx is emitted. + std::optional capture_toolchange_position(); + void synchronize_toolchange_position(const ToolchangePositionState &before, + const std::string &emitted_gcode); + std::unique_ptr m_cooling_buffer; std::unique_ptr m_spiral_vase; From 5ec9169bc7929124d8ba0de2a0ff2a8435cd4ae0 Mon Sep 17 00:00:00 2001 From: Harry Loud Date: Thu, 16 Jul 2026 14:44:07 +0100 Subject: [PATCH 15/38] Route exclusion travels at planned lift height --- src/libslic3r/GCode.cpp | 17 +++++++++++++---- src/libslic3r/GCodeWriter.cpp | 13 +++++++++++++ src/libslic3r/GCodeWriter.hpp | 3 +++ 3 files changed, 29 insertions(+), 4 deletions(-) diff --git a/src/libslic3r/GCode.cpp b/src/libslic3r/GCode.cpp index b2bdc99192..50a6235f77 100644 --- a/src/libslic3r/GCode.cpp +++ b/src/libslic3r/GCode.cpp @@ -9044,16 +9044,25 @@ std::string GCode::travel_to(const Point& point, ExtrusionRole role, std::string }; const auto route_around_exclusion_volumes = [&]( Polyline &path, - const std::optional &start_z_override) { + const std::optional &start_z_override, + const bool include_planned_lift = false) { if (m_exclusion_volume_travel_avoidance.empty() || path.size() < 2) return false; const double target_z = z == DBL_MAX ? m_nominal_z : z; + double route_start_z = start_z_override.value_or(nominal_writer_z()); + double route_end_z = target_z; + if (include_planned_lift) { + const Vec2d destination_xy = this->point_to_gcode(path.back()); + std::tie(route_start_z, route_end_z) = m_writer.planned_travel_z( + Vec3d(destination_xy.x(), destination_xy.y(), target_z), + m_need_change_layer_lift_z); + } const ExclusionVolumeTravelAvoidance::Result result = m_exclusion_volume_travel_avoidance.route( to_gcode_polyline(path), - start_z_override.value_or(nominal_writer_z()), - target_z, + route_start_z, + route_end_z, active_extruder_id()); if (!result.rerouted()) return false; @@ -9162,7 +9171,7 @@ std::string GCode::travel_to(const Point& point, ExtrusionRole role, std::string } exclusion_volume_travel_rerouted = - route_around_exclusion_volumes(travel, std::nullopt) || + route_around_exclusion_volumes(travel, std::nullopt, true) || (last_post_before_retract == this->last_pos() && exclusion_volume_travel_rerouted); } else { // Reset the wipe path when traveling, so one would not wipe along an old path. diff --git a/src/libslic3r/GCodeWriter.cpp b/src/libslic3r/GCodeWriter.cpp index 0e80cc1fb7..e60e2fa66b 100644 --- a/src/libslic3r/GCodeWriter.cpp +++ b/src/libslic3r/GCodeWriter.cpp @@ -971,6 +971,19 @@ std::string GCodeWriter::travel_to_xyz(const Vec3d &point, const std::string &co return out_string; } +std::pair GCodeWriter::planned_travel_z(const Vec3d &point, const bool force_z) const +{ + double destination_z = point.z(); + if (std::abs(m_to_lift) > EPSILON) { + if ((!this->is_current_position_clear() || m_pos != point) && + m_to_lift + m_pos.z() > point.z()) + destination_z = m_to_lift + m_pos.z(); + } else if (!force_z && !this->will_move_z(point.z())) { + destination_z = m_pos.z(); + } + return { m_pos.z(), destination_z }; +} + std::string GCodeWriter::travel_to_z(double z, const std::string &comment, bool force) { /* If target Z is lower than current Z but higher than nominal Z diff --git a/src/libslic3r/GCodeWriter.hpp b/src/libslic3r/GCodeWriter.hpp index 8247ab757a..ebefeb0745 100644 --- a/src/libslic3r/GCodeWriter.hpp +++ b/src/libslic3r/GCodeWriter.hpp @@ -80,6 +80,9 @@ public: double get_current_speed() const { return m_current_speed;} std::string travel_to_xy(const Vec2d &point, const std::string &comment = std::string()); std::string travel_to_xyz(const Vec3d &point, const std::string &comment = std::string(), bool force_z = false); + // Physical Z range which travel_to_xyz() will emit without mutating writer state. + // This includes an existing lift or a pending lazy lift. + std::pair planned_travel_z(const Vec3d &point, bool force_z = false) const; std::string travel_to_z(double z, const std::string &comment = std::string(), bool force = false); bool will_move_z(double z) const; std::string extrude_to_xy(const Vec2d &point, double dE, const std::string &comment = std::string(), bool force_no_extrusion = false); From fd55cc77d32b688fd9de48545d29babe4a137410 Mon Sep 17 00:00:00 2001 From: Harry Loud Date: Thu, 16 Jul 2026 16:07:45 +0100 Subject: [PATCH 16/38] Make support generation exclusion-volume aware --- src/libslic3r/Brim.cpp | 44 +------- src/libslic3r/ExclusionVolumeGeometry.cpp | 65 +++++++++++ src/libslic3r/ExclusionVolumeGeometry.hpp | 24 +++++ src/libslic3r/GCode.cpp | 21 +++- src/libslic3r/GCode.hpp | 3 +- src/libslic3r/Print.cpp | 68 +++++++++++- src/libslic3r/Print.hpp | 4 + src/libslic3r/Support/SupportCommon.cpp | 119 +++++++++++++++++++++ src/libslic3r/Support/SupportCommon.hpp | 26 +++++ src/libslic3r/Support/SupportMaterial.cpp | 4 + src/libslic3r/Support/TreeModelVolumes.cpp | 32 +++--- src/libslic3r/Support/TreeSupport3D.cpp | 34 +++++- 12 files changed, 376 insertions(+), 68 deletions(-) diff --git a/src/libslic3r/Brim.cpp b/src/libslic3r/Brim.cpp index 9fb1ccf519..ffe355ea50 100644 --- a/src/libslic3r/Brim.cpp +++ b/src/libslic3r/Brim.cpp @@ -8,10 +8,12 @@ #include "PrintConfig.hpp" #include "MaterialType.hpp" #include "Model.hpp" +#include "Support/SupportCommon.hpp" #include #include #include #include +#include #include #include @@ -26,37 +28,6 @@ namespace Slic3r { -static std::vector brim_physical_extruders( - const Print &print, - const size_t filament_id, - const size_t physical_extruder_count) -{ - if (physical_extruder_count == 0) - return {}; - - if (const auto grouping = print.get_layered_nozzle_group_result()) { - if (const auto nozzle = grouping->get_nozzle_for_filament(int(filament_id), 0); - nozzle.has_value() && nozzle->extruder_id >= 0 && - size_t(nozzle->extruder_id) < physical_extruder_count) - return { size_t(nozzle->extruder_id) }; - } - - const bool automatic_mapping_resolved = - !is_auto_filament_map_mode(print.get_filament_map_mode()) || !print.is_BBL_printer() || - print.get_nozzle_group_result() != nullptr; - const int resolved = bed_exclusion_extruder_for_filament( - filament_id, print.get_filament_maps(), print.get_filament_map_mode(), print.is_BBL_printer(), - automatic_mapping_resolved, physical_extruder_count); - if (resolved >= 0) - return { size_t(resolved) }; - - // Generated geometry must remain safe if a late automatic assignment has - // not selected a physical nozzle yet. - std::vector candidates(physical_extruder_count); - std::iota(candidates.begin(), candidates.end(), size_t(0)); - return candidates; -} - static coord_t brim_exclusion_clearance(const Flow &flow) { const coord_t width_spacing_delta = std::max(0, flow.scaled_width() - flow.scaled_spacing()); @@ -470,10 +441,6 @@ static ExPolygons outer_inner_brim_area(const Print& print, get_bed_excluded_regions_by_extruder(print.config()); const double first_layer_top_z = std::max(0.0, print.skirt_first_layer_height()); const coord_t exclusion_clearance = brim_exclusion_clearance(flow); - std::vector combined_brim_physical_extruders; - if (combine_object_brims(print) && !printExtruders.empty()) - combined_brim_physical_extruders = brim_physical_extruders( - print, printExtruders.front(), exclusion_regions_by_extruder.size()); ExPolygons brim_area; ExPolygons no_brim_area; @@ -690,11 +657,8 @@ static ExPolygons outer_inner_brim_area(const Print& print, std::vector object_physical_extruders; if (iter != objPrintVec.end() && iter->second > 0) { - object_physical_extruders = brim_physical_extruders( - print, size_t(iter->second - 1), exclusion_regions_by_extruder.size()); - object_physical_extruders.insert( - object_physical_extruders.end(), - combined_brim_physical_extruders.begin(), combined_brim_physical_extruders.end()); + object_physical_extruders = bed_exclusion_physical_extruders( + print, { iter->second - 1 }, exclusion_regions_by_extruder.size(), 0); for (const size_t extruder_id : object_physical_extruders) { if (extruder_id >= extruder_unprintable_area.size()) continue; diff --git a/src/libslic3r/ExclusionVolumeGeometry.cpp b/src/libslic3r/ExclusionVolumeGeometry.cpp index 32365b8d41..af1bf25091 100644 --- a/src/libslic3r/ExclusionVolumeGeometry.cpp +++ b/src/libslic3r/ExclusionVolumeGeometry.cpp @@ -1,8 +1,10 @@ #include "ExclusionVolumeGeometry.hpp" #include "ClipperUtils.hpp" +#include "Print.hpp" #include +#include #include namespace Slic3r { @@ -89,4 +91,67 @@ ExPolygons active_bed_exclusion_footprints( return union_active_footprints(std::move(footprints), clearance); } +std::vector bed_exclusion_physical_extruders( + const Print &print, + const std::vector &filament_ids, + const size_t physical_extruder_count, + const int layer_id) +{ + if (physical_extruder_count == 0) + return {}; + + std::vector result; + const auto grouping = print.get_layered_nozzle_group_result(); + const bool automatic_mapping_resolved = + !is_auto_filament_map_mode(print.get_filament_map_mode()) || !print.is_BBL_printer() || + print.get_nozzle_group_result() != nullptr; + bool unresolved = filament_ids.empty(); + + for (const unsigned int filament_id : filament_ids) { + if (grouping) { + if (const auto nozzle = grouping->get_nozzle_for_filament(int(filament_id), layer_id); + nozzle.has_value() && nozzle->extruder_id >= 0 && + size_t(nozzle->extruder_id) < physical_extruder_count) { + result.emplace_back(size_t(nozzle->extruder_id)); + continue; + } + } + + const int resolved = bed_exclusion_extruder_for_filament( + filament_id, print.get_filament_maps(), print.get_filament_map_mode(), print.is_BBL_printer(), + automatic_mapping_resolved, physical_extruder_count); + if (resolved >= 0) + result.emplace_back(size_t(resolved)); + else + unresolved = true; + } + + std::sort(result.begin(), result.end()); + result.erase(std::unique(result.begin(), result.end()), result.end()); + if (!unresolved && !result.empty()) + return result; + + result.resize(physical_extruder_count); + std::iota(result.begin(), result.end(), size_t(0)); + return result; +} + +ExPolygons active_bed_exclusion_footprints_for_object( + const PrintObject &object, + const std::vector> ®ions_by_extruder, + const std::vector &physical_extruders, + const double z_min, + const double z_max, + const coord_t clearance) +{ + ExPolygons result; + for (const PrintInstance &instance : object.instances()) { + const Point instance_shift = instance.shift_without_plate_offset(); + const Point shift(-instance_shift.x(), -instance_shift.y()); + expolygons_append(result, active_bed_exclusion_footprints( + regions_by_extruder, physical_extruders, z_min, z_max, shift, clearance)); + } + return result.empty() ? ExPolygons{} : union_ex(result); +} + } // namespace Slic3r diff --git a/src/libslic3r/ExclusionVolumeGeometry.hpp b/src/libslic3r/ExclusionVolumeGeometry.hpp index b72868d76b..cbf7140b85 100644 --- a/src/libslic3r/ExclusionVolumeGeometry.hpp +++ b/src/libslic3r/ExclusionVolumeGeometry.hpp @@ -9,6 +9,9 @@ namespace Slic3r { +class Print; +class PrintObject; + bool bed_exclusion_z_ranges_overlap(double first_min, double first_max, double second_min, double second_max); // Return the union of exclusion footprints intersecting the requested extrusion @@ -30,4 +33,25 @@ ExPolygons active_bed_exclusion_footprints( const Point &translation = Point(0, 0), coord_t clearance = 0); +// Resolve logical filaments to every physical extruder which may print them. +// An unresolved automatic mapping deliberately returns every physical +// extruder, keeping generated geometry conservative until tool assignment is +// known. +std::vector bed_exclusion_physical_extruders( + const Print &print, + const std::vector &filament_ids, + size_t physical_extruder_count, + int layer_id = -1); + +// Exclusion areas are stored in bed coordinates while generated support is +// shared in PrintObject coordinates. Return the conservative union transformed +// for every instance of the object. +ExPolygons active_bed_exclusion_footprints_for_object( + const PrintObject &object, + const std::vector> ®ions_by_extruder, + const std::vector &physical_extruders, + double z_min, + double z_max, + coord_t clearance = 0); + } // namespace Slic3r diff --git a/src/libslic3r/GCode.cpp b/src/libslic3r/GCode.cpp index 50a6235f77..fbdef80299 100644 --- a/src/libslic3r/GCode.cpp +++ b/src/libslic3r/GCode.cpp @@ -5201,13 +5201,25 @@ std::string GCode::generate_object_skirt_group(const Print &print, object_skirt_tools, layer, extruder_id, m_skirt_group_done[group_idx]); } -std::string GCode::generate_object_brim(const Print &print, const PrintObject &object, size_t instance_id, bool first_layer) +std::string GCode::generate_object_brim( + const Print &print, + const PrintObject &object, + const size_t instance_id, + const bool first_layer, + const unsigned int extruder_id) { if (!first_layer) return {}; - auto emit_brim = [this](const ExtrusionEntityCollection& brim, const std::vector& instances) { + auto emit_brim = [this, extruder_id](const ExtrusionEntityCollection& brim, + const std::vector& instances, + const unsigned int brim_filament_id) { std::string gcode; + // Combined brims have an explicit owner filament. Waiting for that + // filament avoids inheriting whichever tool first encounters a carrier + // object in the layer traversal. + if (brim_filament_id != extruder_id) + return gcode; const bool already_emitted = std::none_of(instances.begin(), instances.end(), [this](const ObjectInstanceID& instance) { return m_objsWithBrim.find(instance) != m_objsWithBrim.end(); }); @@ -5232,7 +5244,7 @@ std::string GCode::generate_object_brim(const Print &print, const PrintObject &o std::string gcode; for (const Print::SkirtBrimGroup::Brim& brim : print.skirt_brim_groups()[group_idx].brims) if (std::find(brim.instances.begin(), brim.instances.end(), object_instance_id) != brim.instances.end()) - gcode += emit_brim(brim.brim, brim.instances); + gcode += emit_brim(brim.brim, brim.instances, brim.filament_id); return gcode; } @@ -6497,7 +6509,8 @@ LayerResult GCode::process_layer( const LayerToPrint &layer_to_print = layers[instance_to_print.layer_id]; if (visit.first_visit && print_wipe_extrusions == (is_anything_overridden ? 1 : 0)) { gcode += generate_object_skirt_group(print, instance_to_print.print_object, instance_to_print.instance_id, layer_tools, layer, extruder_id); - gcode += generate_object_brim(print, instance_to_print.print_object, instance_to_print.instance_id, first_layer); + gcode += generate_object_brim( + print, instance_to_print.print_object, instance_to_print.instance_id, first_layer, extruder_id); } // To control print speed of the 1st object layer printed over raft interface. diff --git a/src/libslic3r/GCode.hpp b/src/libslic3r/GCode.hpp index 561c8b77c9..630ab242e8 100644 --- a/src/libslic3r/GCode.hpp +++ b/src/libslic3r/GCode.hpp @@ -370,7 +370,8 @@ private: std::string generate_object_brim(const Print &print, const PrintObject &object, size_t instance_id, - bool first_layer); + bool first_layer, + unsigned int extruder_id); LayerResult process_layer( const Print &print, diff --git a/src/libslic3r/Print.cpp b/src/libslic3r/Print.cpp index 42021d3090..cb6b28eebc 100644 --- a/src/libslic3r/Print.cpp +++ b/src/libslic3r/Print.cpp @@ -9,6 +9,7 @@ #include "BoundingBox.hpp" #include "Brim.hpp" #include "ClipperUtils.hpp" +#include "ExclusionVolumeGeometry.hpp" #include "Extruder.hpp" #include "FilamentMixer.hpp" #include "Flow.hpp" @@ -2906,7 +2907,11 @@ void Print::process(long long *time_cost_with_cache, bool use_cache) // Orca: Build both the old object-keyed brim map and the per-instance // maps used by skirt/brim groups. m_brimMap.clear(); + m_brimFilamentMap.clear(); m_brimMapByInstance.clear(); + for (const auto& [object_id, filament] : objPrintVec) + if (filament > 0) + m_brimFilamentMap.emplace(object_id, filament - 1); m_first_layer_convex_hull.points.clear(); if (this->has_brim()) { Polygons islands_area; @@ -3287,7 +3292,17 @@ void Print::_make_skirt() } } - auto make_brims_for_skirt_brim_group = [this](const std::vector& group_instances) { + const std::vector> brim_exclusion_regions = + translated_bed_exclusion_volumes_by_extruder(*this); + const bool has_brim_exclusions = std::any_of( + brim_exclusion_regions.begin(), brim_exclusion_regions.end(), + [](const std::vector ®ions) { return !regions.empty(); }); + const bool has_nozzle_specific_brim_exclusions = has_brim_exclusions && + m_config.bed_exclude_area_mode.value != BedExcludeAreaMode::Shared; + + auto make_brims_for_skirt_brim_group = + [this, &brim_exclusion_regions, has_nozzle_specific_brim_exclusions] + (const std::vector& group_instances) { std::vector brims; std::vector brim_instances; for (const ObjectInstanceID& instance : group_instances) { @@ -3296,10 +3311,31 @@ void Print::_make_skirt() brim_instances.push_back(instance); } + auto brim_filament = [this](const ObjectInstanceID& instance) -> std::optional { + const auto it = m_brimFilamentMap.find(instance.object_id); + return it == m_brimFilamentMap.end() ? std::nullopt : + std::optional(it->second); + }; + auto compatible_brim_nozzles = + [this, &brim_filament, &brim_exclusion_regions, has_nozzle_specific_brim_exclusions] + (const ObjectInstanceID& first, const ObjectInstanceID& second) { + if (!has_nozzle_specific_brim_exclusions) + return true; + const std::optional first_filament = brim_filament(first); + const std::optional second_filament = brim_filament(second); + return first_filament.has_value() && second_filament.has_value() && + bed_exclusion_physical_extruders( + *this, { *first_filament, *second_filament }, + brim_exclusion_regions.size(), 0).size() == 1; + }; + const bool combine_group_brims = m_config.combine_brims && brim_instances.size() > 1; if (!combine_group_brims) { - for (const ObjectInstanceID& instance : brim_instances) - brims.push_back({ m_brimMapByInstance.at(instance), { instance } }); + for (const ObjectInstanceID& instance : brim_instances) { + const std::optional filament = brim_filament(instance); + if (filament.has_value()) + brims.push_back({ m_brimMapByInstance.at(instance), { instance }, *filament }); + } return brims; } @@ -3327,6 +3363,7 @@ void Print::_make_skirt() for (size_t j = i + 1; j < brim_instances.size(); ++j) { const auto area_j = m_objectBrimAreasByInstance.find(brim_instances[j]); if (area_j != m_objectBrimAreasByInstance.end() && + compatible_brim_nozzles(brim_instances[i], brim_instances[j]) && !intersection_ex(offset_ex(area_i->second, brim_contact_distance, jtRound, SCALED_RESOLUTION), area_j->second).empty()) unite_brims(i, j); } @@ -3337,9 +3374,12 @@ void Print::_make_skirt() combined_brim_ids[find_brim_parent(i)].push_back(brim_instances[i]); for (const auto& [_, instances] : combined_brim_ids) { + const std::optional filament = brim_filament(instances.front()); + if (!filament.has_value()) + continue; if (instances.size() == 1) { const ObjectInstanceID& instance = instances.front(); - brims.push_back({ m_brimMapByInstance.at(instance), { instance } }); + brims.push_back({ m_brimMapByInstance.at(instance), { instance }, *filament }); continue; } @@ -3351,8 +3391,26 @@ void Print::_make_skirt() const float brim_cleanup_delta = std::max(scaled_resolution, float(SCALED_EPSILON)); combined_area = offset2_ex(combined_area, brim_cleanup_delta, -brim_cleanup_delta, jtRound, scaled_resolution); + // The group has one known physical nozzle. Clip after union and + // cleanup so the geometry consumed by path generation remains + // valid for the exact filament recorded on the combined brim. + const std::vector physical_extruders = bed_exclusion_physical_extruders( + *this, { *filament }, brim_exclusion_regions.size(), 0); + const coord_t width_spacing_delta = std::max( + 0, brim_flow().scaled_width() - brim_flow().scaled_spacing()); + const coord_t exclusion_clearance = + (width_spacing_delta + 1) / 2 + coord_t(SCALED_EPSILON); + const ExPolygons exclusions = active_bed_exclusion_footprints( + brim_exclusion_regions, physical_extruders, 0.0, + std::max(0.0, skirt_first_layer_height()), Point(0, 0), exclusion_clearance); + if (!exclusions.empty()) + combined_area = diff_ex(combined_area, exclusions); + if (combined_area.empty()) + continue; + Polygons islands_area; - brims.push_back({ makeBrimInfillFromPlateCoordinates(combined_area, *this, islands_area), instances }); + brims.push_back({ makeBrimInfillFromPlateCoordinates(combined_area, *this, islands_area), + instances, *filament }); } return brims; diff --git a/src/libslic3r/Print.hpp b/src/libslic3r/Print.hpp index 4d01e64580..03489470a4 100644 --- a/src/libslic3r/Print.hpp +++ b/src/libslic3r/Print.hpp @@ -1009,6 +1009,8 @@ public: struct Brim { ExtrusionEntityCollection brim; std::vector instances; + // Zero-based logical filament selected when the brim was planned. + unsigned int filament_id { unsigned(-1) }; }; ExtrusionEntityCollection skirt; @@ -1321,6 +1323,8 @@ private: bool m_has_shared_per_object_skirt { false }; // Orca: Object-keyed brim paths kept for existing code. std::map m_brimMap; + // Zero-based logical filament selected for each object's brim. + std::map m_brimFilamentMap; // Orca: Actual brim paths keyed by object instance. std::map m_brimMapByInstance; // Orca: Translated brim areas keyed by instance, used to find touching brims. diff --git a/src/libslic3r/Support/SupportCommon.cpp b/src/libslic3r/Support/SupportCommon.cpp index e734608803..9560d02fab 100644 --- a/src/libslic3r/Support/SupportCommon.cpp +++ b/src/libslic3r/Support/SupportCommon.cpp @@ -1,4 +1,5 @@ #include "../ClipperUtils.hpp" +#include "../ExclusionVolumeGeometry.hpp" // #include "../ClipperZUtils.hpp" #include "../ExtrusionEntityCollection.hpp" #include "../Layer.hpp" @@ -35,6 +36,124 @@ namespace Slic3r { +namespace { + +int object_layer_id_at_z(const PrintObject &object, const coordf_t print_z) +{ + const ConstLayerPtrsAdaptor layers = object.layers(); + if (layers.empty()) + return -1; + const auto it = std::lower_bound(layers.begin(), layers.end(), print_z - EPSILON, + [](const Layer *layer, const coordf_t z) { return layer->print_z < z; }); + return int(it == layers.end() ? layers.size() - 1 : size_t(it - layers.begin())); +} + +bool support_layer_uses_interface_material(const SupportGeneratorLayer &layer) +{ + return one_of(layer.layer_type, { + SupporLayerType::RaftInterface, + SupporLayerType::BottomContact, + SupporLayerType::BottomInterface, + SupporLayerType::TopContact, + SupporLayerType::TopInterface }); +} + +void trim_polygons(Polygons &polygons, const Polygons &excluded) +{ + if (!polygons.empty() && !excluded.empty()) + polygons = diff(polygons, excluded, ApplySafetyOffset::Yes); +} + +} // namespace + +std::vector support_exclusion_filaments( + const PrintObject &object, + const bool interface_material) +{ + const int configured = interface_material ? object.config().support_interface_filament.value : + object.config().support_filament.value; + if (configured > 0) + return { unsigned(configured - 1) }; + + // "Current filament" is assigned during tool ordering, not from the + // supported object. It may therefore use a filament from another object, + // or one selected for flush-into-support, on any particular layer. + return object.print() == nullptr ? object.object_extruders() : object.print()->extruders(false); +} + +std::vector support_exclusion_areas_for_layers( + const PrintObject &object, + const std::vector> &layer_z_ranges, + const bool interface_material) +{ + std::vector result(layer_z_ranges.size()); + if (layer_z_ranges.empty() || object.print() == nullptr) + return result; + + const Print &print = *object.print(); + const std::vector> regions_by_extruder = + get_bed_excluded_regions_by_extruder(print.config()); + if (regions_by_extruder.empty() || + std::all_of(regions_by_extruder.begin(), regions_by_extruder.end(), + [](const std::vector ®ions) { return regions.empty(); })) + return result; + + const std::vector filaments = support_exclusion_filaments(object, interface_material); + for (size_t idx = 0; idx < layer_z_ranges.size(); ++idx) { + const auto [z_min, z_max] = layer_z_ranges[idx]; + const int layer_id = object_layer_id_at_z(object, z_max); + const std::vector physical_extruders = bed_exclusion_physical_extruders( + print, filaments, regions_by_extruder.size(), layer_id); + result[idx] = to_polygons(active_bed_exclusion_footprints_for_object( + object, regions_by_extruder, physical_extruders, z_min, z_max, coord_t(SCALED_EPSILON))); + } + return result; +} + +void trim_support_layers_by_exclusion_volumes( + const PrintObject &object, + const SupportGeneratorLayersPtr &raft_layers, + const SupportGeneratorLayersPtr &bottom_contacts, + const SupportGeneratorLayersPtr &top_contacts, + const SupportGeneratorLayersPtr &intermediate_layers, + const SupportGeneratorLayersPtr &interface_layers, + const SupportGeneratorLayersPtr &base_interface_layers) +{ + SupportGeneratorLayersPtr layers; + layers.reserve(raft_layers.size() + bottom_contacts.size() + top_contacts.size() + + intermediate_layers.size() + interface_layers.size() + base_interface_layers.size()); + for (const SupportGeneratorLayersPtr *source : { + &raft_layers, &bottom_contacts, &top_contacts, &intermediate_layers, + &interface_layers, &base_interface_layers }) + append(layers, *source); + std::sort(layers.begin(), layers.end()); + layers.erase(std::unique(layers.begin(), layers.end()), layers.end()); + + for (const bool interface_material : { false, true }) { + SupportGeneratorLayersPtr selected; + std::vector> z_ranges; + for (SupportGeneratorLayer *layer : layers) { + if (layer != nullptr && support_layer_uses_interface_material(*layer) == interface_material) { + selected.emplace_back(layer); + z_ranges.emplace_back(layer->bottom_print_z(), layer->print_z); + } + } + + const std::vector excluded = + support_exclusion_areas_for_layers(object, z_ranges, interface_material); + for (size_t idx = 0; idx < selected.size(); ++idx) { + SupportGeneratorLayer &layer = *selected[idx]; + trim_polygons(layer.polygons, excluded[idx]); + if (layer.contact_polygons) + trim_polygons(*layer.contact_polygons, excluded[idx]); + if (layer.overhang_polygons) + trim_polygons(*layer.overhang_polygons, excluded[idx]); + if (layer.enforcer_polygons) + trim_polygons(*layer.enforcer_polygons, excluded[idx]); + } + } +} + // how much we extend support around the actual contact area //FIXME this should be dependent on the nozzle diameter! #define SUPPORT_MATERIAL_MARGIN 1.5 diff --git a/src/libslic3r/Support/SupportCommon.hpp b/src/libslic3r/Support/SupportCommon.hpp index 531daaa0a8..11f336ccd4 100644 --- a/src/libslic3r/Support/SupportCommon.hpp +++ b/src/libslic3r/Support/SupportCommon.hpp @@ -46,6 +46,32 @@ void tree_supports_generate_paths(ExtrusionEntitiesPtr &dst, const Polygons &pol void fill_expolygons_with_sheath_generate_paths( ExtrusionEntitiesPtr &dst, const Polygons &polygons, Fill *filler, float density, ExtrusionRole role, const Flow &flow, const SupportParameters& support_params, bool with_sheath, bool no_sort); +// Return every logical filament which may be selected for this support role. +// An explicit assignment has one result; "current filament" is intentionally +// print-wide because Orca resolves it later while ordering tools and wiping. +std::vector support_exclusion_filaments( + const PrintObject &object, + bool interface_material); + +// Build conservative, object-local exclusion masks for generated support. +// `interface_material` selects the support-interface filament; false selects +// the base support filament. Each pair describes the actual extrusion slab. +std::vector support_exclusion_areas_for_layers( + const PrintObject &object, + const std::vector> &layer_z_ranges, + bool interface_material); + +// Remove exclusion volumes from every support and raft polygon category before +// SupportLayer installation and toolpath generation. +void trim_support_layers_by_exclusion_volumes( + const PrintObject &object, + const SupportGeneratorLayersPtr &raft_layers, + const SupportGeneratorLayersPtr &bottom_contacts, + const SupportGeneratorLayersPtr &top_contacts, + const SupportGeneratorLayersPtr &intermediate_layers, + const SupportGeneratorLayersPtr &interface_layers, + const SupportGeneratorLayersPtr &base_interface_layers); + // returns sorted layers SupportGeneratorLayersPtr generate_support_layers( PrintObject &object, diff --git a/src/libslic3r/Support/SupportMaterial.cpp b/src/libslic3r/Support/SupportMaterial.cpp index a955eb5ca7..1aa7a2fe25 100644 --- a/src/libslic3r/Support/SupportMaterial.cpp +++ b/src/libslic3r/Support/SupportMaterial.cpp @@ -509,6 +509,10 @@ void PrintObjectSupportMaterial::generate(PrintObject &object) BOOST_LOG_TRIVIAL(info) << "Support generator - Creating layers"; + trim_support_layers_by_exclusion_volumes( + object, raft_layers, bottom_contacts, top_contacts, intermediate_layers, + interface_layers, base_interface_layers); + // For debugging purposes, one may want to show only some of the support extrusions. // raft_layers.clear(); // bottom_contacts.clear(); diff --git a/src/libslic3r/Support/TreeModelVolumes.cpp b/src/libslic3r/Support/TreeModelVolumes.cpp index 70c33aab0d..568d9ec191 100644 --- a/src/libslic3r/Support/TreeModelVolumes.cpp +++ b/src/libslic3r/Support/TreeModelVolumes.cpp @@ -136,22 +136,18 @@ TreeModelVolumes::TreeModelVolumes( } }); } - if (! additional_excluded_areas.empty()) { - tbb::parallel_for(tbb::blocked_range(0, m_anti_overhang.size()), - [&](const tbb::blocked_range &range) { - for (size_t layer_idx = range.begin(); layer_idx < range.end(); ++ layer_idx) { - if (layer_idx < coord_t(additional_excluded_areas.size())) - append(m_anti_overhang[layer_idx], additional_excluded_areas[layer_idx]); - // if (SUPPORT_TREE_AVOID_SUPPORT_BLOCKER) - // append(m_anti_overhang[layer_idx], storage.support.supportLayers[layer_idx].anti_overhang); - //FIXME block wipe tower - // if (storage.primeTower.enabled) - // append(m_anti_overhang[layer_idx], layer_idx == 0 ? storage.primeTower.outer_poly_first_layer : storage.primeTower.outer_poly); - m_anti_overhang[layer_idx] = union_(m_anti_overhang[layer_idx]); - } - }); - } #endif + + if (!additional_excluded_areas.empty()) { + m_anti_overhang.resize(std::max(m_anti_overhang.size(), additional_excluded_areas.size())); + tbb::parallel_for(tbb::blocked_range(0, additional_excluded_areas.size()), + [&](const tbb::blocked_range &range) { + for (size_t layer_idx = range.begin(); layer_idx < range.end(); ++layer_idx) { + append(m_anti_overhang[layer_idx], additional_excluded_areas[layer_idx]); + m_anti_overhang[layer_idx] = union_(m_anti_overhang[layer_idx]); + } + }); + } } void TreeModelVolumes::precalculate(const PrintObject& print_object, const coord_t max_layer, std::function throw_on_cancel) @@ -432,7 +428,8 @@ void TreeModelVolumes::calculateCollision(const coord_t radius, const LayerIndex if (calculate_placable) data_placeable.allocate(data.begin(), data.end()); - for (size_t outline_idx : layer_outline_indices) + for (size_t outline_pos = 0; outline_pos < layer_outline_indices.size(); ++outline_pos) { + const size_t outline_idx = layer_outline_indices[outline_pos]; if (const std::vector &outlines = m_layer_outlines[outline_idx].second; ! outlines.empty()) { const TreeSupportMeshGroupSettings &settings = m_layer_outlines[outline_idx].first; const coord_t layer_height = settings.layer_height; @@ -469,7 +466,7 @@ void TreeModelVolumes::calculateCollision(const coord_t radius, const LayerIndex }); // 2) Sum over top / bottom ranges. - const bool processing_last_mesh = outline_idx == layer_outline_indices.back(); + const bool processing_last_mesh = outline_pos + 1 == layer_outline_indices.size(); tbb::parallel_for(tbb::blocked_range(data.begin(), data.end()), [&collision_areas_offsetted, &outlines, &machine_border = m_machine_border, &anti_overhang = m_anti_overhang, radius, xy_distance, z_distance_bottom_layers, z_distance_top_layers, min_resolution = m_min_resolution, &data, processing_last_mesh, &throw_on_cancel] @@ -563,6 +560,7 @@ void TreeModelVolumes::calculateCollision(const coord_t radius, const LayerIndex // Calculating just the collision areas. } } + } #ifdef SLIC3R_TREESUPPORTS_PROGRESS { std::lock_guard critical_section(*m_critical_progress); diff --git a/src/libslic3r/Support/TreeSupport3D.cpp b/src/libslic3r/Support/TreeSupport3D.cpp index 3cd3f4110d..a1d95ad90f 100644 --- a/src/libslic3r/Support/TreeSupport3D.cpp +++ b/src/libslic3r/Support/TreeSupport3D.cpp @@ -3438,12 +3438,41 @@ static void generate_support_areas(Print &print, TreeSupport* tree_support, cons m_progress_offset = counter == 0 ? 0 : TREE_PROGRESS_TOTAL * (double(counter) * m_progress_multiplier); #endif // SLIC3R_TREESUPPORT_PROGRESS PrintObject &print_object = *print.get_object(processing.second.front()); + const size_t num_raft_layers_for_exclusions = config.raft_layers.size(); + std::vector> tree_layer_z_ranges; + tree_layer_z_ranges.reserve(num_raft_layers_for_exclusions + print_object.layer_count()); + coordf_t previous_z = 0.; + for (const coordf_t print_z : config.raft_layers) { + tree_layer_z_ranges.emplace_back(previous_z, print_z); + previous_z = print_z; + } + for (const Layer *layer : print_object.layers()) { + tree_layer_z_ranges.emplace_back(layer->print_z - layer->height, layer->print_z); + } + // A tree is one continuous structure while "current filament" may + // alternate between base and interface nozzles from layer to layer. + // Planning against both masks prevents a locally valid layer from + // forcing a branch through another possible nozzle's exclusion volume. + std::vector exclusion_areas = + support_exclusion_areas_for_layers(print_object, tree_layer_z_ranges, false); + const bool tree_uses_interface_material = !config.raft_layers.empty() || + print_object.config().support_interface_top_layers.value > 0 || + number_of_support_interface_bottom_layers(print_object.config()) > 0; + if (tree_uses_interface_material) { + const std::vector interface_exclusion_areas = + support_exclusion_areas_for_layers(print_object, tree_layer_z_ranges, true); + for (size_t layer_idx = 0; layer_idx < exclusion_areas.size(); ++layer_idx) { + append(exclusion_areas[layer_idx], interface_exclusion_areas[layer_idx]); + exclusion_areas[layer_idx] = union_(exclusion_areas[layer_idx]); + } + } + // Generator for model collision, avoidance and internal guide volumes. TreeModelVolumes volumes{ print_object, build_volume, config.maximum_move_distance, config.maximum_move_distance_slow, processing.second.front(), #ifdef SLIC3R_TREESUPPORTS_PROGRESS m_progress_multiplier, m_progress_offset, #endif // SLIC3R_TREESUPPORTS_PROGRESS - /* additional_excluded_areas */{} }; + exclusion_areas }; //FIXME generating overhangs just for the first mesh of the group. assert(processing.second.size() == 1); @@ -3591,6 +3620,9 @@ static void generate_support_areas(Print &print, TreeSupport* tree_support, cons // Produce the support G-code. SupportGeneratorLayersPtr raft_layers = generate_raft_base(print_object, support_params, print_object.slicing_parameters(), top_contacts, interface_layers, base_interface_layers, intermediate_layers, layer_storage); + trim_support_layers_by_exclusion_volumes( + print_object, raft_layers, bottom_contacts, top_contacts, intermediate_layers, + interface_layers, base_interface_layers); SupportGeneratorLayersPtr layers_sorted = generate_support_layers(print_object, raft_layers, bottom_contacts, top_contacts, intermediate_layers, interface_layers, base_interface_layers); // BBS: This is a hack to avoid the support being generated outside the bed area. See #4769. From 9d88932c8174c0716a8c8bb50dc523d6f29f2717 Mon Sep 17 00:00:00 2001 From: Harry Loud Date: Thu, 16 Jul 2026 16:35:11 +0100 Subject: [PATCH 17/38] Use neutral exclusion preview for single-nozzle printers --- src/slic3r/GUI/PartPlate.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/slic3r/GUI/PartPlate.cpp b/src/slic3r/GUI/PartPlate.cpp index eb8a3d7153..c45c8e6e4c 100644 --- a/src/slic3r/GUI/PartPlate.cpp +++ b/src/slic3r/GUI/PartPlate.cpp @@ -1236,6 +1236,11 @@ void PartPlate::update_exclusion_volume_preview_models() for (const std::vector &extruder_regions : regions_by_extruder) regions.insert(regions.end(), extruder_regions.begin(), extruder_regions.end()); const BedExcludeAreaMode mode = config->opt_enum("bed_exclude_area_mode"); + // A coloured border communicates which physical nozzle owns a footprint. + // With only one nozzle the exclusion applies to every filament, so using + // the first filament colour would incorrectly imply material ownership. + const bool show_nozzle_ownership = + regions_by_extruder.size() > 1 && mode != BedExcludeAreaMode::Shared; std::ostringstream grouped_key; grouped_key << exclusion_volume_preview_cache_key(regions) << "mode:" << int(mode) << ";groups:"; for (const std::vector &group : regions_by_extruder) @@ -1304,7 +1309,7 @@ void PartPlate::update_exclusion_volume_preview_models() Polygons preview_footprints; std::vector active_prisms; - if (mode != BedExcludeAreaMode::Shared) { + if (show_nozzle_ownership) { static const std::array fallback_colors = { ColorRGBA{ .18f, .52f, .95f, .92f }, ColorRGBA{ .95f, .35f, .22f, .92f }, ColorRGBA{ .25f, .72f, .38f, .92f }, ColorRGBA{ .72f, .34f, .88f, .92f }, From 8fcf9dd3c45178b5c865cf227e488871ccc6a34d Mon Sep 17 00:00:00 2001 From: Harry Loud Date: Thu, 16 Jul 2026 16:48:37 +0100 Subject: [PATCH 18/38] Keep extended exclusion regions out of legacy point data --- src/OrcaSlicer.cpp | 13 ++++++++--- src/libslic3r/Config.hpp | 23 ++++++++------------ src/libslic3r/GCode/TimelapsePosPicker.cpp | 11 +++++----- tests/libslic3r/test_bed_exclude_regions.cpp | 18 +++++++++++++++ 4 files changed, 43 insertions(+), 22 deletions(-) diff --git a/src/OrcaSlicer.cpp b/src/OrcaSlicer.cpp index 2d6fe873b7..5bbade3561 100644 --- a/src/OrcaSlicer.cpp +++ b/src/OrcaSlicer.cpp @@ -61,6 +61,7 @@ using namespace nlohmann; #include "libslic3r/ModelArrange.hpp" #include "libslic3r/Platform.hpp" #include "libslic3r/Print.hpp" +#include "libslic3r/PrintConfig.hpp" #include "libslic3r/SLAPrint.hpp" #include "libslic3r/TriangleMesh.hpp" #include "libslic3r/Format/AMF.hpp" @@ -118,6 +119,12 @@ using namespace Slic3r; #define MAX_CLONEABLE_SIZE 512 +static Pointfs legacy_bed_exclude_area_points(const DynamicPrintConfig &config) +{ + const ConfigOptionPoints *option = config.option("bed_exclude_area"); + return option != nullptr && !has_bed_exclusion_volume_syntax(*option) ? option->values : Pointfs{}; +} + std::map cli_errors = { {CLI_SUCCESS, "Success."}, {CLI_ENVIRONMENT_ERROR, "Failed setting up server environment."}, @@ -1803,7 +1810,7 @@ int CLI::run(int argc, char **argv) //use Pointfs insteadof Points old_printable_area = config.option("printable_area", true)->values; - old_exclude_area = config.option("bed_exclude_area", true)->values; + old_exclude_area = legacy_bed_exclude_area_points(config); if (old_printable_area.size() >= 4) { BoundingBoxf old_printable_bbox(old_printable_area); old_printable_width = static_cast(old_printable_bbox.size().x()); @@ -4062,7 +4069,7 @@ int CLI::run(int argc, char **argv) Slic3r::GUI::PartPlateList partplate_list(NULL, m_models.data(), printer_technology); //use Pointfs insteadof Points Pointfs current_printable_area = m_print_config.opt("printable_area")->values; - Pointfs current_exclude_area = m_print_config.opt("bed_exclude_area")->values; + Pointfs current_exclude_area = legacy_bed_exclude_area_points(m_print_config); std::vector current_extruder_areas; //update part plate's size double print_height = m_print_config.opt_float("printable_height"); @@ -4472,7 +4479,7 @@ int CLI::run(int argc, char **argv) printer_plate.printer_name = config_name; temp_printable_area = config.option("printable_area", true)->values; - temp_exclude_area = config.option("bed_exclude_area", true)->values; + temp_exclude_area = legacy_bed_exclude_area_points(config); temp_wrapping_area = config.option("wrapping_exclude_area", true)->values; temp_extruder_areas = config.option("extruder_printable_area", true)->values; temp_extruder_print_heights = config.option("extruder_printable_height", true)->values; diff --git a/src/libslic3r/Config.hpp b/src/libslic3r/Config.hpp index 67c237d430..4129b7838c 100644 --- a/src/libslic3r/Config.hpp +++ b/src/libslic3r/Config.hpp @@ -1611,24 +1611,19 @@ public: } const bool has_extended_bed_exclusion_syntax = str.find('|') != std::string::npos || (str.find("..") != std::string::npos && str.find(';') != std::string::npos); - if (has_extended_bed_exclusion_syntax && ! append) - m_serialized_override = str; + if (has_extended_bed_exclusion_syntax && append) + return false; - std::string points_str = str; if (has_extended_bed_exclusion_syntax) { - std::ostringstream points; - std::istringstream regions(str); - std::string region; - while (std::getline(regions, region, '|')) { - const size_t sep = region.find(';'); - if (points.tellp() > 0) - points << ","; - points << (sep == std::string::npos ? region : region.substr(sep + 1)); - } - points_str = points.str(); + m_serialized_override = str; + // Multiple independent polygons have no valid representation in + // the legacy flat point array. Keep the serialized definition as + // the sole source of truth so old consumers cannot mistake their + // concatenated vertices for one polygon. + return true; } - std::istringstream is(points_str); + std::istringstream is(str); std::string point_str; while (std::getline(is, point_str, ',')) { Vec2d point(Vec2d::Zero()); diff --git a/src/libslic3r/GCode/TimelapsePosPicker.cpp b/src/libslic3r/GCode/TimelapsePosPicker.cpp index 364624a88c..0ee2bd99a7 100644 --- a/src/libslic3r/GCode/TimelapsePosPicker.cpp +++ b/src/libslic3r/GCode/TimelapsePosPicker.cpp @@ -78,9 +78,10 @@ namespace Slic3r { m_plate_height = unscale_(bed_bbox.max.y()); m_plate_width = unscale_(bed_bbox.max.x()); - Polygon bed_exclude_area; - for (size_t idx = 0; idx < config.bed_exclude_area.values.size(); ++idx) - bed_exclude_area.points.emplace_back(coord_t(scale_(config.bed_exclude_area.values[idx].x())), coord_t(scale_(config.bed_exclude_area.values[idx].y()))); + // Timelapse positions are selected in the bed plane. Use the resolved + // bed-level footprints instead of the legacy flat point array, which + // cannot represent multiple or per-nozzle exclusion polygons. + const Polygons bed_exclude_areas = get_bed_excluded_area(config); Point base_wp_pt = print->get_fake_wipe_tower().pos.cast(); base_wp_pt = Point{ scale_(base_wp_pt.x()),scale_(base_wp_pt.y()) }; @@ -100,7 +101,7 @@ namespace Slic3r { wipe_tower_area = expand_object_projection(wipe_tower_area, m_print_seq == PrintSequence::ByObject); for (size_t idx = 0; idx < extruder_count; ++idx) { - ExPolygons printable_area = diff_ex(diff(m_bed_polygon, bed_exclude_area), { wipe_tower_area }); + ExPolygons printable_area = diff_ex(diff(Polygons{ m_bed_polygon }, bed_exclude_areas), { wipe_tower_area }); if (idx < config.extruder_printable_area.size()) { Polygon extruder_printable_area; for (size_t j = 0; j < config.extruder_printable_area.values[idx].size(); ++j) @@ -661,4 +662,4 @@ namespace Slic3r { return true; } -} \ No newline at end of file +} diff --git a/tests/libslic3r/test_bed_exclude_regions.cpp b/tests/libslic3r/test_bed_exclude_regions.cpp index ff61f404d4..d938a1a404 100644 --- a/tests/libslic3r/test_bed_exclude_regions.cpp +++ b/tests/libslic3r/test_bed_exclude_regions.cpp @@ -24,6 +24,24 @@ BoundingBox region_bounds(const BedExcludeRegion ®ion) } // namespace +TEST_CASE("Extended exclusion syntax does not populate the legacy point array", "[PrintConfig][BedExclude]") +{ + ConfigOptionPoints option; + + REQUIRE(option.deserialize("0..10;0x0,10x0,10x10,0x10|20x20,30x20,30x30,20x30")); + CHECK(option.values.empty()); + CHECK(option.serialize() == "0..10;0x0,10x0,10x10,0x10|20x20,30x20,30x30,20x30"); +} + +TEST_CASE("Legacy exclusion syntax retains its point representation", "[PrintConfig][BedExclude]") +{ + ConfigOptionPoints option; + + REQUIRE(option.deserialize("0x0,10x0,10x10,0x10")); + REQUIRE(option.values.size() == 4); + CHECK(option.serialize() == "0x0,10x0,10x10,0x10"); +} + TEST_CASE("Shared exclusion volumes resolve identically for every extruder", "[PrintConfig][BedExclude]") { DynamicPrintConfig config = two_extruder_config(); From 3d04d78f1104ccde2096b23e24f4a675d3193d7c Mon Sep 17 00:00:00 2001 From: Harry Loud Date: Thu, 16 Jul 2026 17:27:07 +0100 Subject: [PATCH 19/38] Remove exclusion volume tests --- tests/fff_print/test_print.cpp | 37 ------- tests/libslic3r/CMakeLists.txt | 1 - tests/libslic3r/test_bed_exclude_regions.cpp | 111 ------------------- 3 files changed, 149 deletions(-) delete mode 100644 tests/libslic3r/test_bed_exclude_regions.cpp diff --git a/tests/fff_print/test_print.cpp b/tests/fff_print/test_print.cpp index 9ef63dff02..6bff945fc3 100644 --- a/tests/fff_print/test_print.cpp +++ b/tests/fff_print/test_print.cpp @@ -119,23 +119,6 @@ size_t count_opt_key(const std::vector& warnings, const s [&](const StringObjectException& w) { return w.opt_key == key; }); } -DynamicPrintConfig dual_extruder_exclusion_config(FilamentMapMode map_mode, int mapped_extruder) -{ - DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); - config.set_num_extruders(2); - config.set_key_value("nozzle_diameter", new ConfigOptionFloats{ 0.4, 0.4 }); - config.set_key_value("extruder_offset", new ConfigOptionPoints{ Vec2d::Zero(), Vec2d(20.0, 0.0) }); - config.set_key_value("extruder_printable_height", new ConfigOptionFloatsNullable{ 256.0, 256.0 }); - config.set_key_value("bed_exclude_area_mode", new ConfigOptionEnum(BedExcludeAreaMode::PerExtruder)); - config.set_key_value("extruder_bed_exclude_area", new ConfigOptionStrings{ - "0..256;-100x-100,300x-100,300x300,-100x300", - "" - }); - config.set_key_value("filament_map_mode", new ConfigOptionEnum(map_mode)); - config.set_key_value("filament_map", new ConfigOptionInts{ mapped_extruder }); - return config; -} - // Make `default_acceleration` exceed the machine's extruding-acceleration limit. void trigger_acceleration_warning(DynamicPrintConfig& c) { @@ -162,26 +145,6 @@ void trigger_precise_wall_warning(DynamicPrintConfig& c) } // namespace -TEST_CASE("Print validation applies exclusion volumes to the relevant extruder", "[Print][BedExclude][MultiNozzle]") -{ - std::vector warnings; - - SECTION("manual mapping rejects the colliding extruder") { - const StringObjectException error = validate_cubes(dual_extruder_exclusion_config(fmmManual, 1), warnings); - CHECK(error.string.find("extruder 1") != std::string::npos); - } - - SECTION("manual mapping accepts a clear extruder") { - const StringObjectException error = validate_cubes(dual_extruder_exclusion_config(fmmManual, 2), warnings); - CHECK(error.string.empty()); - } - - SECTION("automatic mapping remains valid when at least one extruder is clear") { - const StringObjectException error = validate_cubes(dual_extruder_exclusion_config(fmmAutoForMatch, 1), warnings); - CHECK(error.string.empty()); - } -} - // --------------------------------------------------------------------------- // {first_object_name} filename placeholder // --------------------------------------------------------------------------- diff --git a/tests/libslic3r/CMakeLists.txt b/tests/libslic3r/CMakeLists.txt index 187bb8e019..2f859f46fe 100644 --- a/tests/libslic3r/CMakeLists.txt +++ b/tests/libslic3r/CMakeLists.txt @@ -9,7 +9,6 @@ add_executable(${_TEST_NAME}_tests test_arrange.cpp test_bambu_networking.cpp test_buildvolume.cpp - test_bed_exclude_regions.cpp test_calib.cpp test_clipper_offset.cpp test_clipper_utils.cpp diff --git a/tests/libslic3r/test_bed_exclude_regions.cpp b/tests/libslic3r/test_bed_exclude_regions.cpp deleted file mode 100644 index d938a1a404..0000000000 --- a/tests/libslic3r/test_bed_exclude_regions.cpp +++ /dev/null @@ -1,111 +0,0 @@ -#include - -#include "libslic3r/PrintConfig.hpp" - -using namespace Slic3r; - -namespace { - -DynamicPrintConfig two_extruder_config() -{ - DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); - config.set_key_value("nozzle_diameter", new ConfigOptionFloats{ 0.4, 0.4 }); - config.set_key_value("extruder_offset", new ConfigOptionPoints{ Vec2d(0.0, 0.0), Vec2d(20.0, 5.0) }); - config.set_key_value("master_extruder_id", new ConfigOptionInt(1)); - config.set_key_value("printable_height", new ConfigOptionFloat(200.0)); - config.set_deserialize_strict("bed_exclude_area", "10..30;0x0,10x0,10x10,0x10"); - return config; -} - -BoundingBox region_bounds(const BedExcludeRegion ®ion) -{ - return get_extents(region.polygon); -} - -} // namespace - -TEST_CASE("Extended exclusion syntax does not populate the legacy point array", "[PrintConfig][BedExclude]") -{ - ConfigOptionPoints option; - - REQUIRE(option.deserialize("0..10;0x0,10x0,10x10,0x10|20x20,30x20,30x30,20x30")); - CHECK(option.values.empty()); - CHECK(option.serialize() == "0..10;0x0,10x0,10x10,0x10|20x20,30x20,30x30,20x30"); -} - -TEST_CASE("Legacy exclusion syntax retains its point representation", "[PrintConfig][BedExclude]") -{ - ConfigOptionPoints option; - - REQUIRE(option.deserialize("0x0,10x0,10x10,0x10")); - REQUIRE(option.values.size() == 4); - CHECK(option.serialize() == "0x0,10x0,10x10,0x10"); -} - -TEST_CASE("Shared exclusion volumes resolve identically for every extruder", "[PrintConfig][BedExclude]") -{ - DynamicPrintConfig config = two_extruder_config(); - config.set_key_value("bed_exclude_area_mode", new ConfigOptionEnum(BedExcludeAreaMode::Shared)); - - const auto groups = get_bed_excluded_regions_by_extruder(config); - REQUIRE(groups.size() == 2); - REQUIRE(groups[0].size() == 1); - REQUIRE(groups[1].size() == 1); - CHECK(groups[0][0].polygon.points == groups[1][0].polygon.points); - CHECK(groups[0][0].z_min == Catch::Approx(10.0)); - CHECK(groups[0][0].z_max == Catch::Approx(30.0)); - - // The global compatibility view returns a shared definition only once. - CHECK(get_bed_excluded_regions(config).size() == 1); -} - -TEST_CASE("Toolhead-relative exclusion volumes follow nozzle offset deltas", "[PrintConfig][BedExclude]") -{ - DynamicPrintConfig config = two_extruder_config(); - config.set_key_value("bed_exclude_area_mode", new ConfigOptionEnum(BedExcludeAreaMode::ToolheadOffset)); - - const auto groups = get_bed_excluded_regions_by_extruder(config); - REQUIRE(groups.size() == 2); - REQUIRE(groups[0].size() == 1); - REQUIRE(groups[1].size() == 1); - - const BoundingBox reference = region_bounds(groups[0][0]); - const BoundingBox offset = region_bounds(groups[1][0]); - CHECK(unscale(offset.min.x() - reference.min.x()) == Catch::Approx(20.0)); - CHECK(unscale(offset.min.y() - reference.min.y()) == Catch::Approx(5.0)); - CHECK(groups[1][0].z_min == Catch::Approx(groups[0][0].z_min)); - CHECK(groups[1][0].z_max == Catch::Approx(groups[0][0].z_max)); -} - -TEST_CASE("Individual exclusion volumes are authoritative per extruder", "[PrintConfig][BedExclude]") -{ - DynamicPrintConfig config = two_extruder_config(); - config.set_key_value("bed_exclude_area_mode", new ConfigOptionEnum(BedExcludeAreaMode::PerExtruder)); - config.set_key_value("extruder_bed_exclude_area", new ConfigOptionStrings{ - "0..25;0x0,8x0,8x8,0x8|40..60;20x20,30x20,30x30,20x30", - "" - }); - - const auto groups = get_bed_excluded_regions_by_extruder(config); - REQUIRE(groups.size() == 2); - CHECK(groups[0].size() == 2); - CHECK(groups[1].empty()); - CHECK(groups[0][0].z_min == Catch::Approx(0.0)); - CHECK(groups[0][0].z_max == Catch::Approx(25.0)); - CHECK(groups[0][1].z_min == Catch::Approx(40.0)); - CHECK(groups[0][1].z_max == Catch::Approx(60.0)); -} - -TEST_CASE("Offset mode honours a non-zero reference extruder", "[PrintConfig][BedExclude]") -{ - DynamicPrintConfig config = two_extruder_config(); - config.set_key_value("master_extruder_id", new ConfigOptionInt(2)); - config.set_key_value("bed_exclude_area_mode", new ConfigOptionEnum(BedExcludeAreaMode::ToolheadOffset)); - - const auto groups = get_bed_excluded_regions_by_extruder(config); - REQUIRE(groups.size() == 2); - const BoundingBox first = region_bounds(groups[0][0]); - const BoundingBox reference = region_bounds(groups[1][0]); - CHECK(unscale(first.min.x() - reference.min.x()) == Catch::Approx(-20.0)); - CHECK(unscale(first.min.y() - reference.min.y()) == Catch::Approx(-5.0)); -} From c00909e68760e4b04b435f063f7681c2f08f78e5 Mon Sep 17 00:00:00 2001 From: Harry Loud Date: Tue, 1 Sep 2026 18:23:25 +0100 Subject: [PATCH 20/38] Add comprehensive exclusion volume tests --- tests/fff_print/CMakeLists.txt | 1 + tests/fff_print/test_exclusion_volumes.cpp | 652 +++++++++++++++++++++ tests/fff_print/test_print.cpp | 89 +++ tests/libslic3r/CMakeLists.txt | 1 + tests/libslic3r/test_3mf.cpp | 69 +++ tests/libslic3r/test_arrange.cpp | 98 ++++ tests/libslic3r/test_exclusion_volumes.cpp | 296 ++++++++++ 7 files changed, 1206 insertions(+) create mode 100644 tests/fff_print/test_exclusion_volumes.cpp create mode 100644 tests/libslic3r/test_exclusion_volumes.cpp diff --git a/tests/fff_print/CMakeLists.txt b/tests/fff_print/CMakeLists.txt index 3247bfda66..8bafd20b7c 100644 --- a/tests/fff_print/CMakeLists.txt +++ b/tests/fff_print/CMakeLists.txt @@ -6,6 +6,7 @@ add_executable(${_TEST_NAME}_tests test_cooling.cpp test_extrusion_entity.cpp test_extrusion_processor.cpp + test_exclusion_volumes.cpp test_fill.cpp test_flow.cpp test_gcode_timing.cpp diff --git a/tests/fff_print/test_exclusion_volumes.cpp b/tests/fff_print/test_exclusion_volumes.cpp new file mode 100644 index 0000000000..981eeea6c4 --- /dev/null +++ b/tests/fff_print/test_exclusion_volumes.cpp @@ -0,0 +1,652 @@ +#include + +#include "libslic3r/GCode/ExclusionVolumePathCheck.hpp" +#include "libslic3r/GCode/ExclusionVolumeTravelAvoidance.hpp" +#include "libslic3r/GCode/GCodeProcessor.hpp" +#include "libslic3r/ClipperUtils.hpp" +#include "libslic3r/Print.hpp" +#include "libslic3r/PrintConfig.hpp" +#include "libslic3r/Support/SupportCommon.hpp" +#include "libslic3r/Support/SupportLayer.hpp" + +#include "test_helpers.hpp" +#include "test_utils.hpp" + +#include +#include +#include +#include +#include + +using namespace Slic3r; +using Catch::Matchers::WithinAbs; + +namespace { + +DynamicPrintConfig exclusion_config( + BedExcludeAreaMode mode = BedExcludeAreaMode::Shared, + const std::string &shared = "0..10;40x40,60x40,60x60,40x60", + const std::vector &per_extruder = {}) +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + const size_t extruder_count = std::max(1, per_extruder.size()); + config.set_num_extruders(extruder_count); + config.set_key_value("nozzle_diameter", new ConfigOptionFloats(extruder_count, 0.4)); + config.set_key_value("extruder_offset", new ConfigOptionPoints(extruder_count, Vec2d::Zero())); + config.set_key_value("extruder_printable_height", new ConfigOptionFloatsNullable(extruder_count, 100.0)); + config.set_key_value("printable_height", new ConfigOptionFloat(100.0)); + config.set_key_value("printable_area", new ConfigOptionPoints{ + Vec2d(0.0, 0.0), Vec2d(100.0, 0.0), Vec2d(100.0, 100.0), Vec2d(0.0, 100.0), + }); + config.set_key_value("bed_exclude_area_mode", new ConfigOptionEnum(mode)); + config.set_deserialize_strict("bed_exclude_area", shared); + if (!per_extruder.empty()) + config.set_key_value("extruder_bed_exclude_area", new ConfigOptionStrings(per_extruder)); + return config; +} + +FullPrintConfig static_config(const DynamicPrintConfig &dynamic) +{ + FullPrintConfig config; + // full_print_config() also contains GUI/profile-only keys which are not + // members of the static slicing config used by these lower-level classes. + config.apply(dynamic, true); + return config; +} + +Polyline travel(std::initializer_list points) +{ + Points scaled_points; + scaled_points.reserve(points.size()); + for (const Vec2d &point : points) + scaled_points.emplace_back(Point::new_scale(point)); + return Polyline(std::move(scaled_points)); +} + +Vec2d to_mm(const Point &point) +{ + return point.cast() * SCALING_FACTOR; +} + +struct Rect +{ + double min_x; + double min_y; + double max_x; + double max_y; +}; + +bool point_inside_open_rect(const Vec2d &point, const Rect &rect) +{ + return point.x() > rect.min_x && point.x() < rect.max_x && + point.y() > rect.min_y && point.y() < rect.max_y; +} + +// Independent Liang-Barsky-style test oracle for the simple rectangular +// obstacles used here. This deliberately does not call the production path +// checker, so matching bugs in the checker and router cannot hide each other. +bool segment_enters_open_rect(const Vec2d &from, const Vec2d &to, const Rect &rect) +{ + if (point_inside_open_rect(from, rect) || point_inside_open_rect(to, rect)) + return true; + + double t_min = 0.0; + double t_max = 1.0; + const Vec2d delta = to - from; + const auto clip_axis = [&](double origin, double direction, double min_value, double max_value, + double &lower, double &upper) { + if (std::abs(direction) < 1e-12) + return origin > min_value && origin < max_value; + double first = (min_value - origin) / direction; + double second = (max_value - origin) / direction; + if (first > second) + std::swap(first, second); + lower = std::max(lower, first); + upper = std::min(upper, second); + return lower < upper; + }; + + if (!clip_axis(from.x(), delta.x(), rect.min_x, rect.max_x, t_min, t_max)) + return false; + if (!clip_axis(from.y(), delta.y(), rect.min_y, rect.max_y, t_min, t_max)) + return false; + if (t_min >= t_max) + return false; + + const double midpoint_t = 0.5 * (std::max(0.0, t_min) + std::min(1.0, t_max)); + return midpoint_t >= 0.0 && midpoint_t <= 1.0 && + point_inside_open_rect(from + midpoint_t * delta, rect); +} + +void check_path_avoids_rect(const Polyline &path, const Rect &rect) +{ + REQUIRE(path.points.size() >= 2); + for (size_t idx = 1; idx < path.points.size(); ++idx) + CHECK_FALSE(segment_enters_open_rect(to_mm(path.points[idx - 1]), to_mm(path.points[idx]), rect)); +} + +ExclusionVolumePathChecker configured_checker(const FullPrintConfig &config) +{ + ExclusionVolumePathChecker checker; + checker.configure(config); + return checker; +} + +void check_motion( + ExclusionVolumePathChecker &checker, + const Vec3d &from, + const Vec3d &to, + int extruder_id = 0, + ExclusionVolumeMotionType type = ExclusionVolumeMotionType::Travel, + bool start_xy_known = true, + bool end_xy_known = true, + bool start_z_known = true, + bool end_z_known = true, + unsigned int gcode_id = 17, + size_t move_id = 23) +{ + checker.check_motion( + from, to, start_xy_known, end_xy_known, start_z_known, end_z_known, + extruder_id, type, 7, gcode_id, move_id); +} + +struct ProcessorExclusionResult +{ + bool checked {false}; + bool conflict {false}; + bool travel_conflict {false}; + bool extrusion_conflict {false}; + int conflict_extruder_id {-1}; +}; + +class ScopedBblPrinterMode +{ +public: + explicit ScopedBblPrinterMode(bool enabled) + : m_previous(GCodeProcessor::s_IsBBLPrinter) + { + GCodeProcessor::s_IsBBLPrinter = enabled; + } + + ~ScopedBblPrinterMode() { GCodeProcessor::s_IsBBLPrinter = m_previous; } + +private: + bool m_previous; +}; + +ProcessorExclusionResult run_processor(const FullPrintConfig &config, const std::string &gcode) +{ + ScopedTemporaryFile file(".gcode"); + { + std::ofstream output(file.string()); + output << gcode; + } + + // The processor exposes this mode as shared state. Restore it after each + // invocation so these tests remain independent of Catch2 execution order. + ScopedBblPrinterMode printer_mode(false); + GCodeProcessor processor; + processor.apply_config(config); + processor.configure_exclusion_volume_path_check(config); + processor.process_file(file.string()); + const GCodeProcessorResult &result = processor.get_result(); + return { + result.exclusion_volume_path_checked, + result.exclusion_volume_path_conflict, + result.exclusion_volume_travel_conflict, + result.exclusion_volume_extrusion_conflict, + result.exclusion_volume_conflict_extruder_id, + }; +} + +Polygon rectangle(double min_x, double min_y, double max_x, double max_y) +{ + Polygon polygon({ + Point::new_scale(min_x, min_y), + Point::new_scale(max_x, min_y), + Point::new_scale(max_x, max_y), + Point::new_scale(min_x, max_y), + }); + polygon.make_counter_clockwise(); + return polygon; +} + +bool polygons_cover(const Polygons &polygons, double x, double y) +{ + const Point point = Point::new_scale(x, y); + const ExPolygons expolygons = union_ex(polygons); + return std::any_of(expolygons.begin(), expolygons.end(), + [&point](const ExPolygon &polygon) { return polygon.contains(point); }); +} + +struct BrimRun +{ + double total_length {0.0}; + bool intersects_test_region {false}; +}; + +BrimRun generate_brim(const std::string &exclusion_definition) +{ + DynamicPrintConfig config = exclusion_config(BedExcludeAreaMode::Shared, exclusion_definition); + config.set_deserialize_strict({ + {"skirt_loops", "0"}, + {"brim_type", "outer_only"}, + {"brim_width", "10"}, + {"initial_layer_line_width", "0.5"}, + }); + + TriangleMesh mesh = make_cube(20.0, 20.0, 20.0); + mesh.translate(40.0f, 40.0f, 0.0f); + Print print; + Model model; + Test::init_print(std::vector{std::move(mesh)}, print, model, config, nullptr, false); + print.process(); + + Polylines paths; + for (const Print::SkirtBrimGroup &group : print.skirt_brim_groups()) + for (const Print::SkirtBrimGroup::Brim &brim : group.brims) { + Polylines current = brim.brim.as_polylines(); + paths.insert(paths.end(), std::make_move_iterator(current.begin()), std::make_move_iterator(current.end())); + } + + BrimRun result; + for (const Polyline &path : paths) + result.total_length += path.length(); + result.intersects_test_region = + !intersection_pl(paths, Polygons{rectangle(32.0, 35.0, 38.0, 65.0)}).empty(); + return result; +} + +DynamicPrintConfig support_config(int support_filament, int interface_filament) +{ + DynamicPrintConfig config = exclusion_config( + BedExcludeAreaMode::PerExtruder, "", + {"0..10;4x4,12x4,12x12,4x12", "0..10;22x4,30x4,30x12,22x12"}); + // PrintObject clamps support role ids against the number of logical + // filaments, represented by filament_diameter in the static config. + config.set_key_value("filament_diameter", new ConfigOptionFloats{1.75, 1.75}); + config.set_key_value("filament_map_mode", new ConfigOptionEnum(fmmManual)); + config.set_key_value("filament_map", new ConfigOptionInts{1, 2}); + config.set_key_value("support_filament", new ConfigOptionInt(support_filament)); + config.set_key_value("support_interface_filament", new ConfigOptionInt(interface_filament)); + return config; +} + +struct SupportPrintFixture +{ + Model model; + Print print; + + explicit SupportPrintFixture(const DynamicPrintConfig &config) + { + ModelObject *object = model.add_object(); + ModelVolume *first = object->add_volume(make_cube(20.0, 20.0, 20.0)); + ModelVolume *second = object->add_volume(make_cube(20.0, 20.0, 20.0)); + first->config.set("extruder", 1); + second->config.set("extruder", 2); + // Pin the role assignments on the object as well as the process + // config. This fixture intentionally exercises support exclusion + // selection, not the separate preset-remapping subsystem. + object->config.set("support_filament", config.opt_int("support_filament")); + object->config.set("support_interface_filament", config.opt_int("support_interface_filament")); + object->add_instance(); + object->ensure_on_bed(); + print.apply(model, config); + } + + PrintObject &object() { return *print.objects_mutable().front(); } +}; + +} // namespace + +TEST_CASE("Path checker ignores clear motions and motions outside the active Z slab", "[ExclusionVolume][GCode]") +{ + const FullPrintConfig config = static_config(exclusion_config()); + + SECTION("clear XY") { + auto checker = configured_checker(config); + check_motion(checker, Vec3d(10.0, 10.0, 5.0), Vec3d(20.0, 20.0, 5.0)); + CHECK_FALSE(checker.result().has_any_conflict); + } + + SECTION("above volume") { + auto checker = configured_checker(config); + check_motion(checker, Vec3d(20.0, 50.0, 20.0), Vec3d(80.0, 50.0, 20.0)); + CHECK_FALSE(checker.result().has_any_conflict); + } + + SECTION("below volume") { + auto checker = configured_checker(config); + check_motion(checker, Vec3d(20.0, 50.0, -5.0), Vec3d(80.0, 50.0, -5.0)); + CHECK_FALSE(checker.result().has_any_conflict); + } +} + +TEST_CASE("Path checker detects crossing inside and boundary motions", "[ExclusionVolume][GCode]") +{ + const FullPrintConfig config = static_config(exclusion_config()); + const auto [from, to] = GENERATE(table({ + {Vec3d(20.0, 50.0, 5.0), Vec3d(80.0, 50.0, 5.0)}, + {Vec3d(45.0, 45.0, 5.0), Vec3d(55.0, 55.0, 5.0)}, + {Vec3d(20.0, 40.0, 5.0), Vec3d(80.0, 40.0, 5.0)}, + {Vec3d(50.0, 20.0, -5.0), Vec3d(50.0, 80.0, 15.0)}, + })); + + auto checker = configured_checker(config); + check_motion(checker, from, to); + CHECK(checker.result().has_any_conflict); + REQUIRE(checker.result().first_hit.has_value()); + CHECK(checker.result().first_hit->extruder_id == 0); +} + +TEST_CASE("Path checker records motion classification and stable first-hit metadata", "[ExclusionVolume][GCode]") +{ + const auto [type, travel_hit, extrusion_hit, other_hit] = GENERATE(table({ + {ExclusionVolumeMotionType::Travel, true, false, false}, + {ExclusionVolumeMotionType::Extrude, false, true, false}, + {ExclusionVolumeMotionType::Other, false, false, true }, + })); + + auto checker = configured_checker(static_config(exclusion_config())); + check_motion(checker, Vec3d(20.0, 50.0, 5.0), Vec3d(80.0, 50.0, 5.0), 0, type, + true, true, true, true, 101, 202); + check_motion(checker, Vec3d(20.0, 50.0, 5.0), Vec3d(80.0, 50.0, 5.0), 0, type, + true, true, true, true, 303, 404); + + const ExclusionVolumePathCheckResult &result = checker.result(); + CHECK(result.has_travel_conflict == travel_hit); + CHECK(result.has_extrusion_conflict == extrusion_hit); + CHECK(result.has_other_motion_conflict == other_hit); + REQUIRE(result.first_hit.has_value()); + CHECK(result.first_hit->gcode_id == 101); + CHECK(result.first_hit->move_id == 202); + CHECK(result.first_hit->source_move_type == 7); +} + +TEST_CASE("Path checker handles unknown coordinates conservatively without inventing XY", "[ExclusionVolume][GCode]") +{ + const FullPrintConfig config = static_config(exclusion_config()); + + SECTION("unknown XY start is ignored") { + auto checker = configured_checker(config); + check_motion(checker, Vec3d(0.0, 0.0, 5.0), Vec3d(80.0, 50.0, 5.0), 0, + ExclusionVolumeMotionType::Travel, false, true); + CHECK_FALSE(checker.result().has_any_conflict); + } + + SECTION("unknown Z checks every height and marks the result") { + auto checker = configured_checker(config); + check_motion(checker, Vec3d(20.0, 50.0, 100.0), Vec3d(80.0, 50.0, 100.0), 0, + ExclusionVolumeMotionType::Travel, true, true, false, false); + REQUIRE(checker.result().first_hit.has_value()); + CHECK(checker.result().first_hit->used_unknown_z); + } +} + +TEST_CASE("Path checker selects the active nozzle and applies its XY offset", "[ExclusionVolume][GCode][MultiNozzle]") +{ + DynamicPrintConfig dynamic = exclusion_config( + BedExcludeAreaMode::PerExtruder, "", {"", "0..10;40x40,60x40,60x60,40x60"}); + dynamic.set_key_value("extruder_offset", new ConfigOptionPoints{Vec2d::Zero(), Vec2d(20.0, 0.0)}); + const FullPrintConfig config = static_config(dynamic); + + SECTION("unrelated nozzle remains clear") { + auto checker = configured_checker(config); + check_motion(checker, Vec3d(20.0, 50.0, 5.0), Vec3d(80.0, 50.0, 5.0), 0); + CHECK_FALSE(checker.result().has_any_conflict); + } + + SECTION("active nozzle offset converts emitted coordinates into model space") { + auto checker = configured_checker(config); + check_motion(checker, Vec3d(0.0, 50.0, 5.0), Vec3d(50.0, 50.0, 5.0), 1); + REQUIRE(checker.result().first_hit.has_value()); + CHECK(checker.result().first_hit->extruder_id == 1); + CHECK_THAT(checker.result().first_hit->from.x(), WithinAbs(20.0, 1e-9)); + } + + SECTION("unknown active nozzle checks all physical nozzles") { + auto checker = configured_checker(config); + check_motion(checker, Vec3d(0.0, 50.0, 5.0), Vec3d(50.0, 50.0, 5.0), -1); + REQUIRE(checker.result().first_hit.has_value()); + CHECK(checker.result().first_hit->extruder_id == 1); + } +} + +TEST_CASE("Travel router leaves clear and vertically separated paths unchanged", "[ExclusionVolume][TravelRouting]") +{ + ExclusionVolumeTravelAvoidance router; + router.init(static_config(exclusion_config()), Vec3d::Zero()); + + const Polyline clear = travel({Vec2d(10.0, 10.0), Vec2d(90.0, 10.0)}); + auto result = router.route(clear, 5.0, 5.0, 0); + CHECK(result.status == ExclusionVolumeTravelAvoidance::Status::Unchanged); + CHECK(result.detail == ExclusionVolumeTravelAvoidance::Detail::NoIntersection); + CHECK(result.path.points == clear.points); + + const Polyline crossing = travel({Vec2d(20.0, 50.0), Vec2d(80.0, 50.0)}); + result = router.route(crossing, 20.0, 20.0, 0); + CHECK(result.status == ExclusionVolumeTravelAvoidance::Status::Unchanged); + CHECK(result.detail == ExclusionVolumeTravelAvoidance::Detail::NoActiveObstacles); +} + +TEST_CASE("Travel router produces a safe in-bed detour around an active volume", "[ExclusionVolume][TravelRouting]") +{ + ExclusionVolumeTravelAvoidance router; + router.init(static_config(exclusion_config()), Vec3d::Zero()); + const Polyline direct = travel({Vec2d(20.0, 50.0), Vec2d(80.0, 50.0)}); + + const auto result = router.route(direct, 5.0, 5.0, 0); + REQUIRE(result.status == ExclusionVolumeTravelAvoidance::Status::Rerouted); + REQUIRE(result.path.points.size() > 2); + CHECK(result.path.points.front() == direct.points.front()); + CHECK(result.path.points.back() == direct.points.back()); + check_path_avoids_rect(result.path, Rect{40.0, 40.0, 60.0, 60.0}); + for (const Point &point : result.path.points) { + const Vec2d position = to_mm(point); + CHECK(position.x() >= 0.0); + CHECK(position.x() <= 100.0); + CHECK(position.y() >= 0.0); + CHECK(position.y() <= 100.0); + } +} + +TEST_CASE("Travel router activates volumes touched by a sloped Z move", "[ExclusionVolume][TravelRouting]") +{ + ExclusionVolumeTravelAvoidance router; + router.init(static_config(exclusion_config()), Vec3d::Zero()); + const Polyline direct = travel({Vec2d(20.0, 50.0), Vec2d(80.0, 50.0)}); + + const auto result = router.route(direct, -5.0, 15.0, 0); + REQUIRE(result.status == ExclusionVolumeTravelAvoidance::Status::Rerouted); + check_path_avoids_rect(result.path, Rect{40.0, 40.0, 60.0, 60.0}); +} + +TEST_CASE("Travel router reports unsafe endpoints unknown tools and blocked beds", "[ExclusionVolume][TravelRouting]") +{ + SECTION("endpoint inside") { + ExclusionVolumeTravelAvoidance router; + router.init(static_config(exclusion_config()), Vec3d::Zero()); + const auto result = router.route(travel({Vec2d(50.0, 50.0), Vec2d(80.0, 50.0)}), 5.0, 5.0, 0); + CHECK(result.status == ExclusionVolumeTravelAvoidance::Status::EndpointInside); + CHECK(result.detail == ExclusionVolumeTravelAvoidance::Detail::EndpointInside); + } + + SECTION("unknown tool") { + ExclusionVolumeTravelAvoidance router; + router.init(static_config(exclusion_config()), Vec3d::Zero()); + const auto result = router.route(travel({Vec2d(20.0, 50.0), Vec2d(80.0, 50.0)}), 5.0, 5.0, -1); + CHECK(result.status == ExclusionVolumeTravelAvoidance::Status::Failed); + CHECK(result.detail == ExclusionVolumeTravelAvoidance::Detail::UnknownExtruder); + } + + SECTION("obstacle separates the bed") { + ExclusionVolumeTravelAvoidance router; + router.init(static_config(exclusion_config( + BedExcludeAreaMode::Shared, "0..10;45x0,55x0,55x100,45x100")), Vec3d::Zero()); + const auto result = router.route(travel({Vec2d(20.0, 50.0), Vec2d(80.0, 50.0)}), 5.0, 5.0, 0); + CHECK(result.status == ExclusionVolumeTravelAvoidance::Status::Failed); + } +} + +TEST_CASE("Travel router uses only the active nozzle exclusion set", "[ExclusionVolume][TravelRouting][MultiNozzle]") +{ + const FullPrintConfig config = static_config(exclusion_config( + BedExcludeAreaMode::PerExtruder, "", {"0..10;40x40,60x40,60x60,40x60", ""})); + ExclusionVolumeTravelAvoidance router; + router.init(config, Vec3d::Zero()); + const Polyline direct = travel({Vec2d(20.0, 50.0), Vec2d(80.0, 50.0)}); + + CHECK(router.route(direct, 5.0, 5.0, 0).status == ExclusionVolumeTravelAvoidance::Status::Rerouted); + const auto clear = router.route(direct, 5.0, 5.0, 1); + CHECK(clear.status == ExclusionVolumeTravelAvoidance::Status::Unchanged); + CHECK(clear.detail == ExclusionVolumeTravelAvoidance::Detail::NoActiveObstacles); +} + +TEST_CASE("G-code processor ignores the artificial first XY origin and checks subsequent travel", "[ExclusionVolume][GCodeProcessor]") +{ + const FullPrintConfig config = static_config(exclusion_config()); + + SECTION("first explicit position has no invented start") { + const ProcessorExclusionResult result = run_processor(config, "G90\nG1 X80 Y50 Z5 F6000\n"); + CHECK(result.checked); + CHECK_FALSE(result.conflict); + } + + SECTION("next motion starts at the established position") { + const ProcessorExclusionResult result = run_processor(config, "G90\nG1 X80 Y50 Z5 F6000\nG1 X20 Y50\n"); + CHECK(result.conflict); + CHECK(result.travel_conflict); + } +} + +TEST_CASE("G-code processor tracks absolute relative and reset coordinate state", "[ExclusionVolume][GCodeProcessor]") +{ + const FullPrintConfig config = static_config(exclusion_config()); + + SECTION("relative move crosses the volume") { + const ProcessorExclusionResult result = run_processor( + config, "G90\nG1 X20 Y50 Z5\nG91\nG1 X60 Y0\n"); + CHECK(result.conflict); + } + + SECTION("G92 preserves a known transformed coordinate frame") { + const ProcessorExclusionResult result = run_processor( + config, "G90\nG1 X20 Y50 Z5\nG92 X0 Y0\nG1 X60 Y0\n"); + CHECK(result.conflict); + } + + SECTION("homing does not create a synthetic checked move") { + const ProcessorExclusionResult result = run_processor(config, "G28\nG1 X80 Y50 Z5\n"); + CHECK_FALSE(result.conflict); + } +} + +TEST_CASE("G-code processor classifies extrusion conflicts", "[ExclusionVolume][GCodeProcessor]") +{ + const FullPrintConfig config = static_config(exclusion_config()); + const ProcessorExclusionResult result = run_processor( + config, "G90\nM83\nG1 X20 Y50 Z5\nG1 X80 Y50 E1\n"); + + CHECK(result.conflict); + CHECK(result.extrusion_conflict); + CHECK_FALSE(result.travel_conflict); +} + +TEST_CASE("G-code processor changes the active physical nozzle at tool selection", "[ExclusionVolume][GCodeProcessor][MultiNozzle]") +{ + const FullPrintConfig config = static_config(exclusion_config( + BedExcludeAreaMode::PerExtruder, "", {"", "0..10;40x40,60x40,60x60,40x60"})); + + const ProcessorExclusionResult first_tool = run_processor(config, "G90\nT0\nG1 X20 Y50 Z5\nG1 X80 Y50\n"); + CHECK_FALSE(first_tool.conflict); + + const ProcessorExclusionResult second_tool = run_processor(config, "G90\nT1\nG1 X20 Y50 Z5\nG1 X80 Y50\n"); + CHECK(second_tool.conflict); + CHECK(second_tool.conflict_extruder_id == 1); +} + +TEST_CASE("Brim paths are clipped only by exclusions active on the first layer", "[ExclusionVolume][Brim]") +{ + const BrimRun active = generate_brim("0..1;32x35,38x35,38x65,32x65"); + const BrimRun raised = generate_brim("10..20;32x35,38x35,38x65,32x65"); + + REQUIRE(active.total_length > 0.0); + REQUIRE(raised.total_length > 0.0); + CHECK_FALSE(active.intersects_test_region); + CHECK(raised.intersects_test_region); + CHECK(active.total_length < raised.total_length); +} + +TEST_CASE("Support exclusion masks follow explicit and current-filament roles", "[ExclusionVolume][Support][MultiNozzle]") +{ + SECTION("explicit support roles select one physical nozzle each") { + SupportPrintFixture fixture(support_config(1, 2)); + CHECK(support_exclusion_filaments(fixture.object(), false) == std::vector{0}); + CHECK(support_exclusion_filaments(fixture.object(), true) == std::vector{1}); + + const auto base_masks = support_exclusion_areas_for_layers(fixture.object(), {{0.0, 1.0}}, false); + const auto interface_masks = support_exclusion_areas_for_layers(fixture.object(), {{0.0, 1.0}}, true); + REQUIRE(base_masks.size() == 1); + REQUIRE(interface_masks.size() == 1); + // PrintObject support geometry is centred around the object's local + // origin; the plate-space regions above are shifted by (10, 10). + CHECK(polygons_cover(base_masks.front(), -4.0, -4.0)); + CHECK_FALSE(polygons_cover(base_masks.front(), 14.0, -4.0)); + CHECK_FALSE(polygons_cover(interface_masks.front(), -4.0, -4.0)); + CHECK(polygons_cover(interface_masks.front(), 14.0, -4.0)); + } + + SECTION("current filament remains conservative across every used nozzle") { + SupportPrintFixture fixture(support_config(0, 2)); + std::vector filaments = support_exclusion_filaments(fixture.object(), false); + std::sort(filaments.begin(), filaments.end()); + CHECK(filaments == std::vector{0, 1}); + + const auto masks = support_exclusion_areas_for_layers(fixture.object(), {{0.0, 1.0}, {11.0, 12.0}}, false); + REQUIRE(masks.size() == 2); + CHECK(polygons_cover(masks[0], -4.0, -4.0)); + CHECK(polygons_cover(masks[0], 14.0, -4.0)); + CHECK(masks[1].empty()); + } +} + +TEST_CASE("Support trimming applies the correct nozzle mask to every polygon category", "[ExclusionVolume][Support][MultiNozzle]") +{ + SupportPrintFixture fixture(support_config(1, 2)); + const Polygon source = rectangle(-20.0, -20.0, 40.0, 20.0); + + SupportGeneratorLayer base; + base.layer_type = SupporLayerType::Base; + base.print_z = 1.0; + base.height = 0.2; + base.polygons = {source}; + base.contact_polygons = std::make_unique(Polygons{source}); + base.overhang_polygons = std::make_unique(Polygons{source}); + base.enforcer_polygons = std::make_unique(Polygons{source}); + + SupportGeneratorLayer interface; + interface.layer_type = SupporLayerType::TopInterface; + interface.print_z = 1.0; + interface.height = 0.2; + interface.polygons = {source}; + + const SupportGeneratorLayersPtr none; + const SupportGeneratorLayersPtr base_layers{&base}; + const SupportGeneratorLayersPtr interface_layers{&interface}; + trim_support_layers_by_exclusion_volumes( + fixture.object(), none, none, none, base_layers, interface_layers, none); + + // Base support uses filament 1 and interface support uses filament 2. + CHECK_FALSE(polygons_cover(base.polygons, -4.0, -4.0)); + CHECK(polygons_cover(base.polygons, 14.0, -4.0)); + CHECK(polygons_cover(interface.polygons, -4.0, -4.0)); + CHECK_FALSE(polygons_cover(interface.polygons, 14.0, -4.0)); + + // The same sanitization is mandatory for the auxiliary support categories. + REQUIRE(base.contact_polygons != nullptr); + REQUIRE(base.overhang_polygons != nullptr); + REQUIRE(base.enforcer_polygons != nullptr); + CHECK_FALSE(polygons_cover(*base.contact_polygons, -4.0, -4.0)); + CHECK_FALSE(polygons_cover(*base.overhang_polygons, -4.0, -4.0)); + CHECK_FALSE(polygons_cover(*base.enforcer_polygons, -4.0, -4.0)); +} diff --git a/tests/fff_print/test_print.cpp b/tests/fff_print/test_print.cpp index 6bff945fc3..3bc027ebb5 100644 --- a/tests/fff_print/test_print.cpp +++ b/tests/fff_print/test_print.cpp @@ -119,6 +119,39 @@ size_t count_opt_key(const std::vector& warnings, const s [&](const StringObjectException& w) { return w.opt_key == key; }); } +DynamicPrintConfig dual_extruder_exclusion_config( + BedExcludeAreaMode mode, + const std::vector &per_extruder, + const std::vector &filament_map = {1}) +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_num_extruders(2); + config.set_key_value("nozzle_diameter", new ConfigOptionFloats{0.4, 0.4}); + config.set_key_value("extruder_offset", new ConfigOptionPoints{Vec2d::Zero(), Vec2d(20.0, 0.0)}); + config.set_key_value("extruder_printable_height", new ConfigOptionFloatsNullable{256.0, 256.0}); + config.set_key_value("bed_exclude_area_mode", new ConfigOptionEnum(mode)); + config.set_key_value("extruder_bed_exclude_area", new ConfigOptionStrings(per_extruder)); + config.set_key_value("filament_map_mode", new ConfigOptionEnum(fmmManual)); + config.set_key_value("filament_map", new ConfigOptionInts(filament_map)); + return config; +} + +StringObjectException validate_multimaterial_cube(const DynamicPrintConfig &config) +{ + Model model; + ModelObject *object = model.add_object(); + ModelVolume *first = object->add_volume(cube(20)); + ModelVolume *second = object->add_volume(cube(20)); + first->config.set("extruder", 1); + second->config.set("extruder", 2); + object->add_instance(); + object->ensure_on_bed(); + + Print print; + print.apply(model, config); + return print.validate(); +} + // Make `default_acceleration` exceed the machine's extruding-acceleration limit. void trigger_acceleration_warning(DynamicPrintConfig& c) { @@ -145,6 +178,62 @@ void trigger_precise_wall_warning(DynamicPrintConfig& c) } // namespace +TEST_CASE("Print validation applies individual exclusion volumes to the mapped physical extruder", "[Print][ExclusionVolume][MultiNozzle]") +{ + const std::string colliding = "0..256;-100x-100,300x-100,300x300,-100x300"; + std::vector warnings; + + SECTION("mapped colliding extruder is rejected") { + const DynamicPrintConfig config = dual_extruder_exclusion_config( + BedExcludeAreaMode::PerExtruder, {colliding, ""}, {1}); + const StringObjectException error = validate_cubes(config, warnings); + CHECK(error.string.find("extruder 1") != std::string::npos); + } + + SECTION("mapped clear extruder is accepted") { + const DynamicPrintConfig config = dual_extruder_exclusion_config( + BedExcludeAreaMode::PerExtruder, {colliding, ""}, {2}); + const StringObjectException error = validate_cubes(config, warnings); + CHECK(error.string.empty()); + } + + SECTION("an unrelated nozzle exclusion does not reject the object") { + const DynamicPrintConfig config = dual_extruder_exclusion_config( + BedExcludeAreaMode::PerExtruder, {"", colliding}, {1}); + const StringObjectException error = validate_cubes(config, warnings); + CHECK(error.string.empty()); + } +} + +TEST_CASE("Print validation applies shared exclusions and ignores volumes above the object", "[Print][ExclusionVolume]") +{ + std::vector warnings; + + SECTION("shared volume intersects") { + DynamicPrintConfig config = dual_extruder_exclusion_config(BedExcludeAreaMode::Shared, {"", ""}, {2}); + config.set_deserialize_strict("bed_exclude_area", "0..30;-100x-100,300x-100,300x300,-100x300"); + const StringObjectException error = validate_cubes(config, warnings); + CHECK(error.string.find("extruder 2") != std::string::npos); + } + + SECTION("elevated shared volume clears a 20mm cube") { + DynamicPrintConfig config = dual_extruder_exclusion_config(BedExcludeAreaMode::Shared, {"", ""}, {1}); + config.set_deserialize_strict("bed_exclude_area", "30..50;-100x-100,300x-100,300x300,-100x300"); + const StringObjectException error = validate_cubes(config, warnings); + CHECK(error.string.empty()); + } +} + +TEST_CASE("Print validation checks every nozzle used by a multimaterial object", "[Print][ExclusionVolume][MultiNozzle]") +{ + const std::string colliding = "0..256;-100x-100,300x-100,300x300,-100x300"; + const DynamicPrintConfig config = dual_extruder_exclusion_config( + BedExcludeAreaMode::PerExtruder, {"", colliding}, {1, 2}); + + const StringObjectException error = validate_multimaterial_cube(config); + CHECK(error.string.find("extruder 2") != std::string::npos); +} + // --------------------------------------------------------------------------- // {first_object_name} filename placeholder // --------------------------------------------------------------------------- diff --git a/tests/libslic3r/CMakeLists.txt b/tests/libslic3r/CMakeLists.txt index 2f859f46fe..37f1f0fafe 100644 --- a/tests/libslic3r/CMakeLists.txt +++ b/tests/libslic3r/CMakeLists.txt @@ -21,6 +21,7 @@ add_executable(${_TEST_NAME}_tests test_vendor_cache.cpp test_preset_options.cpp test_elephant_foot_compensation.cpp + test_exclusion_volumes.cpp test_fill_corner_smoothing.cpp test_filament_mixer.cpp test_fill_plane_path.cpp diff --git a/tests/libslic3r/test_3mf.cpp b/tests/libslic3r/test_3mf.cpp index 5c38859a12..f89790f287 100644 --- a/tests/libslic3r/test_3mf.cpp +++ b/tests/libslic3r/test_3mf.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include // for std::enable_if_t #include // for typeid @@ -143,6 +144,74 @@ SCENARIO("Export+Import geometry to/from 3mf file cycle", "[3mf]") { } } +TEST_CASE("Volumetric per-extruder exclusions survive a 3MF round-trip", "[3mf][ExclusionVolume][MultiNozzle]") +{ + Model model; + ModelObject *object = model.add_object(); + object->add_volume(make_cube(10.0, 10.0, 10.0)); + object->add_instance(); + + // Keep the project config intentionally sparse: this test owns only the + // exclusion settings and should not depend on unrelated printer-profile + // defaults surviving the project archive round-trip. + DynamicPrintConfig source; + source.set_key_value("bed_exclude_area_mode", + new ConfigOptionEnum(BedExcludeAreaMode::PerExtruder)); + source.set_deserialize_strict("bed_exclude_area", "0x0,10x0,10x10,0x10"); + source.set_key_value("extruder_bed_exclude_area", new ConfigOptionStrings{ + "0..25;5x5,15x5,15x15,5x15", + "30..80;40x40,55x40,55x55,40x55|0..5;70x10,80x10,80x20,70x20", + }); + + const boost::filesystem::path backup_dir = + boost::filesystem::temp_directory_path() / boost::filesystem::unique_path("orca_exclusion_backup_%%%%%%%%"); + boost::filesystem::create_directories(backup_dir); + model.set_backup_path(backup_dir.string()); + + const boost::filesystem::path path = + boost::filesystem::temp_directory_path() / boost::filesystem::unique_path("orca_exclusion_%%%%%%%%.3mf"); + const std::string path_string = path.string(); + auto plate = std::make_unique(); + plate->plate_index = 0; + StoreParams store_params; + store_params.path = path_string.c_str(); + store_params.model = &model; + store_params.config = &source; + store_params.plate_data_list.push_back(plate.get()); + store_params.strategy = SaveStrategy::Zip64 | SaveStrategy::Silence; + REQUIRE(store_bbs_3mf(store_params)); + + Model reloaded_model; + DynamicPrintConfig reloaded; + ConfigSubstitutionContext substitutions{ForwardCompatibilitySubstitutionRule::Disable}; + PlateDataPtrs reloaded_plates; + std::vector project_presets; + bool is_bbl_3mf = false; + bool is_orca_3mf = false; + Semver file_version; + const bool loaded = load_bbs_3mf( + path_string.c_str(), &reloaded, &substitutions, &reloaded_model, &reloaded_plates, + &project_presets, &is_bbl_3mf, &is_orca_3mf, &file_version, nullptr, + LoadStrategy::LoadModel | LoadStrategy::LoadConfig); + boost::filesystem::remove(path); + boost::filesystem::remove_all(backup_dir); + release_PlateData_list(reloaded_plates); + + REQUIRE(loaded); + REQUIRE(reloaded.option>("bed_exclude_area_mode") != nullptr); + CHECK(reloaded.option>("bed_exclude_area_mode")->value == + BedExcludeAreaMode::PerExtruder); + + const auto *areas = reloaded.option("extruder_bed_exclude_area"); + REQUIRE(areas != nullptr); + REQUIRE(areas->values.size() == 2); + CHECK(areas->values == source.option("extruder_bed_exclude_area")->values); + + const auto *legacy = reloaded.option("bed_exclude_area"); + REQUIRE(legacy != nullptr); + CHECK(legacy->serialize() == "0x0,10x0,10x10,0x10"); +} + // .3mf multi-nozzle round-trip. // Locks the load/save handling for the H2C multi-nozzle plate metadata: // * filament_volume_maps -> plate config "filament_volume_map" (with the >1 -> 0 clamp) diff --git a/tests/libslic3r/test_arrange.cpp b/tests/libslic3r/test_arrange.cpp index 3906cba8ba..b4f0a73699 100644 --- a/tests/libslic3r/test_arrange.cpp +++ b/tests/libslic3r/test_arrange.cpp @@ -316,3 +316,101 @@ TEST_CASE("Layered printing does not floor the object distance", "[Arrange]") update_selected_items_inflation(items, &cfg, p); CHECK(p.min_obj_distance == 0); } + +TEST_CASE("Bed exclusions apply by physical nozzle and overlapping Z range", "[Arrange][ExclusionVolume][MultiNozzle]") +{ + ArrangePolygon object = make_square(scaled(20.)); + object.has_z_range = true; + object.z_min = 0.0; + object.z_max = 20.0; + object.bed_exclusion_extruder_ids = {1}; + + ArrangePolygon exclusion = make_square(scaled(20.)); + exclusion.is_bed_exclusion = true; + exclusion.has_z_range = true; + exclusion.z_min = 10.0; + exclusion.z_max = 30.0; + exclusion.bed_exclusion_extruder_id = 1; + + CHECK(bed_exclusion_applies(object, exclusion)); + + exclusion.bed_exclusion_extruder_id = 0; + CHECK_FALSE(bed_exclusion_applies(object, exclusion)); + + // Empty physical-nozzle assignments mean unresolved, so arrangement stays conservative. + object.bed_exclusion_extruder_ids.clear(); + CHECK(bed_exclusion_applies(object, exclusion)); + + object.bed_exclusion_extruder_ids = {0}; + object.z_max = 9.0; + CHECK_FALSE(bed_exclusion_applies(object, exclusion)); + + // Touching at one Z plane is intentionally treated as a collision. + object.z_max = 10.0; + CHECK(bed_exclusion_applies(object, exclusion)); +} + +TEST_CASE("Shared bed exclusions apply to every arranged object", "[Arrange][ExclusionVolume]") +{ + ArrangePolygon object = make_square(scaled(20.)); + object.bed_exclusion_extruder_ids = {1}; + + ArrangePolygon shared = make_square(scaled(20.)); + shared.is_bed_exclusion = true; + shared.bed_exclusion_extruder_id = -1; + + CHECK(has_bed_exclusion_regions({shared})); + CHECK_FALSE(has_bed_exclusion_regions({object})); + CHECK(bed_exclusion_applies(object, shared)); +} + +TEST_CASE("Conservative exclusion validation invalidates only relevant placements", "[Arrange][ExclusionVolume][MultiNozzle]") +{ + ArrangePolygon exclusion = make_square(scaled(20.)); + exclusion.is_bed_exclusion = true; + exclusion.bed_exclusion_extruder_id = 0; + exclusion.has_z_range = true; + exclusion.z_min = 0.0; + exclusion.z_max = 30.0; + + ArrangePolygon relevant = make_square(scaled(10.)); + relevant.bed_exclusion_extruder_ids = {0}; + relevant.has_z_range = true; + relevant.z_min = 0.0; + relevant.z_max = 10.0; + + ArrangePolygon other_nozzle = relevant; + other_nozzle.bed_exclusion_extruder_ids = {1}; + + ArrangePolygon above = relevant; + above.z_min = 31.0; + above.z_max = 40.0; + + ArrangePolygons items{relevant, other_nozzle, above}; + invalidate_bed_exclusion_conflicts(items, {exclusion}); + + CHECK(items[0].bed_idx == UNARRANGED); + CHECK(items[1].bed_idx == 0); + CHECK(items[2].bed_idx == 0); +} + +TEST_CASE("Arrange keeps relevant objects outside conditional exclusion obstacles", "[Arrange][ExclusionVolume]") +{ + ArrangePolygon exclusion = make_square(scaled(30.)); + exclusion.translation = Vec2crd(scaled(35.0), scaled(35.0)); + exclusion.is_bed_exclusion = true; + exclusion.bed_exclusion_extruder_id = 0; + + ArrangePolygons items = squares(4, 20.0); + for (ArrangePolygon &item : items) + item.bed_exclusion_extruder_ids = {0}; + + arrange(items, {exclusion}, bed(100.0, 100.0), quiet_params(scaled(1.0))); + + const ExPolygon excluded_shape = exclusion.transformed_poly(); + for (const ArrangePolygon &item : items) { + REQUIRE(item.bed_idx == 0); + CHECK(intersection(ExPolygons{item.transformed_poly()}, ExPolygons{excluded_shape}).empty()); + } + require_no_overlap(items); +} diff --git a/tests/libslic3r/test_exclusion_volumes.cpp b/tests/libslic3r/test_exclusion_volumes.cpp new file mode 100644 index 0000000000..dbdf0366e6 --- /dev/null +++ b/tests/libslic3r/test_exclusion_volumes.cpp @@ -0,0 +1,296 @@ +#include + +#include "libslic3r/BoundingBox.hpp" +#include "libslic3r/ExclusionVolumeGeometry.hpp" +#include "libslic3r/Model.hpp" +#include "libslic3r/PrintConfig.hpp" +#include "libslic3r/TriangleMesh.hpp" + +#include +#include +#include + +using namespace Slic3r; +using Catch::Matchers::WithinAbs; + +namespace { + +Polygon rectangle(double min_x, double min_y, double max_x, double max_y) +{ + Polygon polygon({ + Point::new_scale(min_x, min_y), + Point::new_scale(max_x, min_y), + Point::new_scale(max_x, max_y), + Point::new_scale(min_x, max_y), + }); + polygon.make_counter_clockwise(); + return polygon; +} + +BedExcludeRegion region(double min_x, double min_y, double max_x, double max_y, + double z_min, double z_max, bool has_z_range = true) +{ + return {rectangle(min_x, min_y, max_x, max_y), z_min, z_max, true, has_z_range}; +} + +DynamicPrintConfig two_extruder_config() +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_num_extruders(2); + config.set_key_value("nozzle_diameter", new ConfigOptionFloats{0.4, 0.6}); + config.set_key_value("extruder_offset", new ConfigOptionPoints{Vec2d(0.0, 0.0), Vec2d(20.0, 5.0)}); + config.set_key_value("extruder_printable_height", new ConfigOptionFloatsNullable{200.0, 200.0}); + config.set_key_value("master_extruder_id", new ConfigOptionInt(1)); + config.set_key_value("printable_height", new ConfigOptionFloat(200.0)); + config.set_deserialize_strict("bed_exclude_area", "10..30;0x0,10x0,10x10,0x10"); + return config; +} + +BoundingBox bounds(const BedExcludeRegion ®ion) +{ + return get_extents(region.polygon); +} + +double unscaled_x(coord_t value) +{ + return unscale(value); +} + +bool contains(const ExPolygons &polygons, double x, double y) +{ + const Point point = Point::new_scale(x, y); + return std::any_of(polygons.begin(), polygons.end(), [&](const ExPolygon &polygon) { + return polygon.contains(point); + }); +} + +struct CubeModel +{ + Model model; + ModelInstance *instance {nullptr}; + + explicit CubeModel(const Vec3d &offset = Vec3d::Zero()) + { + ModelObject *object = model.add_object(); + object->add_volume(make_cube(20.0, 20.0, 20.0)); + instance = object->add_instance(); + instance->set_offset(offset); + } +}; + +} // namespace + +TEST_CASE("Legacy exclusion polygons keep their point representation", "[ExclusionVolume][PrintConfig]") +{ + ConfigOptionPoints option; + REQUIRE(option.deserialize("0x0,10x0,10x10,0x10")); + REQUIRE(option.values.size() == 4); + CHECK(option.serialize() == "0x0,10x0,10x10,0x10"); + CHECK_FALSE(has_bed_exclusion_volume_syntax(option)); +} + +TEST_CASE("Extended exclusion definitions retain their serialized representation", "[ExclusionVolume][PrintConfig]") +{ + const std::string definition = "0..10;0x0,10x0,10x10,0x10|20x20,30x20,30x30,20x30"; + ConfigOptionPoints option; + REQUIRE(option.deserialize(definition)); + CHECK(option.values.empty()); + CHECK(option.serialize() == definition); + CHECK(option.vserialize() == std::vector{definition}); + CHECK(has_bed_exclusion_volume_syntax(option)); + + std::unique_ptr cloned(option.clone()); + REQUIRE(cloned != nullptr); + CHECK(*cloned == option); + CHECK(cloned->hash() == option.hash()); + + ConfigOptionPoints assigned; + assigned.set(&option); + CHECK(assigned == option); +} + +TEST_CASE("Exclusion syntax validation accepts supported forms and rejects malformed regions", "[ExclusionVolume][PrintConfig]") +{ + const auto [definition, valid] = GENERATE(table({ + {"", true}, + {"0x0,10x0,10x10,0x10", true}, + {"0..10;0x0,10x0,10x10,0x10", true}, + {"..10;0x0,10x0,10x10,0x10", true}, + {"10..;0x0,10x0,10x10,0x10", true}, + {"0x0,10x0,10x10,0x10|20x20,30x20,30x30,20x30", true}, + {"20..10;0x0,10x0,10x10,0x10", false}, + {"zero..10;0x0,10x0,10x10,0x10", false}, + {"0..10;0x0,10x0", false}, + {"0..10;", false}, + {"|", false}, + })); + + DYNAMIC_SECTION(definition) { + CHECK(is_valid_bed_exclude_area_string(definition, 200.0) == valid); + } +} + +TEST_CASE("Extended exclusion Z ranges are defaulted and clamped to printable height", "[ExclusionVolume][PrintConfig]") +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_key_value("printable_height", new ConfigOptionFloat(100.0)); + config.set_deserialize_strict( + "bed_exclude_area", + "-20..25;0x0,10x0,10x10,0x10|75..150;20x0,30x0,30x10,20x10|..;40x0,50x0,50x10,40x10"); + + const std::vector regions = get_bed_excluded_regions(config); + REQUIRE(regions.size() == 3); + CHECK_THAT(regions[0].z_min, WithinAbs(0.0, 1e-9)); + CHECK_THAT(regions[0].z_max, WithinAbs(25.0, 1e-9)); + CHECK_THAT(regions[1].z_min, WithinAbs(75.0, 1e-9)); + CHECK_THAT(regions[1].z_max, WithinAbs(100.0, 1e-9)); + CHECK_THAT(regions[2].z_min, WithinAbs(0.0, 1e-9)); + CHECK_THAT(regions[2].z_max, WithinAbs(100.0, 1e-9)); +} + +TEST_CASE("Shared exclusion volumes resolve identically for every extruder", "[ExclusionVolume][PrintConfig][MultiNozzle]") +{ + DynamicPrintConfig config = two_extruder_config(); + config.set_key_value("bed_exclude_area_mode", new ConfigOptionEnum(BedExcludeAreaMode::Shared)); + + const auto groups = get_bed_excluded_regions_by_extruder(config); + REQUIRE(groups.size() == 2); + REQUIRE(groups[0].size() == 1); + REQUIRE(groups[1].size() == 1); + CHECK(groups[0][0].polygon.points == groups[1][0].polygon.points); + CHECK_THAT(groups[0][0].z_min, WithinAbs(10.0, 1e-9)); + CHECK_THAT(groups[0][0].z_max, WithinAbs(30.0, 1e-9)); + + // A shared compatibility view contains one definition, not one duplicate per nozzle. + CHECK(get_bed_excluded_regions(config).size() == 1); +} + +TEST_CASE("Toolhead-relative exclusion volumes follow nozzle offset deltas", "[ExclusionVolume][PrintConfig][MultiNozzle]") +{ + DynamicPrintConfig config = two_extruder_config(); + config.set_key_value("bed_exclude_area_mode", new ConfigOptionEnum(BedExcludeAreaMode::ToolheadOffset)); + + const auto groups = get_bed_excluded_regions_by_extruder(config); + REQUIRE(groups.size() == 2); + REQUIRE(groups[0].size() == 1); + REQUIRE(groups[1].size() == 1); + const BoundingBox reference = bounds(groups[0][0]); + const BoundingBox shifted = bounds(groups[1][0]); + CHECK_THAT(unscaled_x(shifted.min.x() - reference.min.x()), WithinAbs(20.0, 1e-6)); + CHECK_THAT(unscaled_x(shifted.min.y() - reference.min.y()), WithinAbs(5.0, 1e-6)); +} + +TEST_CASE("Toolhead-relative exclusions honour a non-default reference extruder", "[ExclusionVolume][PrintConfig][MultiNozzle]") +{ + DynamicPrintConfig config = two_extruder_config(); + config.set_key_value("master_extruder_id", new ConfigOptionInt(2)); + config.set_key_value("bed_exclude_area_mode", new ConfigOptionEnum(BedExcludeAreaMode::ToolheadOffset)); + + const auto groups = get_bed_excluded_regions_by_extruder(config); + REQUIRE(groups.size() == 2); + const BoundingBox first = bounds(groups[0][0]); + const BoundingBox reference = bounds(groups[1][0]); + CHECK_THAT(unscaled_x(first.min.x() - reference.min.x()), WithinAbs(-20.0, 1e-6)); + CHECK_THAT(unscaled_x(first.min.y() - reference.min.y()), WithinAbs(-5.0, 1e-6)); +} + +TEST_CASE("Individual exclusion volumes remain authoritative per extruder", "[ExclusionVolume][PrintConfig][MultiNozzle]") +{ + DynamicPrintConfig config = two_extruder_config(); + config.set_key_value("bed_exclude_area_mode", new ConfigOptionEnum(BedExcludeAreaMode::PerExtruder)); + config.set_key_value("extruder_bed_exclude_area", new ConfigOptionStrings{ + "0..25;0x0,8x0,8x8,0x8|40..60;20x20,30x20,30x30,20x30", + "", + }); + + const auto groups = get_bed_excluded_regions_by_extruder(config); + REQUIRE(groups.size() == 2); + CHECK(groups[0].size() == 2); + CHECK(groups[1].empty()); + CHECK(get_bed_excluded_regions(config).size() == 2); +} + +TEST_CASE("Legacy bed helpers include only regions touching the first layer", "[ExclusionVolume][PrintConfig]") +{ + DynamicPrintConfig dynamic = DynamicPrintConfig::full_print_config(); + dynamic.set_key_value("printable_height", new ConfigOptionFloat(100.0)); + dynamic.set_deserialize_strict( + "bed_exclude_area", + "0..5;0x0,10x0,10x10,0x10|20..30;20x0,30x0,30x10,20x10"); + PrintConfig config; + config.apply(dynamic, true); + + const Polygons bed_regions = get_bed_excluded_area(config); + REQUIRE(bed_regions.size() == 1); + CHECK(bed_regions.front().contains(Point::new_scale(5.0, 5.0))); + CHECK_FALSE(bed_regions.front().contains(Point::new_scale(25.0, 5.0))); +} + +TEST_CASE("Filament mapping resolves physical exclusion extruders conservatively", "[ExclusionVolume][PrintConfig][MultiNozzle]") +{ + CHECK(bed_exclusion_extruder_for_filament(0, {2, 1}, fmmManual, false, true, 2) == 1); + CHECK(bed_exclusion_extruder_for_filament(1, {2, 1}, fmmManual, false, true, 2) == 0); + + // Generic automatic multi-tool printers use matching logical and physical ids. + CHECK(bed_exclusion_extruder_for_filament(1, {1, 1}, fmmAutoForMatch, false, false, 2) == 1); + + // Until Bambu automatic grouping has produced a concrete mapping, every nozzle remains possible. + CHECK(bed_exclusion_extruder_for_filament(0, {1}, fmmAutoForMatch, true, false, 2) == -1); + CHECK(bed_exclusion_extruder_for_filament(0, {2}, fmmAutoForMatch, true, true, 2) == 1); + CHECK(bed_exclusion_extruder_for_filament(3, {}, fmmManual, false, true, 2) == -1); +} + +TEST_CASE("Exclusion Z overlap treats touching slabs conservatively", "[ExclusionVolume][Geometry]") +{ + CHECK(bed_exclusion_z_ranges_overlap(0.0, 10.0, 10.0, 20.0)); + CHECK(bed_exclusion_z_ranges_overlap(10.0, 0.0, 20.0, 10.0)); + CHECK_FALSE(bed_exclusion_z_ranges_overlap(0.0, 9.0, 10.0, 20.0)); +} + +TEST_CASE("Active exclusion footprints select Z range nozzle translation and clearance", "[ExclusionVolume][Geometry][MultiNozzle]") +{ + const std::vector> regions_by_extruder{ + {region(0.0, 0.0, 10.0, 10.0, 0.0, 5.0)}, + {region(20.0, 0.0, 30.0, 10.0, 10.0, 20.0)}, + }; + + ExPolygons active = active_bed_exclusion_footprints( + regions_by_extruder, {1, 1, 99}, 12.0, 13.0, Point::new_scale(5.0, 2.0), scale_(1.0)); + REQUIRE(active.size() == 1); + CHECK(contains(active, 26.0, 3.0)); + CHECK(contains(active, 35.5, 3.0)); + CHECK_FALSE(contains(active, 5.0, 5.0)); + + CHECK(active_bed_exclusion_footprints(regions_by_extruder, {0}, 6.0, 9.0).empty()); +} + +TEST_CASE("Exact model intersection respects XY Z and preview collection", "[ExclusionVolume][Model]") +{ + CubeModel cube(Vec3d(30.0, 40.0, 0.0)); + + // Cross the cube's outer surface rather than placing the prism wholly + // inside the solid; the preview is built from clipped surface triangles. + const BedExcludeRegion crossing = region(45.0, 45.0, 55.0, 55.0, 5.0, 15.0); + const BedExcludeRegion above = region(45.0, 45.0, 55.0, 55.0, 25.0, 30.0); + const BedExcludeRegion outside = region(60.0, 70.0, 70.0, 80.0, 0.0, 20.0); + + CHECK(cube.instance->intersects_bed_exclude_region(crossing)); + CHECK_FALSE(cube.instance->intersects_bed_exclude_region(above)); + CHECK_FALSE(cube.instance->intersects_bed_exclude_region(outside)); + + indexed_triangle_set preview; + CHECK(cube.instance->intersects_bed_exclude_region(crossing, &preview)); + CHECK_FALSE(preview.empty()); + CHECK_FALSE(cube.instance->intersects_bed_exclude_region(above, &preview)); + CHECK(preview.empty()); +} + +TEST_CASE("Exact model intersection follows instance and volume transforms", "[ExclusionVolume][Model]") +{ + CubeModel cube(Vec3d(50.0, 50.0, 0.0)); + cube.instance->set_rotation(Vec3d(0.0, 0.0, PI / 4.0)); + cube.instance->set_scaling_factor(Vec3d(1.5, 0.5, 1.0)); + + CHECK(cube.instance->intersects_bed_exclude_region(region(50.0, 50.0, 55.0, 55.0, 0.0, 20.0))); + CHECK_FALSE(cube.instance->intersects_bed_exclude_region(region(100.0, 100.0, 110.0, 110.0, 0.0, 20.0))); +} From cca51293a4b32bee51d28cc30ee578dcef284a0b Mon Sep 17 00:00:00 2001 From: Harry Loud Date: Wed, 2 Sep 2026 09:35:47 +0100 Subject: [PATCH 21/38] Fix enclosed exclusion volume detection --- src/libslic3r/Model.cpp | 30 +++++++++++++++-- tests/libslic3r/test_exclusion_volumes.cpp | 38 +++++++++++++++++++--- 2 files changed, 62 insertions(+), 6 deletions(-) diff --git a/src/libslic3r/Model.cpp b/src/libslic3r/Model.cpp index 94c192ec66..02ee6679f9 100644 --- a/src/libslic3r/Model.cpp +++ b/src/libslic3r/Model.cpp @@ -1,5 +1,6 @@ #include "Model.hpp" #include "libslic3r.h" +#include "AABBMesh.hpp" #include "BuildVolume.hpp" #include "TexturePainting.hpp" #include "Format/AssimpImport.hpp" @@ -3613,6 +3614,7 @@ bool ModelInstance::intersects_bed_exclude_region(const BedExcludeRegion ®ion continue; const Transform3d volume_matrix = instance_matrix * volume->get_matrix(); + bool volume_surface_intersects = false; for (const stl_triangle_vertex_indices &face : its.indices) { const Vec3d p0 = volume_matrix * its.vertices[face[0]].cast(); const Vec3d p1 = volume_matrix * its.vertices[face[1]].cast(); @@ -3631,6 +3633,7 @@ bool ModelInstance::intersects_bed_exclude_region(const BedExcludeRegion ®ion if (polygon_3d_area2(clipped) <= 1e-8) continue; + volume_surface_intersects = true; intersects = true; if (intersection_mesh == nullptr) return true; @@ -3638,6 +3641,28 @@ bool ModelInstance::intersects_bed_exclude_region(const BedExcludeRegion ®ion append_clipped_polygon(*intersection_mesh, clipped); } } + + if (!volume_surface_intersects && !intersects) { + // Surface clipping cannot detect a prism wholly enclosed by a + // solid. In that topology, with no boundary crossing, one point + // inside the connected prism is sufficient to test containment. + const ExclusionPrismFootprintTriangle &footprint = footprints.front(); + const Vec2d probe_xy = (footprint.vertices[0] + footprint.vertices[1] + footprint.vertices[2]) / 3.0; + const Vec3d probe_world(probe_xy.x(), probe_xy.y(), z_min + 0.5 * (z_max - z_min)); + const Vec3d probe_local = volume_matrix.inverse() * probe_world; + + // Avoid constructing the spatial index for the common case where + // the probe is plainly outside this model part. + if (volume->mesh().bounding_box().contains(probe_local)) { + const AABBMesh mesh(its); + if (!mesh.query_ray_hit(probe_local, Vec3d::UnitX()).is_inside()) + continue; + + intersects = true; + if (intersection_mesh == nullptr) + return true; + } + } } return intersects; @@ -3665,9 +3690,10 @@ bool ModelInstance::intersects_bed_exclude_regions( } indexed_triangle_set region_intersection; - if (intersects_bed_exclude_region(region, ®ion_intersection) && !region_intersection.empty()) { + if (intersects_bed_exclude_region(region, ®ion_intersection)) { intersects = true; - its_merge(*intersection_mesh, region_intersection); + if (!region_intersection.empty()) + its_merge(*intersection_mesh, region_intersection); } } return intersects; diff --git a/tests/libslic3r/test_exclusion_volumes.cpp b/tests/libslic3r/test_exclusion_volumes.cpp index dbdf0366e6..db0f425506 100644 --- a/tests/libslic3r/test_exclusion_volumes.cpp +++ b/tests/libslic3r/test_exclusion_volumes.cpp @@ -69,10 +69,10 @@ struct CubeModel Model model; ModelInstance *instance {nullptr}; - explicit CubeModel(const Vec3d &offset = Vec3d::Zero()) + explicit CubeModel(const Vec3d &offset = Vec3d::Zero(), const Vec3d &size = Vec3d(20.0, 20.0, 20.0)) { ModelObject *object = model.add_object(); - object->add_volume(make_cube(20.0, 20.0, 20.0)); + object->add_volume(make_cube(size.x(), size.y(), size.z())); instance = object->add_instance(); instance->set_offset(offset); } @@ -268,8 +268,9 @@ TEST_CASE("Exact model intersection respects XY Z and preview collection", "[Exc { CubeModel cube(Vec3d(30.0, 40.0, 0.0)); - // Cross the cube's outer surface rather than placing the prism wholly - // inside the solid; the preview is built from clipped surface triangles. + // Cross the cube's outer surface so this case can also verify the red + // preview, which is built from clipped surface triangles. The enclosed + // prism topology is covered separately below. const BedExcludeRegion crossing = region(45.0, 45.0, 55.0, 55.0, 5.0, 15.0); const BedExcludeRegion above = region(45.0, 45.0, 55.0, 55.0, 25.0, 30.0); const BedExcludeRegion outside = region(60.0, 70.0, 70.0, 80.0, 0.0, 20.0); @@ -294,3 +295,32 @@ TEST_CASE("Exact model intersection follows instance and volume transforms", "[E CHECK(cube.instance->intersects_bed_exclude_region(region(50.0, 50.0, 55.0, 55.0, 0.0, 20.0))); CHECK_FALSE(cube.instance->intersects_bed_exclude_region(region(100.0, 100.0, 110.0, 110.0, 0.0, 20.0))); } + +TEST_CASE("Exact model intersection detects an exclusion prism enclosed by a solid", "[ExclusionVolume][Model]") +{ + // A surface-only test misses this topology: the exclusion prism is fully + // enclosed, so none of the block's surface triangles enters the prism. + CubeModel block(Vec3d(200.0, 300.0, 0.0), Vec3d(100.0, 100.0, 60.0)); + const BedExcludeRegion enclosed = region(230.0, 330.0, 260.0, 358.0, 8.0, 22.0); + const BedExcludeRegion enclosing = region(190.0, 290.0, 310.0, 410.0, -5.0, 65.0); + const BedExcludeRegion above = region(230.0, 330.0, 260.0, 358.0, 65.0, 75.0); + + CHECK(block.instance->intersects_bed_exclude_region(enclosed)); + CHECK_FALSE(block.instance->intersects_bed_exclude_region(above)); + + indexed_triangle_set preview; + CHECK(block.instance->intersects_bed_exclude_region(enclosed, &preview)); + // There is no model surface inside a fully enclosed prism from which to + // build the usual red clipped-surface preview. + CHECK(preview.empty()); + + // Pin the opposite containment topology too. Here the model surface lies + // inside the prism, so the existing clipped preview remains available. + CHECK(block.instance->intersects_bed_exclude_region(enclosing, &preview)); + CHECK_FALSE(preview.empty()); + + // The multi-region wrapper must preserve the collision result even when + // that optional surface preview is empty. + CHECK(block.instance->intersects_bed_exclude_regions({above, enclosed}, &preview)); + CHECK(preview.empty()); +} From ac2c33b43b6b0567a9c68009f009bcd0a68a905c Mon Sep 17 00:00:00 2001 From: Harry Loud Date: Wed, 2 Sep 2026 13:37:35 +0100 Subject: [PATCH 22/38] Make exclusion 3MF test portable --- tests/libslic3r/test_3mf.cpp | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/tests/libslic3r/test_3mf.cpp b/tests/libslic3r/test_3mf.cpp index f89790f287..f1fc5c0bf5 100644 --- a/tests/libslic3r/test_3mf.cpp +++ b/tests/libslic3r/test_3mf.cpp @@ -146,6 +146,10 @@ SCENARIO("Export+Import geometry to/from 3mf file cycle", "[3mf]") { TEST_CASE("Volumetric per-extruder exclusions survive a 3MF round-trip", "[3mf][ExclusionVolume][MultiNozzle]") { + // The importer creates a backup tree for the reloaded model. Give that + // process-global temp root a writable, isolated location on every OS. + ScopedSlic3rTemporaryDir temporary_dir("orca_exclusion"); + Model model; ModelObject *object = model.add_object(); object->add_volume(make_cube(10.0, 10.0, 10.0)); @@ -163,13 +167,10 @@ TEST_CASE("Volumetric per-extruder exclusions survive a 3MF round-trip", "[3mf][ "30..80;40x40,55x40,55x55,40x55|0..5;70x10,80x10,80x20,70x20", }); - const boost::filesystem::path backup_dir = - boost::filesystem::temp_directory_path() / boost::filesystem::unique_path("orca_exclusion_backup_%%%%%%%%"); - boost::filesystem::create_directories(backup_dir); + const boost::filesystem::path backup_dir = temporary_dir.path() / "source_backup"; model.set_backup_path(backup_dir.string()); - const boost::filesystem::path path = - boost::filesystem::temp_directory_path() / boost::filesystem::unique_path("orca_exclusion_%%%%%%%%.3mf"); + const boost::filesystem::path path = temporary_dir.path() / "round_trip.3mf"; const std::string path_string = path.string(); auto plate = std::make_unique(); plate->plate_index = 0; @@ -193,8 +194,6 @@ TEST_CASE("Volumetric per-extruder exclusions survive a 3MF round-trip", "[3mf][ path_string.c_str(), &reloaded, &substitutions, &reloaded_model, &reloaded_plates, &project_presets, &is_bbl_3mf, &is_orca_3mf, &file_version, nullptr, LoadStrategy::LoadModel | LoadStrategy::LoadConfig); - boost::filesystem::remove(path); - boost::filesystem::remove_all(backup_dir); release_PlateData_list(reloaded_plates); REQUIRE(loaded); From ef7348995ca437c06fb1ae8304727eeccff408f7 Mon Sep 17 00:00:00 2001 From: Harry Loud Date: Wed, 2 Sep 2026 15:02:36 +0100 Subject: [PATCH 23/38] Avoid rebuilding mesh trees for exclusion containment --- src/libslic3r/Model.cpp | 40 ++++++++++++++++++++++++++++++++-------- 1 file changed, 32 insertions(+), 8 deletions(-) diff --git a/src/libslic3r/Model.cpp b/src/libslic3r/Model.cpp index 02ee6679f9..4060bd5363 100644 --- a/src/libslic3r/Model.cpp +++ b/src/libslic3r/Model.cpp @@ -1,6 +1,6 @@ #include "Model.hpp" #include "libslic3r.h" -#include "AABBMesh.hpp" +#include "AABBTreeIndirect.hpp" #include "BuildVolume.hpp" #include "TexturePainting.hpp" #include "Format/AssimpImport.hpp" @@ -3577,6 +3577,34 @@ static void append_clipped_polygon(indexed_triangle_set &out, const std::vector< } } +static bool mesh_contains_point_linear(const indexed_triangle_set &its, const Vec3d &point) +{ + constexpr double ray_epsilon = 1e-6; + const Vec3d ray_direction = Vec3d::UnitX(); + double nearest_hit_distance = std::numeric_limits::infinity(); + size_t nearest_face = size_t(-1); + + for (size_t face_id = 0; face_id < its.indices.size(); ++face_id) { + const stl_triangle_vertex_indices &face = its.indices[face_id]; + double distance; + double u; + double v; + if (AABBTreeIndirect::detail::intersect_triangle( + point, ray_direction, + its.vertices[face[0]], its.vertices[face[1]], its.vertices[face[2]], + distance, u, v, ray_epsilon) && + distance > 0.0 && distance < nearest_hit_distance) { + nearest_hit_distance = distance; + nearest_face = face_id; + } + } + + // This matches AABBMesh::hit_result::is_inside(): for a consistently + // oriented closed mesh, the nearest face points along a ray leaving it. + return nearest_face != size_t(-1) && + its_unnormalized_normal(its, nearest_face).cast().dot(ray_direction) > 0.0; +} + } // namespace bool ModelInstance::intersects_bed_exclude_region(const BedExcludeRegion ®ion, indexed_triangle_set *intersection_mesh) const @@ -3651,13 +3679,9 @@ bool ModelInstance::intersects_bed_exclude_region(const BedExcludeRegion ®ion const Vec3d probe_world(probe_xy.x(), probe_xy.y(), z_min + 0.5 * (z_max - z_min)); const Vec3d probe_local = volume_matrix.inverse() * probe_world; - // Avoid constructing the spatial index for the common case where - // the probe is plainly outside this model part. - if (volume->mesh().bounding_box().contains(probe_local)) { - const AABBMesh mesh(its); - if (!mesh.query_ray_hit(probe_local, Vec3d::UnitX()).is_inside()) - continue; - + // A linear ray scan keeps this one-off fallback O(n) without + // adding ray tests to the usual surface-intersection path. + if (volume->mesh().bounding_box().contains(probe_local) && mesh_contains_point_linear(its, probe_local)) { intersects = true; if (intersection_mesh == nullptr) return true; From e49840d0c6ae446ae0d7c3d1671d021882382f2c Mon Sep 17 00:00:00 2001 From: Harry Loud Date: Mon, 14 Sep 2026 15:19:14 +0100 Subject: [PATCH 24/38] Fix exclusion clipping warning-as-error --- src/libslic3r/Model.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libslic3r/Model.cpp b/src/libslic3r/Model.cpp index 4060bd5363..9c9dbd76e3 100644 --- a/src/libslic3r/Model.cpp +++ b/src/libslic3r/Model.cpp @@ -3437,7 +3437,7 @@ static std::vector clip_polygon_by_signed_distance(const std::vector duplicate_epsilon_sq) output.emplace_back(point); }; From f832cae2eba8163629eb1914dfb2d5a841823020 Mon Sep 17 00:00:00 2001 From: Harry Loud Date: Mon, 21 Sep 2026 10:28:26 +0100 Subject: [PATCH 25/38] Separate legacy bed areas from collision volumes --- src/OrcaSlicer.cpp | 2 +- src/libslic3r/Config.hpp | 78 +----- src/libslic3r/GCode.cpp | 5 +- .../GCode/ExclusionVolumePathCheck.cpp | 5 +- .../GCode/ExclusionVolumeTravelAvoidance.cpp | 2 + src/libslic3r/GCode/GCodeProcessor.cpp | 54 +++- src/libslic3r/Model.cpp | 2 +- src/libslic3r/Preset.cpp | 2 +- src/libslic3r/Print.cpp | 24 +- src/libslic3r/PrintConfig.cpp | 233 ++++++++++++------ src/libslic3r/PrintConfig.hpp | 24 +- src/slic3r/GUI/ConfigWizard.cpp | 2 +- src/slic3r/GUI/Field.cpp | 6 +- src/slic3r/GUI/Jobs/ArrangeJob.cpp | 4 +- src/slic3r/GUI/PartPlate.cpp | 32 ++- src/slic3r/GUI/Plater.cpp | 12 +- src/slic3r/GUI/Tab.cpp | 116 +++++++-- tests/fff_print/test_exclusion_volumes.cpp | 56 ++++- tests/fff_print/test_print.cpp | 33 ++- tests/libslic3r/test_3mf.cpp | 21 +- tests/libslic3r/test_exclusion_volumes.cpp | 124 +++++++--- 21 files changed, 558 insertions(+), 279 deletions(-) diff --git a/src/OrcaSlicer.cpp b/src/OrcaSlicer.cpp index 5bbade3561..743644f82e 100644 --- a/src/OrcaSlicer.cpp +++ b/src/OrcaSlicer.cpp @@ -122,7 +122,7 @@ using namespace Slic3r; static Pointfs legacy_bed_exclude_area_points(const DynamicPrintConfig &config) { const ConfigOptionPoints *option = config.option("bed_exclude_area"); - return option != nullptr && !has_bed_exclusion_volume_syntax(*option) ? option->values : Pointfs{}; + return option != nullptr && !has_bed_exclude_volumes(config) ? option->values : Pointfs{}; } std::map cli_errors = { diff --git a/src/libslic3r/Config.hpp b/src/libslic3r/Config.hpp index 4129b7838c..e4c3f4d1b0 100644 --- a/src/libslic3r/Config.hpp +++ b/src/libslic3r/Config.hpp @@ -1547,34 +1547,14 @@ public: ConfigOptionType type() const override { return static_type(); } ConfigOption* clone() const override { return new ConfigOptionPoints(*this); } ConfigOptionPoints& operator= (const ConfigOption *opt) { this->set(opt); return *this; } - bool operator==(const ConfigOptionPoints &rhs) const throw() { return this->values == rhs.values && m_serialized_override == rhs.m_serialized_override; } - bool operator==(const ConfigOption &rhs) const override - { - if (rhs.type() != this->type()) - throw ConfigurationError("ConfigOptionPoints: Comparing incompatible types"); - assert(dynamic_cast(&rhs)); - const ConfigOptionPoints *other = static_cast(&rhs); - return this->values == other->values && m_serialized_override == other->m_serialized_override; - } + using ConfigOptionVector::operator==; + bool operator==(const ConfigOptionPoints &rhs) const throw() { return this->values == rhs.values; } bool operator< (const ConfigOptionPoints &rhs) const throw() { return std::lexicographical_compare(this->values.begin(), this->values.end(), rhs.values.begin(), rhs.values.end(), [](const auto &l, const auto &r){ return l < r; }); } bool is_nil(size_t) const override { return false; } - void set(const ConfigOption *rhs) override - { - if (rhs->type() != this->type()) - throw ConfigurationError("ConfigOptionPoints: Assigning an incompatible type"); - assert(dynamic_cast(rhs)); - const ConfigOptionPoints *other = static_cast(rhs); - this->values = other->values; - m_serialized_override = other->m_serialized_override; - } - std::string serialize() const override { - if (! m_serialized_override.empty()) - return m_serialized_override; - std::ostringstream ss; for (Pointfs::const_iterator it = this->values.begin(); it != this->values.end(); ++it) { if (it - this->values.begin() != 0) ss << ","; @@ -1587,9 +1567,6 @@ public: std::vector vserialize() const override { - if (! m_serialized_override.empty()) - return { m_serialized_override }; - std::vector vv; for (Pointfs::const_iterator it = this->values.begin(); it != this->values.end(); ++it) { std::ostringstream ss; @@ -1605,24 +1582,13 @@ public: bool deserialize(const std::string &str, bool append = false) override { - if (! append) { - this->values.clear(); - m_serialized_override.clear(); - } - - const bool has_extended_bed_exclusion_syntax = str.find('|') != std::string::npos || (str.find("..") != std::string::npos && str.find(';') != std::string::npos); - if (has_extended_bed_exclusion_syntax && append) + // Extended exclusion-volume syntax belongs to the dedicated string option. + // Rejecting it here also makes --bed-exclude-area fail instead of silently + // turning a volume definition into malformed legacy points. + if (str.find('|') != std::string::npos || str.find(';') != std::string::npos || str.find("..") != std::string::npos) return false; - - if (has_extended_bed_exclusion_syntax) { - m_serialized_override = str; - // Multiple independent polygons have no valid representation in - // the legacy flat point array. Keep the serialized definition as - // the sole source of truth so old consumers cannot mistake their - // concatenated vertices for one polygon. - return true; - } - + if (! append) + this->values.clear(); std::istringstream is(str); std::string point_str; while (std::getline(is, point_str, ',')) { @@ -1640,45 +1606,21 @@ public: return true; } - size_t hash() const throw() override - { - size_t seed = 0; - std::hash point_hasher; - std::hash string_hasher; - for (const Vec2d &point : this->values) - boost::hash_combine(seed, point_hasher(point)); - boost::hash_combine(seed, string_hasher(m_serialized_override)); - return seed; - } - private: - std::string m_serialized_override; - friend class cereal::access; - template void save(Archive& archive, const std::uint32_t /* version */) const { + template void save(Archive& archive) const { size_t cnt = this->values.size(); archive(cnt); archive.saveBinary((const char*)this->values.data(), sizeof(Vec2d) * cnt); - archive(m_serialized_override); } - template void load(Archive& archive, const std::uint32_t version) { + template void load(Archive& archive) { size_t cnt; archive(cnt); this->values.assign(cnt, Vec2d()); archive.loadBinary((char*)this->values.data(), sizeof(Vec2d) * cnt); - if (version >= 1) - archive(m_serialized_override); - else - m_serialized_override.clear(); } }; -} // namespace Slic3r - -CEREAL_CLASS_VERSION(Slic3r::ConfigOptionPoints, 1); - -namespace Slic3r { - class ConfigOptionPoint3 : public ConfigOptionSingle { public: diff --git a/src/libslic3r/GCode.cpp b/src/libslic3r/GCode.cpp index fbdef80299..b084000e5d 100644 --- a/src/libslic3r/GCode.cpp +++ b/src/libslic3r/GCode.cpp @@ -294,10 +294,7 @@ static std::vector get_path_of_change_filament(const Print& print) Vec2d end_point = points[1]; // the cutter area size(18, 28) - if (has_bed_exclusion_volume_syntax(print.config().bed_exclude_area)) - return out_points; - - Pointfs excluse_area = print.config().bed_exclude_area.values; + Pointfs excluse_area = has_bed_exclude_volumes(print.config()) ? Pointfs{} : print.config().bed_exclude_area.values; if (excluse_area.size() != 4) return out_points; diff --git a/src/libslic3r/GCode/ExclusionVolumePathCheck.cpp b/src/libslic3r/GCode/ExclusionVolumePathCheck.cpp index f2f3bb9cbe..c795c5808c 100644 --- a/src/libslic3r/GCode/ExclusionVolumePathCheck.cpp +++ b/src/libslic3r/GCode/ExclusionVolumePathCheck.cpp @@ -114,7 +114,10 @@ void ExclusionVolumePathChecker::configure(const PrintConfig &config) std::vector &prepared = m_regions_by_extruder[extruder_id]; prepared.reserve(regions[extruder_id].size()); for (const BedExcludeRegion ®ion : regions[extruder_id]) { - if (region.polygon.points.size() < 3 || region.z_max < region.z_min) + // Legacy excluded areas are material keep-outs. Some stock profiles + // deliberately move the nozzle into them (for example, a cutter), so + // only explicitly configured collision volumes constrain motion. + if (!region.is_collision_volume() || region.polygon.points.size() < 3 || region.z_max < region.z_min) continue; PreparedRegion item; diff --git a/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.cpp b/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.cpp index 5fb7ca6b8b..3b001a12d7 100644 --- a/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.cpp +++ b/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.cpp @@ -410,6 +410,8 @@ void ExclusionVolumeTravelAvoidance::init(const PrintConfig &config, const Vec3d for (size_t extruder_id = 0; extruder_id < regions_by_extruder.size(); ++extruder_id) { RoutingSpace &space = m_spaces[extruder_id]; space.regions = std::move(regions_by_extruder[extruder_id]); + space.regions.erase(std::remove_if(space.regions.begin(), space.regions.end(), + [](const BedExcludeRegion ®ion) { return !region.is_collision_volume(); }), space.regions.end()); const Vec2d extruder_offset = extruder_id < config.extruder_offset.values.size() ? config.extruder_offset.values[extruder_id] : Vec2d::Zero(); diff --git a/src/libslic3r/GCode/GCodeProcessor.cpp b/src/libslic3r/GCode/GCodeProcessor.cpp index eb05146892..e2dbcb99b6 100644 --- a/src/libslic3r/GCode/GCodeProcessor.cpp +++ b/src/libslic3r/GCode/GCodeProcessor.cpp @@ -20,6 +20,8 @@ #include #include +#include +#include #include #include #include @@ -3176,7 +3178,7 @@ void GCodeProcessor::apply_config(const DynamicPrintConfig& config) //BBS: add bed_exclude_area const ConfigOptionPoints* bed_exclude_area = config.option("bed_exclude_area"); - if (bed_exclude_area != nullptr && !has_bed_exclusion_volume_syntax(*bed_exclude_area)) + if (bed_exclude_area != nullptr && !has_bed_exclude_volumes(config)) m_result.bed_exclude_area = bed_exclude_area->values; const ConfigOptionPoints* wrapping_exclude_area = config.option("wrapping_exclude_area"); @@ -6115,22 +6117,56 @@ void GCodeProcessor::process_G23(const GCodeReader::GCodeLine& line) store_move_vertex(EMoveType::Unretract); } +static std::array g28_homed_axes(const GCodeReader::GCodeLine &line) +{ + std::array homed { false, false, false }; + std::string_view raw = line.raw(); + const size_t command_end = raw.find_first_of(" \t;"); + size_t pos = command_end == std::string_view::npos ? raw.size() : command_end; + + while (pos < raw.size()) { + pos = raw.find_first_not_of(" \t", pos); + if (pos == std::string_view::npos || raw[pos] == ';') + break; + const size_t end = raw.find_first_of(" \t;", pos); + const std::string_view word = raw.substr(pos, end == std::string_view::npos ? raw.size() - pos : end - pos); + + const bool compact_axes = !word.empty() && std::all_of(word.begin(), word.end(), [](const char c) { + const char upper = static_cast(std::toupper(static_cast(c))); + return upper == 'X' || upper == 'Y' || upper == 'Z'; + }); + if (compact_axes) { + for (const char c : word) + homed[static_cast(std::toupper(static_cast(c)) - 'X')] = true; + } else if (!word.empty()) { + const char axis = static_cast(std::toupper(static_cast(word.front()))); + const bool numeric_axis_word = word.size() > 1 && + (std::isdigit(static_cast(word[1])) || word[1] == '+' || word[1] == '-' || word[1] == '.'); + if (axis >= 'X' && axis <= 'Z' && numeric_axis_word) + homed[static_cast(axis - 'X')] = true; + } + + if (end == std::string_view::npos || raw[end] == ';') + break; + pos = end; + } + return homed; +} + void GCodeProcessor::process_G28(const GCodeReader::GCodeLine& line) { std::string_view cmd = line.cmd(); std::string new_line_raw = { cmd.data(), cmd.size() }; - bool found = false; - if (line.has('X')) { + const std::array homed = g28_homed_axes(line); + const bool found = std::any_of(homed.begin(), homed.end(), [](const bool value) { return value; }); + if (homed[X]) { new_line_raw += " X0"; - found = true; } - if (line.has('Y')) { + if (homed[Y]) { new_line_raw += " Y0"; - found = true; } - if (line.has('Z')) { + if (homed[Z]) { new_line_raw += " Z0"; - found = true; } if (!found) new_line_raw += " X0 Y0 Z0"; @@ -6146,7 +6182,7 @@ void GCodeProcessor::process_G28(const GCodeReader::GCodeLine& line) // zero. Wait for a subsequent explicit absolute coordinate before checking // a path from any homed axis. for (unsigned char axis = X; axis <= Z; ++axis) { - if (!found || line.has(static_cast(axis))) { + if (!found || homed[axis]) { m_axis_position_known[axis] = false; m_axis_origin_known[axis] = true; } diff --git a/src/libslic3r/Model.cpp b/src/libslic3r/Model.cpp index 9c9dbd76e3..b0d96428d9 100644 --- a/src/libslic3r/Model.cpp +++ b/src/libslic3r/Model.cpp @@ -3105,7 +3105,7 @@ void Model::setPrintSpeedTable(const DynamicPrintConfig& config, const PrintConf //auto print_config = print.config(); //printSpeedMap.bed_poly.points = get_bed_shape(*(wxGetApp().plater()->config())); printSpeedMap.bed_poly.points = get_bed_shape(config); - Pointfs excluse_area_points = has_bed_exclusion_volume_syntax(print_config.bed_exclude_area) ? Pointfs{} : print_config.bed_exclude_area.values; + Pointfs excluse_area_points = has_bed_exclude_volumes(print_config) ? Pointfs{} : print_config.bed_exclude_area.values; Polygons exclude_polys; Polygon exclude_poly; for (int i = 0; i < excluse_area_points.size(); i++) { diff --git a/src/libslic3r/Preset.cpp b/src/libslic3r/Preset.cpp index e98e459162..e578a3e840 100644 --- a/src/libslic3r/Preset.cpp +++ b/src/libslic3r/Preset.cpp @@ -1440,7 +1440,7 @@ static std::vector s_Preset_machine_limits_options { static std::vector s_Preset_printer_options { "printer_technology", "printable_area", "extruder_printable_area", "support_parallel_printheads", "parallel_printheads_count", "parallel_printheads_bed_exclude_areas", - "bed_exclude_area_mode", "bed_exclude_area", "extruder_bed_exclude_area", "bed_custom_texture", "bed_custom_model", "gcode_flavor", + "bed_exclude_area", "bed_exclude_volumes", "bed_exclude_volume_mode", "extruder_bed_exclude_volumes", "bed_custom_texture", "bed_custom_model", "gcode_flavor", "gcode_skip_config_block", "fan_kickstart", "part_cooling_fan_min_pwm", "fan_speedup_time", "fan_speedup_overhangs", "single_extruder_multi_material", "manual_filament_change", "file_start_gcode", "machine_start_gcode", "machine_end_gcode", "before_layer_change_gcode", "printing_by_object_gcode", "layer_change_gcode", "time_lapse_gcode", "wrapping_detection_gcode", "change_filament_gcode", "change_extrusion_role_gcode", "printer_model", "printer_variant", "printer_extruder_id", "printer_extruder_variant", "extruder_variant_list", "default_nozzle_volume_type", diff --git a/src/libslic3r/Print.cpp b/src/libslic3r/Print.cpp index cb6b28eebc..d11defb03b 100644 --- a/src/libslic3r/Print.cpp +++ b/src/libslic3r/Print.cpp @@ -187,11 +187,6 @@ bool Print::invalidate_state_by_config_options(const ConfigOptionResolver & /* n "reduce_crossing_wall", "max_travel_detour_distance", "printable_area", - //BBS: add bed_exclude_area - "bed_exclude_area_mode", - "bed_exclude_area", - "extruder_bed_exclude_area", - "extruder_offset", "thumbnail_size", "before_layer_change_gcode", "enable_pressure_advance", @@ -215,7 +210,6 @@ bool Print::invalidate_state_by_config_options(const ConfigOptionResolver & /* n "extruder_clearance_radius", "nozzle_height", "extruder_colour", - "extruder_offset", "filament_flow_ratio", "reduce_fan_stop_start_freq", "dont_slow_down_outer_wall", @@ -337,13 +331,27 @@ bool Print::invalidate_state_by_config_options(const ConfigOptionResolver & /* n }; static std::unordered_set steps_ignore; + static const std::unordered_set steps_exclusion_geometry = { + "bed_exclude_area", + "bed_exclude_volumes", + "bed_exclude_volume_mode", + "extruder_bed_exclude_volumes", + "extruder_offset" + }; std::vector steps; std::vector osteps; bool invalidated = false; for (const t_config_option_key &opt_key : opt_keys) { - if (steps_gcode.find(opt_key) != steps_gcode.end()) { + if (steps_exclusion_geometry.find(opt_key) != steps_exclusion_geometry.end()) { + // Exclusions are consumed while generating brims, support, tree + // support and wipe-tower geometry, not only during final export. + steps.emplace_back(psWipeTower); + steps.emplace_back(psSkirtBrim); + osteps.emplace_back(posSupportMaterial); + osteps.emplace_back(posSimplifySupportPath); + } else if (steps_gcode.find(opt_key) != steps_gcode.end()) { // These options only affect G-code export or they are just notes without influence on the generated G-code, // so there is nothing to invalidate. steps.emplace_back(psGCodeExport); @@ -3298,7 +3306,7 @@ void Print::_make_skirt() brim_exclusion_regions.begin(), brim_exclusion_regions.end(), [](const std::vector ®ions) { return !regions.empty(); }); const bool has_nozzle_specific_brim_exclusions = has_brim_exclusions && - m_config.bed_exclude_area_mode.value != BedExcludeAreaMode::Shared; + active_bed_exclude_volume_mode(m_config) != BedExcludeVolumeMode::Shared; auto make_brims_for_skirt_brim_group = [this, &brim_exclusion_regions, has_nozzle_specific_brim_exclusions] diff --git a/src/libslic3r/PrintConfig.cpp b/src/libslic3r/PrintConfig.cpp index a5a8076a1a..a4ab2e0127 100644 --- a/src/libslic3r/PrintConfig.cpp +++ b/src/libslic3r/PrintConfig.cpp @@ -9,6 +9,8 @@ #include "GCode/Thumbnails.hpp" #include +#include +#include #include #include #include @@ -641,12 +643,12 @@ static const t_config_enum_values s_keys_map_FilamentMapMode = { }; CONFIG_OPTION_ENUM_DEFINE_STATIC_MAPS(FilamentMapMode) -static const t_config_enum_values s_keys_map_BedExcludeAreaMode = { - { "shared", int(BedExcludeAreaMode::Shared) }, - { "toolhead_offset", int(BedExcludeAreaMode::ToolheadOffset) }, - { "per_extruder", int(BedExcludeAreaMode::PerExtruder) } +static const t_config_enum_values s_keys_map_BedExcludeVolumeMode = { + { "shared", int(BedExcludeVolumeMode::Shared) }, + { "toolhead_offset", int(BedExcludeVolumeMode::ToolheadOffset) }, + { "per_extruder", int(BedExcludeVolumeMode::PerExtruder) } }; -CONFIG_OPTION_ENUM_DEFINE_STATIC_MAPS(BedExcludeAreaMode) +CONFIG_OPTION_ENUM_DEFINE_STATIC_MAPS(BedExcludeVolumeMode) // PrimeVolumeMode. Serialized string keys must stay stable; they round-trip through .3mf. static const t_config_enum_values s_keys_map_PrimeVolumeMode = { @@ -882,29 +884,37 @@ void PrintConfigDef::init_common_params() def->mode = comAdvanced; def->set_default_value(new ConfigOptionStrings()); - def = this->add("bed_exclude_area_mode", coEnum); - def->label = L("Exclusion volume behaviour"); - def->tooltip = L("Choose whether all nozzles use the same exclusion volumes, derive toolhead-relative volumes from each nozzle's XY offset, or configure independent volumes for every extruder."); - def->enum_keys_map = &ConfigOptionEnum::get_enum_values(); - def->enum_values = { "shared", "toolhead_offset", "per_extruder" }; - def->enum_labels = { L("Shared"), L("Toolhead-relative (nozzle offsets)"), L("Individual per extruder") }; - def->mode = comAdvanced; - def->set_default_value(new ConfigOptionEnum(BedExcludeAreaMode::Shared)); - //BBS: add "bed_exclude_area" def = this->add("bed_exclude_area", coPoints); - def->label = L("Excluded bed area"); + def->label = L("Excluded bed area (legacy)"); def->tooltip = L("Unprintable area in XY plane. For example, X1 Series printers use the front left corner to cut filament during filament change. " - "The area is expressed as polygon by points in following format: \"XxY, XxY, ...\". " - "Use \"ZMIN..ZMAX;XxY, XxY, ...\" for a 3D Z-limited exclusion volume. " - "Separate multiple areas or volumes with \"|\". "); + "The area is expressed as a polygon in the format \"XxY, XxY, ...\". Legacy areas keep generated material and models out, " + "but do not check or reroute machine travel. Configure exclusion volumes below for full collision checking."); def->mode = comAdvanced; def->gui_type = ConfigOptionDef::GUIType::one_string; def->set_default_value(new ConfigOptionPoints{ Vec2d(0, 0) }); - def = this->add("extruder_bed_exclude_area", coStrings); + def = this->add("bed_exclude_volumes", coString); + def->label = L("Exclusion volumes"); + def->tooltip = L("Collision volumes used for model and generated-material exclusion, G-code checking, and travel avoidance. " + "Use \"XxY, XxY, ...\" for a full-height polygon or \"ZMIN..ZMAX;XxY, XxY, ...\" for a Z-limited volume. " + "Separate multiple volumes with \"|\". When configured, these volumes take precedence over the legacy excluded bed area."); + def->mode = comAdvanced; + def->gui_type = ConfigOptionDef::GUIType::one_string; + def->set_default_value(new ConfigOptionString()); + + def = this->add("bed_exclude_volume_mode", coEnum); + def->label = L("Exclusion volume behaviour"); + def->tooltip = L("Choose whether all nozzles use the same exclusion volumes, derive toolhead-relative volumes from each nozzle's XY offset, or configure independent volumes for every extruder."); + def->enum_keys_map = &ConfigOptionEnum::get_enum_values(); + def->enum_values = { "shared", "toolhead_offset", "per_extruder" }; + def->enum_labels = { L("Shared"), L("Toolhead-relative (nozzle offsets)"), L("Individual per extruder") }; + def->mode = comAdvanced; + def->set_default_value(new ConfigOptionEnum(BedExcludeVolumeMode::Shared)); + + def = this->add("extruder_bed_exclude_volumes", coStrings); def->label = L("Extruder exclusion volumes"); - def->tooltip = L("Exclusion volumes used only by this extruder in individual mode. Use the same polygon and optional Z-range format as the shared excluded bed area. Leave empty for no exclusion volumes on this extruder."); + def->tooltip = L("Collision volumes used only by this extruder in individual mode. Use the same polygon and optional Z-range format as the shared exclusion volumes. Leave empty for no exclusion volumes on this extruder."); def->mode = comAdvanced; def->gui_type = ConfigOptionDef::GUIType::one_string; def->set_default_value(new ConfigOptionStrings{ "" }); @@ -8236,7 +8246,7 @@ void PrintConfigDef::init_extruder_option_keys() "default_filament_profile", "default_nozzle_volume_type", "deretraction_speed", - "extruder_bed_exclude_area", + "extruder_bed_exclude_volumes", "extruder_colour", "extruder_offset", "extruder_printable_height", @@ -9407,7 +9417,7 @@ std::set printer_extruder_options = { "nozzle_diameter", "default_nozzle_volume_type", "extruder_printable_area", - "extruder_bed_exclude_area", + "extruder_bed_exclude_volumes", "extruder_printable_height", "min_layer_height", "max_layer_height", @@ -11576,17 +11586,23 @@ std::map validate(const FullPrintConfig &cfg, bool und break; } - if (cfg.bed_exclude_area_mode.value == BedExcludeAreaMode::ToolheadOffset && + const bool collision_volumes_enabled = has_bed_exclude_volumes(cfg); + if (cfg.bed_exclude_volume_mode.value != BedExcludeVolumeMode::PerExtruder && + !cfg.bed_exclude_volumes.value.empty() && + !is_valid_bed_exclude_volumes_string(cfg.bed_exclude_volumes.value, cfg.printable_height.value)) { + error_message.emplace("bed_exclude_volumes", L("Invalid exclusion volume definition.")); + } + if (collision_volumes_enabled && cfg.bed_exclude_volume_mode.value == BedExcludeVolumeMode::ToolheadOffset && cfg.extruder_offset.size() < cfg.nozzle_diameter.size()) { error_message.emplace("extruder_offset", L("A nozzle offset is required for every extruder when toolhead-relative exclusion volumes are enabled.")); } - if (cfg.bed_exclude_area_mode.value == BedExcludeAreaMode::PerExtruder) { - if (cfg.extruder_bed_exclude_area.size() < cfg.nozzle_diameter.size()) { - error_message.emplace("extruder_bed_exclude_area", L("An exclusion-volume entry is required for every extruder. An entry may be empty when that extruder has no exclusion volumes.")); + if (collision_volumes_enabled && cfg.bed_exclude_volume_mode.value == BedExcludeVolumeMode::PerExtruder) { + if (cfg.extruder_bed_exclude_volumes.size() < cfg.nozzle_diameter.size()) { + error_message.emplace("extruder_bed_exclude_volumes", L("An exclusion-volume entry is required for every extruder. An entry may be empty when that extruder has no exclusion volumes.")); } else { - for (const std::string &entry : cfg.extruder_bed_exclude_area.values) { - if (!is_valid_bed_exclude_area_string(entry, cfg.printable_height.value)) { - error_message.emplace("extruder_bed_exclude_area", L("Invalid per-extruder exclusion volume definition.")); + for (const std::string &entry : cfg.extruder_bed_exclude_volumes.values) { + if (!is_valid_bed_exclude_volumes_string(entry, cfg.printable_height.value)) { + error_message.emplace("extruder_bed_exclude_volumes", L("Invalid per-extruder exclusion volume definition.")); break; } } @@ -12775,7 +12791,7 @@ Points get_bed_shape(const SLAPrinterConfig &cfg) { return to_points(make_counte namespace { -static bool is_bed_exclusion_volume_syntax(const std::string &value) +static bool looks_like_bed_exclusion_volume_syntax(const std::string &value) { return value.find('|') != std::string::npos || (value.find("..") != std::string::npos && value.find(';') != std::string::npos); } @@ -12832,14 +12848,33 @@ static bool parse_z_range_token( static std::optional parse_exclude_polygon_points(const std::string &points_str) { - ConfigOptionPoints points; - if (! points.deserialize(points_str) || points.values.size() < 3) + Pointfs points; + std::vector point_tokens; + boost::split(point_tokens, points_str, boost::is_any_of(",")); + points.reserve(point_tokens.size()); + for (std::string point_token : point_tokens) { + boost::trim(point_token); + const size_t separator = point_token.find('x'); + if (separator == std::string::npos || point_token.find('x', separator + 1) != std::string::npos) + return std::nullopt; + + double x = 0.0; + double y = 0.0; + if (!parse_double_token(point_token.substr(0, separator), x) || + !parse_double_token(point_token.substr(separator + 1), y) || + !std::isfinite(x) || !std::isfinite(y)) + return std::nullopt; + points.emplace_back(x, y); + } + if (points.size() < 3) return std::nullopt; Polygon polygon; - polygon.points.reserve(points.values.size()); - for (const Vec2d &pt : points.values) + polygon.points.reserve(points.size()); + for (const Vec2d &pt : points) polygon.points.emplace_back(scale_(pt.x()), scale_(pt.y())); + if (polygon.area() == 0.0) + return std::nullopt; polygon.make_counter_clockwise(); return polygon; } @@ -12858,7 +12893,8 @@ static void append_legacy_bed_exclude_regions( polygon.points.emplace_back(scale_(pt.x()), scale_(pt.y())); polygon.make_counter_clockwise(); - out.push_back({ std::move(polygon), 0.0, printable_height, false, false }); + out.push_back({ std::move(polygon), 0.0, printable_height, + BedExcludeRegion::Purpose::MaterialKeepout, false }); } static void append_bed_exclusion_volume_regions( @@ -12921,50 +12957,54 @@ static void append_bed_exclusion_volume_regions( if (! polygon) continue; - out.push_back({ std::move(*polygon), z_min, z_max, true, has_z_range }); + out.push_back({ std::move(*polygon), z_min, z_max, + BedExcludeRegion::Purpose::CollisionVolume, has_z_range }); } } -static std::vector get_bed_excluded_regions_impl( +static bool has_nonempty_string(const std::string &value) +{ + return std::any_of(value.begin(), value.end(), [](const char c) { return !std::isspace(static_cast(c)); }); +} + +static bool collision_volumes_configured( + const std::string &shared_specs, + const BedExcludeVolumeMode mode, + const std::vector &per_extruder_specs) +{ + if (mode == BedExcludeVolumeMode::PerExtruder) + return std::any_of(per_extruder_specs.begin(), per_extruder_specs.end(), has_nonempty_string); + return has_nonempty_string(shared_specs); +} + +static std::vector parse_master_bed_excluded_regions( const Pointfs &legacy_points, - const std::string ®ion_specs, + const std::string &shared_specs, + const bool use_collision_volumes, const double printable_height) { std::vector regions; const double height = std::max(0.0, printable_height); - append_legacy_bed_exclude_regions(regions, legacy_points, height); - append_bed_exclusion_volume_regions(regions, region_specs, height); + if (use_collision_volumes) + append_bed_exclusion_volume_regions(regions, shared_specs, height); + else + append_legacy_bed_exclude_regions(regions, legacy_points, height); return regions; } -static std::vector parse_master_bed_excluded_regions( - const ConfigOptionPoints *option, - const double printable_height) -{ - if (option == nullptr) - return {}; - - const std::string serialized = option->serialize(); - const bool volume_syntax = is_bed_exclusion_volume_syntax(serialized); - return get_bed_excluded_regions_impl( - volume_syntax ? Pointfs{} : option->values, - volume_syntax ? serialized : std::string{}, - printable_height); -} - static std::vector resolve_bed_excluded_regions( const std::vector &master_regions, - const BedExcludeAreaMode mode, + const BedExcludeVolumeMode mode, const std::vector &per_extruder_specs, const std::vector &extruder_offsets, const size_t reference_extruder, const size_t extruder_id, const double printable_height) { - if (mode == BedExcludeAreaMode::Shared) + if (mode == BedExcludeVolumeMode::Shared) return master_regions; - if (mode == BedExcludeAreaMode::PerExtruder) { + if (mode == BedExcludeVolumeMode::PerExtruder) { if (extruder_id >= per_extruder_specs.size() || per_extruder_specs[extruder_id].empty()) return {}; @@ -12997,12 +13037,12 @@ static size_t bed_exclusion_extruder_count( } static std::vector flatten_bed_excluded_regions( - const BedExcludeAreaMode mode, + const BedExcludeVolumeMode mode, std::vector> regions_by_extruder) { if (regions_by_extruder.empty()) return {}; - if (mode == BedExcludeAreaMode::Shared) + if (mode == BedExcludeVolumeMode::Shared) return std::move(regions_by_extruder.front()); size_t total = 0; @@ -13046,17 +13086,22 @@ std::vector> get_bed_excluded_regions_by_extruder( { const ConfigOptionFloat *height_option = cfg.opt("printable_height"); const double printable_height = height_option != nullptr ? height_option->value : 0.0; - const std::vector master_regions = parse_master_bed_excluded_regions( - cfg.opt("bed_exclude_area"), printable_height); - - const BedExcludeAreaMode mode = cfg.has("bed_exclude_area_mode") ? - cfg.opt_enum("bed_exclude_area_mode") : BedExcludeAreaMode::Shared; - const ConfigOptionStrings *per_extruder_option = cfg.opt("extruder_bed_exclude_area"); + const ConfigOptionPoints *legacy_option = cfg.opt("bed_exclude_area"); + const ConfigOptionString *shared_option = cfg.opt("bed_exclude_volumes"); + const BedExcludeVolumeMode configured_mode = cfg.has("bed_exclude_volume_mode") ? + cfg.opt_enum("bed_exclude_volume_mode") : BedExcludeVolumeMode::Shared; + const ConfigOptionStrings *per_extruder_option = cfg.opt("extruder_bed_exclude_volumes"); const ConfigOptionPoints *offset_option = cfg.opt("extruder_offset"); const ConfigOptionFloats *nozzle_option = cfg.opt("nozzle_diameter"); const ConfigOptionInt *reference_option = cfg.opt("master_extruder_id"); + const Pointfs legacy_points = legacy_option != nullptr ? legacy_option->values : Pointfs{}; + const std::string shared_specs = shared_option != nullptr ? shared_option->value : std::string{}; const std::vector per_extruder_specs = per_extruder_option != nullptr ? per_extruder_option->values : std::vector{}; + const bool use_collision_volumes = collision_volumes_configured(shared_specs, configured_mode, per_extruder_specs); + const BedExcludeVolumeMode active_mode = use_collision_volumes ? configured_mode : BedExcludeVolumeMode::Shared; + const std::vector master_regions = parse_master_bed_excluded_regions( + legacy_points, shared_specs, use_collision_volumes, printable_height); const std::vector offsets = offset_option != nullptr ? offset_option->values : std::vector{}; const size_t count = bed_exclusion_extruder_count( nozzle_option != nullptr ? nozzle_option->size() : 0, @@ -13066,23 +13111,29 @@ std::vector> get_bed_excluded_regions_by_extruder( std::vector> result; result.reserve(count); for (size_t extruder_id = 0; extruder_id < count; ++extruder_id) - result.emplace_back(resolve_bed_excluded_regions(master_regions, mode, per_extruder_specs, offsets, reference, extruder_id, printable_height)); + result.emplace_back(resolve_bed_excluded_regions(master_regions, active_mode, per_extruder_specs, offsets, reference, extruder_id, printable_height)); return result; } std::vector> get_bed_excluded_regions_by_extruder(const PrintConfig &cfg) { const double printable_height = cfg.printable_height.value; - const std::vector master_regions = parse_master_bed_excluded_regions(&cfg.bed_exclude_area, printable_height); + const bool use_collision_volumes = collision_volumes_configured( + cfg.bed_exclude_volumes.value, cfg.bed_exclude_volume_mode.value, + cfg.extruder_bed_exclude_volumes.values); + const BedExcludeVolumeMode active_mode = use_collision_volumes ? + cfg.bed_exclude_volume_mode.value : BedExcludeVolumeMode::Shared; + const std::vector master_regions = parse_master_bed_excluded_regions( + cfg.bed_exclude_area.values, cfg.bed_exclude_volumes.value, use_collision_volumes, printable_height); const size_t count = bed_exclusion_extruder_count( - cfg.nozzle_diameter.size(), cfg.extruder_offset.size(), cfg.extruder_bed_exclude_area.size()); + cfg.nozzle_diameter.size(), cfg.extruder_offset.size(), cfg.extruder_bed_exclude_volumes.size()); const size_t reference = cfg.master_extruder_id.value > 0 ? size_t(cfg.master_extruder_id.value - 1) : 0; std::vector> result; result.reserve(count); for (size_t extruder_id = 0; extruder_id < count; ++extruder_id) { result.emplace_back(resolve_bed_excluded_regions( - master_regions, cfg.bed_exclude_area_mode.value, cfg.extruder_bed_exclude_area.values, + master_regions, active_mode, cfg.extruder_bed_exclude_volumes.values, cfg.extruder_offset.values, reference, extruder_id, printable_height)); } return result; @@ -13102,22 +13153,20 @@ std::vector get_bed_excluded_regions(const PrintConfig &cfg, c std::vector get_bed_excluded_regions(const DynamicPrintConfig &cfg) { - const BedExcludeAreaMode mode = cfg.has("bed_exclude_area_mode") ? - cfg.opt_enum("bed_exclude_area_mode") : BedExcludeAreaMode::Shared; - return flatten_bed_excluded_regions(mode, get_bed_excluded_regions_by_extruder(cfg)); + return flatten_bed_excluded_regions(active_bed_exclude_volume_mode(cfg), get_bed_excluded_regions_by_extruder(cfg)); } std::vector get_bed_excluded_regions(const PrintConfig &cfg) { - return flatten_bed_excluded_regions(cfg.bed_exclude_area_mode.value, get_bed_excluded_regions_by_extruder(cfg)); + return flatten_bed_excluded_regions(active_bed_exclude_volume_mode(cfg), get_bed_excluded_regions_by_extruder(cfg)); } -bool has_bed_exclusion_volume_syntax(const ConfigOptionPoints& bed_exclude_area) +bool is_bed_exclusion_volume_syntax(const std::string &value) { - return is_bed_exclusion_volume_syntax(bed_exclude_area.serialize()); + return looks_like_bed_exclusion_volume_syntax(value); } -bool is_valid_bed_exclude_area_string(const std::string &value, const double printable_height) +bool is_valid_bed_exclude_volumes_string(const std::string &value, const double printable_height) { if (value.empty()) return true; @@ -13138,6 +13187,36 @@ bool is_valid_bed_exclude_area_string(const std::string &value, const double pri return found_nonempty; } +bool has_bed_exclude_volumes(const DynamicPrintConfig &cfg) +{ + const ConfigOptionString *shared = cfg.opt("bed_exclude_volumes"); + const ConfigOptionStrings *per_extruder = cfg.opt("extruder_bed_exclude_volumes"); + const BedExcludeVolumeMode mode = cfg.has("bed_exclude_volume_mode") ? + cfg.opt_enum("bed_exclude_volume_mode") : BedExcludeVolumeMode::Shared; + return collision_volumes_configured( + shared != nullptr ? shared->value : std::string{}, mode, + per_extruder != nullptr ? per_extruder->values : std::vector{}); +} + +bool has_bed_exclude_volumes(const PrintConfig &cfg) +{ + return collision_volumes_configured( + cfg.bed_exclude_volumes.value, cfg.bed_exclude_volume_mode.value, + cfg.extruder_bed_exclude_volumes.values); +} + +BedExcludeVolumeMode active_bed_exclude_volume_mode(const DynamicPrintConfig &cfg) +{ + if (!has_bed_exclude_volumes(cfg) || !cfg.has("bed_exclude_volume_mode")) + return BedExcludeVolumeMode::Shared; + return cfg.opt_enum("bed_exclude_volume_mode"); +} + +BedExcludeVolumeMode active_bed_exclude_volume_mode(const PrintConfig &cfg) +{ + return has_bed_exclude_volumes(cfg) ? cfg.bed_exclude_volume_mode.value : BedExcludeVolumeMode::Shared; +} + Polygons get_bed_excluded_area(const PrintConfig& cfg) { const std::vector regions = get_bed_excluded_regions(cfg); diff --git a/src/libslic3r/PrintConfig.hpp b/src/libslic3r/PrintConfig.hpp index 109d1544ad..fd2fcf692e 100644 --- a/src/libslic3r/PrintConfig.hpp +++ b/src/libslic3r/PrintConfig.hpp @@ -532,7 +532,7 @@ enum FilamentMapMode { // Defines how bed exclusion volumes are resolved for printers with multiple // independently positioned nozzles/toolheads. -enum class BedExcludeAreaMode { +enum class BedExcludeVolumeMode { Shared = 0, ToolheadOffset, PerExtruder @@ -1765,9 +1765,10 @@ PRINT_CONFIG_CLASS_DERIVED_DEFINE( ((ConfigOptionInt, parallel_printheads_count)) ((ConfigOptionStrings, parallel_printheads_bed_exclude_areas)) //BBS: add bed_exclude_area - ((ConfigOptionEnum, bed_exclude_area_mode)) ((ConfigOptionPoints, bed_exclude_area)) - ((ConfigOptionStrings, extruder_bed_exclude_area)) + ((ConfigOptionString, bed_exclude_volumes)) + ((ConfigOptionEnum, bed_exclude_volume_mode)) + ((ConfigOptionStrings, extruder_bed_exclude_volumes)) ((ConfigOptionPoints, head_wrap_detect_zone)) // BBS ((ConfigOptionString, bed_custom_texture)) @@ -2314,11 +2315,18 @@ Points get_bed_shape(const DynamicPrintConfig &cfg, bool use_share = true); Points get_bed_shape(const PrintConfig &cfg, bool use_share = false); Points get_bed_shape(const SLAPrinterConfig &cfg); struct BedExcludeRegion { + enum class Purpose { + MaterialKeepout, + CollisionVolume + }; + Polygon polygon; double z_min { 0.0 }; double z_max { 0.0 }; - bool from_3d_config { false }; + Purpose purpose { Purpose::MaterialKeepout }; bool has_z_range { false }; + + bool is_collision_volume() const { return purpose == Purpose::CollisionVolume; } }; std::vector get_bed_excluded_regions(const DynamicPrintConfig& cfg); std::vector get_bed_excluded_regions(const PrintConfig& cfg); @@ -2332,8 +2340,12 @@ std::vector> get_bed_excluded_regions_by_extruder( int bed_exclusion_extruder_for_filament(size_t filament_id, const std::vector &configured_map, FilamentMapMode map_mode, bool is_bambu, bool automatic_map_resolved, size_t extruder_count); -bool has_bed_exclusion_volume_syntax(const ConfigOptionPoints& bed_exclude_area); -bool is_valid_bed_exclude_area_string(const std::string &value, double printable_height); +bool is_bed_exclusion_volume_syntax(const std::string &value); +bool is_valid_bed_exclude_volumes_string(const std::string &value, double printable_height); +bool has_bed_exclude_volumes(const DynamicPrintConfig &cfg); +bool has_bed_exclude_volumes(const PrintConfig &cfg); +BedExcludeVolumeMode active_bed_exclude_volume_mode(const DynamicPrintConfig &cfg); +BedExcludeVolumeMode active_bed_exclude_volume_mode(const PrintConfig &cfg); Slic3r::Polygons get_bed_excluded_area(const PrintConfig& cfg); Slic3r::Polygon get_bed_shape_with_excluded_area(const PrintConfig& cfg, bool use_share = false); bool has_skirt(const DynamicPrintConfig& cfg); diff --git a/src/slic3r/GUI/ConfigWizard.cpp b/src/slic3r/GUI/ConfigWizard.cpp index c9255da2b2..4ada874c41 100644 --- a/src/slic3r/GUI/ConfigWizard.cpp +++ b/src/slic3r/GUI/ConfigWizard.cpp @@ -2637,7 +2637,7 @@ ConfigWizard::ConfigWizard(wxWindow *parent) p->load_vendors(); //BBS: add bed exclude areas p->custom_config.reset(DynamicPrintConfig::new_from_defaults_keys({ - "gcode_flavor", "printable_area", "bed_exclude_area_mode", "bed_exclude_area", "extruder_bed_exclude_area", + "gcode_flavor", "printable_area", "bed_exclude_area", "bed_exclude_volumes", "bed_exclude_volume_mode", "extruder_bed_exclude_volumes", "bed_custom_texture", "bed_custom_model", "nozzle_diameter", "filament_diameter", "thumbnails" //, "nozzle_temperature", "bed_temperature" })); diff --git a/src/slic3r/GUI/Field.cpp b/src/slic3r/GUI/Field.cpp index a4146f33a0..6282dee392 100644 --- a/src/slic3r/GUI/Field.cpp +++ b/src/slic3r/GUI/Field.cpp @@ -684,9 +684,9 @@ void Field::get_value_by_opt_type(wxString& str, const bool check_value/* = true m_value = into_u8(str); } break; - } else if (m_opt.opt_key == "extruder_bed_exclude_area") { + } else if (m_opt.opt_key == "bed_exclude_volumes" || m_opt.opt_key == "extruder_bed_exclude_volumes") { const std::string definition = into_u8(str); - if (!is_valid_bed_exclude_area_string(definition, std::numeric_limits::max())) { + if (!is_valid_bed_exclude_volumes_string(definition, std::numeric_limits::max())) { show_error(m_parent, _L("Invalid exclusion volume format. Use XxY, XxY, ... or ZMIN..ZMAX;XxY, XxY, ... and separate multiple volumes with |.")); const std::string old_value = m_value.empty() ? std::string{} : boost::any_cast(m_value); set_value(from_u8(old_value), true); @@ -784,7 +784,7 @@ void Field::get_value_by_opt_type(wxString& str, const bool check_value/* = true if (!m_value.empty() && boost::any_cast>(&m_value) != nullptr) text_value = get_thumbnails_string(boost::any_cast>(m_value)); set_value(text_value, true); - show_error(m_parent, format_wxstr(_L("Invalid format. Expected vector format: \"%1%\""), m_opt_id == "bed_exclude_area" ? "XxY, XxY, ... or ZMIN..ZMAX;XxY, XxY, ..." : "XxY, XxY, ...")); + show_error(m_parent, format_wxstr(_L("Invalid format. Expected vector format: \"%1%\""), "XxY, XxY, ...")); } } diff --git a/src/slic3r/GUI/Jobs/ArrangeJob.cpp b/src/slic3r/GUI/Jobs/ArrangeJob.cpp index df11be8563..4c0c1c0694 100644 --- a/src/slic3r/GUI/Jobs/ArrangeJob.cpp +++ b/src/slic3r/GUI/Jobs/ArrangeJob.cpp @@ -25,7 +25,7 @@ void set_arrange_polygon_bed_exclusion_extruders(ArrangePolygon &polygon, const const PartPlate &plate, const DynamicPrintConfig &config) { polygon.bed_exclusion_extruder_ids.clear(); - if (config.opt_enum("bed_exclude_area_mode") == BedExcludeAreaMode::Shared) + if (active_bed_exclude_volume_mode(config) == BedExcludeVolumeMode::Shared) return; const ConfigOptionFloats *nozzle_diameters = config.opt("nozzle_diameter"); @@ -57,7 +57,7 @@ static void set_arrange_polygon_bed_exclusion_extruders_for_all_plates(ArrangePo const DynamicPrintConfig &config) { polygon.bed_exclusion_extruder_ids.clear(); - if (config.opt_enum("bed_exclude_area_mode") == BedExcludeAreaMode::Shared) + if (active_bed_exclude_volume_mode(config) == BedExcludeVolumeMode::Shared) return; std::set extruder_ids; diff --git a/src/slic3r/GUI/PartPlate.cpp b/src/slic3r/GUI/PartPlate.cpp index c45c8e6e4c..719d7ac92a 100644 --- a/src/slic3r/GUI/PartPlate.cpp +++ b/src/slic3r/GUI/PartPlate.cpp @@ -1093,7 +1093,7 @@ void PartPlate::render_exclude_area(bool force_default_color) { // the other extruders' regions hollow. const DynamicPrintConfig *config = m_plater != nullptr ? m_plater->config() : nullptr; if (config != nullptr && - config->opt_enum("bed_exclude_area_mode") != BedExcludeAreaMode::Shared) + active_bed_exclude_volume_mode(*config) != BedExcludeVolumeMode::Shared) return; ColorRGBA select_color{ .9f, .86f, .82f, .7f }; // ORCA @@ -1164,7 +1164,7 @@ std::string PartPlate::exclusion_volume_preview_cache_key(const std::vector regions; for (const std::vector &extruder_regions : regions_by_extruder) regions.insert(regions.end(), extruder_regions.begin(), extruder_regions.end()); - const BedExcludeAreaMode mode = config->opt_enum("bed_exclude_area_mode"); + const BedExcludeVolumeMode mode = active_bed_exclude_volume_mode(*config); // A coloured border communicates which physical nozzle owns a footprint. // With only one nozzle the exclusion applies to every filament, so using // the first filament colour would incorrectly imply material ownership. const bool show_nozzle_ownership = - regions_by_extruder.size() > 1 && mode != BedExcludeAreaMode::Shared; + regions_by_extruder.size() > 1 && mode != BedExcludeVolumeMode::Shared; std::ostringstream grouped_key; grouped_key << exclusion_volume_preview_cache_key(regions) << "mode:" << int(mode) << ";groups:"; for (const std::vector &group : regions_by_extruder) @@ -1345,7 +1345,7 @@ void PartPlate::update_exclusion_volume_preview_models() for (size_t extruder_id = 0; extruder_id < regions_by_extruder.size(); ++extruder_id) { // Shared regions are identical for every nozzle. Keeping one copy // avoids duplicate floor, prism and intersection geometry. - if (mode == BedExcludeAreaMode::Shared && extruder_id > 0) + if (mode == BedExcludeVolumeMode::Shared && extruder_id > 0) break; for (const BedExcludeRegion ®ion_src : regions_by_extruder[extruder_id]) { @@ -1360,7 +1360,7 @@ void PartPlate::update_exclusion_volume_preview_models() // In non-shared modes these resolved regions are the authoritative bed // preview, including legacy master polygons duplicated by nozzle offset. // Shared legacy polygons continue to use m_exclude_triangles above. - if (region_src.from_3d_config || mode != BedExcludeAreaMode::Shared) { + if (region_src.is_collision_volume() || mode != BedExcludeVolumeMode::Shared) { if (!region_src.has_z_range || region_src.z_min <= EPSILON) { floor_regions.emplace_back(region); } else { @@ -1400,7 +1400,7 @@ void PartPlate::update_exclusion_volume_preview_models() continue; std::set relevant_extruders; - if (mode != BedExcludeAreaMode::Shared) { + if (mode != BedExcludeVolumeMode::Shared) { for (const auto &mapping : get_object_filament_extruders( *object, project_config, regions_by_extruder.size())) relevant_extruders.emplace(mapping.second); @@ -1409,7 +1409,7 @@ void PartPlate::update_exclusion_volume_preview_models() Polygon hull = instance->convex_hull_2d(); const BoundingBoxf3 instance_box = object->instance_convex_hull_bounding_box(instance_id); for (const PreviewRegion &preview_region : preview_regions) { - if (mode != BedExcludeAreaMode::Shared && + if (mode != BedExcludeVolumeMode::Shared && relevant_extruders.find(preview_region.extruder_id) == relevant_extruders.end()) continue; @@ -3457,16 +3457,16 @@ bool PartPlate::check_outside(int obj_id, int instance_id, BoundingBoxf3* boundi if (config != nullptr) { const std::vector> regions_by_extruder = get_bed_excluded_regions_by_extruder(*config); - const BedExcludeAreaMode mode = config->opt_enum("bed_exclude_area_mode"); + const BedExcludeVolumeMode mode = active_bed_exclude_volume_mode(*config); // The legacy outside flag has no filament/nozzle context. Keep it // authoritative for the shared mode, but let the newer per-extruder // placement pipeline handle offset/individual modes so a collision // belonging to an unused nozzle does not block the whole plate. - checked_config_regions = mode != BedExcludeAreaMode::Shared; + checked_config_regions = mode != BedExcludeVolumeMode::Shared; const Point plate_offset(scale_(m_origin.x()), scale_(m_origin.y())); Polygon hull = instance->convex_hull_2d(); - const size_t groups_to_check = mode == BedExcludeAreaMode::Shared && !regions_by_extruder.empty() ? 1 : 0; + const size_t groups_to_check = mode == BedExcludeVolumeMode::Shared && !regions_by_extruder.empty() ? 1 : 0; for (size_t group_id = 0; group_id < groups_to_check; ++group_id) { const std::vector &extruder_regions = regions_by_extruder[group_id]; checked_config_regions = checked_config_regions || !extruder_regions.empty(); @@ -6492,15 +6492,13 @@ bool PartPlateList::preprocess_exclude_areas(arrangement::ArrangePolygons &unsel } added = true; } - const BedExcludeAreaMode mode = config.opt_enum("bed_exclude_area_mode"); - const ConfigOptionPoints *configured_areas = config.opt("bed_exclude_area"); - const bool use_resolved_regions = mode != BedExcludeAreaMode::Shared || - (configured_areas != nullptr && has_bed_exclusion_volume_syntax(*configured_areas)); + const BedExcludeVolumeMode mode = active_bed_exclude_volume_mode(config); + const bool use_resolved_regions = has_bed_exclude_volumes(config); if (use_resolved_regions) { const std::vector> regions_by_extruder = get_bed_excluded_regions_by_extruder(config); - const size_t extruder_count = mode == BedExcludeAreaMode::Shared ? + const size_t extruder_count = mode == BedExcludeVolumeMode::Shared ? std::min(1, regions_by_extruder.size()) : regions_by_extruder.size(); for (size_t extruder_id = 0; extruder_id < extruder_count; ++extruder_id) { @@ -6517,7 +6515,7 @@ bool PartPlateList::preprocess_exclude_areas(arrangement::ArrangePolygons &unsel blocker.rotation = 0.0; blocker.is_virt_object = true; blocker.is_bed_exclusion = true; - blocker.bed_exclusion_extruder_id = mode == BedExcludeAreaMode::Shared ? -1 : int(extruder_id); + blocker.bed_exclusion_extruder_id = mode == BedExcludeVolumeMode::Shared ? -1 : int(extruder_id); blocker.bed_idx = plate_idx; blocker.height = std::max(0.0, region.z_max - region.z_min); blocker.z_min = region.z_min; diff --git a/src/slic3r/GUI/Plater.cpp b/src/slic3r/GUI/Plater.cpp index 7c52c7f81c..7fbc77193b 100644 --- a/src/slic3r/GUI/Plater.cpp +++ b/src/slic3r/GUI/Plater.cpp @@ -7331,7 +7331,7 @@ Plater::priv::priv(Plater *q, MainFrame *main_frame) , main_frame(main_frame) //BBS: add bed_exclude_area , config(Slic3r::DynamicPrintConfig::new_from_defaults_keys({ - "printable_area", "bed_exclude_area_mode", "bed_exclude_area", "extruder_bed_exclude_area", "extruder_offset", + "printable_area", "bed_exclude_area", "bed_exclude_volumes", "bed_exclude_volume_mode", "extruder_bed_exclude_volumes", "extruder_offset", "wrapping_exclude_area", "extruder_printable_area", "bed_custom_texture", "bed_custom_model", "print_sequence", "extruder_clearance_radius", "extruder_clearance_height_to_lid", "extruder_clearance_height_to_rod", @@ -20082,8 +20082,8 @@ void Plater::on_config_change(const DynamicPrintConfig &config) } p->config->set_key_value(opt_key, config.option(opt_key)->clone()); - if (opt_key == "bed_exclude_area_mode" || opt_key == "bed_exclude_area" || - opt_key == "extruder_bed_exclude_area" || opt_key == "extruder_offset" || + if (opt_key == "bed_exclude_volume_mode" || opt_key == "bed_exclude_area" || + opt_key == "bed_exclude_volumes" || opt_key == "extruder_bed_exclude_volumes" || opt_key == "extruder_offset" || opt_key == "master_extruder_id" || opt_key == "nozzle_diameter" || opt_key == "printable_height" || opt_key == "extruder_colour") exclusion_preview_changed = true; @@ -20099,8 +20099,8 @@ void Plater::on_config_change(const DynamicPrintConfig &config) p->partplate_list.invalid_all_slice_result(); } //BBS: add bed_exclude_area - else if (opt_key == "printable_area" || opt_key == "bed_exclude_area_mode" || opt_key == "bed_exclude_area" - || opt_key == "extruder_bed_exclude_area" || opt_key == "extruder_offset" + else if (opt_key == "printable_area" || opt_key == "bed_exclude_volume_mode" || opt_key == "bed_exclude_area" + || opt_key == "bed_exclude_volumes" || opt_key == "extruder_bed_exclude_volumes" || opt_key == "extruder_offset" || opt_key == "bed_custom_texture" || opt_key == "bed_custom_model" || opt_key == "extruder_clearance_height_to_lid" || opt_key == "extruder_clearance_height_to_rod") { @@ -20239,7 +20239,7 @@ void Plater::set_bed_shape() const const ConfigOptionPoints *bed_exclude_area = p->config->option("bed_exclude_area"); set_bed_shape(p->config->option("printable_area")->values, //BBS: add bed exclude areas - has_bed_exclusion_volume_syntax(*bed_exclude_area) ? Pointfs{} : bed_exclude_area->values, + has_bed_exclude_volumes(*p->config) ? Pointfs{} : bed_exclude_area->values, p->config->option("wrapping_exclude_area")->values, p->config->option("printable_height")->value, p->config->option("extruder_printable_area")->values, diff --git a/src/slic3r/GUI/Tab.cpp b/src/slic3r/GUI/Tab.cpp index fdaadda0fd..25bf93efea 100644 --- a/src/slic3r/GUI/Tab.cpp +++ b/src/slic3r/GUI/Tab.cpp @@ -1805,6 +1805,54 @@ void Tab::on_value_change(const std::string& opt_key, const boost::any& value) return; } + // A legacy point option cannot represent multiple or Z-limited regions. If + // that syntax is pasted into the legacy field, offer an explicit, atomic + // conversion rather than silently changing its meaning based on syntax. + if (opt_key == "bed_exclude_area" && m_type == Preset::TYPE_PRINTER) { + const std::string *definition = boost::any_cast(&value); + if (definition != nullptr && is_bed_exclusion_volume_syntax(*definition)) { + const double printable_height = m_config->opt_float("printable_height"); + if (!is_valid_bed_exclude_volumes_string(*definition, printable_height)) { + show_error(wxGetApp().plater(), _L("Invalid exclusion volume format. Use XxY, XxY, ... or ZMIN..ZMAX;XxY, XxY, ... and separate multiple volumes with |.")); + reload_config(); + return; + } + + MessageDialog dialog( + wxGetApp().plater(), + _L("This definition contains collision-volume syntax. Convert it to exclusion volumes and enable G-code checking and travel avoidance?"), + _L("Convert exclusion volumes"), wxICON_QUESTION | wxYES | wxNO); + if (dialog.ShowModal() == wxID_YES) { + DynamicPrintConfig converted = *m_config; + converted.set_key_value("bed_exclude_volumes", new ConfigOptionString(*definition)); + converted.set_key_value("bed_exclude_volume_mode", + new ConfigOptionEnum(BedExcludeVolumeMode::Shared)); + converted.set_key_value("bed_exclude_area", new ConfigOptionPoints()); + load_config(converted); + on_presets_changed(); + wxGetApp().plater()->update(); + } else { + reload_config(); + } + return; + } + } + + // Editing the dedicated collision-volume fields is an explicit opt-in to + // the new behaviour. Keep presets unambiguous by removing any legacy area; + // the resolver still gives volumes precedence when externally authored + // profiles contain both keys. + if (m_type == Preset::TYPE_PRINTER && + (opt_key == "bed_exclude_volumes" || opt_key.rfind("extruder_bed_exclude_volumes#", 0) == 0)) { + const std::string *definition = boost::any_cast(&value); + const ConfigOptionPoints *legacy = m_config->option("bed_exclude_area"); + if (definition != nullptr && !definition->empty() && legacy != nullptr && !legacy->values.empty()) { + DynamicPrintConfig converted = *m_config; + converted.set_key_value("bed_exclude_area", new ConfigOptionPoints()); + m_config_manipulation.apply(m_config, &converted); + } + } + // Keep this preset's "plugins" manifest in sync when a plugin picker changes, so full_config() and // save_to_json() always find resolved "name;uuid;capability" references and rebuild it nowhere else. // Also drop any plugin config override entries for a capability the change just stopped @@ -1827,21 +1875,20 @@ void Tab::on_value_change(const std::string& opt_key, const boost::any& value) printer_tab->on_gcode_flavor_changed(); } - if (opt_key == "bed_exclude_area_mode" && m_type == Preset::TYPE_PRINTER && - m_config->opt_enum("bed_exclude_area_mode") == BedExcludeAreaMode::PerExtruder) { - auto *per_extruder = m_config->option("extruder_bed_exclude_area"); - const auto *shared = m_config->option("bed_exclude_area"); + if (opt_key == "bed_exclude_volume_mode" && m_type == Preset::TYPE_PRINTER && + m_config->opt_enum("bed_exclude_volume_mode") == BedExcludeVolumeMode::PerExtruder) { + auto *per_extruder = m_config->option("extruder_bed_exclude_volumes"); + const auto *shared = m_config->option("bed_exclude_volumes"); const size_t extruder_count = m_config->option("nozzle_diameter")->size(); const bool definitions_empty = per_extruder == nullptr || std::all_of(per_extruder->values.begin(), per_extruder->values.end(), [](const std::string &entry) { return entry.empty(); }); if (definitions_empty && shared != nullptr && extruder_count > 0) { - const std::string serialized = shared->serialize(); - const bool valid_shared_definition = shared->values.size() >= 3 || - (has_bed_exclusion_volume_syntax(*shared) && - is_valid_bed_exclude_area_string(serialized, std::numeric_limits::max())); + const std::string serialized = shared->value; + const bool valid_shared_definition = + is_valid_bed_exclude_volumes_string(serialized, std::numeric_limits::max()); DynamicPrintConfig new_conf = *m_config; - new_conf.set_key_value("extruder_bed_exclude_area", + new_conf.set_key_value("extruder_bed_exclude_volumes", new ConfigOptionStrings(std::vector(extruder_count, valid_shared_definition ? serialized : std::string{}))); m_config_manipulation.apply(m_config, &new_conf); } @@ -5023,10 +5070,44 @@ void TabPrinter::build_fff() return create_bed_shape_widget(parent); }); optgroup->append_single_option_line("parallel_printheads_count"); - optgroup->append_single_option_line("bed_exclude_area_mode"); Option option = optgroup->get_option("bed_exclude_area"); option.opt.full_width = true; optgroup->append_single_option_line(option, "printer_basic_information_printable_space#excluded-bed-area"); + Line convert_exclusion_line = Line{ L("Collision checking"), L("Convert the legacy excluded bed area into a collision volume so Orca can check G-code moves and reroute travel around it.") }; + convert_exclusion_line.widget = [this](wxWindow *parent) { + Button *button = new Button(parent, _L("Convert area to collision volume")); + button->Bind(wxEVT_BUTTON, [this](wxCommandEvent &) { + const ConfigOptionPoints *legacy = m_config->option("bed_exclude_area"); + if (legacy == nullptr || legacy->values.size() < 3) { + show_error(wxGetApp().plater(), _L("Configure a valid excluded bed area before converting it.")); + return; + } + + const std::string definition = legacy->serialize(); + MessageDialog dialog( + wxGetApp().plater(), + _L("Convert this legacy excluded bed area into a full-height collision volume? This enables G-code checking and travel avoidance."), + _L("Convert exclusion volume"), wxICON_QUESTION | wxYES | wxNO); + if (dialog.ShowModal() != wxID_YES) + return; + + DynamicPrintConfig converted = *m_config; + converted.set_key_value("bed_exclude_volumes", new ConfigOptionString(definition)); + converted.set_key_value("bed_exclude_volume_mode", + new ConfigOptionEnum(BedExcludeVolumeMode::Shared)); + converted.set_key_value("bed_exclude_area", new ConfigOptionPoints()); + load_config(converted); + on_presets_changed(); + wxGetApp().plater()->update(); + }); + return button; + }; + optgroup->append_line(convert_exclusion_line); + + Option volume_option = optgroup->get_option("bed_exclude_volumes"); + volume_option.opt.full_width = true; + optgroup->append_single_option_line(volume_option); + optgroup->append_single_option_line("bed_exclude_volume_mode"); // optgroup->append_single_option_line("printable_area"); optgroup->append_single_option_line("printable_height", "printer_basic_information_printable_space#printable-height"); optgroup->append_single_option_line("support_multi_bed_types","printer_basic_information_printable_space#support-multi-bed-types"); @@ -5660,7 +5741,7 @@ if (is_marlin_flavor) option.opt.full_width = true; optgroup->append_single_option_line(option, "printer_extruder_basic_information#extruder-offset-position"); - Option exclusion_option = optgroup->get_option("extruder_bed_exclude_area", extruder_idx); + Option exclusion_option = optgroup->get_option("extruder_bed_exclude_volumes", extruder_idx); exclusion_option.opt.full_width = true; optgroup->append_single_option_line(exclusion_option, "printer_basic_information_printable_space#excluded-bed-area"); @@ -6092,9 +6173,11 @@ void TabPrinter::toggle_options() toggle_line("parallel_printheads_count", support_parallel_printheads); const size_t exclusion_extruder_count = m_preset_bundle->get_printer_extruder_count(); - const BedExcludeAreaMode exclusion_mode = m_config->opt_enum("bed_exclude_area_mode"); - toggle_line("bed_exclude_area_mode", exclusion_extruder_count > 1); - toggle_line("bed_exclude_area", exclusion_extruder_count <= 1 || exclusion_mode != BedExcludeAreaMode::PerExtruder); + const bool collision_volumes_enabled = has_bed_exclude_volumes(*m_config); + const BedExcludeVolumeMode exclusion_mode = active_bed_exclude_volume_mode(*m_config); + toggle_option("bed_exclude_area", !collision_volumes_enabled); + toggle_line("bed_exclude_volume_mode", collision_volumes_enabled && exclusion_extruder_count > 1); + toggle_line("bed_exclude_volumes", exclusion_extruder_count <= 1 || exclusion_mode != BedExcludeVolumeMode::PerExtruder); toggle_line("fan_direction", m_config->opt_bool("auxiliary_fan")); @@ -6153,8 +6236,9 @@ void TabPrinter::toggle_options() toggle_option("extruder_printable_area", false, i); // disable toggle_line("extruder_printable_area", m_preset_bundle->get_printer_extruder_count() == 2, i); //hide - const bool per_extruder_exclusions = m_config->opt_enum("bed_exclude_area_mode") == BedExcludeAreaMode::PerExtruder; - toggle_line("extruder_bed_exclude_area", m_preset_bundle->get_printer_extruder_count() > 1 && per_extruder_exclusions, i); + const bool per_extruder_exclusions = has_bed_exclude_volumes(*m_config) && + active_bed_exclude_volume_mode(*m_config) == BedExcludeVolumeMode::PerExtruder; + toggle_line("extruder_bed_exclude_volumes", m_preset_bundle->get_printer_extruder_count() > 1 && per_extruder_exclusions, i); toggle_option("extruder_printable_height", false, i); toggle_line("extruder_printable_height", m_preset_bundle->get_printer_extruder_count() == 2, i); diff --git a/tests/fff_print/test_exclusion_volumes.cpp b/tests/fff_print/test_exclusion_volumes.cpp index 981eeea6c4..83f43fe6b8 100644 --- a/tests/fff_print/test_exclusion_volumes.cpp +++ b/tests/fff_print/test_exclusion_volumes.cpp @@ -24,7 +24,7 @@ using Catch::Matchers::WithinAbs; namespace { DynamicPrintConfig exclusion_config( - BedExcludeAreaMode mode = BedExcludeAreaMode::Shared, + BedExcludeVolumeMode mode = BedExcludeVolumeMode::Shared, const std::string &shared = "0..10;40x40,60x40,60x60,40x60", const std::vector &per_extruder = {}) { @@ -38,10 +38,18 @@ DynamicPrintConfig exclusion_config( config.set_key_value("printable_area", new ConfigOptionPoints{ Vec2d(0.0, 0.0), Vec2d(100.0, 0.0), Vec2d(100.0, 100.0), Vec2d(0.0, 100.0), }); - config.set_key_value("bed_exclude_area_mode", new ConfigOptionEnum(mode)); - config.set_deserialize_strict("bed_exclude_area", shared); + config.set_key_value("bed_exclude_volume_mode", new ConfigOptionEnum(mode)); + config.set_key_value("bed_exclude_volumes", new ConfigOptionString(shared)); if (!per_extruder.empty()) - config.set_key_value("extruder_bed_exclude_area", new ConfigOptionStrings(per_extruder)); + config.set_key_value("extruder_bed_exclude_volumes", new ConfigOptionStrings(per_extruder)); + return config; +} + +DynamicPrintConfig legacy_exclusion_config() +{ + DynamicPrintConfig config = exclusion_config(); + config.set_key_value("bed_exclude_volumes", new ConfigOptionString()); + config.set_deserialize_strict("bed_exclude_area", "40x40,60x40,60x60,40x60"); return config; } @@ -227,7 +235,7 @@ struct BrimRun BrimRun generate_brim(const std::string &exclusion_definition) { - DynamicPrintConfig config = exclusion_config(BedExcludeAreaMode::Shared, exclusion_definition); + DynamicPrintConfig config = exclusion_config(BedExcludeVolumeMode::Shared, exclusion_definition); config.set_deserialize_strict({ {"skirt_loops", "0"}, {"brim_type", "outer_only"}, @@ -260,7 +268,7 @@ BrimRun generate_brim(const std::string &exclusion_definition) DynamicPrintConfig support_config(int support_filament, int interface_filament) { DynamicPrintConfig config = exclusion_config( - BedExcludeAreaMode::PerExtruder, "", + BedExcludeVolumeMode::PerExtruder, "", {"0..10;4x4,12x4,12x12,4x12", "0..10;22x4,30x4,30x12,22x12"}); // PrintObject clamps support role ids against the number of logical // filaments, represented by filament_diameter in the static config. @@ -322,6 +330,23 @@ TEST_CASE("Path checker ignores clear motions and motions outside the active Z s } } +TEST_CASE("Legacy excluded areas do not constrain machine motion", "[ExclusionVolume][GCode][Compatibility]") +{ + const FullPrintConfig config = static_config(legacy_exclusion_config()); + const Polyline direct = travel({Vec2d(20.0, 50.0), Vec2d(80.0, 50.0)}); + + auto checker = configured_checker(config); + check_motion(checker, Vec3d(20.0, 50.0, 5.0), Vec3d(80.0, 50.0, 5.0)); + CHECK_FALSE(checker.result().has_any_conflict); + + ExclusionVolumeTravelAvoidance router; + router.init(config, Vec3d::Zero()); + const auto route = router.route(direct, 5.0, 5.0, 0); + CHECK(route.status == ExclusionVolumeTravelAvoidance::Status::Unchanged); + CHECK(route.detail == ExclusionVolumeTravelAvoidance::Detail::NoActiveObstacles); + CHECK(route.path.points == direct.points); +} + TEST_CASE("Path checker detects crossing inside and boundary motions", "[ExclusionVolume][GCode]") { const FullPrintConfig config = static_config(exclusion_config()); @@ -386,7 +411,7 @@ TEST_CASE("Path checker handles unknown coordinates conservatively without inven TEST_CASE("Path checker selects the active nozzle and applies its XY offset", "[ExclusionVolume][GCode][MultiNozzle]") { DynamicPrintConfig dynamic = exclusion_config( - BedExcludeAreaMode::PerExtruder, "", {"", "0..10;40x40,60x40,60x60,40x60"}); + BedExcludeVolumeMode::PerExtruder, "", {"", "0..10;40x40,60x40,60x60,40x60"}); dynamic.set_key_value("extruder_offset", new ConfigOptionPoints{Vec2d::Zero(), Vec2d(20.0, 0.0)}); const FullPrintConfig config = static_config(dynamic); @@ -482,7 +507,7 @@ TEST_CASE("Travel router reports unsafe endpoints unknown tools and blocked beds SECTION("obstacle separates the bed") { ExclusionVolumeTravelAvoidance router; router.init(static_config(exclusion_config( - BedExcludeAreaMode::Shared, "0..10;45x0,55x0,55x100,45x100")), Vec3d::Zero()); + BedExcludeVolumeMode::Shared, "0..10;45x0,55x0,55x100,45x100")), Vec3d::Zero()); const auto result = router.route(travel({Vec2d(20.0, 50.0), Vec2d(80.0, 50.0)}), 5.0, 5.0, 0); CHECK(result.status == ExclusionVolumeTravelAvoidance::Status::Failed); } @@ -491,7 +516,7 @@ TEST_CASE("Travel router reports unsafe endpoints unknown tools and blocked beds TEST_CASE("Travel router uses only the active nozzle exclusion set", "[ExclusionVolume][TravelRouting][MultiNozzle]") { const FullPrintConfig config = static_config(exclusion_config( - BedExcludeAreaMode::PerExtruder, "", {"0..10;40x40,60x40,60x60,40x60", ""})); + BedExcludeVolumeMode::PerExtruder, "", {"0..10;40x40,60x40,60x60,40x60", ""})); ExclusionVolumeTravelAvoidance router; router.init(config, Vec3d::Zero()); const Polyline direct = travel({Vec2d(20.0, 50.0), Vec2d(80.0, 50.0)}); @@ -539,6 +564,17 @@ TEST_CASE("G-code processor tracks absolute relative and reset coordinate state" const ProcessorExclusionResult result = run_processor(config, "G28\nG1 X80 Y50 Z5\n"); CHECK_FALSE(result.conflict); } + + SECTION("all supported homing-axis spellings make the homed position unknown") { + const std::string homing = GENERATE( + std::string("G28"), std::string("G28 X"), std::string("G28 X Y"), + std::string("G28 XY"), std::string("G28 X0 Y0"), std::string("G28 XYZ"), + std::string("G28 Z P0"), std::string("G28 Z Z_OFFSET -0.07"), + std::string("G28 W")); + const ProcessorExclusionResult result = run_processor( + config, "G90\nG1 X20 Y50 Z5\n" + homing + "\nG1 X80 Y50 Z5\n"); + CHECK_FALSE(result.conflict); + } } TEST_CASE("G-code processor classifies extrusion conflicts", "[ExclusionVolume][GCodeProcessor]") @@ -555,7 +591,7 @@ TEST_CASE("G-code processor classifies extrusion conflicts", "[ExclusionVolume][ TEST_CASE("G-code processor changes the active physical nozzle at tool selection", "[ExclusionVolume][GCodeProcessor][MultiNozzle]") { const FullPrintConfig config = static_config(exclusion_config( - BedExcludeAreaMode::PerExtruder, "", {"", "0..10;40x40,60x40,60x60,40x60"})); + BedExcludeVolumeMode::PerExtruder, "", {"", "0..10;40x40,60x40,60x60,40x60"})); const ProcessorExclusionResult first_tool = run_processor(config, "G90\nT0\nG1 X20 Y50 Z5\nG1 X80 Y50\n"); CHECK_FALSE(first_tool.conflict); diff --git a/tests/fff_print/test_print.cpp b/tests/fff_print/test_print.cpp index 3bc027ebb5..b87fce5f95 100644 --- a/tests/fff_print/test_print.cpp +++ b/tests/fff_print/test_print.cpp @@ -120,7 +120,7 @@ size_t count_opt_key(const std::vector& warnings, const s } DynamicPrintConfig dual_extruder_exclusion_config( - BedExcludeAreaMode mode, + BedExcludeVolumeMode mode, const std::vector &per_extruder, const std::vector &filament_map = {1}) { @@ -129,8 +129,8 @@ DynamicPrintConfig dual_extruder_exclusion_config( config.set_key_value("nozzle_diameter", new ConfigOptionFloats{0.4, 0.4}); config.set_key_value("extruder_offset", new ConfigOptionPoints{Vec2d::Zero(), Vec2d(20.0, 0.0)}); config.set_key_value("extruder_printable_height", new ConfigOptionFloatsNullable{256.0, 256.0}); - config.set_key_value("bed_exclude_area_mode", new ConfigOptionEnum(mode)); - config.set_key_value("extruder_bed_exclude_area", new ConfigOptionStrings(per_extruder)); + config.set_key_value("bed_exclude_volume_mode", new ConfigOptionEnum(mode)); + config.set_key_value("extruder_bed_exclude_volumes", new ConfigOptionStrings(per_extruder)); config.set_key_value("filament_map_mode", new ConfigOptionEnum(fmmManual)); config.set_key_value("filament_map", new ConfigOptionInts(filament_map)); return config; @@ -185,21 +185,21 @@ TEST_CASE("Print validation applies individual exclusion volumes to the mapped p SECTION("mapped colliding extruder is rejected") { const DynamicPrintConfig config = dual_extruder_exclusion_config( - BedExcludeAreaMode::PerExtruder, {colliding, ""}, {1}); + BedExcludeVolumeMode::PerExtruder, {colliding, ""}, {1}); const StringObjectException error = validate_cubes(config, warnings); CHECK(error.string.find("extruder 1") != std::string::npos); } SECTION("mapped clear extruder is accepted") { const DynamicPrintConfig config = dual_extruder_exclusion_config( - BedExcludeAreaMode::PerExtruder, {colliding, ""}, {2}); + BedExcludeVolumeMode::PerExtruder, {colliding, ""}, {2}); const StringObjectException error = validate_cubes(config, warnings); CHECK(error.string.empty()); } SECTION("an unrelated nozzle exclusion does not reject the object") { const DynamicPrintConfig config = dual_extruder_exclusion_config( - BedExcludeAreaMode::PerExtruder, {"", colliding}, {1}); + BedExcludeVolumeMode::PerExtruder, {"", colliding}, {1}); const StringObjectException error = validate_cubes(config, warnings); CHECK(error.string.empty()); } @@ -210,25 +210,36 @@ TEST_CASE("Print validation applies shared exclusions and ignores volumes above std::vector warnings; SECTION("shared volume intersects") { - DynamicPrintConfig config = dual_extruder_exclusion_config(BedExcludeAreaMode::Shared, {"", ""}, {2}); - config.set_deserialize_strict("bed_exclude_area", "0..30;-100x-100,300x-100,300x300,-100x300"); + DynamicPrintConfig config = dual_extruder_exclusion_config(BedExcludeVolumeMode::Shared, {"", ""}, {2}); + config.set_key_value("bed_exclude_volumes", new ConfigOptionString("0..30;-100x-100,300x-100,300x300,-100x300")); const StringObjectException error = validate_cubes(config, warnings); CHECK(error.string.find("extruder 2") != std::string::npos); } SECTION("elevated shared volume clears a 20mm cube") { - DynamicPrintConfig config = dual_extruder_exclusion_config(BedExcludeAreaMode::Shared, {"", ""}, {1}); - config.set_deserialize_strict("bed_exclude_area", "30..50;-100x-100,300x-100,300x300,-100x300"); + DynamicPrintConfig config = dual_extruder_exclusion_config(BedExcludeVolumeMode::Shared, {"", ""}, {1}); + config.set_key_value("bed_exclude_volumes", new ConfigOptionString("30..50;-100x-100,300x-100,300x300,-100x300")); const StringObjectException error = validate_cubes(config, warnings); CHECK(error.string.empty()); } } +TEST_CASE("Legacy excluded areas retain object placement validation", "[Print][ExclusionVolume][Compatibility]") +{ + DynamicPrintConfig config = dual_extruder_exclusion_config( + BedExcludeVolumeMode::Shared, {"", ""}, {1}); + config.set_deserialize_strict("bed_exclude_area", "-100x-100,300x-100,300x300,-100x300"); + + std::vector warnings; + const StringObjectException error = validate_cubes(config, warnings); + CHECK_FALSE(error.string.empty()); +} + TEST_CASE("Print validation checks every nozzle used by a multimaterial object", "[Print][ExclusionVolume][MultiNozzle]") { const std::string colliding = "0..256;-100x-100,300x-100,300x300,-100x300"; const DynamicPrintConfig config = dual_extruder_exclusion_config( - BedExcludeAreaMode::PerExtruder, {"", colliding}, {1, 2}); + BedExcludeVolumeMode::PerExtruder, {"", colliding}, {1, 2}); const StringObjectException error = validate_multimaterial_cube(config); CHECK(error.string.find("extruder 2") != std::string::npos); diff --git a/tests/libslic3r/test_3mf.cpp b/tests/libslic3r/test_3mf.cpp index f1fc5c0bf5..85ce5dc00a 100644 --- a/tests/libslic3r/test_3mf.cpp +++ b/tests/libslic3r/test_3mf.cpp @@ -159,10 +159,11 @@ TEST_CASE("Volumetric per-extruder exclusions survive a 3MF round-trip", "[3mf][ // exclusion settings and should not depend on unrelated printer-profile // defaults surviving the project archive round-trip. DynamicPrintConfig source; - source.set_key_value("bed_exclude_area_mode", - new ConfigOptionEnum(BedExcludeAreaMode::PerExtruder)); + source.set_key_value("bed_exclude_volume_mode", + new ConfigOptionEnum(BedExcludeVolumeMode::PerExtruder)); source.set_deserialize_strict("bed_exclude_area", "0x0,10x0,10x10,0x10"); - source.set_key_value("extruder_bed_exclude_area", new ConfigOptionStrings{ + source.set_key_value("bed_exclude_volumes", new ConfigOptionString("0..10;1x1,2x1,2x2,1x2")); + source.set_key_value("extruder_bed_exclude_volumes", new ConfigOptionStrings{ "0..25;5x5,15x5,15x15,5x15", "30..80;40x40,55x40,55x55,40x55|0..5;70x10,80x10,80x20,70x20", }); @@ -197,14 +198,18 @@ TEST_CASE("Volumetric per-extruder exclusions survive a 3MF round-trip", "[3mf][ release_PlateData_list(reloaded_plates); REQUIRE(loaded); - REQUIRE(reloaded.option>("bed_exclude_area_mode") != nullptr); - CHECK(reloaded.option>("bed_exclude_area_mode")->value == - BedExcludeAreaMode::PerExtruder); + REQUIRE(reloaded.option>("bed_exclude_volume_mode") != nullptr); + CHECK(reloaded.option>("bed_exclude_volume_mode")->value == + BedExcludeVolumeMode::PerExtruder); - const auto *areas = reloaded.option("extruder_bed_exclude_area"); + const auto *areas = reloaded.option("extruder_bed_exclude_volumes"); REQUIRE(areas != nullptr); REQUIRE(areas->values.size() == 2); - CHECK(areas->values == source.option("extruder_bed_exclude_area")->values); + CHECK(areas->values == source.option("extruder_bed_exclude_volumes")->values); + + const auto *shared_volumes = reloaded.option("bed_exclude_volumes"); + REQUIRE(shared_volumes != nullptr); + CHECK(shared_volumes->value == source.opt_string("bed_exclude_volumes")); const auto *legacy = reloaded.option("bed_exclude_area"); REQUIRE(legacy != nullptr); diff --git a/tests/libslic3r/test_exclusion_volumes.cpp b/tests/libslic3r/test_exclusion_volumes.cpp index db0f425506..e5ad6b5fff 100644 --- a/tests/libslic3r/test_exclusion_volumes.cpp +++ b/tests/libslic3r/test_exclusion_volumes.cpp @@ -30,7 +30,8 @@ Polygon rectangle(double min_x, double min_y, double max_x, double max_y) BedExcludeRegion region(double min_x, double min_y, double max_x, double max_y, double z_min, double z_max, bool has_z_range = true) { - return {rectangle(min_x, min_y, max_x, max_y), z_min, z_max, true, has_z_range}; + return {rectangle(min_x, min_y, max_x, max_y), z_min, z_max, + BedExcludeRegion::Purpose::CollisionVolume, has_z_range}; } DynamicPrintConfig two_extruder_config() @@ -42,7 +43,7 @@ DynamicPrintConfig two_extruder_config() config.set_key_value("extruder_printable_height", new ConfigOptionFloatsNullable{200.0, 200.0}); config.set_key_value("master_extruder_id", new ConfigOptionInt(1)); config.set_key_value("printable_height", new ConfigOptionFloat(200.0)); - config.set_deserialize_strict("bed_exclude_area", "10..30;0x0,10x0,10x10,0x10"); + config.set_key_value("bed_exclude_volumes", new ConfigOptionString("10..30;0x0,10x0,10x10,0x10")); return config; } @@ -86,27 +87,16 @@ TEST_CASE("Legacy exclusion polygons keep their point representation", "[Exclusi REQUIRE(option.deserialize("0x0,10x0,10x10,0x10")); REQUIRE(option.values.size() == 4); CHECK(option.serialize() == "0x0,10x0,10x10,0x10"); - CHECK_FALSE(has_bed_exclusion_volume_syntax(option)); + CHECK_FALSE(is_bed_exclusion_volume_syntax(option.serialize())); } -TEST_CASE("Extended exclusion definitions retain their serialized representation", "[ExclusionVolume][PrintConfig]") +TEST_CASE("Legacy point options reject collision-volume syntax", "[ExclusionVolume][PrintConfig]") { const std::string definition = "0..10;0x0,10x0,10x10,0x10|20x20,30x20,30x30,20x30"; ConfigOptionPoints option; - REQUIRE(option.deserialize(definition)); + CHECK_FALSE(option.deserialize(definition)); CHECK(option.values.empty()); - CHECK(option.serialize() == definition); - CHECK(option.vserialize() == std::vector{definition}); - CHECK(has_bed_exclusion_volume_syntax(option)); - - std::unique_ptr cloned(option.clone()); - REQUIRE(cloned != nullptr); - CHECK(*cloned == option); - CHECK(cloned->hash() == option.hash()); - - ConfigOptionPoints assigned; - assigned.set(&option); - CHECK(assigned == option); + CHECK(is_bed_exclusion_volume_syntax(definition)); } TEST_CASE("Exclusion syntax validation accepts supported forms and rejects malformed regions", "[ExclusionVolume][PrintConfig]") @@ -126,7 +116,7 @@ TEST_CASE("Exclusion syntax validation accepts supported forms and rejects malfo })); DYNAMIC_SECTION(definition) { - CHECK(is_valid_bed_exclude_area_string(definition, 200.0) == valid); + CHECK(is_valid_bed_exclude_volumes_string(definition, 200.0) == valid); } } @@ -134,9 +124,8 @@ TEST_CASE("Extended exclusion Z ranges are defaulted and clamped to printable he { DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); config.set_key_value("printable_height", new ConfigOptionFloat(100.0)); - config.set_deserialize_strict( - "bed_exclude_area", - "-20..25;0x0,10x0,10x10,0x10|75..150;20x0,30x0,30x10,20x10|..;40x0,50x0,50x10,40x10"); + config.set_key_value("bed_exclude_volumes", new ConfigOptionString( + "-20..25;0x0,10x0,10x10,0x10|75..150;20x0,30x0,30x10,20x10|..;40x0,50x0,50x10,40x10")); const std::vector regions = get_bed_excluded_regions(config); REQUIRE(regions.size() == 3); @@ -148,10 +137,88 @@ TEST_CASE("Extended exclusion Z ranges are defaulted and clamped to printable he CHECK_THAT(regions[2].z_max, WithinAbs(100.0, 1e-9)); } +TEST_CASE("CLI keeps legacy areas and collision volumes on separate options", "[ExclusionVolume][PrintConfig][CLI]") +{ + const char *legacy_area_argv[] = { + "orca-slicer", "--bed-exclude-area", "0x0,10x0,10x10,0x10" + }; + DynamicPrintAndCLIConfig legacy_area_config; + t_config_option_keys extra; + t_config_option_keys keys; + REQUIRE(legacy_area_config.read_cli(3, legacy_area_argv, &extra, &keys)); + REQUIRE(legacy_area_config.opt("bed_exclude_area") != nullptr); + CHECK(legacy_area_config.opt("bed_exclude_area")->values.size() == 4); + + const char *volume_argv[] = { + "orca-slicer", "--bed-exclude-volumes", "0..10;0x0,10x0,10x10,0x10" + }; + DynamicPrintAndCLIConfig volume_config; + extra.clear(); + keys.clear(); + REQUIRE(volume_config.read_cli(3, volume_argv, &extra, &keys)); + CHECK(volume_config.opt_string("bed_exclude_volumes") == volume_argv[2]); + + const char *legacy_argv[] = { + "orca-slicer", "--bed-exclude-area", "0..10;0x0,10x0,10x10,0x10" + }; + DynamicPrintAndCLIConfig legacy_config; + extra.clear(); + keys.clear(); + CHECK_FALSE(legacy_config.read_cli(3, legacy_argv, &extra, &keys)); +} + +TEST_CASE("Legacy areas remain material keep-outs until collision volumes are configured", "[ExclusionVolume][PrintConfig]") +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_key_value("printable_height", new ConfigOptionFloat(100.0)); + config.set_deserialize_strict("bed_exclude_area", "0x0,10x0,10x10,0x10"); + + auto regions = get_bed_excluded_regions(config); + REQUIRE(regions.size() == 1); + CHECK_FALSE(regions.front().is_collision_volume()); + CHECK_FALSE(has_bed_exclude_volumes(config)); + + config.set_key_value("bed_exclude_volumes", new ConfigOptionString("20x20,30x20,30x30,20x30")); + regions = get_bed_excluded_regions(config); + REQUIRE(regions.size() == 1); + CHECK(regions.front().is_collision_volume()); + CHECK(regions.front().polygon.contains(Point::new_scale(25.0, 25.0))); + CHECK_FALSE(regions.front().polygon.contains(Point::new_scale(5.0, 5.0))); +} + +TEST_CASE("A nonempty invalid collision-volume definition never falls back to the legacy area", "[ExclusionVolume][PrintConfig]") +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_deserialize_strict("bed_exclude_area", "0x0,10x0,10x10,0x10"); + config.set_key_value("bed_exclude_volumes", new ConfigOptionString("not a polygon")); + + CHECK(has_bed_exclude_volumes(config)); + CHECK(get_bed_excluded_regions(config).empty()); + CHECK_FALSE(is_valid_bed_exclude_volumes_string(config.opt_string("bed_exclude_volumes"), 100.0)); +} + +TEST_CASE("An empty collision-volume configuration falls back to the legacy area", "[ExclusionVolume][PrintConfig]") +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_num_extruders(2); + config.set_deserialize_strict("bed_exclude_area", "0x0,10x0,10x10,0x10"); + config.set_key_value("bed_exclude_volume_mode", + new ConfigOptionEnum(BedExcludeVolumeMode::PerExtruder)); + config.set_key_value("extruder_bed_exclude_volumes", new ConfigOptionStrings{"", ""}); + + CHECK_FALSE(has_bed_exclude_volumes(config)); + CHECK(active_bed_exclude_volume_mode(config) == BedExcludeVolumeMode::Shared); + const auto groups = get_bed_excluded_regions_by_extruder(config); + REQUIRE(groups.size() == 2); + REQUIRE(groups[0].size() == 1); + REQUIRE(groups[1].size() == 1); + CHECK_FALSE(groups[0][0].is_collision_volume()); +} + TEST_CASE("Shared exclusion volumes resolve identically for every extruder", "[ExclusionVolume][PrintConfig][MultiNozzle]") { DynamicPrintConfig config = two_extruder_config(); - config.set_key_value("bed_exclude_area_mode", new ConfigOptionEnum(BedExcludeAreaMode::Shared)); + config.set_key_value("bed_exclude_volume_mode", new ConfigOptionEnum(BedExcludeVolumeMode::Shared)); const auto groups = get_bed_excluded_regions_by_extruder(config); REQUIRE(groups.size() == 2); @@ -168,7 +235,7 @@ TEST_CASE("Shared exclusion volumes resolve identically for every extruder", "[E TEST_CASE("Toolhead-relative exclusion volumes follow nozzle offset deltas", "[ExclusionVolume][PrintConfig][MultiNozzle]") { DynamicPrintConfig config = two_extruder_config(); - config.set_key_value("bed_exclude_area_mode", new ConfigOptionEnum(BedExcludeAreaMode::ToolheadOffset)); + config.set_key_value("bed_exclude_volume_mode", new ConfigOptionEnum(BedExcludeVolumeMode::ToolheadOffset)); const auto groups = get_bed_excluded_regions_by_extruder(config); REQUIRE(groups.size() == 2); @@ -184,7 +251,7 @@ TEST_CASE("Toolhead-relative exclusions honour a non-default reference extruder" { DynamicPrintConfig config = two_extruder_config(); config.set_key_value("master_extruder_id", new ConfigOptionInt(2)); - config.set_key_value("bed_exclude_area_mode", new ConfigOptionEnum(BedExcludeAreaMode::ToolheadOffset)); + config.set_key_value("bed_exclude_volume_mode", new ConfigOptionEnum(BedExcludeVolumeMode::ToolheadOffset)); const auto groups = get_bed_excluded_regions_by_extruder(config); REQUIRE(groups.size() == 2); @@ -197,8 +264,8 @@ TEST_CASE("Toolhead-relative exclusions honour a non-default reference extruder" TEST_CASE("Individual exclusion volumes remain authoritative per extruder", "[ExclusionVolume][PrintConfig][MultiNozzle]") { DynamicPrintConfig config = two_extruder_config(); - config.set_key_value("bed_exclude_area_mode", new ConfigOptionEnum(BedExcludeAreaMode::PerExtruder)); - config.set_key_value("extruder_bed_exclude_area", new ConfigOptionStrings{ + config.set_key_value("bed_exclude_volume_mode", new ConfigOptionEnum(BedExcludeVolumeMode::PerExtruder)); + config.set_key_value("extruder_bed_exclude_volumes", new ConfigOptionStrings{ "0..25;0x0,8x0,8x8,0x8|40..60;20x20,30x20,30x30,20x30", "", }); @@ -214,9 +281,8 @@ TEST_CASE("Legacy bed helpers include only regions touching the first layer", "[ { DynamicPrintConfig dynamic = DynamicPrintConfig::full_print_config(); dynamic.set_key_value("printable_height", new ConfigOptionFloat(100.0)); - dynamic.set_deserialize_strict( - "bed_exclude_area", - "0..5;0x0,10x0,10x10,0x10|20..30;20x0,30x0,30x10,20x10"); + dynamic.set_key_value("bed_exclude_volumes", new ConfigOptionString( + "0..5;0x0,10x0,10x10,0x10|20..30;20x0,30x0,30x10,20x10")); PrintConfig config; config.apply(dynamic, true); From c3087a92f7d6b6a7da043102397164841da04c08 Mon Sep 17 00:00:00 2001 From: Harry Loud Date: Mon, 21 Sep 2026 13:41:54 +0100 Subject: [PATCH 26/38] Fix exclusion conversion row for current widget API --- src/slic3r/GUI/Tab.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/slic3r/GUI/Tab.cpp b/src/slic3r/GUI/Tab.cpp index 62b4e6d54a..ed9de1938f 100644 --- a/src/slic3r/GUI/Tab.cpp +++ b/src/slic3r/GUI/Tab.cpp @@ -5158,6 +5158,8 @@ void TabPrinter::build_fff() Line convert_exclusion_line = Line{ L("Collision checking"), L("Convert the legacy excluded bed area into a collision volume so Orca can check G-code moves and reroute travel around it.") }; convert_exclusion_line.widget = [this](wxWindow *parent) { Button *button = new Button(parent, _L("Convert area to collision volume")); + wxSizer *sizer = new wxBoxSizer(wxHORIZONTAL); + sizer->Add(button); button->Bind(wxEVT_BUTTON, [this](wxCommandEvent &) { const ConfigOptionPoints *legacy = m_config->option("bed_exclude_area"); if (legacy == nullptr || legacy->values.size() < 3) { @@ -5182,7 +5184,7 @@ void TabPrinter::build_fff() on_presets_changed(); wxGetApp().plater()->update(); }); - return button; + return sizer; }; optgroup->append_line(convert_exclusion_line); From c69687c5f067bebf16b20ca1364ce584dcc64295 Mon Sep 17 00:00:00 2001 From: Harry Loud Date: Tue, 22 Sep 2026 14:17:54 +0100 Subject: [PATCH 27/38] Correct Z-only homing test expectation --- tests/fff_print/test_exclusion_volumes.cpp | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/tests/fff_print/test_exclusion_volumes.cpp b/tests/fff_print/test_exclusion_volumes.cpp index 83f43fe6b8..bb3cd90aef 100644 --- a/tests/fff_print/test_exclusion_volumes.cpp +++ b/tests/fff_print/test_exclusion_volumes.cpp @@ -565,16 +565,23 @@ TEST_CASE("G-code processor tracks absolute relative and reset coordinate state" CHECK_FALSE(result.conflict); } - SECTION("all supported homing-axis spellings make the homed position unknown") { + SECTION("full or XY homing makes the XY start position unknown") { const std::string homing = GENERATE( std::string("G28"), std::string("G28 X"), std::string("G28 X Y"), std::string("G28 XY"), std::string("G28 X0 Y0"), std::string("G28 XYZ"), - std::string("G28 Z P0"), std::string("G28 Z Z_OFFSET -0.07"), std::string("G28 W")); const ProcessorExclusionResult result = run_processor( config, "G90\nG1 X20 Y50 Z5\n" + homing + "\nG1 X80 Y50 Z5\n"); CHECK_FALSE(result.conflict); } + + SECTION("Z-only homing preserves the known XY position") { + const std::string homing = GENERATE( + std::string("G28 Z P0"), std::string("G28 Z Z_OFFSET -0.07")); + const ProcessorExclusionResult result = run_processor( + config, "G90\nG1 X20 Y50 Z5\n" + homing + "\nG1 X80 Y50 Z5\n"); + CHECK(result.conflict); + } } TEST_CASE("G-code processor classifies extrusion conflicts", "[ExclusionVolume][GCodeProcessor]") From 0b8ce26bd3669c4639aeaf616324ab629edb9825 Mon Sep 17 00:00:00 2001 From: Harry Loud Date: Wed, 23 Sep 2026 18:20:39 +0100 Subject: [PATCH 28/38] Preserve legacy exclusion behavior for opt-in volumes --- src/OrcaSlicer.cpp | 6 - src/libslic3r/Arrange.cpp | 25 --- src/libslic3r/Arrange.hpp | 2 - src/libslic3r/Brim.cpp | 11 +- src/libslic3r/GCode.cpp | 32 +++- src/libslic3r/GCode.hpp | 1 - .../GCode/ExclusionVolumeTravelAvoidance.cpp | 180 +++++++++++++----- .../GCode/ExclusionVolumeTravelAvoidance.hpp | 21 +- src/libslic3r/Print.cpp | 64 +++++-- src/libslic3r/PrintConfig.cpp | 86 +++++---- src/libslic3r/Support/SupportCommon.cpp | 10 +- src/slic3r/GUI/3DScene.cpp | 16 +- src/slic3r/GUI/Jobs/ArrangeJob.cpp | 3 - src/slic3r/GUI/Jobs/FillBedJob.cpp | 5 - src/slic3r/GUI/PartPlate.cpp | 54 ++++-- src/slic3r/GUI/Tab.cpp | 29 +-- tests/fff_print/test_exclusion_volumes.cpp | 20 ++ tests/libslic3r/test_arrange.cpp | 30 --- tests/libslic3r/test_exclusion_volumes.cpp | 80 +++++++- 19 files changed, 426 insertions(+), 249 deletions(-) diff --git a/src/OrcaSlicer.cpp b/src/OrcaSlicer.cpp index 6bcd98ab45..e496cba9a6 100644 --- a/src/OrcaSlicer.cpp +++ b/src/OrcaSlicer.cpp @@ -5318,8 +5318,6 @@ int CLI::run(int argc, char **argv) partplate_list.preprocess_exclude_areas( arrange_cfg.excluded_regions, m_print_config, enable_wrapping_detect, 1, scale_(1)); - if (has_bed_exclusion_regions(arrange_cfg.excluded_regions)) - arrange_cfg.do_final_align = false; { BOOST_LOG_TRIVIAL(debug) << "arrange bedpts:" << beds[0].transpose() << ", " << beds[1].transpose() << ", " << beds[2].transpose() << ", " << beds[3].transpose(); @@ -5339,7 +5337,6 @@ int CLI::run(int argc, char **argv) //Step-3:do the arrange BOOST_LOG_TRIVIAL(info) << boost::format("start plate %1%'s arranging...") % (i + 1); arrangement::arrange(selected, unselected, beds, arrange_cfg); - invalidate_bed_exclusion_conflicts(selected, unselected); //arrangement::arrange(unprintable, {}, beds, arrange_cfg); BOOST_LOG_TRIVIAL(info) << boost::format("finished plate %1%'s arranging") % (i + 1); @@ -5773,8 +5770,6 @@ int CLI::run(int argc, char **argv) partplate_list.preprocess_exclude_areas( arrange_cfg.excluded_regions, m_print_config, enable_wrapping_detect, 1, scale_(1)); - if (has_bed_exclusion_regions(arrange_cfg.excluded_regions)) - arrange_cfg.do_final_align = false; { BOOST_LOG_TRIVIAL(debug) << "arrange bedpts:" << beds[0].transpose() << ", " << beds[1].transpose() << ", " << beds[2].transpose() << ", " << beds[3].transpose(); @@ -5794,7 +5789,6 @@ int CLI::run(int argc, char **argv) //Step-3:do the arrange BOOST_LOG_TRIVIAL(info) << boost::format("start %1% th arranging...")%arrange_count; arrangement::arrange(selected, unselected, beds, arrange_cfg); - invalidate_bed_exclusion_conflicts(selected, unselected); arrangement::arrange(unprintable, {}, beds, arrange_cfg); BOOST_LOG_TRIVIAL(info) << boost::format("finished %1% th arranging...")%arrange_count; diff --git a/src/libslic3r/Arrange.cpp b/src/libslic3r/Arrange.cpp index d2dcf0d3a9..7d3d33171f 100644 --- a/src/libslic3r/Arrange.cpp +++ b/src/libslic3r/Arrange.cpp @@ -122,31 +122,6 @@ bool bed_exclusion_applies(const ArrangePolygon &item, const ArrangePolygon &fix return bed_exclusion_applies_impl(item, fixed_item); } -void invalidate_bed_exclusion_conflicts(ArrangePolygons &items, const ArrangePolygons &fixed_items, - const Vec2crd fixed_items_offset) -{ - for (ArrangePolygon &item : items) { - if (item.bed_idx < 0) - continue; - - BoundingBox item_bbox = get_extents(item.transformed_poly()); - item_bbox.offset(std::max(0, item.inflation)); - - for (const ArrangePolygon &fixed : fixed_items) { - if (fixed.bed_idx != item.bed_idx || !bed_exclusion_applies(item, fixed)) - continue; - - BoundingBox exclusion_bbox = get_extents(fixed.transformed_poly()); - exclusion_bbox.offset(std::max(0, fixed.inflation)); - exclusion_bbox.translate(fixed_items_offset.x(), fixed_items_offset.y()); - if (item_bbox.overlap(exclusion_bbox)) { - item.bed_idx = UNARRANGED; - break; - } - } - } -} - void update_arrange_params(ArrangeParams& params, const DynamicPrintConfig* print_cfg, const ArrangePolygons& selected) { double skirt_distance = get_real_skirt_dist(*print_cfg); diff --git a/src/libslic3r/Arrange.hpp b/src/libslic3r/Arrange.hpp index 8f3098c38b..19f1dcfafd 100644 --- a/src/libslic3r/Arrange.hpp +++ b/src/libslic3r/Arrange.hpp @@ -198,8 +198,6 @@ void update_selected_items_axis_align(ArrangePolygons& selected, const DynamicPr bool has_bed_exclusion_regions(const ArrangePolygons& polygons); bool bed_exclusion_applies(const ArrangePolygon& item, const ArrangePolygon& fixed_item); -void invalidate_bed_exclusion_conflicts(ArrangePolygons& items, const ArrangePolygons& fixed_items, - Vec2crd fixed_items_offset = Vec2crd::Zero()); Points get_shrink_bedpts(const DynamicPrintConfig* print_cfg, const ArrangeParams& params); diff --git a/src/libslic3r/Brim.cpp b/src/libslic3r/Brim.cpp index ffe355ea50..f1bbfa67de 100644 --- a/src/libslic3r/Brim.cpp +++ b/src/libslic3r/Brim.cpp @@ -437,8 +437,15 @@ static ExPolygons outer_inner_brim_area(const Print& print, { unsigned int support_material_extruder = printExtruders.front() + 1; Flow flow = print.brim_flow(); - const std::vector> exclusion_regions_by_extruder = - get_bed_excluded_regions_by_extruder(print.config()); + std::vector> exclusion_regions_by_extruder; + if (has_bed_exclude_volumes(print.config())) { + exclusion_regions_by_extruder = get_bed_excluded_regions_by_extruder(print.config()); + // Legacy areas historically constrain placement, not generated + // geometry. Only explicit collision volumes may trim a brim. + for (std::vector ®ions : exclusion_regions_by_extruder) + regions.erase(std::remove_if(regions.begin(), regions.end(), + [](const BedExcludeRegion ®ion) { return !region.is_collision_volume(); }), regions.end()); + } const double first_layer_top_z = std::max(0.0, print.skirt_first_layer_height()); const coord_t exclusion_clearance = brim_exclusion_clearance(flow); diff --git a/src/libslic3r/GCode.cpp b/src/libslic3r/GCode.cpp index 5f629c596f..25033fa580 100644 --- a/src/libslic3r/GCode.cpp +++ b/src/libslic3r/GCode.cpp @@ -1402,6 +1402,13 @@ static std::vector get_path_of_change_filament(const Print& print) // We have informed the m_writer about the current extruder_id, we can ignore the generated G-code. } + // The change G-code may move the carriage even when the incoming + // filament uses the same physical nozzle (the common AMS case). + // Synchronize before planning the tower-entry travel so exclusion + // avoidance starts from the emitted position, not the stale one. + if (position_before_toolchange) + gcodegen.synchronize_toolchange_position(*position_before_toolchange, toolchange_gcode_str); + if (need_travel_after_change_filament_gcode) { // move to start_pos for wiping after toolchange if (!is_used_travel_avoid_perimeter) { @@ -2671,11 +2678,16 @@ void GCode::do_export(Print* print, const char* path, GCodeProcessorResult* resu m_processor.finalize(true); if (m_processor.get_result().exclusion_volume_path_conflict) { const int extruder_id = m_processor.get_result().exclusion_volume_conflict_extruder_id; - const std::string warning = extruder_id >= 0 ? + std::string warning = extruder_id >= 0 ? Slic3r::format( _(L("A G-code move intersects an exclusion volume for extruder %1%. This may cause a printer collision.")), std::to_string(extruder_id + 1)) : _(L("A G-code move intersects an exclusion volume. This may cause a printer collision.")); + if (m_processor.get_result().exclusion_volume_conflict_used_unknown_z) { + warning += "\n" + Slic3r::format( + _(L("The intersecting move is at G-code line %1%. Its Z position is unknown after homing, so Orca checked it against every height.")), + std::to_string(m_processor.get_result().exclusion_volume_conflict_gcode_id)); + } print->active_step_add_warning( PrintStateBase::WarningLevel::CRITICAL, warning, @@ -5259,14 +5271,16 @@ std::string GCode::generate_object_brim( if (!first_layer) return {}; - auto emit_brim = [this, extruder_id](const ExtrusionEntityCollection& brim, + const bool wait_for_owner_filament = has_bed_exclude_volumes(m_config) && + active_bed_exclude_volume_mode(m_config) != BedExcludeVolumeMode::Shared; + auto emit_brim = [this, extruder_id, wait_for_owner_filament](const ExtrusionEntityCollection& brim, const std::vector& instances, const unsigned int brim_filament_id) { std::string gcode; // Combined brims have an explicit owner filament. Waiting for that - // filament avoids inheriting whichever tool first encounters a carrier - // object in the layer traversal. - if (brim_filament_id != extruder_id) + // filament is only required when each nozzle has different obstacles. + // Otherwise retain Orca's established first-visit emission order. + if (wait_for_owner_filament && brim_filament_id != extruder_id) return gcode; const bool already_emitted = std::none_of(instances.begin(), instances.end(), [this](const ObjectInstanceID& instance) { return m_objsWithBrim.find(instance) != m_objsWithBrim.end(); @@ -7273,14 +7287,13 @@ std::optional GCode::capture_toolchange_position const Vec2d plate_offset = m_writer.get_xy_offset().cast(); return ToolchangePositionState{ - int(m_writer.filament()->extruder_id()), this->point_to_gcode(m_last_pos.to_point()) - plate_offset }; } void GCode::synchronize_toolchange_position(const ToolchangePositionState &before, const std::string &emitted_gcode) { - if (m_writer.filament() == nullptr || int(m_writer.filament()->extruder_id()) == before.physical_extruder_id) + if (m_writer.filament() == nullptr) return; const std::optional emitted_xy = emitted_xy_after_gcode(emitted_gcode, before.emitted_xy); @@ -7294,7 +7307,12 @@ void GCode::synchronize_toolchange_position(const ToolchangePositionState &befor Vec3d writer_position = m_writer.get_position(); writer_position.head<2>() = writer_xy; m_writer.set_position(writer_position); + // Updating the known XY origin must not cancel Orca's deliberate + // post-toolchange Z restore. set_last_pos() normally marks the entire + // position as defined, so preserve the caller's state across the XY sync. + const bool last_pos_defined = m_last_pos_defined; this->set_last_pos(this->gcode_to_point(writer_xy)); + m_last_pos_defined = last_pos_defined; } void GCode::set_origin(const Vec2d &pointf) diff --git a/src/libslic3r/GCode.hpp b/src/libslic3r/GCode.hpp index f5f7151626..f50b9dde9d 100644 --- a/src/libslic3r/GCode.hpp +++ b/src/libslic3r/GCode.hpp @@ -734,7 +734,6 @@ private: struct ToolchangePositionState { - int physical_extruder_id{-1}; Vec2d emitted_xy{Vec2d::Zero()}; }; diff --git a/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.cpp b/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.cpp index 3b001a12d7..b5f4fe1d67 100644 --- a/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.cpp +++ b/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.cpp @@ -287,11 +287,32 @@ Polyline make_backward_detour( return Polyline(std::move(points)); } -bool polyline_inside_bed(const Polyline &polyline, const ExPolygons &valid_bed) +bool routed_polyline_inside_bed( + const Polyline &polyline, + const ExPolygons &valid_bed, + const bool allow_start_outside, + const bool allow_end_outside) { - for (size_t idx = 1; idx < polyline.points.size(); ++idx) + if (valid_bed.empty()) + return true; + + const size_t last_idx = polyline.points.size() - 1; + for (size_t idx = 0; idx < polyline.points.size(); ++idx) { + if ((idx == 0 && allow_start_outside) || (idx == last_idx && allow_end_outside)) + continue; + if (!point_in_expolygons(valid_bed, polyline.points[idx], true)) + return false; + } + + for (size_t idx = 1; idx < polyline.points.size(); ++idx) { + // A start or end produced by machine G-code may legitimately lie on + // or beyond the printable boundary. Constrain only the route vertices + // Orca adds; the firmware-defined transition to the bed remains intact. + if ((idx == 1 && allow_start_outside) || (idx == last_idx && allow_end_outside)) + continue; if (!segment_inside_bed(polyline.points[idx - 1], polyline.points[idx], valid_bed)) return false; + } return true; } @@ -325,7 +346,9 @@ std::optional detour_around_obstacle( const Point &b, const ExPolygon &obstacle, const ExPolygons &obstacles, - const ExPolygons &valid_bed) + const ExPolygons &valid_bed, + const bool allow_start_outside, + const bool allow_end_outside) { const std::vector intersections = contour_intersections(a, b, obstacle.contour); if (intersections.size() < 2) @@ -336,8 +359,10 @@ std::optional detour_around_obstacle( const Polyline forward = make_forward_detour(a, b, obstacle.contour, entry, exit); const Polyline backward = make_backward_detour(a, b, obstacle.contour, entry, exit); - const bool forward_bed_valid = polyline_inside_bed(forward, valid_bed); - const bool backward_bed_valid = polyline_inside_bed(backward, valid_bed); + const bool forward_bed_valid = routed_polyline_inside_bed( + forward, valid_bed, allow_start_outside, allow_end_outside); + const bool backward_bed_valid = routed_polyline_inside_bed( + backward, valid_bed, allow_start_outside, allow_end_outside); const bool forward_clear = forward_bed_valid && !polyline_intersects_obstacles(forward, obstacles); const bool backward_clear = backward_bed_valid && !polyline_intersects_obstacles(backward, obstacles); @@ -401,6 +426,17 @@ void ExclusionVolumeTravelAvoidance::init(const PrintConfig &config, const Vec3d { clear(); + double max_nozzle_diameter = 0.0; + for (double diameter : config.nozzle_diameter.values) + max_nozzle_diameter = std::max(max_nozzle_diameter, diameter); + + // This is a numerical/perimeter-walk clearance, not a hidden toolhead + // footprint. The exact configured volume remains Stage 2's source of truth. + const coord_t minimum_clearance = static_cast(SCALED_EPSILON); + const coord_t configured_clearance = + static_cast(scale_(std::max(0.05, 0.1 * max_nozzle_diameter))); + m_clearance = std::max(minimum_clearance, configured_clearance); + std::vector> regions_by_extruder = get_bed_excluded_regions_by_extruder(config); m_spaces.resize(regions_by_extruder.size()); @@ -420,24 +456,22 @@ void ExclusionVolumeTravelAvoidance::init(const PrintConfig &config, const Vec3d // subtracts the plate origin, so transform both obstacles and bed alike. const Vec2d translation_mm = plate_xy - extruder_offset; const Point translation = scaled(translation_mm); - for (BedExcludeRegion ®ion : space.regions) + for (BedExcludeRegion ®ion : space.regions) { region.polygon.translate(translation); + BoundingBox bbox(region.polygon.points); + bbox.offset(m_clearance); + space.region_bboxes.emplace_back(std::move(bbox)); + } - space.bed_shape = base_bed_shape; - space.bed_shape.translate(translation); - space.bed_shape.make_counter_clockwise(); + Polygon bed_shape = base_bed_shape; + bed_shape.translate(translation); + bed_shape.make_counter_clockwise(); + if (bed_shape.points.size() >= 3) { + space.valid_bed = offset_ex(bed_shape, -float(m_clearance)); + if (space.valid_bed.empty()) + space.valid_bed = union_ex(Polygons { std::move(bed_shape) }); + } } - - double max_nozzle_diameter = 0.0; - for (double diameter : config.nozzle_diameter.values) - max_nozzle_diameter = std::max(max_nozzle_diameter, diameter); - - // This is a numerical/perimeter-walk clearance, not a hidden toolhead - // footprint. The exact configured volume remains Stage 2's source of truth. - const coord_t minimum_clearance = static_cast(SCALED_EPSILON); - const coord_t configured_clearance = - static_cast(scale_(std::max(0.05, 0.1 * max_nozzle_diameter))); - m_clearance = std::max(minimum_clearance, configured_clearance); } void ExclusionVolumeTravelAvoidance::clear() @@ -453,30 +487,43 @@ bool ExclusionVolumeTravelAvoidance::empty() const }); } -std::optional +const ExPolygons * ExclusionVolumeTravelAvoidance::active_obstacles( - const RoutingSpace &space, + RoutingSpace &space, double z_min, - double z_max) const + double z_max) { - ActiveObstacles active; - active.obstacles = active_bed_exclusion_footprints( - space.regions, z_min, z_max, Point(0, 0), m_clearance); - if (active.obstacles.empty()) - return std::nullopt; - if (space.bed_shape.points.size() >= 3) { - active.valid_bed = offset_ex(space.bed_shape, -float(m_clearance)); - if (active.valid_bed.empty()) - active.valid_bed = union_ex(Polygons { space.bed_shape }); + std::vector active_region_ids; + active_region_ids.reserve(space.regions.size()); + for (size_t region_id = 0; region_id < space.regions.size(); ++region_id) { + const BedExcludeRegion ®ion = space.regions[region_id]; + if (bed_exclusion_z_ranges_overlap(z_min, z_max, region.z_min, region.z_max)) + active_region_ids.emplace_back(region_id); } - return active; + if (active_region_ids.empty()) + return nullptr; + + const auto cached = space.obstacle_cache.find(active_region_ids); + if (cached != space.obstacle_cache.end()) + return cached->second.empty() ? nullptr : &cached->second; + + std::vector active_regions; + active_regions.reserve(active_region_ids.size()); + for (const size_t region_id : active_region_ids) + active_regions.emplace_back(space.regions[region_id]); + + ExPolygons obstacles = active_bed_exclusion_footprints( + active_regions, z_min, z_max, Point(0, 0), m_clearance); + const auto cache_result = space.obstacle_cache.emplace( + std::move(active_region_ids), std::move(obstacles)); + return cache_result.first->second.empty() ? nullptr : &cache_result.first->second; } ExclusionVolumeTravelAvoidance::Result ExclusionVolumeTravelAvoidance::route( const Polyline &travel, double start_z, double end_z, - int extruder_id) const + int extruder_id) { Result result; result.path = travel; @@ -488,7 +535,7 @@ ExclusionVolumeTravelAvoidance::Result ExclusionVolumeTravelAvoidance::route( return result; } - const RoutingSpace &space = m_spaces[size_t(extruder_id)]; + RoutingSpace &space = m_spaces[size_t(extruder_id)]; if (space.regions.empty()) { result.detail = Detail::NoActiveObstacles; return result; @@ -496,19 +543,48 @@ ExclusionVolumeTravelAvoidance::Result ExclusionVolumeTravelAvoidance::route( const double z_min = std::min(start_z, end_z); const double z_max = std::max(start_z, end_z); - const std::optional active = active_obstacles(space, z_min, z_max); - if (!active || active->obstacles.empty()) { + + // Most travels are nowhere near an exclusion. Reject them using the cheap + // precomputed boxes before unioning and inflating obstacle polygons. + const BoundingBox travel_bbox(travel.points); + bool has_active_z = false; + bool may_intersect = false; + for (size_t region_id = 0; region_id < space.regions.size(); ++region_id) { + const BedExcludeRegion ®ion = space.regions[region_id]; + if (!bed_exclusion_z_ranges_overlap(z_min, z_max, region.z_min, region.z_max)) + continue; + has_active_z = true; + if (region_id < space.region_bboxes.size() && space.region_bboxes[region_id].overlap(travel_bbox)) { + may_intersect = true; + break; + } + } + if (!has_active_z) { result.detail = Detail::NoActiveObstacles; return result; } - result.active_obstacles = active->obstacles.size(); + if (!may_intersect) { + result.detail = Detail::NoIntersection; + return result; + } + + const ExPolygons *active = active_obstacles(space, z_min, z_max); + if (active == nullptr || active->empty()) { + result.detail = Detail::NoActiveObstacles; + return result; + } + result.active_obstacles = active->size(); const Point &start = travel.points.front(); const Point &end = travel.points.back(); - const std::optional start_obstacles = active_obstacles(space, start_z, start_z); - const std::optional end_obstacles = active_obstacles(space, end_z, end_z); - if ((start_obstacles && point_in_expolygons_interior(start_obstacles->obstacles, start)) || - (end_obstacles && point_in_expolygons_interior(end_obstacles->obstacles, end))) { + const bool start_outside_bed = !space.valid_bed.empty() && + !point_in_expolygons(space.valid_bed, start, true); + const bool end_outside_bed = !space.valid_bed.empty() && + !point_in_expolygons(space.valid_bed, end, true); + const ExPolygons *start_obstacles = active_obstacles(space, start_z, start_z); + const ExPolygons *end_obstacles = active_obstacles(space, end_z, end_z); + if ((start_obstacles != nullptr && point_in_expolygons_interior(*start_obstacles, start)) || + (end_obstacles != nullptr && point_in_expolygons_interior(*end_obstacles, end))) { result.status = Status::EndpointInside; result.detail = Detail::EndpointInside; return result; @@ -516,7 +592,7 @@ ExclusionVolumeTravelAvoidance::Result ExclusionVolumeTravelAvoidance::route( bool needs_reroute = false; for (size_t idx = 1; idx < travel.points.size(); ++idx) { - if (segment_enters_expolygons_interior(travel.points[idx - 1], travel.points[idx], active->obstacles)) { + if (segment_enters_expolygons_interior(travel.points[idx - 1], travel.points[idx], *active)) { needs_reroute = true; break; } @@ -534,18 +610,23 @@ ExclusionVolumeTravelAvoidance::Result ExclusionVolumeTravelAvoidance::route( for (size_t segment_idx = 0; segment_idx + 1 < path.points.size(); ++segment_idx) { const Point &a = path.points[segment_idx]; const Point &b = path.points[segment_idx + 1]; - if (!segment_inside_bed(a, b, active->valid_bed)) { + const bool allow_a_outside = start_outside_bed && segment_idx == 0; + const bool allow_b_outside = end_outside_bed && segment_idx + 2 == path.points.size(); + const Polyline segment({a, b}); + if (!routed_polyline_inside_bed( + segment, space.valid_bed, allow_a_outside, allow_b_outside)) { result.status = Status::Failed; result.detail = Detail::SegmentOutsideBed; return result; } - const std::optional obstacle_idx = first_intersected_obstacle(a, b, active->obstacles); + const std::optional obstacle_idx = first_intersected_obstacle(a, b, *active); if (!obstacle_idx) continue; const std::optional detour = detour_around_obstacle( - a, b, active->obstacles[*obstacle_idx], active->obstacles, active->valid_bed); + a, b, (*active)[*obstacle_idx], *active, space.valid_bed, + allow_a_outside, allow_b_outside); if (!detour) { result.status = Status::Failed; result.detail = Detail::DetourFailed; @@ -561,9 +642,10 @@ ExclusionVolumeTravelAvoidance::Result ExclusionVolumeTravelAvoidance::route( } if (!changed) { - path = simplify_path(path, active->obstacles, active->valid_bed); - if (!polyline_inside_bed(path, active->valid_bed) || - polyline_intersects_obstacles(path, active->obstacles)) { + path = simplify_path(path, *active, space.valid_bed); + if (!routed_polyline_inside_bed( + path, space.valid_bed, start_outside_bed, end_outside_bed) || + polyline_intersects_obstacles(path, *active)) { result.status = Status::Failed; result.detail = Detail::FinalPathInvalid; return result; diff --git a/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.hpp b/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.hpp index 27b3318039..4c439389b0 100644 --- a/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.hpp +++ b/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.hpp @@ -1,11 +1,12 @@ #pragma once #include "libslic3r/ExPolygon.hpp" +#include "libslic3r/BoundingBox.hpp" #include "libslic3r/Polyline.hpp" #include "libslic3r/PrintConfig.hpp" #include -#include +#include #include namespace Slic3r { @@ -52,25 +53,21 @@ public: // Input and output are scaled XY points in the active nozzle's generated // G-code coordinates before GCodeWriter subtracts the plate offset. - Result route(const Polyline &travel, double start_z, double end_z, int extruder_id) const; + Result route(const Polyline &travel, double start_z, double end_z, int extruder_id); private: struct RoutingSpace { std::vector regions; - Polygon bed_shape; + std::vector region_bboxes; + ExPolygons valid_bed; + std::map, ExPolygons> obstacle_cache; }; - struct ActiveObstacles - { - ExPolygons obstacles; - ExPolygons valid_bed; - }; - - std::optional active_obstacles( - const RoutingSpace &space, + const ExPolygons *active_obstacles( + RoutingSpace &space, double z_min, - double z_max) const; + double z_max); std::vector m_spaces; coord_t m_clearance { 0 }; diff --git a/src/libslic3r/Print.cpp b/src/libslic3r/Print.cpp index 124146593c..61dc11edf6 100644 --- a/src/libslic3r/Print.cpp +++ b/src/libslic3r/Print.cpp @@ -89,7 +89,24 @@ static std::vector> translated_bed_exclusion_volum return regions_by_extruder; } -static std::optional colliding_bed_exclusion_extruder( +struct BedExclusionCollision +{ + size_t extruder_id; + bool collision_volume; +}; + +static bool intersects_bed_exclusion_purpose( + const ModelInstance &instance, + const std::vector ®ions, + const bool collision_volume) +{ + return std::any_of(regions.begin(), regions.end(), [&](const BedExcludeRegion ®ion) { + return region.is_collision_volume() == collision_volume && + instance.intersects_bed_exclude_region(region); + }); +} + +static std::optional colliding_bed_exclusion( const Print &print, const PrintObject &print_object, const ModelInstance &instance, @@ -98,6 +115,11 @@ static std::optional colliding_bed_exclusion_extruder( if (regions_by_extruder.empty()) return std::nullopt; + // The legacy area is shared by every nozzle. Report it with Orca's + // established wording even when opt-in collision volumes coexist. + if (intersects_bed_exclusion_purpose(instance, regions_by_extruder.front(), false)) + return BedExclusionCollision{ 0, false }; + const bool automatic = is_auto_filament_map_mode(print.get_filament_map_mode()); if (automatic && print.is_BBL_printer()) { // Bambu automatic grouping owns the concrete filament assignment and @@ -107,12 +129,13 @@ static std::optional colliding_bed_exclusion_extruder( // can print it. std::optional first_collision; for (size_t extruder_id = 0; extruder_id < regions_by_extruder.size(); ++extruder_id) { - if (!instance.intersects_bed_exclude_regions(regions_by_extruder[extruder_id])) + if (!intersects_bed_exclusion_purpose(instance, regions_by_extruder[extruder_id], true)) return std::nullopt; if (!first_collision.has_value()) first_collision = extruder_id; } - return first_collision; + return first_collision.has_value() ? + std::optional(BedExclusionCollision{ *first_collision, true }) : std::nullopt; } for (const unsigned int filament_id : print_object.printing_extruders()) { @@ -122,8 +145,8 @@ static std::optional colliding_bed_exclusion_extruder( if (resolved_extruder < 0) continue; const size_t extruder_id = size_t(resolved_extruder); - if (instance.intersects_bed_exclude_regions(regions_by_extruder[extruder_id])) - return extruder_id; + if (intersects_bed_exclusion_purpose(instance, regions_by_extruder[extruder_id], true)) + return BedExclusionCollision{ extruder_id, true }; } return std::nullopt; } @@ -786,13 +809,14 @@ StringObjectException Print::sequential_print_clearance_valid(const Print &print // Convert the shift from the PrintObject's coordinates into ModelObject's coordinates by removing the centering offset. convex_hull.translate(instance.shift - print_object->center_offset()); } - const std::optional collision_extruder = colliding_bed_exclusion_extruder( + const std::optional exclusion_collision = colliding_bed_exclusion( print, *print_object, *instance.model_instance, exclusion_volumes); - if (collision_extruder.has_value()) { - const std::string collision_message = + if (exclusion_collision.has_value()) { + const std::string collision_message = !exclusion_collision->collision_volume ? + (boost::format(L("%1% is too close to exclusion area. There may be collisions when printing.")) % instance.model_instance->get_object()->name).str() : is_auto_filament_map_mode(print.get_filament_map_mode()) && print.is_BBL_printer() ? - (boost::format(L("%1% intersects exclusion volumes for every available extruder.")) % instance.model_instance->get_object()->name).str() : - (boost::format(L("%1% intersects an exclusion volume for extruder %2%.")) % instance.model_instance->get_object()->name % (*collision_extruder + 1)).str(); + (boost::format(L("%1% intersects exclusion volumes for every available extruder.")) % instance.model_instance->get_object()->name).str() : + (boost::format(L("%1% intersects an exclusion volume for extruder %2%.")) % instance.model_instance->get_object()->name % (exclusion_collision->extruder_id + 1)).str(); if (single_object_exception.string.empty()) { single_object_exception.string = collision_message; // single_object_exception.object = instance.model_instance->get_object(); @@ -1457,12 +1481,13 @@ static StringObjectException layered_print_cleareance_valid(const Print &print, } current_instance_hulls.emplace_back(volume_hull); } - if (const std::optional collision_extruder = colliding_bed_exclusion_extruder( - print, *inst->print_object, *inst->model_instance, exclusion_volumes); collision_extruder.has_value()) { - const std::string message = + if (const std::optional exclusion_collision = colliding_bed_exclusion( + print, *inst->print_object, *inst->model_instance, exclusion_volumes); exclusion_collision.has_value()) { + const std::string message = !exclusion_collision->collision_volume ? + inst->model_instance->get_object()->name + L(" is too close to exclusion area, there may be collisions when printing.") : is_auto_filament_map_mode(print.get_filament_map_mode()) && print.is_BBL_printer() ? - (boost::format(L("%1% intersects exclusion volumes for every available extruder.")) % inst->model_instance->get_object()->name).str() : - (boost::format(L("%1% intersects an exclusion volume for extruder %2%.")) % inst->model_instance->get_object()->name % (*collision_extruder + 1)).str(); + (boost::format(L("%1% intersects exclusion volumes for every available extruder.")) % inst->model_instance->get_object()->name).str() : + (boost::format(L("%1% intersects an exclusion volume for extruder %2%.")) % inst->model_instance->get_object()->name % (exclusion_collision->extruder_id + 1)).str(); return {message + "\n", inst->model_instance}; } @@ -3691,8 +3716,13 @@ void Print::_make_skirt() } } - const std::vector> brim_exclusion_regions = - translated_bed_exclusion_volumes_by_extruder(*this); + std::vector> brim_exclusion_regions; + if (has_bed_exclude_volumes(m_config)) { + brim_exclusion_regions = translated_bed_exclusion_volumes_by_extruder(*this); + for (std::vector ®ions : brim_exclusion_regions) + regions.erase(std::remove_if(regions.begin(), regions.end(), + [](const BedExcludeRegion ®ion) { return !region.is_collision_volume(); }), regions.end()); + } const bool has_brim_exclusions = std::any_of( brim_exclusion_regions.begin(), brim_exclusion_regions.end(), [](const std::vector ®ions) { return !regions.empty(); }); diff --git a/src/libslic3r/PrintConfig.cpp b/src/libslic3r/PrintConfig.cpp index 886ca4c37c..862955d192 100644 --- a/src/libslic3r/PrintConfig.cpp +++ b/src/libslic3r/PrintConfig.cpp @@ -5,6 +5,7 @@ #include "FilamentMixer.hpp" #include "MaterialType.hpp" #include "I18N.hpp" +#include "LocalesUtils.hpp" #include "format.hpp" #include "GCode/Thumbnails.hpp" @@ -889,7 +890,7 @@ void PrintConfigDef::init_common_params() def = this->add("bed_exclude_area", coPoints); def->label = L("Excluded bed area (legacy)"); def->tooltip = L("Unprintable area in XY plane. For example, X1 Series printers use the front left corner to cut filament during filament change. " - "The area is expressed as a polygon in the format \"XxY, XxY, ...\". Legacy areas keep generated material and models out, " + "The area is expressed as a polygon in the format \"XxY, XxY, ...\". Legacy areas constrain model placement, " "but do not check or reroute machine travel. Configure exclusion volumes below for full collision checking."); def->mode = comAdvanced; def->gui_type = ConfigOptionDef::GUIType::one_string; @@ -899,7 +900,7 @@ void PrintConfigDef::init_common_params() def->label = L("Exclusion volumes"); def->tooltip = L("Collision volumes used for model and generated-material exclusion, G-code checking, and travel avoidance. " "Use \"XxY, XxY, ...\" for a full-height polygon or \"ZMIN..ZMAX;XxY, XxY, ...\" for a Z-limited volume. " - "Separate multiple volumes with \"|\". When configured, these volumes take precedence over the legacy excluded bed area."); + "Separate multiple volumes with \"|\". These volumes are additional to any legacy excluded bed area."); def->mode = comAdvanced; def->gui_type = ConfigOptionDef::GUIType::one_string; def->set_default_value(new ConfigOptionString()); @@ -8329,7 +8330,6 @@ void PrintConfigDef::init_extruder_option_keys() "default_filament_profile", "default_nozzle_volume_type", "deretraction_speed", - "extruder_bed_exclude_volumes", "extruder_colour", "extruder_offset", "extruder_printable_height", @@ -11680,14 +11680,10 @@ std::map validate(const FullPrintConfig &cfg, bool und error_message.emplace("extruder_offset", L("A nozzle offset is required for every extruder when toolhead-relative exclusion volumes are enabled.")); } if (collision_volumes_enabled && cfg.bed_exclude_volume_mode.value == BedExcludeVolumeMode::PerExtruder) { - if (cfg.extruder_bed_exclude_volumes.size() < cfg.nozzle_diameter.size()) { - error_message.emplace("extruder_bed_exclude_volumes", L("An exclusion-volume entry is required for every extruder. An entry may be empty when that extruder has no exclusion volumes.")); - } else { - for (const std::string &entry : cfg.extruder_bed_exclude_volumes.values) { - if (!is_valid_bed_exclude_volumes_string(entry, cfg.printable_height.value)) { - error_message.emplace("extruder_bed_exclude_volumes", L("Invalid per-extruder exclusion volume definition.")); - break; - } + for (const std::string &entry : cfg.extruder_bed_exclude_volumes.values) { + if (!is_valid_bed_exclude_volumes_string(entry, cfg.printable_height.value)) { + error_message.emplace("extruder_bed_exclude_volumes", L("Invalid per-extruder exclusion volume definition.")); + break; } } } @@ -12963,13 +12959,9 @@ static bool parse_double_token(const std::string &text, double &out) if (token.empty()) return false; - try { - size_t parsed = 0; - out = std::stod(token, &parsed); - return parsed == token.size(); - } catch (...) { - return false; - } + size_t parsed = 0; + out = string_to_double_decimal_point(token, &parsed); + return parsed == token.size() && std::isfinite(out); } static bool parse_z_range_token( @@ -13003,7 +12995,9 @@ static bool parse_z_range_token( z_min = std::clamp(parsed_min, 0.0, printable_height); z_max = std::clamp(parsed_max, 0.0, printable_height); has_z = true; - return z_min <= z_max; + // A range wholly outside the printable height clamps to a plane, which is + // not a volume and must not participate in conservative unknown-Z checks. + return z_min < z_max; } static std::optional parse_exclude_polygon_points(const std::string &points_str) @@ -13110,7 +13104,7 @@ static void append_bed_exclusion_volume_regions( z_max = printable_height; } - if (z_min > z_max) + if (z_min >= z_max) continue; std::optional polygon = parse_exclude_polygon_points(points_field); @@ -13141,14 +13135,17 @@ static std::vector parse_master_bed_excluded_regions( const Pointfs &legacy_points, const std::string &shared_specs, const bool use_collision_volumes, + const BedExcludeVolumeMode mode, const double printable_height) { std::vector regions; const double height = std::max(0.0, printable_height); - if (use_collision_volumes) + // Legacy excluded areas remain a shared material/placement keep-out even + // when collision volumes are configured. Collision volumes add constraints; + // they do not silently remove the printer profile's established area. + append_legacy_bed_exclude_regions(regions, legacy_points, height); + if (use_collision_volumes && mode != BedExcludeVolumeMode::PerExtruder) append_bed_exclusion_volume_regions(regions, shared_specs, height); - else - append_legacy_bed_exclude_regions(regions, legacy_points, height); return regions; } @@ -13165,11 +13162,10 @@ static std::vector resolve_bed_excluded_regions( return master_regions; if (mode == BedExcludeVolumeMode::PerExtruder) { - if (extruder_id >= per_extruder_specs.size() || per_extruder_specs[extruder_id].empty()) - return {}; - - std::vector regions; - append_bed_exclusion_volume_regions(regions, per_extruder_specs[extruder_id], std::max(0.0, printable_height)); + std::vector regions = master_regions; + if (extruder_id < per_extruder_specs.size()) + append_bed_exclusion_volume_regions( + regions, per_extruder_specs[extruder_id], std::max(0.0, printable_height)); return regions; } @@ -13183,8 +13179,12 @@ static std::vector resolve_bed_excluded_regions( // nozzle's model space translated by (other_offset - reference_offset). const Vec2d delta = extruder_offsets[extruder_id] - extruder_offsets[clamped_reference]; const Point translation(scale_(delta.x()), scale_(delta.y())); - for (BedExcludeRegion ®ion : regions) - region.polygon.translate(translation); + for (BedExcludeRegion ®ion : regions) { + // Toolhead-relative offsets apply only to opt-in collision volumes. + // A legacy material keep-out is bed-fixed and shared by every nozzle. + if (region.is_collision_volume()) + region.polygon.translate(translation); + } return regions; } @@ -13205,14 +13205,21 @@ static std::vector flatten_bed_excluded_regions( if (mode == BedExcludeVolumeMode::Shared) return std::move(regions_by_extruder.front()); - size_t total = 0; - for (const std::vector ®ions : regions_by_extruder) - total += regions.size(); - std::vector flattened; - flattened.reserve(total); - for (std::vector ®ions : regions_by_extruder) - flattened.insert(flattened.end(), std::make_move_iterator(regions.begin()), std::make_move_iterator(regions.end())); + // A shared legacy area is present in every resolved nozzle group so object + // validation sees it for every tool. Flatten it only once, while retaining + // every nozzle-specific collision volume. + bool material_keepout_added = false; + for (std::vector ®ions : regions_by_extruder) { + for (BedExcludeRegion ®ion : regions) { + if (!region.is_collision_volume()) { + if (material_keepout_added) + continue; + material_keepout_added = true; + } + flattened.emplace_back(std::move(region)); + } + } return flattened; } @@ -13261,7 +13268,7 @@ std::vector> get_bed_excluded_regions_by_extruder( const bool use_collision_volumes = collision_volumes_configured(shared_specs, configured_mode, per_extruder_specs); const BedExcludeVolumeMode active_mode = use_collision_volumes ? configured_mode : BedExcludeVolumeMode::Shared; const std::vector master_regions = parse_master_bed_excluded_regions( - legacy_points, shared_specs, use_collision_volumes, printable_height); + legacy_points, shared_specs, use_collision_volumes, active_mode, printable_height); const std::vector offsets = offset_option != nullptr ? offset_option->values : std::vector{}; const size_t count = bed_exclusion_extruder_count( nozzle_option != nullptr ? nozzle_option->size() : 0, @@ -13284,7 +13291,8 @@ std::vector> get_bed_excluded_regions_by_extruder( const BedExcludeVolumeMode active_mode = use_collision_volumes ? cfg.bed_exclude_volume_mode.value : BedExcludeVolumeMode::Shared; const std::vector master_regions = parse_master_bed_excluded_regions( - cfg.bed_exclude_area.values, cfg.bed_exclude_volumes.value, use_collision_volumes, printable_height); + cfg.bed_exclude_area.values, cfg.bed_exclude_volumes.value, use_collision_volumes, + active_mode, printable_height); const size_t count = bed_exclusion_extruder_count( cfg.nozzle_diameter.size(), cfg.extruder_offset.size(), cfg.extruder_bed_exclude_volumes.size()); const size_t reference = cfg.master_extruder_id.value > 0 ? size_t(cfg.master_extruder_id.value - 1) : 0; diff --git a/src/libslic3r/Support/SupportCommon.cpp b/src/libslic3r/Support/SupportCommon.cpp index 9560d02fab..f6e011d442 100644 --- a/src/libslic3r/Support/SupportCommon.cpp +++ b/src/libslic3r/Support/SupportCommon.cpp @@ -91,8 +91,16 @@ std::vector support_exclusion_areas_for_layers( return result; const Print &print = *object.print(); - const std::vector> regions_by_extruder = + // Preserve established support output for legacy bed-exclude areas. Support + // avoidance is an opt-in property of explicit collision volumes. + if (!has_bed_exclude_volumes(print.config())) + return result; + + std::vector> regions_by_extruder = get_bed_excluded_regions_by_extruder(print.config()); + for (std::vector ®ions : regions_by_extruder) + regions.erase(std::remove_if(regions.begin(), regions.end(), + [](const BedExcludeRegion ®ion) { return !region.is_collision_volume(); }), regions.end()); if (regions_by_extruder.empty() || std::all_of(regions_by_extruder.begin(), regions_by_extruder.end(), [](const std::vector ®ions) { return regions.empty(); })) diff --git a/src/slic3r/GUI/3DScene.cpp b/src/slic3r/GUI/3DScene.cpp index fb206c8e83..45cb00105d 100644 --- a/src/slic3r/GUI/3DScene.cpp +++ b/src/slic3r/GUI/3DScene.cpp @@ -30,6 +30,8 @@ #include #include +#include + #include #include @@ -1363,8 +1365,18 @@ bool GLVolumeCollection::check_outside_state(const BuildVolume &build_volume, Mo BuildVolume plate_build_volume(pp_bed_shape, build_volume.printable_height(), build_volume.extruder_areas(), build_volume.extruder_heights()); const std::vector& exclude_areas = curr_plate->get_exclude_areas(); - std::vector> exclusion_regions = - get_bed_excluded_regions_by_extruder(*GUI::wxGetApp().plater()->config()); + const DynamicPrintConfig *plater_config = GUI::wxGetApp().plater()->config(); + std::vector> exclusion_regions; + // Legacy bed-exclude areas retain Orca's existing 2D presentation. The + // per-extruder 3D state is needed only after collision volumes are enabled. + if (has_bed_exclude_volumes(*plater_config)) { + exclusion_regions = get_bed_excluded_regions_by_extruder(*plater_config); + // The native BuildVolume path below already presents the shared legacy + // area. Merge only opt-in collision volumes into nozzle-specific state. + for (std::vector ®ions : exclusion_regions) + regions.erase(std::remove_if(regions.begin(), regions.end(), + [](const BedExcludeRegion ®ion) { return !region.is_collision_volume(); }), regions.end()); + } const Vec3d plate_origin = curr_plate->get_origin(); const Point exclusion_offset(scale_(plate_origin.x()), scale_(plate_origin.y())); for (std::vector ®ions : exclusion_regions) diff --git a/src/slic3r/GUI/Jobs/ArrangeJob.cpp b/src/slic3r/GUI/Jobs/ArrangeJob.cpp index 4c0c1c0694..03274567f9 100644 --- a/src/slic3r/GUI/Jobs/ArrangeJob.cpp +++ b/src/slic3r/GUI/Jobs/ArrangeJob.cpp @@ -601,8 +601,6 @@ void ArrangeJob::process(Ctl &ctl) bool enable_wrapping = global_config.option("enable_wrapping_detection")->value; partplate_list.preprocess_exclude_areas(params.excluded_regions, global_config, enable_wrapping, 1, scale_(1)); - if (has_bed_exclusion_regions(params.excluded_regions)) - params.do_final_align = false; BOOST_LOG_TRIVIAL(debug) << "arrange bedpts:" << bedpts[0].transpose() << ", " << bedpts[1].transpose() << ", " << bedpts[2].transpose() << ", " << bedpts[3].transpose(); @@ -626,7 +624,6 @@ void ArrangeJob::process(Ctl &ctl) } arrangement::arrange(m_selected, m_unselected, bedpts, params); - invalidate_bed_exclusion_conflicts(m_selected, m_unselected); // sort by item id std::sort(m_selected.begin(), m_selected.end(), [](auto a, auto b) {return a.itemid < b.itemid; }); diff --git a/src/slic3r/GUI/Jobs/FillBedJob.cpp b/src/slic3r/GUI/Jobs/FillBedJob.cpp index 4e105c51ac..a59a610511 100644 --- a/src/slic3r/GUI/Jobs/FillBedJob.cpp +++ b/src/slic3r/GUI/Jobs/FillBedJob.cpp @@ -244,8 +244,6 @@ void FillBedJob::process(Ctl &ctl) }; // final align用的是凸包,在有fixed item的情况下可能找到的参考点位置是错的,这里就不做了。见STUDIO-3265 params.do_final_align = !is_bbl; - if (has_bed_exclusion_regions(params.excluded_regions)) - params.do_final_align = false; if (m_selected.size() > 100) { // too many items, just find grid empty cells to put them @@ -303,11 +301,8 @@ void FillBedJob::process(Ctl &ctl) } } - invalidate_bed_exclusion_conflicts( - m_selected, m_unselected, Vec2crd(scale_(plate_origin.x()), scale_(plate_origin.y()))); } else { arrangement::arrange(m_selected, m_unselected, m_bedpts, params); - invalidate_bed_exclusion_conflicts(m_selected, m_unselected); } // finalize just here. diff --git a/src/slic3r/GUI/PartPlate.cpp b/src/slic3r/GUI/PartPlate.cpp index ea55b53992..56e5016805 100644 --- a/src/slic3r/GUI/PartPlate.cpp +++ b/src/slic3r/GUI/PartPlate.cpp @@ -1233,9 +1233,16 @@ void PartPlate::update_exclusion_volume_preview_models() const std::vector> regions_by_extruder = get_bed_excluded_regions_by_extruder(*config); std::vector regions; - for (const std::vector &extruder_regions : regions_by_extruder) - regions.insert(regions.end(), extruder_regions.begin(), extruder_regions.end()); const BedExcludeVolumeMode mode = active_bed_exclude_volume_mode(*config); + for (size_t extruder_id = 0; extruder_id < regions_by_extruder.size(); ++extruder_id) { + if (mode == BedExcludeVolumeMode::Shared && extruder_id > 0) + break; + for (const BedExcludeRegion ®ion : regions_by_extruder[extruder_id]) { + if (!region.is_collision_volume() && extruder_id > 0) + continue; + regions.emplace_back(region); + } + } // A coloured border communicates which physical nozzle owns a footprint. // With only one nozzle the exclusion applies to every filament, so using // the first filament colour would incorrectly imply material ownership. @@ -1327,6 +1334,8 @@ void PartPlate::update_exclusion_volume_preview_models() } for (const BedExcludeRegion ®ion_src : regions_by_extruder[extruder_id]) { + if (!region_src.is_collision_volume()) + continue; Polygon footprint = region_src.polygon; footprint.translate(plate_offset); footprint.make_counter_clockwise(); @@ -1349,6 +1358,10 @@ void PartPlate::update_exclusion_volume_preview_models() break; for (const BedExcludeRegion ®ion_src : regions_by_extruder[extruder_id]) { + // The legacy area is shared and bed-fixed, even when nozzle-specific + // collision volumes are active. Keep only one preview copy. + if (!region_src.is_collision_volume() && extruder_id > 0) + continue; Polygon region = region_src.polygon; region.translate(plate_offset); region.make_counter_clockwise(); @@ -1357,10 +1370,9 @@ void PartPlate::update_exclusion_volume_preview_models() preview_regions.push_back({ std::move(translated_region), region, extruder_id }); preview_footprints.emplace_back(region); - // In non-shared modes these resolved regions are the authoritative bed - // preview, including legacy master polygons duplicated by nozzle offset. - // Shared legacy polygons continue to use m_exclude_triangles above. - if (region_src.is_collision_volume() || mode != BedExcludeVolumeMode::Shared) { + // Legacy polygons continue to use Orca's existing grey bed preview; + // the additional floor/ribbon belongs only to collision volumes. + if (region_src.is_collision_volume()) { if (!region_src.has_z_range || region_src.z_min <= EPSILON) { floor_regions.emplace_back(region); } else { @@ -1376,6 +1388,8 @@ void PartPlate::update_exclusion_volume_preview_models() if (preview_height > EPSILON) { for (const PreviewRegion &preview_region : preview_regions) { const BedExcludeRegion ®ion_src = preview_region.region; + if (!region_src.is_collision_volume()) + continue; const double z_min = region_src.has_z_range ? region_src.z_min : 0.0; const double z_max = std::min(region_src.z_max, preview_height); if (z_max > z_min + EPSILON) @@ -1409,7 +1423,7 @@ void PartPlate::update_exclusion_volume_preview_models() Polygon hull = instance->convex_hull_2d(); const BoundingBoxf3 instance_box = object->instance_convex_hull_bounding_box(instance_id); for (const PreviewRegion &preview_region : preview_regions) { - if (mode != BedExcludeVolumeMode::Shared && + if (preview_region.region.is_collision_volume() && mode != BedExcludeVolumeMode::Shared && relevant_extruders.find(preview_region.extruder_id) == relevant_extruders.end()) continue; @@ -3454,19 +3468,19 @@ bool PartPlate::check_outside(int obj_id, int instance_id, BoundingBoxf3* boundi const std::vector> regions_by_extruder = get_bed_excluded_regions_by_extruder(*config); const BedExcludeVolumeMode mode = active_bed_exclude_volume_mode(*config); - // The legacy outside flag has no filament/nozzle context. Keep it - // authoritative for the shared mode, but let the newer per-extruder - // placement pipeline handle offset/individual modes so a collision - // belonging to an unused nozzle does not block the whole plate. - checked_config_regions = mode != BedExcludeVolumeMode::Shared; + // The legacy outside flag has no filament/nozzle context. Always + // check the shared legacy area here, but let the newer per-extruder + // pipeline handle nozzle-specific collision volumes. const Point plate_offset(scale_(m_origin.x()), scale_(m_origin.y())); Polygon hull = instance->convex_hull_2d(); - const size_t groups_to_check = mode == BedExcludeVolumeMode::Shared && !regions_by_extruder.empty() ? 1 : 0; + const size_t groups_to_check = regions_by_extruder.empty() ? 0 : 1; for (size_t group_id = 0; group_id < groups_to_check; ++group_id) { const std::vector &extruder_regions = regions_by_extruder[group_id]; - checked_config_regions = checked_config_regions || !extruder_regions.empty(); for (const BedExcludeRegion ®ion_src : extruder_regions) { + if (mode != BedExcludeVolumeMode::Shared && region_src.is_collision_volume()) + continue; + checked_config_regions = true; Polygon region = region_src.polygon; region.translate(plate_offset); region.make_counter_clockwise(); @@ -6502,13 +6516,13 @@ bool PartPlateList::preprocess_exclude_areas(arrangement::ArrangePolygons &unsel for (size_t extruder_id = 0; extruder_id < extruder_count; ++extruder_id) { for (size_t region_id = 0; region_id < regions_by_extruder[extruder_id].size(); ++region_id) { const BedExcludeRegion ®ion = regions_by_extruder[extruder_id][region_id]; - const BoundingBox bbox = region.polygon.bounding_box(); - if (!bbox.defined || (region.has_z_range && region.z_max <= region.z_min + EPSILON)) + if (!region.is_collision_volume() || region.polygon.points.size() < 3 || + (region.has_z_range && region.z_max <= region.z_min + EPSILON)) continue; for (int plate_idx = 0; plate_idx < num_plates; ++plate_idx) { arrangement::ArrangePolygon blocker; - blocker.poly.contour = bbox.polygon(); + blocker.poly.contour = region.polygon; blocker.translation = Vec2crd::Zero(); blocker.rotation = 0.0; blocker.is_virt_object = true; @@ -6526,7 +6540,11 @@ bool PartPlateList::preprocess_exclude_areas(arrangement::ArrangePolygons &unsel added = true; } } - } else if (!m_exclude_areas.empty()) { + } + + // Keep Orca's established legacy-area arrange obstacle alongside any + // explicit collision-volume blockers. The two settings are additive. + if (!m_exclude_areas.empty()) { //has exclude areas PartPlate *plate = m_plate_list[0]; diff --git a/src/slic3r/GUI/Tab.cpp b/src/slic3r/GUI/Tab.cpp index ed9de1938f..2900d6a305 100644 --- a/src/slic3r/GUI/Tab.cpp +++ b/src/slic3r/GUI/Tab.cpp @@ -1868,21 +1868,6 @@ void Tab::on_value_change(const std::string& opt_key, const boost::any& value) } } - // Editing the dedicated collision-volume fields is an explicit opt-in to - // the new behaviour. Keep presets unambiguous by removing any legacy area; - // the resolver still gives volumes precedence when externally authored - // profiles contain both keys. - if (m_type == Preset::TYPE_PRINTER && - (opt_key == "bed_exclude_volumes" || opt_key.rfind("extruder_bed_exclude_volumes#", 0) == 0)) { - const std::string *definition = boost::any_cast(&value); - const ConfigOptionPoints *legacy = m_config->option("bed_exclude_area"); - if (definition != nullptr && !definition->empty() && legacy != nullptr && !legacy->values.empty()) { - DynamicPrintConfig converted = *m_config; - converted.set_key_value("bed_exclude_area", new ConfigOptionPoints()); - m_config_manipulation.apply(m_config, &converted); - } - } - // Keep this preset's "plugins" manifest in sync when a plugin picker changes, so full_config() and // save_to_json() always find resolved "name;uuid;capability" references and rebuild it nowhere else. // Also drop any plugin config override entries for a capability the change just stopped @@ -5152,12 +5137,9 @@ void TabPrinter::build_fff() return create_bed_shape_widget(parent); }); optgroup->append_single_option_line("parallel_printheads_count"); - Option option = optgroup->get_option("bed_exclude_area"); - option.opt.full_width = true; - optgroup->append_single_option_line(option, "printer_basic_information_printable_space#excluded-bed-area"); - Line convert_exclusion_line = Line{ L("Collision checking"), L("Convert the legacy excluded bed area into a collision volume so Orca can check G-code moves and reroute travel around it.") }; - convert_exclusion_line.widget = [this](wxWindow *parent) { + create_line_with_widget(optgroup.get(), "bed_exclude_area", "printer_basic_information_printable_space#excluded-bed-area", [this](wxWindow *parent) { Button *button = new Button(parent, _L("Convert area to collision volume")); + button->SetToolTip(_L("Convert the legacy excluded bed area into a collision volume so Orca can check G-code moves and reroute travel around it.")); wxSizer *sizer = new wxBoxSizer(wxHORIZONTAL); sizer->Add(button); button->Bind(wxEVT_BUTTON, [this](wxCommandEvent &) { @@ -5185,8 +5167,7 @@ void TabPrinter::build_fff() wxGetApp().plater()->update(); }); return sizer; - }; - optgroup->append_line(convert_exclusion_line); + }); Option volume_option = optgroup->get_option("bed_exclude_volumes"); volume_option.opt.full_width = true; @@ -6260,7 +6241,9 @@ void TabPrinter::toggle_options() const size_t exclusion_extruder_count = m_preset_bundle->get_printer_extruder_count(); const bool collision_volumes_enabled = has_bed_exclude_volumes(*m_config); const BedExcludeVolumeMode exclusion_mode = active_bed_exclude_volume_mode(*m_config); - toggle_option("bed_exclude_area", !collision_volumes_enabled); + // Legacy areas and collision volumes are additive. Keep the established + // material keep-out editable while the opt-in motion constraints exist. + toggle_option("bed_exclude_area", true); toggle_line("bed_exclude_volume_mode", collision_volumes_enabled && exclusion_extruder_count > 1); toggle_line("bed_exclude_volumes", exclusion_extruder_count <= 1 || exclusion_mode != BedExcludeVolumeMode::PerExtruder); diff --git a/tests/fff_print/test_exclusion_volumes.cpp b/tests/fff_print/test_exclusion_volumes.cpp index bb3cd90aef..5a530b0f48 100644 --- a/tests/fff_print/test_exclusion_volumes.cpp +++ b/tests/fff_print/test_exclusion_volumes.cpp @@ -527,6 +527,26 @@ TEST_CASE("Travel router uses only the active nozzle exclusion set", "[Exclusion CHECK(clear.detail == ExclusionVolumeTravelAvoidance::Detail::NoActiveObstacles); } +TEST_CASE("Travel router accepts firmware positions outside the printable boundary", "[ExclusionVolume][TravelRouting]") +{ + ExclusionVolumeTravelAvoidance router; + router.init(static_config(exclusion_config()), Vec3d::Zero()); + + SECTION("start outside") { + const auto result = router.route( + travel({Vec2d(-5.0, 50.0), Vec2d(80.0, 50.0)}), 5.0, 5.0, 0); + REQUIRE(result.status == ExclusionVolumeTravelAvoidance::Status::Rerouted); + check_path_avoids_rect(result.path, Rect{40.0, 40.0, 60.0, 60.0}); + } + + SECTION("end outside") { + const auto result = router.route( + travel({Vec2d(20.0, 50.0), Vec2d(105.0, 50.0)}), 5.0, 5.0, 0); + REQUIRE(result.status == ExclusionVolumeTravelAvoidance::Status::Rerouted); + check_path_avoids_rect(result.path, Rect{40.0, 40.0, 60.0, 60.0}); + } +} + TEST_CASE("G-code processor ignores the artificial first XY origin and checks subsequent travel", "[ExclusionVolume][GCodeProcessor]") { const FullPrintConfig config = static_config(exclusion_config()); diff --git a/tests/libslic3r/test_arrange.cpp b/tests/libslic3r/test_arrange.cpp index b4f0a73699..6d2b493f25 100644 --- a/tests/libslic3r/test_arrange.cpp +++ b/tests/libslic3r/test_arrange.cpp @@ -364,36 +364,6 @@ TEST_CASE("Shared bed exclusions apply to every arranged object", "[Arrange][Exc CHECK(bed_exclusion_applies(object, shared)); } -TEST_CASE("Conservative exclusion validation invalidates only relevant placements", "[Arrange][ExclusionVolume][MultiNozzle]") -{ - ArrangePolygon exclusion = make_square(scaled(20.)); - exclusion.is_bed_exclusion = true; - exclusion.bed_exclusion_extruder_id = 0; - exclusion.has_z_range = true; - exclusion.z_min = 0.0; - exclusion.z_max = 30.0; - - ArrangePolygon relevant = make_square(scaled(10.)); - relevant.bed_exclusion_extruder_ids = {0}; - relevant.has_z_range = true; - relevant.z_min = 0.0; - relevant.z_max = 10.0; - - ArrangePolygon other_nozzle = relevant; - other_nozzle.bed_exclusion_extruder_ids = {1}; - - ArrangePolygon above = relevant; - above.z_min = 31.0; - above.z_max = 40.0; - - ArrangePolygons items{relevant, other_nozzle, above}; - invalidate_bed_exclusion_conflicts(items, {exclusion}); - - CHECK(items[0].bed_idx == UNARRANGED); - CHECK(items[1].bed_idx == 0); - CHECK(items[2].bed_idx == 0); -} - TEST_CASE("Arrange keeps relevant objects outside conditional exclusion obstacles", "[Arrange][ExclusionVolume]") { ArrangePolygon exclusion = make_square(scaled(30.)); diff --git a/tests/libslic3r/test_exclusion_volumes.cpp b/tests/libslic3r/test_exclusion_volumes.cpp index e5ad6b5fff..e5f07ad64a 100644 --- a/tests/libslic3r/test_exclusion_volumes.cpp +++ b/tests/libslic3r/test_exclusion_volumes.cpp @@ -7,6 +7,7 @@ #include "libslic3r/TriangleMesh.hpp" #include +#include #include #include @@ -105,10 +106,13 @@ TEST_CASE("Exclusion syntax validation accepts supported forms and rejects malfo {"", true}, {"0x0,10x0,10x10,0x10", true}, {"0..10;0x0,10x0,10x10,0x10", true}, + {"0.5..10.5;0x0,10x0,10x10,0x10", true}, {"..10;0x0,10x0,10x10,0x10", true}, {"10..;0x0,10x0,10x10,0x10", true}, {"0x0,10x0,10x10,0x10|20x20,30x20,30x30,20x30", true}, {"20..10;0x0,10x0,10x10,0x10", false}, + {"10..10;0x0,10x0,10x10,0x10", false}, + {"300..400;0x0,10x0,10x10,0x10", false}, {"zero..10;0x0,10x0,10x10,0x10", false}, {"0..10;0x0,10x0", false}, {"0..10;", false}, @@ -167,7 +171,7 @@ TEST_CASE("CLI keeps legacy areas and collision volumes on separate options", "[ CHECK_FALSE(legacy_config.read_cli(3, legacy_argv, &extra, &keys)); } -TEST_CASE("Legacy areas remain material keep-outs until collision volumes are configured", "[ExclusionVolume][PrintConfig]") +TEST_CASE("Legacy areas and collision volumes remain additive", "[ExclusionVolume][PrintConfig]") { DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); config.set_key_value("printable_height", new ConfigOptionFloat(100.0)); @@ -180,20 +184,23 @@ TEST_CASE("Legacy areas remain material keep-outs until collision volumes are co config.set_key_value("bed_exclude_volumes", new ConfigOptionString("20x20,30x20,30x30,20x30")); regions = get_bed_excluded_regions(config); - REQUIRE(regions.size() == 1); - CHECK(regions.front().is_collision_volume()); - CHECK(regions.front().polygon.contains(Point::new_scale(25.0, 25.0))); - CHECK_FALSE(regions.front().polygon.contains(Point::new_scale(5.0, 5.0))); + REQUIRE(regions.size() == 2); + CHECK_FALSE(regions[0].is_collision_volume()); + CHECK(regions[0].polygon.contains(Point::new_scale(5.0, 5.0))); + CHECK(regions[1].is_collision_volume()); + CHECK(regions[1].polygon.contains(Point::new_scale(25.0, 25.0))); } -TEST_CASE("A nonempty invalid collision-volume definition never falls back to the legacy area", "[ExclusionVolume][PrintConfig]") +TEST_CASE("An invalid collision-volume definition does not suppress the legacy area", "[ExclusionVolume][PrintConfig]") { DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); config.set_deserialize_strict("bed_exclude_area", "0x0,10x0,10x10,0x10"); config.set_key_value("bed_exclude_volumes", new ConfigOptionString("not a polygon")); CHECK(has_bed_exclude_volumes(config)); - CHECK(get_bed_excluded_regions(config).empty()); + const auto regions = get_bed_excluded_regions(config); + REQUIRE(regions.size() == 1); + CHECK_FALSE(regions.front().is_collision_volume()); CHECK_FALSE(is_valid_bed_exclude_volumes_string(config.opt_string("bed_exclude_volumes"), 100.0)); } @@ -247,6 +254,27 @@ TEST_CASE("Toolhead-relative exclusion volumes follow nozzle offset deltas", "[E CHECK_THAT(unscaled_x(shifted.min.y() - reference.min.y()), WithinAbs(5.0, 1e-6)); } +TEST_CASE("Toolhead-relative mode offsets collision volumes but not the shared legacy area", "[ExclusionVolume][PrintConfig][MultiNozzle]") +{ + DynamicPrintConfig config = two_extruder_config(); + config.set_deserialize_strict("bed_exclude_area", "70x70,80x70,80x80,70x80"); + config.set_key_value("bed_exclude_volume_mode", new ConfigOptionEnum(BedExcludeVolumeMode::ToolheadOffset)); + + const auto groups = get_bed_excluded_regions_by_extruder(config); + REQUIRE(groups.size() == 2); + REQUIRE(groups[0].size() == 2); + REQUIRE(groups[1].size() == 2); + CHECK_FALSE(groups[0][0].is_collision_volume()); + CHECK_FALSE(groups[1][0].is_collision_volume()); + CHECK(groups[0][0].polygon.points == groups[1][0].polygon.points); + CHECK(groups[0][1].polygon.points != groups[1][1].polygon.points); + + const auto flattened = get_bed_excluded_regions(config); + CHECK(flattened.size() == 3); + CHECK(std::count_if(flattened.begin(), flattened.end(), + [](const BedExcludeRegion ®ion) { return !region.is_collision_volume(); }) == 1); +} + TEST_CASE("Toolhead-relative exclusions honour a non-default reference extruder", "[ExclusionVolume][PrintConfig][MultiNozzle]") { DynamicPrintConfig config = two_extruder_config(); @@ -277,6 +305,44 @@ TEST_CASE("Individual exclusion volumes remain authoritative per extruder", "[Ex CHECK(get_bed_excluded_regions(config).size() == 2); } +TEST_CASE("Individual collision volumes retain the shared legacy area", "[ExclusionVolume][PrintConfig][MultiNozzle]") +{ + DynamicPrintConfig config = two_extruder_config(); + config.set_deserialize_strict("bed_exclude_area", "70x70,80x70,80x80,70x80"); + config.set_key_value("bed_exclude_volume_mode", new ConfigOptionEnum(BedExcludeVolumeMode::PerExtruder)); + config.set_key_value("extruder_bed_exclude_volumes", new ConfigOptionStrings{ + "0..25;0x0,8x0,8x8,0x8", "0..25;20x0,28x0,28x8,20x8" + }); + + const auto groups = get_bed_excluded_regions_by_extruder(config); + REQUIRE(groups.size() == 2); + REQUIRE(groups[0].size() == 2); + REQUIRE(groups[1].size() == 2); + CHECK_FALSE(groups[0][0].is_collision_volume()); + CHECK(groups[0][0].polygon.points == groups[1][0].polygon.points); + CHECK(groups[0][1].is_collision_volume()); + CHECK(groups[1][1].is_collision_volume()); +} + +TEST_CASE("Individual exclusion validation accepts omitted trailing extruders", "[ExclusionVolume][PrintConfig][MultiNozzle]") +{ + DynamicPrintConfig dynamic = two_extruder_config(); + dynamic.set_key_value("bed_exclude_volume_mode", + new ConfigOptionEnum(BedExcludeVolumeMode::PerExtruder)); + dynamic.set_key_value("extruder_bed_exclude_volumes", + new ConfigOptionStrings{"0..25;0x0,8x0,8x8,0x8"}); + + FullPrintConfig config; + config.apply(dynamic, true); + const std::map errors = validate(config); + CHECK(errors.find("extruder_bed_exclude_volumes") == errors.end()); + + const auto groups = get_bed_excluded_regions_by_extruder(config); + REQUIRE(groups.size() == 2); + CHECK(groups[0].size() == 1); + CHECK(groups[1].empty()); +} + TEST_CASE("Legacy bed helpers include only regions touching the first layer", "[ExclusionVolume][PrintConfig]") { DynamicPrintConfig dynamic = DynamicPrintConfig::full_print_config(); From 432debfc74a7e62e84b1af420804c47590ace43f Mon Sep 17 00:00:00 2001 From: Harry Loud Date: Thu, 24 Sep 2026 09:09:03 +0100 Subject: [PATCH 29/38] Restore shared printer option variable --- src/slic3r/GUI/Tab.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/slic3r/GUI/Tab.cpp b/src/slic3r/GUI/Tab.cpp index 2900d6a305..c7ff94669a 100644 --- a/src/slic3r/GUI/Tab.cpp +++ b/src/slic3r/GUI/Tab.cpp @@ -5169,9 +5169,9 @@ void TabPrinter::build_fff() return sizer; }); - Option volume_option = optgroup->get_option("bed_exclude_volumes"); - volume_option.opt.full_width = true; - optgroup->append_single_option_line(volume_option); + Option option = optgroup->get_option("bed_exclude_volumes"); + option.opt.full_width = true; + optgroup->append_single_option_line(option); optgroup->append_single_option_line("bed_exclude_volume_mode"); // optgroup->append_single_option_line("printable_area"); optgroup->append_single_option_line("printable_height", "printer_basic_information_printable_space#printable-height"); From 7481fdcdaed9c5c4138178acbd66b9ece6c4dc90 Mon Sep 17 00:00:00 2001 From: Harry Loud Date: Thu, 24 Sep 2026 13:54:26 +0100 Subject: [PATCH 30/38] Fix exclusion conversion and legacy brim clipping --- src/libslic3r/Brim.cpp | 10 ++-- src/libslic3r/ExclusionVolumeGeometry.cpp | 17 ++++++ src/libslic3r/ExclusionVolumeGeometry.hpp | 4 ++ src/libslic3r/Model.cpp | 5 +- src/libslic3r/PrintConfig.cpp | 53 +++++++++++++++++-- src/libslic3r/PrintConfig.hpp | 8 +++ src/slic3r/GUI/PartPlate.cpp | 3 +- src/slic3r/GUI/Tab.cpp | 24 ++++----- tests/fff_print/test_exclusion_volumes.cpp | 19 ++++++- tests/libslic3r/test_exclusion_volumes.cpp | 60 ++++++++++++++++++++++ 10 files changed, 179 insertions(+), 24 deletions(-) diff --git a/src/libslic3r/Brim.cpp b/src/libslic3r/Brim.cpp index f1bbfa67de..a40fdd13f2 100644 --- a/src/libslic3r/Brim.cpp +++ b/src/libslic3r/Brim.cpp @@ -440,8 +440,8 @@ static ExPolygons outer_inner_brim_area(const Print& print, std::vector> exclusion_regions_by_extruder; if (has_bed_exclude_volumes(print.config())) { exclusion_regions_by_extruder = get_bed_excluded_regions_by_extruder(print.config()); - // Legacy areas historically constrain placement, not generated - // geometry. Only explicit collision volumes may trim a brim. + // The established bed polygon below still clips the bed edge and + // legacy areas. Only explicit volumes use the new Z-aware trimming. for (std::vector ®ions : exclusion_regions_by_extruder) regions.erase(std::remove_if(regions.begin(), regions.end(), [](const BedExcludeRegion ®ion) { return !region.is_collision_volume(); }), regions.end()); @@ -646,6 +646,8 @@ static ExPolygons outer_inner_brim_area(const Print& print, if (extruder_unprintable_area.empty()) { extruder_unprintable_area.resize(extruder_nums, Polygons{Model::getBedPolygon()}); } + const size_t physical_extruder_count = std::max( + print.config().nozzle_diameter.size(), extruder_unprintable_area.size()); if (print.has_wipe_tower() && !print.get_fake_wipe_tower().outer_wall.empty()) { ExPolygons expolyFromLines{}; for (auto polyline : print.get_fake_wipe_tower().outer_wall.begin()->second) { @@ -665,7 +667,7 @@ static ExPolygons outer_inner_brim_area(const Print& print, if (iter != objPrintVec.end() && iter->second > 0) { object_physical_extruders = bed_exclusion_physical_extruders( - print, { iter->second - 1 }, exclusion_regions_by_extruder.size(), 0); + print, { iter->second - 1 }, physical_extruder_count, 0); for (const size_t extruder_id : object_physical_extruders) { if (extruder_id >= extruder_unprintable_area.size()) continue; @@ -678,7 +680,7 @@ static ExPolygons outer_inner_brim_area(const Print& print, } if (object_physical_extruders.empty()) { - object_physical_extruders.resize(exclusion_regions_by_extruder.size()); + object_physical_extruders.resize(physical_extruder_count); std::iota(object_physical_extruders.begin(), object_physical_extruders.end(), size_t(0)); } const ExPolygons exclusions = active_bed_exclusion_footprints( diff --git a/src/libslic3r/ExclusionVolumeGeometry.cpp b/src/libslic3r/ExclusionVolumeGeometry.cpp index af1bf25091..b7bae0bb30 100644 --- a/src/libslic3r/ExclusionVolumeGeometry.cpp +++ b/src/libslic3r/ExclusionVolumeGeometry.cpp @@ -1,6 +1,8 @@ #include "ExclusionVolumeGeometry.hpp" +#include "BoundingBox.hpp" #include "ClipperUtils.hpp" +#include "Geometry/ConvexHull.hpp" #include "Print.hpp" #include @@ -57,6 +59,21 @@ bool bed_exclusion_z_ranges_overlap( return first_max >= second_min - Z_EPSILON_MM && first_min <= second_max + Z_EPSILON_MM; } +Polygon bed_exclusion_arrange_polygon(const Polygon &polygon) +{ + if (polygon.points.size() < 3) + return polygon; + + const Polygon convex_hull = Geometry::convex_hull(polygon.points); + const double polygon_area = std::abs(polygon.area()); + const double hull_area = std::abs(convex_hull.area()); + const double tolerance = std::max(1.0, hull_area) * 1e-12; + if (std::abs(hull_area - polygon_area) <= tolerance) + return polygon; + + return get_extents(polygon).polygon(); +} + ExPolygons active_bed_exclusion_footprints( const std::vector ®ions, const double z_min, diff --git a/src/libslic3r/ExclusionVolumeGeometry.hpp b/src/libslic3r/ExclusionVolumeGeometry.hpp index cbf7140b85..5bcaaaa5aa 100644 --- a/src/libslic3r/ExclusionVolumeGeometry.hpp +++ b/src/libslic3r/ExclusionVolumeGeometry.hpp @@ -14,6 +14,10 @@ class PrintObject; bool bed_exclusion_z_ranges_overlap(double first_min, double first_max, double second_min, double second_max); +// libnest2d currently accepts only convex fixed obstacles. Keep convex +// exclusions exact and conservatively use the bounding box for concave ones. +Polygon bed_exclusion_arrange_polygon(const Polygon &polygon); + // Return the union of exclusion footprints intersecting the requested extrusion // slab. Regions are already resolved into physical-nozzle/model coordinates by // PrintConfig; callers only provide the physical nozzles that may emit the diff --git a/src/libslic3r/Model.cpp b/src/libslic3r/Model.cpp index 135004821a..55fbae6bda 100644 --- a/src/libslic3r/Model.cpp +++ b/src/libslic3r/Model.cpp @@ -3108,7 +3108,10 @@ void Model::setPrintSpeedTable(const DynamicPrintConfig& config, const PrintConf //auto print_config = print.config(); //printSpeedMap.bed_poly.points = get_bed_shape(*(wxGetApp().plater()->config())); printSpeedMap.bed_poly.points = get_bed_shape(config); - Pointfs excluse_area_points = has_bed_exclude_volumes(print_config) ? Pointfs{} : print_config.bed_exclude_area.values; + // Collision volumes are additive to the legacy bed keep-out. Preserve the + // established printable-bed polygon so bed-edge and legacy-area brim + // clipping continue to work when collision volumes are also configured. + Pointfs excluse_area_points = print_config.bed_exclude_area.values; Polygons exclude_polys; Polygon exclude_poly; for (int i = 0; i < excluse_area_points.size(); i++) { diff --git a/src/libslic3r/PrintConfig.cpp b/src/libslic3r/PrintConfig.cpp index 862955d192..e1dd457bce 100644 --- a/src/libslic3r/PrintConfig.cpp +++ b/src/libslic3r/PrintConfig.cpp @@ -900,14 +900,15 @@ void PrintConfigDef::init_common_params() def->label = L("Exclusion volumes"); def->tooltip = L("Collision volumes used for model and generated-material exclusion, G-code checking, and travel avoidance. " "Use \"XxY, XxY, ...\" for a full-height polygon or \"ZMIN..ZMAX;XxY, XxY, ...\" for a Z-limited volume. " - "Separate multiple volumes with \"|\". These volumes are additional to any legacy excluded bed area."); + "Separate multiple volumes with \"|\". These volumes are additional to any legacy excluded bed area. " + "Automatic arrangement conservatively uses the bounding box of a non-convex volume."); def->mode = comAdvanced; def->gui_type = ConfigOptionDef::GUIType::one_string; def->set_default_value(new ConfigOptionString()); def = this->add("bed_exclude_volume_mode", coEnum); def->label = L("Exclusion volume behaviour"); - def->tooltip = L("Choose whether all nozzles use the same exclusion volumes, derive toolhead-relative volumes from each nozzle's XY offset, or configure independent volumes for every extruder."); + def->tooltip = L("Choose whether all nozzles use the same exclusion volumes, derive toolhead-relative volumes from each nozzle's XY offset, or configure independent volumes for every extruder. In individual mode, configure the volumes on each Extruder page."); def->enum_keys_map = &ConfigOptionEnum::get_enum_values(); def->enum_values = { "shared", "toolhead_offset", "per_extruder" }; def->enum_labels = { L("Shared"), L("Toolhead-relative (nozzle offsets)"), L("Individual per extruder") }; @@ -916,7 +917,7 @@ void PrintConfigDef::init_common_params() def = this->add("extruder_bed_exclude_volumes", coStrings); def->label = L("Extruder exclusion volumes"); - def->tooltip = L("Collision volumes used only by this extruder in individual mode. Use the same polygon and optional Z-range format as the shared exclusion volumes. Leave empty for no exclusion volumes on this extruder."); + def->tooltip = L("Collision volumes used only by this extruder in individual mode. Use the same polygon and optional Z-range format as the shared exclusion volumes. Leave empty for no exclusion volumes on this extruder. Automatic arrangement conservatively uses the bounding box of a non-convex volume."); def->mode = comAdvanced; def->gui_type = ConfigOptionDef::GUIType::one_string; def->set_default_value(new ConfigOptionStrings{ "" }); @@ -13355,6 +13356,52 @@ bool is_valid_bed_exclude_volumes_string(const std::string &value, const double return found_nonempty; } +std::string legacy_bed_exclude_area_to_volumes(const Pointfs &points) +{ + // The legacy option has always interpreted each consecutive group of four + // points as a separate rectangular keep-out. Preserve that meaning instead + // of joining several rectangles into one invalid concave polygon. + if (points.size() < 4 || points.size() % 4 != 0) + return {}; + + std::string result; + for (size_t offset = 0; offset < points.size(); offset += 4) { + const Pointfs rectangle(points.begin() + offset, points.begin() + offset + 4); + const std::string serialized = ConfigOptionPoints(rectangle).serialize(); + if (!result.empty()) + result += '|'; + result += serialized; + } + return result; +} + +void append_bed_exclude_volumes(DynamicPrintConfig &config, const std::string &definition) +{ + if (definition.empty()) + return; + + const auto append = [&definition](const std::string ¤t) { + return current.empty() ? definition : current + '|' + definition; + }; + const BedExcludeVolumeMode mode = config.has("bed_exclude_volume_mode") ? + config.opt_enum("bed_exclude_volume_mode") : BedExcludeVolumeMode::Shared; + if (mode == BedExcludeVolumeMode::PerExtruder) { + const ConfigOptionStrings *current = config.option("extruder_bed_exclude_volumes"); + std::vector definitions = current != nullptr ? current->values : std::vector{}; + const ConfigOptionFloats *nozzles = config.option("nozzle_diameter"); + const size_t extruder_count = std::max(1, nozzles != nullptr ? nozzles->size() : 0); + definitions.resize(std::max(definitions.size(), extruder_count)); + for (size_t extruder_id = 0; extruder_id < extruder_count; ++extruder_id) + definitions[extruder_id] = append(definitions[extruder_id]); + config.set_key_value("extruder_bed_exclude_volumes", new ConfigOptionStrings(std::move(definitions))); + return; + } + + const ConfigOptionString *current = config.option("bed_exclude_volumes"); + config.set_key_value("bed_exclude_volumes", new ConfigOptionString( + append(current != nullptr ? current->value : std::string{}))); +} + bool has_bed_exclude_volumes(const DynamicPrintConfig &cfg) { const ConfigOptionString *shared = cfg.opt("bed_exclude_volumes"); diff --git a/src/libslic3r/PrintConfig.hpp b/src/libslic3r/PrintConfig.hpp index 32b5279758..35cc6f8cfd 100644 --- a/src/libslic3r/PrintConfig.hpp +++ b/src/libslic3r/PrintConfig.hpp @@ -2348,6 +2348,14 @@ int bed_exclusion_extruder_for_filament(size_t filament_id, const std::vector(BedExcludeVolumeMode::Shared)); + append_bed_exclude_volumes(converted, *definition); converted.set_key_value("bed_exclude_area", new ConfigOptionPoints()); load_config(converted); on_presets_changed(); @@ -5138,29 +5136,29 @@ void TabPrinter::build_fff() }); optgroup->append_single_option_line("parallel_printheads_count"); create_line_with_widget(optgroup.get(), "bed_exclude_area", "printer_basic_information_printable_space#excluded-bed-area", [this](wxWindow *parent) { - Button *button = new Button(parent, _L("Convert area to collision volume")); - button->SetToolTip(_L("Convert the legacy excluded bed area into a collision volume so Orca can check G-code moves and reroute travel around it.")); + Button *button = new Button(parent, _L("Convert") + " " + dots); + button->SetStyle(ButtonStyle::Regular, ButtonType::Parameter); + button->SetToolTip(_L("Convert each legacy excluded-bed rectangle into a full-height collision volume. Existing collision volumes and the selected multi-nozzle behaviour are preserved.")); wxSizer *sizer = new wxBoxSizer(wxHORIZONTAL); - sizer->Add(button); + sizer->Add(button, 0, wxALIGN_CENTER_VERTICAL); button->Bind(wxEVT_BUTTON, [this](wxCommandEvent &) { const ConfigOptionPoints *legacy = m_config->option("bed_exclude_area"); - if (legacy == nullptr || legacy->values.size() < 3) { - show_error(wxGetApp().plater(), _L("Configure a valid excluded bed area before converting it.")); + const std::string definition = legacy != nullptr ? + legacy_bed_exclude_area_to_volumes(legacy->values) : std::string{}; + if (definition.empty()) { + show_error(wxGetApp().plater(), _L("Configure a valid legacy excluded bed area containing one or more four-corner rectangles before converting it.")); return; } - const std::string definition = legacy->serialize(); MessageDialog dialog( wxGetApp().plater(), - _L("Convert this legacy excluded bed area into a full-height collision volume? This enables G-code checking and travel avoidance."), + _L("Convert the legacy excluded bed area into full-height collision volumes? They will be added to any existing collision volumes, the current multi-nozzle behaviour will be preserved, and the legacy area will be cleared."), _L("Convert exclusion volume"), wxICON_QUESTION | wxYES | wxNO); if (dialog.ShowModal() != wxID_YES) return; DynamicPrintConfig converted = *m_config; - converted.set_key_value("bed_exclude_volumes", new ConfigOptionString(definition)); - converted.set_key_value("bed_exclude_volume_mode", - new ConfigOptionEnum(BedExcludeVolumeMode::Shared)); + append_bed_exclude_volumes(converted, definition); converted.set_key_value("bed_exclude_area", new ConfigOptionPoints()); load_config(converted); on_presets_changed(); diff --git a/tests/fff_print/test_exclusion_volumes.cpp b/tests/fff_print/test_exclusion_volumes.cpp index 5a530b0f48..d37e12e59d 100644 --- a/tests/fff_print/test_exclusion_volumes.cpp +++ b/tests/fff_print/test_exclusion_volumes.cpp @@ -231,9 +231,10 @@ struct BrimRun { double total_length {0.0}; bool intersects_test_region {false}; + bool leaves_bed {false}; }; -BrimRun generate_brim(const std::string &exclusion_definition) +BrimRun generate_brim(const std::string &exclusion_definition, const Vec2d &object_position = Vec2d(40.0, 40.0)) { DynamicPrintConfig config = exclusion_config(BedExcludeVolumeMode::Shared, exclusion_definition); config.set_deserialize_strict({ @@ -244,7 +245,7 @@ BrimRun generate_brim(const std::string &exclusion_definition) }); TriangleMesh mesh = make_cube(20.0, 20.0, 20.0); - mesh.translate(40.0f, 40.0f, 0.0f); + mesh.translate(float(object_position.x()), float(object_position.y()), 0.0f); Print print; Model model; Test::init_print(std::vector{std::move(mesh)}, print, model, config, nullptr, false); @@ -262,6 +263,13 @@ BrimRun generate_brim(const std::string &exclusion_definition) result.total_length += path.length(); result.intersects_test_region = !intersection_pl(paths, Polygons{rectangle(32.0, 35.0, 38.0, 65.0)}).empty(); + result.leaves_bed = std::any_of(paths.begin(), paths.end(), [](const Polyline &path) { + return std::any_of(path.points.begin(), path.points.end(), [](const Point &point) { + const Vec2d position = to_mm(point); + return position.x() < -EPSILON || position.x() > 100.0 + EPSILON || + position.y() < -EPSILON || position.y() > 100.0 + EPSILON; + }); + }); return result; } @@ -640,6 +648,13 @@ TEST_CASE("Brim paths are clipped only by exclusions active on the first layer", CHECK(active.total_length < raised.total_length); } +TEST_CASE("Brim paths remain clipped to the bed without collision volumes", "[ExclusionVolume][Brim][Regression]") +{ + const BrimRun brim = generate_brim("", Vec2d(21.0, 5.0)); + REQUIRE(brim.total_length > 0.0); + CHECK_FALSE(brim.leaves_bed); +} + TEST_CASE("Support exclusion masks follow explicit and current-filament roles", "[ExclusionVolume][Support][MultiNozzle]") { SECTION("explicit support roles select one physical nozzle each") { diff --git a/tests/libslic3r/test_exclusion_volumes.cpp b/tests/libslic3r/test_exclusion_volumes.cpp index e5f07ad64a..9bb01ff91b 100644 --- a/tests/libslic3r/test_exclusion_volumes.cpp +++ b/tests/libslic3r/test_exclusion_volumes.cpp @@ -100,6 +100,48 @@ TEST_CASE("Legacy point options reject collision-volume syntax", "[ExclusionVolu CHECK(is_bed_exclusion_volume_syntax(definition)); } +TEST_CASE("Legacy rectangle groups convert into separate collision volumes", "[ExclusionVolume][PrintConfig]") +{ + ConfigOptionPoints legacy; + REQUIRE(legacy.deserialize("0x0,10x0,10x10,0x10,20x20,30x20,30x30,20x30")); + CHECK(legacy_bed_exclude_area_to_volumes(legacy.values) == + "0x0,10x0,10x10,0x10|20x20,30x20,30x30,20x30"); + + legacy.values.pop_back(); + CHECK(legacy_bed_exclude_area_to_volumes(legacy.values).empty()); +} + +TEST_CASE("Converted volumes preserve existing definitions and nozzle mode", "[ExclusionVolume][PrintConfig][MultiNozzle]") +{ + const std::string converted = "40x40,50x40,50x50,40x50"; + + SECTION("toolhead-relative definitions remain shared") { + DynamicPrintConfig config = two_extruder_config(); + config.set_key_value("bed_exclude_volume_mode", + new ConfigOptionEnum(BedExcludeVolumeMode::ToolheadOffset)); + append_bed_exclude_volumes(config, converted); + + CHECK(config.opt_enum("bed_exclude_volume_mode") == BedExcludeVolumeMode::ToolheadOffset); + CHECK(config.opt_string("bed_exclude_volumes") == + "10..30;0x0,10x0,10x10,0x10|40x40,50x40,50x50,40x50"); + } + + SECTION("individual definitions receive the former shared keep-out") { + DynamicPrintConfig config = two_extruder_config(); + config.set_key_value("bed_exclude_volume_mode", + new ConfigOptionEnum(BedExcludeVolumeMode::PerExtruder)); + config.set_key_value("extruder_bed_exclude_volumes", new ConfigOptionStrings{"", "60x60,70x60,70x70,60x70"}); + append_bed_exclude_volumes(config, converted); + + CHECK(config.opt_enum("bed_exclude_volume_mode") == BedExcludeVolumeMode::PerExtruder); + const ConfigOptionStrings *per_extruder = config.option("extruder_bed_exclude_volumes"); + REQUIRE(per_extruder != nullptr); + REQUIRE(per_extruder->values.size() == 2); + CHECK(per_extruder->values[0] == converted); + CHECK(per_extruder->values[1] == "60x60,70x60,70x70,60x70|40x40,50x40,50x50,40x50"); + } +} + TEST_CASE("Exclusion syntax validation accepts supported forms and rejects malformed regions", "[ExclusionVolume][PrintConfig]") { const auto [definition, valid] = GENERATE(table({ @@ -379,6 +421,24 @@ TEST_CASE("Exclusion Z overlap treats touching slabs conservatively", "[Exclusio CHECK_FALSE(bed_exclusion_z_ranges_overlap(0.0, 9.0, 10.0, 20.0)); } +TEST_CASE("Arrange keeps convex exclusions exact and bounds concave exclusions", "[ExclusionVolume][Geometry][Arrange]") +{ + const Polygon convex = rectangle(0.0, 0.0, 10.0, 10.0); + CHECK(bed_exclusion_arrange_polygon(convex).points == convex.points); + + Polygon concave({ + Point::new_scale(0.0, 0.0), Point::new_scale(10.0, 0.0), + Point::new_scale(10.0, 4.0), Point::new_scale(4.0, 4.0), + Point::new_scale(4.0, 10.0), Point::new_scale(0.0, 10.0), + }); + concave.make_counter_clockwise(); + REQUIRE_FALSE(concave.contains(Point::new_scale(8.0, 8.0))); + + const Polygon blocker = bed_exclusion_arrange_polygon(concave); + CHECK(blocker.points.size() == 4); + CHECK(blocker.contains(Point::new_scale(8.0, 8.0))); +} + TEST_CASE("Active exclusion footprints select Z range nozzle translation and clearance", "[ExclusionVolume][Geometry][MultiNozzle]") { const std::vector> regions_by_extruder{ From a0f7170b833658e7c88d2c5ecb12a724db09b14b Mon Sep 17 00:00:00 2001 From: Harry Loud Date: Fri, 25 Sep 2026 10:58:37 +0100 Subject: [PATCH 31/38] Fix exclusion preview build against current main --- src/slic3r/GUI/GLCanvas3D.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/slic3r/GUI/GLCanvas3D.cpp b/src/slic3r/GUI/GLCanvas3D.cpp index 77247b327f..af02479489 100644 --- a/src/slic3r/GUI/GLCanvas3D.cpp +++ b/src/slic3r/GUI/GLCanvas3D.cpp @@ -2243,7 +2243,12 @@ void GLCanvas3D::_render_scene(const Camera& camera, const Size& cnv_size) // Depth pass for object-on-object and self shadows; consumed by the gouraud shader below. _render_shadows(camera.get_view_matrix(), camera.get_projection_matrix()); _render_objects(GLVolumeCollection::ERenderType::Opaque, !m_gizmos.is_running()); - if (!no_partplate) + // Collision previews follow the same visibility rule as the bed. + const bool show_exclusion_intersections = m_show_bed && + (!m_main_toolbar.is_enabled() || + (gizmo_type != GLGizmosManager::FdmSupports && gizmo_type != GLGizmosManager::Seam && + gizmo_type != GLGizmosManager::MmSegmentation && gizmo_type != GLGizmosManager::FuzzySkin)); + if (show_exclusion_intersections) wxGetApp().plater()->get_partplate_list().render_exclusion_volume_intersections( camera.get_view_matrix(), camera.get_projection_matrix()); _render_sla_slices(); From f2e17c7f6d38ec84a0e6b811b042784edcac3fdf Mon Sep 17 00:00:00 2001 From: Harry Loud Date: Mon, 28 Sep 2026 11:15:00 +0100 Subject: [PATCH 32/38] Fix headless brim boundary clipping --- src/libslic3r/Brim.cpp | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/src/libslic3r/Brim.cpp b/src/libslic3r/Brim.cpp index a40fdd13f2..9202b33e56 100644 --- a/src/libslic3r/Brim.cpp +++ b/src/libslic3r/Brim.cpp @@ -640,14 +640,24 @@ static ExPolygons outer_inner_brim_area(const Print& print, } } - int extruder_nums = print.config().nozzle_diameter.values.size(); std::vector extruder_unprintable_area = print.get_extruder_printable_polygons(); - // Orca: if per-extruder print area is not specified, use the whole bed as printable area for all extruders - if (extruder_unprintable_area.empty()) { - extruder_unprintable_area.resize(extruder_nums, Polygons{Model::getBedPolygon()}); - } const size_t physical_extruder_count = std::max( print.config().nozzle_diameter.size(), extruder_unprintable_area.size()); + // Keep brim clipping self-contained in the slicing configuration. The GUI + // also caches this shape in Model::printSpeedMap, but that cache is not + // initialized by headless slicing and must not determine generated paths. + Polygons fallback_printable_area {Polygon::new_scale(print.config().printable_area.values)}; + Polygons legacy_keepouts; + for (const BedExcludeRegion ®ion : get_bed_excluded_regions(print.config(), 0)) + if (!region.is_collision_volume()) + legacy_keepouts.emplace_back(region.polygon); + if (!legacy_keepouts.empty()) + fallback_printable_area = diff(fallback_printable_area, legacy_keepouts); + + extruder_unprintable_area.resize(physical_extruder_count); + for (Polygons &printable_area : extruder_unprintable_area) + if (printable_area.empty()) + printable_area = fallback_printable_area; if (print.has_wipe_tower() && !print.get_fake_wipe_tower().outer_wall.empty()) { ExPolygons expolyFromLines{}; for (auto polyline : print.get_fake_wipe_tower().outer_wall.begin()->second) { From 2616041a804585d5c393ff108c169b56e14636a8 Mon Sep 17 00:00:00 2001 From: Harry Loud Date: Tue, 29 Sep 2026 16:17:09 +0100 Subject: [PATCH 33/38] Isolate brim boundary regression coverage --- src/libslic3r/Brim.cpp | 21 +++++---------------- tests/fff_print/test_exclusion_volumes.cpp | 6 ++++++ 2 files changed, 11 insertions(+), 16 deletions(-) diff --git a/src/libslic3r/Brim.cpp b/src/libslic3r/Brim.cpp index 9202b33e56..c1dcf323dc 100644 --- a/src/libslic3r/Brim.cpp +++ b/src/libslic3r/Brim.cpp @@ -641,23 +641,12 @@ static ExPolygons outer_inner_brim_area(const Print& print, } std::vector extruder_unprintable_area = print.get_extruder_printable_polygons(); + const size_t extruder_count = print.config().nozzle_diameter.size(); + // Orca: if per-extruder print area is not specified, use the whole bed as printable area for all extruders + if (extruder_unprintable_area.empty()) + extruder_unprintable_area.resize(extruder_count, Polygons{Model::getBedPolygon()}); const size_t physical_extruder_count = std::max( - print.config().nozzle_diameter.size(), extruder_unprintable_area.size()); - // Keep brim clipping self-contained in the slicing configuration. The GUI - // also caches this shape in Model::printSpeedMap, but that cache is not - // initialized by headless slicing and must not determine generated paths. - Polygons fallback_printable_area {Polygon::new_scale(print.config().printable_area.values)}; - Polygons legacy_keepouts; - for (const BedExcludeRegion ®ion : get_bed_excluded_regions(print.config(), 0)) - if (!region.is_collision_volume()) - legacy_keepouts.emplace_back(region.polygon); - if (!legacy_keepouts.empty()) - fallback_printable_area = diff(fallback_printable_area, legacy_keepouts); - - extruder_unprintable_area.resize(physical_extruder_count); - for (Polygons &printable_area : extruder_unprintable_area) - if (printable_area.empty()) - printable_area = fallback_printable_area; + extruder_count, extruder_unprintable_area.size()); if (print.has_wipe_tower() && !print.get_fake_wipe_tower().outer_wall.empty()) { ExPolygons expolyFromLines{}; for (auto polyline : print.get_fake_wipe_tower().outer_wall.begin()->second) { diff --git a/tests/fff_print/test_exclusion_volumes.cpp b/tests/fff_print/test_exclusion_volumes.cpp index d37e12e59d..0342934adf 100644 --- a/tests/fff_print/test_exclusion_volumes.cpp +++ b/tests/fff_print/test_exclusion_volumes.cpp @@ -237,6 +237,12 @@ struct BrimRun BrimRun generate_brim(const std::string &exclusion_definition, const Vec2d &object_position = Vec2d(40.0, 40.0)) { DynamicPrintConfig config = exclusion_config(BedExcludeVolumeMode::Shared, exclusion_definition); + // Brim clipping normally receives the cached bed polygon initialized by + // the application. Give this headless fixture an explicit nozzle-reachable + // area so it exercises the same boundary path without mutating global state. + config.set_key_value("extruder_printable_area", new ConfigOptionPointsGroups{{ + Vec2d(0.0, 0.0), Vec2d(100.0, 0.0), Vec2d(100.0, 100.0), Vec2d(0.0, 100.0), + }}); config.set_deserialize_strict({ {"skirt_loops", "0"}, {"brim_type", "outer_only"}, From dc9d4994342236e9ebd5f238a33ebd7917aa5920 Mon Sep 17 00:00:00 2001 From: Harry Loud Date: Thu, 15 Oct 2026 16:24:52 +0100 Subject: [PATCH 34/38] Simplify collision volume settings layout --- docs/HLSD/exclusion-volumes.md | 7 ++-- src/libslic3r/PrintConfig.cpp | 13 ------ src/libslic3r/PrintConfig.hpp | 3 -- src/slic3r/GUI/Tab.cpp | 47 +++------------------- tests/libslic3r/test_exclusion_volumes.cpp | 26 +----------- 5 files changed, 10 insertions(+), 86 deletions(-) diff --git a/docs/HLSD/exclusion-volumes.md b/docs/HLSD/exclusion-volumes.md index e2e7956533..46962eeb6b 100644 --- a/docs/HLSD/exclusion-volumes.md +++ b/docs/HLSD/exclusion-volumes.md @@ -24,10 +24,9 @@ to collision volumes in toolhead-relative mode. The existing bed area never move or disappears when collision volumes are configured. The printer settings expose the bed area as a normal editable field with Orca's -standard reset controls. Collision volumes occupy a separate advanced settings -group. Copying a bed area creates a full-height volume with the same polygon and -preserves the source, existing volumes and selected nozzle mode. In individual -mode, a copy is added to each extruder's definition. Pasted volume syntax in the +standard reset controls. Collision volumes appear directly below it in Printable +space, as a separate field. A bed-area polygon can be manually copied into this +field to define a full-height collision volume. Pasted volume syntax in the area field requires confirmation before it is added to the volume settings; declining or invalid input leaves the stored area intact. diff --git a/src/libslic3r/PrintConfig.cpp b/src/libslic3r/PrintConfig.cpp index ec20a3e5dd..308865c68c 100644 --- a/src/libslic3r/PrintConfig.cpp +++ b/src/libslic3r/PrintConfig.cpp @@ -13928,19 +13928,6 @@ bool is_valid_bed_exclude_volumes_string(const std::string &value, const double return found_nonempty; } -std::string legacy_bed_exclude_area_to_volumes(const Pointfs &points) -{ - // Copy the polygon as resolved by get_bed_excluded_regions(). Inferring - // four-point groups would change the shape of non-rectangular bed areas. - if (points.size() < 3) - return {}; - if (std::any_of(points.begin(), points.end(), [](const Vec2d &point) { return !point.allFinite(); })) - return {}; - - const std::string definition = ConfigOptionPoints(points).serialize(); - return is_valid_bed_exclude_volumes_string(definition, std::numeric_limits::max()) ? definition : std::string{}; -} - void append_bed_exclude_volumes(DynamicPrintConfig &config, const std::string &definition) { if (definition.empty()) diff --git a/src/libslic3r/PrintConfig.hpp b/src/libslic3r/PrintConfig.hpp index b35f63d08b..49d69e56ab 100644 --- a/src/libslic3r/PrintConfig.hpp +++ b/src/libslic3r/PrintConfig.hpp @@ -2519,9 +2519,6 @@ int bed_exclusion_extruder_for_filament(size_t filament_id, const std::vectorappend_single_option_line(option, "printer_basic_information_printable_space#excluded-bed-area"); - optgroup->append_single_option_line("printable_height", "printer_basic_information_printable_space#printable-height"); - optgroup->append_single_option_line("support_multi_bed_types", "printer_basic_information_printable_space#support-multi-bed-types"); - optgroup->append_single_option_line("best_object_pos", "printer_basic_information_printable_space#best-object-position"); - optgroup->append_single_option_line("z_offset", "printer_basic_information_printable_space#z-offset"); - optgroup->append_single_option_line("preferred_orientation", "printer_basic_information_printable_space#preferred-orientation"); - - optgroup = page->new_optgroup(L("Toolhead collision volumes"), "param_printable_space"); option = optgroup->get_option("bed_exclude_volumes"); option.opt.full_width = true; optgroup->append_single_option_line(option); optgroup->append_single_option_line("bed_exclude_volume_mode"); - // Keep the area as a normal field so its edit/reset controls work for - // every existing profile. Copying only changes the volume settings. - Line copy_line{ "", "" }; - copy_line.full_width = 1; - copy_line.append_widget([this](wxWindow *parent) { - Button *button = new Button(parent, _L("Copy bed area to collision volumes") + " " + dots); - button->SetStyle(ButtonStyle::Regular, ButtonType::Parameter); - button->SetToolTip(_L("Copy the excluded bed area into a full-height collision volume. The bed area, existing collision volumes and selected multi-nozzle behaviour are preserved.")); - wxSizer *sizer = new wxBoxSizer(wxHORIZONTAL); - sizer->Add(button, 0, wxALIGN_CENTER_VERTICAL); - button->Bind(wxEVT_BUTTON, [this](wxCommandEvent &) { - const ConfigOptionPoints *area = m_config->option("bed_exclude_area"); - const std::string definition = area != nullptr ? - legacy_bed_exclude_area_to_volumes(area->values) : std::string{}; - if (definition.empty()) { - show_error(wxGetApp().plater(), _L("Configure a valid excluded bed area before copying it. The bed area has not been changed; you can edit it directly or configure collision volumes separately.")); - return; - } - - MessageDialog dialog( - wxGetApp().plater(), - _L("Copy the excluded bed area into full-height collision volumes? The copies will be checked against G-code and used for travel avoidance. The original bed area and current multi-nozzle behaviour will be preserved."), - _L("Copy collision volumes"), wxICON_QUESTION | wxYES | wxNO); - if (dialog.ShowModal() != wxID_YES) - return; - - DynamicPrintConfig converted = *m_config; - append_bed_exclude_volumes(converted, definition); - load_config(converted); - on_presets_changed(); - wxGetApp().plater()->update(); - }); - return sizer; - }); - optgroup->append_line(copy_line); + optgroup->append_single_option_line("printable_height", "printer_basic_information_printable_space#printable-height"); + optgroup->append_single_option_line("support_multi_bed_types", "printer_basic_information_printable_space#support-multi-bed-types"); + optgroup->append_single_option_line("best_object_pos", "printer_basic_information_printable_space#best-object-position"); + optgroup->append_single_option_line("z_offset", "printer_basic_information_printable_space#z-offset"); + optgroup->append_single_option_line("preferred_orientation", "printer_basic_information_printable_space#preferred-orientation"); optgroup = page->new_optgroup(L("Advanced"), L"param_advanced"); diff --git a/tests/libslic3r/test_exclusion_volumes.cpp b/tests/libslic3r/test_exclusion_volumes.cpp index fc27045baa..e581773ad3 100644 --- a/tests/libslic3r/test_exclusion_volumes.cpp +++ b/tests/libslic3r/test_exclusion_volumes.cpp @@ -101,39 +101,17 @@ TEST_CASE("Legacy point options reject collision-volume syntax", "[ExclusionVolu CHECK(is_bed_exclusion_volume_syntax(definition)); } -TEST_CASE("Copying a non-rectangular bed area preserves its complete polygon", "[ExclusionVolume][PrintConfig]") +TEST_CASE("A bed-area polygon can also define a full-height collision volume", "[ExclusionVolume][PrintConfig]") { const std::string definition = "0x0,20x0,20x10,10x10,10x20,0x20"; - ConfigOptionPoints area; - REQUIRE(area.deserialize(definition)); - CHECK(legacy_bed_exclude_area_to_volumes(area.values) == definition); - DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); config.set_deserialize_strict("bed_exclude_area", definition); - config.set_key_value("bed_exclude_volumes", new ConfigOptionString(legacy_bed_exclude_area_to_volumes(area.values))); + config.set_key_value("bed_exclude_volumes", new ConfigOptionString(definition)); const auto regions = get_bed_excluded_regions(config); REQUIRE(regions.size() == 2); CHECK(regions[0].polygon.points == regions[1].polygon.points); } -TEST_CASE("Bed-area copying rejects invalid polygons", "[ExclusionVolume][PrintConfig]") -{ - const Pointfs valid{Vec2d(0, 0), Vec2d(10, 0), Vec2d(10, 10), Vec2d(0, 10)}; - Pointfs points = valid; - - SECTION("too few corners") { - points.resize(2); - } - SECTION("a degenerate polygon") { - points = {Vec2d(20, 0), Vec2d(21, 0), Vec2d(22, 0), Vec2d(23, 0)}; - } - SECTION("a non-finite coordinate") { - points.back().x() = std::numeric_limits::infinity(); - } - - CHECK(legacy_bed_exclude_area_to_volumes(points).empty()); -} - TEST_CASE("Copied volumes preserve the bed area, existing definitions and nozzle mode", "[ExclusionVolume][PrintConfig][MultiNozzle]") { const std::string converted = "40x40,50x40,50x50,40x50"; From 929beaee15efb14d5385b9453b5271a0800f3e1e Mon Sep 17 00:00:00 2001 From: Harry Loud Date: Fri, 16 Oct 2026 09:29:22 +0100 Subject: [PATCH 35/38] Fix merged IMEX placement check and explicit header dependencies --- src/libslic3r/ExclusionVolumeGeometry.cpp | 8 ++++++++ src/libslic3r/ExclusionVolumeGeometry.hpp | 2 ++ src/libslic3r/GCode.cpp | 1 + .../GCode/ExclusionVolumePathCheck.cpp | 7 +++++++ .../GCode/ExclusionVolumePathCheck.hpp | 1 + .../GCode/ExclusionVolumeTravelAvoidance.cpp | 7 +++++++ .../GCode/ExclusionVolumeTravelAvoidance.hpp | 2 ++ src/libslic3r/GCode/GCodeProcessor.cpp | 1 + src/slic3r/GUI/PartPlate.cpp | 18 ++++++++++++------ tests/fff_print/test_exclusion_volumes.cpp | 18 +++++++++++++++++- tests/libslic3r/test_3mf.cpp | 1 + tests/libslic3r/test_exclusion_volumes.cpp | 11 ++++++++++- .../slic3rutils/test_bed_exclusion_fields.cpp | 2 ++ 13 files changed, 71 insertions(+), 8 deletions(-) diff --git a/src/libslic3r/ExclusionVolumeGeometry.cpp b/src/libslic3r/ExclusionVolumeGeometry.cpp index b7bae0bb30..cee9f9506f 100644 --- a/src/libslic3r/ExclusionVolumeGeometry.cpp +++ b/src/libslic3r/ExclusionVolumeGeometry.cpp @@ -1,4 +1,12 @@ #include "ExclusionVolumeGeometry.hpp" +#include "ExPolygon.hpp" +#include "Point.hpp" +#include "Polygon.hpp" +#include "PrintConfig.hpp" +#include "libslic3r.h" +#include +#include +#include #include "BoundingBox.hpp" #include "ClipperUtils.hpp" diff --git a/src/libslic3r/ExclusionVolumeGeometry.hpp b/src/libslic3r/ExclusionVolumeGeometry.hpp index 5bcaaaa5aa..fc745bb5dd 100644 --- a/src/libslic3r/ExclusionVolumeGeometry.hpp +++ b/src/libslic3r/ExclusionVolumeGeometry.hpp @@ -1,6 +1,8 @@ #pragma once #include "ExPolygon.hpp" +#include "Polygon.hpp" +#include "libslic3r.h" #include "Point.hpp" #include "PrintConfig.hpp" diff --git a/src/libslic3r/GCode.cpp b/src/libslic3r/GCode.cpp index 5a55a51d8c..b10224aa97 100644 --- a/src/libslic3r/GCode.cpp +++ b/src/libslic3r/GCode.cpp @@ -1,4 +1,5 @@ #include "ArcFitter.hpp" +#include #include "BoundingBox.hpp" #include "Circle.hpp" #include "Config.hpp" diff --git a/src/libslic3r/GCode/ExclusionVolumePathCheck.cpp b/src/libslic3r/GCode/ExclusionVolumePathCheck.cpp index c795c5808c..fbe3e6b465 100644 --- a/src/libslic3r/GCode/ExclusionVolumePathCheck.cpp +++ b/src/libslic3r/GCode/ExclusionVolumePathCheck.cpp @@ -1,4 +1,11 @@ #include "ExclusionVolumePathCheck.hpp" +#include "libslic3r/AABBTreeLines.hpp" +#include "libslic3r/BoundingBox.hpp" +#include "libslic3r/Line.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/PrintConfig.hpp" +#include +#include #include "libslic3r/Polygon.hpp" #include "libslic3r/libslic3r.h" diff --git a/src/libslic3r/GCode/ExclusionVolumePathCheck.hpp b/src/libslic3r/GCode/ExclusionVolumePathCheck.hpp index b04db406dc..af94ef0076 100644 --- a/src/libslic3r/GCode/ExclusionVolumePathCheck.hpp +++ b/src/libslic3r/GCode/ExclusionVolumePathCheck.hpp @@ -1,6 +1,7 @@ #pragma once #include "libslic3r/AABBTreeLines.hpp" +#include "libslic3r/Point.hpp" #include "libslic3r/BoundingBox.hpp" #include "libslic3r/Line.hpp" #include "libslic3r/PrintConfig.hpp" diff --git a/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.cpp b/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.cpp index b5f4fe1d67..5f702ccdec 100644 --- a/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.cpp +++ b/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.cpp @@ -1,4 +1,11 @@ #include "ExclusionVolumeTravelAvoidance.hpp" +#include "libslic3r/ExPolygon.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/PrintConfig.hpp" +#include "libslic3r/libslic3r.h" +#include +#include +#include #include "libslic3r/ClipperUtils.hpp" #include "libslic3r/ExclusionVolumeGeometry.hpp" diff --git a/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.hpp b/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.hpp index 4c439389b0..64dca94865 100644 --- a/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.hpp +++ b/src/libslic3r/GCode/ExclusionVolumeTravelAvoidance.hpp @@ -1,6 +1,8 @@ #pragma once #include "libslic3r/ExPolygon.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/libslic3r.h" #include "libslic3r/BoundingBox.hpp" #include "libslic3r/Polyline.hpp" #include "libslic3r/PrintConfig.hpp" diff --git a/src/libslic3r/GCode/GCodeProcessor.cpp b/src/libslic3r/GCode/GCodeProcessor.cpp index 7bdd98b298..932e049691 100644 --- a/src/libslic3r/GCode/GCodeProcessor.cpp +++ b/src/libslic3r/GCode/GCodeProcessor.cpp @@ -1,4 +1,5 @@ #include "libslic3r/ArcFitter.hpp" +#include "ExclusionVolumePathCheck.hpp" #include "libslic3r/Config.hpp" #include "libslic3r/CustomGCode.hpp" #include "libslic3r/Exception.hpp" diff --git a/src/slic3r/GUI/PartPlate.cpp b/src/slic3r/GUI/PartPlate.cpp index a46251ac0a..3d66f597ab 100644 --- a/src/slic3r/GUI/PartPlate.cpp +++ b/src/slic3r/GUI/PartPlate.cpp @@ -4444,6 +4444,14 @@ bool PartPlate::check_outside(int obj_id, int instance_id, BoundingBoxf3* boundi ModelInstance* instance = object->instances[instance_id]; BoundingBoxf3 instance_box = bounding_box? *bounding_box: object->instance_convex_hull_bounding_box(instance_id); + // Reuse the hull across exclusion and IMEX checks, but do not build it for + // instances rejected by the plate bounds or printers with no relevant zones. + std::optional instance_hull; + const auto get_instance_hull = [&]() -> const Polygon & { + if (!instance_hull) + instance_hull = instance->convex_hull_2d(); + return *instance_hull; + }; BoundingBoxf3 plate_box = get_plate_box(); this->open_belt_y(plate_box); if (instance_box.max.z() > plate_box.min.z()) @@ -4473,7 +4481,7 @@ bool PartPlate::check_outside(int obj_id, int instance_id, BoundingBoxf3* boundi // check the shared legacy area here, but let the newer per-extruder // pipeline handle nozzle-specific collision volumes. const Point plate_offset(scale_(m_origin.x()), scale_(m_origin.y())); - Polygon hull = instance->convex_hull_2d(); + const Polygon &hull = get_instance_hull(); const size_t groups_to_check = regions_by_extruder.empty() ? 0 : 1; for (size_t group_id = 0; group_id < groups_to_check; ++group_id) { @@ -4505,7 +4513,7 @@ bool PartPlate::check_outside(int obj_id, int instance_id, BoundingBoxf3* boundi } if (!checked_config_regions && m_exclude_bounding_box.size() > 0) { - Polygon hull = instance->convex_hull_2d(); + const Polygon &hull = get_instance_hull(); for (const BoundingBoxf3 &exclude_box : m_exclude_bounding_box) { Polygon p = exclude_box.polygon(true); // instance convex hull is scaled, so we need to scale here if (!intersection({ p }, { hull }).empty()) { @@ -4520,10 +4528,8 @@ bool PartPlate::check_outside(int obj_id, int instance_id, BoundingBoxf3* boundi // Block objects that overlap secondary (copy/mirror) zones or the carriage // danger strip at the primary zone boundary. Reuses the existing // outside=true → instance_outside_set → update_states() → blocks slicing path. - // Reuse the hull computed above: ModelInstance::convex_hull_2d() is NOT cached - // (Model.cpp has the validity guard commented out), so recomputing it here would - // cost every user a per-instance hull rebuild, including on non-IMEX printers. - if (!outside && imex_hull_violates(hull)) + if (!outside && (!m_imex_secondary_zone_boxes.empty() || !m_imex_collision_zones.empty()) && + imex_hull_violates(get_instance_hull())) outside = true; return outside; diff --git a/tests/fff_print/test_exclusion_volumes.cpp b/tests/fff_print/test_exclusion_volumes.cpp index 0342934adf..1393c5e01a 100644 --- a/tests/fff_print/test_exclusion_volumes.cpp +++ b/tests/fff_print/test_exclusion_volumes.cpp @@ -1,4 +1,20 @@ -#include +#include +#include +#include +#include +#include "libslic3r/Config.hpp" +#include "libslic3r/ExPolygon.hpp" +#include "libslic3r/Model.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/Polygon.hpp" +#include "libslic3r/Polyline.hpp" +#include "libslic3r/TriangleMesh.hpp" +#include "libslic3r/libslic3r.h" +#include +#include +#include +#include +#include #include "libslic3r/GCode/ExclusionVolumePathCheck.hpp" #include "libslic3r/GCode/ExclusionVolumeTravelAvoidance.hpp" diff --git a/tests/libslic3r/test_3mf.cpp b/tests/libslic3r/test_3mf.cpp index fe22b43ae7..425c86c0f7 100644 --- a/tests/libslic3r/test_3mf.cpp +++ b/tests/libslic3r/test_3mf.cpp @@ -1,5 +1,6 @@ #include +#include #include #include #include diff --git a/tests/libslic3r/test_exclusion_volumes.cpp b/tests/libslic3r/test_exclusion_volumes.cpp index e581773ad3..40f85a0274 100644 --- a/tests/libslic3r/test_exclusion_volumes.cpp +++ b/tests/libslic3r/test_exclusion_volumes.cpp @@ -1,4 +1,13 @@ -#include +#include +#include +#include +#include +#include +#include "libslic3r/Config.hpp" +#include "libslic3r/ExPolygon.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/Polygon.hpp" +#include "libslic3r/libslic3r.h" #include "libslic3r/BoundingBox.hpp" #include "libslic3r/ExclusionVolumeGeometry.hpp" diff --git a/tests/slic3rutils/test_bed_exclusion_fields.cpp b/tests/slic3rutils/test_bed_exclusion_fields.cpp index 94fe1bb6f8..2c02e5578a 100644 --- a/tests/slic3rutils/test_bed_exclusion_fields.cpp +++ b/tests/slic3rutils/test_bed_exclusion_fields.cpp @@ -1,4 +1,6 @@ #include +#include "libslic3r/Point.hpp" +#include #include "libslic3r/PrintConfig.hpp" #include "slic3r/GUI/GUI.hpp" From 20ef416b37f61e2337ac28f093ac2abb205fae4f Mon Sep 17 00:00:00 2001 From: Harry Loud Date: Sat, 17 Oct 2026 11:54:14 +0100 Subject: [PATCH 36/38] Preserve belt bed-area projection in resolved exclusion regions --- docs/HLSD/exclusion-volumes.md | 4 ++ src/libslic3r/PrintConfig.cpp | 40 ++++++++----- tests/libslic3r/test_exclusion_volumes.cpp | 65 ++++++++++++++++++++++ 3 files changed, 96 insertions(+), 13 deletions(-) diff --git a/docs/HLSD/exclusion-volumes.md b/docs/HLSD/exclusion-volumes.md index 46962eeb6b..b427e75848 100644 --- a/docs/HLSD/exclusion-volumes.md +++ b/docs/HLSD/exclusion-volumes.md @@ -23,6 +23,10 @@ Material keep-outs and collision volumes are additive. Nozzle offsets apply only to collision volumes in toolhead-relative mode. The existing bed area never moves or disappears when collision volumes are configured. +On belt printers, the region resolver projects material keep-outs onto the +tilted bed surface before placement and tower validation. Collision volumes +remain in model coordinates; the bed-surface projection is not applied to them. + The printer settings expose the bed area as a normal editable field with Orca's standard reset controls. Collision volumes appear directly below it in Printable space, as a separate field. A bed-area polygon can be manually copied into this diff --git a/src/libslic3r/PrintConfig.cpp b/src/libslic3r/PrintConfig.cpp index c3e339dad6..b75b0a82fa 100644 --- a/src/libslic3r/PrintConfig.cpp +++ b/src/libslic3r/PrintConfig.cpp @@ -13912,6 +13912,28 @@ static std::vector parse_master_bed_excluded_regions( return regions; } +static void project_bed_material_keepouts(std::vector ®ions, const ConfigBase &cfg) +{ + const auto *belt = cfg.option("belt_printer"); + if (belt == nullptr || !belt->value) + return; + + const auto *axis = cfg.option>("belt_slice_rotation"); + const auto *angle = cfg.option("belt_slice_rotation_angle"); + if (axis == nullptr || angle == nullptr) + return; + + const auto tilt = BeltTransformPipeline::physical_tilt(axis->value, angle->value); + const double cos_x = std::cos(Geometry::deg2rad(tilt.tilt_x_deg)); + const double cos_y = std::cos(Geometry::deg2rad(tilt.tilt_y_deg)); + // Resolve bed-surface coordinates once, before any placement or tower + // consumer sees them. Collision volumes already use model coordinates. + for (BedExcludeRegion ®ion : regions) + if (!region.is_collision_volume()) + for (Point &point : region.polygon.points) + point = Point(scale_(unscale(point.x()) * cos_y), scale_(unscale(point.y()) * cos_x)); +} + static std::vector resolve_bed_excluded_regions( const std::vector &master_regions, const BedExcludeVolumeMode mode, @@ -14030,8 +14052,9 @@ std::vector> get_bed_excluded_regions_by_extruder( const std::vector per_extruder_specs = per_extruder_option != nullptr ? per_extruder_option->values : std::vector{}; const bool use_collision_volumes = collision_volumes_configured(shared_specs, configured_mode, per_extruder_specs); const BedExcludeVolumeMode active_mode = use_collision_volumes ? configured_mode : BedExcludeVolumeMode::Shared; - const std::vector master_regions = parse_master_bed_excluded_regions( + std::vector master_regions = parse_master_bed_excluded_regions( legacy_points, shared_specs, use_collision_volumes, active_mode, printable_height); + project_bed_material_keepouts(master_regions, cfg); const std::vector offsets = offset_option != nullptr ? offset_option->values : std::vector{}; const size_t count = bed_exclusion_extruder_count( nozzle_option != nullptr ? nozzle_option->size() : 0, @@ -14053,9 +14076,10 @@ std::vector> get_bed_excluded_regions_by_extruder( cfg.extruder_bed_exclude_volumes.values); const BedExcludeVolumeMode active_mode = use_collision_volumes ? cfg.bed_exclude_volume_mode.value : BedExcludeVolumeMode::Shared; - const std::vector master_regions = parse_master_bed_excluded_regions( + std::vector master_regions = parse_master_bed_excluded_regions( cfg.bed_exclude_area.values, cfg.bed_exclude_volumes.value, use_collision_volumes, active_mode, printable_height); + project_bed_material_keepouts(master_regions, cfg); const size_t count = bed_exclusion_extruder_count( cfg.nozzle_diameter.size(), cfg.extruder_offset.size(), cfg.extruder_bed_exclude_volumes.size()); const size_t reference = cfg.master_extruder_id.value > 0 ? size_t(cfg.master_extruder_id.value - 1) : 0; @@ -14187,17 +14211,7 @@ Polygons get_bed_excluded_area(const PrintConfig& cfg) if (region.z_max <= EPSILON) continue; - Polygon polygon = region.polygon; - if (cfg.belt_printer.value && !region.is_collision_volume()) { - // Preserve upstream's projection of material keep-outs on the belt surface. - const auto tilt = BeltTransformPipeline::physical_tilt( - cfg.belt_slice_rotation.value, cfg.belt_slice_rotation_angle.value); - const double cos_x = std::cos(Geometry::deg2rad(tilt.tilt_x_deg)); - const double cos_y = std::cos(Geometry::deg2rad(tilt.tilt_y_deg)); - for (Point &point : polygon.points) - point = Point(scale_(unscale(point.x()) * cos_y), scale_(unscale(point.y()) * cos_x)); - } - excluded_polygons.emplace_back(std::move(polygon)); + excluded_polygons.emplace_back(region.polygon); } return excluded_polygons; diff --git a/tests/libslic3r/test_exclusion_volumes.cpp b/tests/libslic3r/test_exclusion_volumes.cpp index 40f85a0274..d006e88b54 100644 --- a/tests/libslic3r/test_exclusion_volumes.cpp +++ b/tests/libslic3r/test_exclusion_volumes.cpp @@ -16,6 +16,7 @@ #include "libslic3r/TriangleMesh.hpp" #include +#include #include #include #include @@ -101,6 +102,70 @@ TEST_CASE("Legacy exclusion polygons keep their point representation", "[Exclusi CHECK_FALSE(is_bed_exclusion_volume_syntax(option.serialize())); } +TEST_CASE("Belt material keep-outs are projected once without projecting collision volumes", "[ExclusionVolume][PrintConfig][Belt][Regression]") +{ + const auto [belt, axis, angle, scale_x, scale_y] = GENERATE(table({ + {true, BeltRotationAxis::X, 60.0, 1.0, 0.5}, + {true, BeltRotationAxis::X, -60.0, 1.0, 0.5}, + {true, BeltRotationAxis::Y, 60.0, 0.5, 1.0}, + {true, BeltRotationAxis::Z, 60.0, 1.0, 1.0}, + {true, BeltRotationAxis::None, 60.0, 1.0, 1.0}, + {false, BeltRotationAxis::X, 60.0, 1.0, 1.0}, + })); + const auto mode = GENERATE(BedExcludeVolumeMode::Shared, BedExcludeVolumeMode::ToolheadOffset, + BedExcludeVolumeMode::PerExtruder); + DynamicPrintConfig config = two_extruder_config(); + config.set_key_value("belt_printer", new ConfigOptionBool(belt)); + config.set_key_value("belt_slice_rotation", new ConfigOptionEnum(axis)); + config.set_key_value("belt_slice_rotation_angle", new ConfigOptionFloat(angle)); + config.set_deserialize_strict("bed_exclude_area", "100x100,150x100,150x150,100x150"); + config.set_key_value("bed_exclude_volume_mode", new ConfigOptionEnum(mode)); + config.set_key_value("extruder_bed_exclude_volumes", new ConfigOptionStrings{ + "10..30;0x0,10x0,10x10,0x10", "10..30;20x5,30x5,30x15,20x15"}); + + PrintConfig fixed; + fixed.apply(config, true); + const auto dynamic_regions = get_bed_excluded_regions_by_extruder(config); + const auto fixed_regions = get_bed_excluded_regions_by_extruder(fixed); + REQUIRE(dynamic_regions.size() == 2); + REQUIRE(fixed_regions.size() == 2); + for (size_t nozzle = 0; nozzle < dynamic_regions.size(); ++nozzle) { + REQUIRE(dynamic_regions[nozzle].size() == 2); + REQUIRE(fixed_regions[nozzle].size() == 2); + const BoundingBox area = bounds(dynamic_regions[nozzle][0]); + CHECK_THAT(unscale(area.min.x()), WithinAbs(100.0 * scale_x, 1e-5)); + CHECK_THAT(unscale(area.min.y()), WithinAbs(100.0 * scale_y, 1e-5)); + CHECK_THAT(unscale(area.max.x()), WithinAbs(150.0 * scale_x, 1e-5)); + CHECK_THAT(unscale(area.max.y()), WithinAbs(150.0 * scale_y, 1e-5)); + CHECK(dynamic_regions[nozzle][0].polygon.points == fixed_regions[nozzle][0].polygon.points); + const double offset_x = mode == BedExcludeVolumeMode::Shared ? 0.0 : 20.0 * nozzle; + const double offset_y = mode == BedExcludeVolumeMode::Shared ? 0.0 : 5.0 * nozzle; + CHECK(dynamic_regions[nozzle][1].polygon.points == rectangle(offset_x, offset_y, offset_x + 10.0, offset_y + 10.0).points); + CHECK(dynamic_regions[nozzle][1].polygon.points == fixed_regions[nozzle][1].polygon.points); + } + // The older polygon API must not apply the projection a second time. + const Polygons projected = get_bed_excluded_area(fixed); + REQUIRE(projected.size() == 1); + CHECK(projected.front().points == fixed_regions.front().front().polygon.points); + CHECK(config.option("bed_exclude_area")->serialize() == "100x100,150x100,150x150,100x150"); +} + +TEST_CASE("Belt object intersections use the projected bed area", "[ExclusionVolume][PrintConfig][Belt][Regression]") +{ + const auto [y, collides] = GENERATE(table({ + {80.0, true}, {95.0, true}, {110.0, false}, {125.0, false}, {140.0, false}, + })); + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_key_value("belt_printer", new ConfigOptionBool(true)); + config.set_key_value("belt_slice_rotation", new ConfigOptionEnum(BeltRotationAxis::X)); + config.set_key_value("belt_slice_rotation_angle", new ConfigOptionFloat(45.0)); + config.set_deserialize_strict("bed_exclude_area", "100x100,150x100,150x150,100x150"); + const auto regions = get_bed_excluded_regions(config); + REQUIRE(regions.size() == 1); + CubeModel cube(Vec3d(120.0, y, 0.0), Vec3d(10.0, 10.0, 10.0)); + CHECK(cube.instance->intersects_bed_exclude_region(regions.front()) == collides); +} + TEST_CASE("Legacy point options reject collision-volume syntax", "[ExclusionVolume][PrintConfig]") { const std::string definition = "0..10;0x0,10x0,10x10,0x10|20x20,30x20,30x30,20x30"; From 9bbb7ff2c4e71035e124ec3a152d64ed4171b5d0 Mon Sep 17 00:00:00 2001 From: Harry Loud Date: Mon, 19 Oct 2026 12:07:01 +0100 Subject: [PATCH 37/38] Preserve additive bed areas across preview arrange and cutter paths --- localization/i18n/OrcaSlicer.pot | 72 +++++++++++++++++++++- src/OrcaSlicer.cpp | 2 +- src/libslic3r/GCode.cpp | 6 +- src/libslic3r/GCode/GCodeProcessor.cpp | 2 +- src/libslic3r/Print.cpp | 8 +-- src/libslic3r/PrintConfig.cpp | 12 ++-- src/slic3r/GUI/Field.cpp | 2 +- src/slic3r/GUI/Plater.cpp | 2 +- src/slic3r/GUI/Tab.cpp | 8 +-- tests/fff_print/test_exclusion_volumes.cpp | 60 ++++++++++++++++++ 10 files changed, 152 insertions(+), 22 deletions(-) diff --git a/localization/i18n/OrcaSlicer.pot b/localization/i18n/OrcaSlicer.pot index c679c1829f..b221f073b7 100644 --- a/localization/i18n/OrcaSlicer.pot +++ b/localization/i18n/OrcaSlicer.pot @@ -5320,6 +5320,9 @@ msgstr "" msgid "This parameter expects a valid template." msgstr "" +msgid "Invalid collision volume format. Use XxY, XxY, ... or ZMIN..ZMAX;XxY, XxY, ... and separate multiple volumes with |." +msgstr "" + msgid "Invalid pattern. Use N, N#K, or a comma-separated list with optional #K per entry. Examples: 5, 5#2, 1,7,9, 5,9#2,18." msgstr "" @@ -6518,6 +6521,12 @@ msgstr "" msgid "Show object labels in 3D scene." msgstr "" +msgid "Show all collision volumes" +msgstr "" + +msgid "Show the full height of every configured collision volume, including on an empty bed." +msgstr "" + msgid "Show &Overhang" msgstr "" @@ -11046,6 +11055,12 @@ msgstr "" msgid "Click to reset all settings to the last saved preset." msgstr "" +msgid "This definition contains collision-volume syntax. Add it to the toolhead collision volumes for G-code checking and travel avoidance? The existing excluded bed area will be preserved." +msgstr "" + +msgid "Add collision volumes" +msgstr "" + msgid "Prime tower is required for nozzle changing. There may be flaws on the model without prime tower. Are you sure you want to disable prime tower?" msgstr "" @@ -12708,6 +12723,17 @@ msgid "" "Is the disk full?" msgstr "" +#, possible-boost-format +msgid "A G-code move intersects a collision volume for extruder %1%. This may cause a printer collision." +msgstr "" + +msgid "A G-code move intersects a collision volume. This may cause a printer collision." +msgstr "" + +#, possible-boost-format +msgid "The intersecting move is at G-code line %1%. Its Z position is unknown after homing, so Orca checked it against every height." +msgstr "" + #. TRN %1% is the temporary file path, %2% the output file path, %3% the system error message. #, possible-boost-format msgid "" @@ -12974,6 +13000,14 @@ msgstr "" msgid "%1% is too close to exclusion area. There may be collisions when printing." msgstr "" +#, possible-boost-format +msgid "%1% intersects collision volumes for every available extruder." +msgstr "" + +#, possible-boost-format +msgid "%1% intersects a collision volume for extruder %2%." +msgstr "" + #, possible-boost-format msgid "%1% is too close to others, and collisions may be caused." msgstr "" @@ -13303,7 +13337,34 @@ msgstr "" msgid "Excluded bed area" msgstr "" -msgid "Unprintable area in XY plane. For example, X1 Series printers use the front left corner to cut filament during filament change. The area is expressed as polygon by points in following format: \"XxY, XxY, ...\"" +msgid "Unprintable area in XY plane. For example, X1 Series printers use the front left corner to cut filament during filament change. The area is expressed as a polygon in the format \"XxY, XxY, ...\". It constrains material and model placement, but allows machine travel. Configure toolhead collision volumes separately for G-code checking and travel avoidance." +msgstr "" + +msgid "Toolhead collision volumes" +msgstr "" + +msgid "Collision volumes used for model and generated-material exclusion, G-code checking, and travel avoidance. Use \"XxY, XxY, ...\" for a full-height polygon or \"ZMIN..ZMAX;XxY, XxY, ...\" for a Z-limited volume. Separate multiple volumes with \"|\". These volumes are additional to the excluded bed area. Automatic arrangement conservatively uses the bounding box of a non-convex volume." +msgstr "" + +msgid "Collision volume behavior" +msgstr "" + +msgid "Choose whether all nozzles use the same collision volumes, derive toolhead-relative volumes from each nozzle's XY offset, or configure independent volumes for every extruder. In individual mode, select each extruder on the Extruder page to configure its volumes." +msgstr "" + +msgid "Shared" +msgstr "" + +msgid "Toolhead-relative (nozzle offsets)" +msgstr "" + +msgid "Individual per extruder" +msgstr "" + +msgid "Extruder collision volumes" +msgstr "" + +msgid "Collision volumes used only by this extruder in individual mode. Use the same polygon and optional Z-range format as the shared collision volumes. Leave empty for no collision volumes on this extruder. Automatic arrangement conservatively uses the bounding box of a non-convex volume." msgstr "" msgid "Bed custom texture" @@ -18210,6 +18271,15 @@ msgstr "" msgid "invalid value " msgstr "" +msgid "Invalid collision volume definition." +msgstr "" + +msgid "A nozzle offset is required for every extruder when toolhead-relative collision volumes are enabled." +msgstr "" + +msgid "Invalid per-extruder collision volume definition." +msgstr "" + msgid "Invalid value when spiral vase mode is enabled: " msgstr "" diff --git a/src/OrcaSlicer.cpp b/src/OrcaSlicer.cpp index 8baf6dc114..9eff0ceb46 100644 --- a/src/OrcaSlicer.cpp +++ b/src/OrcaSlicer.cpp @@ -187,7 +187,7 @@ using namespace Slic3r; static Pointfs legacy_bed_exclude_area_points(const DynamicPrintConfig &config) { const ConfigOptionPoints *option = config.option("bed_exclude_area"); - return option != nullptr && !has_bed_exclude_volumes(config) ? option->values : Pointfs{}; + return option != nullptr ? option->values : Pointfs{}; } std::map cli_errors = { diff --git a/src/libslic3r/GCode.cpp b/src/libslic3r/GCode.cpp index b10224aa97..8e3efd3289 100644 --- a/src/libslic3r/GCode.cpp +++ b/src/libslic3r/GCode.cpp @@ -338,7 +338,7 @@ static std::vector get_path_of_change_filament(const Print& print) Vec2d end_point = points[1]; // the cutter area size(18, 28) - Pointfs excluse_area = has_bed_exclude_volumes(print.config()) ? Pointfs{} : print.config().bed_exclude_area.values; + Pointfs excluse_area = print.config().bed_exclude_area.values; if (excluse_area.size() != 4) return out_points; @@ -2992,9 +2992,9 @@ void GCode::do_export(Print* print, const char* path, GCodeProcessorResult* resu const int extruder_id = m_processor.get_result().exclusion_volume_conflict_extruder_id; std::string warning = extruder_id >= 0 ? Slic3r::format( - _(L("A G-code move intersects an exclusion volume for extruder %1%. This may cause a printer collision.")), + _(L("A G-code move intersects a collision volume for extruder %1%. This may cause a printer collision.")), std::to_string(extruder_id + 1)) : - _(L("A G-code move intersects an exclusion volume. This may cause a printer collision.")); + _(L("A G-code move intersects a collision volume. This may cause a printer collision.")); if (m_processor.get_result().exclusion_volume_conflict_used_unknown_z) { warning += "\n" + Slic3r::format( _(L("The intersecting move is at G-code line %1%. Its Z position is unknown after homing, so Orca checked it against every height.")), diff --git a/src/libslic3r/GCode/GCodeProcessor.cpp b/src/libslic3r/GCode/GCodeProcessor.cpp index 932e049691..39b0b13b05 100644 --- a/src/libslic3r/GCode/GCodeProcessor.cpp +++ b/src/libslic3r/GCode/GCodeProcessor.cpp @@ -3328,7 +3328,7 @@ void GCodeProcessor::apply_config(const DynamicPrintConfig& config) //BBS: add bed_exclude_area const ConfigOptionPoints* bed_exclude_area = config.option("bed_exclude_area"); - if (bed_exclude_area != nullptr && !has_bed_exclude_volumes(config)) + if (bed_exclude_area != nullptr) m_result.bed_exclude_area = bed_exclude_area->values; const ConfigOptionPoints* wrapping_exclude_area = config.option("wrapping_exclude_area"); diff --git a/src/libslic3r/Print.cpp b/src/libslic3r/Print.cpp index 26d5ea368f..ed1ce9379d 100644 --- a/src/libslic3r/Print.cpp +++ b/src/libslic3r/Print.cpp @@ -949,8 +949,8 @@ StringObjectException Print::sequential_print_clearance_valid(const Print &print const std::string collision_message = !exclusion_collision->collision_volume ? (boost::format(L("%1% is too close to exclusion area. There may be collisions when printing.")) % instance.model_instance->get_object()->name).str() : is_auto_filament_map_mode(print.get_filament_map_mode()) && print.is_BBL_printer() ? - (boost::format(L("%1% intersects exclusion volumes for every available extruder.")) % instance.model_instance->get_object()->name).str() : - (boost::format(L("%1% intersects an exclusion volume for extruder %2%.")) % instance.model_instance->get_object()->name % (exclusion_collision->extruder_id + 1)).str(); + (boost::format(L("%1% intersects collision volumes for every available extruder.")) % instance.model_instance->get_object()->name).str() : + (boost::format(L("%1% intersects a collision volume for extruder %2%.")) % instance.model_instance->get_object()->name % (exclusion_collision->extruder_id + 1)).str(); if (single_object_exception.string.empty()) { single_object_exception.string = collision_message; // single_object_exception.object = instance.model_instance->get_object(); @@ -1620,8 +1620,8 @@ static StringObjectException layered_print_cleareance_valid(const Print &print, const std::string message = !exclusion_collision->collision_volume ? (boost::format(L("%1% is too close to exclusion area. There may be collisions when printing.")) % inst->model_instance->get_object()->name).str() : is_auto_filament_map_mode(print.get_filament_map_mode()) && print.is_BBL_printer() ? - (boost::format(L("%1% intersects exclusion volumes for every available extruder.")) % inst->model_instance->get_object()->name).str() : - (boost::format(L("%1% intersects an exclusion volume for extruder %2%.")) % inst->model_instance->get_object()->name % (exclusion_collision->extruder_id + 1)).str(); + (boost::format(L("%1% intersects collision volumes for every available extruder.")) % inst->model_instance->get_object()->name).str() : + (boost::format(L("%1% intersects a collision volume for extruder %2%.")) % inst->model_instance->get_object()->name % (exclusion_collision->extruder_id + 1)).str(); return {message + "\n", inst->model_instance}; } diff --git a/src/libslic3r/PrintConfig.cpp b/src/libslic3r/PrintConfig.cpp index b75b0a82fa..01e3184efd 100644 --- a/src/libslic3r/PrintConfig.cpp +++ b/src/libslic3r/PrintConfig.cpp @@ -1057,8 +1057,8 @@ void PrintConfigDef::init_common_params() def->set_default_value(new ConfigOptionString()); def = this->add("bed_exclude_volume_mode", coEnum); - def->label = L("Collision volume behaviour"); - def->tooltip = L("Choose whether all nozzles use the same exclusion volumes, derive toolhead-relative volumes from each nozzle's XY offset, or configure independent volumes for every extruder. In individual mode, select each extruder on the Extruder page to configure its volumes."); + def->label = L("Collision volume behavior"); + def->tooltip = L("Choose whether all nozzles use the same collision volumes, derive toolhead-relative volumes from each nozzle's XY offset, or configure independent volumes for every extruder. In individual mode, select each extruder on the Extruder page to configure its volumes."); def->enum_keys_map = &ConfigOptionEnum::get_enum_values(); def->enum_values = { "shared", "toolhead_offset", "per_extruder" }; def->enum_labels = { L("Shared"), L("Toolhead-relative (nozzle offsets)"), L("Individual per extruder") }; @@ -1067,7 +1067,7 @@ void PrintConfigDef::init_common_params() def = this->add("extruder_bed_exclude_volumes", coStrings); def->label = L("Extruder collision volumes"); - def->tooltip = L("Collision volumes used only by this extruder in individual mode. Use the same polygon and optional Z-range format as the shared exclusion volumes. Leave empty for no exclusion volumes on this extruder. Automatic arrangement conservatively uses the bounding box of a non-convex volume."); + def->tooltip = L("Collision volumes used only by this extruder in individual mode. Use the same polygon and optional Z-range format as the shared collision volumes. Leave empty for no collision volumes on this extruder. Automatic arrangement conservatively uses the bounding box of a non-convex volume."); def->mode = comAdvanced; def->gui_type = ConfigOptionDef::GUIType::one_string; def->set_default_value(new ConfigOptionStrings{ "" }); @@ -12394,16 +12394,16 @@ std::map validate(const FullPrintConfig &cfg, bool und if (cfg.bed_exclude_volume_mode.value != BedExcludeVolumeMode::PerExtruder && !cfg.bed_exclude_volumes.value.empty() && !is_valid_bed_exclude_volumes_string(cfg.bed_exclude_volumes.value, cfg.printable_height.value)) { - error_message.emplace("bed_exclude_volumes", L("Invalid exclusion volume definition.")); + error_message.emplace("bed_exclude_volumes", L("Invalid collision volume definition.")); } if (collision_volumes_enabled && cfg.bed_exclude_volume_mode.value == BedExcludeVolumeMode::ToolheadOffset && cfg.extruder_offset.size() < cfg.nozzle_diameter.size()) { - error_message.emplace("extruder_offset", L("A nozzle offset is required for every extruder when toolhead-relative exclusion volumes are enabled.")); + error_message.emplace("extruder_offset", L("A nozzle offset is required for every extruder when toolhead-relative collision volumes are enabled.")); } if (collision_volumes_enabled && cfg.bed_exclude_volume_mode.value == BedExcludeVolumeMode::PerExtruder) { for (const std::string &entry : cfg.extruder_bed_exclude_volumes.values) { if (!is_valid_bed_exclude_volumes_string(entry, cfg.printable_height.value)) { - error_message.emplace("extruder_bed_exclude_volumes", L("Invalid per-extruder exclusion volume definition.")); + error_message.emplace("extruder_bed_exclude_volumes", L("Invalid per-extruder collision volume definition.")); break; } } diff --git a/src/slic3r/GUI/Field.cpp b/src/slic3r/GUI/Field.cpp index 54ec91f672..55c491f811 100644 --- a/src/slic3r/GUI/Field.cpp +++ b/src/slic3r/GUI/Field.cpp @@ -736,7 +736,7 @@ void Field::get_value_by_opt_type(wxString& str, const bool check_value/* = true } else if (m_opt.opt_key == "bed_exclude_volumes" || m_opt.opt_key == "extruder_bed_exclude_volumes") { const std::string definition = into_u8(str); if (!is_valid_bed_exclude_volumes_string(definition, std::numeric_limits::max())) { - show_error(m_parent, _L("Invalid exclusion volume format. Use XxY, XxY, ... or ZMIN..ZMAX;XxY, XxY, ... and separate multiple volumes with |.")); + show_error(m_parent, _L("Invalid collision volume format. Use XxY, XxY, ... or ZMIN..ZMAX;XxY, XxY, ... and separate multiple volumes with |.")); const std::string old_value = m_value.empty() ? std::string{} : boost::any_cast(m_value); set_value(from_u8(old_value), true); break; diff --git a/src/slic3r/GUI/Plater.cpp b/src/slic3r/GUI/Plater.cpp index 469afeb3b3..e639ab8b00 100644 --- a/src/slic3r/GUI/Plater.cpp +++ b/src/slic3r/GUI/Plater.cpp @@ -21678,7 +21678,7 @@ void Plater::set_bed_shape() const const ConfigOptionPoints *bed_exclude_area = p->config->option("bed_exclude_area"); set_bed_shape(p->config->option("printable_area")->values, //BBS: add bed exclude areas - has_bed_exclude_volumes(*p->config) ? Pointfs{} : bed_exclude_area->values, + bed_exclude_area->values, p->config->option("wrapping_exclude_area")->values, p->config->option("printable_height")->value, p->config->option("extruder_printable_area")->values, diff --git a/src/slic3r/GUI/Tab.cpp b/src/slic3r/GUI/Tab.cpp index 1e6bc8b97c..07b857d443 100644 --- a/src/slic3r/GUI/Tab.cpp +++ b/src/slic3r/GUI/Tab.cpp @@ -1952,7 +1952,7 @@ void Tab::on_value_change(const std::string& opt_key, const boost::any& value) if (definition != nullptr && is_bed_exclusion_volume_syntax(*definition)) { const double printable_height = m_config->opt_float("printable_height"); if (!is_valid_bed_exclude_volumes_string(*definition, printable_height)) { - show_error(wxGetApp().plater(), _L("Invalid exclusion volume format. Use XxY, XxY, ... or ZMIN..ZMAX;XxY, XxY, ... and separate multiple volumes with |.")); + show_error(wxGetApp().plater(), _L("Invalid collision volume format. Use XxY, XxY, ... or ZMIN..ZMAX;XxY, XxY, ... and separate multiple volumes with |.")); reload_config(); return; } @@ -5302,8 +5302,8 @@ void TabPrinter::build_fff() option = optgroup->get_option("bed_exclude_volumes"); option.opt.full_width = true; - optgroup->append_single_option_line(option); - optgroup->append_single_option_line("bed_exclude_volume_mode"); + optgroup->append_single_option_line(option, "printer_basic_information_printable_space#toolhead-collision-volumes"); + optgroup->append_single_option_line("bed_exclude_volume_mode", "printer_basic_information_printable_space#toolhead-collision-volumes"); optgroup->append_single_option_line("printable_height", "printer_basic_information_printable_space#printable-height"); optgroup->append_single_option_line("support_multi_bed_types", "printer_basic_information_printable_space#support-multi-bed-types"); @@ -6123,7 +6123,7 @@ if (is_marlin_flavor) Option exclusion_option = optgroup->get_option("extruder_bed_exclude_volumes", extruder_idx); exclusion_option.opt.full_width = true; - optgroup->append_single_option_line(exclusion_option, "printer_basic_information_printable_space#excluded-bed-area"); + optgroup->append_single_option_line(exclusion_option, "printer_basic_information_printable_space#toolhead-collision-volumes"); optgroup->m_on_change = [this](const t_config_option_key& opt_key, boost::any value) { diff --git a/tests/fff_print/test_exclusion_volumes.cpp b/tests/fff_print/test_exclusion_volumes.cpp index 1393c5e01a..6b20d07973 100644 --- a/tests/fff_print/test_exclusion_volumes.cpp +++ b/tests/fff_print/test_exclusion_volumes.cpp @@ -2,6 +2,7 @@ #include #include #include +#include #include "libslic3r/Config.hpp" #include "libslic3r/ExPolygon.hpp" #include "libslic3r/Model.hpp" @@ -377,6 +378,65 @@ TEST_CASE("Legacy excluded areas do not constrain machine motion", "[ExclusionVo CHECK(route.path.points == direct.points); } +TEST_CASE("G-code preview retains the bed area alongside collision volumes", "[ExclusionVolume][GCode][Compatibility][Regression]") +{ + const auto mode = GENERATE(BedExcludeVolumeMode::Shared, BedExcludeVolumeMode::ToolheadOffset, + BedExcludeVolumeMode::PerExtruder); + DynamicPrintConfig config = exclusion_config(mode, "0..10;70x70,80x70,80x80,70x80", + {"0..10;70x70,80x70,80x80,70x80"}); + config.set_deserialize_strict("bed_exclude_area", "0x0,18x0,18x28,0x28"); + ScopedTemporaryFile file(".gcode"); + { + std::ofstream output(file.string()); + REQUIRE(output.is_open()); + output << "; generated by OrcaSlicer\nG90\nM83\nG1 X30 Y30 Z0.2 F3000\n" + << "; CONFIG_BLOCK_START\n"; + for (const std::string &key : config.keys()) + output << "; " << key << " = " << config.opt_serialize(key) << '\n'; + output << "; CONFIG_BLOCK_END\n"; + REQUIRE(output.good()); + } + ScopedBblPrinterMode printer_mode(false); + GCodeProcessor processor; + // Standalone preview loading uses the embedded DynamicPrintConfig, not + // the streaming writer's PrintConfig overload. + processor.process_file(file.string()); + CHECK(processor.get_result().bed_exclude_area == config.option("bed_exclude_area")->values); +} + +TEST_CASE("Collision volumes preserve the configured cutter travel points", "[ExclusionVolume][GCode][Compatibility][Regression]") +{ + DynamicPrintConfig config = Test::multifilament_config(2, { + {"enable_prime_tower", "0"}, {"gcode_flavor", "klipper"}, + {"start_end_points", "20x-3,60x90"}, {"bed_exclude_area", "0x0,18x0,18x28,0x28"}, + {"change_filament_gcode", ";CUTTER_PATH [travel_point_1_x],[travel_point_1_y];[travel_point_2_x],[travel_point_2_y];[travel_point_3_x],[travel_point_3_y]"}, + }); + const auto cutter_path = [](const DynamicPrintConfig &settings) { + Model model; + Print print; + const std::vector> overrides{ + {{"extruder", "1"}}, {{"extruder", "2"}}}; + std::vector meshes; + for (const double x : {30.0, 45.0}) { + TriangleMesh mesh = make_cube(5.0, 5.0, 0.6); + mesh.translate(Vec3f(float(x), 40.0f, 0.0f)); + meshes.push_back(std::move(mesh)); + } + Test::init_print(std::move(meshes), print, model, settings, &overrides, false); + const std::string gcode = Test::gcode(print); + const size_t marker = gcode.find(";CUTTER_PATH "); + REQUIRE(marker != std::string::npos); + return gcode.substr(marker, gcode.find('\n', marker) - marker); + }; + const std::string expected = cutter_path(config); + // The configured endpoint differs from the fallback (54, 245), so this + // comparison cannot pass by silently disabling the cutter-area calculation. + CHECK_THAT(expected, Catch::Matchers::ContainsSubstring("60")); + CHECK_THAT(expected, Catch::Matchers::ContainsSubstring("90")); + config.set_key_value("bed_exclude_volumes", new ConfigOptionString("0..10;80x80,90x80,90x90,80x90")); + CHECK(cutter_path(config) == expected); +} + TEST_CASE("Path checker detects crossing inside and boundary motions", "[ExclusionVolume][GCode]") { const FullPrintConfig config = static_config(exclusion_config()); From 4083b7996c52797dfa247128c9aa196463276c08 Mon Sep 17 00:00:00 2001 From: Harry Loud Date: Tue, 20 Oct 2026 11:17:46 +0100 Subject: [PATCH 38/38] Avoid text-editing chord for collision-volume preview shortcut --- docs/HLSD/exclusion-volumes.md | 4 ++-- src/slic3r/GUI/Shortcuts.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/HLSD/exclusion-volumes.md b/docs/HLSD/exclusion-volumes.md index b427e75848..1b68c256d5 100644 --- a/docs/HLSD/exclusion-volumes.md +++ b/docs/HLSD/exclusion-volumes.md @@ -63,7 +63,7 @@ imply ownership by a particular filament. Automatic 3D previews are limited to nearby object height to avoid obscuring the workspace. **View → Show all collision volumes** displays each volume over its complete -resolved Z range, including on an empty bed. Its default shortcut is Ctrl+Shift+V -(Command+Shift+V on macOS), configurable through Orca's shortcut settings. The +resolved Z range, including on an empty bed. Its default shortcut is Ctrl+Shift+K +(Command+Shift+K on macOS), configurable through Orca's shortcut settings. The application remembers this display preference independently of printer presets; it changes neither collision checking nor slicing results. diff --git a/src/slic3r/GUI/Shortcuts.cpp b/src/slic3r/GUI/Shortcuts.cpp index e145bf9e0f..7cc8336e0b 100644 --- a/src/slic3r/GUI/Shortcuts.cpp +++ b/src/slic3r/GUI/Shortcuts.cpp @@ -147,7 +147,7 @@ constexpr std::array shortcut_table = {{ // Display SHORTCUT(ShowLabels, "show_labels", L("Show object labels in 3D scene."), GLOBAL, { 'E', CTRL }), - SHORTCUT(ShowCollisionVolumes, "show_collision_volumes", L("Show all collision volumes"), GLOBAL, { 'V', CTRL_SHIFT }), + SHORTCUT(ShowCollisionVolumes, "show_collision_volumes", L("Show all collision volumes"), GLOBAL, { 'K', CTRL_SHIFT }), SHORTCUT(ShowWireframe, "show_wireframe", L("Show/Hide wireframe"), CANVAS, { WXK_RETURN, CTRL_SHIFT }), SHORTCUT(ToggleGcodeWindow, "toggle_gcode_window", L("On/Off G-code window"), PREVIEW, { 'C' }), SHORTCUT(ToggleOneLayerMode, "toggle_one_layer_mode", L("On/Off one layer mode of the vertical slider"), PREVIEW, { 'L' }),