From f48ed5091c8bd458643190c27a77ccc67ba48d29 Mon Sep 17 00:00:00 2001 From: supermerill Date: Sat, 5 Sep 2020 20:00:22 +0200 Subject: [PATCH] Add monotonous infill thanks to @bubnikv and @wavexx also the rectilinear2.cpp rework that go along use of monotonous in ironing use of monotonous instead of rectilinear of "filled" in top & bottom reduce gap fill area from rectilinearWGapFill to the area with no overlap fix flatten(): don't put everything in a no_sort collection but correctly recreate the hierarchy of no_sort, sort, no_sort of collections. --- src/libslic3r/ExtrusionEntityCollection.cpp | 5 +- src/libslic3r/Fill/FillBase.cpp | 10 +- src/libslic3r/Fill/FillBase.hpp | 37 +- src/libslic3r/Fill/FillRectilinear2.cpp | 2671 ++++++++++++++----- src/libslic3r/Fill/FillRectilinear2.hpp | 27 +- src/libslic3r/Fill/FillSmooth.cpp | 10 +- src/libslic3r/GCode.cpp | 1 + src/libslic3r/PrintConfig.cpp | 18 +- src/libslic3r/PrintConfig.hpp | 9 +- src/libslic3r/PrintObject.cpp | 1 + src/libslic3r/ShortestPath.cpp | 1 + src/slic3r/GUI/Field.cpp | 4 +- 12 files changed, 2031 insertions(+), 763 deletions(-) diff --git a/src/libslic3r/ExtrusionEntityCollection.cpp b/src/libslic3r/ExtrusionEntityCollection.cpp index f8ede16e9..a7c338e02 100644 --- a/src/libslic3r/ExtrusionEntityCollection.cpp +++ b/src/libslic3r/ExtrusionEntityCollection.cpp @@ -151,14 +151,13 @@ ExtrusionEntityCollection ExtrusionEntityCollection::flatten(bool preserve_order } void FlatenEntities::use(const ExtrusionEntityCollection &coll) { - if (coll.no_sort && preserve_ordering) { + if ((coll.no_sort || this->to_fill.no_sort) && preserve_ordering) { FlatenEntities unsortable(coll, preserve_ordering); for (const ExtrusionEntity* entity : coll.entities) { entity->visit(unsortable); } to_fill.append(std::move(unsortable.to_fill)); - } - else { + } else { for (const ExtrusionEntity* entity : coll.entities) { entity->visit(*this); } diff --git a/src/libslic3r/Fill/FillBase.cpp b/src/libslic3r/Fill/FillBase.cpp index eb1714de9..55bf5a613 100644 --- a/src/libslic3r/Fill/FillBase.cpp +++ b/src/libslic3r/Fill/FillBase.cpp @@ -32,6 +32,7 @@ Fill* Fill::new_from_type(const InfillPattern type) case ipGyroid: return new FillGyroid(); case ipRectilinear: return new FillRectilinear2(); // case ipRectilinear: return new FillRectilinear(); + case ipMonotonous: return new FillMonotonous(); case ipRectilinearWGapFill: return new FillRectilinear2WGapFill(); case ipScatteredRectilinear:return new FillScatteredRectilinear(); case ipLine: return new FillLine(); @@ -146,7 +147,11 @@ std::pair Fill::_infill_direction(const Surface *surface) const void Fill::fill_surface_extrusion(const Surface *surface, const FillParams ¶ms, ExtrusionEntitiesPtr &out) const { //add overlap & call fill_surface - Polylines polylines = this->fill_surface(surface, params); + Polylines polylines; + try { + polylines = this->fill_surface(surface, params); + } catch (InfillFailedException&) { + } if (polylines.empty()) return; // ensure it doesn't over or under-extrude @@ -590,10 +595,11 @@ Fill::do_gap_fill(const ExPolygons &gapfill_areas, const FillParams ¶ms, Ext // offset2_ex(gapfill_areas, double(-max / 2), double(+max / 2)), // true); ExPolygons gapfill_areas_collapsed = offset2_ex(gapfill_areas, double(-min / 2), double(+min / 2)); + const double minarea = scale_(params.config->gap_fill_min_area.get_abs_value(params.flow->width) ) * params.flow->scaled_width(); for (const ExPolygon &ex : gapfill_areas_collapsed) { //remove too small gaps that are too hard to fill. //ie one that are smaller than an extrusion with width of min and a length of max. - if (ex.area() > scale_(params.flow->nozzle_diameter)*scale_(params.flow->nozzle_diameter) * 2) { + if (ex.area() > minarea) { MedialAxis{ ex, params.flow->scaled_width() * 2, params.flow->scaled_width() / 5, coord_t(params.flow->height) }.build(polylines_gapfill); } } diff --git a/src/libslic3r/Fill/FillBase.hpp b/src/libslic3r/Fill/FillBase.hpp index 46be4fcf9..bef34595d 100644 --- a/src/libslic3r/Fill/FillBase.hpp +++ b/src/libslic3r/Fill/FillBase.hpp @@ -22,49 +22,46 @@ namespace Slic3r { class ExPolygon; class Surface; +class InfillFailedException : public std::runtime_error { +public: + InfillFailedException() : std::runtime_error("Infill failed") {} +}; + struct FillParams { - FillParams() { - memset(this, 0, sizeof(FillParams)); - // Adjustment does not work. - dont_adjust = true; - flow_mult = 1.f; - fill_exactly = false; - role = erNone; - flow = NULL; - config = NULL; - } - bool full_infill() const { return density > 0.9999f && density < 1.0001f; } // Fill density, fraction in <0, 1> - float density; + float density { 0.f }; // Fill extruding flow multiplier, fraction in <0, 1>. Used by "over bridge compensation" - float flow_mult; + float flow_mult { 1.0f }; // Don't connect the fill lines around the inner perimeter. - bool dont_connect; + bool dont_connect{ false }; // Don't adjust spacing to fill the space evenly. - bool dont_adjust; + bool dont_adjust { true }; + + // Monotonous infill - strictly left to right for better surface quality of top infills. + bool monotonous { false }; // Try to extrude the exact amount of plastic to fill the volume requested - bool fill_exactly; + bool fill_exactly{ false }; // For Honeycomb. // we were requested to complete each loop; // in this case we don't try to make more continuous paths - bool complete; + bool complete { false }; // if role == erNone or ERCustom, this method have to choose the best role itself, else it must use the argument's role. - ExtrusionRole role; + ExtrusionRole role { erNone }; //flow to use - Flow const *flow; + Flow const* flow { nullptr }; //full configuration for the region, to avoid copying every bit that is needed. Use this for process-specific parameters. - PrintRegionConfig const *config; + PrintRegionConfig const *config{ nullptr }; }; static_assert(IsTriviallyCopyable::value, "FillParams class is not POD (and it should be - see constructor)."); diff --git a/src/libslic3r/Fill/FillRectilinear2.cpp b/src/libslic3r/Fill/FillRectilinear2.cpp index eddc61821..3ed3a9429 100644 --- a/src/libslic3r/Fill/FillRectilinear2.cpp +++ b/src/libslic3r/Fill/FillRectilinear2.cpp @@ -6,7 +6,9 @@ #include #include #include +#include +#include #include #include #include @@ -111,26 +113,15 @@ static inline void polygon_segment_append_reversed(Points &out, const Polygon &p } // Intersection point of a vertical line with a polygon segment. -class SegmentIntersection +struct SegmentIntersection { -public: - SegmentIntersection() : - iContour(0), - iSegment(0), - pos_p(0), - pos_q(1), - type(UNKNOWN), - consumed_vertical_up(false), - consumed_perimeter_right(false) - {} - // Index of a contour in ExPolygonWithOffset, with which this vertical line intersects. - size_t iContour; + size_t iContour{ 0 }; // Index of a segment in iContour, with which this vertical line intersects. - size_t iSegment; - // y position of the intersection, ratinal number. - int64_t pos_p; - uint32_t pos_q; + size_t iSegment{ 0 }; + // y position of the intersection, rational number. + int64_t pos_p{ 0 }; + uint32_t pos_q{ 1 }; coord_t pos() const { // Division rounds both positive and negative down to zero. @@ -147,21 +138,50 @@ public: // A vertical segment will be at least intersected by OUTER_LOW, OUTER_HIGH, // but it could be intersected with OUTER_LOW, INNER_LOW, INNER_HIGH, OUTER_HIGH, // and there may be more than one pair of INNER_LOW, INNER_HIGH between OUTER_LOW, OUTER_HIGH. - enum SegmentIntersectionType { - OUTER_LOW = 0, - OUTER_HIGH = 1, - INNER_LOW = 2, - INNER_HIGH = 3, - UNKNOWN = -1 + enum SegmentIntersectionType : char { + UNKNOWN, + OUTER_LOW, + OUTER_HIGH, + INNER_LOW, + INNER_HIGH, }; - SegmentIntersectionType type; + SegmentIntersectionType type{ UNKNOWN }; + + // Left vertical line / contour intersection point. + // null if next_on_contour_vertical. + int32_t prev_on_contour{ 0 }; + // Right vertical line / contour intersection point. + // If next_on_contour_vertical, then then next_on_contour contains next contour point on the same vertical line. + int32_t next_on_contour{ 0 }; + + enum class LinkType : uint8_t { + // Horizontal link (left or right). + Horizontal, + // Vertical link, up. + Up, + // Vertical link, down. + Down + }; + + enum class LinkQuality : uint8_t { + Invalid, + Valid, + // Valid link, but too long to be followed. + TooLong, + }; + + // Kept grouped with other booleans for smaller memory footprint. + LinkType prev_on_contour_type{ LinkType::Horizontal }; + LinkType next_on_contour_type{ LinkType::Horizontal }; + LinkQuality prev_on_contour_quality{ LinkQuality::Valid }; + LinkQuality next_on_contour_quality{ LinkQuality::Valid }; // Was this segment along the y axis consumed? // Up means up along the vertical segment. - bool consumed_vertical_up; + bool consumed_vertical_up{ false }; // Was a segment of the inner perimeter contour consumed? // Right means right from the vertical segment. - bool consumed_perimeter_right; + bool consumed_perimeter_right{ false }; // For the INNER_LOW type, this point may be connected to another INNER_LOW point following a perimeter contour. // For the INNER_HIGH type, this point may be connected to another INNER_HIGH point following a perimeter contour. @@ -172,6 +192,77 @@ public: bool is_low () const { return type == INNER_LOW || type == OUTER_LOW; } bool is_high () const { return type == INNER_HIGH || type == OUTER_HIGH; } + enum class Side { + Left, + Right + }; + enum class Direction { + Up, + Down + }; + + bool has_left_horizontal() const { return this->prev_on_contour_type == LinkType::Horizontal; } + bool has_right_horizontal() const { return this->next_on_contour_type == LinkType::Horizontal; } + bool has_horizontal(Side side) const { return side == Side::Left ? this->has_left_horizontal() : this->has_right_horizontal(); } + + bool has_left_vertical_up() const { return this->prev_on_contour_type == LinkType::Up; } + bool has_left_vertical_down() const { return this->prev_on_contour_type == LinkType::Down; } + bool has_left_vertical(Direction dir) const { return dir == Direction::Up ? this->has_left_vertical_up() : this->has_left_vertical_down(); } + bool has_left_vertical() const { return this->has_left_vertical_up() || this->has_left_vertical_down(); } + bool has_left_vertical_outside() const { return this->is_low() ? this->has_left_vertical_down() : this->has_left_vertical_up(); } + + bool has_right_vertical_up() const { return this->next_on_contour_type == LinkType::Up; } + bool has_right_vertical_down() const { return this->next_on_contour_type == LinkType::Down; } + bool has_right_vertical(Direction dir) const { return dir == Direction::Up ? this->has_right_vertical_up() : this->has_right_vertical_down(); } + bool has_right_vertical() const { return this->has_right_vertical_up() || this->has_right_vertical_down(); } + bool has_right_vertical_outside() const { return this->is_low() ? this->has_right_vertical_down() : this->has_right_vertical_up(); } + + bool has_vertical() const { return this->has_left_vertical() || this->has_right_vertical(); } + bool has_vertical(Side side) const { return side == Side::Left ? this->has_left_vertical() : this->has_right_vertical(); } + bool has_vertical_up() const { return this->has_left_vertical_up() || this->has_right_vertical_up(); } + bool has_vertical_down() const { return this->has_left_vertical_down() || this->has_right_vertical_down(); } + bool has_vertical(Direction dir) const { return dir == Direction::Up ? this->has_vertical_up() : this->has_vertical_down(); } + + int left_horizontal() const { return this->has_left_horizontal() ? this->prev_on_contour : -1; } + int right_horizontal() const { return this->has_right_horizontal() ? this->next_on_contour : -1; } + int horizontal(Side side) const { return side == Side::Left ? this->left_horizontal() : this->right_horizontal(); } + LinkQuality horizontal_quality(Side side) const { + assert(this->has_horizontal(side)); + return side == Side::Left ? this->prev_on_contour_quality : this->next_on_contour_quality; + } + + int left_vertical_up() const { return this->has_left_vertical_up() ? this->prev_on_contour : -1; } + int left_vertical_down() const { return this->has_left_vertical_down() ? this->prev_on_contour : -1; } + int left_vertical(Direction dir) const { return (dir == Direction::Up ? this->has_left_vertical_up() : this->has_left_vertical_down()) ? this->prev_on_contour : -1; } + int left_vertical() const { return this->has_left_vertical() ? this->prev_on_contour : -1; } + int left_vertical_outside() const { return this->is_low() ? this->left_vertical_down() : this->left_vertical_up(); } + int right_vertical_up() const { return this->has_right_vertical_up() ? this->next_on_contour : -1; } + int right_vertical_down() const { return this->has_right_vertical_down() ? this->next_on_contour : -1; } + int right_vertical(Direction dir) const { return (dir == Direction::Up ? this->has_right_vertical_up() : this->has_right_vertical_down()) ? this->next_on_contour : -1; } + int right_vertical() const { return this->has_right_vertical() ? this->next_on_contour : -1; } + int right_vertical_outside() const { return this->is_low() ? this->right_vertical_down() : this->right_vertical_up(); } + + int vertical_up(Side side) const { return side == Side::Left ? this->left_vertical_up() : this->right_vertical_up(); } + int vertical_down(Side side) const { return side == Side::Left ? this->left_vertical_down() : this->right_vertical_down(); } + int vertical_outside(Side side) const { return side == Side::Left ? this->left_vertical_outside() : this->right_vertical_outside(); } + // Returns -1 if there is no link up. + int vertical_up() const { + return this->has_left_vertical_up() ? this->left_vertical_up() : this->right_vertical_up(); + } + LinkQuality vertical_up_quality() const { + return this->has_left_vertical_up() ? this->prev_on_contour_quality : this->next_on_contour_quality; + } + // Returns -1 if there is no link down. + int vertical_down() const { + // assert(! this->has_left_vertical_down() || ! this->has_right_vertical_down()); + return this->has_left_vertical_down() ? this->left_vertical_down() : this->right_vertical_down(); + } + LinkQuality vertical_down_quality() const { + return this->has_left_vertical_down() ? this->prev_on_contour_quality : this->next_on_contour_quality; + } + int vertical_outside() const { return this->is_low() ? this->vertical_down() : this->vertical_up(); } + LinkQuality vertical_outside_quality() const { return this->is_low() ? this->vertical_down_quality() : this->vertical_up_quality(); } + // Compare two y intersection points given by rational numbers. // Note that the rational number is given as pos_p/pos_q, where pos_p is int64 and pos_q is uint32. // This function calculates pos_p * other.pos_q < other.pos_p * pos_q as a 48bit number. @@ -256,11 +347,11 @@ public: return l_hi + (l_lo >> 32) == r_hi + (r_lo >> 32); } }; +static_assert(sizeof(SegmentIntersection::pos_q) == 4, "SegmentIntersection::pos_q has to be 32bit long!"); // A vertical line with intersection points with polygons. -class SegmentedIntersectionLine +struct SegmentedIntersectionLine { -public: // Index of this vertical intersection line. size_t idx; // x position of this vertical intersection line. @@ -296,10 +387,10 @@ public: // bool sticks_removed = remove_sticks(polygons_src); // if (sticks_removed) printf("Sticks removed!\n"); - polygons_outer = offset(polygons_src, aoffset1, + polygons_outer = offset(polygons_src, float(aoffset1), ClipperLib::jtMiter, mitterLimit); - polygons_inner = offset(polygons_outer, aoffset2 - aoffset1, + polygons_inner = offset(polygons_outer, float(aoffset2 - aoffset1), ClipperLib::jtMiter, mitterLimit); // Filter out contours with zero area or small area, contours with 2 points only. @@ -369,227 +460,92 @@ static inline int distance_of_segmens(const Polygon &poly, size_t seg1, size_t s d += int(poly.points.size()); return d; } - -// For a vertical line, an inner contour and an intersection point, -// find an intersection point on the previous resp. next vertical line. -// The intersection point is connected with the prev resp. next intersection point with iInnerContour. -// Return -1 if there is no such point on the previous resp. next vertical line. -static inline int intersection_on_prev_next_vertical_line( - const ExPolygonWithOffset &poly_with_offset, - const std::vector &segs, - size_t iVerticalLine, - size_t iInnerContour, - size_t iIntersection, - bool dir_is_next) -{ - size_t iVerticalLineOther = iVerticalLine; - if (dir_is_next) { - if (++ iVerticalLineOther == segs.size()) - // No successive vertical line. - return -1; - } else if (iVerticalLineOther -- == 0) { - // No preceding vertical line. - return -1; - } - - const SegmentedIntersectionLine &il = segs[iVerticalLine]; - const SegmentIntersection &itsct = il.intersections[iIntersection]; - const SegmentedIntersectionLine &il2 = segs[iVerticalLineOther]; - const Polygon &poly = poly_with_offset.contour(iInnerContour); -// const bool ccw = poly_with_offset.is_contour_ccw(iInnerContour); - const bool forward = itsct.is_low() == dir_is_next; - // Resulting index of an intersection point on il2. - int out = -1; - // Find an intersection point on iVerticalLineOther, intersecting iInnerContour - // at the same orientation as iIntersection, and being closest to iIntersection - // in the number of contour segments, when following the direction of the contour. - int dmin = std::numeric_limits::max(); - for (size_t i = 0; i < il2.intersections.size(); ++ i) { - const SegmentIntersection &itsct2 = il2.intersections[i]; - if (itsct.iContour == itsct2.iContour && itsct.type == itsct2.type) { - /* - if (itsct.is_low()) { - assert(itsct.type == SegmentIntersection::INNER_LOW); - assert(iIntersection > 0); - assert(il.intersections[iIntersection-1].type == SegmentIntersection::OUTER_LOW); - assert(i > 0); - if (il2.intersections[i-1].is_inner()) - // Take only the lowest inner intersection point. - continue; - assert(il2.intersections[i-1].type == SegmentIntersection::OUTER_LOW); - } else { - assert(itsct.type == SegmentIntersection::INNER_HIGH); - assert(iIntersection+1 < il.intersections.size()); - assert(il.intersections[iIntersection+1].type == SegmentIntersection::OUTER_HIGH); - assert(i+1 < il2.intersections.size()); - if (il2.intersections[i+1].is_inner()) - // Take only the highest inner intersection point. - continue; - assert(il2.intersections[i+1].type == SegmentIntersection::OUTER_HIGH); - } - */ - // The intersection points lie on the same contour and have the same orientation. - // Find the intersection point with a shortest path in the direction of the contour. - int d = distance_of_segmens(poly, itsct.iSegment, itsct2.iSegment, forward); - if (d < dmin) { - out = i; - dmin = d; - } - } - } - //FIXME this routine is not asymptotic optimal, it will be slow if there are many intersection points along the line. - return out; -} - -static inline int intersection_on_prev_vertical_line( - const ExPolygonWithOffset &poly_with_offset, - const std::vector &segs, - size_t iVerticalLine, - size_t iInnerContour, - size_t iIntersection) -{ - return intersection_on_prev_next_vertical_line(poly_with_offset, segs, iVerticalLine, iInnerContour, iIntersection, false); -} - -static inline int intersection_on_next_vertical_line( - const ExPolygonWithOffset &poly_with_offset, - const std::vector &segs, - size_t iVerticalLine, - size_t iInnerContour, - size_t iIntersection) -{ - return intersection_on_prev_next_vertical_line(poly_with_offset, segs, iVerticalLine, iInnerContour, iIntersection, true); -} - -enum IntersectionTypeOtherVLine { - // There is no connection point on the other vertical line. - INTERSECTION_TYPE_OTHER_VLINE_UNDEFINED = -1, - // Connection point on the other vertical segment was found - // and it could be followed. - INTERSECTION_TYPE_OTHER_VLINE_OK = 0, - // The connection segment connects to a middle of a vertical segment. - // Cannot follow. - INTERSECTION_TYPE_OTHER_VLINE_INNER, - // Cannot extend the contor to this intersection point as either the connection segment - // or the succeeding vertical segment were already consumed. - INTERSECTION_TYPE_OTHER_VLINE_CONSUMED, - // Not the first intersection along the contor. This intersection point - // has been preceded by an intersection point along the vertical line. - INTERSECTION_TYPE_OTHER_VLINE_NOT_FIRST, -}; - // Find an intersection on a previous line, but return -1, if the connecting segment of a perimeter was already extruded. -static inline IntersectionTypeOtherVLine intersection_type_on_prev_next_vertical_line( - const std::vector &segs, +static inline bool intersection_on_prev_next_vertical_line_valid( + const std::vector& segs, size_t iVerticalLine, size_t iIntersection, - size_t iIntersectionOther, - bool dir_is_next) + SegmentIntersection::Side side) { - // This routine will propose a connecting line even if the connecting perimeter segment intersects - // iVertical line multiple times before reaching iIntersectionOther. - if (iIntersectionOther == size_t(-1)) - return INTERSECTION_TYPE_OTHER_VLINE_UNDEFINED; - assert(dir_is_next ? (iVerticalLine + 1 < segs.size()) : (iVerticalLine > 0)); - const SegmentedIntersectionLine &il_this = segs[iVerticalLine]; - const SegmentIntersection &itsct_this = il_this.intersections[iIntersection]; - const SegmentedIntersectionLine &il_other = segs[dir_is_next ? (iVerticalLine+1) : (iVerticalLine-1)]; - const SegmentIntersection &itsct_other = il_other.intersections[iIntersectionOther]; - assert(itsct_other.is_inner()); + const SegmentedIntersectionLine& vline_this = segs[iVerticalLine]; + const SegmentIntersection& it_this = vline_this.intersections[iIntersection]; + if (it_this.has_vertical(side)) + // Not the first intersection along the contor. This intersection point + // has been preceded by an intersection point along the vertical line. + return false; + int iIntersectionOther = it_this.horizontal(side); + if (iIntersectionOther == -1) + return false; + assert(side == SegmentIntersection::Side::Right ? (iVerticalLine + 1 < segs.size()) : (iVerticalLine > 0)); + const SegmentedIntersectionLine& vline_other = segs[side == SegmentIntersection::Side::Right ? (iVerticalLine + 1) : (iVerticalLine - 1)]; + const SegmentIntersection& it_other = vline_other.intersections[iIntersectionOther]; + assert(it_other.is_inner()); assert(iIntersectionOther > 0); - assert(iIntersectionOther + 1 < il_other.intersections.size()); + assert(iIntersectionOther + 1 < vline_other.intersections.size()); // Is iIntersectionOther at the boundary of a vertical segment? - const SegmentIntersection &itsct_other2 = il_other.intersections[itsct_other.is_low() ? iIntersectionOther - 1 : iIntersectionOther + 1]; - if (itsct_other2.is_inner()) + const SegmentIntersection& it_other2 = vline_other.intersections[it_other.is_low() ? iIntersectionOther - 1 : iIntersectionOther + 1]; + if (it_other2.is_inner()) // Cannot follow a perimeter segment into the middle of another vertical segment. // Only perimeter segments connecting to the end of a vertical segment are followed. - return INTERSECTION_TYPE_OTHER_VLINE_INNER; - assert(itsct_other.is_low() == itsct_other2.is_low()); - if (dir_is_next ? itsct_this.consumed_perimeter_right : itsct_other.consumed_perimeter_right) + return false; + assert(it_other.is_low() == it_other2.is_low()); + if (it_this.horizontal_quality(side) != SegmentIntersection::LinkQuality::Valid) + return false; + if (side == SegmentIntersection::Side::Right ? it_this.consumed_perimeter_right : it_other.consumed_perimeter_right) // This perimeter segment was already consumed. - return INTERSECTION_TYPE_OTHER_VLINE_CONSUMED; - if (itsct_other.is_low() ? itsct_other.consumed_vertical_up : il_other.intersections[iIntersectionOther-1].consumed_vertical_up) + return false; + if (it_other.is_low() ? it_other.consumed_vertical_up : vline_other.intersections[iIntersectionOther - 1].consumed_vertical_up) // This vertical segment was already consumed. - return INTERSECTION_TYPE_OTHER_VLINE_CONSUMED; - return INTERSECTION_TYPE_OTHER_VLINE_OK; + return false; +#if 0 + if (it_other.vertical_outside() != -1 && it_other.vertical_outside_quality() == SegmentIntersection::LinkQuality::Valid) + // Landed inside a vertical run. Stop here. + return false; +#endif + return true; } -static inline IntersectionTypeOtherVLine intersection_type_on_prev_vertical_line( - const std::vector &segs, - size_t iVerticalLine, - size_t iIntersection, - size_t iIntersectionPrev) +static inline bool intersection_on_prev_vertical_line_valid( + const std::vector& segs, + size_t iVerticalLine, + size_t iIntersection) { - return intersection_type_on_prev_next_vertical_line(segs, iVerticalLine, iIntersection, iIntersectionPrev, false); + return intersection_on_prev_next_vertical_line_valid(segs, iVerticalLine, iIntersection, SegmentIntersection::Side::Left); } -static inline IntersectionTypeOtherVLine intersection_type_on_next_vertical_line( - const std::vector &segs, - size_t iVerticalLine, - size_t iIntersection, - size_t iIntersectionNext) +static inline bool intersection_on_next_vertical_line_valid( + const std::vector& segs, + size_t iVerticalLine, + size_t iIntersection) { - return intersection_type_on_prev_next_vertical_line(segs, iVerticalLine, iIntersection, iIntersectionNext, true); + return intersection_on_prev_next_vertical_line_valid(segs, iVerticalLine, iIntersection, SegmentIntersection::Side::Right); } // Measure an Euclidian length of a perimeter segment when going from iIntersection to iIntersection2. -static inline coordf_t measure_perimeter_prev_next_segment_length( - const ExPolygonWithOffset &poly_with_offset, - const std::vector &segs, +static inline coordf_t measure_perimeter_horizontal_segment_length( + const ExPolygonWithOffset& poly_with_offset, + const std::vector& segs, size_t iVerticalLine, - size_t iInnerContour, - size_t iIntersection, - size_t iIntersection2, - bool dir_is_next) -{ - size_t iVerticalLineOther = iVerticalLine; - if (dir_is_next) { - if (++ iVerticalLineOther == segs.size()) - // No successive vertical line. - return coordf_t(-1); - } else if (iVerticalLineOther -- == 0) { - // No preceding vertical line. - return coordf_t(-1); - } - - const SegmentedIntersectionLine &il = segs[iVerticalLine]; - const SegmentIntersection &itsct = il.intersections[iIntersection]; - const SegmentedIntersectionLine &il2 = segs[iVerticalLineOther]; - const SegmentIntersection &itsct2 = il2.intersections[iIntersection2]; - const Polygon &poly = poly_with_offset.contour(iInnerContour); -// const bool ccw = poly_with_offset.is_contour_ccw(iInnerContour); - assert(itsct.type == itsct2.type); - assert(itsct.iContour == itsct2.iContour); - assert(itsct.is_inner()); - const bool forward = itsct.is_low() == dir_is_next; - - Point p1(il.pos, itsct.pos()); - Point p2(il2.pos, itsct2.pos()); - return forward ? - segment_length(poly, itsct .iSegment, p1, itsct2.iSegment, p2) : - segment_length(poly, itsct2.iSegment, p2, itsct .iSegment, p1); -} - -static inline coordf_t measure_perimeter_prev_segment_length( - const ExPolygonWithOffset &poly_with_offset, - const std::vector &segs, - size_t iVerticalLine, - size_t iInnerContour, size_t iIntersection, size_t iIntersection2) { - return measure_perimeter_prev_next_segment_length(poly_with_offset, segs, iVerticalLine, iInnerContour, iIntersection, iIntersection2, false); -} + size_t iVerticalLineOther = iVerticalLine + 1; + assert(iVerticalLineOther < segs.size()); + const SegmentedIntersectionLine& vline = segs[iVerticalLine]; + const SegmentIntersection& it = vline.intersections[iIntersection]; + const SegmentedIntersectionLine& vline2 = segs[iVerticalLineOther]; + const SegmentIntersection& it2 = vline2.intersections[iIntersection2]; + assert(it.iContour == it2.iContour); + const Polygon& poly = poly_with_offset.contour(it.iContour); + // const bool ccw = poly_with_offset.is_contour_ccw(vline.iContour); + assert(it.type == it2.type); + assert(it.iContour == it2.iContour); -static inline coordf_t measure_perimeter_next_segment_length( - const ExPolygonWithOffset &poly_with_offset, - const std::vector &segs, - size_t iVerticalLine, - size_t iInnerContour, - size_t iIntersection, - size_t iIntersection2) -{ - return measure_perimeter_prev_next_segment_length(poly_with_offset, segs, iVerticalLine, iInnerContour, iIntersection, iIntersection2, true); + Point p1(vline.pos, it.pos()); + Point p2(vline2.pos, it2.pos()); + return it.is_low() ? + segment_length(poly, it.iSegment, p1, it2.iSegment, p2) : + segment_length(poly, it2.iSegment, p2, it.iSegment, p1); } // Append the points of a perimeter segment when going from iIntersection to iIntersection2. @@ -638,25 +594,22 @@ static inline coordf_t measure_perimeter_segment_on_vertical_line_length( const ExPolygonWithOffset &poly_with_offset, const std::vector &segs, size_t iVerticalLine, - size_t iInnerContour, size_t iIntersection, size_t iIntersection2, bool forward) { - const SegmentedIntersectionLine &il = segs[iVerticalLine]; - const SegmentIntersection &itsct = il.intersections[iIntersection]; - const SegmentIntersection &itsct2 = il.intersections[iIntersection2]; - const Polygon &poly = poly_with_offset.contour(iInnerContour); - assert(itsct.is_inner()); - assert(itsct2.is_inner()); + const SegmentedIntersectionLine& il = segs[iVerticalLine]; + const SegmentIntersection& itsct = il.intersections[iIntersection]; + const SegmentIntersection& itsct2 = il.intersections[iIntersection2]; + const Polygon& poly = poly_with_offset.contour(itsct.iContour); + assert(itsct.is_inner() == itsct2.is_inner()); assert(itsct.type != itsct2.type); - assert(itsct.iContour == iInnerContour); assert(itsct.iContour == itsct2.iContour); Point p1(il.pos, itsct.pos()); Point p2(il.pos, itsct2.pos()); return forward ? - segment_length(poly, itsct .iSegment, p1, itsct2.iSegment, p2) : - segment_length(poly, itsct2.iSegment, p2, itsct .iSegment, p1); + segment_length(poly, itsct.iSegment, p1, itsct2.iSegment, p2) : + segment_length(poly, itsct2.iSegment, p2, itsct.iSegment, p1); } // Append the points of a perimeter segment when going from iIntersection to iIntersection2. @@ -736,10 +689,10 @@ static inline float measure_outer_contour_slab( distance_of_segmens(poly, iSegBelow, itsct.iSegment, true); int d_up = (iAbove == -1) ? std::numeric_limits::max() : distance_of_segmens(poly, iSegAbove, itsct.iSegment, true); - if (intrsctn_type_prev == INTERSECTION_TYPE_OTHER_VLINE_OK && d_horiz > std::min(d_down, d_up)) + if (intrsection_type_prev == INTERSECTION_TYPE_OTHER_VLINE_OK && d_horiz > std::min(d_down, d_up)) // The vertical crossing comes eralier than the prev crossing. // Disable the perimeter going back. - intrsctn_type_prev = INTERSECTION_TYPE_OTHER_VLINE_NOT_FIRST; + intrsection_type_prev = INTERSECTION_TYPE_OTHER_VLINE_NOT_FIRST; if (d_up > std::min(d_horiz, d_down)) // The horizontal crossing comes earlier than the vertical crossing. vert_seg_dir_valid_mask &= ~DIR_BACKWARD; @@ -759,6 +712,17 @@ static inline float measure_outer_contour_slab( } */ +void +FillRectilinear2::init_spacing(coordf_t spacing, const FillParams& params) +{ + Fill::init_spacing(spacing, params); + //remove this code path becaus it's only really useful for squares at 45° and it override a setting + // define flow spacing according to requested density + //if (params.full_infill() && !params.dont_adjust) { + // this->spacing = unscale(this->_adjust_solid_spacing(bounding_box.size()(0), _line_spacing_for_density(params.density))); + //} +} + enum DirectionMask { DIR_FORWARD = 1, @@ -772,7 +736,7 @@ std::vector FillRectilinear2::_vert_lines_for_polygon size_t n_vlines = (bounding_box.max(0) - bounding_box.min(0) + line_spacing - 1) / line_spacing; coord_t x0 = bounding_box.min(0); if (params.full_infill()) - x0 += (line_spacing + SCALED_EPSILON) / 2; + x0 += (line_spacing + coord_t(SCALED_EPSILON)) / 2; #ifdef SLIC3R_DEBUG static int iRun = 0; @@ -865,15 +829,1697 @@ std::vector FillRectilinear2::_vert_lines_for_polygon return segs; } -void -FillRectilinear2::init_spacing(coordf_t spacing, const FillParams ¶ms) + +static void slice_region_by_vertical_lines(std::vector& segs, + const ExPolygonWithOffset& poly_with_offset)//, size_t n_vlines, coord_t x0, coord_t line_spacing) { - Fill::init_spacing(spacing, params); - //remove this code path becaus it's only really useful for squares at 45° and it override a setting - // define flow spacing according to requested density - //if (params.full_infill() && !params.dont_adjust) { - // this->spacing = unscale(this->_adjust_solid_spacing(bounding_box.size()(0), _line_spacing_for_density(params.density))); - //} + // Sort the intersections along their segments, specify the intersection types. + for (size_t i_seg = 0; i_seg < segs.size(); ++i_seg) { + SegmentedIntersectionLine& sil = segs[i_seg]; + // Sort the intersection points using exact rational arithmetic. + std::sort(sil.intersections.begin(), sil.intersections.end()); + // Assign the intersection types, remove duplicate or overlapping intersection points. + // When a loop vertex touches a vertical line, intersection point is generated for both segments. + // If such two segments are oriented equally, then one of them is removed. + // Otherwise the vertex is tangential to the vertical line and both segments are removed. + // The same rule applies, if the loop is pinched into a single point and this point touches the vertical line: + // The loop has a zero vertical size at the vertical line, therefore the intersection point is removed. + size_t j = 0; + for (size_t i = 0; i < sil.intersections.size(); ++i) { + // What is the orientation of the segment at the intersection point? + size_t iContour = sil.intersections[i].iContour; + const Points& contour = poly_with_offset.contour(iContour).points; + size_t iSegment = sil.intersections[i].iSegment; + size_t iPrev = ((iSegment == 0) ? contour.size() : iSegment) - 1; + coord_t dir = contour[iSegment](0) - contour[iPrev](0); + bool low = dir > 0; + sil.intersections[i].type = poly_with_offset.is_contour_outer(iContour) ? + (low ? SegmentIntersection::OUTER_LOW : SegmentIntersection::OUTER_HIGH) : + (low ? SegmentIntersection::INNER_LOW : SegmentIntersection::INNER_HIGH); + if (j > 0 && sil.intersections[i].iContour == sil.intersections[j - 1].iContour) { + // Two successive intersection points on a vertical line with the same contour. This may be a special case. + if (sil.intersections[i].pos() == sil.intersections[j - 1].pos()) { + // Two successive segments meet exactly at the vertical line. +#ifdef SLIC3R_DEBUG + // Verify that the segments of sil.intersections[i] and sil.intersections[j-1] are adjoint. + size_t iSegment2 = sil.intersections[j - 1].iSegment; + size_t iPrev2 = ((iSegment2 == 0) ? contour.size() : iSegment2) - 1; + assert(iSegment == iPrev2 || iSegment2 == iPrev); +#endif /* SLIC3R_DEBUG */ + if (sil.intersections[i].type == sil.intersections[j - 1].type) { + // Two successive segments of the same direction (both to the right or both to the left) + // meet exactly at the vertical line. + // Remove the second intersection point. + } else { + // This is a loop returning to the same point. + // It may as well be a vertex of a loop touching this vertical line. + // Remove both the lines. + --j; + } + } else if (sil.intersections[i].type == sil.intersections[j - 1].type) { + // Two non successive segments of the same direction (both to the right or both to the left) + // meet exactly at the vertical line. That means there is a Z shaped path, where the center segment + // of the Z shaped path is aligned with this vertical line. + // Remove one of the intersection points while maximizing the vertical segment length. + if (low) { + // Remove the second intersection point, keep the first intersection point. + } else { + // Remove the first intersection point, keep the second intersection point. + sil.intersections[j - 1] = sil.intersections[i]; + } + } else { + // Vertical line intersects a contour segment at a general position (not at one of its end points). + // or the contour just touches this vertical line with a vertical segment or a sequence of vertical segments. + + //if you have to remove a point, be sure to remove also its sibling. + if (sil.intersections[j].pos() != sil.intersections[i].pos() || j + 1 != i) { + // Keep both intersection points. + if (j < i) + sil.intersections[j] = sil.intersections[i]; + ++j; + } + } + } else { + // Vertical line intersects a contour segment at a general position (not at one of its end points). + if (j < i) + sil.intersections[j] = sil.intersections[i]; + ++j; + } + } + // Shrink the list of intersections, if any of the intersection was removed during the classification. + if (j < sil.intersections.size()) + sil.intersections.erase(sil.intersections.begin() + j, sil.intersections.end()); + } + + // Verify the segments. If something is wrong, give up. +#define ASSERT_THROW(CONDITION) do { assert(CONDITION); if (! (CONDITION)) throw InfillFailedException(); } while (0) + for (size_t i_seg = 0; i_seg < segs.size(); ++i_seg) { + SegmentedIntersectionLine& sil = segs[i_seg]; + // The intersection points have to be even. + ASSERT_THROW((sil.intersections.size() & 1) == 0); + for (size_t i = 0; i < sil.intersections.size();) { + // An intersection segment crossing the bigger contour may cross the inner offsetted contour even number of times. + ASSERT_THROW(sil.intersections[i].type == SegmentIntersection::OUTER_LOW); + size_t j = i + 1; + ASSERT_THROW(j < sil.intersections.size()); + ASSERT_THROW(sil.intersections[j].type == SegmentIntersection::INNER_LOW || sil.intersections[j].type == SegmentIntersection::OUTER_HIGH); + for (; j < sil.intersections.size() && sil.intersections[j].is_inner(); ++j); + ASSERT_THROW(j < sil.intersections.size()); + ASSERT_THROW((j & 1) == 1); + ASSERT_THROW(sil.intersections[j].type == SegmentIntersection::OUTER_HIGH); + ASSERT_THROW(i + 1 == j || sil.intersections[j - 1].type == SegmentIntersection::INNER_HIGH); + i = j + 1; + } + } +#undef ASSERT_THROW + +} + +// Connect each contour / vertical line intersection point with another two contour / vertical line intersection points. +// (fill in SegmentIntersection::{prev_on_contour, prev_on_contour_vertical, next_on_contour, next_on_contour_vertical}. +// These contour points are either on the same vertical line, or on the vertical line left / right to the current one. +static void connect_segment_intersections_by_contours( + const ExPolygonWithOffset& poly_with_offset, std::vector& segs, + const FillParams& params, const coord_t link_max_length) +{ + for (size_t i_vline = 0; i_vline < segs.size(); ++i_vline) { + SegmentedIntersectionLine& il = segs[i_vline]; + const SegmentedIntersectionLine* il_prev = i_vline > 0 ? &segs[i_vline - 1] : nullptr; + const SegmentedIntersectionLine* il_next = i_vline + 1 < segs.size() ? &segs[i_vline + 1] : nullptr; + + for (size_t i_intersection = 0; i_intersection < il.intersections.size(); ++i_intersection) { + SegmentIntersection& itsct = il.intersections[i_intersection]; + const Polygon& poly = poly_with_offset.contour(itsct.iContour); + const bool forward = itsct.is_low(); // == poly_with_offset.is_contour_ccw(intrsctn->iContour); + + // 1) Find possible connection points on the previous / next vertical line. + // Find an intersection point on il_prev, intersecting i_intersection + // at the same orientation as i_intersection, and being closest to i_intersection + // in the number of contour segments, when following the direction of the contour. + //FIXME this has O(n) time complexity. Likely an O(log(n)) scheme is possible. + int iprev = -1; + int d_prev = std::numeric_limits::max(); + if (il_prev) { + for (int i = 0; i < il_prev->intersections.size(); ++i) { + const SegmentIntersection& itsct2 = il_prev->intersections[i]; + if (itsct.iContour == itsct2.iContour && itsct.type == itsct2.type) { + // The intersection points lie on the same contour and have the same orientation. + // Find the intersection point with a shortest path in the direction of the contour. + int d = distance_of_segmens(poly, itsct2.iSegment, itsct.iSegment, forward); + if (d < d_prev) { + iprev = i; + d_prev = d; + } + } + } + } + + // The same for il_next. + int inext = -1; + int d_next = std::numeric_limits::max(); + if (il_next) { + for (size_t i = 0; i < il_next->intersections.size(); ++i) { + const SegmentIntersection& itsct2 = il_next->intersections[i]; + if (itsct.iContour == itsct2.iContour && itsct.type == itsct2.type) { + // The intersection points lie on the same contour and have the same orientation. + // Find the intersection point with a shortest path in the direction of the contour. + int d = distance_of_segmens(poly, itsct.iSegment, itsct2.iSegment, forward); + if (d < d_next) { + inext = int(i); + d_next = d; + } + } + } + } + + // 2) Find possible connection points on the same vertical line. + bool same_prev = false; + bool same_next = false; + // Does the perimeter intersect the current vertical line above intrsctn? + for (size_t i = 0; i < il.intersections.size(); ++i) + if (const SegmentIntersection& it2 = il.intersections[i]; + i != i_intersection && it2.iContour == itsct.iContour && it2.type != itsct.type) { + int d = distance_of_segmens(poly, it2.iSegment, itsct.iSegment, forward); + if (d < d_prev) { + iprev = i; + d_prev = d; + same_prev = true; + } + d = distance_of_segmens(poly, itsct.iSegment, it2.iSegment, forward); + if (d < d_next) { + inext = i; + d_next = d; + same_next = true; + } + } + assert(iprev >= 0); + assert(inext >= 0); + + itsct.prev_on_contour = iprev; + itsct.prev_on_contour_type = same_prev ? + (iprev < int(i_intersection) ? SegmentIntersection::LinkType::Down : SegmentIntersection::LinkType::Up) : + SegmentIntersection::LinkType::Horizontal; + itsct.next_on_contour = inext; + itsct.next_on_contour_type = same_next ? + (inext < int(i_intersection) ? SegmentIntersection::LinkType::Down : SegmentIntersection::LinkType::Up) : + SegmentIntersection::LinkType::Horizontal; + + if (same_prev) { + // Only follow a vertical perimeter segment if it skips just the outer intersections. + SegmentIntersection* it = &itsct; + SegmentIntersection* end = il.intersections.data() + iprev; + assert(it != end); + if (it > end) + std::swap(it, end); + for (++it; it != end; ++it) + if (it->is_inner()) { + itsct.prev_on_contour_quality = SegmentIntersection::LinkQuality::Invalid; + break; + } + } + + if (same_next) { + // Only follow a vertical perimeter segment if it skips just the outer intersections. + SegmentIntersection* it = &itsct; + SegmentIntersection* end = il.intersections.data() + inext; + assert(it != end); + if (it > end) + std::swap(it, end); + for (++it; it != end; ++it) + if (it->is_inner()) { + itsct.next_on_contour_quality = SegmentIntersection::LinkQuality::Invalid; + break; + } + } + + // If both iprev and inext are on this vline, then there must not be any intersection with the previous or next contour and we will + // not trace this contour when generating infill. + if (same_prev && same_next) { + assert(iprev != i_intersection); + assert(inext != i_intersection); + if ((iprev > i_intersection) == (inext > i_intersection)) { + // Both closest intersections of this contour are on the same vertical line and at the same side of this point. + // Ignore them when tracing the infill. + itsct.prev_on_contour_quality = SegmentIntersection::LinkQuality::Invalid; + itsct.next_on_contour_quality = SegmentIntersection::LinkQuality::Invalid; + } + } + + if (params.dont_connect) { + if (itsct.prev_on_contour_quality == SegmentIntersection::LinkQuality::Valid) + itsct.prev_on_contour_quality = SegmentIntersection::LinkQuality::TooLong; + if (itsct.next_on_contour_quality == SegmentIntersection::LinkQuality::Valid) + itsct.next_on_contour_quality = SegmentIntersection::LinkQuality::TooLong; + } else if (link_max_length > 0) { + // Measure length of the links. + if (itsct.prev_on_contour_quality == SegmentIntersection::LinkQuality::Valid && + (same_prev ? + measure_perimeter_segment_on_vertical_line_length(poly_with_offset, segs, i_vline, iprev, i_intersection, forward) : + measure_perimeter_horizontal_segment_length(poly_with_offset, segs, i_vline - 1, iprev, i_intersection)) > link_max_length) + itsct.prev_on_contour_quality = SegmentIntersection::LinkQuality::TooLong; + if (itsct.next_on_contour_quality == SegmentIntersection::LinkQuality::Valid && + (same_next ? + measure_perimeter_segment_on_vertical_line_length(poly_with_offset, segs, i_vline, i_intersection, inext, forward) : + measure_perimeter_horizontal_segment_length(poly_with_offset, segs, i_vline, i_intersection, inext)) > link_max_length) + itsct.next_on_contour_quality = SegmentIntersection::LinkQuality::TooLong; + } + } + + // Make the LinkQuality::Invalid symmetric on vertical connections. + for (size_t i_intersection = 0; i_intersection < il.intersections.size(); ++i_intersection) { + SegmentIntersection& it = il.intersections[i_intersection]; + if (it.has_left_vertical() && it.prev_on_contour_quality == SegmentIntersection::LinkQuality::Invalid) { + SegmentIntersection& it2 = il.intersections[it.left_vertical()]; + assert(it2.left_vertical() == i_intersection); + it2.prev_on_contour_quality = SegmentIntersection::LinkQuality::Invalid; + } + if (it.has_right_vertical() && it.next_on_contour_quality == SegmentIntersection::LinkQuality::Invalid) { + SegmentIntersection& it2 = il.intersections[it.right_vertical()]; + assert(it2.right_vertical() == i_intersection); + it2.next_on_contour_quality = SegmentIntersection::LinkQuality::Invalid; + } + } + } + +#ifndef NDEBUG + // Validate the connectivity. + for (size_t i_vline = 0; i_vline + 1 < segs.size(); ++i_vline) { + const SegmentedIntersectionLine& il_left = segs[i_vline]; + const SegmentedIntersectionLine& il_right = segs[i_vline + 1]; + for (const SegmentIntersection& it : il_left.intersections) { + if (it.has_right_horizontal()) { + const SegmentIntersection& it_right = il_right.intersections[it.right_horizontal()]; + // For a right link there is a symmetric left link. + assert(it.iContour == it_right.iContour); + assert(it.type == it_right.type); + assert(it_right.has_left_horizontal()); + assert(it_right.left_horizontal() == int(&it - il_left.intersections.data())); + } + } + for (const SegmentIntersection& it : il_right.intersections) { + if (it.has_left_horizontal()) { + const SegmentIntersection& it_left = il_left.intersections[it.left_horizontal()]; + // For a right link there is a symmetric left link. + assert(it.iContour == it_left.iContour); + assert(it.type == it_left.type); + assert(it_left.has_right_horizontal()); + assert(it_left.right_horizontal() == int(&it - il_right.intersections.data())); + } + } + } + for (size_t i_vline = 0; i_vline < segs.size(); ++i_vline) { + const SegmentedIntersectionLine& il = segs[i_vline]; + for (const SegmentIntersection& it : il.intersections) { + auto i_it = int(&it - il.intersections.data()); + if (it.has_left_vertical_up()) { + assert(il.intersections[it.left_vertical_up()].left_vertical_down() == i_it); + assert(il.intersections[it.left_vertical_up()].prev_on_contour_quality == it.prev_on_contour_quality); + } + if (it.has_left_vertical_down()) { + assert(il.intersections[it.left_vertical_down()].left_vertical_up() == i_it); + assert(il.intersections[it.left_vertical_down()].prev_on_contour_quality == it.prev_on_contour_quality); + } + if (it.has_right_vertical_up()) { + assert(il.intersections[it.right_vertical_up()].right_vertical_down() == i_it); + assert(il.intersections[it.right_vertical_up()].next_on_contour_quality == it.next_on_contour_quality); + } + if (it.has_right_vertical_down()) { + assert(il.intersections[it.right_vertical_down()].right_vertical_up() == i_it); + assert(il.intersections[it.right_vertical_down()].next_on_contour_quality == it.next_on_contour_quality); + } + } + } +#endif /* NDEBUG */ +} + +// Find the last INNER_HIGH intersection starting with INNER_LOW, that is followed by OUTER_HIGH intersection. +// Such intersection shall always exist. +static const SegmentIntersection& end_of_vertical_run_raw(const SegmentIntersection& start) +{ + assert(start.type == SegmentIntersection::INNER_LOW); + // Step back to the beginning of the vertical segment to mark it as consumed. + auto* it = &start; + do { + ++it; + } while (it->type != SegmentIntersection::OUTER_HIGH); + if ((it - 1)->is_inner()) { + // Step back. + --it; + assert(it->type == SegmentIntersection::INNER_HIGH); + } + return *it; +} +static SegmentIntersection& end_of_vertical_run_raw(SegmentIntersection& start) +{ + return const_cast(end_of_vertical_run_raw(std::as_const(start))); +} + +// Find the last INNER_HIGH intersection starting with INNER_LOW, that is followed by OUTER_HIGH intersection, traversing vertical up contours if enabled. +// Such intersection shall always exist. +static const SegmentIntersection& end_of_vertical_run(const SegmentedIntersectionLine& il, const SegmentIntersection& start) +{ + assert(start.type == SegmentIntersection::INNER_LOW); + const SegmentIntersection* end = &end_of_vertical_run_raw(start); + assert(end->type == SegmentIntersection::INNER_HIGH); + for (;;) { + int up = end->vertical_up(); + if (up == -1 || (end->has_left_vertical_up() ? end->prev_on_contour_quality : end->next_on_contour_quality) != SegmentIntersection::LinkQuality::Valid) + break; + const SegmentIntersection& new_start = il.intersections[up]; + assert(end->iContour == new_start.iContour); + assert(new_start.type == SegmentIntersection::INNER_LOW); + end = &end_of_vertical_run_raw(new_start); + } + assert(end->type == SegmentIntersection::INNER_HIGH); + return *end; +} +static SegmentIntersection& end_of_vertical_run(SegmentedIntersectionLine& il, SegmentIntersection& start) +{ + return const_cast(end_of_vertical_run(std::as_const(il), std::as_const(start))); +} + +static void traverse_graph_generate_polylines( + const ExPolygonWithOffset& poly_with_offset, const FillParams& params, std::vector& segs, Polylines& polylines_out) +{ + // For each outer only chords, measure their maximum distance to the bow of the outer contour. + // Mark an outer only chord as consumed, if the distance is low. + for (size_t i_vline = 0; i_vline < segs.size(); ++i_vline) { + SegmentedIntersectionLine& vline = segs[i_vline]; + for (size_t i_intersection = 0; i_intersection + 1 < vline.intersections.size(); ++i_intersection) { + if (vline.intersections[i_intersection].type == SegmentIntersection::OUTER_LOW && + vline.intersections[i_intersection + 1].type == SegmentIntersection::OUTER_HIGH) { + bool consumed = false; + // if (params.full_infill()) { + // measure_outer_contour_slab(poly_with_offset, segs, i_vline, i_ntersection); + // } else + consumed = true; + vline.intersections[i_intersection].consumed_vertical_up = consumed; + } + } + } + + // Now construct a graph. + // Find the first point. + // Naively one would expect to achieve best results by chaining the paths by the shortest distance, + // but that procedure does not create the longest continuous paths. + // A simple "sweep left to right" procedure achieves better results. + int i_vline = 0; + int i_intersection = -1; + // Follow the line, connect the lines into a graph. + // Until no new line could be added to the output path: + Point pointLast; + Polyline* polyline_current = nullptr; + if (!polylines_out.empty()) + pointLast = polylines_out.back().points.back(); + for (;;) { + if (i_intersection == -1) { + // The path has been interrupted. Find a next starting point, closest to the previous extruder position. + coordf_t dist2min = std::numeric_limits().max(); + for (size_t i_vline2 = 0; i_vline2 < segs.size(); ++i_vline2) { + const SegmentedIntersectionLine& vline = segs[i_vline2]; + if (!vline.intersections.empty()) { + assert(vline.intersections.size() > 1); + // Even number of intersections with the loops. + assert((vline.intersections.size() & 1) == 0); + assert(vline.intersections.front().type == SegmentIntersection::OUTER_LOW); + for (size_t i = 0; i < vline.intersections.size(); ++i) { + const SegmentIntersection& intrsctn = vline.intersections[i]; + if (intrsctn.is_outer()) { + assert(intrsctn.is_low() || i > 0); + bool consumed = intrsctn.is_low() ? + intrsctn.consumed_vertical_up : + vline.intersections[i - 1].consumed_vertical_up; + if (!consumed) { + coordf_t dist2 = sqr(coordf_t(pointLast(0) - vline.pos)) + sqr(coordf_t(pointLast(1) - intrsctn.pos())); + if (dist2 < dist2min) { + dist2min = dist2; + i_vline = int(i_vline2); + i_intersection = int(i); + //FIXME We are taking the first left point always. Verify, that the caller chains the paths + // by a shortest distance, while reversing the paths if needed. + //if (polylines_out.empty()) + // Initial state, take the first line, which is the first from the left. + goto found; + } + } + } + } + } + } + if (i_intersection == -1) + // We are finished. + break; + found: + // Start a new path. + polylines_out.push_back(Polyline()); + polyline_current = &polylines_out.back(); + // Emit the first point of a path. + pointLast = Point(segs[i_vline].pos, segs[i_vline].intersections[i_intersection].pos()); + polyline_current->points.push_back(pointLast); + } + + // From the initial point (i_vline, i_intersection), follow a path. + SegmentedIntersectionLine& vline = segs[i_vline]; + SegmentIntersection* it = &vline.intersections[i_intersection]; + bool going_up = it->is_low(); + bool try_connect = false; + if (going_up) { + assert(!it->consumed_vertical_up); + assert(i_intersection + 1 < vline.intersections.size()); + // Step back to the beginning of the vertical segment to mark it as consumed. + if (it->is_inner()) { + assert(i_intersection > 0); + --it; + --i_intersection; + } + // Consume the complete vertical segment up to the outer contour. + do { + it->consumed_vertical_up = true; + ++it; + ++i_intersection; + assert(i_intersection < vline.intersections.size()); + } while (it->type != SegmentIntersection::OUTER_HIGH); + if ((it - 1)->is_inner()) { + // Step back. + --it; + --i_intersection; + assert(it->type == SegmentIntersection::INNER_HIGH); + try_connect = true; + } + } else { + // Going down. + assert(it->is_high()); + assert(i_intersection > 0); + assert(!(it - 1)->consumed_vertical_up); + // Consume the complete vertical segment up to the outer contour. + if (it->is_inner()) + it->consumed_vertical_up = true; + do { + assert(i_intersection > 0); + --it; + --i_intersection; + it->consumed_vertical_up = true; + } while (it->type != SegmentIntersection::OUTER_LOW); + if ((it + 1)->is_inner()) { + // Step back. + ++it; + ++i_intersection; + assert(it->type == SegmentIntersection::INNER_LOW); + try_connect = true; + } + } + if (try_connect) { + // Decide, whether to finish the segment, or whether to follow the perimeter. + // 1) Find possible connection points on the previous / next vertical line. + int i_prev = it->left_horizontal(); + int i_next = it->right_horizontal(); + bool intersection_prev_valid = intersection_on_prev_vertical_line_valid(segs, i_vline, i_intersection); + bool intersection_next_valid = intersection_on_next_vertical_line_valid(segs, i_vline, i_intersection); + bool intersection_horizontal_valid = intersection_prev_valid || intersection_next_valid; + // Mark both the left and right connecting segment as consumed, because one cannot go to this intersection point as it has been consumed. + if (i_prev != -1) + segs[i_vline - 1].intersections[i_prev].consumed_perimeter_right = true; + if (i_next != -1) + it->consumed_perimeter_right = true; + + // Try to connect to a previous or next vertical line, making a zig-zag pattern. + if (intersection_horizontal_valid) { + // A horizontal connection along the perimeter line exists. + assert(it->is_inner()); + bool take_next = intersection_next_valid; + if (intersection_prev_valid && intersection_next_valid) { + // Take the shorter segment. This greedy heuristics may not be the best. + coordf_t dist_prev = measure_perimeter_horizontal_segment_length(poly_with_offset, segs, i_vline - 1, i_prev, i_intersection); + coordf_t dist_next = measure_perimeter_horizontal_segment_length(poly_with_offset, segs, i_vline, i_intersection, i_next); + take_next = dist_next < dist_prev; + } + polyline_current->points.emplace_back(vline.pos, it->pos()); + emit_perimeter_prev_next_segment(poly_with_offset, segs, i_vline, it->iContour, i_intersection, take_next ? i_next : i_prev, *polyline_current, take_next); + //FIXME consume the left / right connecting segments at the other end of this line? Currently it is not critical because a perimeter segment is not followed if the vertical segment at the other side has already been consumed. + // Advance to the neighbor line. + if (take_next) { + ++i_vline; + i_intersection = i_next; + } else { + --i_vline; + i_intersection = i_prev; + } + continue; + } + + // Try to connect to a previous or next point on the same vertical line. + int i_vertical = it->vertical_outside(); + auto vertical_link_quality = (i_vertical == -1 || vline.intersections[i_vertical + (going_up ? 0 : -1)].consumed_vertical_up) ? + SegmentIntersection::LinkQuality::Invalid : it->vertical_outside_quality(); +#if 0 + if (vertical_link_quality == SegmentIntersection::LinkQuality::Valid || + // Follow the link if there is no horizontal link available. + (!intersection_horizontal_valid && vertical_link_quality != SegmentIntersection::LinkQuality::Invalid)) { +#else + if (vertical_link_quality != SegmentIntersection::LinkQuality::Invalid) { +#endif + assert(it->iContour == vline.intersections[i_vertical].iContour); + polyline_current->points.emplace_back(vline.pos, it->pos()); + if (vertical_link_quality == SegmentIntersection::LinkQuality::Valid) + // Consume the connecting contour and the next segment. + emit_perimeter_segment_on_vertical_line(poly_with_offset, segs, i_vline, it->iContour, i_intersection, i_vertical, + *polyline_current, going_up ? it->has_left_vertical_up() : it->has_right_vertical_down()); + else { + // Just skip the connecting contour and start a new path. + polylines_out.emplace_back(); + polyline_current = &polylines_out.back(); + polyline_current->points.emplace_back(vline.pos, vline.intersections[i_vertical].pos()); + } + // Mark both the left and right connecting segment as consumed, because one cannot go to this intersection point as it has been consumed. + // If there are any outer intersection points skipped (bypassed) by the contour, + // mark them as processed. + if (going_up) + for (int i = i_intersection; i < i_vertical; ++i) + vline.intersections[i].consumed_vertical_up = true; + else + for (int i = i_vertical; i < i_intersection; ++i) + vline.intersections[i].consumed_vertical_up = true; + // seg.intersections[going_up ? i_intersection : i_intersection - 1].consumed_vertical_up = true; + it->consumed_perimeter_right = true; + (going_up ? ++it : --it)->consumed_perimeter_right = true; + i_intersection = i_vertical; + continue; + } + + // No way to continue the current polyline. Take the rest of the line up to the outer contour. + // This will finish the polyline, starting another polyline at a new point. + going_up ? ++it : --it; + } + + // Finish the current vertical line, + // reset the current vertical line to pick a new starting point in the next round. + assert(it->is_outer()); + assert(it->is_high() == going_up); + pointLast = Point(vline.pos, it->pos()); + polyline_current->points.emplace_back(pointLast); + // Handle duplicate points and zero length segments. + polyline_current->remove_duplicate_points(); + assert(!polyline_current->has_duplicate_points()); + // Handle nearly zero length edges. + if (polyline_current->points.size() <= 1 || + (polyline_current->points.size() == 2 && + std::abs(polyline_current->points.front()(0) - polyline_current->points.back()(0)) < SCALED_EPSILON && + std::abs(polyline_current->points.front()(1) - polyline_current->points.back()(1)) < SCALED_EPSILON)) + { + polylines_out.pop_back(); + } + it = nullptr; + i_intersection = -1; + polyline_current = nullptr; + } +} + +struct MonotonousRegion +{ + struct Boundary { + int vline; + int low; + int high; + }; + + Boundary left; + Boundary right; + + // Length when starting at left.low + float len1{ 0.f }; + // Length when starting at left.high + float len2{ 0.f }; + // If true, then when starting at left.low, then ending at right.high and vice versa. + // If false, then ending at the same side as starting. + bool flips{ false }; + + float length(bool region_flipped) const { return region_flipped ? len2 : len1; } + int left_intersection_point(bool region_flipped) const { return region_flipped ? left.high : left.low; } + int right_intersection_point(bool region_flipped) const { return (region_flipped == flips) ? right.low : right.high; } + +#if NDEBUG + // Left regions are used to track whether all regions left to this one have already been printed. + boost::container::small_vector left_neighbors; + // Right regions are held to pick a next region to be extruded using the "Ant colony" heuristics. + boost::container::small_vector right_neighbors; +#else + // For debugging, use the normal vector as it is better supported by debug visualizers. + std::vector left_neighbors; + std::vector right_neighbors; +#endif +}; + +struct AntPath +{ + float length{ -1. }; // Length of the link to the next region. + float visibility{ -1. }; // 1 / length. Which length, just to the next region, or including the path accross the region? + float pheromone{ 0 }; // <0, 1> +}; + +struct MonotonousRegionLink +{ + MonotonousRegion* region; + bool flipped; + // Distance of right side of this region to left side of the next region, if the "flipped" flag of this region and the next region + // is applied as defined. + AntPath* next; + // Distance of right side of this region to left side of the next region, if the "flipped" flag of this region and the next region + // is applied in reverse order as if the zig-zags were flipped. + AntPath* next_flipped; +}; + +// Matrix of paths (AntPath) connecting ends of MontonousRegions. +// AntPath lengths and their derived visibilities refer to the length of the perimeter line if such perimeter segment exists. +class AntPathMatrix +{ +public: + AntPathMatrix( + const std::vector& regions, + const ExPolygonWithOffset& poly_with_offset, + const std::vector& segs, + const float initial_pheromone) : + m_regions(regions), + m_poly_with_offset(poly_with_offset), + m_segs(segs), + // From end of one region to the start of another region, both flipped or not flipped. + m_matrix(regions.size()* regions.size() * 4, AntPath{ -1., -1., initial_pheromone }) {} + + void update_inital_pheromone(float initial_pheromone) + { + for (AntPath& ap : m_matrix) + ap.pheromone = initial_pheromone; + } + + AntPath& operator()(const MonotonousRegion& region_from, bool flipped_from, const MonotonousRegion& region_to, bool flipped_to) + { + int row = 2 * int(®ion_from - m_regions.data()) + flipped_from; + int col = 2 * int(®ion_to - m_regions.data()) + flipped_to; + AntPath& path = m_matrix[row * m_regions.size() * 2 + col]; + if (path.length == -1.) { + // This path is accessed for the first time. Update the length and cost. + int i_from = region_from.right_intersection_point(flipped_from); + int i_to = region_to.left_intersection_point(flipped_to); + const SegmentedIntersectionLine& vline_from = m_segs[region_from.right.vline]; + const SegmentedIntersectionLine& vline_to = m_segs[region_to.left.vline]; + if (region_from.right.vline + 1 == region_from.left.vline) { + int i_right = vline_from.intersections[i_from].right_horizontal(); + if (i_right == i_to && vline_from.intersections[i_from].next_on_contour_quality == SegmentIntersection::LinkQuality::Valid) { + // Measure length along the contour. + path.length = unscale(measure_perimeter_horizontal_segment_length(m_poly_with_offset, m_segs, region_from.right.vline, i_from, i_to)); + } + } + if (path.length == -1.) { + // Just apply the Eucledian distance of the end points. + path.length = unscale(Vec2f(vline_to.pos - vline_from.pos, vline_to.intersections[i_to].pos() - vline_from.intersections[i_from].pos()).norm()); + } + path.visibility = 1.f / (path.length + float(EPSILON)); + } + return path; + } + + AntPath& operator()(const MonotonousRegionLink& region_from, const MonotonousRegion& region_to, bool flipped_to) + { + return (*this)(*region_from.region, region_from.flipped, region_to, flipped_to); + } + AntPath& operator()(const MonotonousRegion& region_from, bool flipped_from, const MonotonousRegionLink& region_to) + { + return (*this)(region_from, flipped_from, *region_to.region, region_to.flipped); + } + AntPath& operator()(const MonotonousRegionLink& region_from, const MonotonousRegionLink& region_to) + { + return (*this)(*region_from.region, region_from.flipped, *region_to.region, region_to.flipped); + } + +private: + // Source regions, used for addressing and updating m_matrix. + const std::vector& m_regions; + // To calculate the intersection points and contour lengths. + const ExPolygonWithOffset& m_poly_with_offset; + const std::vector& m_segs; + // From end of one region to the start of another region, both flipped or not flipped. + //FIXME one may possibly use sparse representation of the matrix, likely using hashing. + std::vector m_matrix; +}; + +static const SegmentIntersection& vertical_run_bottom(const SegmentedIntersectionLine & vline, const SegmentIntersection & start) +{ + assert(start.is_inner()); + const SegmentIntersection* it = &start; + // Find the lowest SegmentIntersection::INNER_LOW starting with right. + for (;;) { + while (it->type != SegmentIntersection::INNER_LOW) + --it; + if ((it - 1)->type == SegmentIntersection::INNER_HIGH) + --it; + else { + int down = it->vertical_down(); + if (down == -1 || it->vertical_down_quality() != SegmentIntersection::LinkQuality::Valid) + break; + it = &vline.intersections[down]; + assert(it->type == SegmentIntersection::INNER_HIGH); + } + } + return *it; +} + +static SegmentIntersection& vertical_run_bottom(SegmentedIntersectionLine & vline, SegmentIntersection & start) +{ + return const_cast(vertical_run_bottom(std::as_const(vline), std::as_const(start))); +} + +static const SegmentIntersection& vertical_run_top(const SegmentedIntersectionLine & vline, const SegmentIntersection & start) +{ + assert(start.is_inner()); + const SegmentIntersection* it = &start; + // Find the lowest SegmentIntersection::INNER_LOW starting with right. + for (;;) { + while (it->type != SegmentIntersection::INNER_HIGH) + ++it; + if ((it + 1)->type == SegmentIntersection::INNER_LOW) + ++it; + else { + int up = it->vertical_up(); + if (up == -1 || it->vertical_up_quality() != SegmentIntersection::LinkQuality::Valid) + break; + it = &vline.intersections[up]; + assert(it->type == SegmentIntersection::INNER_LOW); + } + } + return *it; +} + +static SegmentIntersection& vertical_run_top(SegmentedIntersectionLine & vline, SegmentIntersection & start) +{ + return const_cast(vertical_run_top(std::as_const(vline), std::as_const(start))); +} + +static SegmentIntersection* overlap_bottom(SegmentIntersection & start, SegmentIntersection & end, SegmentedIntersectionLine & vline_this, SegmentedIntersectionLine & vline_other, SegmentIntersection::Side side) +{ + SegmentIntersection* other = nullptr; + assert(start.is_inner()); + assert(end.is_inner()); + const SegmentIntersection* it = &start; + for (;;) { + if (it->is_inner()) { + int i = it->horizontal(side); + if (i != -1) { + other = &vline_other.intersections[i]; + break; + } + if (it == &end) + break; + } + if (it->type != SegmentIntersection::INNER_HIGH) + ++it; + else if ((it + 1)->type == SegmentIntersection::INNER_LOW) + ++it; + else { + int up = it->vertical_up(); + if (up == -1 || it->vertical_up_quality() != SegmentIntersection::LinkQuality::Valid) + break; + it = &vline_this.intersections[up]; + assert(it->type == SegmentIntersection::INNER_LOW); + } + } + return other == nullptr ? nullptr : &vertical_run_bottom(vline_other, *other); +} + +static SegmentIntersection* overlap_top(SegmentIntersection & start, SegmentIntersection & end, SegmentedIntersectionLine & vline_this, SegmentedIntersectionLine & vline_other, SegmentIntersection::Side side) +{ + SegmentIntersection* other = nullptr; + assert(start.is_inner()); + assert(end.is_inner()); + const SegmentIntersection* it = &end; + for (;;) { + if (it->is_inner()) { + int i = it->horizontal(side); + if (i != -1) { + other = &vline_other.intersections[i]; + break; + } + if (it == &start) + break; + } + if (it->type != SegmentIntersection::INNER_LOW) + --it; + else if ((it - 1)->type == SegmentIntersection::INNER_HIGH) + --it; + else { + int down = it->vertical_down(); + if (down == -1 || it->vertical_down_quality() != SegmentIntersection::LinkQuality::Valid) + break; + it = &vline_this.intersections[down]; + assert(it->type == SegmentIntersection::INNER_HIGH); + } + } + return other == nullptr ? nullptr : &vertical_run_top(vline_other, *other); +} + +static std::pair left_overlap(SegmentIntersection & start, SegmentIntersection & end, SegmentedIntersectionLine & vline_this, SegmentedIntersectionLine & vline_left) +{ + std::pair out(nullptr, nullptr); + out.first = overlap_bottom(start, end, vline_this, vline_left, SegmentIntersection::Side::Left); + if (out.first != nullptr) + out.second = overlap_top(start, end, vline_this, vline_left, SegmentIntersection::Side::Left); + assert((out.first == nullptr && out.second == nullptr) || out.first < out.second); + return out; +} + +static std::pair left_overlap(std::pair & start_end, SegmentedIntersectionLine & vline_this, SegmentedIntersectionLine & vline_left) +{ + assert((start_end.first == nullptr) == (start_end.second == nullptr)); + return start_end.first == nullptr ? start_end : left_overlap(*start_end.first, *start_end.second, vline_this, vline_left); +} + +static std::pair right_overlap(SegmentIntersection & start, SegmentIntersection & end, SegmentedIntersectionLine & vline_this, SegmentedIntersectionLine & vline_right) +{ + std::pair out(nullptr, nullptr); + out.first = overlap_bottom(start, end, vline_this, vline_right, SegmentIntersection::Side::Right); + if (out.first != nullptr) + out.second = overlap_top(start, end, vline_this, vline_right, SegmentIntersection::Side::Right); + assert((out.first == nullptr && out.second == nullptr) || out.first < out.second); + return out; +} + +static std::pair right_overlap(std::pair & start_end, SegmentedIntersectionLine & vline_this, SegmentedIntersectionLine & vline_right) +{ + assert((start_end.first == nullptr) == (start_end.second == nullptr)); + return start_end.first == nullptr ? start_end : right_overlap(*start_end.first, *start_end.second, vline_this, vline_right); +} + +static std::vector generate_montonous_regions(std::vector & segs) +{ + std::vector monotonous_regions; + +#ifndef NDEBUG +#define SLIC3R_DEBUG_MONOTONOUS_REGIONS +#endif + +#ifdef SLIC3R_DEBUG_MONOTONOUS_REGIONS + std::vector>> consumed(segs.size()); + auto test_overlap = [&consumed](int segment, int low, int high) { + for (const std::pair& interval : consumed[segment]) + if ((low >= interval.first && low <= interval.second) || + (interval.first >= low && interval.first <= high)) + return true; + consumed[segment].emplace_back(low, high); + return false; + }; +#else + auto test_overlap = [](int, int, int) { return false; }; +#endif + + for (size_t i_vline_seed = 0; i_vline_seed < segs.size(); ++i_vline_seed) { + SegmentedIntersectionLine& vline_seed = segs[i_vline_seed]; + for (size_t i_intersection_seed = 1; i_intersection_seed + 1 < vline_seed.intersections.size(); ) { + while (i_intersection_seed < vline_seed.intersections.size() && + vline_seed.intersections[i_intersection_seed].type != SegmentIntersection::INNER_LOW) + ++i_intersection_seed; + if (i_intersection_seed == vline_seed.intersections.size()) + break; + SegmentIntersection* start = &vline_seed.intersections[i_intersection_seed]; + SegmentIntersection* end = &end_of_vertical_run(vline_seed, *start); + if (!start->consumed_vertical_up) { + // Draw a new monotonous region starting with this segment. + // while there is only a single right neighbor + size_t i_vline = i_vline_seed; + std::pair left(start, end); + MonotonousRegion region; + region.left.vline = int(i_vline); + region.left.low = int(left.first - vline_seed.intersections.data()); + region.left.high = int(left.second - vline_seed.intersections.data()); + region.right = region.left; + assert(!test_overlap(region.left.vline, region.left.low, region.left.high)); + start->consumed_vertical_up = true; + int num_lines = 1; + while (++i_vline < segs.size()) { + SegmentedIntersectionLine& vline_left = segs[i_vline - 1]; + SegmentedIntersectionLine& vline_right = segs[i_vline]; + std::pair right = right_overlap(left, vline_left, vline_right); + if (right.first == nullptr) + // No neighbor at the right side of the current segment. + break; + SegmentIntersection* right_top_first = &vertical_run_top(vline_right, *right.first); + if (right_top_first != right.second) + // This segment overlaps with multiple segments at its right side. + break; + std::pair right_left = left_overlap(right, vline_right, vline_left); + if (left != right_left) + // Left & right draws don't overlap exclusively, right neighbor segment overlaps with multiple segments at its left. + break; + region.right.vline = int(i_vline); + region.right.low = int(right.first - vline_right.intersections.data()); + region.right.high = int(right.second - vline_right.intersections.data()); + right.first->consumed_vertical_up = true; + assert(!test_overlap(region.right.vline, region.right.low, region.right.high)); + ++num_lines; + left = right; + } + // Even number of lines makes the infill zig-zag to exit on the other side of the region than where it starts. + region.flips = (num_lines & 1) != 0; + monotonous_regions.emplace_back(region); + } + i_intersection_seed = int(end - vline_seed.intersections.data()) + 1; + } + } + + return monotonous_regions; +} + +// Traverse path, calculate length of the draw for the purpose of optimization. +// This function is very similar to polylines_from_paths() in the way how it traverses the path, but +// polylines_from_paths() emits a path, while this function just calculates the path length. +static float montonous_region_path_length(const MonotonousRegion& region, bool dir, const ExPolygonWithOffset& poly_with_offset, const std::vector& segs) +{ + // From the initial point (i_vline, i_intersection), follow a path. + int i_intersection = region.left_intersection_point(dir); + int i_vline = region.left.vline; + float total_length = 0.; + bool no_perimeter = false; + Vec2f last_point; + + for (;;) { + const SegmentedIntersectionLine& vline = segs[i_vline]; + const SegmentIntersection* it = &vline.intersections[i_intersection]; + const bool going_up = it->is_low(); + + if (no_perimeter) + total_length += (last_point - Vec2f(vline.pos, (it + (going_up ? -1 : 1))->pos())).norm(); + + int iright = it->right_horizontal(); + if (going_up) { + // Traverse the complete vertical segment up to the inner contour. + for (;;) { + do { + ++it; + iright = std::max(iright, it->right_horizontal()); + assert(it->is_inner()); + } while (it->type != SegmentIntersection::INNER_HIGH || (it + 1)->type != SegmentIntersection::OUTER_HIGH); + int inext = it->vertical_up(); + if (inext == -1 || it->vertical_up_quality() != SegmentIntersection::LinkQuality::Valid) + break; + assert(it->iContour == vline.intersections[inext].iContour); + it = vline.intersections.data() + inext; + } + } else { + // Going down. + assert(it->is_high()); + assert(i_intersection > 0); + for (;;) { + do { + --it; + if (int iright_new = it->right_horizontal(); iright_new != -1) + iright = iright_new; + assert(it->is_inner()); + } while (it->type != SegmentIntersection::INNER_LOW || (it - 1)->type != SegmentIntersection::OUTER_LOW); + int inext = it->vertical_down(); + if (inext == -1 || it->vertical_down_quality() != SegmentIntersection::LinkQuality::Valid) + break; + assert(it->iContour == vline.intersections[inext].iContour); + it = vline.intersections.data() + inext; + } + } + + if (i_vline == region.right.vline) + break; + + int inext = it->right_horizontal(); + if (inext != -1 && it->next_on_contour_quality == SegmentIntersection::LinkQuality::Valid) { + // Summarize length of the connection line along the perimeter. + //FIXME should it be weighted with a lower weight than non-extruding connection line? What weight? + // Taking half of the length. + total_length += 0.5f * float(measure_perimeter_horizontal_segment_length(poly_with_offset, segs, i_vline, it - vline.intersections.data(), inext)); + // Don't add distance to the next vertical line start to the total length. + no_perimeter = false; + i_intersection = inext; + } else { + // Finish the current vertical line, + going_up ? ++it : --it; + assert(it->is_outer()); + assert(it->is_high() == going_up); + // Mark the end of this vertical line. + last_point = Vec2f(vline.pos, it->pos()); + // Remember to add distance to the last point. + no_perimeter = true; + if (inext == -1) { + // Find the end of the next overlapping vertical segment. + const SegmentedIntersectionLine& vline_right = segs[i_vline + 1]; + const SegmentIntersection* right = going_up ? + &vertical_run_top(vline_right, vline_right.intersections[iright]) : &vertical_run_bottom(vline_right, vline_right.intersections[iright]); + i_intersection = int(right - vline_right.intersections.data()); + } else + i_intersection = inext; + } + + ++i_vline; + } + + return unscale(total_length); +} + +static void connect_monotonous_regions(std::vector& regions, const ExPolygonWithOffset& poly_with_offset, std::vector& segs) +{ + // Map from low intersection to left / right side of a monotonous region. + using MapType = std::pair; + std::vector map_intersection_to_region_start; + std::vector map_intersection_to_region_end; + map_intersection_to_region_start.reserve(regions.size()); + map_intersection_to_region_end.reserve(regions.size()); + for (MonotonousRegion& region : regions) { + map_intersection_to_region_start.emplace_back(&segs[region.left.vline].intersections[region.left.low], ®ion); + map_intersection_to_region_end.emplace_back(&segs[region.right.vline].intersections[region.right.low], ®ion); + } + auto intersections_lower = [](const MapType& l, const MapType& r) { return l.first < r.first; }; + auto intersections_equal = [](const MapType& l, const MapType& r) { return l.first == r.first; }; + std::sort(map_intersection_to_region_start.begin(), map_intersection_to_region_start.end(), intersections_lower); + std::sort(map_intersection_to_region_end.begin(), map_intersection_to_region_end.end(), intersections_lower); + + // Scatter links to neighboring regions. + for (MonotonousRegion& region : regions) { + if (region.left.vline > 0) { + auto& vline = segs[region.left.vline]; + auto& vline_left = segs[region.left.vline - 1]; + auto [lbegin, lend] = left_overlap(vline.intersections[region.left.low], vline.intersections[region.left.high], vline, vline_left); + if (lbegin != nullptr) { + for (;;) { + MapType key(lbegin, nullptr); + auto it = std::lower_bound(map_intersection_to_region_end.begin(), map_intersection_to_region_end.end(), key); + assert(it != map_intersection_to_region_end.end() && it->first == key.first); + it->second->right_neighbors.emplace_back(®ion); + SegmentIntersection* lnext = &vertical_run_top(vline_left, *lbegin); + if (lnext == lend) + break; + while (lnext->type != SegmentIntersection::INNER_LOW) + ++lnext; + lbegin = lnext; + } + } + } + if (region.right.vline + 1 < int(segs.size())) { + auto& vline = segs[region.right.vline]; + auto& vline_right = segs[region.right.vline + 1]; + auto [rbegin, rend] = right_overlap(vline.intersections[region.right.low], vline.intersections[region.right.high], vline, vline_right); + if (rbegin != nullptr) { + for (;;) { + MapType key(rbegin, nullptr); + auto it = std::lower_bound(map_intersection_to_region_start.begin(), map_intersection_to_region_start.end(), key); + assert(it != map_intersection_to_region_start.end() && it->first == key.first); + it->second->left_neighbors.emplace_back(®ion); + SegmentIntersection* rnext = &vertical_run_top(vline_right, *rbegin); + if (rnext == rend) + break; + while (rnext->type != SegmentIntersection::INNER_LOW) + ++rnext; + rbegin = rnext; + } + } + } + } + + // Sometimes a segment may indicate that it connects to a segment on the other side while the other does not. + // This may be a valid case if one side contains runs of OUTER_LOW, INNER_LOW, {INNER_HIGH, INNER_LOW}*, INNER_HIGH, OUTER_HIGH, + // where the part in the middle does not connect to the other side, but it will be extruded through. + for (MonotonousRegion& region : regions) { + std::sort(region.left_neighbors.begin(), region.left_neighbors.end()); + std::sort(region.right_neighbors.begin(), region.right_neighbors.end()); + } + for (MonotonousRegion& region : regions) { + for (MonotonousRegion* neighbor : region.left_neighbors) { + auto it = std::lower_bound(neighbor->right_neighbors.begin(), neighbor->right_neighbors.end(), ®ion); + if (it == neighbor->right_neighbors.end() || *it != ®ion) + neighbor->right_neighbors.insert(it, ®ion); + } + for (MonotonousRegion* neighbor : region.right_neighbors) { + auto it = std::lower_bound(neighbor->left_neighbors.begin(), neighbor->left_neighbors.end(), ®ion); + if (it == neighbor->left_neighbors.end() || *it != ®ion) + neighbor->left_neighbors.insert(it, ®ion); + } + } + +#ifndef NDEBUG + // Verify symmetry of the left_neighbors / right_neighbors. + for (MonotonousRegion& region : regions) { + for (MonotonousRegion* neighbor : region.left_neighbors) { + assert(std::count(region.left_neighbors.begin(), region.left_neighbors.end(), neighbor) == 1); + assert(std::find(neighbor->right_neighbors.begin(), neighbor->right_neighbors.end(), ®ion) != neighbor->right_neighbors.end()); + } + for (MonotonousRegion* neighbor : region.right_neighbors) { + assert(std::count(region.right_neighbors.begin(), region.right_neighbors.end(), neighbor) == 1); + assert(std::find(neighbor->left_neighbors.begin(), neighbor->left_neighbors.end(), ®ion) != neighbor->left_neighbors.end()); + } + } +#endif /* NDEBUG */ + + // Fill in sum length of connecting lines of a region. This length is used for optimizing the infill path for minimum length. + for (MonotonousRegion& region : regions) { + region.len1 = montonous_region_path_length(region, false, poly_with_offset, segs); + region.len2 = montonous_region_path_length(region, true, poly_with_offset, segs); + // Subtract the smaller length from the longer one, so we will optimize just with the positive difference of the two. + if (region.len1 > region.len2) { + region.len1 -= region.len2; + region.len2 = 0; + } else { + region.len2 -= region.len1; + region.len1 = 0; + } + } +} + +// Raad Salman: Algorithms for the Precedence Constrained Generalized Travelling Salesperson Problem +// https://www.chalmers.se/en/departments/math/research/research-groups/optimization/OptimizationMasterTheses/MScThesis-RaadSalman-final.pdf +// Algorithm 6.1 Lexicographic Path Preserving 3-opt +// Optimize path while maintaining the ordering constraints. +void monotonous_3_opt(std::vector & path, const std::vector & segs) +{ + // When doing the 3-opt path preserving flips, one has to fulfill two constraints: + // + // 1) The new path should be shorter than the old path. + // 2) The precedence constraints shall be satisified on the new path. + // + // Branch & bound with KD-tree may be used with the shorter path constraint, but the precedence constraint will have to be recalculated for each + // shorter path candidate found, which has a quadratic cost for a dense precedence graph. For a sparse precedence graph the precedence + // constraint verification will be cheaper. + // + // On the other side, if the full search space is traversed as in the diploma thesis by Raad Salman (page 24, Algorithm 6.1 Lexicographic Path Preserving 3-opt), + // then the precedence constraint verification is amortized inside the O(n^3) loop. Now which is better for our task? + // + // It is beneficial to also try flipping of the infill zig-zags, for which a prefix sum of both flipped and non-flipped paths over + // MonotonousRegionLinks may be utilized, however updating the prefix sum has a linear complexity, the same complexity as doing the 3-opt + // exchange by copying the pieces. +} + +// #define SLIC3R_DEBUG_ANTS + +template +inline void print_ant(const std::string & fmt, TArgs &&... args) { +#ifdef SLIC3R_DEBUG_ANTS + std::cout << Slic3r::format(fmt, std::forward(args)...) << std::endl; +#endif +} + +// Find a run through monotonous infill blocks using an 'Ant colony" optimization method. +// http://www.scholarpedia.org/article/Ant_colony_optimization +static std::vector chain_monotonous_regions( + std::vector & regions, const ExPolygonWithOffset & poly_with_offset, const std::vector & segs, std::mt19937_64 & rng) +{ + // Number of left neighbors (regions that this region depends on, this region cannot be printed before the regions left of it are printed) + self. + std::vector left_neighbors_unprocessed(regions.size(), 1); + // Queue of regions, which have their left neighbors already printed. + std::vector queue; + queue.reserve(regions.size()); + for (MonotonousRegion& region : regions) + if (region.left_neighbors.empty()) + queue.emplace_back(®ion); + else + left_neighbors_unprocessed[®ion - regions.data()] += int(region.left_neighbors.size()); + // Make copy of structures that need to be initialized at each ant iteration. + auto left_neighbors_unprocessed_initial = left_neighbors_unprocessed; + auto queue_initial = queue; + + std::vector path, best_path; + path.reserve(regions.size()); + best_path.reserve(regions.size()); + float best_path_length = std::numeric_limits::max(); + + struct NextCandidate { + MonotonousRegion* region; + AntPath* link; + AntPath* link_flipped; + float probability; + bool dir; + }; + std::vector next_candidates; + + auto validate_unprocessed = +#ifdef NDEBUG + []() { return true; }; +#else + [®ions, &left_neighbors_unprocessed, &path, &queue]() { + std::vector regions_processed(regions.size(), false); + std::vector regions_in_queue(regions.size(), false); + for (const MonotonousRegion* region : queue) { + // This region is not processed yet, his predecessors are processed. + assert(left_neighbors_unprocessed[region - regions.data()] == 1); + regions_in_queue[region - regions.data()] = true; + } + for (const MonotonousRegionLink& link : path) { + assert(left_neighbors_unprocessed[link.region - regions.data()] == 0); + regions_processed[link.region - regions.data()] = true; + } + for (size_t i = 0; i < regions_processed.size(); ++i) { + assert(!regions_processed[i] || !regions_in_queue[i]); + const MonotonousRegion& region = regions[i]; + if (regions_processed[i] || regions_in_queue[i]) { + assert(left_neighbors_unprocessed[i] == (regions_in_queue[i] ? 1 : 0)); + // All left neighbors should be processed already. + for (const MonotonousRegion* left : region.left_neighbors) { + assert(regions_processed[left - regions.data()]); + assert(left_neighbors_unprocessed[left - regions.data()] == 0); + } + } else { + // Some left neihgbor should not be processed yet. + assert(left_neighbors_unprocessed[i] > 1); + size_t num_predecessors_unprocessed = 0; + bool has_left_last_on_path = false; + for (const MonotonousRegion* left : region.left_neighbors) { + size_t iprev = left - regions.data(); + if (regions_processed[iprev]) { + assert(left_neighbors_unprocessed[iprev] == 0); + if (left == path.back().region) { + // This region should actually be on queue, but to optimize the queue management + // this item will be processed in the next round by traversing path.back().region->right_neighbors before processing the queue. + assert(!has_left_last_on_path); + has_left_last_on_path = true; + ++num_predecessors_unprocessed; + } + } else { + if (regions_in_queue[iprev]) + assert(left_neighbors_unprocessed[iprev] == 1); + else + assert(left_neighbors_unprocessed[iprev] > 1); + ++num_predecessors_unprocessed; + } + } + assert(num_predecessors_unprocessed > 0); + assert(left_neighbors_unprocessed[i] == num_predecessors_unprocessed + 1); + } + } + return true; + }; +#endif /* NDEBUG */ + + // How many times to repeat the ant simulation. + constexpr int num_rounds = 25; + // After how many rounds without an improvement to exit? + constexpr int num_rounds_no_change_exit = 8; + // With how many ants each of the run will be performed? + const int num_ants = std::min(regions.size(), 10); + // Base (initial) pheromone level. This value will be adjusted based on the length of the first greedy path found. + float pheromone_initial_deposit = 0.5f; + // Evaporation rate of pheromones. + constexpr float pheromone_evaporation = 0.1f; + // Evaporation rate to diversify paths taken by individual ants. + constexpr float pheromone_diversification = 0.1f; + // Probability at which to take the next best path. Otherwise take the the path based on the cost distribution. + constexpr float probability_take_best = 0.9f; + // Exponents of the cost function. + constexpr float pheromone_alpha = 1.f; // pheromone exponent + constexpr float pheromone_beta = 2.f; // attractiveness weighted towards edge length + + AntPathMatrix path_matrix(regions, poly_with_offset, segs, pheromone_initial_deposit); + + // Find an initial path in a greedy way, set the initial pheromone value to 10% of the cost of the greedy path. + { + // Construct the first path in a greedy way to calculate an initial value of the pheromone value. + queue = queue_initial; + left_neighbors_unprocessed = left_neighbors_unprocessed_initial; + assert(validate_unprocessed()); + // Pick the last of the queue. + MonotonousRegionLink path_end{ queue.back(), false }; + queue.pop_back(); + --left_neighbors_unprocessed[path_end.region - regions.data()]; + + float total_length = path_end.region->length(false); + while (!queue.empty() || !path_end.region->right_neighbors.empty()) { + // Chain. + MonotonousRegion& region = *path_end.region; + bool dir = path_end.flipped; + NextCandidate next_candidate; + next_candidate.probability = 0; + for (MonotonousRegion* next : region.right_neighbors) { + int& unprocessed = left_neighbors_unprocessed[next - regions.data()]; + assert(unprocessed > 1); + if (left_neighbors_unprocessed[next - regions.data()] == 2) { + // Dependencies of the successive blocks are satisfied. + AntPath& path1 = path_matrix(region, dir, *next, false); + AntPath& path2 = path_matrix(region, dir, *next, true); + if (path1.visibility > next_candidate.probability) + next_candidate = { next, &path1, &path1, path1.visibility, false }; + if (path2.visibility > next_candidate.probability) + next_candidate = { next, &path2, &path2, path2.visibility, true }; + } + } + bool from_queue = next_candidate.probability == 0; + if (from_queue) { + for (MonotonousRegion* next : queue) { + AntPath& path1 = path_matrix(region, dir, *next, false); + AntPath& path2 = path_matrix(region, dir, *next, true); + if (path1.visibility > next_candidate.probability) + next_candidate = { next, &path1, &path1, path1.visibility, false }; + if (path2.visibility > next_candidate.probability) + next_candidate = { next, &path2, &path2, path2.visibility, true }; + } + } + // Move the other right neighbors with satisified constraints to the queue. + for (MonotonousRegion* next : region.right_neighbors) + if (--left_neighbors_unprocessed[next - regions.data()] == 1 && next_candidate.region != next) + queue.emplace_back(next); + if (from_queue) { + // Remove the selected path from the queue. + auto it = std::find(queue.begin(), queue.end(), next_candidate.region); + assert(it != queue.end()); + *it = queue.back(); + queue.pop_back(); + } + // Extend the path. + MonotonousRegion* next_region = next_candidate.region; + bool next_dir = next_candidate.dir; + total_length += next_region->length(next_dir) + path_matrix(*path_end.region, path_end.flipped, *next_region, next_dir).length; + path_end = { next_region, next_dir }; + assert(left_neighbors_unprocessed[next_region - regions.data()] == 1); + left_neighbors_unprocessed[next_region - regions.data()] = 0; + } + + // Set an initial pheromone value to 10% of the greedy path's value. + pheromone_initial_deposit = 0.1 / total_length; + path_matrix.update_inital_pheromone(pheromone_initial_deposit); + } + + // Probability (unnormalized) of traversing a link between two monotonous regions. + auto path_probability = [pheromone_alpha, pheromone_beta](AntPath& path) { + return pow(path.pheromone, pheromone_alpha) * pow(path.visibility, pheromone_beta); + }; + +#ifdef SLIC3R_DEBUG_ANTS + static int irun = 0; + ++irun; +#endif /* SLIC3R_DEBUG_ANTS */ + + int num_rounds_no_change = 0; + for (int round = 0; round < num_rounds && num_rounds_no_change < num_rounds_no_change_exit; ++round) + { + bool improved = false; + for (int ant = 0; ant < num_ants; ++ant) + { + // Find a new path following the pheromones deposited by the previous ants. + print_ant("Round %1% ant %2%", round, ant); + path.clear(); + queue = queue_initial; + left_neighbors_unprocessed = left_neighbors_unprocessed_initial; + assert(validate_unprocessed()); + // Pick randomly the first from the queue at random orientation. + //FIXME picking the 1st monotonous region should likely be done based on accumulated pheromone level as well, + // but the inefficiency caused by the random pick of the 1st monotonous region is likely insignificant. + int first_idx = std::uniform_int_distribution<>(0, int(queue.size()) - 1)(rng); + path.emplace_back(MonotonousRegionLink{ queue[first_idx], rng() > rng.max() / 2 }); + *(queue.begin() + first_idx) = std::move(queue.back()); + queue.pop_back(); + --left_neighbors_unprocessed[path.back().region - regions.data()]; + assert(left_neighbors_unprocessed[path.back().region - regions.data()] == 0); + assert(validate_unprocessed()); + print_ant("\tRegion (%1%:%2%,%3%) (%4%:%5%,%6%)", + path.back().region->left.vline, + path.back().flipped ? path.back().region->left.high : path.back().region->left.low, + path.back().flipped ? path.back().region->left.low : path.back().region->left.high, + path.back().region->right.vline, + path.back().flipped == path.back().region->flips ? path.back().region->right.high : path.back().region->right.low, + path.back().flipped == path.back().region->flips ? path.back().region->right.low : path.back().region->right.high); + + while (!queue.empty() || !path.back().region->right_neighbors.empty()) { + // Chain. + MonotonousRegion& region = *path.back().region; + bool dir = path.back().flipped; + // Sort by distance to pt. + next_candidates.clear(); + next_candidates.reserve(region.right_neighbors.size() * 2); + for (MonotonousRegion* next : region.right_neighbors) { + int& unprocessed = left_neighbors_unprocessed[next - regions.data()]; + assert(unprocessed > 1); + if (--unprocessed == 1) { + // Dependencies of the successive blocks are satisfied. + AntPath& path1 = path_matrix(region, dir, *next, false); + AntPath& path1_flipped = path_matrix(region, !dir, *next, true); + AntPath& path2 = path_matrix(region, dir, *next, true); + AntPath& path2_flipped = path_matrix(region, !dir, *next, false); + next_candidates.emplace_back(NextCandidate{ next, &path1, &path1_flipped, path_probability(path1), false }); + next_candidates.emplace_back(NextCandidate{ next, &path2, &path2_flipped, path_probability(path2), true }); + } + } + size_t num_direct_neighbors = next_candidates.size(); + //FIXME add the queue items to the candidates? These are valid moves as well. + if (num_direct_neighbors == 0) { + // Add the queue candidates. + for (MonotonousRegion* next : queue) { + assert(left_neighbors_unprocessed[next - regions.data()] == 1); + AntPath& path1 = path_matrix(region, dir, *next, false); + AntPath& path1_flipped = path_matrix(region, !dir, *next, true); + AntPath& path2 = path_matrix(region, dir, *next, true); + AntPath& path2_flipped = path_matrix(region, !dir, *next, false); + next_candidates.emplace_back(NextCandidate{ next, &path1, &path1_flipped, path_probability(path1), false }); + next_candidates.emplace_back(NextCandidate{ next, &path2, &path2_flipped, path_probability(path2), true }); + } + } + float dice = float(rng()) / float(rng.max()); + std::vector::iterator take_path; + if (dice < probability_take_best) { + // Take the highest probability path. + take_path = std::max_element(next_candidates.begin(), next_candidates.end(), [](auto& l, auto& r) { return l.probability < r.probability; }); + print_ant("\tTaking best path at probability %1% below %2%", dice, probability_take_best); + } else { + // Take the path based on the probability. + // Calculate the total probability. + float total_probability = std::accumulate(next_candidates.begin(), next_candidates.end(), 0.f, [](const float l, const NextCandidate& r) { return l + r.probability; }); + // Take a random path based on the probability. + float probability_threshold = float(rng()) * total_probability / float(rng.max()); + take_path = next_candidates.end(); + --take_path; + for (auto it = next_candidates.begin(); it < next_candidates.end(); ++it) + if ((probability_threshold -= it->probability) <= 0.) { + take_path = it; + break; + } + print_ant("\tTaking path at probability threshold %1% of %2%", probability_threshold, total_probability); + } + // Move the other right neighbors with satisified constraints to the queue. + for (std::vector::iterator it_next_candidate = next_candidates.begin(); it_next_candidate != next_candidates.begin() + num_direct_neighbors; ++it_next_candidate) + if ((queue.empty() || it_next_candidate->region != queue.back()) && it_next_candidate->region != take_path->region) + queue.emplace_back(it_next_candidate->region); + if (size_t(take_path - next_candidates.begin()) >= num_direct_neighbors) { + // Remove the selected path from the queue. + auto it = std::find(queue.begin(), queue.end(), take_path->region); + assert(it != queue.end()); + *it = queue.back(); + queue.pop_back(); + } + // Extend the path. + MonotonousRegion* next_region = take_path->region; + bool next_dir = take_path->dir; + path.back().next = take_path->link; + path.back().next_flipped = take_path->link_flipped; + path.emplace_back(MonotonousRegionLink{ next_region, next_dir }); + assert(left_neighbors_unprocessed[next_region - regions.data()] == 1); + left_neighbors_unprocessed[next_region - regions.data()] = 0; + print_ant("\tRegion (%1%:%2%,%3%) (%4%:%5%,%6%) length to prev %7%", + next_region->left.vline, + next_dir ? next_region->left.high : next_region->left.low, + next_dir ? next_region->left.low : next_region->left.high, + next_region->right.vline, + next_dir == next_region->flips ? next_region->right.high : next_region->right.low, + next_dir == next_region->flips ? next_region->right.low : next_region->right.high, + take_path->link->length); + + print_ant("\tRegion (%1%:%2%,%3%) (%4%:%5%,%6%)", + path.back().region->left.vline, + path.back().flipped ? path.back().region->left.high : path.back().region->left.low, + path.back().flipped ? path.back().region->left.low : path.back().region->left.high, + path.back().region->right.vline, + path.back().flipped == path.back().region->flips ? path.back().region->right.high : path.back().region->right.low, + path.back().flipped == path.back().region->flips ? path.back().region->right.low : path.back().region->right.high); + + // Update pheromones along this link, see Ant Colony System (ACS) update rule. + // http://www.scholarpedia.org/article/Ant_colony_optimization + // The goal here is to lower the pheromone trace for paths taken to diversify the next path picked in the same batch of ants. + take_path->link->pheromone = (1.f - pheromone_diversification) * take_path->link->pheromone + pheromone_diversification * pheromone_initial_deposit; + assert(validate_unprocessed()); + } + + // Perform 3-opt local optimization of the path. + monotonous_3_opt(path, segs); + + // Measure path length. + assert(!path.empty()); + float path_length = std::accumulate(path.begin(), path.end() - 1, + path.back().region->length(path.back().flipped), + [&path_matrix](const float l, const MonotonousRegionLink& r) { + const MonotonousRegionLink& next = *(&r + 1); + return l + r.region->length(r.flipped) + path_matrix(*r.region, r.flipped, *next.region, next.flipped).length; + }); + // Save the shortest path. + print_ant("\tThis length: %1%, shortest length: %2%", path_length, best_path_length); + if (path_length < best_path_length) { + best_path_length = path_length; + std::swap(best_path, path); +#if 0 // #if ! defined(SLIC3R_DEBUG_ANTS) && ! defined(ndebug) + if (round == 0 && ant == 0) + std::cout << std::endl; + std::cout << Slic3r::format("round %1% ant %2% path length %3%", round, ant, path_length) << std::endl; +#endif + if (path_length == 0) + // Perfect path found. + goto end; + improved = true; + } + } + + // Reinforce the path pheromones with the best path. + float total_cost = best_path_length + float(EPSILON); + for (size_t i = 0; i + 1 < path.size(); ++i) { + MonotonousRegionLink& link = path[i]; + link.next->pheromone = (1.f - pheromone_evaporation) * link.next->pheromone + pheromone_evaporation / total_cost; + } + + if (improved) + num_rounds_no_change = 0; + else + ++num_rounds_no_change; + } + +end: + return best_path; +} + +// Traverse path, produce polylines. +static void polylines_from_paths(const std::vector& path, const ExPolygonWithOffset& poly_with_offset, const std::vector& segs, Polylines& polylines_out) +{ + Polyline* polyline = nullptr; + auto finish_polyline = [&polyline, &polylines_out]() { + polyline->remove_duplicate_points(); + // Handle duplicate points and zero length segments. + assert(!polyline->has_duplicate_points()); + // Handle nearly zero length edges. + if (polyline->points.size() <= 1 || + (polyline->points.size() == 2 && + std::abs(polyline->points.front()(0) - polyline->points.back()(0)) < SCALED_EPSILON && + std::abs(polyline->points.front()(1) - polyline->points.back()(1)) < SCALED_EPSILON)) + polylines_out.pop_back(); + polyline = nullptr; + }; + + for (const MonotonousRegionLink& path_segment : path) { + MonotonousRegion& region = *path_segment.region; + bool dir = path_segment.flipped; + + // From the initial point (i_vline, i_intersection), follow a path. + int i_intersection = region.left_intersection_point(dir); + int i_vline = region.left.vline; + + if (polyline != nullptr && &path_segment != path.data()) { + // Connect previous path segment with the new one. + const MonotonousRegionLink& path_segment_prev = *(&path_segment - 1); + const MonotonousRegion& region_prev = *path_segment_prev.region; + bool dir_prev = path_segment_prev.flipped; + int i_vline_prev = region_prev.right.vline; + const SegmentedIntersectionLine& vline_prev = segs[i_vline_prev]; + int i_intersection_prev = region_prev.right_intersection_point(dir_prev); + const SegmentIntersection* ip_prev = &vline_prev.intersections[i_intersection_prev]; + bool extended = false; + if (i_vline_prev + 1 == i_vline) { + if (ip_prev->right_horizontal() == i_intersection && ip_prev->next_on_contour_quality == SegmentIntersection::LinkQuality::Valid) { + // Emit a horizontal connection contour. + emit_perimeter_prev_next_segment(poly_with_offset, segs, i_vline_prev, ip_prev->iContour, i_intersection_prev, i_intersection, *polyline, true); + extended = true; + } + } + if (!extended) { + // Finish the current vertical line, + assert(ip_prev->is_inner()); + ip_prev->is_low() ? --ip_prev : ++ip_prev; + assert(ip_prev->is_outer()); + polyline->points.back() = Point(vline_prev.pos, ip_prev->pos()); + finish_polyline(); + } + } + + for (;;) { + const SegmentedIntersectionLine& vline = segs[i_vline]; + const SegmentIntersection* it = &vline.intersections[i_intersection]; + const bool going_up = it->is_low(); + if (polyline == nullptr) { + polylines_out.emplace_back(); + polyline = &polylines_out.back(); + // Extend the infill line up to the outer contour. + polyline->points.emplace_back(vline.pos, (it + (going_up ? -1 : 1))->pos()); + } else + polyline->points.emplace_back(vline.pos, it->pos()); + + int iright = it->right_horizontal(); + if (going_up) { + // Consume the complete vertical segment up to the inner contour. + for (;;) { + do { + ++it; + iright = std::max(iright, it->right_horizontal()); + assert(it->is_inner()); + } while (it->type != SegmentIntersection::INNER_HIGH || (it + 1)->type != SegmentIntersection::OUTER_HIGH); + polyline->points.emplace_back(vline.pos, it->pos()); + int inext = it->vertical_up(); + if (inext == -1 || it->vertical_up_quality() != SegmentIntersection::LinkQuality::Valid) + break; + assert(it->iContour == vline.intersections[inext].iContour); + emit_perimeter_segment_on_vertical_line(poly_with_offset, segs, i_vline, it->iContour, it - vline.intersections.data(), inext, *polyline, it->has_left_vertical_up()); + it = vline.intersections.data() + inext; + } + } else { + // Going down. + assert(it->is_high()); + assert(i_intersection > 0); + for (;;) { + do { + --it; + if (int iright_new = it->right_horizontal(); iright_new != -1) + iright = iright_new; + assert(it->is_inner()); + } while (it->type != SegmentIntersection::INNER_LOW || (it - 1)->type != SegmentIntersection::OUTER_LOW); + polyline->points.emplace_back(vline.pos, it->pos()); + int inext = it->vertical_down(); + if (inext == -1 || it->vertical_down_quality() != SegmentIntersection::LinkQuality::Valid) + break; + assert(it->iContour == vline.intersections[inext].iContour); + emit_perimeter_segment_on_vertical_line(poly_with_offset, segs, i_vline, it->iContour, it - vline.intersections.data(), inext, *polyline, it->has_right_vertical_down()); + it = vline.intersections.data() + inext; + } + } + + if (i_vline == region.right.vline) + break; + + int inext = it->right_horizontal(); + if (inext != -1 && it->next_on_contour_quality == SegmentIntersection::LinkQuality::Valid) { + // Emit a horizontal connection contour. + emit_perimeter_prev_next_segment(poly_with_offset, segs, i_vline, it->iContour, it - vline.intersections.data(), inext, *polyline, true); + i_intersection = inext; + } else { + // Finish the current vertical line, + going_up ? ++it : --it; + assert(it->is_outer()); + assert(it->is_high() == going_up); + polyline->points.back() = Point(vline.pos, it->pos()); + finish_polyline(); + if (inext == -1) { + // Find the end of the next overlapping vertical segment. + const SegmentedIntersectionLine& vline_right = segs[i_vline + 1]; + const SegmentIntersection* right = going_up ? + &vertical_run_top(vline_right, vline_right.intersections[iright]) : &vertical_run_bottom(vline_right, vline_right.intersections[iright]); + i_intersection = int(right - vline_right.intersections.data()); + } else + i_intersection = inext; + } + + ++i_vline; + } + } + + if (polyline != nullptr) { + // Finish the current vertical line, + const MonotonousRegion& region = *path.back().region; + const SegmentedIntersectionLine& vline = segs[region.right.vline]; + const SegmentIntersection* ip = &vline.intersections[region.right_intersection_point(path.back().flipped)]; + assert(ip->is_inner()); + ip->is_low() ? --ip : ++ip; + assert(ip->is_outer()); + polyline->points.back() = Point(vline.pos, ip->pos()); + finish_polyline(); + } } bool FillRectilinear2::fill_surface_by_lines(const Surface *surface, const FillParams ¶ms, float angleBase, float pattern_shift, Polylines &polylines_out) const @@ -897,8 +2543,8 @@ bool FillRectilinear2::fill_surface_by_lines(const Surface *surface, const FillP ExPolygonWithOffset poly_with_offset( surface->expolygon, - rotate_vector.first, - scale_(0 /*this->overlap*/ - (0.5 - INFILL_OVERLAP_OVER_SPACING) * this->spacing), - scale_(0 /*this->overlap*/ - 0.5 * this->spacing)); + float(scale_(0 /*this->overlap*/ - (0.5 - INFILL_OVERLAP_OVER_SPACING) * this->spacing)), + float(scale_(0 /*this->overlap*/ - 0.5 * this->spacing))); if (poly_with_offset.n_contours_inner == 0) { // Not a single infill line fits. //Prusa: maybe one shall trigger the gap fill here? @@ -925,108 +2571,28 @@ bool FillRectilinear2::fill_surface_by_lines(const Surface *surface, const FillP refpt)); } +#ifdef SLIC3R_DEBUG + static int iRun = 0; + BoundingBox bbox_svg = poly_with_offset.bounding_box_outer(); + ::Slic3r::SVG svg(debug_out_path("FillRectilinear2-%d.svg", iRun), bbox_svg); // , scale_(1.)); + poly_with_offset.export_to_svg(svg); + { + ::Slic3r::SVG svg(debug_out_path("FillRectilinear2-initial-%d.svg", iRun), bbox_svg); // , scale_(1.)); + poly_with_offset.export_to_svg(svg); + } + iRun++; +#endif /* SLIC3R_DEBUG */ + + // Intersect a set of equally spaced vertical lines with expolygon. std::vector segs = _vert_lines_for_polygon(poly_with_offset, bounding_box, params, line_spacing); - // Sort the intersections along their segments, specify the intersection types. - for (size_t i_seg = 0; i_seg < segs.size(); ++ i_seg) { - SegmentedIntersectionLine &sil = segs[i_seg]; - // Sort the intersection points using exact rational arithmetic. - std::sort(sil.intersections.begin(), sil.intersections.end()); - // Assign the intersection types, remove duplicate or overlapping intersection points. - // When a loop vertex touches a vertical line, intersection point is generated for both segments. - // If such two segments are oriented equally, then one of them is removed. - // Otherwise the vertex is tangential to the vertical line and both segments are removed. - // The same rule applies, if the loop is pinched into a single point and this point touches the vertical line: - // The loop has a zero vertical size at the vertical line, therefore the intersection point is removed. - size_t j = 0; - for (size_t i = 0; i < sil.intersections.size(); ++ i) { - // What is the orientation of the segment at the intersection point? - size_t iContour = sil.intersections[i].iContour; - const Points &contour = poly_with_offset.contour(iContour).points; - size_t iSegment = sil.intersections[i].iSegment; - size_t iPrev = ((iSegment == 0) ? contour.size() : iSegment) - 1; - coord_t dir = contour[iSegment](0) - contour[iPrev](0); - bool low = dir > 0; - sil.intersections[i].type = poly_with_offset.is_contour_outer(iContour) ? - (low ? SegmentIntersection::OUTER_LOW : SegmentIntersection::OUTER_HIGH) : - (low ? SegmentIntersection::INNER_LOW : SegmentIntersection::INNER_HIGH); - if (j > 0 && sil.intersections[i].iContour == sil.intersections[j-1].iContour) { - // Two successive intersection points on a vertical line with the same contour. This may be a special case. - if (sil.intersections[i].pos() == sil.intersections[j-1].pos()) { - // Two successive segments meet exactly at the vertical line. - #ifdef SLIC3R_DEBUG - // Verify that the segments of sil.intersections[i] and sil.intersections[j-1] are adjoint. - size_t iSegment2 = sil.intersections[j-1].iSegment; - size_t iPrev2 = ((iSegment2 == 0) ? contour.size() : iSegment2) - 1; - assert(iSegment == iPrev2 || iSegment2 == iPrev); - #endif /* SLIC3R_DEBUG */ - if (sil.intersections[i].type == sil.intersections[j-1].type) { - // Two successive segments of the same direction (both to the right or both to the left) - // meet exactly at the vertical line. - // Remove the second intersection point. - } else { - // This is a loop returning to the same point. - // It may as well be a vertex of a loop touching this vertical line. - // Remove both the lines. - -- j; - } - } else if (sil.intersections[i].type == sil.intersections[j-1].type) { - // Two non successive segments of the same direction (both to the right or both to the left) - // meet exactly at the vertical line. That means there is a Z shaped path, where the center segment - // of the Z shaped path is aligned with this vertical line. - // Remove one of the intersection points while maximizing the vertical segment length. - if (low) { - // Remove the second intersection point, keep the first intersection point. - } else { - // Remove the first intersection point, keep the second intersection point. - sil.intersections[j-1] = sil.intersections[i]; - } - } else { - // Vertical line intersects a contour segment at a general position (not at one of its end points). - // or the contour just touches this vertical line with a vertical segment or a sequence of vertical segments. + slice_region_by_vertical_lines(segs, poly_with_offset); - //if you have to remove a point, be sure to remove also its sibling. - if (sil.intersections[j].pos() != sil.intersections[i].pos() || j + 1 != i) { - // Keep both intersection points. - if (j < i) - sil.intersections[j] = sil.intersections[i]; - ++j; - } - } - } else { - // Vertical line intersects a contour segment at a general position (not at one of its end points). - if (j < i) - sil.intersections[j] = sil.intersections[i]; - ++ j; - } - } - // Shrink the list of intersections, if any of the intersection was removed during the classification. - if (j < sil.intersections.size()) - sil.intersections.erase(sil.intersections.begin() + j, sil.intersections.end()); - } + //all the works is done HERE + // Connect by horizontal / vertical links, classify the links based on link_max_length as too long. + connect_segment_intersections_by_contours(poly_with_offset, segs, params, link_max_length); - // Verify the segments. If something is wrong, give up. -#define ASSERT_OR_RETURN(CONDITION) do { /*assert(CONDITION); error here. Didn't do any mod that should affect it. Didn't have the time to understand algo, so i let it fail*/ if (! (CONDITION)) return false; } while (0) - for (size_t i_seg = 0; i_seg < segs.size(); ++ i_seg) { - SegmentedIntersectionLine &sil = segs[i_seg]; - // The intersection points have to be even. - ASSERT_OR_RETURN((sil.intersections.size() & 1) == 0); - for (size_t i = 0; i < sil.intersections.size();) { - // An intersection segment crossing the bigger contour may cross the inner offsetted contour even number of times. - ASSERT_OR_RETURN(sil.intersections[i].type == SegmentIntersection::OUTER_LOW); - size_t j = i + 1; - ASSERT_OR_RETURN(j < sil.intersections.size()); - ASSERT_OR_RETURN(sil.intersections[j].type == SegmentIntersection::INNER_LOW || sil.intersections[j].type == SegmentIntersection::OUTER_HIGH); - for (; j < sil.intersections.size() && sil.intersections[j].is_inner(); ++ j) ; - ASSERT_OR_RETURN(j < sil.intersections.size()); - ASSERT_OR_RETURN((j & 1) == 1); - ASSERT_OR_RETURN(sil.intersections[j].type == SegmentIntersection::OUTER_HIGH); - ASSERT_OR_RETURN(i + 1 == j || sil.intersections[j - 1].type == SegmentIntersection::INNER_HIGH); - i = j + 1; - } - } -#undef ASSERT_OR_RETURN #ifdef SLIC3R_DEBUG // Paint the segments and finalize the SVG file. @@ -1048,371 +2614,19 @@ bool FillRectilinear2::fill_surface_by_lines(const Surface *surface, const FillP svg.Close(); #endif /* SLIC3R_DEBUG */ - // For each outer only chords, measure their maximum distance to the bow of the outer contour. - // Mark an outer only chord as consumed, if the distance is low. - for (size_t i_vline = 0; i_vline < segs.size(); ++ i_vline) { - SegmentedIntersectionLine &seg = segs[i_vline]; - for (size_t i_intersection = 0; i_intersection + 1 < seg.intersections.size(); ++ i_intersection) { - if (seg.intersections[i_intersection].type == SegmentIntersection::OUTER_LOW && - seg.intersections[i_intersection+1].type == SegmentIntersection::OUTER_HIGH) { - bool consumed = false; -// if (params.full_infill()) { -// measure_outer_contour_slab(poly_with_offset, segs, i_vline, i_ntersection); -// } else - consumed = true; - seg.intersections[i_intersection].consumed_vertical_up = consumed; - } + //FIXME this is a hack to get the monotonous infill rolling. We likely want a smarter switch, likely based on user decison. + bool monotonous_infill = params.monotonous; // || params.density > 0.99; + if (monotonous_infill) { + std::vector regions = generate_montonous_regions(segs); + connect_monotonous_regions(regions, poly_with_offset, segs); + if (!regions.empty()) { + std::mt19937_64 rng; + std::vector path = chain_monotonous_regions(regions, poly_with_offset, segs, rng); + polylines_from_paths(path, poly_with_offset, segs, polylines_out); } - } + } else + traverse_graph_generate_polylines(poly_with_offset, params, segs, polylines_out); - // Now construct a graph. - // Find the first point. - // Naively one would expect to achieve best results by chaining the paths by the shortest distance, - // but that procedure does not create the longest continuous paths. - // A simple "sweep left to right" procedure achieves better results. - size_t i_vline = 0; - size_t i_intersection = size_t(-1); - // Follow the line, connect the lines into a graph. - // Until no new line could be added to the output path: - Point pointLast; - Polyline *polyline_current = NULL; - if (! polylines_out.empty()) - pointLast = polylines_out.back().points.back(); - for (;;) { - if (i_intersection == size_t(-1)) { - // The path has been interrupted. Find a next starting point, closest to the previous extruder position. - coordf_t dist2min = std::numeric_limits().max(); - for (size_t i_vline2 = 0; i_vline2 < segs.size(); ++ i_vline2) { - const SegmentedIntersectionLine &seg = segs[i_vline2]; - if (! seg.intersections.empty()) { - assert(seg.intersections.size() > 1); - // Even number of intersections with the loops. - assert((seg.intersections.size() & 1) == 0); - assert(seg.intersections.front().type == SegmentIntersection::OUTER_LOW); - for (size_t i = 0; i < seg.intersections.size(); ++ i) { - const SegmentIntersection &intrsctn = seg.intersections[i]; - if (intrsctn.is_outer()) { - assert(intrsctn.is_low() || i > 0); - bool consumed = intrsctn.is_low() ? - intrsctn.consumed_vertical_up : - seg.intersections[i-1].consumed_vertical_up; - if (! consumed) { - coordf_t dist2 = sqr(coordf_t(pointLast(0) - seg.pos)) + sqr(coordf_t(pointLast(1) - intrsctn.pos())); - if (dist2 < dist2min) { - dist2min = dist2; - i_vline = i_vline2; - i_intersection = i; - //FIXME We are taking the first left point always. Verify, that the caller chains the paths - // by a shortest distance, while reversing the paths if needed. - //if (polylines_out.empty()) - // Initial state, take the first line, which is the first from the left. - goto found; - } - } - } - } - } - } - if (i_intersection == size_t(-1)) - // We are finished. - break; - found: - // Start a new path. - polylines_out.push_back(Polyline()); - polyline_current = &polylines_out.back(); - // Emit the first point of a path. - pointLast = Point(segs[i_vline].pos, segs[i_vline].intersections[i_intersection].pos()); - polyline_current->points.push_back(pointLast); - } - - // From the initial point (i_vline, i_intersection), follow a path. - SegmentedIntersectionLine &seg = segs[i_vline]; - SegmentIntersection *intrsctn = &seg.intersections[i_intersection]; - bool going_up = intrsctn->is_low(); - bool try_connect = false; - if (going_up) { - assert(! intrsctn->consumed_vertical_up); - assert(i_intersection + 1 < seg.intersections.size()); - // Step back to the beginning of the vertical segment to mark it as consumed. - if (intrsctn->is_inner()) { - assert(i_intersection > 0); - -- intrsctn; - -- i_intersection; - } - // Consume the complete vertical segment up to the outer contour. - do { - intrsctn->consumed_vertical_up = true; - ++ intrsctn; - ++ i_intersection; - assert(i_intersection < seg.intersections.size()); - } while (intrsctn->type != SegmentIntersection::OUTER_HIGH); - if ((intrsctn - 1)->is_inner()) { - // Step back. - -- intrsctn; - -- i_intersection; - assert(intrsctn->type == SegmentIntersection::INNER_HIGH); - try_connect = true; - } - } else { - // Going down. - assert(intrsctn->is_high()); - assert(i_intersection > 0); - assert(! (intrsctn - 1)->consumed_vertical_up); - // Consume the complete vertical segment up to the outer contour. - if (intrsctn->is_inner()) - intrsctn->consumed_vertical_up = true; - do { - assert(i_intersection > 0); - -- intrsctn; - -- i_intersection; - intrsctn->consumed_vertical_up = true; - } while (intrsctn->type != SegmentIntersection::OUTER_LOW); - if ((intrsctn + 1)->is_inner()) { - // Step back. - ++ intrsctn; - ++ i_intersection; - assert(intrsctn->type == SegmentIntersection::INNER_LOW); - try_connect = true; - } - } - if (try_connect) { - // Decide, whether to finish the segment, or whether to follow the perimeter. - - // 1) Find possible connection points on the previous / next vertical line. - int iPrev = intersection_on_prev_vertical_line(poly_with_offset, segs, i_vline, intrsctn->iContour, i_intersection); - int iNext = intersection_on_next_vertical_line(poly_with_offset, segs, i_vline, intrsctn->iContour, i_intersection); - IntersectionTypeOtherVLine intrsctn_type_prev = intersection_type_on_prev_vertical_line(segs, i_vline, i_intersection, iPrev); - IntersectionTypeOtherVLine intrsctn_type_next = intersection_type_on_next_vertical_line(segs, i_vline, i_intersection, iNext); - - // 2) Find possible connection points on the same vertical line. - int iAbove = -1; - int iBelow = -1; - int iSegAbove = -1; - int iSegBelow = -1; - { -// SegmentIntersection::SegmentIntersectionType type_crossing = (intrsctn->type == SegmentIntersection::INNER_LOW) ? -// SegmentIntersection::INNER_HIGH : SegmentIntersection::INNER_LOW; - // Does the perimeter intersect the current vertical line above intrsctn? - for (size_t i = i_intersection + 1; i + 1 < seg.intersections.size(); ++ i) -// if (seg.intersections[i].iContour == intrsctn->iContour && seg.intersections[i].type == type_crossing) { - if (seg.intersections[i].iContour == intrsctn->iContour) { - iAbove = i; - iSegAbove = seg.intersections[i].iSegment; - break; - } - // Does the perimeter intersect the current vertical line below intrsctn? - for (size_t i = i_intersection - 1; i > 0; -- i) -// if (seg.intersections[i].iContour == intrsctn->iContour && seg.intersections[i].type == type_crossing) { - if (seg.intersections[i].iContour == intrsctn->iContour) { - iBelow = i; - iSegBelow = seg.intersections[i].iSegment; - break; - } - } - - // 3) Sort the intersection points, clear iPrev / iNext / iSegBelow / iSegAbove, - // if it is preceded by any other intersection point along the contour. - unsigned int vert_seg_dir_valid_mask = - (going_up ? - (iSegAbove != -1 && seg.intersections[iAbove].type == SegmentIntersection::INNER_LOW) : - (iSegBelow != -1 && seg.intersections[iBelow].type == SegmentIntersection::INNER_HIGH)) ? - (DIR_FORWARD | DIR_BACKWARD) : - 0; - { - // Invalidate iPrev resp. iNext, if the perimeter crosses the current vertical line earlier than iPrev resp. iNext. - // The perimeter contour orientation. - const bool forward = intrsctn->is_low(); // == poly_with_offset.is_contour_ccw(intrsctn->iContour); - const Polygon &poly = poly_with_offset.contour(intrsctn->iContour); - { - int d_horiz = (iPrev == -1) ? std::numeric_limits::max() : - distance_of_segmens(poly, segs[i_vline-1].intersections[iPrev].iSegment, intrsctn->iSegment, forward); - int d_down = (iSegBelow == -1) ? std::numeric_limits::max() : - distance_of_segmens(poly, iSegBelow, intrsctn->iSegment, forward); - int d_up = (iSegAbove == -1) ? std::numeric_limits::max() : - distance_of_segmens(poly, iSegAbove, intrsctn->iSegment, forward); - if (intrsctn_type_prev == INTERSECTION_TYPE_OTHER_VLINE_OK && d_horiz > std::min(d_down, d_up)) - // The vertical crossing comes eralier than the prev crossing. - // Disable the perimeter going back. - intrsctn_type_prev = INTERSECTION_TYPE_OTHER_VLINE_NOT_FIRST; - if (going_up ? (d_up > std::min(d_horiz, d_down)) : (d_down > std::min(d_horiz, d_up))) - // The horizontal crossing comes earlier than the vertical crossing. - vert_seg_dir_valid_mask &= ~(forward ? DIR_BACKWARD : DIR_FORWARD); - } - { - int d_horiz = (iNext == -1) ? std::numeric_limits::max() : - distance_of_segmens(poly, intrsctn->iSegment, segs[i_vline+1].intersections[iNext].iSegment, forward); - int d_down = (iSegBelow == -1) ? std::numeric_limits::max() : - distance_of_segmens(poly, intrsctn->iSegment, iSegBelow, forward); - int d_up = (iSegAbove == -1) ? std::numeric_limits::max() : - distance_of_segmens(poly, intrsctn->iSegment, iSegAbove, forward); - if (intrsctn_type_next == INTERSECTION_TYPE_OTHER_VLINE_OK && d_horiz > std::min(d_down, d_up)) - // The vertical crossing comes eralier than the prev crossing. - // Disable the perimeter going forward. - intrsctn_type_next = INTERSECTION_TYPE_OTHER_VLINE_NOT_FIRST; - if (going_up ? (d_up > std::min(d_horiz, d_down)) : (d_down > std::min(d_horiz, d_up))) - // The horizontal crossing comes earlier than the vertical crossing. - vert_seg_dir_valid_mask &= ~(forward ? DIR_FORWARD : DIR_BACKWARD); - } - } - - // 4) Try to connect to a previous or next vertical line, making a zig-zag pattern. - if (intrsctn_type_prev == INTERSECTION_TYPE_OTHER_VLINE_OK || intrsctn_type_next == INTERSECTION_TYPE_OTHER_VLINE_OK) { - coordf_t distPrev = (intrsctn_type_prev != INTERSECTION_TYPE_OTHER_VLINE_OK) ? std::numeric_limits::max() : - measure_perimeter_prev_segment_length(poly_with_offset, segs, i_vline, intrsctn->iContour, i_intersection, iPrev); - coordf_t distNext = (intrsctn_type_next != INTERSECTION_TYPE_OTHER_VLINE_OK) ? std::numeric_limits::max() : - measure_perimeter_next_segment_length(poly_with_offset, segs, i_vline, intrsctn->iContour, i_intersection, iNext); - // Take the shorter path. - //FIXME this may not be always the best strategy to take the shortest connection line now. - bool take_next = (intrsctn_type_prev == INTERSECTION_TYPE_OTHER_VLINE_OK && intrsctn_type_next == INTERSECTION_TYPE_OTHER_VLINE_OK) ? - (distNext < distPrev) : - intrsctn_type_next == INTERSECTION_TYPE_OTHER_VLINE_OK; - assert(intrsctn->is_inner()); - bool skip = params.dont_connect || (link_max_length > 0 && (take_next ? distNext : distPrev) > link_max_length * 3); - if (skip) { - // Just skip the connecting contour and start a new path. - goto dont_connect; - } - skip = params.dont_connect || (link_max_length > 0 && (take_next ? distNext : distPrev) > link_max_length); - if (skip) { - //"skip" the connection but continue to print something as it was connected - //also, add a bit of extrusion at the tip, to not under-extrude - //TODO: supermerill: don't output polyline but Extrusion entiyt, to be able to extrude a small line here (gap-fill style) instead of big bits. - Point last_point = Point(seg.pos, intrsctn->pos()); - const SegmentedIntersectionLine &il2 = segs[take_next ? (i_vline + 1) : (i_vline - 1)]; - Point next_point = Point(il2.pos, il2.intersections[take_next ? iNext : iPrev].pos()); - //compute angle to see where it's possible to extrude a bit - float coeff_before = 0.5f; - if (!polyline_current->points.empty()) coeff_before = 1 - std::abs(((last_point.ccw_angle(polyline_current->points.back(), next_point)) / PI) - 1); - if (coeff_before < 0.5) coeff_before = 0.0; - if (coeff_before > 0.5) coeff_before = 1.0; - //now add the points at the end of the current polyline - polyline_current->points.push_back(last_point); - if (coeff_before > 0.0) - polyline_current->points.push_back(last_point.interpolate(coeff_before * scale_(this->spacing * 0.7) / ( (take_next ? distNext : distPrev)), next_point)); - //now create & add the points at the start of the new polyline - polylines_out.push_back(Polyline()); - polyline_current = &polylines_out.back(); - if (coeff_before < 1.0) - polyline_current->points.push_back(next_point.interpolate((1 - coeff_before) * scale_(this->spacing * 0.7) / ((take_next ? distNext : distPrev)), last_point)); - polyline_current->points.push_back(next_point); - } else { - polyline_current->points.push_back(Point(seg.pos, intrsctn->pos())); - emit_perimeter_prev_next_segment(poly_with_offset, segs, i_vline, intrsctn->iContour, i_intersection, take_next ? iNext : iPrev, *polyline_current, take_next); - } - // Mark both the left and right connecting segment as consumed, because one cannot go to this intersection point as it has been consumed. - if (iPrev != -1) - segs[i_vline-1].intersections[iPrev].consumed_perimeter_right = true; - if (iNext != -1) - intrsctn->consumed_perimeter_right = true; - //FIXME consume the left / right connecting segments at the other end of this line? Currently it is not critical because a perimeter segment is not followed if the vertical segment at the other side has already been consumed. - // Advance to the neighbor line. - if (take_next) { - ++ i_vline; - i_intersection = iNext; - } else { - -- i_vline; - i_intersection = iPrev; - } - continue; - } - - // 5) Try to connect to a previous or next point on the same vertical line. - if (vert_seg_dir_valid_mask) { - bool valid = true; - // Verify, that there is no intersection with the inner contour up to the end of the contour segment. - // Verify, that the successive segment has not been consumed yet. - if (going_up) { - if (seg.intersections[iAbove].consumed_vertical_up) { - valid = false; - } else { - for (int i = (int)i_intersection + 1; i < iAbove && valid; ++i) - if (seg.intersections[i].is_inner()) - valid = false; - } - } else { - if (seg.intersections[iBelow-1].consumed_vertical_up) { - valid = false; - } else { - for (int i = iBelow + 1; i < (int)i_intersection && valid; ++i) - if (seg.intersections[i].is_inner()) - valid = false; - } - } - if (valid) { - const Polygon &poly = poly_with_offset.contour(intrsctn->iContour); - int iNext = going_up ? iAbove : iBelow; - int iSegNext = going_up ? iSegAbove : iSegBelow; - bool dir_forward = (vert_seg_dir_valid_mask == (DIR_FORWARD | DIR_BACKWARD)) ? - // Take the shorter length between the current and the next intersection point. - (distance_of_segmens(poly, intrsctn->iSegment, iSegNext, true) < - distance_of_segmens(poly, intrsctn->iSegment, iSegNext, false)) : - (vert_seg_dir_valid_mask == DIR_FORWARD); - // Skip this perimeter line? - bool skip = params.dont_connect; - if (! skip && link_max_length > 0) { - coordf_t link_length = measure_perimeter_segment_on_vertical_line_length( - poly_with_offset, segs, i_vline, intrsctn->iContour, i_intersection, iNext, dir_forward); - skip = link_length > link_max_length; - } - polyline_current->points.push_back(Point(seg.pos, intrsctn->pos())); - if (skip) { - // Just skip the connecting contour and start a new path. - polylines_out.push_back(Polyline()); - polyline_current = &polylines_out.back(); - polyline_current->points.push_back(Point(seg.pos, seg.intersections[iNext].pos())); - } else { - // Consume the connecting contour and the next segment. - emit_perimeter_segment_on_vertical_line(poly_with_offset, segs, i_vline, intrsctn->iContour, i_intersection, iNext, *polyline_current, dir_forward); - } - // Mark both the left and right connecting segment as consumed, because one cannot go to this intersection point as it has been consumed. - // If there are any outer intersection points skipped (bypassed) by the contour, - // mark them as processed. - if (going_up) { - for (int i = (int)i_intersection; i < iAbove; ++ i) - seg.intersections[i].consumed_vertical_up = true; - } else { - for (int i = iBelow; i < (int)i_intersection; ++ i) - seg.intersections[i].consumed_vertical_up = true; - } -// seg.intersections[going_up ? i_intersection : i_intersection - 1].consumed_vertical_up = true; - intrsctn->consumed_perimeter_right = true; - i_intersection = iNext; - if (going_up) - ++ intrsctn; - else - -- intrsctn; - intrsctn->consumed_perimeter_right = true; - continue; - } - } - dont_connect: - // No way to continue the current polyline. Take the rest of the line up to the outer contour. - // This will finish the polyline, starting another polyline at a new point. - if (going_up) - ++ intrsctn; - else - -- intrsctn; - } - - // Finish the current vertical line, - // reset the current vertical line to pick a new starting point in the next round. - assert(intrsctn->is_outer()); - assert(intrsctn->is_high() == going_up); - pointLast = Point(seg.pos, intrsctn->pos()); - polyline_current->points.push_back(pointLast); - // Handle duplicate points and zero length segments. - polyline_current->remove_duplicate_points(); - assert(! polyline_current->has_duplicate_points()); - // Handle nearly zero length edges. - if (polyline_current->points.size() <= 1 || - (polyline_current->points.size() == 2 && - std::abs(polyline_current->points.front()(0) - polyline_current->points.back()(0)) < SCALED_EPSILON && - std::abs(polyline_current->points.front()(1) - polyline_current->points.back()(1)) < SCALED_EPSILON)) - polylines_out.pop_back(); - intrsctn = NULL; - i_intersection = -1; - polyline_current = NULL; - } #ifdef SLIC3R_DEBUG { @@ -1460,6 +2674,17 @@ Polylines FillRectilinear2::fill_surface(const Surface *surface, const FillParam return polylines_out; } +Polylines FillMonotonous::fill_surface(const Surface *surface, const FillParams ¶ms) const +{ + FillParams params2 = params; + params2.monotonous = true; + Polylines polylines_out; + if (!fill_surface_by_lines(surface, params2, 0.f, 0.f, polylines_out)) { + printf("FillMonotonous::fill_surface() failed to fill a region.\n"); + } + return polylines_out; +} + Polylines FillGrid2::fill_surface(const Surface *surface, const FillParams ¶ms) const { // Each linear fill covers half of the target coverage. @@ -1514,10 +2739,10 @@ Polylines FillCubic::fill_surface(const Surface *surface, const FillParams ¶ params3.dont_connect = true; Polylines polylines_out; coordf_t dx = sqrt(0.5) * z; - if (! fill_surface_by_lines(surface, params2, 0.f, dx, polylines_out) || - ! fill_surface_by_lines(surface, params2, float(M_PI / 3.), - dx, polylines_out) || + if (! fill_surface_by_lines(surface, params2, 0.f, float(dx), polylines_out) || + ! fill_surface_by_lines(surface, params2, float(M_PI / 3.), -float(dx), polylines_out) || // Rotated by PI*2/3 + PI to achieve reverse sloping wall. - ! fill_surface_by_lines(surface, params3, float(M_PI * 2. / 3.), dx, polylines_out)) { + ! fill_surface_by_lines(surface, params3, float(M_PI * 2. / 3.), float(dx), polylines_out)) { printf("FillCubic::fill_surface() failed to fill a region.\n"); } return polylines_out; @@ -1823,9 +3048,11 @@ FillRectilinear2WGapFill::fill_surface_extrusion(const Surface *surface, const F // rectilinear Polylines polylines_rectilinear; Surface rectilinear_surface{ *surface }; + FillParams params_monotonous = params; + params_monotonous.monotonous = true; for (const ExPolygon &rectilinear_area : rectilinear_areas) { rectilinear_surface.expolygon = rectilinear_area, 0 - 0.5 * params.flow->scaled_spacing(); - if (!fill_surface_by_lines(&rectilinear_surface, params, 0.f, 0.f, polylines_rectilinear)) { + if (!fill_surface_by_lines(&rectilinear_surface, params_monotonous, 0.f, 0.f, polylines_rectilinear)) { printf("FillRectilinear2::fill_surface() failed to fill a region.\n"); } } @@ -1873,7 +3100,11 @@ FillRectilinear2WGapFill::fill_surface_extrusion(const Surface *surface, const F //Create extrusions ExtrusionEntityCollection *eec = new ExtrusionEntityCollection(); /// pass the no_sort attribute to the extrusion path - eec->no_sort = this->no_sort(); + //don't force monotonous if not top or bottom + if (surface->surface_type & (stPosTop | stPosBottom) != 0) + eec->no_sort = true; + else + eec->no_sort = this->no_sort(); extrusion_entities_append_paths( eec->entities, polylines_rectilinear, @@ -1893,9 +3124,17 @@ FillRectilinear2WGapFill::fill_surface_extrusion(const Surface *surface, const F gapfill_areas.insert(gapfill_areas.end(), unextruded_areas.begin(), unextruded_areas.end()); gapfill_areas = union_ex(gapfill_areas, true); if (gapfill_areas.size() > 0) { + const double minarea = scale_(params.config->gap_fill_min_area.get_abs_value(params.flow->width)) * params.flow->scaled_width(); + for (int i = 0; i < gapfill_areas.size(); i++) { + if (gapfill_areas[i].area() < minarea) { + gapfill_areas.erase(gapfill_areas.begin() + i); + i--; + } + } FillParams params2{ params }; params2.role = good_role; - do_gap_fill(gapfill_areas, params2, coll_nosort->entities); + + do_gap_fill(intersection_ex(gapfill_areas, no_overlap_expolygons), params2, coll_nosort->entities); } // === end === diff --git a/src/libslic3r/Fill/FillRectilinear2.hpp b/src/libslic3r/Fill/FillRectilinear2.hpp index 3dd15fbdf..1d6c07382 100644 --- a/src/libslic3r/Fill/FillRectilinear2.hpp +++ b/src/libslic3r/Fill/FillRectilinear2.hpp @@ -15,7 +15,7 @@ class FillRectilinear2 : public Fill { public: virtual Fill* clone() const override { return new FillRectilinear2(*this); }; - virtual ~FillRectilinear2() {} + virtual ~FillRectilinear2() = default; virtual void init_spacing(coordf_t spacing, const FillParams ¶ms) override; virtual Polylines fill_surface(const Surface *surface, const FillParams ¶ms) const override; @@ -25,11 +25,20 @@ protected: bool fill_surface_by_lines(const Surface *surface, const FillParams ¶ms, float angleBase, float pattern_shift, Polylines &polylines_out) const; }; +class FillMonotonous : public FillRectilinear2 +{ +public: + virtual Fill* clone() const { return new FillMonotonous(*this); }; + virtual ~FillMonotonous() = default; + virtual Polylines fill_surface(const Surface * surface, const FillParams & params) const override; + virtual bool no_sort() const { return true; } +}; + class FillGrid2 : public FillRectilinear2 { public: virtual Fill* clone() const override { return new FillGrid2(*this); }; - virtual ~FillGrid2() {} + virtual ~FillGrid2() = default; virtual Polylines fill_surface(const Surface *surface, const FillParams ¶ms) const override; protected: @@ -41,7 +50,7 @@ class FillTriangles : public FillRectilinear2 { public: virtual Fill* clone() const override { return new FillTriangles(*this); }; - virtual ~FillTriangles() {} + virtual ~FillTriangles() = default; virtual Polylines fill_surface(const Surface *surface, const FillParams ¶ms) const override; protected: @@ -53,7 +62,7 @@ class FillStars : public FillRectilinear2 { public: virtual Fill* clone() const override { return new FillStars(*this); }; - virtual ~FillStars() {} + virtual ~FillStars() = default; virtual Polylines fill_surface(const Surface *surface, const FillParams ¶ms) const override; protected: @@ -65,7 +74,7 @@ class FillCubic : public FillRectilinear2 { public: virtual Fill* clone() const override { return new FillCubic(*this); }; - virtual ~FillCubic() {} + virtual ~FillCubic() = default; virtual Polylines fill_surface(const Surface *surface, const FillParams ¶ms) const override; protected: @@ -78,7 +87,7 @@ class FillRectilinear2Peri : public FillRectilinear2 public: virtual Fill* clone() const override { return new FillRectilinear2Peri(*this); }; - virtual ~FillRectilinear2Peri() {} + virtual ~FillRectilinear2Peri() = default; //virtual Polylines fill_surface(const Surface *surface, const FillParams ¶ms); virtual void fill_surface_extrusion(const Surface *surface, const FillParams ¶ms, ExtrusionEntitiesPtr &out) const override; @@ -89,7 +98,7 @@ class FillScatteredRectilinear : public FillRectilinear2 { public: virtual Fill* clone() const override{ return new FillScatteredRectilinear(*this); }; - virtual ~FillScatteredRectilinear() {} + virtual ~FillScatteredRectilinear() = default; virtual Polylines fill_surface(const Surface *surface, const FillParams ¶ms) const override; protected: @@ -102,7 +111,7 @@ class FillRectilinearSawtooth : public FillRectilinear2 { public: virtual Fill* clone() const override { return new FillRectilinearSawtooth(*this); }; - virtual ~FillRectilinearSawtooth() {} + virtual ~FillRectilinearSawtooth() = default; virtual void fill_surface_extrusion(const Surface *surface, const FillParams ¶ms, ExtrusionEntitiesPtr &out) const override; }; @@ -112,7 +121,7 @@ class FillRectilinear2WGapFill : public FillRectilinear2 public: virtual Fill* clone() const { return new FillRectilinear2WGapFill(*this); }; - virtual ~FillRectilinear2WGapFill() {} + virtual ~FillRectilinear2WGapFill() = default; virtual void fill_surface_extrusion(const Surface *surface, const FillParams ¶ms, ExtrusionEntitiesPtr &out) const override; static void split_polygon_gap_fill(const Surface &surface, const FillParams ¶ms, ExPolygons &rectilinear, ExPolygons &gapfill); }; diff --git a/src/libslic3r/Fill/FillSmooth.cpp b/src/libslic3r/Fill/FillSmooth.cpp index 93f57fe4c..e962523a4 100644 --- a/src/libslic3r/Fill/FillSmooth.cpp +++ b/src/libslic3r/Fill/FillSmooth.cpp @@ -24,7 +24,7 @@ namespace Slic3r { // Save into layer smoothing path. ExtrusionEntityCollection *eec = new ExtrusionEntityCollection(); - eec->no_sort = false; + eec->no_sort = params.monotonous; FillParams params_modifided = params; if (params.config != NULL && idx > 0) params_modifided.density /= (float)params.config->fill_smooth_width.get_abs_value(1); else if (params.config != NULL && idx == 0) params_modifided.density *= 1; @@ -133,14 +133,18 @@ namespace Slic3r { // first infill perform_single_fill(0, *eecroot, *surface, params, volumeToOccupy); + //use monotonous for ironing pass + FillParams monotonous_params = params; + monotonous_params.monotonous = true; + //second infill if (nbPass > 1){ - perform_single_fill(1, *eecroot, *surface, params, volumeToOccupy); + perform_single_fill(1, *eecroot, *surface, monotonous_params, volumeToOccupy); } // third infill if (nbPass > 2){ - perform_single_fill(2, *eecroot, *surface, params, volumeToOccupy); + perform_single_fill(2, *eecroot, *surface, monotonous_params, volumeToOccupy); } if (!eecroot->entities.empty()) diff --git a/src/libslic3r/GCode.cpp b/src/libslic3r/GCode.cpp index c61474fa3..03163ea70 100644 --- a/src/libslic3r/GCode.cpp +++ b/src/libslic3r/GCode.cpp @@ -4501,6 +4501,7 @@ void GCode::ObjectByExtruder::Island::Region::append(const Type type, const Extr // First we append the entities, there are eec->entities.size() of them: //don't do fill->entities because it will discard no_sort, we must use flatten(preserve_ordering = true) + // this method will encapsulate every no_sort into an other collection, so we can get the entities directly. ExtrusionEntitiesPtr entities = eec->flatten(true).entities; size_t old_size = perimeters_or_infills->size(); size_t new_size = old_size + entities.size(); diff --git a/src/libslic3r/PrintConfig.cpp b/src/libslic3r/PrintConfig.cpp index 80b1877a3..91d096068 100644 --- a/src/libslic3r/PrintConfig.cpp +++ b/src/libslic3r/PrintConfig.cpp @@ -597,6 +597,7 @@ void PrintConfigDef::init_fff_params() def->enum_keys_map = &ConfigOptionEnum::get_enum_values(); def->enum_values.push_back("rectilinear"); def->enum_values.push_back("rectilineargapfill"); + def->enum_values.push_back("monotonous"); def->enum_values.push_back("concentric"); def->enum_values.push_back("concentricgapfill"); def->enum_values.push_back("hilbertcurve"); @@ -607,7 +608,8 @@ void PrintConfigDef::init_fff_params() def->enum_values.push_back("smoothtriple"); def->enum_values.push_back("smoothhilbert"); def->enum_labels.push_back(L("Rectilinear")); - def->enum_labels.push_back(L("Rectilinear (filled)")); + def->enum_labels.push_back(L("Monotonous (filled)")); + def->enum_labels.push_back(L("Monotonous")); def->enum_labels.push_back(L("Concentric")); def->enum_labels.push_back(L("Concentric (filled)")); def->enum_labels.push_back(L("Hilbert Curve")); @@ -615,7 +617,7 @@ void PrintConfigDef::init_fff_params() def->enum_labels.push_back(L("Octagram Spiral")); def->enum_labels.push_back(L("Sawtooth")); def->enum_labels.push_back(L("Ironing")); - def->set_default_value(new ConfigOptionEnum(ipRectilinear)); + def->set_default_value(new ConfigOptionEnum(ipMonotonous)); def = this->add("bottom_fill_pattern", coEnum); def->label = L("Bottom"); @@ -627,6 +629,7 @@ void PrintConfigDef::init_fff_params() def->enum_values.push_back("rectilinear"); def->enum_values.push_back("rectilineargapfill"); + def->enum_values.push_back("monotonous"); def->enum_values.push_back("concentric"); def->enum_values.push_back("concentricgapfill"); def->enum_values.push_back("hilbertcurve"); @@ -634,7 +637,8 @@ void PrintConfigDef::init_fff_params() def->enum_values.push_back("octagramspiral"); def->enum_values.push_back("smooth"); def->enum_labels.push_back(L("Rectilinear")); - def->enum_labels.push_back(L("Rectilinear (filled)")); + def->enum_labels.push_back(L("Monotonous (filled)")); + def->enum_labels.push_back(L("Monotonous")); def->enum_labels.push_back(L("Concentric")); def->enum_labels.push_back(L("Concentric (filled)")); def->enum_labels.push_back(L("Hilbert Curve")); @@ -642,7 +646,7 @@ void PrintConfigDef::init_fff_params() def->enum_labels.push_back(L("Octagram Spiral")); def->enum_labels.push_back(L("Ironing")); def->mode = comAdvanced; - def->set_default_value(new ConfigOptionEnum(ipRectilinear)); + def->set_default_value(new ConfigOptionEnum(ipMonotonous)); def = this->add("solid_fill_pattern", coEnum); def->label = L("Solid pattern"); @@ -653,6 +657,7 @@ void PrintConfigDef::init_fff_params() def->enum_values.push_back("smooth"); def->enum_values.push_back("rectilinear"); def->enum_values.push_back("rectilineargapfill"); + def->enum_values.push_back("monotonous"); def->enum_values.push_back("concentric"); def->enum_values.push_back("concentricgapfill"); def->enum_values.push_back("hilbertcurve"); @@ -661,6 +666,7 @@ void PrintConfigDef::init_fff_params() def->enum_labels.push_back(L("Ironing")); def->enum_labels.push_back(L("Rectilinear")); def->enum_labels.push_back(L("Rectilinear (filled)")); + def->enum_labels.push_back(L("Monotonous")); def->enum_labels.push_back(L("Concentric")); def->enum_labels.push_back(L("Concentric (filled)")); def->enum_labels.push_back(L("Hilbert Curve")); @@ -1410,6 +1416,7 @@ void PrintConfigDef::init_fff_params() def->tooltip = L("Fill pattern for general low-density infill."); def->enum_keys_map = &ConfigOptionEnum::get_enum_values(); def->enum_values.push_back("rectilinear"); + def->enum_values.push_back("monotonous"); def->enum_values.push_back("grid"); def->enum_values.push_back("triangles"); def->enum_values.push_back("stars"); @@ -1424,6 +1431,7 @@ void PrintConfigDef::init_fff_params() def->enum_values.push_back("octagramspiral"); def->enum_values.push_back("scatteredrectilinear"); def->enum_labels.push_back(L("Rectilinear")); + def->enum_labels.push_back(L("Monotonous")); def->enum_labels.push_back(L("Grid")); def->enum_labels.push_back(L("Triangles")); def->enum_labels.push_back(L("Stars")); @@ -3136,12 +3144,14 @@ void PrintConfigDef::init_fff_params() def->tooltip = L("Pattern for interface layer."); def->enum_keys_map = &ConfigOptionEnum::get_enum_values(); def->enum_values.push_back("rectilinear"); + def->enum_values.push_back("monotonous"); def->enum_values.push_back("concentric"); def->enum_values.push_back("concentricgapfill"); def->enum_values.push_back("hilbertcurve"); def->enum_values.push_back("sawtooth"); def->enum_values.push_back("smooth"); def->enum_labels.push_back(L("Rectilinear")); + def->enum_labels.push_back(L("Monotonous")); def->enum_labels.push_back(L("Concentric")); def->enum_labels.push_back(L("Concentric (filled)")); def->enum_labels.push_back(L("Hilbert Curve")); diff --git a/src/libslic3r/PrintConfig.hpp b/src/libslic3r/PrintConfig.hpp index 05348c2fd..6afa1be71 100644 --- a/src/libslic3r/PrintConfig.hpp +++ b/src/libslic3r/PrintConfig.hpp @@ -59,7 +59,9 @@ enum PrintHostType { enum InfillPattern { ipRectilinear, ipGrid, ipTriangles, ipStars, ipCubic, ipLine, ipConcentric, ipHoneycomb, ip3DHoneycomb, ipGyroid, ipHilbertCurve, ipArchimedeanChords, ipOctagramSpiral, ipSmooth, ipSmoothHilbert, ipSmoothTriple, - ipRectiWithPerimeter, ipConcentricGapFill, ipScatteredRectilinear, ipSawtooth, ipRectilinearWGapFill, ipCount + ipRectiWithPerimeter, ipConcentricGapFill, ipScatteredRectilinear, ipSawtooth, ipRectilinearWGapFill, + ipMonotonous, + ipCount }; enum SupportMaterialPattern { @@ -165,6 +167,7 @@ template<> inline const t_config_enum_values& ConfigOptionEnum::g static t_config_enum_values keys_map; if (keys_map.empty()) { keys_map["rectilinear"] = ipRectilinear; + keys_map["monotonous"] = ipMonotonous; keys_map["grid"] = ipGrid; keys_map["triangles"] = ipTriangles; keys_map["stars"] = ipStars; @@ -182,8 +185,8 @@ template<> inline const t_config_enum_values& ConfigOptionEnum::g keys_map["smoothtriple"] = ipSmoothTriple; keys_map["smoothhilbert"] = ipSmoothHilbert; keys_map["rectiwithperimeter"] = ipRectiWithPerimeter; - keys_map["scatteredrectilinear"] = ipScatteredRectilinear; - keys_map["rectilineargapfill"] = ipRectilinearWGapFill; + keys_map["scatteredrectilinear"]= ipScatteredRectilinear; + keys_map["rectilineargapfill"] = ipRectilinearWGapFill; keys_map["sawtooth"] = ipSawtooth; } return keys_map; diff --git a/src/libslic3r/PrintObject.cpp b/src/libslic3r/PrintObject.cpp index 5b80a3ee2..555bb4a02 100644 --- a/src/libslic3r/PrintObject.cpp +++ b/src/libslic3r/PrintObject.cpp @@ -3351,6 +3351,7 @@ void PrintObject::combine_infill() // Because fill areas for rectilinear and honeycomb are grown // later to overlap perimeters, we need to counteract that too. ((region->config().fill_pattern == ipRectilinear || + region->config().fill_pattern == ipMonotonous || region->config().fill_pattern == ipGrid || region->config().fill_pattern == ipLine || region->config().fill_pattern == ipHoneycomb) ? 1.5f : 0.5f) * diff --git a/src/libslic3r/ShortestPath.cpp b/src/libslic3r/ShortestPath.cpp index 4a5f453e4..98931bfb8 100644 --- a/src/libslic3r/ShortestPath.cpp +++ b/src/libslic3r/ShortestPath.cpp @@ -58,6 +58,7 @@ std::vector> chain_segments_closest_point(std::vector> 1)); out.emplace_back(next_idx / 2, (next_idx & 1) != 0); //now switch to the other end of the segment this_idx = next_idx ^ 1; diff --git a/src/slic3r/GUI/Field.cpp b/src/slic3r/GUI/Field.cpp index ef5be5877..3abde4cf9 100644 --- a/src/slic3r/GUI/Field.cpp +++ b/src/slic3r/GUI/Field.cpp @@ -987,11 +987,9 @@ void Choice::set_value(const boost::any& value, bool change_event) int val = boost::any_cast(value); if (m_opt_id == "top_fill_pattern" || m_opt_id == "bottom_fill_pattern" || m_opt_id == "solid_fill_pattern" || m_opt_id == "fill_pattern" || m_opt_id == "support_material_interface_pattern" || m_opt_id == "brim_ears_pattern") - { val = idx_from_enum_value(val); - } else if (m_opt_id.compare("perimeter_loop_seam") == 0) { + else if (m_opt_id.compare("perimeter_loop_seam") == 0) val = idx_from_enum_value(val); - } else if (m_opt_id.compare("complete_objects_sort") == 0) val = idx_from_enum_value(val); else if (m_opt_id.compare("gcode_flavor") == 0)