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,