From 5a4ca90594f965b6a5e6af626a5c508185277162 Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Mon, 20 Nov 2023 11:57:44 +0100 Subject: [PATCH 01/48] Fixed basic code compilation warnings --- conanfile.py | 4 ++-- include/plugins/metadata.h | 18 +++++++++++++++--- include/settings/types/LayerIndex.h | 11 +++++++++-- src/TreeSupportTipGenerator.cpp | 2 +- src/progress/Progress.cpp | 4 ++-- 5 files changed, 29 insertions(+), 10 deletions(-) diff --git a/conanfile.py b/conanfile.py index b3e464843a..6b4d5ecf66 100644 --- a/conanfile.py +++ b/conanfile.py @@ -90,8 +90,8 @@ def requirements(self): self.requires("boost/1.82.0") self.requires("rapidjson/1.1.0") self.requires("stb/20200203") - self.requires("spdlog/1.10.0") - self.requires("fmt/9.0.0") + self.requires("spdlog/1.12.0") + self.requires("fmt/10.1.1") self.requires("range-v3/0.12.0") self.requires("scripta/0.1.0@ultimaker/testing") self.requires("neargye-semver/0.3.0") diff --git a/include/plugins/metadata.h b/include/plugins/metadata.h index af3e210342..f7d8036260 100644 --- a/include/plugins/metadata.h +++ b/include/plugins/metadata.h @@ -4,15 +4,17 @@ #ifndef CURAENGINE_INCLUDE_PLUGINS_METADATA_H #define CURAENGINE_INCLUDE_PLUGINS_METADATA_H -#include "cura/plugins/v0/slot_id.pb.h" -#include "plugins/types.h" - #include #include #include #include #include +#include + +#include "cura/plugins/v0/slot_id.pb.h" +#include "plugins/types.h" + namespace cura::plugins { @@ -34,4 +36,14 @@ struct slot_metadata } // namespace cura::plugins +namespace cura::plugins::v0 +{ + +constexpr auto format_as(SlotID id) +{ + return fmt::underlying(id); +} + +} // namespace cura::plugins::v0 + #endif // CURAENGINE_INCLUDE_PLUGINS_METADATA_H diff --git a/include/settings/types/LayerIndex.h b/include/settings/types/LayerIndex.h index b1a7524428..6298555dc0 100644 --- a/include/settings/types/LayerIndex.h +++ b/include/settings/types/LayerIndex.h @@ -4,10 +4,12 @@ #ifndef LAYERINDEX_H #define LAYERINDEX_H -#include "utils/types/generic.h" - #include +#include + +#include "utils/types/generic.h" + namespace cura { @@ -192,6 +194,11 @@ struct LayerIndex } }; +constexpr auto format_as(LayerIndex index) +{ + return index.value; +} + } // namespace cura namespace std diff --git a/src/TreeSupportTipGenerator.cpp b/src/TreeSupportTipGenerator.cpp index 094a819544..af313019d8 100644 --- a/src/TreeSupportTipGenerator.cpp +++ b/src/TreeSupportTipGenerator.cpp @@ -175,7 +175,7 @@ Polygons TreeSupportTipGenerator::convertInternalToLines(std::vector)> TreeSupportTipGenerator::getEvaluatePointForNextLayerFunction(size_t current_layer) { - std::function)> evaluatePoint = [=](std::pair p) + std::function)> evaluatePoint = [this, current_layer](std::pair p) { if (config.support_rest_preference != RestPreference::GRACEFUL && ! volumes_ diff --git a/src/progress/Progress.cpp b/src/progress/Progress.cpp index be6a688813..e0cafbec02 100644 --- a/src/progress/Progress.cpp +++ b/src/progress/Progress.cpp @@ -76,13 +76,13 @@ void Progress::messageProgressLayer(LayerIndex layer_nr, size_t total_layers, do { if (first_skipped_layer) { - spdlog::info("Skipped time reporting for layers [{}...{}]", first_skipped_layer.value().value, layer_nr.value); + spdlog::info("Skipped time reporting for layers [{}...{}]", first_skipped_layer.value(), layer_nr); first_skipped_layer.reset(); } messageProgress(Stage::EXPORT, std::max(layer_nr.value, LayerIndex::value_type(0)) + 1, total_layers); - spdlog::info("┌ Layer export [{}] accomplished in {:03.3f}s", layer_nr.value, total_time); + spdlog::info("┌ Layer export [{}] accomplished in {:03.3f}s", layer_nr, total_time); size_t padding = 0; auto iterator_max_size = std::max_element( From 853d47c2622202753e2c88edcf5435b896dee605 Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Mon, 20 Nov 2023 15:18:44 +0100 Subject: [PATCH 02/48] Fixed many more warnings --- include/BeadingStrategy/BeadingStrategy.h | 7 +- include/settings/types/Angle.h | 85 ++++++----- include/slicer.h | 167 ++++++++++------------ include/utils/Coord_t.h | 19 +-- include/utils/IntPoint.h | 65 +++++---- include/utils/Point3.h | 154 +++++++++++--------- include/utils/VoxelUtils.h | 91 ++++++------ include/utils/actions/smooth.h | 22 +-- include/utils/floatpoint.h | 127 ++++++++++------ include/utils/math.h | 43 ++---- include/utils/polygonUtils.h | 59 +++++--- src/FffGcodeWriter.cpp | 16 +-- src/FffPolygonGenerator.cpp | 6 +- src/InterlockingGenerator.cpp | 28 ++-- src/LayerPlan.cpp | 6 +- src/MeshGroup.cpp | 20 +-- src/Mold.cpp | 2 +- src/PrimeTower.cpp | 4 +- src/SkeletalTrapezoidation.cpp | 4 +- src/TreeSupportTipGenerator.cpp | 6 +- src/gcodeExport.cpp | 84 +++++------ src/infill.cpp | 2 +- src/infill/GyroidInfill.cpp | 30 ++-- src/infill/ImageBasedDensityProvider.cpp | 36 ++--- src/infill/SierpinskiFill.cpp | 36 +++-- src/infill/SierpinskiFillProvider.cpp | 5 +- src/infill/SubDivCube.cpp | 26 ++-- src/mesh.cpp | 18 ++- src/pathPlanning/Comb.cpp | 20 +-- src/settings/AdaptiveLayerHeights.cpp | 10 +- src/settings/Settings.cpp | 2 +- src/sliceDataStorage.cpp | 14 +- src/slicer.cpp | 124 ++++++++-------- src/support.cpp | 8 +- src/utils/AABB3D.cpp | 60 ++++---- src/utils/ExtrusionSegment.cpp | 28 ++-- src/utils/FMatrix4x3.cpp | 34 +++-- src/utils/LinearAlg2D.cpp | 4 +- src/utils/Point3.cpp | 66 ++++----- src/utils/ToolpathVisualizer.cpp | 77 +++++----- src/utils/VoxelUtils.cpp | 99 ++++++------- src/utils/polygon.cpp | 6 +- src/utils/polygonUtils.cpp | 91 ++++++------ tests/PathOrderMonotonicTest.cpp | 4 +- tests/arcus/ArcusCommunicationTest.cpp | 2 +- tests/integration/SlicePhaseTest.cpp | 4 +- tests/settings/SettingsTest.cpp | 6 +- tests/utils/LinearAlg2DTest.cpp | 2 +- tests/utils/PolygonTest.cpp | 2 +- tests/utils/SimplifyTest.cpp | 2 +- tests/utils/SmoothTest.cpp | 2 +- 51 files changed, 967 insertions(+), 868 deletions(-) diff --git a/include/BeadingStrategy/BeadingStrategy.h b/include/BeadingStrategy/BeadingStrategy.h index 5f2625bac8..ee2d2635e6 100644 --- a/include/BeadingStrategy/BeadingStrategy.h +++ b/include/BeadingStrategy/BeadingStrategy.h @@ -36,7 +36,12 @@ class BeadingStrategy coord_t left_over; //! The distance not covered by any bead; gap area. }; - BeadingStrategy(coord_t optimal_width, Ratio wall_split_middle_threshold, Ratio wall_add_middle_threshold, coord_t default_transition_length, float transitioning_angle = pi_div(3)); + BeadingStrategy( + coord_t optimal_width, + Ratio wall_split_middle_threshold, + Ratio wall_add_middle_threshold, + coord_t default_transition_length, + float transitioning_angle = std::numbers::pi_v / 3.0); BeadingStrategy(const BeadingStrategy& other); diff --git a/include/settings/types/Angle.h b/include/settings/types/Angle.h index ba79710ed4..4b4ed3de5e 100644 --- a/include/settings/types/Angle.h +++ b/include/settings/types/Angle.h @@ -1,17 +1,18 @@ -//Copyright (c) 2021 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2021 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef ANGLE_H #define ANGLE_H #include //For fmod. + #include "../../utils/math.h" //For M_PI. #define TAU (2.0 * M_PI) namespace cura { -//AngleDegrees and AngleRadians classes defined together here interweaved, to resolve their interdependencies. +// AngleDegrees and AngleRadians classes defined together here interweaved, to resolve their interdependencies. class AngleRadians; /* @@ -26,7 +27,10 @@ class AngleDegrees /* * \brief Default constructor setting the angle to 0. */ - AngleDegrees() : value(0.0) {}; + AngleDegrees() + : value_(0.0) + { + } /* * \brief Converts radians to degrees. @@ -36,45 +40,48 @@ class AngleDegrees /* * \brief Casts a double to an AngleDegrees instance. */ - AngleDegrees(double value) : value(std::fmod(std::fmod(value, 360) + 360, 360)) {}; + AngleDegrees(double value) + : value_(std::fmod(std::fmod(value, 360) + 360, 360)) + { + } /* * \brief Casts the AngleDegrees instance to a double. */ operator double() const { - return value; + return value_; } /* * Some operators implementing the clock arithmetic. */ - AngleDegrees operator +(const AngleDegrees& other) const + AngleDegrees operator+(const AngleDegrees& other) const { - return std::fmod(std::fmod(value + other.value, 360) + 360, 360); + return std::fmod(std::fmod(value_ + other.value_, 360) + 360, 360); } template - AngleDegrees operator +(const T& other) const + AngleDegrees operator+(const T& other) const { return operator+(AngleDegrees(static_cast(other))); } - AngleDegrees& operator +=(const AngleDegrees& other) + AngleDegrees& operator+=(const AngleDegrees& other) { - value = std::fmod(std::fmod(value + other.value, 360) + 360, 360); + value_ = std::fmod(std::fmod(value_ + other.value_, 360) + 360, 360); return *this; } - AngleDegrees operator -(const AngleDegrees& other) const + AngleDegrees operator-(const AngleDegrees& other) const { - return std::fmod(std::fmod(value - other.value, 360) + 360, 360); + return std::fmod(std::fmod(value_ - other.value_, 360) + 360, 360); } template - AngleDegrees operator -(const T& other) const + AngleDegrees operator-(const T& other) const { return operator-(AngleDegrees(static_cast(other))); } - AngleDegrees& operator -=(const AngleDegrees& other) + AngleDegrees& operator-=(const AngleDegrees& other) { - value = std::fmod(std::fmod(value - other.value, 360) + 360, 360); + value_ = std::fmod(std::fmod(value_ - other.value_, 360) + 360, 360); return *this; } @@ -83,7 +90,7 @@ class AngleDegrees * * This value should always be between 0 and 360. */ - double value = 0; + double value_ = 0; }; /* @@ -98,7 +105,10 @@ class AngleRadians /* * \brief Default constructor setting the angle to 0. */ - AngleRadians() : value(0.0) {}; + AngleRadians() + : value_(0.0) + { + } /*! * \brief Converts an angle from degrees into radians. @@ -108,35 +118,38 @@ class AngleRadians /* * \brief Translate the double value in degrees to an AngleRadians instance. */ - AngleRadians(double value) : value(std::fmod(std::fmod(value, TAU) + TAU, TAU)) {}; + AngleRadians(double value) + : value_(std::fmod(std::fmod(value, TAU) + TAU, TAU)) + { + } /* * \brief Casts the AngleRadians instance to a double. */ operator double() const { - return value; + return value_; } /* * Some operators implementing the clock arithmetic. */ - AngleRadians operator +(const AngleRadians& other) const + AngleRadians operator+(const AngleRadians& other) const { - return std::fmod(std::fmod(value + other.value, TAU) + TAU, TAU); + return std::fmod(std::fmod(value_ + other.value_, TAU) + TAU, TAU); } - AngleRadians& operator +=(const AngleRadians& other) + AngleRadians& operator+=(const AngleRadians& other) { - value = std::fmod(std::fmod(value + other.value, TAU) + TAU, TAU); + value_ = std::fmod(std::fmod(value_ + other.value_, TAU) + TAU, TAU); return *this; } - AngleRadians operator -(const AngleRadians& other) const + AngleRadians operator-(const AngleRadians& other) const { - return std::fmod(std::fmod(value - other.value, TAU) + TAU, TAU); + return std::fmod(std::fmod(value_ - other.value_, TAU) + TAU, TAU); } - AngleRadians& operator -=(const AngleRadians& other) + AngleRadians& operator-=(const AngleRadians& other) { - value = std::fmod(std::fmod(value - other.value, TAU) + TAU, TAU); + value_ = std::fmod(std::fmod(value_ - other.value_, TAU) + TAU, TAU); return *this; } @@ -145,12 +158,18 @@ class AngleRadians * * This value should always be between 0 and 2 * pi. */ - double value = 0; + double value_ = 0; }; -inline AngleDegrees::AngleDegrees(const AngleRadians& value) : value(value * 360 / TAU) {} -inline AngleRadians::AngleRadians(const AngleDegrees& value) : value(double(value) * TAU / 360.0) {} - +inline AngleDegrees::AngleDegrees(const AngleRadians& value) + : value_(value * 360 / TAU) +{ } +inline AngleRadians::AngleRadians(const AngleDegrees& value) + : value_(double(value) * TAU / 360.0) +{ +} + +} // namespace cura -#endif //ANGLE_H \ No newline at end of file +#endif // ANGLE_H diff --git a/include/slicer.h b/include/slicer.h index a5de21fdf5..789da58a8c 100644 --- a/include/slicer.h +++ b/include/slicer.h @@ -1,13 +1,15 @@ -//Copyright (c) 2018 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2018 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef SLICER_H #define SLICER_H +#include #include #include -#include "utils/polygon.h" + #include "settings/EnumSettings.h" +#include "utils/polygon.h" /* The Slicer creates layers of polygons from an optimized 3D model. @@ -34,19 +36,20 @@ class SlicerSegment }; class ClosePolygonResult -{ //The result of trying to find a point on a closed polygon line. This gives back the point index, the polygon index, and the point of the connection. - //The line on which the point lays is between pointIdx-1 and pointIdx +{ // The result of trying to find a point on a closed polygon line. This gives back the point index, the polygon index, and the point of the connection. + // The line on which the point lays is between pointIdx-1 and pointIdx public: - int polygonIdx = -1; - size_t pointIdx = -1; + size_t polygonIdx = 0; + size_t pointIdx = 0; }; + class GapCloserResult { public: - coord_t len = -1; - int polygonIdx = -1; - size_t pointIdxA = -1; - size_t pointIdxB = -1; + coord_t len = 0; + size_t polygonIdx = 0; + size_t pointIdxA = 0; + size_t pointIdxB = 0; bool AtoB = false; }; @@ -112,9 +115,9 @@ class SlicerLayer */ void stitch(Polygons& open_polylines); - GapCloserResult findPolygonGapCloser(Point ip0, Point ip1); + std::optional findPolygonGapCloser(Point ip0, Point ip1); - ClosePolygonResult findPolygonPointClosestTo(Point input); + std::optional findPolygonPointClosestTo(Point input); /*! * Try to close up polylines into polygons while they have large gaps in them. @@ -151,7 +154,8 @@ class SlicerLayer /*! Constructor leaving uninitialized. */ Terminus() - {} + { + } /*! Constructor from Index representation. * @@ -159,7 +163,7 @@ class SlicerLayer */ Terminus(Index idx) { - m_idx = idx; + idx_ = idx; } /*! Constuctor from the polyline index and which end of the polyline. @@ -168,19 +172,19 @@ class SlicerLayer */ Terminus(size_t polyline_idx, bool is_end) { - m_idx = polyline_idx * 2 + (is_end ? 1 : 0); + idx_ = polyline_idx * 2 + (is_end ? 1 : 0); } /*! Gets the polyline index for this Terminus. */ size_t getPolylineIdx() const { - return m_idx / 2; + return idx_ / 2; } /*! Gets whether this Terminus represents the end point of the polyline. */ bool isEnd() const { - return (m_idx & 1) == 1; + return (idx_ & 1) == 1; } /*! Gets the Index representation of this Terminus. @@ -201,7 +205,7 @@ class SlicerLayer */ Index asIndex() const { - return m_idx; + return idx_; } /*! Calculates the Terminus end Index from the polyline vector end index. @@ -213,23 +217,23 @@ class SlicerLayer */ static Index endIndexFromPolylineEndIndex(unsigned int polyline_end_idx) { - return polyline_end_idx*2; + return polyline_end_idx * 2; } /*! Tests for equality. - * - * Two Terminus are equal if they return the same results for - * \ref getPolylineIdx() and \ref isEnd(). - */ - bool operator==(const Terminus &other) + * + * Two Terminus are equal if they return the same results for + * \ref getPolylineIdx() and \ref isEnd(). + */ + bool operator==(const Terminus& other) { - return m_idx == other.m_idx; + return idx_ == other.idx_; } /*! Tests for inequality. */ - bool operator!=(const Terminus &other) + bool operator!=(const Terminus& other) { - return m_idx != other.m_idx; + return idx_ != other.idx_; } private: @@ -237,7 +241,7 @@ class SlicerLayer * * The polyline_idx and end flags are calculated from this on demand. */ - Index m_idx = -1; + Index idx_ = std::numeric_limits::max(); }; /*! @@ -276,8 +280,7 @@ class SlicerLayer bool in_order() const { // in order if using back of line 0 and front of line 1 - return terminus_0.isEnd() && - !terminus_1.isEnd(); + return terminus_0.isEnd() && ! terminus_1.isEnd(); } /*! Orders PossibleStitch by goodness. @@ -285,8 +288,8 @@ class SlicerLayer * Better PossibleStitch are > then worse PossibleStitch. * priority_queue will give greatest first so greatest * must be most desirable stitch - */ - bool operator<(const PossibleStitch &other) const; + */ + bool operator<(const PossibleStitch& other) const; }; /*! @@ -321,7 +324,7 @@ class SlicerLayer * \return The current Terminus location or INVALID_TERMINUS * if the old endpoint is no longer an endpoint. */ - Terminus getCurFromOld(const Terminus &old) const + Terminus getCurFromOld(const Terminus& old) const { return m_terminus_old_to_cur_map[old.asIndex()]; } @@ -334,7 +337,7 @@ class SlicerLayer * INVALID_TERMINUS if the old Terminus location was * removed (used to form a Polygon). */ - Terminus getOldFromCur(const Terminus &cur) const + Terminus getOldFromCur(const Terminus& cur) const { return m_terminus_cur_to_old_map[cur.asIndex()]; } @@ -344,7 +347,7 @@ class SlicerLayer * This marks the current Terminus as being removed from the * polyline vector. */ - void markRemoved(const Terminus &cur) + void markRemoved(const Terminus& cur) { Terminus old = getOldFromCur(cur); m_terminus_old_to_cur_map[old.asIndex()] = Terminus::INVALID_TERMINUS; @@ -379,10 +382,7 @@ class SlicerLayer * \param removed_cur_terms The Terminus locations that will * be removed after the update. */ - void updateMap(size_t num_terms, - const Terminus *cur_terms, const Terminus *next_terms, - size_t num_removed_terms, - const Terminus *removed_cur_terms); + void updateMap(size_t num_terms, const Terminus* cur_terms, const Terminus* next_terms, size_t num_removed_terms, const Terminus* removed_cur_terms); private: /*! map from old terminus location to current terminus location */ @@ -398,8 +398,7 @@ class SlicerLayer * \param[in] face_idx The index of the face that might have generated a continuation segment. * \param[in] start_segment_idx The index of the segment that started this polyline. */ - int tryFaceNextSegmentIdx(const SlicerSegment& segment, - const int face_idx, const size_t start_segment_idx) const; + int tryFaceNextSegmentIdx(const SlicerSegment& segment, const int face_idx, const size_t start_segment_idx) const; /*! * Find possible allowed stitches in goodness order. @@ -418,9 +417,7 @@ class SlicerLayer * the order of a polyline. * \return The stitches that are allowed in order from best to worst. */ - std::priority_queue findPossibleStitches( - const Polygons& open_polylines, coord_t max_dist, coord_t cell_size, - bool allow_reverse) const; + std::priority_queue findPossibleStitches(const Polygons& open_polylines, coord_t max_dist, coord_t cell_size, bool allow_reverse) const; /*! Plans the best way to perform a stitch. * @@ -438,9 +435,7 @@ class SlicerLayer * \param[in,out] terminus_1 the Terminus on polyline_1 to join at. * \param[out] reverse Whether the polylines need to be reversed. */ - void planPolylineStitch(const Polygons& open_polylines, - Terminus& terminus_0, Terminus& terminus_1, - bool reverse[2]) const; + void planPolylineStitch(const Polygons& open_polylines, Terminus& terminus_0, Terminus& terminus_1, bool reverse[2]) const; /*! Joins polyline_1 onto polyline_0. * @@ -458,8 +453,7 @@ class SlicerLayer * polyline_0 and reverse[1] indicates whether to reverse * polyline_1 */ - void joinPolylines(PolygonRef& polyline_0, PolygonRef& polyline_1, - const bool reverse[2]) const; + void joinPolylines(PolygonRef& polyline_0, PolygonRef& polyline_1, const bool reverse[2]) const; /*! * Connecting polylines that are not closed yet. @@ -479,9 +473,7 @@ class SlicerLayer * \param[in] allow_reverse If true, then this function is allowed * to reverse edge directions to merge polylines. */ - void connectOpenPolylinesImpl(Polygons& open_polylines, - coord_t max_dist, coord_t cell_size, - bool allow_reverse); + void connectOpenPolylinesImpl(Polygons& open_polylines, coord_t max_dist, coord_t cell_size, bool allow_reverse); }; class Slicer @@ -491,11 +483,10 @@ class Slicer const Mesh* mesh = nullptr; //!< The sliced mesh - Slicer(Mesh* mesh, const coord_t thickness, const size_t slice_layer_count, bool use_variable_layer_heights, std::vector *adaptive_layers); + Slicer(Mesh* mesh, const coord_t thickness, const size_t slice_layer_count, bool use_variable_layer_heights, std::vector* adaptive_layers); private: - /*! * \brief Linear interpolation between coordinates of a line. * @@ -525,48 +516,46 @@ class Slicer static SlicerSegment project2D(const Point3& p0, const Point3& p1, const Point3& p2, const coord_t z); /*! Creates an array of "z bounding boxes" for each face. - * \param[in] mesh The mesh which is analyzed. - * \return z heights aka z bounding boxes of the faces. - */ - static std::vector> buildZHeightsForFaces(const Mesh &mesh); + * \param[in] mesh The mesh which is analyzed. + * \return z heights aka z bounding boxes of the faces. + */ + static std::vector> buildZHeightsForFaces(const Mesh& mesh); /*! Creates the polygons in layers. - * \param[in] mesh The mesh which is analyzed. - * \param[in] slicing_tolerance The way the slicing tolerance should be applied (MIDDLE/INCLUSIVE/EXCLUSIVE). - * \param[in, out] layers The polygon are created here. - */ + * \param[in] mesh The mesh which is analyzed. + * \param[in] slicing_tolerance The way the slicing tolerance should be applied (MIDDLE/INCLUSIVE/EXCLUSIVE). + * \param[in, out] layers The polygon are created here. + */ static void makePolygons(Mesh& mesh, SlicingTolerance slicing_tolerance, std::vector& layers); /*! Creates a vector of layers and set their z value. - * \param[in] mesh The mesh which is analyzed. - * \param[in] slice_layer_count The amount of layers which shall be sliced. - * \param[in] slicing_tolerance The way the slicing tolerance should be applied (MIDDLE/INCLUSIVE/EXCLUSIVE). - * \param[in] initial_layer_thickness Thickness of the first layer. - * \param[in] thickness Thickness of the layers (apart the first one). - * \param[in] use_variable_layer_heights Shall we use adaptive layer heights. - * \param[in] adaptive_layers Adaptive layers (if use_variable_layer_heights). - * \return layers with set z values. - */ - static std::vector buildLayersWithHeight(size_t slice_layer_count, SlicingTolerance slicing_tolerance, - coord_t initial_layer_thickness, coord_t thickness, bool use_variable_layer_heights, + * \param[in] mesh The mesh which is analyzed. + * \param[in] slice_layer_count The amount of layers which shall be sliced. + * \param[in] slicing_tolerance The way the slicing tolerance should be applied (MIDDLE/INCLUSIVE/EXCLUSIVE). + * \param[in] initial_layer_thickness Thickness of the first layer. + * \param[in] thickness Thickness of the layers (apart the first one). + * \param[in] use_variable_layer_heights Shall we use adaptive layer heights. + * \param[in] adaptive_layers Adaptive layers (if use_variable_layer_heights). + * \return layers with set z values. + */ + static std::vector buildLayersWithHeight( + size_t slice_layer_count, + SlicingTolerance slicing_tolerance, + coord_t initial_layer_thickness, + coord_t thickness, + bool use_variable_layer_heights, const std::vector* adaptive_layers); /*! Creates the segments and write them into the layers. - * \param[in] mesh The mesh which is analyzed. - * \param[in] zbboxes The z part of the bounding boxes of the faces of the mesh. - * \param[in] slicing_tolderance Slicing tolerance in order to figure out what happens when vertices are exactly on the slicing boundary. - * \param[in, out] layers The segments are created here. - */ - static void buildSegments - ( - const Mesh& mesh, - const std::vector> &zbboxes, - const SlicingTolerance& slicing_tolerance, - std::vector& layers - ); - + * \param[in] mesh The mesh which is analyzed. + * \param[in] zbboxes The z part of the bounding boxes of the faces of the mesh. + * \param[in] slicing_tolderance Slicing tolerance in order to figure out what happens when vertices are exactly on the slicing boundary. + * \param[in, out] layers The segments are created here. + */ + static void + buildSegments(const Mesh& mesh, const std::vector>& zbboxes, const SlicingTolerance& slicing_tolerance, std::vector& layers); }; -}//namespace cura +} // namespace cura -#endif//SLICER_H +#endif // SLICER_H diff --git a/include/utils/Coord_t.h b/include/utils/Coord_t.h index 910efb941e..bd8f3e088b 100644 --- a/include/utils/Coord_t.h +++ b/include/utils/Coord_t.h @@ -1,11 +1,11 @@ -//Copyright (c) 2018 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2018 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef UTILS_COORD_T_H #define UTILS_COORD_T_H -//Include Clipper to get the ClipperLib::IntPoint definition, which we reuse as Point definition. +// Include Clipper to get the ClipperLib::IntPoint definition, which we reuse as Point definition. #include namespace cura @@ -13,16 +13,19 @@ namespace cura using coord_t = ClipperLib::cInt; -static inline coord_t operator "" _mu(unsigned long long i) { return i; }; +static inline coord_t operator"" _mu(unsigned long long i) +{ + return static_cast(i); +}; #define INT2MM(n) (static_cast(n) / 1000.0) #define INT2MM2(n) (static_cast(n) / 1000000.0) -#define MM2INT(n) (static_cast((n) * 1000 + 0.5 * (((n) > 0) - ((n) < 0)))) -#define MM2_2INT(n) (static_cast((n) * 1000000 + 0.5 * (((n) > 0) - ((n) < 0)))) -#define MM3_2INT(n) (static_cast((n) * 1000000000 + 0.5 * (((n) > 0) - ((n) < 0)))) +#define MM2INT(n) (static_cast((n)*1000 + 0.5 * (((n) > 0) - ((n) < 0)))) +#define MM2_2INT(n) (static_cast((n)*1000000 + 0.5 * (((n) > 0) - ((n) < 0)))) +#define MM3_2INT(n) (static_cast((n)*1000000000 + 0.5 * (((n) > 0) - ((n) < 0)))) #define INT2MICRON(n) ((n) / 1) -#define MICRON2INT(n) ((n) * 1) +#define MICRON2INT(n) ((n)*1) } // namespace cura diff --git a/include/utils/IntPoint.h b/include/utils/IntPoint.h index ce5cbc9785..7649241e82 100644 --- a/include/utils/IntPoint.h +++ b/include/utils/IntPoint.h @@ -11,9 +11,6 @@ Integer points are used to avoid floating point rounding errors, and because Cli #define INLINE static inline // Include Clipper to get the ClipperLib::IntPoint definition, which we reuse as Point definition. -#include "../utils/math.h" // for M_PI. Use relative path to avoid pulling -#include "Point3.h" //For applying Point3Matrices. - #include #include // for hash function object #include // auto-serialization / auto-toString() @@ -21,6 +18,9 @@ Integer points are used to avoid floating point rounding errors, and because Cli #include #include +#include "../utils/math.h" // for M_PI. Use relative path to avoid pulling +#include "Point3.h" //For applying Point3Matrices. + #ifdef __GNUC__ #define DEPRECATED(func) func __attribute__((deprecated)) #elif defined(_MSC_VER) @@ -62,7 +62,7 @@ INLINE Point operator*(const Point& p0, const coord_t i) template::value, T>::type> // Use only for numeric types. INLINE Point operator*(const Point& p0, const T i) { - return Point(std::llrint(p0.X * i), std::llrint(p0.Y * i)); + return Point(std::llrint(static_cast(p0.X) * i), std::llrint(static_cast(p0.Y) * i)); } template::value, T>::type> // Use only for numeric types. INLINE Point operator*(const T i, const Point& p0) @@ -141,7 +141,7 @@ INLINE bool shorterThan(const Point& p0, const coord_t len) INLINE coord_t vSize(const Point& p0) { - return sqrt(vSize2(p0)); + return std::llrint(sqrt(static_cast(vSize2(p0)))); } INLINE double vSizeMM(const Point& p0) @@ -168,7 +168,9 @@ INLINE Point rotate(const Point& p0, double angle) { const double cos_component = std::cos(angle); const double sin_component = std::sin(angle); - return Point(cos_component * p0.X - sin_component * p0.Y, sin_component * p0.X + cos_component * p0.Y); + const double x = static_cast(p0.X); + const double y = static_cast(p0.Y); + return Point(std::llrint(cos_component * x - sin_component * y), std::llrint(sin_component * x + cos_component * y)); } INLINE coord_t dot(const Point& p0, const Point& p1) @@ -186,7 +188,7 @@ INLINE int angle(const Point& p) double angle = std::atan2(p.X, p.Y) / M_PI * 180.0; if (angle < 0.0) angle += 360.0; - return angle; + return static_cast(std::lrint(angle)); } // Identity function, used to be able to make templated algorithms where the input is sometimes points, sometimes things that contain or can be converted to points. @@ -206,9 +208,9 @@ struct hash { static int prime = 31; int result = 89; - result = result * prime + pp.X; - result = result * prime + pp.Y; - return result; + result = static_cast(result * prime + pp.X); + result = static_cast(result * prime + pp.Y); + return static_cast(result); } }; } // namespace std @@ -240,8 +242,8 @@ class PointMatrix PointMatrix(const Point p) { - matrix[0] = p.X; - matrix[1] = p.Y; + matrix[0] = static_cast(p.X); + matrix[1] = static_cast(p.Y); double f = sqrt((matrix[0] * matrix[0]) + (matrix[1] * matrix[1])); matrix[0] /= f; matrix[1] /= f; @@ -259,7 +261,9 @@ class PointMatrix Point apply(const Point p) const { - return Point(p.X * matrix[0] + p.Y * matrix[1], p.X * matrix[2] + p.Y * matrix[3]); + const double x = static_cast(p.X); + const double y = static_cast(p.Y); + return Point(std::llrint(x * matrix[0] + y * matrix[1]), std::llrint(x * matrix[2] + y * matrix[3])); } /*! @@ -267,7 +271,9 @@ class PointMatrix */ Point unapply(const Point p) const { - return Point(p.X * matrix[0] + p.Y * matrix[2], p.X * matrix[1] + p.Y * matrix[3]); + const double x = static_cast(p.X); + const double y = static_cast(p.Y); + return Point(std::llrint(x * matrix[0] + y * matrix[2]), std::llrint(x * matrix[1] + y * matrix[3])); } PointMatrix inverse() const @@ -319,10 +325,13 @@ class Point3Matrix Point3 apply(const Point3 p) const { + const double x = static_cast(p.x_); + const double y = static_cast(p.y_); + const double z = static_cast(p.z_); return Point3( - std::llrint(p.x * matrix[0] + p.y * matrix[1] + p.z * matrix[2]), - std::llrint(p.x * matrix[3] + p.y * matrix[4] + p.z * matrix[5]), - std::llrint(p.x * matrix[6] + p.y * matrix[7] + p.z * matrix[8])); + std::llrint(x * matrix[0] + y * matrix[1] + z * matrix[2]), + std::llrint(x * matrix[3] + y * matrix[4] + z * matrix[5]), + std::llrint(x * matrix[6] + y * matrix[7] + z * matrix[8])); } /*! @@ -331,14 +340,14 @@ class Point3Matrix Point apply(const Point p) const { Point3 result = apply(Point3(p.X, p.Y, 1)); - return Point(result.x / result.z, result.y / result.z); + return Point(result.x_ / result.z_, result.y_ / result.z_); } static Point3Matrix translate(const Point p) { Point3Matrix ret; // uniform matrix - ret.matrix[2] = p.X; - ret.matrix[5] = p.Y; + ret.matrix[2] = static_cast(p.X); + ret.matrix[5] = static_cast(p.Y); return ret; } @@ -363,35 +372,35 @@ class Point3Matrix inline Point3 operator+(const Point3& p3, const Point& p2) { - return Point3(p3.x + p2.X, p3.y + p2.Y, p3.z); + return Point3(p3.x_ + p2.X, p3.y_ + p2.Y, p3.z_); } inline Point3& operator+=(Point3& p3, const Point& p2) { - p3.x += p2.X; - p3.y += p2.Y; + p3.x_ += p2.X; + p3.y_ += p2.Y; return p3; } inline Point operator+(const Point& p2, const Point3& p3) { - return Point(p3.x + p2.X, p3.y + p2.Y); + return Point(p3.x_ + p2.X, p3.y_ + p2.Y); } inline Point3 operator-(const Point3& p3, const Point& p2) { - return Point3(p3.x - p2.X, p3.y - p2.Y, p3.z); + return Point3(p3.x_ - p2.X, p3.y_ - p2.Y, p3.z_); } inline Point3& operator-=(Point3& p3, const Point& p2) { - p3.x -= p2.X; - p3.y -= p2.Y; + p3.x_ -= p2.X; + p3.y_ -= p2.Y; return p3; } inline Point operator-(const Point& p2, const Point3& p3) { - return Point(p2.X - p3.x, p2.Y - p3.y); + return Point(p2.X - p3.x_, p2.Y - p3.y_); } } // namespace cura diff --git a/include/utils/Point3.h b/include/utils/Point3.h index 6dc18c27b8..54c3819e22 100644 --- a/include/utils/Point3.h +++ b/include/utils/Point3.h @@ -1,15 +1,15 @@ -//Copyright (c) 2018 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2018 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef UTILS_POINT3_H #define UTILS_POINT3_H +#include #include //For sqrt. #include //Auto-serialization. #include //For numeric_limits::min and max. #include //For int32_t and int64_t. #include // for operations on any arithmetic number type -#include #include "Coord_t.h" @@ -20,49 +20,56 @@ namespace cura class Point3 { public: - coord_t x,y,z; - Point3() {} - Point3(const coord_t _x, const coord_t _y, const coord_t _z): x(_x), y(_y), z(_z) {} - - Point3 operator +(const Point3& p) const; - Point3 operator -() const; - Point3 operator -(const Point3& p) const; - Point3 operator *(const Point3& p) const; //!< Element-wise multiplication. For dot product, use .dot()! - Point3 operator /(const Point3& p) const; + coord_t x_, y_, z_; + Point3() + { + } + Point3(const coord_t x, const coord_t y, const coord_t z) + : x_(x) + , y_(y) + , z_(z) + { + } + + Point3 operator+(const Point3& p) const; + Point3 operator-() const; + Point3 operator-(const Point3& p) const; + Point3 operator*(const Point3& p) const; //!< Element-wise multiplication. For dot product, use .dot()! + Point3 operator/(const Point3& p) const; template::value, num_t>::type> - Point3 operator *(const num_t i) const + Point3 operator*(const num_t i) const { - return Point3(x * i, y * i, z * i); + return Point3(std::llround(static_cast(x_) * i), std::llround(static_cast(y_) * i), std::llround(static_cast(z_) * i)); } template::value, num_t>::type> - Point3 operator /(const num_t i) const + Point3 operator/(const num_t i) const { - return Point3(x / i, y / i, z / i); + return Point3(x_ / i, y_ / i, z_ / i); } template::value, num_t>::type> - Point3 operator %(const num_t i) const + Point3 operator%(const num_t i) const { - return Point3(x % i, y % i, z % i); + return Point3(x_ % i, y_ % i, z_ % i); } - Point3& operator +=(const Point3& p); - Point3& operator -=(const Point3& p); - Point3& operator *=(const Point3& p); - Point3& operator /=(const Point3& p); + Point3& operator+=(const Point3& p); + Point3& operator-=(const Point3& p); + Point3& operator*=(const Point3& p); + Point3& operator/=(const Point3& p); template::value, num_t>::type> - Point3& operator *=(const num_t i) + Point3& operator*=(const num_t i) { - x *= i; - y *= i; - z *= i; + x_ *= i; + y_ *= i; + z_ *= i; return *this; } template::value, num_t>::type> - Point3& operator /=(const num_t i) + Point3& operator/=(const num_t i) { - x /= i; - y /= i; - z /= i; + x_ /= i; + y_ /= i; + z_ /= i; return *this; } @@ -71,68 +78,71 @@ class Point3 template - friend - std::basic_ostream& - operator <<(std::basic_ostream& os, const Point3& p) + friend std::basic_ostream& operator<<(std::basic_ostream& os, const Point3& p) { - return os << "(" << p.x << ", " << p.y << ", " << p.z << ")"; + return os << "(" << p.x_ << ", " << p.y_ << ", " << p.z_ << ")"; } coord_t max() const { - if (x > y && x > z) return x; - if (y > z) return y; - return z; + if (x_ > y_ && x_ > z_) + return x_; + if (y_ > z_) + return y_; + return z_; } bool testLength(coord_t len) const { - if (x > len || x < -len) + if (x_ > len || x_ < -len) return false; - if (y > len || y < -len) + if (y_ > len || y_ < -len) return false; - if (z > len || z < -len) + if (z_ > len || z_ < -len) return false; - return vSize2() <= len*len; + return vSize2() <= len * len; } coord_t vSize2() const { - return x * x + y * y + z * z; + return x_ * x_ + y_ * y_ + z_ * z_; } coord_t vSize() const { - return sqrt(vSize2()); + return std::llrint(sqrt(static_cast(vSize2()))); } - + double vSizeMM() const { - double fx = INT2MM(x); - double fy = INT2MM(y); - double fz = INT2MM(z); - return sqrt(fx*fx+fy*fy+fz*fz); + double fx = INT2MM(x_); + double fy = INT2MM(y_); + double fz = INT2MM(z_); + return sqrt(fx * fx + fy * fy + fz * fz); } coord_t dot(const Point3& p) const { - return x*p.x + y*p.y + z*p.z; + return x_ * p.x_ + y_ * p.y_ + z_ * p.z_; } - coord_t& operator[] (const size_t index) + coord_t& operator[](const size_t index) { assert(index < 3); - switch(index) + switch (index) { - case 0: return x; - case 1: return y; - default: return z; + case 0: + return x_; + case 1: + return y_; + default: + return z_; } } - const coord_t& operator[] (const size_t index) const + const coord_t& operator[](const size_t index) const { - return const_cast(this)->operator[] (index); + return const_cast(this)->operator[](index); } }; @@ -152,20 +162,22 @@ inline Point3 operator*(const num_t i, const Point3& rhs) } // namespace cura -namespace std { - template <> - struct hash { - size_t operator()(const cura::Point3 & pp) const - { - static int prime = 31; - int result = 89; - result = result * prime + pp.x; - result = result * prime + pp.y; - result = result * prime + pp.z; - return result; - } - }; -} +namespace std +{ +template<> +struct hash +{ + size_t operator()(const cura::Point3& pp) const + { + static int prime = 31; + int result = 89; + result = static_cast(result * prime + pp.x_); + result = static_cast(result * prime + pp.y_); + result = static_cast(result * prime + pp.z_); + return static_cast(result); + } +}; +} // namespace std -#endif //UTILS_POINT3_H +#endif // UTILS_POINT3_H diff --git a/include/utils/VoxelUtils.h b/include/utils/VoxelUtils.h index f4b93bb3b5..b080a4d5b6 100644 --- a/include/utils/VoxelUtils.h +++ b/include/utils/VoxelUtils.h @@ -1,5 +1,5 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef UTILS_VOXEL_UTILS_H #define UTILS_VOXEL_UTILS_H @@ -10,7 +10,7 @@ #include "utils/IntPoint.h" #include "utils/polygon.h" -namespace cura +namespace cura { using GridPoint3 = Point3; @@ -26,13 +26,13 @@ struct DilationKernel * |\ ___\ * | | | * \|____| - * + * * A diamond kernel uses a manhattan distance to create a diamond shape around a reference voxel. * /|\ * /_|_\ * \ | / * \|/ - * + * * A prism kernel is diamond in XY, but extrudes straight in Z around a reference voxel. * / \ * / \ @@ -42,7 +42,12 @@ struct DilationKernel * \ | / * \|/ */ - enum class Type { CUBE, DIAMOND, PRISM }; + enum class Type + { + CUBE, + DIAMOND, + PRISM + }; DilationKernel(GridPoint3 kernel_size, Type type); GridPoint3 kernel_size; //!< Size of the kernel in number of voxel cells Type type; @@ -51,7 +56,7 @@ struct DilationKernel /*! * Utility class for walking over a 3D voxel grid. - * + * * Contains the math for intersecting voxels with lines, polgons, areas, etc. */ class VoxelUtils @@ -59,106 +64,107 @@ class VoxelUtils public: using grid_coord_t = coord_t; VoxelUtils(Point3 cell_size) - : cell_size(cell_size) - {} + : cell_size(cell_size) + { + } Point3 cell_size; /*! * Process voxels which a line segment crosses. - * + * * \param start Start point of the line * \param end End point of the line * \param process_cell_func Function to perform on each cell the line crosses * \return Whether executing was stopped short as indicated by the \p cell_processing_function */ - bool walkLine(Point3 start, Point3 end, const std::function& process_cell_func) const; + bool walkLine(Point3 start, Point3 end, const std::function& process_cell_func) const; /*! * Process voxels which the line segments of a polygon crosses. - * + * * \warning Voxels may be processed multiple times! - * + * * \param polys The polygons to walk * \param z The height at which the polygons occur * \param process_cell_func Function to perform on each voxel cell * \return Whether executing was stopped short as indicated by the \p cell_processing_function */ - bool walkPolygons(const Polygons& polys, coord_t z, const std::function& process_cell_func) const; + bool walkPolygons(const Polygons& polys, coord_t z, const std::function& process_cell_func) const; /*! * Process voxels near the line segments of a polygon. * For each voxel the polygon crosses we process each of the offset voxels according to the kernel. - * + * * \warning Voxels may be processed multiple times! - * + * * \param polys The polygons to walk * \param z The height at which the polygons occur * \param process_cell_func Function to perform on each voxel cell * \return Whether executing was stopped short as indicated by the \p cell_processing_function */ - bool walkDilatedPolygons(const Polygons& polys, coord_t z, const DilationKernel& kernel, const std::function& process_cell_func) const; + bool walkDilatedPolygons(const Polygons& polys, coord_t z, const DilationKernel& kernel, const std::function& process_cell_func) const; private: /*! * \warning the \p polys is assumed to be translated by half the cell_size in xy already */ - bool _walkAreas(const Polygons& polys, coord_t z, const std::function& process_cell_func) const; + bool _walkAreas(const Polygons& polys, coord_t z, const std::function& process_cell_func) const; public: /*! * Process all voxels inside the area of a polygons object. - * + * * \warning The voxels along the area are not processed. Thin areas might not process any voxels at all. - * + * * \param polys The area to fill * \param z The height at which the polygons occur * \param process_cell_func Function to perform on each voxel cell * \return Whether executing was stopped short as indicated by the \p cell_processing_function */ - bool walkAreas(const Polygons& polys, coord_t z, const std::function& process_cell_func) const; + bool walkAreas(const Polygons& polys, coord_t z, const std::function& process_cell_func) const; /*! * Process all voxels inside the area of a polygons object. * For each voxel inside the polygon we process each of the offset voxels according to the kernel. - * + * * \warning The voxels along the area are not processed. Thin areas might not process any voxels at all. - * + * * \param polys The area to fill * \param z The height at which the polygons occur * \param process_cell_func Function to perform on each voxel cell * \return Whether executing was stopped short as indicated by the \p cell_processing_function */ - bool walkDilatedAreas(const Polygons& polys, coord_t z, const DilationKernel& kernel, const std::function& process_cell_func) const; + bool walkDilatedAreas(const Polygons& polys, coord_t z, const DilationKernel& kernel, const std::function& process_cell_func) const; /*! * Dilate with a kernel. - * + * * Extends the \p process_cell_func, so that for each cell we process nearby cells as well. - * + * * Apply this function to a process_cell_func to create a new process_cell_func which applies the effect to nearby voxels as well. - * + * * \param kernel The offset positions relative to the input of \p process_cell_func * \param process_cell_func Function to perform on each voxel cell */ - std::function dilate(const DilationKernel& kernel, const std::function& process_cell_func) const; - - GridPoint3 toGridPoint(const Point3& point) const + std::function dilate(const DilationKernel& kernel, const std::function& process_cell_func) const; + + GridPoint3 toGridPoint(const Point3& point) const { - return GridPoint3(toGridCoord(point.x, 0), toGridCoord(point.y, 1), toGridCoord(point.z, 2)); + return GridPoint3(toGridCoord(point.x_, 0), toGridCoord(point.y_, 1), toGridCoord(point.z_, 2)); } - - grid_coord_t toGridCoord(const coord_t& coord, const size_t dim) const + + grid_coord_t toGridCoord(const coord_t& coord, const size_t dim) const { assert(dim < 3); return coord / cell_size[dim] - (coord < 0); } - - Point3 toLowerCorner(const GridPoint3& location) const + + Point3 toLowerCorner(const GridPoint3& location) const { - return cura::Point3(toLowerCoord(location.x, 0), toLowerCoord(location.y, 1), toLowerCoord(location.z, 2)); + return cura::Point3(toLowerCoord(location.x_, 0), toLowerCoord(location.y_, 1), toLowerCoord(location.z_, 2)); } - - coord_t toLowerCoord(const grid_coord_t& grid_coord, const size_t dim) const + + coord_t toLowerCoord(const grid_coord_t& grid_coord, const size_t dim) const { assert(dim < 3); return grid_coord * cell_size[dim]; @@ -171,13 +177,12 @@ class VoxelUtils { Polygon ret; Point3 c = toLowerCorner(p); - ret.emplace_back(c.x, c.y); - ret.emplace_back(c.x + cell_size.x, c.y); - ret.emplace_back(c.x + cell_size.x, c.y + cell_size.y); - ret.emplace_back(c.x, c.y + cell_size.y); + ret.emplace_back(c.x_, c.y_); + ret.emplace_back(c.x_ + cell_size.x_, c.y_); + ret.emplace_back(c.x_ + cell_size.x_, c.y_ + cell_size.y_); + ret.emplace_back(c.x_, c.y_ + cell_size.y_); return ret; } - }; } // namespace cura diff --git a/include/utils/actions/smooth.h b/include/utils/actions/smooth.h index 67e4adebe6..a450a9fe40 100644 --- a/include/utils/actions/smooth.h +++ b/include/utils/actions/smooth.h @@ -4,12 +4,10 @@ #ifndef UTILS_VIEWS_SMOOTH_H #define UTILS_VIEWS_SMOOTH_H -#include "settings/Settings.h" -#include "settings/types/Angle.h" -#include "utils/types/arachne.h" -#include "utils/types/generic.h" -#include "utils/types/geometry.h" -#include "utils/types/get.h" +#include +#include +#include +#include #include #include @@ -22,10 +20,12 @@ #include #include -#include -#include -#include -#include +#include "settings/Settings.h" +#include "settings/types/Angle.h" +#include "utils/types/arachne.h" +#include "utils/types/generic.h" +#include "utils/types/geometry.h" +#include "utils/types/get.h" namespace cura { @@ -43,7 +43,7 @@ struct smooth_fn { const auto fluid_motion_shift_distance = settings.get("meshfix_fluid_motion_shift_distance"); const auto fluid_motion_small_distance = settings.get("meshfix_fluid_motion_small_distance"); - const auto fluid_motion_angle = settings.get("meshfix_fluid_motion_angle").value; + const auto fluid_motion_angle = settings.get("meshfix_fluid_motion_angle").value_; return ranges::make_action_closure(ranges::bind_back(smooth_fn{}, fluid_motion_shift_distance, fluid_motion_small_distance, fluid_motion_angle)); } diff --git a/include/utils/floatpoint.h b/include/utils/floatpoint.h index 9019f30b24..8f4d35b52f 100644 --- a/include/utils/floatpoint.h +++ b/include/utils/floatpoint.h @@ -1,18 +1,18 @@ -//Copyright (c) 2020 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2020 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef FLOAT_POINT_H #define FLOAT_POINT_H -#include "IntPoint.h" - -#include #include +#include + +#include "IntPoint.h" namespace cura { - + /* Floating point 3D points are used during model loading as 3D vectors. They represent millimeters in 3D space. @@ -20,38 +20,88 @@ They represent millimeters in 3D space. class FPoint3 { public: - float x,y,z; - FPoint3() {} - FPoint3(float _x, float _y, float _z): x(_x), y(_y), z(_z) {} - FPoint3(const Point3& p): x(p.x*.001), y(p.y*.001), z(p.z*.001) {} + float x, y, z; + FPoint3() + { + } + FPoint3(float _x, float _y, float _z) + : x(_x) + , y(_y) + , z(_z) + { + } + FPoint3(const Point3& p) + : x(static_cast(p.x_) * .001f) + , y(static_cast(p.y_) * .001f) + , z(static_cast(p.z_) * .001f) + { + } - FPoint3 operator+(const FPoint3& p) const { return FPoint3(x+p.x, y+p.y, z+p.z); } - FPoint3 operator-(const FPoint3& p) const { return FPoint3(x-p.x, y-p.y, z-p.z); } - FPoint3 operator*(const float f) const { return FPoint3(x*f, y*f, z*f); } - FPoint3 operator/(const float f) const { return FPoint3(x/f, y/f, z/f); } + FPoint3 operator+(const FPoint3& p) const + { + return FPoint3(x + p.x, y + p.y, z + p.z); + } + FPoint3 operator-(const FPoint3& p) const + { + return FPoint3(x - p.x, y - p.y, z - p.z); + } + FPoint3 operator*(const float f) const + { + return FPoint3(x * f, y * f, z * f); + } + FPoint3 operator/(const float f) const + { + return FPoint3(x / f, y / f, z / f); + } - FPoint3& operator += (const FPoint3& p) { x += p.x; y += p.y; z += p.z; return *this; } - FPoint3& operator -= (const FPoint3& p) { x -= p.x; y -= p.y; z -= p.z; return *this; } - FPoint3& operator *= (const float f) { x *= f; y *= f; z *= f; return *this; } + FPoint3& operator+=(const FPoint3& p) + { + x += p.x; + y += p.y; + z += p.z; + return *this; + } + FPoint3& operator-=(const FPoint3& p) + { + x -= p.x; + y -= p.y; + z -= p.z; + return *this; + } + FPoint3& operator*=(const float f) + { + x *= f; + y *= f; + z *= f; + return *this; + } - bool operator==(FPoint3& p) const { return x==p.x&&y==p.y&&z==p.z; } - bool operator!=(FPoint3& p) const { return x!=p.x||y!=p.y||z!=p.z; } + bool operator==(FPoint3& p) const + { + return x == p.x && y == p.y && z == p.z; + } + bool operator!=(FPoint3& p) const + { + return x != p.x || y != p.y || z != p.z; + } float max() const { - if (x > y && x > z) return x; - if (y > z) return y; + if (x > y && x > z) + return x; + if (y > z) + return y; return z; } bool testLength(float len) const { - return vSize2() <= len*len; + return vSize2() <= len * len; } float vSize2() const { - return x*x+y*y+z*z; + return x * x + y * y + z * z; } float vSize() const @@ -61,24 +111,17 @@ class FPoint3 inline FPoint3 normalized() const { - return (*this)/vSize(); + return (*this) / vSize(); } FPoint3 cross(const FPoint3& p) const { - return FPoint3( - y*p.z-z*p.y, - z*p.x-x*p.z, - x*p.y-y*p.x); + return FPoint3(y * p.z - z * p.y, z * p.x - x * p.z, x * p.y - y * p.x); } static FPoint3 cross(const Point3& a, const Point3& b) { return FPoint3(a).cross(FPoint3(b)); -// FPoint3( -// a.y*b.z-a.z*b.y, -// a.z*b.x-a.x*b.z, -// a.x*b.y-a.y*b.x); } Point3 toPoint3() @@ -87,20 +130,10 @@ class FPoint3 } }; - -//inline FPoint3 operator+(FPoint3 lhs, const FPoint3& rhs) { -// lhs += rhs; -// return lhs; -//} -inline float operator*(FPoint3 lhs, const FPoint3& rhs) { - return lhs.x*rhs.x + lhs.y*rhs.y + lhs.z*rhs.z; +inline float operator*(FPoint3 lhs, const FPoint3& rhs) +{ + return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z; } -//inline FPoint3 operator*(FPoint3 lhs, const float f) { -// lhs *= f; -// return lhs; -//} - - -}//namespace cura -#endif//INT_POINT_H +} // namespace cura +#endif // INT_POINT_H diff --git a/include/utils/math.h b/include/utils/math.h index 21a015ff2e..23561cc86f 100644 --- a/include/utils/math.h +++ b/include/utils/math.h @@ -1,30 +1,28 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef UTILS_MATH_H #define UTILS_MATH_H -#include #include +#include +#include -//c++11 no longer defines M_PI, so add our own constant. -#ifndef M_PI -#define M_PI 3.14159265358979323846 -#endif - namespace cura { -static constexpr float sqrt2 = 1.41421356237; - -template inline T square(const T& a) { return a * a; } +template +inline T square(const T& a) +{ + return a * a; +} inline int64_t round_divide_signed(const int64_t dividend, const int64_t divisor) //!< Return dividend divided by divisor rounded to the nearest integer { - if((dividend < 0) ^ (divisor < 0)) //Either the numerator or the denominator is negative, so the result must be negative. + if ((dividend < 0) ^ (divisor < 0)) // Either the numerator or the denominator is negative, so the result must be negative. { - return (dividend - divisor / 2) / divisor; //Flip the .5 offset to do proper rounding in the negatives too. + return (dividend - divisor / 2) / divisor; // Flip the .5 offset to do proper rounding in the negatives too. } else { @@ -33,11 +31,11 @@ inline int64_t round_divide_signed(const int64_t dividend, const int64_t divisor } inline uint64_t ceil_divide_signed(const int64_t dividend, const int64_t divisor) //!< Return dividend divided by divisor rounded up towards positive infinity. { - return (dividend / divisor) + (dividend * divisor > 0 ? 1 : 0); + return static_cast((dividend / divisor) + (dividend * divisor > 0 ? 1 : 0)); } inline uint64_t floor_divide_signed(const int64_t dividend, const int64_t divisor) //!< Return dividend divided by divisor rounded down towards negative infinity. { - return (dividend / divisor) + (dividend * divisor > 0 ? 0 : -1); + return static_cast((dividend / divisor) + (dividend * divisor > 0 ? 0 : -1)); } inline uint64_t round_divide(const uint64_t dividend, const uint64_t divisor) //!< Return dividend divided by divisor rounded to the nearest integer { @@ -48,18 +46,5 @@ inline uint64_t round_up_divide(const uint64_t dividend, const uint64_t divisor) return (dividend + divisor - 1) / divisor; } -template -constexpr T pi_div(const T div) -{ - return static_cast(M_PI) / div; -} - -template -constexpr T pi_mul(const T mul) -{ - return static_cast(M_PI) / mul; -} - -}//namespace cura +} // namespace cura #endif // UTILS_MATH_H - diff --git a/include/utils/polygonUtils.h b/include/utils/polygonUtils.h index c4ea2c2db6..24d8936561 100644 --- a/include/utils/polygonUtils.h +++ b/include/utils/polygonUtils.h @@ -22,40 +22,55 @@ namespace cura */ struct ClosestPolygonPoint { - Point location; //!< Result location - ConstPolygonPointer poly; //!< Polygon in which the result was found (or nullptr if no result was found) - unsigned int poly_idx; //!< The index of the polygon in some Polygons where ClosestPolygonPoint::poly can be found - unsigned int point_idx; //!< Index to the first point in the polygon of the line segment on which the result was found - ClosestPolygonPoint(Point p, int pos, ConstPolygonRef poly) - : location(p) - , poly(poly) - , poly_idx(NO_INDEX) - , point_idx(pos){}; - ClosestPolygonPoint(Point p, int pos, ConstPolygonRef poly, int poly_idx) - : location(p) - , poly(poly) - , poly_idx(poly_idx) - , point_idx(pos){}; + Point location_; //!< Result location + ConstPolygonPointer poly_; //!< Polygon in which the result was found (or nullptr if no result was found) + size_t poly_idx_; //!< The index of the polygon in some Polygons where ClosestPolygonPoint::poly can be found + size_t point_idx_; //!< Index to the first point in the polygon of the line segment on which the result was found + + ClosestPolygonPoint(Point p, size_t pos, ConstPolygonRef poly) + : location_(p) + , poly_(poly) + , poly_idx_(NO_INDEX) + , point_idx_(pos) + { + } + + ClosestPolygonPoint(Point p, size_t pos, ConstPolygonRef poly, size_t poly_idx) + : location_(p) + , poly_(poly) + , poly_idx_(poly_idx) + , point_idx_(pos) + { + } + ClosestPolygonPoint(ConstPolygonRef poly) - : poly(poly) - , poly_idx(NO_INDEX) - , point_idx(NO_INDEX){}; + : poly_(poly) + , poly_idx_(NO_INDEX) + , point_idx_(NO_INDEX) + { + } + ClosestPolygonPoint() - : poly_idx(NO_INDEX) - , point_idx(NO_INDEX){}; + : poly_idx_(NO_INDEX) + , point_idx_(NO_INDEX) + { + } + Point p() const { // conformity with other classes - return location; + return location_; } + bool isValid() const { - return point_idx != NO_INDEX; + return point_idx_ != NO_INDEX; } + bool operator==(const ClosestPolygonPoint& rhs) const { // no need to compare on poy_idx // it's sometimes unused while poly is always initialized - return poly == rhs.poly && point_idx == rhs.point_idx && location == rhs.location; + return poly_ == rhs.poly_ && point_idx_ == rhs.point_idx_ && location_ == rhs.location_; } }; diff --git a/src/FffGcodeWriter.cpp b/src/FffGcodeWriter.cpp index a42d12889d..aced5673aa 100644 --- a/src/FffGcodeWriter.cpp +++ b/src/FffGcodeWriter.cpp @@ -183,7 +183,7 @@ void FffGcodeWriter::writeGCode(SliceDataStorage& storage, TimeKeeper& time_keep Progress::messageProgressStage(Progress::Stage::FINISH, &time_keeper); // Store the object height for when we are printing multiple objects, as we need to clear every one of them when moving to the next position. - max_object_height = std::max(max_object_height, storage.model_max.z); + max_object_height = std::max(max_object_height, storage.model_max.z_); constexpr bool force = true; @@ -205,7 +205,7 @@ unsigned int FffGcodeWriter::findSpiralizedLayerSeamVertexIndex(const SliceDataS { seam_pos = mesh.getZSeamHint(); } - return PolygonUtils::findClosest(seam_pos, layer.parts[0].spiral_wall[0]).point_idx; + return PolygonUtils::findClosest(seam_pos, layer.parts[0].spiral_wall[0]).point_idx_; } else { @@ -238,7 +238,7 @@ unsigned int FffGcodeWriter::findSpiralizedLayerSeamVertexIndex(const SliceDataS // now test the vertex following the candidate seam vertex and if it lies to the left of the vector, it's good to use float a = LinearAlg2D::getAngleLeft(last_wall_seam_vertex_vector, last_wall_seam_vertex, wall[(seam_vertex_idx + 1) % n_points]); - if (a <= 0 || a >= M_PI) + if (a <= 0 || a >= std::numbers::pi) { // the vertex was not on the left of the vector so move the seam vertex on seam_vertex_idx = (seam_vertex_idx + 1) % n_points; @@ -546,7 +546,7 @@ void FffGcodeWriter::processNextMeshGroupCode(const SliceDataStorage& storage) Application::getInstance().communication->sendCurrentPosition(gcode.getPositionXY()); gcode.writeTravel(gcode.getPositionXY(), Application::getInstance().current_slice->scene.extruders[gcode.getExtruderNr()].settings.get("speed_travel")); - Point start_pos(storage.model_min.x, storage.model_min.y); + Point start_pos(storage.model_min.x_, storage.model_min.y_); gcode.writeTravel(start_pos, Application::getInstance().current_slice->scene.extruders[gcode.getExtruderNr()].settings.get("speed_travel")); gcode.processInitialLayerTemperature(storage, gcode.getExtruderNr()); @@ -1458,7 +1458,7 @@ std::vector FffGcodeWriter::calculateMeshOrder(const SliceDataStorage& s { const Mesh& mesh_data = mesh_group->meshes[mesh_idx]; const Point3 middle = (mesh_data.getAABB().min + mesh_data.getAABB().max) / 2; - mesh_idx_order_optimizer.addItem(Point(middle.x, middle.y), mesh_idx); + mesh_idx_order_optimizer.addItem(Point(middle.x_, middle.y_), mesh_idx); } } const ExtruderTrain& train = Application::getInstance().current_slice->scene.extruders[extruder_nr]; @@ -1662,7 +1662,7 @@ bool FffGcodeWriter::processMultiLayerInfill( infill_angle = mesh.infill_angles.at((gcode_layer.getLayerNr() / combined_infill_layers) % mesh.infill_angles.size()); } const Point3 mesh_middle = mesh.bounding_box.getMiddle(); - const Point infill_origin(mesh_middle.x + mesh.settings.get("infill_offset_x"), mesh_middle.y + mesh.settings.get("infill_offset_y")); + const Point infill_origin(mesh_middle.x_ + mesh.settings.get("infill_offset_x"), mesh_middle.y_ + mesh.settings.get("infill_offset_y")); // Print the thicker infill lines first. (double or more layer thickness, infill combined with previous layers) bool added_something = false; @@ -1814,7 +1814,7 @@ bool FffGcodeWriter::processSingleLayerInfill( infill_angle = mesh.infill_angles.at((static_cast(gcode_layer.getLayerNr()) / combined_infill_layers) % mesh.infill_angles.size()); } const Point3 mesh_middle = mesh.bounding_box.getMiddle(); - const Point infill_origin(mesh_middle.x + mesh.settings.get("infill_offset_x"), mesh_middle.y + mesh.settings.get("infill_offset_y")); + const Point infill_origin(mesh_middle.x_ + mesh.settings.get("infill_offset_x"), mesh_middle.y_ + mesh.settings.get("infill_offset_y")); auto get_cut_offset = [](const bool zig_zaggify, const coord_t line_width, const size_t line_count) { @@ -2425,7 +2425,7 @@ bool FffGcodeWriter::processInsets( // the supported region is made up of those areas that really are supported by either model or support on the layer below // expanded to take into account the overhang angle, the greater the overhang angle, the larger the supported area is // considered to be - const coord_t overhang_width = layer_height * std::tan(overhang_angle / (180 / M_PI)); + const coord_t overhang_width = layer_height * std::tan(overhang_angle / (180 / std::numbers::pi)); Polygons overhang_region = part.outline.offset(-half_outer_wall_width).difference(outlines_below.offset(10 + overhang_width - half_outer_wall_width)).offset(10); gcode_layer.setOverhangMask(overhang_region); } diff --git a/src/FffPolygonGenerator.cpp b/src/FffPolygonGenerator.cpp index 3b1a5e4c38..0ac8e5ce1b 100644 --- a/src/FffPolygonGenerator.cpp +++ b/src/FffPolygonGenerator.cpp @@ -145,11 +145,11 @@ bool FffPolygonGenerator::sliceModel(MeshGroup* meshgroup, TimeKeeper& timeKeepe { continue; } - const coord_t mesh_height = mesh.max().z; + const coord_t mesh_height = mesh.max().z_; switch (mesh.settings.get("slicing_tolerance")) { case SlicingTolerance::MIDDLE: - if (storage.model_max.z < initial_layer_thickness) + if (storage.model_max.z_ < initial_layer_thickness) { slice_layer_count = std::max(slice_layer_count, (mesh_height > initial_layer_thickness / 2) ? 1 : 0); // One layer if higher than half initial layer height. } @@ -673,7 +673,7 @@ void FffPolygonGenerator::processDerivedWallsSkinInfill(SliceMeshStorage& mesh) if (mesh.settings.get("infill_line_distance") > 0 && mesh.settings.get("infill_pattern") == EFillMethod::CUBICSUBDIV) { const Point3 mesh_middle = mesh.bounding_box.getMiddle(); - const Point infill_origin(mesh_middle.x + mesh.settings.get("infill_offset_x"), mesh_middle.y + mesh.settings.get("infill_offset_y")); + const Point infill_origin(mesh_middle.x_ + mesh.settings.get("infill_offset_x"), mesh_middle.y_ + mesh.settings.get("infill_offset_y")); SubDivCube::precomputeOctree(mesh, infill_origin); } diff --git a/src/InterlockingGenerator.cpp b/src/InterlockingGenerator.cpp index 6310a7ef16..3392f4ee31 100644 --- a/src/InterlockingGenerator.cpp +++ b/src/InterlockingGenerator.cpp @@ -3,19 +3,19 @@ #include "InterlockingGenerator.h" -#include "Application.h" -#include "Slice.h" -#include "settings/types/LayerIndex.h" -#include "slicer.h" -#include "utils/VoxelUtils.h" -#include "utils/polygonUtils.h" +#include // max #include #include #include #include -#include // max +#include "Application.h" +#include "Slice.h" +#include "settings/types/LayerIndex.h" +#include "slicer.h" +#include "utils/VoxelUtils.h" +#include "utils/polygonUtils.h" namespace cura { @@ -109,7 +109,7 @@ void InterlockingGenerator::handleThinAreas(const std::unordered_set for (const auto& cell : has_all_meshes) { const Point3 bottom_corner = vu.toLowerCorner(cell); - for (int layer_nr = bottom_corner.z; layer_nr < bottom_corner.z + cell_size.z && layer_nr < near_interlock_per_layer.size(); ++layer_nr) + for (int layer_nr = bottom_corner.z_; layer_nr < bottom_corner.z_ + cell_size.z_ && layer_nr < near_interlock_per_layer.size(); ++layer_nr) { near_interlock_per_layer[layer_nr].add(vu.toPolygon(cell)); } @@ -214,7 +214,7 @@ void InterlockingGenerator::addBoundaryCells(const std::vector& layers { skin = skin.xorPolygons(layers[layer_nr - 1]); } - skin = skin.offset(-cell_size.x / 2).offset(cell_size.x / 2); // remove superfluous small areas, which would anyway be included because of walkPolygons + skin = skin.offset(-cell_size.x_ / 2).offset(cell_size.x_ / 2); // remove superfluous small areas, which would anyway be included because of walkPolygons vu.walkDilatedAreas(skin, z, kernel, voxel_emplacer); } } @@ -248,12 +248,12 @@ std::vector> InterlockingGenerator::generateMicrostructure cell_area_per_mesh_per_layer.resize(2); cell_area_per_mesh_per_layer[0].resize(2); const coord_t beam_w_sum = beam_width_a + beam_width_b; - const coord_t middle = cell_size.x * beam_width_a / beam_w_sum; - const coord_t width[2] = { middle, cell_size.x - middle }; + const coord_t middle = cell_size.x_ * beam_width_a / beam_w_sum; + const coord_t width[2] = { middle, cell_size.x_ - middle }; for (size_t mesh_idx : { 0, 1 }) { Point offset(mesh_idx ? middle : 0, 0); - Point area_size(width[mesh_idx], cell_size.y); + Point area_size(width[mesh_idx], cell_size.y_); PolygonRef poly = cell_area_per_mesh_per_layer[0][mesh_idx].newPoly(); poly.emplace_back(offset); @@ -297,10 +297,10 @@ void InterlockingGenerator::applyMicrostructureToOutlines(const std::unordered_s Point3 bottom_corner = vu.toLowerCorner(grid_loc); for (size_t mesh_idx = 0; mesh_idx < 2; mesh_idx++) { - for (LayerIndex layer_nr = bottom_corner.z; layer_nr < bottom_corner.z + cell_size.z && layer_nr < max_layer_count; layer_nr += beam_layer_count) + for (LayerIndex layer_nr = bottom_corner.z_; layer_nr < bottom_corner.z_ + cell_size.z_ && layer_nr < max_layer_count; layer_nr += beam_layer_count) { Polygons areas_here = cell_area_per_mesh_per_layer[(layer_nr / beam_layer_count) % cell_area_per_mesh_per_layer.size()][mesh_idx]; - areas_here.translate(Point(bottom_corner.x, bottom_corner.y)); + areas_here.translate(Point(bottom_corner.x_, bottom_corner.y_)); structure_per_layer[mesh_idx][layer_nr / beam_layer_count].add(areas_here); } } diff --git a/src/LayerPlan.cpp b/src/LayerPlan.cpp index 52305a9521..36b6ef02d4 100644 --- a/src/LayerPlan.cpp +++ b/src/LayerPlan.cpp @@ -1491,10 +1491,10 @@ void LayerPlan::spiralizeWallSlice( ClosestPolygonPoint cpp = PolygonUtils::findClosest(p, last_wall_polygons); // if we found a point and it's not further away than max_dist2, use it - if (cpp.isValid() && vSize2(cpp.location - p) <= max_dist2) + if (cpp.isValid() && vSize2(cpp.location_ - p) <= max_dist2) { // interpolate between cpp.location and p depending on how far we have progressed along wall - addExtrusionMove(cpp.location + (p - cpp.location) * (wall_length / total_length), config, SpaceFillType::Polygons, flow, width_factor, spiralize, speed_factor); + addExtrusionMove(cpp.location_ + (p - cpp.location_) * (wall_length / total_length), config, SpaceFillType::Polygons, flow, width_factor, spiralize, speed_factor); } else { @@ -2073,7 +2073,7 @@ void LayerPlan::writeGCode(GCodeExport& gcode) { // Before the final travel, move up to the next layer height, on the current spot, with a sensible speed. Point3 current_position = gcode.getPosition(); - current_position.z = final_travel_z; + current_position.z_ = final_travel_z; gcode.writeTravel(current_position, extruder.settings.get("speed_z_hop")); // Prevent the final travel(s) from resetting to the 'previous' layer height. diff --git a/src/MeshGroup.cpp b/src/MeshGroup.cpp index 84ef4d4923..e14fcc3600 100644 --- a/src/MeshGroup.cpp +++ b/src/MeshGroup.cpp @@ -55,9 +55,9 @@ Point3 MeshGroup::min() const continue; } Point3 v = mesh.min(); - ret.x = std::min(ret.x, v.x); - ret.y = std::min(ret.y, v.y); - ret.z = std::min(ret.z, v.z); + ret.x_ = std::min(ret.x_, v.x_); + ret.y_ = std::min(ret.y_, v.y_); + ret.z_ = std::min(ret.z_, v.z_); } return ret; } @@ -77,9 +77,9 @@ Point3 MeshGroup::max() const continue; } Point3 v = mesh.max(); - ret.x = std::max(ret.x, v.x); - ret.y = std::max(ret.y, v.y); - ret.z = std::max(ret.z, v.z); + ret.x_ = std::max(ret.x_, v.x_); + ret.y_ = std::max(ret.y_, v.y_); + ret.z_ = std::max(ret.z_, v.z_); } return ret; } @@ -98,8 +98,8 @@ void MeshGroup::finalize() Point3 meshgroup_offset(0, 0, 0); if (! settings.get("machine_center_is_zero")) { - meshgroup_offset.x = settings.get("machine_width") / 2; - meshgroup_offset.y = settings.get("machine_depth") / 2; + meshgroup_offset.x_ = settings.get("machine_width") / 2; + meshgroup_offset.y_ = settings.get("machine_depth") / 2; } // If a mesh position was given, put the mesh at this position in 3D space. @@ -111,7 +111,7 @@ void MeshGroup::finalize() Point3 object_min = mesh.min(); Point3 object_max = mesh.max(); Point3 object_size = object_max - object_min; - mesh_offset += Point3(-object_min.x - object_size.x / 2, -object_min.y - object_size.y / 2, -object_min.z); + mesh_offset += Point3(-object_min.x_ - object_size.x_ / 2, -object_min.y_ - object_size.y_ / 2, -object_min.z_); } mesh.translate(mesh_offset + meshgroup_offset); } @@ -127,7 +127,7 @@ void MeshGroup::finalize() void MeshGroup::scaleFromBottom(const Ratio factor_xy, const Ratio factor_z) { const Point3 center = (max() + min()) / 2; - const Point3 origin(center.x, center.y, 0); + const Point3 origin(center.x_, center.y_, 0); const FMatrix4x3 transformation = FMatrix4x3::scale(factor_xy, factor_xy, factor_z, origin); for (Mesh& mesh : meshes) diff --git a/src/Mold.cpp b/src/Mold.cpp index bd5ff2e0b1..ccf5ec0cd6 100644 --- a/src/Mold.cpp +++ b/src/Mold.cpp @@ -71,7 +71,7 @@ void Mold::process(std::vector& slicer_list) const AngleDegrees angle = mesh.settings.get("mold_angle"); const coord_t roof_height = mesh.settings.get("mold_roof_height"); - const coord_t inset = tan(angle / 180 * M_PI) * layer_height; + const coord_t inset = tan(angle / 180 * std::numbers::pi) * layer_height; const size_t roof_layer_count = roof_height / layer_height; diff --git a/src/PrimeTower.cpp b/src/PrimeTower.cpp index d2761327eb..bc62d17a46 100644 --- a/src/PrimeTower.cpp +++ b/src/PrimeTower.cpp @@ -305,8 +305,8 @@ void PrimeTower::gotoStartLocation(LayerPlan& gcode_layer, const int extruder_nr const coord_t inward_dist = train.settings.get("machine_nozzle_size") * 3 / 2; const coord_t start_dist = train.settings.get("machine_nozzle_size") * 2; const Point prime_end = PolygonUtils::moveInsideDiagonally(wipe_location, inward_dist); - const Point outward_dir = wipe_location.location - prime_end; - const Point prime_start = wipe_location.location + normal(outward_dir, start_dist); + const Point outward_dir = wipe_location.location_ - prime_end; + const Point prime_start = wipe_location.location_ + normal(outward_dir, start_dist); gcode_layer.addTravel(prime_start); } diff --git a/src/SkeletalTrapezoidation.cpp b/src/SkeletalTrapezoidation.cpp index c391b0d4f6..4f2eb2151d 100644 --- a/src/SkeletalTrapezoidation.cpp +++ b/src/SkeletalTrapezoidation.cpp @@ -207,7 +207,7 @@ std::vector SkeletalTrapezoidation::discretize(const vd_t::edge_type& vd_ coord_t end_x = projected_x(end); // Part of the edge will be bound to the markings on the endpoints of the edge. Calculate how far that is. - float bound = 0.5 / tan((M_PI - transitioning_angle) * 0.5); + float bound = 0.5 / tan((std::numbers::pi - transitioning_angle) * 0.5); coord_t marking_start_x = -d * bound; coord_t marking_end_x = d * bound; Point marking_start = middle + x_axis_dir * marking_start_x / x_axis_length; @@ -2212,7 +2212,7 @@ void SkeletalTrapezoidation::generateLocalMaximaSingleBeads() constexpr coord_t n_segments = 6; for (coord_t segment = 0; segment < n_segments; segment++) { - float a = 2.0 * M_PI / n_segments * segment; + float a = 2.0 * std::numbers::pi / n_segments * segment; line.junctions.emplace_back(node.p + Point(r * cos(a), r * sin(a)), width, inset_index); } } diff --git a/src/TreeSupportTipGenerator.cpp b/src/TreeSupportTipGenerator.cpp index af313019d8..f1f2aed10c 100644 --- a/src/TreeSupportTipGenerator.cpp +++ b/src/TreeSupportTipGenerator.cpp @@ -48,12 +48,12 @@ TreeSupportTipGenerator::TreeSupportTipGenerator(const SliceDataStorage& storage support_outset(0) , // Since we disable support offset when tree support is enabled we use an offset of 0 rather than the setting value mesh.settings.get("support_offset") roof_outset(use_fake_roof ? support_outset : mesh.settings.get("support_roof_offset")) - , force_tip_to_roof((config.min_radius * config.min_radius * M_PI > minimum_roof_area * (1000 * 1000)) && support_roof_layers && ! use_fake_roof) + , force_tip_to_roof((config.min_radius * config.min_radius * std::numbers::pi > minimum_roof_area * (1000 * 1000)) && support_roof_layers && ! use_fake_roof) , support_tree_limit_branch_reach(mesh.settings.get("support_tree_limit_branch_reach")) , support_tree_branch_reach_limit(support_tree_limit_branch_reach ? mesh.settings.get("support_tree_branch_reach_limit") : 0) , z_distance_delta(std::min(config.z_distance_top_layers + 1, mesh.overhang_areas.size())) , xy_overrides(config.support_overrides == SupportDistPriority::XY_OVERRIDES_Z) - , tip_roof_size(force_tip_to_roof ? config.min_radius * config.min_radius * M_PI : 0) + , tip_roof_size(force_tip_to_roof ? config.min_radius * config.min_radius * std::numbers::pi : 0) , already_inserted(mesh.overhang_areas.size()) , support_roof_drawn(mesh.overhang_areas.size(), Polygons()) , roof_tips_drawn(mesh.overhang_areas.size(), Polygons()) @@ -266,7 +266,7 @@ Polygons TreeSupportTipGenerator::ensureMaximumDistancePolyline(const Polygons& { ClosestPolygonPoint middle_point(part[0], 0, part); middle_point = PolygonUtils::walk(middle_point, coord_t(length / 2)); - line.add(middle_point.location); + line.add(middle_point.location_); } else { diff --git a/src/gcodeExport.cpp b/src/gcodeExport.cpp index 2ef08a0474..210c319c8d 100644 --- a/src/gcodeExport.cpp +++ b/src/gcodeExport.cpp @@ -3,6 +3,13 @@ #include "gcodeExport.h" +#include +#include +#include +#include + +#include + #include "Application.h" //To send layer view data. #include "ExtruderTrain.h" #include "PrintFeature.h" @@ -14,13 +21,6 @@ #include "utils/Date.h" #include "utils/string.h" // MMtoStream, PrecisionedDouble -#include - -#include -#include -#include -#include - namespace cura { @@ -249,18 +249,18 @@ std::string GCodeExport::getFileHeader( prefix << ";PRINT.GROUPS:" << Application::getInstance().current_slice->scene.mesh_groups.size() << new_line; - if (total_bounding_box.min.x > total_bounding_box.max.x) // We haven't encountered any movement (yet). This probably means we're command-line slicing. + if (total_bounding_box.min.x_ > total_bounding_box.max.x_) // We haven't encountered any movement (yet). This probably means we're command-line slicing. { // Put some small default in there. total_bounding_box.min = Point3(0, 0, 0); total_bounding_box.max = Point3(10, 10, 10); } - prefix << ";PRINT.SIZE.MIN.X:" << INT2MM(total_bounding_box.min.x) << new_line; - prefix << ";PRINT.SIZE.MIN.Y:" << INT2MM(total_bounding_box.min.y) << new_line; - prefix << ";PRINT.SIZE.MIN.Z:" << INT2MM(total_bounding_box.min.z) << new_line; - prefix << ";PRINT.SIZE.MAX.X:" << INT2MM(total_bounding_box.max.x) << new_line; - prefix << ";PRINT.SIZE.MAX.Y:" << INT2MM(total_bounding_box.max.y) << new_line; - prefix << ";PRINT.SIZE.MAX.Z:" << INT2MM(total_bounding_box.max.z) << new_line; + prefix << ";PRINT.SIZE.MIN.X:" << INT2MM(total_bounding_box.min.x_) << new_line; + prefix << ";PRINT.SIZE.MIN.Y:" << INT2MM(total_bounding_box.min.y_) << new_line; + prefix << ";PRINT.SIZE.MIN.Z:" << INT2MM(total_bounding_box.min.z_) << new_line; + prefix << ";PRINT.SIZE.MAX.X:" << INT2MM(total_bounding_box.max.x_) << new_line; + prefix << ";PRINT.SIZE.MAX.Y:" << INT2MM(total_bounding_box.max.y_) << new_line; + prefix << ";PRINT.SIZE.MAX.Z:" << INT2MM(total_bounding_box.max.z_) << new_line; prefix << ";SLICE_UUID:" << slice_uuid_ << new_line; prefix << ";END_OF_HEADER" << new_line; break; @@ -302,12 +302,12 @@ std::string GCodeExport::getFileHeader( prefix << new_line; prefix << ";Layer height: " << Application::getInstance().current_slice->scene.current_mesh_group->settings.get("layer_height") << new_line; } - prefix << ";MINX:" << INT2MM(total_bounding_box.min.x) << new_line; - prefix << ";MINY:" << INT2MM(total_bounding_box.min.y) << new_line; - prefix << ";MINZ:" << INT2MM(total_bounding_box.min.z) << new_line; - prefix << ";MAXX:" << INT2MM(total_bounding_box.max.x) << new_line; - prefix << ";MAXY:" << INT2MM(total_bounding_box.max.y) << new_line; - prefix << ";MAXZ:" << INT2MM(total_bounding_box.max.z) << new_line; + prefix << ";MINX:" << INT2MM(total_bounding_box.min.x_) << new_line; + prefix << ";MINY:" << INT2MM(total_bounding_box.min.y_) << new_line; + prefix << ";MINZ:" << INT2MM(total_bounding_box.min.z_) << new_line; + prefix << ";MAXX:" << INT2MM(total_bounding_box.max.x_) << new_line; + prefix << ";MAXY:" << INT2MM(total_bounding_box.max.y_) << new_line; + prefix << ";MAXZ:" << INT2MM(total_bounding_box.max.z_) << new_line; prefix << ";TARGET_MACHINE.NAME:" << transliterate(machine_name) << new_line; } @@ -392,12 +392,12 @@ Point3 GCodeExport::getPosition() const } Point GCodeExport::getPositionXY() const { - return Point(currentPosition.x, currentPosition.y); + return Point(currentPosition.x_, currentPosition.y_); } int GCodeExport::getPositionZ() const { - return currentPosition.z; + return currentPosition.z_; } int GCodeExport::getExtruderNr() const @@ -408,7 +408,7 @@ int GCodeExport::getExtruderNr() const void GCodeExport::setFilamentDiameter(const size_t extruder, const coord_t diameter) { const double r = INT2MM(diameter) / 2.0; - const double area = M_PI * r * r; + const double area = std::numbers::pi * r * r; extruder_attr[extruder].filament_area = area; } @@ -839,20 +839,20 @@ void GCodeExport::writeTravel(const Point3& p, const Velocity& speed) { if (flavor == EGCodeFlavor::BFB) { - writeMoveBFB(p.x, p.y, p.z + is_z_hopped, speed, 0.0, PrintFeatureType::MoveCombing); + writeMoveBFB(p.x_, p.y_, p.z_ + is_z_hopped, speed, 0.0, PrintFeatureType::MoveCombing); return; } - writeTravel(p.x, p.y, p.z + is_z_hopped, speed); + writeTravel(p.x_, p.y_, p.z_ + is_z_hopped, speed); } void GCodeExport::writeExtrusion(const Point3& p, const Velocity& speed, double extrusion_mm3_per_mm, PrintFeatureType feature, bool update_extrusion_offset) { if (flavor == EGCodeFlavor::BFB) { - writeMoveBFB(p.x, p.y, p.z, speed, extrusion_mm3_per_mm, feature); + writeMoveBFB(p.x_, p.y_, p.z_, speed, extrusion_mm3_per_mm, feature); return; } - writeExtrusion(p.x, p.y, p.z, speed, extrusion_mm3_per_mm, feature, update_extrusion_offset); + writeExtrusion(p.x_, p.y_, p.z_, speed, extrusion_mm3_per_mm, feature, update_extrusion_offset); } void GCodeExport::writeMoveBFB(const int x, const int y, const int z, const Velocity& speed, double extrusion_mm3_per_mm, PrintFeatureType feature) @@ -918,14 +918,14 @@ void GCodeExport::writeMoveBFB(const int x, const int y, const int z, const Velo currentPosition = Point3(x, y, z); estimateCalculator.plan( - TimeEstimateCalculator::Position(INT2MM(currentPosition.x), INT2MM(currentPosition.y), INT2MM(currentPosition.z), eToMm(current_e_value)), + TimeEstimateCalculator::Position(INT2MM(currentPosition.x_), INT2MM(currentPosition.y_), INT2MM(currentPosition.z_), eToMm(current_e_value)), speed, feature); } void GCodeExport::writeTravel(const coord_t x, const coord_t y, const coord_t z, const Velocity& speed) { - if (currentPosition.x == x && currentPosition.y == y && currentPosition.z == z) + if (currentPosition.x_ == x && currentPosition.y_ == y && currentPosition.z_ == z) { return; } @@ -955,7 +955,7 @@ void GCodeExport::writeExtrusion( const PrintFeatureType& feature, const bool update_extrusion_offset) { - if (currentPosition.x == x && currentPosition.y == y && currentPosition.z == z) + if (currentPosition.x_ == x && currentPosition.y_ == y && currentPosition.z_ == z) { return; } @@ -1036,7 +1036,7 @@ void GCodeExport::writeFXYZE(const Velocity& speed, const coord_t x, const coord total_bounding_box.include(Point3(gcode_pos.X, gcode_pos.Y, z)); *output_stream << " X" << MMtoStream{ gcode_pos.X } << " Y" << MMtoStream{ gcode_pos.Y }; - if (z != currentPosition.z) + if (z != currentPosition.z_) { *output_stream << " Z" << MMtoStream{ z }; } @@ -1071,7 +1071,7 @@ void GCodeExport::writeUnretractionAndPrime() currentSpeed = extruder_attr[current_extruder].last_retraction_prime_speed; } estimateCalculator.plan( - TimeEstimateCalculator::Position(INT2MM(currentPosition.x), INT2MM(currentPosition.y), INT2MM(currentPosition.z), eToMm(current_e_value)), + TimeEstimateCalculator::Position(INT2MM(currentPosition.x_), INT2MM(currentPosition.y_), INT2MM(currentPosition.z_), eToMm(current_e_value)), 25.0, PrintFeatureType::MoveRetraction); } @@ -1083,7 +1083,7 @@ void GCodeExport::writeUnretractionAndPrime() << extruder_attr[current_extruder].extruderCharacter << PrecisionedDouble{ 5, output_e } << new_line; currentSpeed = extruder_attr[current_extruder].last_retraction_prime_speed; estimateCalculator.plan( - TimeEstimateCalculator::Position(INT2MM(currentPosition.x), INT2MM(currentPosition.y), INT2MM(currentPosition.z), eToMm(current_e_value)), + TimeEstimateCalculator::Position(INT2MM(currentPosition.x_), INT2MM(currentPosition.y_), INT2MM(currentPosition.z_), eToMm(current_e_value)), currentSpeed, PrintFeatureType::MoveRetraction); } @@ -1096,7 +1096,7 @@ void GCodeExport::writeUnretractionAndPrime() *output_stream << PrecisionedDouble{ 5, output_e } << new_line; currentSpeed = extruder_attr[current_extruder].last_retraction_prime_speed; estimateCalculator.plan( - TimeEstimateCalculator::Position(INT2MM(currentPosition.x), INT2MM(currentPosition.y), INT2MM(currentPosition.z), eToMm(current_e_value)), + TimeEstimateCalculator::Position(INT2MM(currentPosition.x_), INT2MM(currentPosition.y_), INT2MM(currentPosition.z_), eToMm(current_e_value)), currentSpeed, PrintFeatureType::NoneType); } @@ -1178,7 +1178,7 @@ void GCodeExport::writeRetraction(const RetractionConfig& config, bool force, bo *output_stream << new_line; // Assume default UM2 retraction settings. estimateCalculator.plan( - TimeEstimateCalculator::Position(INT2MM(currentPosition.x), INT2MM(currentPosition.y), INT2MM(currentPosition.z), eToMm(current_e_value + retraction_diff_e_amount)), + TimeEstimateCalculator::Position(INT2MM(currentPosition.x_), INT2MM(currentPosition.y_), INT2MM(currentPosition.z_), eToMm(current_e_value + retraction_diff_e_amount)), 25.0, PrintFeatureType::MoveRetraction); // TODO: hardcoded values! } @@ -1190,7 +1190,7 @@ void GCodeExport::writeRetraction(const RetractionConfig& config, bool force, bo *output_stream << "G1 F" << PrecisionedDouble{ 1, speed * 60 } << " " << extr_attr.extruderCharacter << PrecisionedDouble{ 5, output_e } << new_line; currentSpeed = speed; estimateCalculator.plan( - TimeEstimateCalculator::Position(INT2MM(currentPosition.x), INT2MM(currentPosition.y), INT2MM(currentPosition.z), eToMm(current_e_value)), + TimeEstimateCalculator::Position(INT2MM(currentPosition.x_), INT2MM(currentPosition.y_), INT2MM(currentPosition.z_), eToMm(current_e_value)), currentSpeed, PrintFeatureType::MoveRetraction); extr_attr.last_retraction_prime_speed = config.primeSpeed; @@ -1227,7 +1227,7 @@ void GCodeExport::writeZhopEnd(Velocity speed /*= 0*/) speed = extruder.settings.get("speed_z_hop"); } is_z_hopped = 0; - currentPosition.z = current_layer_z; + currentPosition.z_ = current_layer_z; currentSpeed = speed; *output_stream << "G1 F" << PrecisionedDouble{ 1, speed * 60 } << " Z" << MMtoStream{ current_layer_z } << new_line; assert(speed > 0.0 && "Z hop speed should be positive."); @@ -1275,7 +1275,7 @@ void GCodeExport::startExtruder(const size_t new_extruder) Application::getInstance().communication->sendCurrentPosition(getPositionXY()); // Change the Z position so it gets re-written again. We do not know if the switch code modified the Z position. - currentPosition.z += 1; + currentPosition.z_ += 1; setExtruderFanNumber(new_extruder); } @@ -1353,7 +1353,7 @@ void GCodeExport::writePrimeTrain(const Velocity& travel_speed) if (! extruder_settings.get("extruder_prime_pos_abs")) { // currentPosition.z can be already z hopped - prime_pos += Point3(currentPosition.x, currentPosition.y, current_layer_z); + prime_pos += Point3(currentPosition.x_, currentPosition.y_, current_layer_z); } writeTravel(prime_pos, travel_speed); } @@ -1676,11 +1676,11 @@ void GCodeExport::insertWipeScript(const WipeScriptConfig& wipe_config) writeZhopStart(wipe_config.hop_amount, wipe_config.hop_speed); } - writeTravel(Point(wipe_config.brush_pos_x, currentPosition.y), wipe_config.move_speed); + writeTravel(Point(wipe_config.brush_pos_x, currentPosition.y_), wipe_config.move_speed); for (size_t i = 0; i < wipe_config.repeat_count; ++i) { - coord_t x = currentPosition.x + (i % 2 ? -wipe_config.move_distance : wipe_config.move_distance); - writeTravel(Point(x, currentPosition.y), wipe_config.move_speed); + coord_t x = currentPosition.x_ + (i % 2 ? -wipe_config.move_distance : wipe_config.move_distance); + writeTravel(Point(x, currentPosition.y_), wipe_config.move_speed); } writeTravel(prev_position, wipe_config.move_speed); diff --git a/src/infill.cpp b/src/infill.cpp index 6da3c25c4f..645c3f653e 100644 --- a/src/infill.cpp +++ b/src/infill.cpp @@ -590,7 +590,7 @@ coord_t Infill::getShiftOffsetFromInfillOriginAndRotation(const double& infill_r { if (infill_origin.X != 0 || infill_origin.Y != 0) { - const double rotation_rads = infill_rotation * M_PI / 180; + const double rotation_rads = infill_rotation * std::numbers::pi / 180; return infill_origin.X * std::cos(rotation_rads) - infill_origin.Y * std::sin(rotation_rads); } return 0; diff --git a/src/infill/GyroidInfill.cpp b/src/infill/GyroidInfill.cpp index d05767623a..861d2b95ae 100644 --- a/src/infill/GyroidInfill.cpp +++ b/src/infill/GyroidInfill.cpp @@ -30,7 +30,7 @@ void GyroidInfill::generateTotalGyroidInfill(Polygons& result_lines, bool zig_za step = pitch / num_steps; } pitch = step * num_steps; // recalculate to avoid precision errors - const double z_rads = 2 * M_PI * z / pitch; + const double z_rads = 2 * std::numbers::pi * z / pitch; const double cos_z = std::cos(z_rads); const double sin_z = std::sin(z_rads); std::vector odd_line_coords; @@ -42,19 +42,19 @@ void GyroidInfill::generateTotalGyroidInfill(Polygons& result_lines, bool zig_za if (std::abs(sin_z) <= std::abs(cos_z)) { // "vertical" lines - const double phase_offset = ((cos_z < 0) ? M_PI : 0) + M_PI; + const double phase_offset = ((cos_z < 0) ? std::numbers::pi : 0) + std::numbers::pi; for (coord_t y = 0; y < pitch; y += step) { - const double y_rads = 2 * M_PI * y / pitch; + const double y_rads = 2 * std::numbers::pi * y / pitch; const double a = cos_z; const double b = std::sin(y_rads + phase_offset); const double odd_c = sin_z * std::cos(y_rads + phase_offset); - const double even_c = sin_z * std::cos(y_rads + phase_offset + M_PI); + const double even_c = sin_z * std::cos(y_rads + phase_offset + std::numbers::pi); const double h = std::sqrt(a * a + b * b); - const double odd_x_rads = ((h != 0) ? std::asin(odd_c / h) + std::asin(b / h) : 0) - M_PI/2; - const double even_x_rads = ((h != 0) ? std::asin(even_c / h) + std::asin(b / h) : 0) - M_PI/2; - odd_line_coords.push_back(odd_x_rads / M_PI * pitch); - even_line_coords.push_back(even_x_rads / M_PI * pitch); + const double odd_x_rads = ((h != 0) ? std::asin(odd_c / h) + std::asin(b / h) : 0) - std::numbers::pi/2; + const double even_x_rads = ((h != 0) ? std::asin(even_c / h) + std::asin(b / h) : 0) - std::numbers::pi/2; + odd_line_coords.push_back(odd_x_rads / std::numbers::pi * pitch); + even_line_coords.push_back(even_x_rads / std::numbers::pi * pitch); } const unsigned num_coords = odd_line_coords.size(); unsigned num_columns = 0; @@ -134,19 +134,19 @@ void GyroidInfill::generateTotalGyroidInfill(Polygons& result_lines, bool zig_za else { // "horizontal" lines - const double phase_offset = (sin_z < 0) ? M_PI : 0; + const double phase_offset = (sin_z < 0) ? std::numbers::pi : 0; for (coord_t x = 0; x < pitch; x += step) { - const double x_rads = 2 * M_PI * x / pitch; + const double x_rads = 2 * std::numbers::pi * x / pitch; const double a = sin_z; const double b = std::cos(x_rads + phase_offset); - const double odd_c = cos_z * std::sin(x_rads + phase_offset + M_PI); + const double odd_c = cos_z * std::sin(x_rads + phase_offset + std::numbers::pi); const double even_c = cos_z * std::sin(x_rads + phase_offset); const double h = std::sqrt(a * a + b * b); - const double odd_y_rads = ((h != 0) ? std::asin(odd_c / h) + std::asin(b / h) : 0) + M_PI/2; - const double even_y_rads = ((h != 0) ? std::asin(even_c / h) + std::asin(b / h) : 0) + M_PI/2; - odd_line_coords.push_back(odd_y_rads / M_PI * pitch); - even_line_coords.push_back(even_y_rads / M_PI * pitch); + const double odd_y_rads = ((h != 0) ? std::asin(odd_c / h) + std::asin(b / h) : 0) + std::numbers::pi/2; + const double even_y_rads = ((h != 0) ? std::asin(even_c / h) + std::asin(b / h) : 0) + std::numbers::pi/2; + odd_line_coords.push_back(odd_y_rads / std::numbers::pi * pitch); + even_line_coords.push_back(even_y_rads / std::numbers::pi * pitch); } const unsigned num_coords = odd_line_coords.size(); unsigned num_rows = 0; diff --git a/src/infill/ImageBasedDensityProvider.cpp b/src/infill/ImageBasedDensityProvider.cpp index 0bbb6532f1..83e53e018f 100644 --- a/src/infill/ImageBasedDensityProvider.cpp +++ b/src/infill/ImageBasedDensityProvider.cpp @@ -3,10 +3,12 @@ #define STBI_FAILURE_USERMSG // enable user friendly bug messages for STB lib #define STB_IMAGE_IMPLEMENTATION // needed in order to enable the implementation of libs/std_image.h -#include +#include "infill/ImageBasedDensityProvider.h" + #include -#include "infill/ImageBasedDensityProvider.h" +#include + #include "infill/SierpinskiFill.h" #include "utils/AABB3D.h" @@ -35,17 +37,17 @@ ImageBasedDensityProvider::ImageBasedDensityProvider(const std::string filename, { // compute aabb Point middle = model_aabb.getMiddle(); Point model_aabb_size = model_aabb.max - model_aabb.min; - Point image_size2 = Point(image_size.x, image_size.y); + Point image_size2 = Point(image_size.x_, image_size.y_); float aabb_aspect_ratio = float(model_aabb_size.X) / float(model_aabb_size.Y); - float image_aspect_ratio = float(image_size.x) / float(image_size.y); + float image_aspect_ratio = float(image_size.x_) / float(image_size.y_); Point aabb_size; if (image_aspect_ratio < aabb_aspect_ratio) { - aabb_size = image_size2 * model_aabb_size.X / image_size.x; + aabb_size = image_size2 * model_aabb_size.X / image_size.x_; } else { - aabb_size = image_size2 * model_aabb_size.Y / image_size.y; + aabb_size = image_size2 * model_aabb_size.Y / image_size.y_; } print_aabb = AABB(middle - aabb_size / 2, middle + aabb_size / 2); assert(aabb_size.X >= model_aabb_size.X && aabb_size.Y >= model_aabb_size.Y); @@ -63,18 +65,18 @@ ImageBasedDensityProvider::~ImageBasedDensityProvider() float ImageBasedDensityProvider::operator()(const AABB3D& query_cube) const { - AABB query_box(Point(query_cube.min.x, query_cube.min.y), Point(query_cube.max.x, query_cube.max.y)); - Point img_min = (query_box.min - print_aabb.min - Point(1, 1)) * image_size.x / (print_aabb.max.X - print_aabb.min.X); - Point img_max = (query_box.max - print_aabb.min + Point(1, 1)) * image_size.y / (print_aabb.max.Y - print_aabb.min.Y); + AABB query_box(Point(query_cube.min.x_, query_cube.min.y_), Point(query_cube.max.x_, query_cube.max.y_)); + Point img_min = (query_box.min - print_aabb.min - Point(1, 1)) * image_size.x_ / (print_aabb.max.X - print_aabb.min.X); + Point img_max = (query_box.max - print_aabb.min + Point(1, 1)) * image_size.y_ / (print_aabb.max.Y - print_aabb.min.Y); long total_lightness = 0; int value_count = 0; - for (int x = std::max((coord_t)0, img_min.X); x <= std::min((coord_t)image_size.x - 1, img_max.X); x++) + for (int x = std::max((coord_t)0, img_min.X); x <= std::min((coord_t)image_size.x_ - 1, img_max.X); x++) { - for (int y = std::max((coord_t)0, img_min.Y); y <= std::min((coord_t)image_size.y - 1, img_max.Y); y++) + for (int y = std::max((coord_t)0, img_min.Y); y <= std::min((coord_t)image_size.y_ - 1, img_max.Y); y++) { - for (int z = 0; z < image_size.z; z++) + for (int z = 0; z < image_size.z_; z++) { - total_lightness += image[((image_size.y - 1 - y) * image_size.x + x) * image_size.z + z]; + total_lightness += image[((image_size.y_ - 1 - y) * image_size.x_ + x) * image_size.z_ + z]; value_count++; } } @@ -82,12 +84,12 @@ float ImageBasedDensityProvider::operator()(const AABB3D& query_cube) const if (value_count == 0) { // triangle falls outside of image or in between pixels, so we return the closest pixel Point closest_pixel = (img_min + img_max) / 2; - closest_pixel.X = std::max((coord_t)0, std::min((coord_t)image_size.x - 1, (coord_t)closest_pixel.X)); - closest_pixel.Y = std::max((coord_t)0, std::min((coord_t)image_size.y - 1, (coord_t)closest_pixel.Y)); + closest_pixel.X = std::max((coord_t)0, std::min((coord_t)image_size.x_ - 1, (coord_t)closest_pixel.X)); + closest_pixel.Y = std::max((coord_t)0, std::min((coord_t)image_size.y_ - 1, (coord_t)closest_pixel.Y)); assert(total_lightness == 0); - for (int z = 0; z < image_size.z; z++) + for (int z = 0; z < image_size.z_; z++) { - total_lightness += image[((image_size.y - 1 - closest_pixel.Y) * image_size.x + closest_pixel.X) * image_size.z + z]; + total_lightness += image[((image_size.y_ - 1 - closest_pixel.Y) * image_size.x_ + closest_pixel.X) * image_size.z_ + z]; value_count++; } } diff --git a/src/infill/SierpinskiFill.cpp b/src/infill/SierpinskiFill.cpp index b345493044..d6b45fc86f 100644 --- a/src/infill/SierpinskiFill.cpp +++ b/src/infill/SierpinskiFill.cpp @@ -42,12 +42,13 @@ SierpinskiFill::SierpinskiFill(const DensityProvider& density_provider, const AA { if (node->getValueError() < -allowed_length_error) { - spdlog::error("Node is subdivided without the appropriate value! value_error: {} from base {} el: {} er: {}, while the realized_length = {}", - node->getValueError(), - node->requested_length, - node->error_left, - node->error_right, - node->realized_length); + spdlog::error( + "Node is subdivided without the appropriate value! value_error: {} from base {} el: {} er: {}, while the realized_length = {}", + node->getValueError(), + node->requested_length, + node->error_left, + node->error_right, + node->realized_length); assert(false); } } @@ -296,7 +297,8 @@ bool SierpinskiFill::bubbleUpConstraintErrors() } -std::list::iterator SierpinskiFill::subdivide(std::list::iterator begin, std::list::iterator end, bool redistribute_errors) +std::list::iterator + SierpinskiFill::subdivide(std::list::iterator begin, std::list::iterator end, bool redistribute_errors) { if (redistribute_errors && deep_debug_checking) debugCheck(); @@ -429,7 +431,13 @@ void SierpinskiFill::balanceErrors(std::listgetValueError() < nodes[b]->getValueError(); }); + std::sort( + order.begin(), + order.end(), + [&nodes](int a, int b) + { + return nodes[a]->getValueError() < nodes[b]->getValueError(); + }); // add error to children with too low value float added = 0; @@ -573,7 +581,12 @@ void SierpinskiFill::diffuseError() error += nodal_value - triangle.realized_length; } } - spdlog::debug("pair_constrained_nodes: {}, constrained_nodes: {}, unconstrained_nodes: {}, subdivided_nodes: {}", pair_constrained_nodes, constrained_nodes, unconstrained_nodes, subdivided_nodes); + spdlog::debug( + "pair_constrained_nodes: {}, constrained_nodes: {}, unconstrained_nodes: {}, subdivided_nodes: {}", + pair_constrained_nodes, + constrained_nodes, + unconstrained_nodes, + subdivided_nodes); } bool SierpinskiFill::isConstrainedBackward(std::list::iterator it) @@ -761,7 +774,7 @@ Polygon SierpinskiFill::generateCross(coord_t z, coord_t min_dist_to_side, coord // \ / ==> \____/ // \ /}\ ^^^^--pocket_size / 2 // \/} / pocket_size_side - coord_t pocket_size_side = pocket_size * sqrt2 / 2; + coord_t pocket_size_side = pocket_size * std::numbers::sqrt2 / 2; Polygon pocketed; pocketed.reserve(ret.size() * 3 / 2); @@ -778,7 +791,8 @@ Polygon SierpinskiFill::generateCross(coord_t z, coord_t min_dist_to_side, coord bool is_straight_corner = prod < sqrt(vSize(v0) * vSize(v1)) * min_dist_to_side; // allow for rounding errors of up to min_dist_to_side if (is_straight_corner) { - coord_t pocket_rounding = std::min(std::min(pocket_size_side, vSize(v0) / 3), vSize(v1) / 3); // a third so that if a line segment is shortened on both sides the middle remains + coord_t pocket_rounding + = std::min(std::min(pocket_size_side, vSize(v0) / 3), vSize(v1) / 3); // a third so that if a line segment is shortened on both sides the middle remains pocketed.add(p1 + normal(v0, pocket_rounding)); pocketed.add(p1 + normal(v1, pocket_rounding)); } diff --git a/src/infill/SierpinskiFillProvider.cpp b/src/infill/SierpinskiFillProvider.cpp index 908c482d7e..b659b48fe9 100644 --- a/src/infill/SierpinskiFillProvider.cpp +++ b/src/infill/SierpinskiFillProvider.cpp @@ -1,10 +1,11 @@ // Copyright (c) 2022 Ultimaker B.V. // CuraEngine is released under the terms of the AGPLv3 or higher +#include "infill/SierpinskiFillProvider.h" + #include #include "infill/ImageBasedDensityProvider.h" -#include "infill/SierpinskiFillProvider.h" #include "infill/UniformDensityProvider.h" #include "utils/AABB3D.h" #include "utils/math.h" @@ -75,7 +76,7 @@ SierpinskiFillProvider::FractalConfig SierpinskiFillProvider::getFractalConfig(c aabb_size *= 2; depth += 2; } - const float half_sqrt2 = .5 * sqrt2; + const float half_sqrt2 = .5 * std::numbers::pi; if (depth > 0 && aabb_size * half_sqrt2 >= max_side_length) { aabb_size *= half_sqrt2; diff --git a/src/infill/SubDivCube.cpp b/src/infill/SubDivCube.cpp index d81b92d0e0..1d35ba0140 100644 --- a/src/infill/SubDivCube.cpp +++ b/src/infill/SubDivCube.cpp @@ -3,13 +3,13 @@ #include "infill/SubDivCube.h" +#include + #include "settings/types/Angle.h" //For the infill angle. #include "sliceDataStorage.h" #include "utils/math.h" #include "utils/polygonUtils.h" -#include - #define ONE_OVER_SQRT_2 0.7071067811865475244008443621048490392848359376884740 // 1 / sqrt(2) #define ONE_OVER_SQRT_3 0.577350269189625764509148780501957455647601751270126876018 // 1 / sqrt(3) #define ONE_OVER_SQRT_6 0.408248290463863016366214012450981898660991246776111688072 // 1 / sqrt(6) @@ -107,7 +107,7 @@ void SubDivCube::generateSubdivisionLines(const coord_t z, Polygons (&directiona { CubeProperties cube_properties = cube_properties_per_recursion_step[depth]; - const coord_t z_diff = std::abs(z - center.z); //!< the difference between the cube center and the target layer. + const coord_t z_diff = std::abs(z - center.z_); //!< the difference between the cube center and the target layer. if (z_diff > cube_properties.height / 2) //!< this cube does not touch the target layer. Early exit. { return; @@ -118,16 +118,16 @@ void SubDivCube::generateSubdivisionLines(const coord_t z, Polygons (&directiona Point a, b; //!< absolute coordinates of line endpoints relative_a.X = (cube_properties.square_height / 2) * (cube_properties.max_draw_z_diff - z_diff) / cube_properties.max_draw_z_diff; relative_b.X = -relative_a.X; - relative_a.Y = cube_properties.max_line_offset - ((z - (center.z - cube_properties.max_draw_z_diff)) * ONE_OVER_SQRT_2); + relative_a.Y = cube_properties.max_line_offset - ((z - (center.z_ - cube_properties.max_draw_z_diff)) * ONE_OVER_SQRT_2); relative_b.Y = relative_a.Y; rotatePointInitial(relative_a); rotatePointInitial(relative_b); for (int dir_idx = 0; dir_idx < 3; dir_idx++) //!< draw the line, then rotate 120 degrees. { - a.X = center.x + relative_a.X; - a.Y = center.y + relative_a.Y; - b.X = center.x + relative_b.X; - b.Y = center.y + relative_b.Y; + a.X = center.x_ + relative_a.X; + a.Y = center.y_ + relative_a.Y; + b.X = center.x_ + relative_b.X; + b.Y = center.y_ + relative_b.Y; addLineAndCombine(directional_line_groups[dir_idx], a, b); if (dir_idx < 2) { @@ -193,13 +193,13 @@ bool SubDivCube::isValidSubdivision(SliceMeshStorage& mesh, Point3& center, coor int inside; Ratio part_dist; // what percentage of the radius the target layer is away from the center along the z axis. 0 - 1 const coord_t layer_height = mesh.settings.get("layer_height"); - int bottom_layer = (center.z - radius) / layer_height; - int top_layer = (center.z + radius) / layer_height; + int bottom_layer = (center.z_ - radius) / layer_height; + int top_layer = (center.z_ + radius) / layer_height; for (int test_layer = bottom_layer; test_layer <= top_layer; test_layer += 3) // steps of three. Low-hanging speed gain. { - part_dist = Ratio{ static_cast(test_layer * layer_height - center.z) } / radius; + part_dist = Ratio{ static_cast(test_layer * layer_height - center.z_) } / radius; sphere_slice_radius2 = radius * radius * (1.0 - (part_dist * part_dist)); - Point loc(center.x, center.y); + Point loc(center.x_, center.y_); inside = distanceFromPointToMesh(mesh, test_layer, loc, &distance2); if (inside == 1) @@ -238,7 +238,7 @@ coord_t SubDivCube::distanceFromPointToMesh(SliceMeshStorage& mesh, const LayerI Point centerpoint = location; bool inside = collide.inside(centerpoint); ClosestPolygonPoint border_point = PolygonUtils::moveInside2(collide, centerpoint); - Point diff = border_point.location - location; + Point diff = border_point.location_ - location; *distance2 = vSize2(diff); if (inside) { diff --git a/src/mesh.cpp b/src/mesh.cpp index 9bacfcf1d1..eba67cf02c 100644 --- a/src/mesh.cpp +++ b/src/mesh.cpp @@ -1,9 +1,10 @@ // Copyright (c) 2022 Ultimaker B.V. // CuraEngine is released under the terms of the AGPLv3 or higher +#include "mesh.h" + #include -#include "mesh.h" #include "utils/floatpoint.h" namespace cura @@ -16,14 +17,21 @@ const int vertex_meld_distance = MM2INT(0.03); */ static inline uint32_t pointHash(const Point3& p) { - return ((p.x + vertex_meld_distance / 2) / vertex_meld_distance) ^ (((p.y + vertex_meld_distance / 2) / vertex_meld_distance) << 10) ^ (((p.z + vertex_meld_distance / 2) / vertex_meld_distance) << 20); + return ((p.x_ + vertex_meld_distance / 2) / vertex_meld_distance) ^ (((p.y_ + vertex_meld_distance / 2) / vertex_meld_distance) << 10) + ^ (((p.z_ + vertex_meld_distance / 2) / vertex_meld_distance) << 20); } -Mesh::Mesh(Settings& parent) : settings(parent), has_disconnected_faces(false), has_overlapping_faces(false) +Mesh::Mesh(Settings& parent) + : settings(parent) + , has_disconnected_faces(false) + , has_overlapping_faces(false) { } -Mesh::Mesh() : settings(), has_disconnected_faces(false), has_overlapping_faces(false) +Mesh::Mesh() + : settings() + , has_disconnected_faces(false) + , has_overlapping_faces(false) { } @@ -226,7 +234,7 @@ int Mesh::getFaceIdxWithPoints(int idx0, int idx1, int notFaceIdx, int notFaceVe double det = n * n0.cross(n1); double angle = std::atan2(det, dot); if (angle < 0) - angle += 2 * M_PI; // 0 <= angle < 2* M_PI + angle += 2 * std::numbers::pi; // 0 <= angle < 2* std::numbers::pi if (angle == 0) { diff --git a/src/pathPlanning/Comb.cpp b/src/pathPlanning/Comb.cpp index eda5d5bc1d..d98ec095b6 100644 --- a/src/pathPlanning/Comb.cpp +++ b/src/pathPlanning/Comb.cpp @@ -3,6 +3,10 @@ #include "pathPlanning/Comb.h" +#include +#include // function +#include + #include "Application.h" #include "ExtruderTrain.h" #include "Slice.h" @@ -13,10 +17,6 @@ #include "utils/SVG.h" #include "utils/linearAlg2D.h" -#include -#include // function -#include - namespace cura { @@ -435,7 +435,7 @@ bool Comb::moveInside(Polygons& boundary_inside, bool is_inside, LocToLineGrid* } else { - inside_poly = cpp.poly_idx; + inside_poly = cpp.poly_idx_; return true; } } @@ -498,7 +498,7 @@ void Comb::Crossing::findCrossingInOrMid(const PartsView& partsView_inside, cons close_towards_start_penalty_function); if (crossing_1_in_cp.isValid()) { - dest_crossing_poly = crossing_1_in_cp.poly; + dest_crossing_poly = crossing_1_in_cp.poly_; in_or_mid = result; } else @@ -569,14 +569,14 @@ std::shared_ptr> Comb::Cross bool seen_close_enough_connection = false; for (std::pair& crossing_candidate : crossing_out_candidates) { - const coord_t crossing_dist2 = vSize2(crossing_candidate.first.location - crossing_candidate.second.location); + const coord_t crossing_dist2 = vSize2(crossing_candidate.first.location_ - crossing_candidate.second.location_); if (crossing_dist2 > comber.max_crossing_dist2 * 2) { // preliminary filtering continue; } - const coord_t dist_to_start = vSize(crossing_candidate.second.location - estimated_start); // use outside location, so that the crossing direction is taken into account - const coord_t dist_to_end = vSize(crossing_candidate.second.location - estimated_end); + const coord_t dist_to_start = vSize(crossing_candidate.second.location_ - estimated_start); // use outside location, so that the crossing direction is taken into account + const coord_t dist_to_end = vSize(crossing_candidate.second.location_ - estimated_end); const coord_t detour_dist = dist_to_start + dist_to_end; const coord_t detour_score = crossing_dist2 + detour_dist * detour_dist / 1000; // prefer a closest connection over a detour // The detour distance is generally large compared to the crossing distance. @@ -607,7 +607,7 @@ std::shared_ptr> Comb::Cross if (best_crossing_dist2 > comber.max_crossing_dist2) { // find closer point on line segments, rather than moving between vertices of the polygons only PolygonUtils::walkToNearestSmallestConnection(*best_in, *best_out); - best_crossing_dist2 = vSize2(best_in->location - best_out->location); + best_crossing_dist2 = vSize2(best_in->location_ - best_out->location_); if (best_crossing_dist2 > comber.max_crossing_dist2) { return std::shared_ptr>(); diff --git a/src/settings/AdaptiveLayerHeights.cpp b/src/settings/AdaptiveLayerHeights.cpp index d70332514d..e2ebe6e37b 100644 --- a/src/settings/AdaptiveLayerHeights.cpp +++ b/src/settings/AdaptiveLayerHeights.cpp @@ -1,13 +1,14 @@ // Copyright (c) 2022 Ultimaker B.V. // CuraEngine is released under the terms of the AGPLv3 or higher +#include "settings/AdaptiveLayerHeights.h" + #include #include #include #include "Application.h" #include "Slice.h" -#include "settings/AdaptiveLayerHeights.h" #include "settings/EnumSettings.h" #include "settings/types/Angle.h" #include "utils/floatpoint.h" @@ -15,7 +16,8 @@ namespace cura { -AdaptiveLayer::AdaptiveLayer(const coord_t layer_height) : layer_height{ layer_height } +AdaptiveLayer::AdaptiveLayer(const coord_t layer_height) + : layer_height{ layer_height } { } @@ -62,7 +64,7 @@ void AdaptiveLayerHeights::calculateLayers() Settings const& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; auto slicing_tolerance = mesh_group_settings.get("slicing_tolerance"); std::vector triangles_of_interest; - const coord_t model_max_z = meshgroup->max().z; + const coord_t model_max_z = meshgroup->max().z_; coord_t z_level = 0; coord_t previous_layer_height = 0; @@ -218,7 +220,7 @@ void AdaptiveLayerHeights::calculateMeshTriangleSlopes() // prevent flat surfaces from influencing the algorithm if (z_angle == 0) { - z_angle = M_PI; + z_angle = std::numbers::pi; } face_min_z_values.push_back(MM2INT(min_z)); diff --git a/src/settings/Settings.cpp b/src/settings/Settings.cpp index 74ec0d3606..22cf7d1c8b 100644 --- a/src/settings/Settings.cpp +++ b/src/settings/Settings.cpp @@ -151,7 +151,7 @@ coord_t Settings::get(const std::string& key) const template<> AngleRadians Settings::get(const std::string& key) const { - return get(key) * M_PI / 180; // The settings are all in degrees, but we need to interpret them as radians. + return get(key) * std::numbers::pi / 180; // The settings are all in degrees, but we need to interpret them as radians. } template<> diff --git a/src/sliceDataStorage.cpp b/src/sliceDataStorage.cpp index 0dddecb5b7..ff69b9d009 100644 --- a/src/sliceDataStorage.cpp +++ b/src/sliceDataStorage.cpp @@ -237,7 +237,7 @@ Point SliceMeshStorage::getZSeamHint() const if (settings.get("z_seam_relative")) { Point3 middle = bounding_box.getMiddle(); - pos += Point(middle.x, middle.y); + pos += Point(middle.x_, middle.y_); } return pos; } @@ -542,13 +542,13 @@ Polygons SliceDataStorage::getMachineBorder(int checking_extruder_nr) const case BuildPlateShape::ELLIPTIC: { // Construct an ellipse to approximate the build volume. - const coord_t width = machine_size.max.x - machine_size.min.x; - const coord_t depth = machine_size.max.y - machine_size.min.y; + const coord_t width = machine_size.max.x_ - machine_size.min.x_; + const coord_t depth = machine_size.max.y_ - machine_size.min.y_; constexpr unsigned int circle_resolution = 50; for (unsigned int i = 0; i < circle_resolution; i++) { - const double angle = M_PI * 2 * i / circle_resolution; - outline.emplace_back(machine_size.getMiddle().x + std::cos(angle) * width / 2, machine_size.getMiddle().y + std::sin(angle) * depth / 2); + const double angle = std::numbers::pi * 2 * i / circle_resolution; + outline.emplace_back(machine_size.getMiddle().x_ + std::cos(angle) * width / 2, machine_size.getMiddle().y_ + std::sin(angle) * depth / 2); } break; } @@ -569,7 +569,7 @@ Polygons SliceDataStorage::getMachineBorder(int checking_extruder_nr) const { for (Point& p : poly) { - p = Point(machine_size.max.x / 2 + p.X, machine_size.max.y / 2 - p.Y); + p = Point(machine_size.max.x_ / 2 + p.X, machine_size.max.y_ / 2 - p.Y); } } } @@ -596,7 +596,7 @@ Polygons SliceDataStorage::getMachineBorder(int checking_extruder_nr) const Point translation(extruder_settings.get("machine_nozzle_offset_x"), extruder_settings.get("machine_nozzle_offset_y")); prime_pos -= translation; Polygons prime_polygons; - prime_polygons.emplace_back(PolygonUtils::makeCircle(prime_pos, prime_clearance, M_PI / 32)); + prime_polygons.emplace_back(PolygonUtils::makeCircle(prime_pos, prime_clearance, std::numbers::pi / 32)); disallowed_areas = disallowed_areas.unionPolygons(prime_polygons); } diff --git a/src/slicer.cpp b/src/slicer.cpp index 2758d133f0..94dc2aeb64 100644 --- a/src/slicer.cpp +++ b/src/slicer.cpp @@ -544,11 +544,7 @@ void SlicerLayer::stitch_extensive(Polygons& open_polylines) { unsigned int best_polyline_1_idx = -1; unsigned int best_polyline_2_idx = -1; - GapCloserResult best_result; - best_result.len = POINT_MAX; - best_result.polygonIdx = -1; - best_result.pointIdxA = -1; - best_result.pointIdxB = -1; + std::optional best_result; for (unsigned int polyline_1_idx = 0; polyline_1_idx < open_polylines.size(); polyline_1_idx++) { @@ -557,8 +553,8 @@ void SlicerLayer::stitch_extensive(Polygons& open_polylines) continue; { - GapCloserResult res = findPolygonGapCloser(polyline_1[0], polyline_1.back()); - if (res.len > 0 && res.len < best_result.len) + std::optional res = findPolygonGapCloser(polyline_1[0], polyline_1.back()); + if (res && (! best_result || res->len < best_result->len)) { best_polyline_1_idx = polyline_1_idx; best_polyline_2_idx = polyline_1_idx; @@ -572,8 +568,8 @@ void SlicerLayer::stitch_extensive(Polygons& open_polylines) if (polyline_2.size() < 1 || polyline_1_idx == polyline_2_idx) continue; - GapCloserResult res = findPolygonGapCloser(polyline_1[0], polyline_2.back()); - if (res.len > 0 && res.len < best_result.len) + std::optional res = findPolygonGapCloser(polyline_1[0], polyline_2.back()); + if (res && (! best_result || res->len < best_result->len)) { best_polyline_1_idx = polyline_1_idx; best_polyline_2_idx = polyline_2_idx; @@ -582,20 +578,20 @@ void SlicerLayer::stitch_extensive(Polygons& open_polylines) } } - if (best_result.len < POINT_MAX) + if (best_result) { if (best_polyline_1_idx == best_polyline_2_idx) { - if (best_result.pointIdxA == best_result.pointIdxB) + if (best_result->pointIdxA == best_result->pointIdxB) { polygons.add(open_polylines[best_polyline_1_idx]); open_polylines[best_polyline_1_idx].clear(); } - else if (best_result.AtoB) + else if (best_result->AtoB) { PolygonRef poly = polygons.newPoly(); - for (unsigned int j = best_result.pointIdxA; j != best_result.pointIdxB; j = (j + 1) % polygons[best_result.polygonIdx].size()) - poly.add(polygons[best_result.polygonIdx][j]); + for (unsigned int j = best_result->pointIdxA; j != best_result->pointIdxB; j = (j + 1) % polygons[best_result->polygonIdx].size()) + poly.add(polygons[best_result->polygonIdx][j]); for (unsigned int j = open_polylines[best_polyline_1_idx].size() - 1; int(j) >= 0; j--) poly.add(open_polylines[best_polyline_1_idx][j]); open_polylines[best_polyline_1_idx].clear(); @@ -604,24 +600,24 @@ void SlicerLayer::stitch_extensive(Polygons& open_polylines) { unsigned int n = polygons.size(); polygons.add(open_polylines[best_polyline_1_idx]); - for (unsigned int j = best_result.pointIdxB; j != best_result.pointIdxA; j = (j + 1) % polygons[best_result.polygonIdx].size()) - polygons[n].add(polygons[best_result.polygonIdx][j]); + for (unsigned int j = best_result->pointIdxB; j != best_result->pointIdxA; j = (j + 1) % polygons[best_result->polygonIdx].size()) + polygons[n].add(polygons[best_result->polygonIdx][j]); open_polylines[best_polyline_1_idx].clear(); } } else { - if (best_result.pointIdxA == best_result.pointIdxB) + if (best_result->pointIdxA == best_result->pointIdxB) { for (unsigned int n = 0; n < open_polylines[best_polyline_1_idx].size(); n++) open_polylines[best_polyline_2_idx].add(open_polylines[best_polyline_1_idx][n]); open_polylines[best_polyline_1_idx].clear(); } - else if (best_result.AtoB) + else if (best_result->AtoB) { Polygon poly; - for (unsigned int n = best_result.pointIdxA; n != best_result.pointIdxB; n = (n + 1) % polygons[best_result.polygonIdx].size()) - poly.add(polygons[best_result.polygonIdx][n]); + for (unsigned int n = best_result->pointIdxA; n != best_result->pointIdxB; n = (n + 1) % polygons[best_result->polygonIdx].size()) + poly.add(polygons[best_result->polygonIdx][n]); for (unsigned int n = poly.size() - 1; int(n) >= 0; n--) open_polylines[best_polyline_2_idx].add(poly[n]); for (unsigned int n = 0; n < open_polylines[best_polyline_1_idx].size(); n++) @@ -630,8 +626,8 @@ void SlicerLayer::stitch_extensive(Polygons& open_polylines) } else { - for (unsigned int n = best_result.pointIdxB; n != best_result.pointIdxA; n = (n + 1) % polygons[best_result.polygonIdx].size()) - open_polylines[best_polyline_2_idx].add(polygons[best_result.polygonIdx][n]); + for (unsigned int n = best_result->pointIdxB; n != best_result->pointIdxA; n = (n + 1) % polygons[best_result->polygonIdx].size()) + open_polylines[best_polyline_2_idx].add(polygons[best_result->polygonIdx][n]); for (unsigned int n = open_polylines[best_polyline_1_idx].size() - 1; int(n) >= 0; n--) open_polylines[best_polyline_2_idx].add(open_polylines[best_polyline_1_idx][n]); open_polylines[best_polyline_1_idx].clear(); @@ -645,19 +641,19 @@ void SlicerLayer::stitch_extensive(Polygons& open_polylines) } } -GapCloserResult SlicerLayer::findPolygonGapCloser(Point ip0, Point ip1) +std::optional SlicerLayer::findPolygonGapCloser(Point ip0, Point ip1) { - GapCloserResult ret; - ClosePolygonResult c1 = findPolygonPointClosestTo(ip0); - ClosePolygonResult c2 = findPolygonPointClosestTo(ip1); - if (c1.polygonIdx < 0 || c1.polygonIdx != c2.polygonIdx) + std::optional c1 = findPolygonPointClosestTo(ip0); + std::optional c2 = findPolygonPointClosestTo(ip1); + if (! c1 || ! c2 || c1->polygonIdx != c2->polygonIdx) { - ret.len = -1; - return ret; + return std::nullopt; } - ret.polygonIdx = c1.polygonIdx; - ret.pointIdxA = c1.pointIdx; - ret.pointIdxB = c2.pointIdx; + + GapCloserResult ret; + ret.polygonIdx = c1->polygonIdx; + ret.pointIdxA = c1->pointIdx; + ret.pointIdxB = c2->pointIdx; ret.AtoB = true; if (ret.pointIdxA == ret.pointIdxB) @@ -702,13 +698,12 @@ GapCloserResult SlicerLayer::findPolygonGapCloser(Point ip0, Point ip1) return ret; } -ClosePolygonResult SlicerLayer::findPolygonPointClosestTo(Point input) +std::optional SlicerLayer::findPolygonPointClosestTo(Point input) { - ClosePolygonResult ret; - for (unsigned int n = 0; n < polygons.size(); n++) + for (size_t n = 0; n < polygons.size(); n++) { Point p0 = polygons[n][polygons[n].size() - 1]; - for (unsigned int i = 0; i < polygons[n].size(); i++) + for (size_t i = 0; i < polygons[n].size(); i++) { Point p1 = polygons[n][i]; @@ -723,6 +718,7 @@ ClosePolygonResult SlicerLayer::findPolygonPointClosestTo(Point input) Point q = p0 + pDiff * distOnLine / lineLength; if (shorterThen(q - input, MM2INT(0.1))) { + ClosePolygonResult ret; ret.polygonIdx = n; ret.pointIdx = i; return ret; @@ -732,8 +728,8 @@ ClosePolygonResult SlicerLayer::findPolygonPointClosestTo(Point input) p0 = p1; } } - ret.polygonIdx = -1; - return ret; + + return std::nullopt; } void SlicerLayer::makePolygons(const Mesh* mesh) @@ -873,9 +869,9 @@ void Slicer::buildSegments(const Mesh& mesh, const std::vector(p0.z == z) * -static_cast(p0.z < 1); - p1.z += static_cast(p1.z == z) * -static_cast(p1.z < 1); - p2.z += static_cast(p2.z == z) * -static_cast(p2.z < 1); + p0.z_ += static_cast(p0.z_ == z) * -static_cast(p0.z_ < 1); + p1.z_ += static_cast(p1.z_ == z) * -static_cast(p1.z_ < 1); + p2.z_ += static_cast(p2.z_ == z) * -static_cast(p2.z_ < 1); } SlicerSegment s; @@ -909,49 +905,49 @@ void Slicer::buildSegments(const Mesh& mesh, const std::vector z && p2.z > z) // 1_______2 + if (p0.z_ < z && p1.z_ > z && p2.z_ > z) // 1_______2 { // \ / s = project2D(p0, p2, p1, z); //------------- z end_edge_idx = 0; // \ / } // 0 - else if (p0.z > z && p1.z <= z && p2.z <= z) // 0 + else if (p0.z_ > z && p1.z_ <= z && p2.z_ <= z) // 0 { // / \ . s = project2D(p0, p1, p2, z); //------------- z end_edge_idx = 2; // / \ . - if (p2.z == z) // 1_______2 + if (p2.z_ == z) // 1_______2 { s.endVertex = &v2; } } - else if (p1.z < z && p0.z > z && p2.z > z) // 0_______2 + else if (p1.z_ < z && p0.z_ > z && p2.z_ > z) // 0_______2 { // \ / s = project2D(p1, p0, p2, z); //------------- z end_edge_idx = 1; // \ / } // 1 - else if (p1.z > z && p0.z <= z && p2.z <= z) // 1 + else if (p1.z_ > z && p0.z_ <= z && p2.z_ <= z) // 1 { // / \ . s = project2D(p1, p2, p0, z); //------------- z end_edge_idx = 0; // / \ . - if (p0.z == z) // 0_______2 + if (p0.z_ == z) // 0_______2 { s.endVertex = &v0; } } - else if (p2.z < z && p1.z > z && p0.z > z) // 0_______1 + else if (p2.z_ < z && p1.z_ > z && p0.z_ > z) // 0_______1 { // \ / s = project2D(p2, p1, p0, z); //------------- z end_edge_idx = 2; // \ / } // 2 - else if (p2.z > z && p1.z <= z && p0.z <= z) // 2 + else if (p2.z_ > z && p1.z_ <= z && p0.z_ <= z) // 2 { // / \ . s = project2D(p2, p0, p1, z); //------------- z end_edge_idx = 1; // / \ . - if (p1.z == z) // 0_______1 + if (p1.z_ == z) // 0_______1 { s.endVertex = &v1; } @@ -1131,24 +1127,24 @@ std::vector> Slicer::buildZHeightsForFaces(const Mes Point3 p2 = v2.p; // find the minimum and maximum z point - int32_t minZ = p0.z; - if (p1.z < minZ) + int32_t minZ = p0.z_; + if (p1.z_ < minZ) { - minZ = p1.z; + minZ = p1.z_; } - if (p2.z < minZ) + if (p2.z_ < minZ) { - minZ = p2.z; + minZ = p2.z_; } - int32_t maxZ = p0.z; - if (p1.z > maxZ) + int32_t maxZ = p0.z_; + if (p1.z_ > maxZ) { - maxZ = p1.z; + maxZ = p1.z_; } - if (p2.z > maxZ) + if (p2.z_ > maxZ) { - maxZ = p2.z; + maxZ = p2.z_; } zHeights.emplace_back(std::make_pair(minZ, maxZ)); @@ -1161,10 +1157,10 @@ SlicerSegment Slicer::project2D(const Point3& p0, const Point3& p1, const Point3 { SlicerSegment seg; - seg.start.X = interpolate(z, p0.z, p1.z, p0.x, p1.x); - seg.start.Y = interpolate(z, p0.z, p1.z, p0.y, p1.y); - seg.end.X = interpolate(z, p0.z, p2.z, p0.x, p2.x); - seg.end.Y = interpolate(z, p0.z, p2.z, p0.y, p2.y); + seg.start.X = interpolate(z, p0.z_, p1.z_, p0.x_, p1.x_); + seg.start.Y = interpolate(z, p0.z_, p1.z_, p0.y_, p1.y_); + seg.end.X = interpolate(z, p0.z_, p2.z_, p0.x_, p2.x_); + seg.end.Y = interpolate(z, p0.z_, p2.z_, p0.y_, p2.y_); return seg; } diff --git a/src/support.cpp b/src/support.cpp index 6bae947fa2..233c8ab499 100644 --- a/src/support.cpp +++ b/src/support.cpp @@ -485,16 +485,16 @@ Polygons AreaSupport::join(const SliceDataStorage& storage, const Polygons& supp case BuildPlateShape::ELLIPTIC: { // Construct an ellipse to approximate the build volume. - const coord_t width = storage.machine_size.max.x - storage.machine_size.min.x; - const coord_t depth = storage.machine_size.max.y - storage.machine_size.min.y; + const coord_t width = storage.machine_size.max.x_ - storage.machine_size.min.x_; + const coord_t depth = storage.machine_size.max.y_ - storage.machine_size.min.y_; Polygon border_circle; constexpr unsigned int circle_resolution = 50; for (unsigned int i = 0; i < circle_resolution; i++) { const AngleRadians angle = TAU * i / circle_resolution; const Point3 machine_middle = storage.machine_size.getMiddle(); - const coord_t x = machine_middle.x + cos(angle) * width / 2; - const coord_t y = machine_middle.y + sin(angle) * depth / 2; + const coord_t x = machine_middle.x_ + cos(angle) * width / 2; + const coord_t y = machine_middle.y_ + sin(angle) * depth / 2; border_circle.emplace_back(x, y); } machine_volume_border.add(border_circle); diff --git a/src/utils/AABB3D.cpp b/src/utils/AABB3D.cpp index 6177e159d5..b354ad0dc2 100644 --- a/src/utils/AABB3D.cpp +++ b/src/utils/AABB3D.cpp @@ -1,5 +1,5 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #include "utils/AABB3D.h" @@ -10,15 +10,15 @@ namespace cura { -AABB3D::AABB3D() -: min(std::numeric_limits::max(), std::numeric_limits::max(), std::numeric_limits::max()) -, max(std::numeric_limits::min(), std::numeric_limits::min(), std::numeric_limits::min()) +AABB3D::AABB3D() + : min(std::numeric_limits::max(), std::numeric_limits::max(), std::numeric_limits::max()) + , max(std::numeric_limits::min(), std::numeric_limits::min(), std::numeric_limits::min()) { } -AABB3D::AABB3D(Point3 min, Point3 max) -: min(min) -, max(max) +AABB3D::AABB3D(Point3 min, Point3 max) + : min(min) + , max(max) { } @@ -29,18 +29,13 @@ Point3 AABB3D::getMiddle() const AABB AABB3D::flatten() const { - return AABB(Point(min.x, min.y), Point(max.x, max.y)); + return AABB(Point(min.x_, min.y_), Point(max.x_, max.y_)); } bool AABB3D::hit(const AABB3D& other) const { - if ( max.x < other.min.x - || min.x > other.max.x - || max.y < other.min.y - || min.y > other.max.y - || max.z < other.min.z - || min.z > other.max.z) + if (max.x_ < other.min.x_ || min.x_ > other.max.x_ || max.y_ < other.min.y_ || min.y_ > other.max.y_ || max.z_ < other.min.z_ || min.z_ > other.max.z_) { return false; } @@ -49,31 +44,31 @@ bool AABB3D::hit(const AABB3D& other) const AABB3D AABB3D::include(Point3 p) { - min.x = std::min(min.x, p.x); - min.y = std::min(min.y, p.y); - min.z = std::min(min.z, p.z); - max.x = std::max(max.x, p.x); - max.y = std::max(max.y, p.y); - max.z = std::max(max.z, p.z); + min.x_ = std::min(min.x_, p.x_); + min.y_ = std::min(min.y_, p.y_); + min.z_ = std::min(min.z_, p.z_); + max.x_ = std::max(max.x_, p.x_); + max.y_ = std::max(max.y_, p.y_); + max.z_ = std::max(max.z_, p.z_); return *this; } AABB3D AABB3D::include(const AABB3D& aabb) { // Note that this is different from including the min and max points, since when 'min > max' it's used to denote an negative/empty box. - min.x = std::min(min.x, aabb.min.x); - min.y = std::min(min.y, aabb.min.y); - min.z = std::min(min.z, aabb.min.z); - max.x = std::max(max.x, aabb.max.x); - max.y = std::max(max.y, aabb.max.y); - max.z = std::max(max.z, aabb.max.z); + min.x_ = std::min(min.x_, aabb.min.x_); + min.y_ = std::min(min.y_, aabb.min.y_); + min.z_ = std::min(min.z_, aabb.min.z_); + max.x_ = std::max(max.x_, aabb.max.x_); + max.y_ = std::max(max.y_, aabb.max.y_); + max.z_ = std::max(max.z_, aabb.max.z_); return *this; } AABB3D AABB3D::includeZ(coord_t z) { - min.z = std::min(min.z, z); - max.z = std::max(max.z, z); + min.z_ = std::min(min.z_, z); + max.z_ = std::max(max.z_, z); return *this; } @@ -95,7 +90,7 @@ AABB3D AABB3D::expand(coord_t outset) { min -= Point3(outset, outset, outset); max += Point3(outset, outset, outset); - if (min.x > max.x || min.y > max.y || min.z > max.z) + if (min.x_ > max.x_ || min.y_ > max.y_ || min.z_ > max.z_) { // make this AABB3D invalid *this = AABB3D(); } @@ -106,12 +101,11 @@ AABB3D AABB3D::expandXY(coord_t outset) { min -= Point3(outset, outset, 0); max += Point3(outset, outset, 0); - if (min.x > max.x || min.y > max.y) + if (min.x_ > max.x_ || min.y_ > max.y_) { // make this AABB3D invalid *this = AABB3D(); } return *this; } -}//namespace cura - +} // namespace cura diff --git a/src/utils/ExtrusionSegment.cpp b/src/utils/ExtrusionSegment.cpp index c264604933..872bae3000 100644 --- a/src/utils/ExtrusionSegment.cpp +++ b/src/utils/ExtrusionSegment.cpp @@ -32,11 +32,11 @@ Polygons ExtrusionSegment::toPolygons(bool reduced) float alpha = std::acos(delta_r / vec_length_fixed); // Angle between the slope along the edge of the polygon (due to varying line width) and the centerline. if (to.w > from.w) { - alpha = M_PI - alpha; + alpha = std::numbers::pi - alpha; } - assert(alpha > -M_PI - 0.0001); - assert(alpha < M_PI + 0.0001); - if (alpha <= -M_PI || alpha >= M_PI) + assert(alpha > -std::numbers::pi - 0.0001); + assert(alpha < std::numbers::pi + 0.0001); + if (alpha <= -std::numbers::pi || alpha >= std::numbers::pi) { RUN_ONCE(spdlog::warn("Line joint slope is out of bounds (should be between -pi and +pi): {}", alpha)); } @@ -44,22 +44,22 @@ Polygons ExtrusionSegment::toPolygons(bool reduced) float dir = std::atan(vec.Y / static_cast(vec.X)); if (vec.X < 0) { - dir += M_PI; + dir += std::numbers::pi; } // Draw the endcap on the "from" vertex's end. { poly.emplace_back(from.p + Point(from.w / 2 * cos(alpha + dir), from.w / 2 * sin(alpha + dir))); - float start_a = 2 * M_PI; + float start_a = 2 * std::numbers::pi; while (start_a > alpha + dir) { start_a -= a_step; } start_a += a_step; - float end_a = -2 * M_PI; - while (end_a < 2 * M_PI - alpha + dir) + float end_a = -2 * std::numbers::pi; + while (end_a < 2 * std::numbers::pi - alpha + dir) { end_a += a_step; } @@ -69,14 +69,14 @@ Polygons ExtrusionSegment::toPolygons(bool reduced) { poly.emplace_back(from.p + Point(from.w / 2 * cos(a), from.w / 2 * sin(a))); } - poly.emplace_back(from.p + Point(from.w / 2 * cos(2 * M_PI - alpha + dir), from.w / 2 * sin(2 * M_PI - alpha + dir))); + poly.emplace_back(from.p + Point(from.w / 2 * cos(2 * std::numbers::pi - alpha + dir), from.w / 2 * sin(2 * std::numbers::pi - alpha + dir))); } // Draw the endcap on the "to" vertex's end. { - poly.emplace_back(to.p + Point(to.w / 2 * cos(2 * M_PI - alpha + dir), to.w / 2 * sin(2 * M_PI - alpha + dir))); // Also draws the main diagonal from the "from" vertex to the "to" vertex! + poly.emplace_back(to.p + Point(to.w / 2 * cos(2 * std::numbers::pi - alpha + dir), to.w / 2 * sin(2 * std::numbers::pi - alpha + dir))); // Also draws the main diagonal from the "from" vertex to the "to" vertex! - float start_a = 2 * M_PI; + float start_a = 2 * std::numbers::pi; while (start_a > alpha + dir) { start_a -= a_step; @@ -88,8 +88,8 @@ Polygons ExtrusionSegment::toPolygons(bool reduced) start_a += a_step; } - float end_a = -2 * M_PI; - while (end_a < 2 * M_PI - alpha + dir) + float end_a = -2 * std::numbers::pi; + while (end_a < 2 * std::numbers::pi - alpha + dir) end_a += a_step; if (reduced) { @@ -97,7 +97,7 @@ Polygons ExtrusionSegment::toPolygons(bool reduced) } else { - end_a -= 2 * M_PI; + end_a -= 2 * std::numbers::pi; } // Draw the endcap. diff --git a/src/utils/FMatrix4x3.cpp b/src/utils/FMatrix4x3.cpp index 1a8260bdcf..a52621b680 100644 --- a/src/utils/FMatrix4x3.cpp +++ b/src/utils/FMatrix4x3.cpp @@ -1,11 +1,11 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #include "utils/FMatrix4x3.h" //The definitions we're implementing. -#include "utils/floatpoint.h" //This matrix gets applied to floating point coordinates. -#include "utils/IntPoint.h" //Conversion directly into integer-based coordinates. #include "settings/types/Ratio.h" //Scale factor. +#include "utils/IntPoint.h" //Conversion directly into integer-based coordinates. +#include "utils/floatpoint.h" //This matrix gets applied to floating point coordinates. namespace cura { @@ -18,14 +18,14 @@ FMatrix4x3 FMatrix4x3::scale(const Ratio scale, const Point3 origin) FMatrix4x3 FMatrix4x3::scale(const Ratio scale_x, const Ratio scale_y, const Ratio scale_z, const Point3 origin) { FMatrix4x3 result; - result.m[0][0] = scale_x; //X scale. - result.m[1][1] = scale_y; //Y scale. - result.m[2][2] = scale_z; //Z scale. + result.m[0][0] = scale_x; // X scale. + result.m[1][1] = scale_y; // Y scale. + result.m[2][2] = scale_z; // Z scale. - //Apply a transformation to scale it away from the origin. - result.m[3][0] = (scale_x - 1.0) * -origin.x; //Arrived at by manually applying an inverse move, the scale, then a move. - result.m[3][1] = (scale_y - 1.0) * -origin.y; - result.m[3][2] = (scale_z - 1.0) * -origin.z; + // Apply a transformation to scale it away from the origin. + result.m[3][0] = (scale_x - 1.0) * -origin.x_; // Arrived at by manually applying an inverse move, the scale, then a move. + result.m[3][1] = (scale_y - 1.0) * -origin.y_; + result.m[3][2] = (scale_z - 1.0) * -origin.z_; return result; } @@ -51,17 +51,15 @@ Point3 FMatrix4x3::apply(const FPoint3& p) const return Point3( MM2INT(p.x * m[0][0] + p.y * m[1][0] + p.z * m[2][0] + m[3][0]), MM2INT(p.x * m[0][1] + p.y * m[1][1] + p.z * m[2][1] + m[3][1]), - MM2INT(p.x * m[0][2] + p.y * m[1][2] + p.z * m[2][2] + m[3][2]) - ); + MM2INT(p.x * m[0][2] + p.y * m[1][2] + p.z * m[2][2] + m[3][2])); } Point3 FMatrix4x3::apply(const Point3& p) const { return Point3( - m[0][0] * p.x + m[1][0] * p.y + m[2][0] * p.z + m[3][0], - m[0][1] * p.x + m[1][1] * p.y + m[2][1] * p.z + m[3][1], - m[0][2] * p.x + m[1][2] * p.y + m[2][2] * p.z + m[3][2] - ); + m[0][0] * p.x_ + m[1][0] * p.y_ + m[2][0] * p.z_ + m[3][0], + m[0][1] * p.x_ + m[1][1] * p.y_ + m[2][1] * p.z_ + m[3][1], + m[0][2] * p.x_ + m[1][2] * p.y_ + m[2][2] * p.z_ + m[3][2]); } -} \ No newline at end of file +} // namespace cura diff --git a/src/utils/LinearAlg2D.cpp b/src/utils/LinearAlg2D.cpp index ae972d6438..a917c073e2 100644 --- a/src/utils/LinearAlg2D.cpp +++ b/src/utils/LinearAlg2D.cpp @@ -26,7 +26,7 @@ float LinearAlg2D::getAngleLeft(const Point& a, const Point& b, const Point& c) } else { - return M_PI; // straight bit + return std::numbers::pi; // straight bit } } const float angle = -atan2(det, dott); // from -pi to pi @@ -36,7 +36,7 @@ float LinearAlg2D::getAngleLeft(const Point& a, const Point& b, const Point& c) } else { - return M_PI * 2 + angle; + return std::numbers::pi * 2 + angle; } } diff --git a/src/utils/Point3.cpp b/src/utils/Point3.cpp index a709c8e485..f84d8589dd 100644 --- a/src/utils/Point3.cpp +++ b/src/utils/Point3.cpp @@ -1,76 +1,76 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #include "utils/Point3.h" //The headers we're implementing. namespace cura { -Point3 Point3::operator +(const Point3& p) const +Point3 Point3::operator+(const Point3& p) const { - return Point3(x + p.x, y + p.y, z + p.z); + return Point3(x_ + p.x_, y_ + p.y_, z_ + p.z_); } -Point3 Point3::operator -() const +Point3 Point3::operator-() const { - return Point3(-x, -y, -z); + return Point3(-x_, -y_, -z_); } -Point3 Point3::operator -(const Point3& p) const +Point3 Point3::operator-(const Point3& p) const { - return Point3(x - p.x, y - p.y, z - p.z); + return Point3(x_ - p.x_, y_ - p.y_, z_ - p.z_); } -Point3 Point3::operator *(const Point3& p) const +Point3 Point3::operator*(const Point3& p) const { - return Point3(x * p.x, y * p.y, z * p.z); + return Point3(x_ * p.x_, y_ * p.y_, z_ * p.z_); } -Point3 Point3::operator /(const Point3& p) const +Point3 Point3::operator/(const Point3& p) const { - return Point3(x / p.x, y / p.y, z / p.z); + return Point3(x_ / p.x_, y_ / p.y_, z_ / p.z_); } -Point3& Point3::operator +=(const Point3& p) +Point3& Point3::operator+=(const Point3& p) { - x += p.x; - y += p.y; - z += p.z; + x_ += p.x_; + y_ += p.y_; + z_ += p.z_; return *this; } -Point3& Point3::operator -=(const Point3& p) +Point3& Point3::operator-=(const Point3& p) { - x -= p.x; - y -= p.y; - z -= p.z; + x_ -= p.x_; + y_ -= p.y_; + z_ -= p.z_; return *this; } -Point3& Point3::operator *=(const Point3& p) +Point3& Point3::operator*=(const Point3& p) { - x *= p.x; - y *= p.y; - z *= p.z; + x_ *= p.x_; + y_ *= p.y_; + z_ *= p.z_; return *this; } -Point3& Point3::operator /=(const Point3& p) +Point3& Point3::operator/=(const Point3& p) { - x /= p.x; - y /= p.y; - z /= p.z; + x_ /= p.x_; + y_ /= p.y_; + z_ /= p.z_; return *this; } -bool Point3::operator ==(const Point3& p) const +bool Point3::operator==(const Point3& p) const { - return x == p.x && y == p.y && z == p.z; + return x_ == p.x_ && y_ == p.y_ && z_ == p.z_; } -bool Point3::operator !=(const Point3& p) const +bool Point3::operator!=(const Point3& p) const { - return x != p.x || y != p.y || z != p.z; + return x_ != p.x_ || y_ != p.y_ || z_ != p.z_; } -} +} // namespace cura diff --git a/src/utils/ToolpathVisualizer.cpp b/src/utils/ToolpathVisualizer.cpp index 8caf916df0..4e470e34e5 100644 --- a/src/utils/ToolpathVisualizer.cpp +++ b/src/utils/ToolpathVisualizer.cpp @@ -1,4 +1,4 @@ -//Copyright (c) 2022 Ultimaker B.V. +// Copyright (c) 2022 Ultimaker B.V. #include "utils/ToolpathVisualizer.h" @@ -33,7 +33,8 @@ void ToolpathVisualizer::toolpaths(const std::vector& all_segm polys = PolygonUtils::connect(polys); for (PolygonRef connected : polys) svg.writeAreas(connected, clr, SVG::Color::NONE); - if (!rounded_visualization) break; + if (! rounded_visualization) + break; } svg.nextLayer(); } @@ -41,15 +42,15 @@ void ToolpathVisualizer::toolpaths(const std::vector& all_segm void ToolpathVisualizer::underfill(const Polygons& underfills) { - svg.writeAreas(underfills, SVG::ColorObject(0,128,255), SVG::Color::NONE); + svg.writeAreas(underfills, SVG::ColorObject(0, 128, 255), SVG::Color::NONE); svg.nextLayer(); } void ToolpathVisualizer::overfill(const Polygons& overfills, const Polygons& double_overfills) { - svg.writeAreas(overfills, SVG::ColorObject(255,128,0), SVG::Color::NONE); + svg.writeAreas(overfills, SVG::ColorObject(255, 128, 0), SVG::Color::NONE); svg.nextLayer(); - svg.writeAreas(double_overfills, SVG::ColorObject(255,100,0), SVG::Color::NONE); - if (!double_overfills.empty()) + svg.writeAreas(double_overfills, SVG::ColorObject(255, 100, 0), SVG::Color::NONE); + if (! double_overfills.empty()) { svg.nextLayer(); } @@ -70,10 +71,10 @@ void ToolpathVisualizer::width_legend(const Polygons& input, coord_t nozzle_size legend_btm.p += (legend_mid.p - legend_btm.p) / 4; legend_top.p += (legend_mid.p - legend_top.p) / 4; ExtrusionSegment legend_segment(legend_btm, legend_top, true, false); - svg.writeAreas(legend_segment.toPolygons(false), SVG::ColorObject(200,200,200), SVG::Color::NONE); // real outline + svg.writeAreas(legend_segment.toPolygons(false), SVG::ColorObject(200, 200, 200), SVG::Color::NONE); // real outline std::vector all_segments_plus; all_segments_plus.emplace_back(legend_segment); // colored - + Point legend_text_offset(nozzle_size, 0); svg.writeText(legend_top.p + legend_text_offset, to_string(INT2MM(legend_top.w))); svg.writeText(legend_btm.p + legend_text_offset, to_string(INT2MM(legend_btm.w))); @@ -81,30 +82,35 @@ void ToolpathVisualizer::width_legend(const Polygons& input, coord_t nozzle_size svg.writeLine(legend_top.p, legend_top.p + legend_text_offset); svg.writeLine(legend_btm.p, legend_btm.p + legend_text_offset); svg.writeLine(legend_mid.p, legend_mid.p + legend_text_offset); - + widths(all_segments_plus, nozzle_size, max_dev, min_w, rounded_visualization); } -void ToolpathVisualizer::widths(const std::vector& all_segments, coord_t nozzle_size, coord_t max_dev, coord_t min_w, bool rounded_visualization, bool exaggerate_widths) +void ToolpathVisualizer::widths( + const std::vector& all_segments, + coord_t nozzle_size, + coord_t max_dev, + coord_t min_w, + bool rounded_visualization, + bool exaggerate_widths) { + // Point3 middle = rounded_visualization? Point3(255,255,255) : Point3(192,192,192); + Point3 middle(255, 255, 255); + Point3 wide(255, 0, 0); + Point3 narrow(0, 0, 255); + + // Polygons connecteds = PolygonUtils::connect(area_covered); + // for (PolygonRef connected : connecteds) + // svg.writeAreas(connected, SVG::Color::BLACK, SVG::Color::NONE); -// Point3 middle = rounded_visualization? Point3(255,255,255) : Point3(192,192,192); - Point3 middle(255,255,255); - Point3 wide(255,0,0); - Point3 narrow(0,0,255); - -// Polygons connecteds = PolygonUtils::connect(area_covered); -// for (PolygonRef connected : connecteds) -// svg.writeAreas(connected, SVG::Color::BLACK, SVG::Color::NONE); - for (float w = .9; w > .25; w = 1.0 - (1.0 - w) * 1.2) { - int brightness = rounded_visualization? 255 - 200 * (w - .25) : 192; + int brightness = rounded_visualization ? 255 - 200 * (w - .25) : 192; for (size_t segment_idx = 0; segment_idx < all_segments.size(); segment_idx++) { ExtrusionSegment ss = all_segments[segment_idx]; -// ss.from.w *= w; -// ss.to.w *= w; + // ss.from.w *= w; + // ss.to.w *= w; for (ExtrusionSegment s : ss.discretize(MM2INT(0.1))) { coord_t avg_w = (s.from.w + s.to.w) / 2; @@ -113,35 +119,36 @@ void ToolpathVisualizer::widths(const std::vector& all_segment color_ratio = color_ratio * .5 + .5 * sqrt(color_ratio); if (avg_w > nozzle_size) { - clr = wide * color_ratio + middle * (1.0 - color_ratio ); + clr = wide * color_ratio + middle * (1.0 - color_ratio); } else { - clr = narrow * color_ratio + middle * (1.0 - color_ratio ); + clr = narrow * color_ratio + middle * (1.0 - color_ratio); } clr = clr * brightness / 255; - -// coord_t clr_max = std::max(clr.x, std::max(clr.y, clr.z)); -// clr = clr * 255 / clr_max; -// clr.y = clr.y * (255 - 92 * clr.dot(green) / green.vSize() / 255) / 255; + // coord_t clr_max = std::max(clr.x, std::max(clr.y, clr.z)); + // clr = clr * 255 / clr_max; + + // clr.y = clr.y * (255 - 92 * clr.dot(green) / green.vSize() / 255) / 255; if (exaggerate_widths) { s.from.w = std::max(min_w, min_w + (s.from.w - (nozzle_size - max_dev)) * 5 / 4); s.to.w = std::max(min_w, min_w + (s.to.w - (nozzle_size - max_dev)) * 5 / 4); } -// else -// { -// s.from.w *= 0.9; -// s.to.w *= 0.9; -// } + // else + // { + // s.from.w *= 0.9; + // s.to.w *= 0.9; + // } s.from.w *= w / .9; s.to.w *= w / .9; Polygons covered = s.toPolygons(); - svg.writeAreas(covered, SVG::ColorObject(clr.x, clr.y, clr.z), SVG::Color::NONE); + svg.writeAreas(covered, SVG::ColorObject(clr.x_, clr.y_, clr.z_), SVG::Color::NONE); } } - if (!rounded_visualization) break; + if (! rounded_visualization) + break; svg.nextLayer(); } } diff --git a/src/utils/VoxelUtils.cpp b/src/utils/VoxelUtils.cpp index 22d674967b..22150a2b95 100644 --- a/src/utils/VoxelUtils.cpp +++ b/src/utils/VoxelUtils.cpp @@ -1,41 +1,41 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #include "utils/VoxelUtils.h" + #include "utils/polygonUtils.h" -namespace cura +namespace cura { DilationKernel::DilationKernel(GridPoint3 kernel_size, DilationKernel::Type type) -: kernel_size(kernel_size) -, type(type) + : kernel_size(kernel_size) + , type(type) { - coord_t mult = kernel_size.x * kernel_size.y * kernel_size.z; // multiplier for division to avoid rounding and to avoid use of floating point numbers + coord_t mult = kernel_size.x_ * kernel_size.y_ * kernel_size.z_; // multiplier for division to avoid rounding and to avoid use of floating point numbers relative_cells.reserve(mult); GridPoint3 half_kernel = kernel_size / 2; - GridPoint3 start = - half_kernel; + GridPoint3 start = -half_kernel; GridPoint3 end = kernel_size - half_kernel; - for (coord_t x = start.x; x < end.x; x++) + for (coord_t x = start.x_; x < end.x_; x++) { - for (coord_t y = start.y; y < end.y; y++) + for (coord_t y = start.y_; y < end.y_; y++) { - for (coord_t z = start.z; z < end.z; z++) + for (coord_t z = start.z_; z < end.z_; z++) { GridPoint3 current(x, y, z); if (type != Type::CUBE) { - GridPoint3 limit((x < 0)? start.x : end.x - 1, - (y < 0)? start.y : end.y - 1, - (z < 0)? start.z : end.z - 1); - if (limit.x == 0) limit.x = 1; - if (limit.y == 0) limit.y = 1; - if (limit.z == 0) limit.z = 1; + GridPoint3 limit((x < 0) ? start.x_ : end.x_ - 1, (y < 0) ? start.y_ : end.y_ - 1, (z < 0) ? start.z_ : end.z_ - 1); + if (limit.x_ == 0) + limit.x_ = 1; + if (limit.y_ == 0) + limit.y_ = 1; + if (limit.z_ == 0) + limit.z_ = 1; const GridPoint3 rel_dists = mult * current / limit; - if ((type == Type::DIAMOND && rel_dists.x + rel_dists.y + rel_dists.z > mult) - || (type == Type::PRISM && rel_dists.x + rel_dists.y > mult) - ) + if ((type == Type::DIAMOND && rel_dists.x_ + rel_dists.y_ + rel_dists.z_ > mult) || (type == Type::PRISM && rel_dists.x_ + rel_dists.y_ > mult)) { continue; // don't consider this cell } @@ -46,23 +46,23 @@ DilationKernel::DilationKernel(GridPoint3 kernel_size, DilationKernel::Type type } } -bool VoxelUtils::walkLine(Point3 start, Point3 end, const std::function& process_cell_func) const +bool VoxelUtils::walkLine(Point3 start, Point3 end, const std::function& process_cell_func) const { Point3 diff = end - start; - + const GridPoint3 start_cell = toGridPoint(start); const GridPoint3 end_cell = toGridPoint(end); if (start_cell == end_cell) { return process_cell_func(start_cell); } - + Point3 current_cell = start_cell; while (true) { bool continue_ = process_cell_func(current_cell); - - if ( ! continue_) + + if (! continue_) { return false; } @@ -95,7 +95,7 @@ bool VoxelUtils::walkLine(Point3 start, Point3 end, const std::function& process_cell_func) const +bool VoxelUtils::walkPolygons(const Polygons& polys, coord_t z, const std::function& process_cell_func) const { for (ConstPolygonRef poly : polys) { @@ -103,7 +103,7 @@ bool VoxelUtils::walkPolygons(const Polygons& polys, coord_t z, const std::funct for (Point p : poly) { bool continue_ = walkLine(Point3(last.X, last.Y, z), Point3(p.X, p.Y, z), process_cell_func); - if ( ! continue_) + if (! continue_) { return false; } @@ -113,35 +113,35 @@ bool VoxelUtils::walkPolygons(const Polygons& polys, coord_t z, const std::funct return true; } -bool VoxelUtils::walkDilatedPolygons(const Polygons& polys, coord_t z, const DilationKernel& kernel, const std::function& process_cell_func) const +bool VoxelUtils::walkDilatedPolygons(const Polygons& polys, coord_t z, const DilationKernel& kernel, const std::function& process_cell_func) const { Polygons translated = polys; - const Point3 translation = (Point3(1,1,1) - kernel.kernel_size % 2) * cell_size / 2; - if (translation.x && translation.y) + const Point3 translation = (Point3(1, 1, 1) - kernel.kernel_size % 2) * cell_size / 2; + if (translation.x_ && translation.y_) { - translated.translate(Point(translation.x, translation.y)); + translated.translate(Point(translation.x_, translation.y_)); } - return walkPolygons(translated, z + translation.z, dilate(kernel, process_cell_func)); + return walkPolygons(translated, z + translation.z_, dilate(kernel, process_cell_func)); } -bool VoxelUtils::walkAreas(const Polygons& polys, coord_t z, const std::function& process_cell_func) const +bool VoxelUtils::walkAreas(const Polygons& polys, coord_t z, const std::function& process_cell_func) const { Polygons translated = polys; - const Point3 translation = - cell_size / 2; // offset half a cell so that the dots of spreadDotsArea are centered on the middle of the cell isntead of the lower corners. - if (translation.x && translation.y) + const Point3 translation = -cell_size / 2; // offset half a cell so that the dots of spreadDotsArea are centered on the middle of the cell isntead of the lower corners. + if (translation.x_ && translation.y_) { - translated.translate(Point(translation.x, translation.y)); + translated.translate(Point(translation.x_, translation.y_)); } return _walkAreas(translated, z, process_cell_func); } -bool VoxelUtils::_walkAreas(const Polygons& polys, coord_t z, const std::function& process_cell_func) const +bool VoxelUtils::_walkAreas(const Polygons& polys, coord_t z, const std::function& process_cell_func) const { - std::vector skin_points = PolygonUtils::spreadDotsArea(polys, Point(cell_size.x, cell_size.y)); + std::vector skin_points = PolygonUtils::spreadDotsArea(polys, Point(cell_size.x_, cell_size.y_)); for (Point p : skin_points) { - bool continue_ = process_cell_func(toGridPoint(Point3(p.X + cell_size.x / 2, p.Y + cell_size.y / 2, z))); - if ( ! continue_) + bool continue_ = process_cell_func(toGridPoint(Point3(p.X + cell_size.x_ / 2, p.Y + cell_size.y_ / 2, z))); + if (! continue_) { return false; } @@ -149,26 +149,27 @@ bool VoxelUtils::_walkAreas(const Polygons& polys, coord_t z, const std::functio return true; } -bool VoxelUtils::walkDilatedAreas(const Polygons& polys, coord_t z, const DilationKernel& kernel, const std::function& process_cell_func) const +bool VoxelUtils::walkDilatedAreas(const Polygons& polys, coord_t z, const DilationKernel& kernel, const std::function& process_cell_func) const { Polygons translated = polys; - const Point3 translation = - (Point3(1,1,1) - kernel.kernel_size % 2) * cell_size / 2 // offset half a cell when using a n even kernel - - cell_size / 2; // offset half a cell so that the dots of spreadDotsArea are centered on the middle of the cell isntead of the lower corners. - if (translation.x && translation.y) + const Point3 translation = (Point3(1, 1, 1) - kernel.kernel_size % 2) * cell_size / 2 // offset half a cell when using a n even kernel + - cell_size / 2; // offset half a cell so that the dots of spreadDotsArea are centered on the middle of the cell isntead of the lower corners. + if (translation.x_ && translation.y_) { - translated.translate(Point(translation.x, translation.y)); + translated.translate(Point(translation.x_, translation.y_)); } - return _walkAreas(translated, z + translation.z, dilate(kernel, process_cell_func)); + return _walkAreas(translated, z + translation.z_, dilate(kernel, process_cell_func)); } -std::function VoxelUtils::dilate(const DilationKernel& kernel, const std::function& process_cell_func) const +std::function VoxelUtils::dilate(const DilationKernel& kernel, const std::function& process_cell_func) const { - return [&process_cell_func, &kernel](GridPoint3 loc) { + return [&process_cell_func, &kernel](GridPoint3 loc) + { for (const GridPoint3& rel : kernel.relative_cells) { bool continue_ = process_cell_func(loc + rel); - if ( ! continue_) return false; + if (! continue_) + return false; } return true; }; diff --git a/src/utils/polygon.cpp b/src/utils/polygon.cpp index 5c8884a6ad..0f80cb9061 100644 --- a/src/utils/polygon.cpp +++ b/src/utils/polygon.cpp @@ -476,11 +476,11 @@ void PolygonRef::removeColinearEdges(const AngleRadians max_deviation_angle) const Point& next = rpath[(point_idx + 1) % pathlen]; float angle = LinearAlg2D::getAngleLeft(prev, pt, next); // [0 : 2 * pi] - if (angle >= M_PI) {angle -= M_PI;} // map [pi : 2 * pi] to [0 : pi] + if (angle >= std::numbers::pi) {angle -= std::numbers::pi;} // map [pi : 2 * pi] to [0 : pi] // Check if the angle is within limits for the point to 'make sense', given the maximum deviation. // If the angle indicates near-parallel segments ignore the point 'pt' - if (angle > max_deviation_angle && angle < M_PI - max_deviation_angle) + if (angle > max_deviation_angle && angle < std::numbers::pi - max_deviation_angle) { new_path.push_back(pt); } @@ -1122,7 +1122,7 @@ void ConstPolygonRef::smooth_outward(const AngleDegrees min_angle, int shortcut_ // 0 int shortcut_length2 = shortcut_length * shortcut_length; - float cos_min_angle = cos(min_angle / 180 * M_PI); + float cos_min_angle = cos(min_angle / 180 * std::numbers::pi); ListPolygon poly; ListPolyIt::convertPolygonToList(*this, poly); diff --git a/src/utils/polygonUtils.cpp b/src/utils/polygonUtils.cpp index d1f4debe21..40a1a29d58 100644 --- a/src/utils/polygonUtils.cpp +++ b/src/utils/polygonUtils.cpp @@ -228,16 +228,16 @@ Point PolygonUtils::moveInsideDiagonally(ClosestPolygonPoint point_on_boundary, { return no_point; } - ConstPolygonRef poly = **point_on_boundary.poly; - Point p0 = poly[point_on_boundary.point_idx]; - Point p1 = poly[(point_on_boundary.point_idx + 1) % poly.size()]; - if (vSize2(p0 - point_on_boundary.location) < vSize2(p1 - point_on_boundary.location)) + ConstPolygonRef poly = **point_on_boundary.poly_; + Point p0 = poly[point_on_boundary.point_idx_]; + Point p1 = poly[(point_on_boundary.point_idx_ + 1) % poly.size()]; + if (vSize2(p0 - point_on_boundary.location_) < vSize2(p1 - point_on_boundary.location_)) { - return point_on_boundary.location + normal(getVertexInwardNormal(poly, point_on_boundary.point_idx), inset); + return point_on_boundary.location_ + normal(getVertexInwardNormal(poly, point_on_boundary.point_idx_), inset); } else { - return point_on_boundary.location + normal(getVertexInwardNormal(poly, (point_on_boundary.point_idx + 1) % poly.size()), inset); + return point_on_boundary.location_ + normal(getVertexInwardNormal(poly, (point_on_boundary.point_idx_ + 1) % poly.size()), inset); } } @@ -294,9 +294,9 @@ ClosestPolygonPoint PolygonUtils::_moveInside2(const ClosestPolygonPoint& closes { return ClosestPolygonPoint(); // stub with invalid indices to signify we haven't found any } - const Point v_boundary_from = from - closest_polygon_point.location; + const Point v_boundary_from = from - closest_polygon_point.location_; Point result = moveInside(closest_polygon_point, distance); - const Point v_boundary_result = result - closest_polygon_point.location; + const Point v_boundary_result = result - closest_polygon_point.location_; if (dot(v_boundary_result, v_boundary_from) > 0) { // point was already on the correct side of the polygon if (vSize2(v_boundary_from) > distance * distance) @@ -314,7 +314,7 @@ ClosestPolygonPoint PolygonUtils::_moveInside2(const ClosestPolygonPoint& closes { if (vSize2(v_boundary_from) > max_dist2) { - return ClosestPolygonPoint(*closest_polygon_point.poly); // stub with invalid indices to signify we haven't found any + return ClosestPolygonPoint(*closest_polygon_point.poly_); // stub with invalid indices to signify we haven't found any } else { @@ -578,11 +578,11 @@ Point PolygonUtils::moveInside(const ClosestPolygonPoint& cpp, const int distanc } if (distance == 0) { // the point which is assumed to be on the boundary doesn't have to be moved - return cpp.location; + return cpp.location_; } - ConstPolygonRef poly = *cpp.poly; - unsigned int point_idx = cpp.point_idx; - const Point& on_boundary = cpp.location; + ConstPolygonRef poly = *cpp.poly_; + unsigned int point_idx = cpp.point_idx_; + const Point& on_boundary = cpp.location_; const Point& p1 = poly[point_idx]; unsigned int p2_idx; @@ -642,7 +642,7 @@ ClosestPolygonPoint PolygonUtils::ensureInsideOrOutside( { return ClosestPolygonPoint(); // we couldn't move inside } - ConstPolygonRef closest_poly = *closest_polygon_point.poly; + ConstPolygonRef closest_poly = *closest_polygon_point.poly_; bool is_outside_boundary = closest_poly.orientation(); { @@ -677,14 +677,14 @@ ClosestPolygonPoint PolygonUtils::ensureInsideOrOutside( ClosestPolygonPoint inside = findClosest(from, insetted, penalty_function); if (inside.isValid()) { - bool is_inside = polygons.inside(inside.location); + bool is_inside = polygons.inside(inside.location_); if (is_inside != (preferred_dist_inside > 0)) { // Insetting from the reference polygon ended up outside another polygon. // Perform an offset on all polygons instead. Polygons all_insetted = polygons.offset(-preferred_dist_inside); ClosestPolygonPoint overall_inside = findClosest(from, all_insetted, penalty_function); - bool overall_is_inside = polygons.inside(overall_inside.location); + bool overall_is_inside = polygons.inside(overall_inside.location_); if (overall_is_inside != (preferred_dist_inside > 0)) { #ifdef DEBUG @@ -722,7 +722,7 @@ ClosestPolygonPoint PolygonUtils::ensureInsideOrOutside( svg.writeComment("From location"); svg.writePoint(from, true, 5, SVG::Color::GREEN); svg.writeComment("Location computed to be inside the black polygon"); - svg.writePoint(inside.location, true, 5, SVG::Color::RED); + svg.writePoint(inside.location_, true, 5, SVG::Color::RED); } catch (...) { @@ -735,7 +735,7 @@ ClosestPolygonPoint PolygonUtils::ensureInsideOrOutside( } inside = overall_inside; } - from = inside.location; + from = inside.location_; } // otherwise we just return the closest polygon point without modifying the from location return closest_polygon_point; // don't return a ClosestPolygonPoint with a reference to the above local polygons variable } @@ -747,11 +747,11 @@ void PolygonUtils::walkToNearestSmallestConnection(ClosestPolygonPoint& poly1_re { return; } - ConstPolygonRef poly1 = *poly1_result.poly; - ConstPolygonRef poly2 = *poly2_result.poly; - size_t poly1_idx = poly1_result.poly_idx; - size_t poly2_idx = poly2_result.poly_idx; - if (poly1_result.point_idx == NO_INDEX || poly2_result.point_idx == NO_INDEX) + ConstPolygonRef poly1 = *poly1_result.poly_; + ConstPolygonRef poly2 = *poly2_result.poly_; + size_t poly1_idx = poly1_result.poly_idx_; + size_t poly2_idx = poly2_result.poly_idx_; + if (poly1_result.point_idx_ == NO_INDEX || poly2_result.point_idx_ == NO_INDEX) { return; } @@ -759,12 +759,12 @@ void PolygonUtils::walkToNearestSmallestConnection(ClosestPolygonPoint& poly1_re int equilibirum_limit = MM2INT(0.1); // hard coded value for (int loop_counter = 0; loop_counter < equilibirum_limit; loop_counter++) { - unsigned int pos1_before = poly1_result.point_idx; - poly1_result = findNearestClosest(poly2_result.location, poly1, poly1_result.point_idx); - unsigned int pos2_before = poly2_result.point_idx; - poly2_result = findNearestClosest(poly1_result.location, poly2, poly2_result.point_idx); + unsigned int pos1_before = poly1_result.point_idx_; + poly1_result = findNearestClosest(poly2_result.location_, poly1, poly1_result.point_idx_); + unsigned int pos2_before = poly2_result.point_idx_; + poly2_result = findNearestClosest(poly1_result.location_, poly2, poly2_result.point_idx_); - if (poly1_result.point_idx == pos1_before && poly2_result.point_idx == pos2_before) + if (poly1_result.point_idx_ == pos1_before && poly2_result.point_idx_ == pos2_before) { break; } @@ -781,13 +781,13 @@ void PolygonUtils::walkToNearestSmallestConnection(ClosestPolygonPoint& poly1_re auto check_neighboring_vert = [&best_distance2](ConstPolygonRef from_poly, ConstPolygonRef to_poly, ClosestPolygonPoint& from_poly_result, ClosestPolygonPoint& to_poly_result, bool vertex_after) { - const Point after_poly2_result = to_poly[(to_poly_result.point_idx + vertex_after) % to_poly.size()]; - const ClosestPolygonPoint poly1_after_poly2_result = findNearestClosest(after_poly2_result, from_poly, from_poly_result.point_idx); + const Point after_poly2_result = to_poly[(to_poly_result.point_idx_ + vertex_after) % to_poly.size()]; + const ClosestPolygonPoint poly1_after_poly2_result = findNearestClosest(after_poly2_result, from_poly, from_poly_result.point_idx_); const coord_t poly1_after_poly2_result_dist2 = vSize2(poly1_after_poly2_result.p() - after_poly2_result); if (poly1_after_poly2_result_dist2 < best_distance2) { from_poly_result = poly1_after_poly2_result; - to_poly_result.location = after_poly2_result; + to_poly_result.location_ = after_poly2_result; best_distance2 = poly1_after_poly2_result_dist2; } }; @@ -796,8 +796,8 @@ void PolygonUtils::walkToNearestSmallestConnection(ClosestPolygonPoint& poly1_re check_neighboring_vert(poly2, poly1, poly2_result, poly1_result, false); check_neighboring_vert(poly2, poly1, poly2_result, poly1_result, true); - poly1_result.poly_idx = poly1_idx; - poly2_result.poly_idx = poly2_idx; + poly1_result.poly_idx_ = poly1_idx; + poly2_result.poly_idx_ = poly2_idx; } ClosestPolygonPoint PolygonUtils::findNearestClosest(Point from, ConstPolygonRef polygon, int start_idx) @@ -809,7 +809,7 @@ ClosestPolygonPoint PolygonUtils::findNearestClosest(Point from, ConstPolygonRef } ClosestPolygonPoint back = findNearestClosest(from, polygon, start_idx, -1); assert(back.isValid()); - if (vSize2(forth.location - from) < vSize2(back.location - from)) + if (vSize2(forth.location_ - from) < vSize2(back.location_ - from)) { return forth; } @@ -880,7 +880,7 @@ ClosestPolygonPoint PolygonUtils::findClosest(Point from, const Polygons& polygo } ClosestPolygonPoint best((*any_polygon)[0], 0, *any_polygon, any_poly_idx); - int64_t closestDist2_score = vSize2(from - best.location) + penalty_function(best.location); + int64_t closestDist2_score = vSize2(from - best.location_) + penalty_function(best.location_); for (unsigned int ply = 0; ply < polygons.size(); ply++) { @@ -892,12 +892,12 @@ ClosestPolygonPoint PolygonUtils::findClosest(Point from, const Polygons& polygo { continue; } - int64_t dist2_score = vSize2(from - closest_here.location) + penalty_function(closest_here.location); + int64_t dist2_score = vSize2(from - closest_here.location_) + penalty_function(closest_here.location_); if (dist2_score < closestDist2_score) { best = closest_here; closestDist2_score = dist2_score; - best.poly_idx = ply; + best.poly_idx_ = ply; } } @@ -1146,11 +1146,11 @@ bool PolygonUtils::getNextPointWithDistance(Point from, int64_t dist, ConstPolyg ClosestPolygonPoint PolygonUtils::walk(const ClosestPolygonPoint& from, coord_t distance) { - ConstPolygonRef poly = *from.poly; + ConstPolygonRef poly = *from.poly_; Point last_vertex = from.p(); Point next_vertex; - size_t last_point_idx = from.point_idx; - for (size_t point_idx = from.point_idx + 1;; point_idx++) + size_t last_point_idx = from.point_idx_; + for (size_t point_idx = from.point_idx_ + 1;; point_idx++) { if (point_idx == poly.size()) { @@ -1164,7 +1164,7 @@ ClosestPolygonPoint PolygonUtils::walk(const ClosestPolygonPoint& from, coord_t last_point_idx = point_idx; } Point result = next_vertex + normal(last_vertex - next_vertex, -distance); - return ClosestPolygonPoint(result, last_point_idx, poly, from.poly_idx); + return ClosestPolygonPoint(result, last_point_idx, poly, from.poly_idx_); } std::optional PolygonUtils::getNextParallelIntersection(const ClosestPolygonPoint& start, const Point& line_to, const coord_t dist, const bool forward) @@ -1181,7 +1181,7 @@ std::optional PolygonUtils::getNextParallelIntersection(con // r=result // t=line_to - ConstPolygonRef poly = *start.poly; + ConstPolygonRef poly = *start.poly_; const Point s = start.p(); const Point t = line_to; @@ -1192,8 +1192,9 @@ std::optional PolygonUtils::getNextParallelIntersection(con coord_t prev_projected = 0; for (unsigned int next_point_nr = 0; next_point_nr < poly.size(); next_point_nr++) { - const unsigned int next_point_idx = forward ? (start.point_idx + 1 + next_point_nr) % poly.size() - : (static_cast(start.point_idx) - next_point_nr + poly.size()) % poly.size(); // cast in order to accomodate subtracting + const unsigned int next_point_idx = forward + ? (start.point_idx_ + 1 + next_point_nr) % poly.size() + : (static_cast(start.point_idx_) - next_point_nr + poly.size()) % poly.size(); // cast in order to accomodate subtracting const Point next_vert = poly[next_point_idx]; const Point so = next_vert - s; const coord_t projected = dot(shift, so) / dist; @@ -1417,7 +1418,7 @@ double PolygonUtils::relativeHammingDistance(const Polygons& poly_a, const Polyg Polygon PolygonUtils::makeCircle(const Point mid, const coord_t radius, const AngleRadians a_step) { Polygon circle; - for (float a = 0; a < 2 * M_PI; a += a_step) + for (float a = 0; a < 2 * std::numbers::pi; a += a_step) { circle.emplace_back(mid + Point(radius * cos(a), radius * sin(a))); } diff --git a/tests/PathOrderMonotonicTest.cpp b/tests/PathOrderMonotonicTest.cpp index 7e69c85606..1a0ca213a4 100644 --- a/tests/PathOrderMonotonicTest.cpp +++ b/tests/PathOrderMonotonicTest.cpp @@ -141,7 +141,7 @@ TEST_P(PathOrderMonotonicTest, SectionsTest) const Point& pt_r = polylines.begin()->at(0); const Point& pt_s = polylines.begin()->at(1); - const double angle_from_first_line = std::atan2(pt_s.Y - pt_r.Y, pt_s.X - pt_r.X) + 0.5 * M_PI; + const double angle_from_first_line = std::atan2(pt_s.Y - pt_r.Y, pt_s.X - pt_r.X) + 0.5 * std::numbers::pi; const Point monotonic_axis(static_cast(std::cos(angle_from_first_line)) * 1000, static_cast(std::sin(angle_from_first_line)) * 1000); const Point perpendicular_axis{ turn90CCW(monotonic_axis) }; @@ -217,7 +217,7 @@ const std::vector polygon_filenames = { std::filesystem::path(__FILE__).parent_path().append("resources/polygon_slant_gap.txt").string(), std::filesystem::path(__FILE__).parent_path().append("resources/polygon_sawtooth.txt").string(), std::filesystem::path(__FILE__).parent_path().append("resources/polygon_letter_y.txt").string() }; -const std::vector angle_radians = { 0, 0.1, 0.25 * M_PI, 1.0, 0.5 * M_PI, 0.75 * M_PI, M_PI, 1.25 * M_PI, 4.0, 1.5 * M_PI, 1.75 * M_PI, 5.0, (2.0 * M_PI) - 0.1 }; +const std::vector angle_radians = { 0, 0.1, 0.25 * std::numbers::pi, 1.0, 0.5 * std::numbers::pi, 0.75 * std::numbers::pi, std::numbers::pi, 1.25 * std::numbers::pi, 4.0, 1.5 * std::numbers::pi, 1.75 * std::numbers::pi, 5.0, (2.0 * std::numbers::pi) - 0.1 }; INSTANTIATE_TEST_SUITE_P(PathOrderMonotonicTestInstantiation, PathOrderMonotonicTest, testing::Combine(testing::ValuesIn(polygon_filenames), testing::ValuesIn(angle_radians))); // NOLINTEND(*-magic-numbers) diff --git a/tests/arcus/ArcusCommunicationTest.cpp b/tests/arcus/ArcusCommunicationTest.cpp index 2618f2090d..6f5692fec6 100644 --- a/tests/arcus/ArcusCommunicationTest.cpp +++ b/tests/arcus/ArcusCommunicationTest.cpp @@ -62,7 +62,7 @@ class ArcusCommunicationTest : public testing::Test for (double a = 0; a < 1.0; a += .05) { - test_circle.add(Point(2050, 2050) + Point(std::cos(a * 2 * M_PI) * 500, std::sin(a * 2 * M_PI) * 500)); + test_circle.add(Point(2050, 2050) + Point(std::cos(a * 2 * std::numbers::pi) * 500, std::sin(a * 2 * std::numbers::pi) * 500)); } test_shapes.add(test_circle); diff --git a/tests/integration/SlicePhaseTest.cpp b/tests/integration/SlicePhaseTest.cpp index 75d66899b8..406554fd08 100644 --- a/tests/integration/SlicePhaseTest.cpp +++ b/tests/integration/SlicePhaseTest.cpp @@ -152,8 +152,8 @@ TEST_F(SlicePhaseTest, Cylinder1000) circle.reserve(num_vertices); for (size_t i = 0; i < 1000; i++) { - const coord_t x = std::cos(M_PI * 2 / num_vertices * i) * radius; - const coord_t y = std::sin(M_PI * 2 / num_vertices * i) * radius; + const coord_t x = std::cos(std::numbers::pi * 2 / num_vertices * i) * radius; + const coord_t y = std::sin(std::numbers::pi * 2 / num_vertices * i) * radius; circle.emplace_back(x, y); } Polygons circles; diff --git a/tests/settings/SettingsTest.cpp b/tests/settings/SettingsTest.cpp index 4ef0a12e10..648cca2e51 100644 --- a/tests/settings/SettingsTest.cpp +++ b/tests/settings/SettingsTest.cpp @@ -17,7 +17,7 @@ #include "utils/Coord_t.h" #include "utils/FMatrix4x3.h" //Testing matrix transformation settings. -#include //For M_PI. +#include //For std::numbers::pi. #include #include //For shared_ptr. @@ -121,10 +121,10 @@ TEST_F(SettingsTest, AddSettingCoordT) TEST_F(SettingsTest, AddSettingAngleRadians) { settings.add("test_setting", "180"); - EXPECT_DOUBLE_EQ(AngleRadians(M_PI), settings.get("test_setting")) << "180 degrees is 1 pi radians."; + EXPECT_DOUBLE_EQ(AngleRadians(std::numbers::pi), settings.get("test_setting")) << "180 degrees is 1 pi radians."; settings.add("test_setting", "810"); - EXPECT_NEAR(AngleRadians(M_PI / 2.0), settings.get("test_setting"), 0.00000001) << "810 degrees in clock arithmetic is 90 degrees, which is 0.5 pi radians."; + EXPECT_NEAR(AngleRadians(std::numbers::pi / 2.0), settings.get("test_setting"), 0.00000001) << "810 degrees in clock arithmetic is 90 degrees, which is 0.5 pi radians."; } TEST_F(SettingsTest, AddSettingAngleDegrees) diff --git a/tests/utils/LinearAlg2DTest.cpp b/tests/utils/LinearAlg2DTest.cpp index 4b2e883b8a..5d471dff36 100644 --- a/tests/utils/LinearAlg2DTest.cpp +++ b/tests/utils/LinearAlg2DTest.cpp @@ -132,7 +132,7 @@ TEST_P(GetAngleTest, GetAngle) const Point b = parameters.b; const Point c = parameters.c; const double angle_degrees = parameters.angle; - const double angle = angle_degrees * M_PI / 180.0; + const double angle = angle_degrees * std::numbers::pi / 180.0; const double supposed_angle = LinearAlg2D::getAngleLeft(a, b, c); ASSERT_LE(std::fabs(angle - supposed_angle), maximum_error) << "Corner in " << a << " - " << b << " - " << c << " was computed to have an angle of " << supposed_angle << " instead of " << angle << "."; diff --git a/tests/utils/PolygonTest.cpp b/tests/utils/PolygonTest.cpp index f7dd485de0..a65298bb89 100644 --- a/tests/utils/PolygonTest.cpp +++ b/tests/utils/PolygonTest.cpp @@ -269,7 +269,7 @@ TEST_F(PolygonTest, convexHullStar) const int num_points = 10; const int outer_radius = 20; const int inner_radius = 10; - const double angle_step = M_PI * 2.0 / num_points; + const double angle_step = std::numbers::pi * 2.0 / num_points; for (int i = 0; i < num_points; ++i) { coord_t x_outer = -std::cos(angle_step * i) * outer_radius; diff --git a/tests/utils/SimplifyTest.cpp b/tests/utils/SimplifyTest.cpp index 35d6689341..118e909644 100644 --- a/tests/utils/SimplifyTest.cpp +++ b/tests/utils/SimplifyTest.cpp @@ -83,7 +83,7 @@ class SimplifyTest : public testing::Test constexpr coord_t amplitude = 45; constexpr coord_t y_step = 100; constexpr size_t periods = 10; // How many waves of the sine to construct. - for (double current_sine = 0; current_sine < M_PI * periods; current_sine += sine_step) + for (double current_sine = 0; current_sine < std::numbers::pi * periods; current_sine += sine_step) { sine.add(Point(std::sin(current_sine) * amplitude, y_step * sine.size())); } diff --git a/tests/utils/SmoothTest.cpp b/tests/utils/SmoothTest.cpp index 7efb08cbb2..8288d605e9 100644 --- a/tests/utils/SmoothTest.cpp +++ b/tests/utils/SmoothTest.cpp @@ -19,7 +19,7 @@ TEST(SmoothTest, TestSmooth) // test isSmooth utility function cura::actions::smooth_fn smooth; const auto FLUID_ANGLE = 15.; - const auto COS_FLUID_ANGLE = std::cos(FLUID_ANGLE * M_PI / 180.); + const auto COS_FLUID_ANGLE = std::cos(FLUID_ANGLE * std::numbers::pi / 180.); { /* From b7445cfd0995e9d6a356b5589325e12bef58fdb7 Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Mon, 20 Nov 2023 15:28:36 +0100 Subject: [PATCH 03/48] Fixed variable shadowing warnings --- include/settings/types/Duration.h | 53 ++++++++++++++++++------------- 1 file changed, 31 insertions(+), 22 deletions(-) diff --git a/include/settings/types/Duration.h b/include/settings/types/Duration.h index f395beff9d..c068ae0e1a 100644 --- a/include/settings/types/Duration.h +++ b/include/settings/types/Duration.h @@ -1,5 +1,5 @@ -//Copyright (c) 2020 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2020 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef DURATION_H #define DURATION_H @@ -19,56 +19,65 @@ struct Duration /* * \brief Default constructor setting the duration to 0. */ - constexpr Duration() : value(0) {}; + constexpr Duration() + : value_(0) + { + } /* * \brief Casts a double to a Duration instance. */ - constexpr Duration(double value) : value(value > 0.0 ? value : 0.0) {}; + constexpr Duration(double value) + : value_(value > 0.0 ? value : 0.0) + { + } /* * \brief Casts the Duration instance to a double. */ constexpr operator double() const { - return value; - }; + return value_; + } /* * Some operators to do arithmetic with Durations. */ - Duration operator +(const Duration& other) const + Duration operator+(const Duration& other) const { - return Duration(value + other.value); - }; - Duration operator -(const Duration& other) const + return Duration(value_ + other.value_); + } + + Duration operator-(const Duration& other) const { - return Duration(value - other.value); - }; - Duration& operator +=(const Duration& other) + return Duration(value_ - other.value_); + } + + Duration& operator+=(const Duration& other) { - value += other.value; + value_ += other.value_; return *this; } - Duration& operator -=(const Duration& other) + + Duration& operator-=(const Duration& other) { - value -= other.value; + value_ -= other.value_; return *this; } /* * \brief The actual duration, as a double. */ - double value = 0; + double value_ = 0; }; -constexpr Duration operator "" _s(const long double seconds) +constexpr Duration operator"" _s(const long double seconds) { - return Duration(seconds); + return Duration(static_cast(seconds)); } -inline std::ostream& operator<< (std::ostream& out, const Duration seconds) +inline std::ostream& operator<<(std::ostream& out, const Duration seconds) { constexpr bool pretty_print = false; @@ -89,6 +98,6 @@ inline std::ostream& operator<< (std::ostream& out, const Duration seconds) return out; } -} +} // namespace cura -#endif //DURATION_H \ No newline at end of file +#endif // DURATION_H From def471344dbc914e4111d0ea770466afb8ac6b68 Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Mon, 20 Nov 2023 15:28:58 +0100 Subject: [PATCH 04/48] Fixed numeric conversion warnings --- include/utils/polygon.h | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/include/utils/polygon.h b/include/utils/polygon.h index 5d9c4c737c..79b50663ae 100644 --- a/include/utils/polygon.h +++ b/include/utils/polygon.h @@ -4,10 +4,6 @@ #ifndef UTILS_POLYGON_H #define UTILS_POLYGON_H -#include "../settings/types/Angle.h" //For angles between vertices. -#include "../settings/types/Ratio.h" -#include "IntPoint.h" - #include #include // std::reverse, fill_n array #include @@ -20,6 +16,10 @@ #include #include +#include "../settings/types/Angle.h" //For angles between vertices. +#include "../settings/types/Ratio.h" +#include "IntPoint.h" + #define CHECK_POLY_ACCESS #ifdef CHECK_POLY_ACCESS #define POLY_ASSERT(e) assert(e) @@ -236,7 +236,7 @@ class ConstPolygonRef for (unsigned int n = 0; n < path->size(); n++) { Point p1 = (*path)[n]; - double second_factor = (p0.X * p1.Y) - (p1.X * p0.Y); + double second_factor = static_cast((p0.X * p1.Y) - (p1.X * p0.Y)); x += double(p0.X + p1.X) * second_factor; y += double(p0.Y + p1.Y) * second_factor; @@ -248,7 +248,7 @@ class ConstPolygonRef x = x / 6 / area; y = y / 6 / area; - return Point(x, y); + return Point(std::llrint(x), std::llrint(y)); } Point closestPointTo(Point p) const From 7469dea27ad1489e7f00bc56b05d472e784a6bcd Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Mon, 20 Nov 2023 16:18:41 +0100 Subject: [PATCH 05/48] Fixed number conversions warnings --- include/utils/polygon.h | 66 +++++++++++++++++++++++++---------------- 1 file changed, 40 insertions(+), 26 deletions(-) diff --git a/include/utils/polygon.h b/include/utils/polygon.h index 79b50663ae..6ce4b72f9d 100644 --- a/include/utils/polygon.h +++ b/include/utils/polygon.h @@ -109,7 +109,7 @@ class ConstPolygonRef */ bool empty() const; - const Point& operator[](unsigned int index) const + const Point& operator[](size_t index) const { POLY_ASSERT(index < size()); return (*path)[index]; @@ -177,7 +177,7 @@ class ConstPolygonRef { coord_t length = 0; Point p0 = path->front(); - for (unsigned int n = 1; n < path->size(); n++) + for (size_t n = 1; n < path->size(); n++) { Point p1 = (*path)[n]; length += vSize(p0 - p1); @@ -231,24 +231,38 @@ class ConstPolygonRef Point centerOfMass() const { - double x = 0, y = 0; - Point p0 = (*path)[path->size() - 1]; - for (unsigned int n = 0; n < path->size(); n++) + if (path->size() > 0) { - Point p1 = (*path)[n]; - double second_factor = static_cast((p0.X * p1.Y) - (p1.X * p0.Y)); + Point p0 = (*path)[0]; + if (path->size() > 1) + { + double x = 0, y = 0; + for (size_t n = 1; n <= path->size(); n++) + { + Point p1 = (*path)[n % path->size()]; + double second_factor = static_cast((p0.X * p1.Y) - (p1.X * p0.Y)); - x += double(p0.X + p1.X) * second_factor; - y += double(p0.Y + p1.Y) * second_factor; - p0 = p1; - } + x += double(p0.X + p1.X) * second_factor; + y += double(p0.Y + p1.Y) * second_factor; + p0 = p1; + } - double area = Area(*path); + double area = Area(*path); - x = x / 6 / area; - y = y / 6 / area; + x = x / 6 / area; + y = y / 6 / area; - return Point(std::llrint(x), std::llrint(y)); + return Point(std::llrint(x), std::llrint(y)); + } + else + { + return p0; + } + } + else + { + return Point(); + } } Point closestPointTo(Point p) const @@ -545,7 +559,7 @@ class PolygonRef : public ConstPolygonRef void insert(size_t index, Point p) { POLY_ASSERT(index < size() && index <= static_cast(std::numeric_limits::max())); - path->insert(path->begin() + index, p); + path->insert(path->begin() + static_cast(index), p); } void clear() @@ -803,7 +817,7 @@ class Polygons public: ClipperLib::Paths paths; - unsigned int size() const + size_t size() const { return paths.size(); } @@ -822,14 +836,14 @@ class Polygons unsigned int pointCount() const; //!< Return the amount of points in all polygons - PolygonRef operator[](unsigned int index) + PolygonRef operator[](size_t index) { - POLY_ASSERT(index < size() && index <= static_cast(std::numeric_limits::max())); + POLY_ASSERT(index < size()); return paths[index]; } - ConstPolygonRef operator[](unsigned int index) const + ConstPolygonRef operator[](size_t index) const { - POLY_ASSERT(index < size() && index <= static_cast(std::numeric_limits::max())); + POLY_ASSERT(index < size()); return paths[index]; } ClipperLib::Paths::iterator begin() @@ -853,9 +867,9 @@ class Polygons * * \warning changes the order of the polygons! */ - void remove(unsigned int index) + void remove(size_t index) { - POLY_ASSERT(index < size() && index <= static_cast(std::numeric_limits::max())); + POLY_ASSERT(index < size()); if (index < paths.size() - 1) { paths[index] = std::move(paths.back()); @@ -1377,7 +1391,7 @@ class Polygons Polygons remove(const Polygons& to_be_removed, int same_distance = 0) const { Polygons result; - for (unsigned int poly_keep_idx = 0; poly_keep_idx < size(); poly_keep_idx++) + for (size_t poly_keep_idx = 0; poly_keep_idx < size(); poly_keep_idx++) { ConstPolygonRef poly_keep = (*this)[poly_keep_idx]; bool should_be_removed = false; @@ -1390,9 +1404,9 @@ class Polygons continue; // find closest point, supposing this point aligns the two shapes in the best way - int closest_point_idx = 0; + size_t closest_point_idx = 0; int smallestDist2 = -1; - for (unsigned int point_rem_idx = 0; point_rem_idx < poly_rem.size(); point_rem_idx++) + for (size_t point_rem_idx = 0; point_rem_idx < poly_rem.size(); point_rem_idx++) { int dist2 = vSize2(poly_rem[point_rem_idx] - poly_keep[0]); if (dist2 < smallestDist2 || smallestDist2 < 0) From ffbb28b18661e455a160665172df13773959bb15 Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Mon, 20 Nov 2023 17:16:50 +0100 Subject: [PATCH 06/48] Fixed more number conversion warnings --- include/settings/types/Duration.h | 2 +- include/utils/SVG.h | 98 ++++++------ include/utils/floatpoint.h | 3 + include/utils/polygon.h | 12 +- src/utils/SVG.cpp | 254 ++++++++++++++++++++---------- src/utils/polygon.cpp | 145 ++++++++++------- 6 files changed, 323 insertions(+), 191 deletions(-) diff --git a/include/settings/types/Duration.h b/include/settings/types/Duration.h index c068ae0e1a..4398622aa6 100644 --- a/include/settings/types/Duration.h +++ b/include/settings/types/Duration.h @@ -84,7 +84,7 @@ inline std::ostream& operator<<(std::ostream& out, const Duration seconds) double s = seconds; if (pretty_print && seconds > 60) { - int min = seconds / 60; + int min = static_cast(seconds) / 60; s -= min * 60; if (min > 60) { diff --git a/include/utils/SVG.h b/include/utils/SVG.h index c4418ef86f..8257e7e959 100644 --- a/include/utils/SVG.h +++ b/include/utils/SVG.h @@ -1,5 +1,5 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef SVG_H #define SVG_H @@ -19,7 +19,8 @@ class FPoint3; class SVG : NoCopy { public: - enum class Color { + enum class Color + { BLACK, WHITE, GRAY, @@ -36,34 +37,38 @@ class SVG : NoCopy struct ColorObject { - bool is_enum; - Color color; - int r, g, b; + bool is_enum_; + Color color_; + int r_, g_, b_; + ColorObject(Color color) - : is_enum(true) - , color(color) - {} + : is_enum_(true) + , color_(color) + { + } + ColorObject(int r, int g, int b) - : is_enum(false) - , r(r) - , g(g) - , b(b) - {} + : is_enum_(false) + , r_(r) + , g_(g) + , b_(b) + { + } }; -private: +private: std::string toString(const Color color) const; std::string toString(const ColorObject& color) const; - FILE* out; // the output file - const AABB aabb; // the boundary box to display - const Point aabb_size; - const Point canvas_size; - const double scale; - ColorObject background; - size_t layer_nr = 1; + FILE* out_; // the output file + const AABB aabb_; // the boundary box to display + const Point aabb_size_; + const Point canvas_size_; + const double scale_; + ColorObject background_; + size_t layer_nr_ = 1; - bool output_is_html; + bool output_is_html_; public: SVG(std::string filename, const AABB aabb, const Point canvas_size = Point(1024, 1024), const ColorObject background = Color::NONE); @@ -91,22 +96,22 @@ class SVG : NoCopy void writeComment(const std::string& comment) const; - void writeAreas(const Polygons& polygons, const ColorObject color = Color::GRAY, const ColorObject outline_color = Color::BLACK, const float stroke_width = 1) const; + void writeAreas(const Polygons& polygons, const ColorObject color = Color::GRAY, const ColorObject outline_color = Color::BLACK, const float stroke_width = 1.0f) const; - void writeAreas(ConstPolygonRef polygon, const ColorObject color = Color::GRAY, const ColorObject outline_color = Color::BLACK, const float stroke_width = 1) const; + void writeAreas(ConstPolygonRef polygon, const ColorObject color = Color::GRAY, const ColorObject outline_color = Color::BLACK, const float stroke_width = 1.0f) const; - void writePoint(const Point& p, const bool write_coords = false, const float size = 5.0, const ColorObject color = Color::BLACK) const; + void writePoint(const Point& p, const bool write_coords = false, const float size = 5.0f, const ColorObject color = Color::BLACK) const; - void writePoints(ConstPolygonRef poly, const bool write_coords = false, const float size = 5.0, const ColorObject color = Color::BLACK) const; + void writePoints(ConstPolygonRef poly, const bool write_coords = false, const float size = 5.0f, const ColorObject color = Color::BLACK) const; - void writePoints(const Polygons& polygons, const bool write_coords = false, const float size = 5.0, const ColorObject color = Color::BLACK) const; + void writePoints(const Polygons& polygons, const bool write_coords = false, const float size = 5.0f, const ColorObject color = Color::BLACK) const; /*! * \brief Draws a polyline on the canvas. - * + * * The polyline is the set of line segments between each pair of consecutive * points in the specified vector. - * + * * \param polyline A set of points between which line segments must be * drawn. * \param color The colour of the line segments. If this is not specified, @@ -114,35 +119,35 @@ class SVG : NoCopy */ void writeLines(const std::vector& polyline, const ColorObject color = Color::BLACK) const; - void writeLine(const Point& a, const Point& b, const ColorObject color = Color::BLACK, const float stroke_width = 1) const; + void writeLine(const Point& a, const Point& b, const ColorObject color = Color::BLACK, const float stroke_width = 1.0f) const; - void writeArrow(const Point& a, const Point& b, const ColorObject color = Color::BLACK, const float stroke_width = 1, const float head_size = 5.0) const; + void writeArrow(const Point& a, const Point& b, const ColorObject color = Color::BLACK, const float stroke_width = 1.0f, const float head_size = 5.0f) const; - void writeLineRGB(const Point& from, const Point& to, const int r = 0, const int g = 0, const int b = 0, const float stroke_width = 1) const; + void writeLineRGB(const Point& from, const Point& to, const int r = 0, const int g = 0, const int b = 0, const float stroke_width = 1.0f) const; /*! * \brief Draws a dashed line on the canvas from point A to point B. - * + * * This is useful in the case where multiple lines may overlap each other. - * + * * \param a The starting endpoint of the line. * \param b The ending endpoint of the line. * \param color The stroke colour of the line. */ - void writeDashedLine(const Point& a,const Point& b, ColorObject color = Color::BLACK) const; + void writeDashedLine(const Point& a, const Point& b, ColorObject color = Color::BLACK) const; template void printf(const char* txt, Args&&... args) const; - void writeText(const Point& p, const std::string& txt, const ColorObject color = Color::BLACK, const float font_size = 10) const; + void writeText(const Point& p, const std::string& txt, const ColorObject color = Color::BLACK, const float font_size = 10.0f) const; - void writePolygons(const Polygons& polys, const ColorObject color = Color::BLACK, const float stroke_width = 1) const; + void writePolygons(const Polygons& polys, const ColorObject color = Color::BLACK, const float stroke_width = 1.0f) const; - void writePolygon(ConstPolygonRef poly, const ColorObject color = Color::BLACK, const float stroke_width = 1) const; + void writePolygon(ConstPolygonRef poly, const ColorObject color = Color::BLACK, const float stroke_width = 1.0f) const; - void writePolylines(const Polygons& polys, const ColorObject color = Color::BLACK, const float stroke_width = 1) const; + void writePolylines(const Polygons& polys, const ColorObject color = Color::BLACK, const float stroke_width = 1.0f) const; - void writePolyline(ConstPolygonRef poly, const ColorObject color = Color::BLACK, const float stroke_width = 1) const; + void writePolyline(ConstPolygonRef poly, const ColorObject color = Color::BLACK, const float stroke_width = 1.0f) const; /*! * Draw variable-width paths into the image. @@ -153,7 +158,7 @@ class SVG : NoCopy * \param color The color to draw the paths with. * \param width_factor A multiplicative factor on the line widths. */ - void writePaths(const std::vector& paths, const ColorObject color = Color::BLACK, const float width_factor = 1.0) const; + void writePaths(const std::vector& paths, const ColorObject color = Color::BLACK, const float width_factor = 1.0f) const; /*! * Draw variable-width lines into the image. @@ -164,7 +169,7 @@ class SVG : NoCopy * \param color The color to draw the lines with. * \param width_factor A multiplicative factor on the line widths. */ - void writeLines(const VariableWidthLines& lines, const ColorObject color = Color::BLACK, const float width_factor = 1.0) const; + void writeLines(const VariableWidthLines& lines, const ColorObject color = Color::BLACK, const float width_factor = 1.0f) const; /*! * Draw a variable-width line into the image. @@ -175,7 +180,7 @@ class SVG : NoCopy * \param color The color to draw the line with. * \param width_factor A multiplicative factor on the line width. */ - void writeLine(const ExtrusionLine& line, const ColorObject color = Color::BLACK, const float width_factor = 1.0) const; + void writeLine(const ExtrusionLine& line, const ColorObject color = Color::BLACK, const float width_factor = 1.0f) const; /*! * Draws a grid across the image and writes down coordinates. @@ -186,14 +191,13 @@ class SVG : NoCopy * \param stroke_width The width of the grid lines. * \param font_size The size of the font to write the coordinates with. */ - void writeCoordinateGrid(const coord_t grid_size = MM2INT(1), const Color color = Color::BLACK, const float stroke_width = 0.1, const float font_size = 10) const; - + void writeCoordinateGrid(const coord_t grid_size = MM2INT(1), const Color color = Color::BLACK, const float stroke_width = 0.1f, const float font_size = 10) const; }; template void SVG::printf(const char* txt, Args&&... args) const { - fprintf(out, txt, args...); + fprintf(out_, txt, args...); } } // namespace cura diff --git a/include/utils/floatpoint.h b/include/utils/floatpoint.h index 8f4d35b52f..df9a2d2ad0 100644 --- a/include/utils/floatpoint.h +++ b/include/utils/floatpoint.h @@ -21,15 +21,18 @@ class FPoint3 { public: float x, y, z; + FPoint3() { } + FPoint3(float _x, float _y, float _z) : x(_x) , y(_y) , z(_z) { } + FPoint3(const Point3& p) : x(static_cast(p.x_) * .001f) , y(static_cast(p.y_) * .001f) diff --git a/include/utils/polygon.h b/include/utils/polygon.h index 6ce4b72f9d..b32b59e51f 100644 --- a/include/utils/polygon.h +++ b/include/utils/polygon.h @@ -1405,10 +1405,10 @@ class Polygons // find closest point, supposing this point aligns the two shapes in the best way size_t closest_point_idx = 0; - int smallestDist2 = -1; + coord_t smallestDist2 = -1; for (size_t point_rem_idx = 0; point_rem_idx < poly_rem.size(); point_rem_idx++) { - int dist2 = vSize2(poly_rem[point_rem_idx] - poly_keep[0]); + coord_t dist2 = vSize2(poly_rem[point_rem_idx] - poly_keep[0]); if (dist2 < smallestDist2 || smallestDist2 < 0) { smallestDist2 = dist2; @@ -1419,9 +1419,9 @@ class Polygons // compare the two polygons on all points if (smallestDist2 > same_distance * same_distance) continue; - for (unsigned int point_idx = 0; point_idx < poly_rem.size(); point_idx++) + for (size_t point_idx = 0; point_idx < poly_rem.size(); point_idx++) { - int dist2 = vSize2(poly_rem[(closest_point_idx + point_idx) % poly_rem.size()] - poly_keep[point_idx]); + coord_t dist2 = vSize2(poly_rem[(closest_point_idx + point_idx) % poly_rem.size()] - poly_keep[point_idx]); if (dist2 > same_distance * same_distance) { poly_rem_is_poly_keep = false; @@ -1558,9 +1558,9 @@ class PolygonsPart : public Polygons class PartsView : public std::vector> { public: - Polygons& polygons; + Polygons& polygons_; PartsView(Polygons& polygons) - : polygons(polygons) + : polygons_(polygons) { } /*! diff --git a/src/utils/SVG.cpp b/src/utils/SVG.cpp index c6959c4810..c0a3170d76 100644 --- a/src/utils/SVG.cpp +++ b/src/utils/SVG.cpp @@ -1,12 +1,13 @@ // Copyright (c) 2022 Ultimaker B.V. // CuraEngine is released under the terms of the AGPLv3 or higher +#include "utils/SVG.h" + #include #include #include "utils/ExtrusionLine.h" -#include "utils/SVG.h" #include "utils/floatpoint.h" #include "utils/polygon.h" @@ -47,141 +48,165 @@ std::string SVG::toString(Color color) const std::string SVG::toString(const ColorObject& color) const { - if (color.is_enum) - return toString(color.color); + if (color.is_enum_) + return toString(color.color_); else { std::ostringstream ss; - ss << "rgb(" << color.r << "," << color.g << "," << color.b << ")"; + ss << "rgb(" << color.r_ << "," << color.g_ << "," << color.b_ << ")"; return ss.str(); } } SVG::SVG(std::string filename, AABB aabb, Point canvas_size, ColorObject background) - : SVG(filename, aabb, std::min(double(canvas_size.X - canvas_size.X / 5 * 2) / (aabb.max.X - aabb.min.X), double(canvas_size.Y - canvas_size.Y / 5) / (aabb.max.Y - aabb.min.Y)), canvas_size, background) + : SVG( + filename, + aabb, + std::min( + static_cast(canvas_size.X - canvas_size.X / 5 * 2) / static_cast(aabb.max.X - aabb.min.X), + static_cast(canvas_size.Y - canvas_size.Y / 5) / static_cast(aabb.max.Y - aabb.min.Y)), + canvas_size, + background) { } -SVG::SVG(std::string filename, AABB aabb, double scale, ColorObject background) : SVG(filename, aabb, scale, (aabb.max - aabb.min) * scale, background) +SVG::SVG(std::string filename, AABB aabb, double scale, ColorObject background) + : SVG(filename, aabb, scale, (aabb.max - aabb.min) * scale, background) { } -SVG::SVG(std::string filename, AABB aabb, double scale, Point canvas_size, ColorObject background) : aabb(aabb), aabb_size(aabb.max - aabb.min), canvas_size(canvas_size), scale(scale), background(background) +SVG::SVG(std::string filename, AABB aabb, double scale, Point canvas_size, ColorObject background) + : aabb_(aabb) + , aabb_size_(aabb.max - aabb.min) + , canvas_size_(canvas_size) + , scale_(scale) + , background_(background) { - output_is_html = strcmp(filename.c_str() + strlen(filename.c_str()) - 4, "html") == 0; - out = fopen(filename.c_str(), "w"); - if (! out) + output_is_html_ = strcmp(filename.c_str() + strlen(filename.c_str()) - 4, "html") == 0; + out_ = fopen(filename.c_str(), "w"); + if (! out_) { spdlog::error("The file %s could not be opened for writing.", filename); } - if (output_is_html) + if (output_is_html_) { - fprintf(out, "\n"); + fprintf(out_, "\n"); } else { - fprintf(out, "\n"); + fprintf(out_, "\n"); } - fprintf(out, "\n"); - fprintf(out, " \n", layer_nr); - - if (! background.is_enum || background.color != Color::NONE) + fprintf(out_, "(aabb_.max.Y - aabb_.min.Y)); + fprintf(out_, " width=\"%f\"\n", scale_ * static_cast(aabb_.max.X - aabb_.min.X)); + fprintf(out_, " version=\"1.1\">\n"); + fprintf(out_, " \n", layer_nr_); + + if (! background_.is_enum_ || background_.color_ != Color::NONE) { - fprintf(out, "\n", toString(background).c_str()); + fprintf(out_, "\n", toString(background_).c_str()); } } SVG::~SVG() { - fprintf(out, " \n"); - fprintf(out, "\n"); - if (output_is_html) + fprintf(out_, " \n"); + fprintf(out_, "\n"); + if (output_is_html_) { - fprintf(out, ""); + fprintf(out_, ""); } - fclose(out); + fclose(out_); } double SVG::getScale() const { - return scale; + return scale_; } void SVG::nextLayer() { - fprintf(out, " \n"); - layer_nr++; - fprintf(out, " \n", layer_nr); + fprintf(out_, " \n"); + layer_nr_++; + fprintf(out_, " \n", layer_nr_); } Point SVG::transform(const Point& p) const { - return Point((p.X - aabb.min.X) * scale, (p.Y - aabb.min.Y) * scale); + return Point(std::llrint(static_cast(p.X - aabb_.min.X) * scale_), std::llrint(static_cast(p.Y - aabb_.min.Y) * scale_)); } FPoint3 SVG::transformF(const Point& p) const { - return FPoint3((p.X - aabb.min.X) * scale, (p.Y - aabb.min.Y) * scale, 0.0); + return FPoint3(static_cast(static_cast(p.X - aabb_.min.X) * scale_), static_cast(static_cast(p.Y - aabb_.min.Y) * scale_), 0.0f); } void SVG::writeComment(const std::string& comment) const { - fprintf(out, "\n", comment.c_str()); + fprintf(out_, "\n", comment.c_str()); } void SVG::writeAreas(const Polygons& polygons, const ColorObject color, const ColorObject outline_color, const float stroke_width) const { - auto parts = polygons.splitIntoParts(); + std::vector parts = polygons.splitIntoParts(); for (auto part_it = parts.rbegin(); part_it != parts.rend(); ++part_it) { - PolygonsPart& parts = *part_it; - for (unsigned int j = 0; j < parts.size(); j++) + PolygonsPart& part = *part_it; + for (size_t j = 0; j < part.size(); j++) { - fprintf(out, "(fp.x), static_cast(fp.y)); } if (j == 0) - fprintf(out, "\" style=\"fill:%s;stroke:%s;stroke-width:%f\" />\n", toString(color).c_str(), toString(outline_color).c_str(), stroke_width); + fprintf(out_, "\" style=\"fill:%s;stroke:%s;stroke-width:%f\" />\n", toString(color).c_str(), toString(outline_color).c_str(), static_cast(stroke_width)); else - fprintf(out, "\" style=\"fill:white;stroke:%s;stroke-width:%f\" />\n", toString(outline_color).c_str(), stroke_width); + fprintf(out_, "\" style=\"fill:white;stroke:%s;stroke-width:%f\" />\n", toString(outline_color).c_str(), static_cast(stroke_width)); } } } void SVG::writeAreas(ConstPolygonRef polygon, const ColorObject color, const ColorObject outline_color, const float stroke_width) const { - fprintf(out, "(stroke_width)); // The beginning of the polygon tag. for (const Point& point : polygon) // Add every point to the list of points. { FPoint3 transformed = transformF(point); - fprintf(out, "%f,%f ", transformed.x, transformed.y); + fprintf(out_, "%f,%f ", static_cast(transformed.x), static_cast(transformed.y)); } - fprintf(out, "\" />\n"); // The end of the polygon tag. + fprintf(out_, "\" />\n"); // The end of the polygon tag. } void SVG::writePoint(const Point& p, const bool write_coords, const float size, const ColorObject color) const { FPoint3 pf = transformF(p); - fprintf(out, "\n", pf.x, pf.y, size, toString(color).c_str()); + fprintf( + out_, + "\n", + static_cast(pf.x), + static_cast(pf.y), + static_cast(size), + toString(color).c_str()); if (write_coords) { - fprintf(out, "%lli,%lli\n", pf.x, pf.y, p.X, p.Y); + fprintf(out_, "%lli,%lli\n", static_cast(pf.x), static_cast(pf.y), p.X, p.Y); } } @@ -195,7 +220,7 @@ void SVG::writePoints(ConstPolygonRef poly, const bool write_coords, const float void SVG::writePoints(const Polygons& polygons, const bool write_coords, const float size, const ColorObject color) const { - for (const ConstPolygonRef& poly : polygons) + for (const ConstPolygonRef poly : polygons) { writePoints(poly, write_coords, size, color); } @@ -209,20 +234,33 @@ void SVG::writeLines(const std::vector& polyline, const ColorObject color } FPoint3 transformed = transformF(polyline[0]); // Element 0 must exist due to the check above. - fprintf(out, "(transformed.x), + static_cast(transformed.y)); // Write the start of the path tag and the first endpoint. for (size_t point = 1; point < polyline.size(); point++) { transformed = transformF(polyline[point]); - fprintf(out, "L%f,%f", transformed.x, transformed.y); // Write a line segment to the next point. + fprintf(out_, "L%f,%f", static_cast(transformed.x), static_cast(transformed.y)); // Write a line segment to the next point. } - fprintf(out, "\" />\n"); // Write the end of the tag. + fprintf(out_, "\" />\n"); // Write the end of the tag. } void SVG::writeLine(const Point& a, const Point& b, const ColorObject color, const float stroke_width) const { FPoint3 fa = transformF(a); FPoint3 fb = transformF(b); - fprintf(out, "\n", fa.x, fa.y, fb.x, fb.y, toString(color).c_str(), stroke_width); + fprintf( + out_, + "\n", + static_cast(fa.x), + static_cast(fa.y), + static_cast(fb.x), + static_cast(fb.y), + toString(color).c_str(), + static_cast(stroke_width)); } void SVG::writeArrow(const Point& a, const Point& b, const ColorObject color, const float stroke_width, const float head_size) const @@ -234,29 +272,66 @@ void SVG::writeArrow(const Point& a, const Point& b, const ColorObject color, co FPoint3 direction = ab.normalized(); FPoint3 tip = fb + normal * head_size - direction * head_size; - FPoint3 b_base = fb + normal * stroke_width - direction * stroke_width * 2.41; + FPoint3 b_base = fb + normal * stroke_width - direction * stroke_width * 2.41f; FPoint3 a_base = fa + normal * stroke_width; - fprintf(out, "", toString(color).c_str(), fa.x, fa.y, fb.x, fb.y, tip.x, tip.y, b_base.x, b_base.y, a_base.x, a_base.y); + fprintf( + out_, + "", + toString(color).c_str(), + static_cast(fa.x), + static_cast(fa.y), + static_cast(fb.x), + static_cast(fb.y), + static_cast(tip.x), + static_cast(tip.y), + static_cast(b_base.x), + static_cast(b_base.y), + static_cast(a_base.x), + static_cast(a_base.y)); } void SVG::writeLineRGB(const Point& from, const Point& to, const int r, const int g, const int b, const float stroke_width) const { FPoint3 fa = transformF(from); FPoint3 fb = transformF(to); - fprintf(out, "\n", fa.x, fa.y, fb.x, fb.y, r, g, b, stroke_width); + fprintf( + out_, + "\n", + static_cast(fa.x), + static_cast(fa.y), + static_cast(fb.x), + static_cast(fb.y), + r, + g, + b, + static_cast(stroke_width)); } void SVG::writeDashedLine(const Point& a, const Point& b, ColorObject color) const { FPoint3 fa = transformF(a); FPoint3 fb = transformF(b); - fprintf(out, "\n", fa.x, fa.y, fb.x, fb.y, toString(color).c_str()); + fprintf( + out_, + "\n", + static_cast(fa.x), + static_cast(fa.y), + static_cast(fb.x), + static_cast(fb.y), + toString(color).c_str()); } void SVG::writeText(const Point& p, const std::string& txt, const ColorObject color, const float font_size) const { FPoint3 pf = transformF(p); - fprintf(out, "%s\n", pf.x, pf.y, font_size, toString(color).c_str(), txt.c_str()); + fprintf( + out_, + "%s\n", + static_cast(pf.x), + static_cast(pf.y), + static_cast(font_size), + toString(color).c_str(), + txt.c_str()); } void SVG::writePolygons(const Polygons& polys, const ColorObject color, const float stroke_width) const @@ -273,12 +348,12 @@ void SVG::writePolygon(ConstPolygonRef poly, const ColorObject color, const floa { return; } - int size = poly.size(); + int size = static_cast(poly.size()); Point p0 = poly.back(); int i = 0; for (Point p1 : poly) { - if (color.color == Color::RAINBOW) + if (color.color_ == Color::RAINBOW) { int g = (i * 255 * 11 / size) % (255 * 2); if (g > 255) @@ -316,13 +391,13 @@ void SVG::writePolyline(ConstPolygonRef poly, const ColorObject color, const flo { return; } - int size = poly.size(); + const int size = static_cast(poly.size()); Point p0 = poly[0]; int i = 0; for (size_t p_idx = 1; p_idx < poly.size(); p_idx++) { Point p1 = poly[p_idx]; - if (color.color == Color::RAINBOW) + if (color.color_ == Color::RAINBOW) { int g = (i * 255 * 11 / size) % (255 * 2); if (g > 255) @@ -373,12 +448,25 @@ void SVG::writeLine(const ExtrusionLine& line, const ColorObject color, const fl const Point direction_vector = end_vertex.p - start_vertex.p; const Point direction_left = turn90CCW(direction_vector); const Point direction_right = -direction_left; // Opposite of left. - const FPoint3 start_left = transformF(start_vertex.p + normal(direction_left, std::max(minimum_line_width, start_vertex.w * width_factor))); - const FPoint3 start_right = transformF(start_vertex.p + normal(direction_right, std::max(minimum_line_width, start_vertex.w * width_factor))); - const FPoint3 end_left = transformF(end_vertex.p + normal(direction_left, std::max(minimum_line_width, end_vertex.w * width_factor))); - const FPoint3 end_right = transformF(end_vertex.p + normal(direction_right, std::max(minimum_line_width, end_vertex.w * width_factor))); - - fprintf(out, "\n", toString(color).c_str(), start_left.x, start_left.y, start_right.x, start_right.y, end_right.x, end_right.y, end_left.x, end_left.y); + const FPoint3 start_left + = transformF(start_vertex.p + normal(direction_left, std::llrint(std::max(minimum_line_width, static_cast(start_vertex.w) * width_factor)))); + const FPoint3 start_right + = transformF(start_vertex.p + normal(direction_right, std::llrint(std::max(minimum_line_width, static_cast(start_vertex.w) * width_factor)))); + const FPoint3 end_left = transformF(end_vertex.p + normal(direction_left, std::llrint(std::max(minimum_line_width, static_cast(end_vertex.w) * width_factor)))); + const FPoint3 end_right = transformF(end_vertex.p + normal(direction_right, std::llrint(std::max(minimum_line_width, static_cast(end_vertex.w) * width_factor)))); + + fprintf( + out_, + "\n", + toString(color).c_str(), + static_cast(start_left.x), + static_cast(start_left.y), + static_cast(start_right.x), + static_cast(start_right.y), + static_cast(end_right.x), + static_cast(end_right.y), + static_cast(end_left.x), + static_cast(end_left.y)); start_vertex = end_vertex; // For the next line segment. } @@ -386,23 +474,23 @@ void SVG::writeLine(const ExtrusionLine& line, const ColorObject color, const fl void SVG::writeCoordinateGrid(const coord_t grid_size, const Color color, const float stroke_width, const float font_size) const { - constexpr float dist_from_edge = 0.05; // As fraction of image width or height. - const coord_t min_x = aabb.min.X - (aabb.min.X % grid_size); - const coord_t min_y = aabb.min.Y - (aabb.min.Y % grid_size); + constexpr float dist_from_edge = 0.05f; // As fraction of image width or height. + const coord_t min_x = aabb_.min.X - (aabb_.min.X % grid_size); + const coord_t min_y = aabb_.min.Y - (aabb_.min.Y % grid_size); - for (coord_t x = min_x; x < aabb.max.X; x += grid_size) + for (coord_t x = min_x; x < aabb_.max.X; x += grid_size) { - writeLine(Point(x, aabb.min.Y), Point(x, aabb.max.Y), color, stroke_width); + writeLine(Point(x, aabb_.min.Y), Point(x, aabb_.max.Y), color, stroke_width); std::stringstream ss; ss << INT2MM(x); - writeText(Point(x, aabb.min.Y + (aabb.max.Y - aabb.min.Y) * dist_from_edge), ss.str(), color, font_size); + writeText(Point(x, std::llrint(static_cast(aabb_.min.Y) + static_cast(aabb_.max.Y - aabb_.min.Y) * dist_from_edge)), ss.str(), color, font_size); } - for (coord_t y = min_y; y < aabb.max.Y; y += grid_size) + for (coord_t y = min_y; y < aabb_.max.Y; y += grid_size) { - writeLine(Point(aabb.min.X, y), Point(aabb.max.Y, y), color, stroke_width); + writeLine(Point(aabb_.min.X, y), Point(aabb_.max.Y, y), color, stroke_width); std::stringstream ss; ss << INT2MM(y); - writeText(Point(aabb.min.X + (aabb.max.X - aabb.min.X) * dist_from_edge, y), ss.str(), color, font_size); + writeText(Point(std::llrint(static_cast(aabb_.min.X) + static_cast(aabb_.max.X - aabb_.min.X) * dist_from_edge), y), ss.str(), color, font_size); } } diff --git a/src/utils/polygon.cpp b/src/utils/polygon.cpp index 0f80cb9061..40974e8d6e 100644 --- a/src/utils/polygon.cpp +++ b/src/utils/polygon.cpp @@ -1,20 +1,18 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #include "utils/polygon.h" #include #include -#include #include #include - -#include "utils/linearAlg2D.h" // pointLiesOnTheRightOfLine +#include #include "utils/ListPolyIt.h" - #include "utils/PolylineStitcher.h" +#include "utils/linearAlg2D.h" // pointLiesOnTheRightOfLine namespace cura { @@ -109,7 +107,14 @@ void Polygons::makeConvex() Polygon convexified; // Start from a vertex that is known to be on the convex hull: The one with the lowest X. - const size_t start_index = std::min_element(poly.begin(), poly.end(), [](Point a, Point b) { return a.X == b.X ? a.Y < b.Y : a.X < b.X; }) - poly.begin(); + const size_t start_index = std::min_element( + poly.begin(), + poly.end(), + [](Point a, Point b) + { + return a.X == b.X ? a.Y < b.Y : a.X < b.X; + }) + - poly.begin(); convexified.path->push_back(poly[start_index]); for (size_t i = 1; i <= poly.size(); ++i) @@ -375,14 +380,19 @@ Polygons Polygons::offset(const std::vector& offset_dists) const Polygons ret; int i = 0; - for (auto& poly_line : this->paths | ranges::views::filter([](const auto& path){ return ! path.empty(); })) + for (auto& poly_line : this->paths + | ranges::views::filter( + [](const auto& path) + { + return ! path.empty(); + })) { std::vector ret_poly_line; auto prev_p = poly_line.back(); auto prev_dist = offset_dists[i + poly_line.size() - 1]; - for (const auto& p: poly_line) + for (const auto& p : poly_line) { auto offset_dist = offset_dists[i]; @@ -400,7 +410,7 @@ Polygons Polygons::offset(const std::vector& offset_dists) const prev_p = p; prev_dist = offset_dist; - i ++; + i++; } ret.add(ret_poly_line); @@ -475,8 +485,11 @@ void PolygonRef::removeColinearEdges(const AngleRadians max_deviation_angle) const Point& pt = rpath[point_idx]; const Point& next = rpath[(point_idx + 1) % pathlen]; - float angle = LinearAlg2D::getAngleLeft(prev, pt, next); // [0 : 2 * pi] - if (angle >= std::numbers::pi) {angle -= std::numbers::pi;} // map [pi : 2 * pi] to [0 : pi] + float angle = LinearAlg2D::getAngleLeft(prev, pt, next); // [0 : 2 * pi] + if (angle >= std::numbers::pi) + { + angle -= std::numbers::pi; + } // map [pi : 2 * pi] to [0 : pi] // Check if the angle is within limits for the point to 'make sense', given the maximum deviation. // If the angle indicates near-parallel segments ignore the point 'pt' @@ -499,8 +512,7 @@ void PolygonRef::removeColinearEdges(const AngleRadians max_deviation_angle) process_indices.clear(); process_indices.insert(process_indices.end(), skip_indices.begin(), skip_indices.end()); } - } - while (num_removed_in_iteration > 0); + } while (num_removed_in_iteration > 0); } void PolygonRef::applyMatrix(const PointMatrix& matrix) @@ -680,7 +692,7 @@ void Polygons::removeSmallAreaCircumference(const double min_area_size, const co { // containing parent outline is removed; hole should be removed as well } - else if (!remove_holes || (circumference >= min_circumference_size && std::abs(area) >= min_area_size)) + else if (! remove_holes || (circumference >= min_circumference_size && std::abs(area) >= min_area_size)) { // keep hole-polygon if we do not remove holes, or if its // circumference is bigger then the minimum circumference size @@ -704,7 +716,7 @@ void Polygons::removeDegenerateVertsPolyline() void Polygons::_removeDegenerateVerts(const bool for_polyline) { Polygons& thiss = *this; - for(size_t poly_idx = 0; poly_idx < size(); poly_idx++) + for (size_t poly_idx = 0; poly_idx < size(); poly_idx++) { PolygonRef poly = thiss[poly_idx]; Polygon result; @@ -716,28 +728,28 @@ void Polygons::_removeDegenerateVerts(const bool for_polyline) return dot(last_line, next_line) == -1 * vSize(last_line) * vSize(next_line); }; - //With polylines, skip the first and last vertex. + // With polylines, skip the first and last vertex. const size_t start_vertex = for_polyline ? 1 : 0; const size_t end_vertex = for_polyline ? poly.size() - 1 : poly.size(); - for(size_t i = 0; i < start_vertex; ++i) + for (size_t i = 0; i < start_vertex; ++i) { - result.add(poly[i]); //Add everything before the start vertex. + result.add(poly[i]); // Add everything before the start vertex. } bool isChanged = false; - for(size_t idx = start_vertex; idx < end_vertex; idx++) + for (size_t idx = start_vertex; idx < end_vertex; idx++) { const Point& last = (result.size() == 0) ? poly.back() : result.back(); - if(idx + 1 >= poly.size() && result.size() == 0) + if (idx + 1 >= poly.size() && result.size() == 0) { break; } const Point& next = (idx + 1 >= poly.size()) ? result[0] : poly[idx + 1]; - if(isDegenerate(last, poly[idx], next)) + if (isDegenerate(last, poly[idx], next)) { // lines are in the opposite direction // don't add vert to the result isChanged = true; - while(result.size() > 1 && isDegenerate(result[result.size() - 2], result.back(), next)) + while (result.size() > 1 && isDegenerate(result[result.size() - 2], result.back(), next)) { result.pop_back(); } @@ -748,14 +760,14 @@ void Polygons::_removeDegenerateVerts(const bool for_polyline) } } - for(size_t i = end_vertex; i < poly.size(); ++i) + for (size_t i = end_vertex; i < poly.size(); ++i) { - result.add(poly[i]); //Add everything after the end vertex. + result.add(poly[i]); // Add everything after the end vertex. } - if(isChanged) + if (isChanged) { - if(for_polyline || result.size() > 2) + if (for_polyline || result.size() > 2) { *poly = *result; } @@ -853,7 +865,7 @@ bool ConstPolygonRef::smooth_corner_complex(const Point p1, ListPolyIt& p0_it, L // handle this separately to avoid rounding problems below in the getPointOnLineWithDist function // p0_it and p2_it are already correct } - else if (!backward_is_blocked && !forward_is_blocked) + else if (! backward_is_blocked && ! forward_is_blocked) { // introduce two new points // 1----b---->2 // ^ / @@ -871,14 +883,15 @@ bool ConstPolygonRef::smooth_corner_complex(const Point p1, ListPolyIt& p0_it, L const Point p0_2 = p0_2_it.p(); const Point v02_2 = p0_2 - p2_2; const int64_t v02_2_size = vSize(v02_2); - float progress = std::min(1.0, INT2MM(shortcut_length - v02_size) / INT2MM(v02_2_size - v02_size)); // account for rounding error when v02_2_size is approx equal to v02_size + float progress + = std::min(1.0, INT2MM(shortcut_length - v02_size) / INT2MM(v02_2_size - v02_size)); // account for rounding error when v02_2_size is approx equal to v02_size assert(progress >= 0.0f && progress <= 1.0f && "shortcut length must be between last length and new length"); const Point new_p0 = p0_it.p() + (p0_2 - p0_it.p()) * progress; p0_it = ListPolyIt::insertPointNonDuplicate(p0_2_it, p0_it, new_p0); const Point new_p2 = p2_it.p() + (p2_2 - p2_it.p()) * progress; p2_it = ListPolyIt::insertPointNonDuplicate(p2_it, p2_2_it, new_p2); } - else if (!backward_is_blocked) + else if (! backward_is_blocked) { // forward is blocked, back is open // | // 1->b @@ -911,7 +924,7 @@ bool ConstPolygonRef::smooth_corner_complex(const Point p1, ListPolyIt& p0_it, L } } } - else if (!forward_is_blocked) + else if (! forward_is_blocked) { // backward is blocked, front is open // 1----2----b----------->2_2 // ^ ,-' @@ -957,20 +970,29 @@ bool ConstPolygonRef::smooth_corner_complex(const Point p1, ListPolyIt& p0_it, L return false; } -void ConstPolygonRef::smooth_outward_step(const Point p1, const int64_t shortcut_length2, ListPolyIt& p0_it, ListPolyIt& p2_it, bool& forward_is_blocked, bool& backward_is_blocked, bool& forward_is_too_far, bool& backward_is_too_far) +void ConstPolygonRef::smooth_outward_step( + const Point p1, + const int64_t shortcut_length2, + ListPolyIt& p0_it, + ListPolyIt& p2_it, + bool& forward_is_blocked, + bool& backward_is_blocked, + bool& forward_is_too_far, + bool& backward_is_too_far) { const bool forward_has_converged = forward_is_blocked || forward_is_too_far; const bool backward_has_converged = backward_is_blocked || backward_is_too_far; const Point p0 = p0_it.p(); const Point p2 = p2_it.p(); - bool walk_forward = !forward_has_converged && (backward_has_converged || (vSize2(p2 - p1) < vSize2(p0 - p1))); // whether to walk along the p1-p2 direction or in the p1-p0 direction + bool walk_forward + = ! forward_has_converged && (backward_has_converged || (vSize2(p2 - p1) < vSize2(p0 - p1))); // whether to walk along the p1-p2 direction or in the p1-p0 direction if (walk_forward) { const ListPolyIt p2_2_it = p2_it.next(); const Point p2_2 = p2_2_it.p(); bool p2_is_left = LinearAlg2D::pointIsLeftOfLine(p2, p0, p2_2) >= 0; - if (!p2_is_left) + if (! p2_is_left) { forward_is_blocked = true; return; @@ -993,7 +1015,7 @@ void ConstPolygonRef::smooth_outward_step(const Point p1, const int64_t shortcut const ListPolyIt p0_2_it = p0_it.prev(); const Point p0_2 = p0_2_it.p(); bool p0_is_left = LinearAlg2D::pointIsLeftOfLine(p0, p0_2, p2) >= 0; - if (!p0_is_left) + if (! p0_is_left) { backward_is_blocked = true; return; @@ -1013,7 +1035,18 @@ void ConstPolygonRef::smooth_outward_step(const Point p1, const int64_t shortcut } } -void ConstPolygonRef::smooth_corner_simple(const Point p0, const Point p1, const Point p2, const ListPolyIt p0_it, const ListPolyIt p1_it, const ListPolyIt p2_it, const Point v10, const Point v12, const Point v02, const int64_t shortcut_length, float cos_angle) +void ConstPolygonRef::smooth_corner_simple( + const Point p0, + const Point p1, + const Point p2, + const ListPolyIt p0_it, + const ListPolyIt p1_it, + const ListPolyIt p2_it, + const Point v10, + const Point v12, + const Point v02, + const int64_t shortcut_length, + float cos_angle) { // 1----b---->2 // ^ / @@ -1207,8 +1240,6 @@ Polygons Polygons::smooth_outward(const AngleDegrees max_angle, int shortcut_len } - - void ConstPolygonRef::splitPolylineIntoSegments(Polygons& result) const { Point last = front(); @@ -1268,7 +1299,7 @@ void ConstPolygonRef::smooth(int remove_length, PolygonRef result) const return false; } const bool p1_is_left_of_v02 = dot1 < 0; - if (!p1_is_left_of_v02) + if (! p1_is_left_of_v02) { // removing p1 wouldn't smooth outward return false; } @@ -1307,7 +1338,7 @@ void ConstPolygonRef::smooth(int remove_length, PolygonRef result) const const int64_t dot1 = dot(v02T, v12); const Point v13T = turn90CCW(v13); const int64_t dot2 = dot(v13T, v12); - bool push_point = force_push || !is_zigzag(v02_size, v12_size, v13_size, dot1, dot2); + bool push_point = force_push || ! is_zigzag(v02_size, v12_size, v13_size, dot1, dot2); force_push = false; if (push_point) { @@ -1432,12 +1463,12 @@ std::vector Polygons::splitIntoParts(bool unionAll) const void Polygons::splitIntoParts_processPolyTreeNode(ClipperLib::PolyNode* node, std::vector& ret) const { - for(int n=0; nChildCount(); n++) + for (int n = 0; n < node->ChildCount(); n++) { ClipperLib::PolyNode* child = node->Childs[n]; PolygonsPart part; part.add(child->Contour); - for(int i=0; iChildCount(); i++) + for (int i = 0; i < child->ChildCount(); i++) { part.add(child->Childs[i]->Contour); splitIntoParts_processPolyTreeNode(child->Childs[i], ret); @@ -1483,11 +1514,17 @@ unsigned int PartsView::getPartContaining(unsigned int poly_idx, unsigned int* b for (unsigned int part_idx_now = 0; part_idx_now < partsView.size(); part_idx_now++) { const std::vector& partView = partsView[part_idx_now]; - if (partView.size() == 0) { continue; } + if (partView.size() == 0) + { + continue; + } std::vector::const_iterator result = std::find(partView.begin(), partView.end(), poly_idx); if (result != partView.end()) { - if (boundary_poly_idx) { *boundary_poly_idx = partView[0]; } + if (boundary_poly_idx) + { + *boundary_poly_idx = partView[0]; + } return part_idx_now; } } @@ -1502,7 +1539,7 @@ PolygonsPart PartsView::assemblePart(unsigned int part_idx) const { for (unsigned int poly_idx_ff : partsView[part_idx]) { - ret.add(polygons[poly_idx_ff]); + ret.add(polygons_[poly_idx_ff]); } } return ret; @@ -1539,14 +1576,14 @@ PartsView Polygons::splitIntoPartsView(bool unionAll) void Polygons::splitIntoPartsView_processPolyTreeNode(PartsView& partsView, Polygons& reordered, ClipperLib::PolyNode* node) const { - for(int n=0; nChildCount(); n++) + for (int n = 0; n < node->ChildCount(); n++) { ClipperLib::PolyNode* child = node->Childs[n]; partsView.emplace_back(); unsigned int pos = partsView.size() - 1; partsView[pos].push_back(reordered.size()); - reordered.add(child->Contour); //TODO: should this steal the internal representation for speed? - for(int i = 0; i < child->ChildCount(); i++) + reordered.add(child->Contour); // TODO: should this steal the internal representation for speed? + for (int i = 0; i < child->ChildCount(); i++) { partsView[pos].push_back(reordered.size()); reordered.add(child->Childs[i]->Contour); @@ -1577,15 +1614,15 @@ void Polygons::ensureManifold() for (Point p : duplicate_locations) { PolygonRef dot = removal_dots.newPoly(); - dot.add(p + Point(0,5)); - dot.add(p + Point(5,0)); - dot.add(p + Point(0,-5)); - dot.add(p + Point(-5,0)); + dot.add(p + Point(0, 5)); + dot.add(p + Point(5, 0)); + dot.add(p + Point(0, -5)); + dot.add(p + Point(-5, 0)); } - if ( ! removal_dots.empty()) + if (! removal_dots.empty()) { *this = polys.difference(removal_dots); } } -}//namespace cura +} // namespace cura From 1a5baf97319d33f3f0bf8086ee08b5bbf8192945 Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Tue, 21 Nov 2023 08:57:23 +0100 Subject: [PATCH 07/48] Fixed variable shadowing warnings --- include/ExtruderPlan.h | 48 +++++----- include/utils/PolygonsPointIndex.h | 92 +++++++++--------- include/utils/PolylineStitcher.h | 22 ++--- src/ExtruderPlan.cpp | 32 +++---- src/LayerPlan.cpp | 146 ++++++++++++++--------------- src/LayerPlanBuffer.cpp | 126 ++++++++++++------------- src/pathPlanning/Comb.cpp | 4 +- src/utils/PolygonsPointIndex.cpp | 2 +- src/utils/PolylineStitcher.cpp | 2 +- src/utils/polygonUtils.cpp | 34 +++---- 10 files changed, 253 insertions(+), 255 deletions(-) diff --git a/include/ExtruderPlan.h b/include/ExtruderPlan.h index 6f3155148e..5f42adfc09 100644 --- a/include/ExtruderPlan.h +++ b/include/ExtruderPlan.h @@ -44,7 +44,7 @@ class ExtruderPlan FRIEND_TEST(ExtruderPlanTest, BackPressureCompensationEmptyPlan); #endif public: - size_t extruder_nr{ 0 }; //!< The extruder used for this paths in the current plan. + size_t extruder_nr_{ 0 }; //!< The extruder used for this paths in the current plan. ExtruderPlan() noexcept = default; @@ -125,20 +125,20 @@ class ExtruderPlan void applyBackPressureCompensation(const Ratio back_pressure_compensation); private: - LayerIndex layer_nr{ 0 }; //!< The layer number at which we are currently printing. - bool is_initial_layer{ false }; //!< Whether this extruder plan is printed on the very first layer (which might be raft) - bool is_raft_layer{ false }; //!< Whether this is a layer which is part of the raft + LayerIndex layer_nr_{ 0 }; //!< The layer number at which we are currently printing. + bool is_initial_layer_{ false }; //!< Whether this extruder plan is printed on the very first layer (which might be raft) + bool is_raft_layer_{ false }; //!< Whether this is a layer which is part of the raft - coord_t layer_thickness{ 200 }; //!< The thickness of this layer in Z-direction + coord_t layer_thickness_{ 200 }; //!< The thickness of this layer in Z-direction - FanSpeedLayerTimeSettings fan_speed_layer_time_settings{}; //!< The fan speed and layer time settings used to limit this extruder plan + FanSpeedLayerTimeSettings fan_speed_layer_time_settings_{}; //!< The fan speed and layer time settings used to limit this extruder plan - RetractionConfig retraction_config{}; //!< The retraction settings for the extruder of this plan + RetractionConfig retraction_config_{}; //!< The retraction settings for the extruder of this plan - std::vector paths; //!< The paths planned for this extruder - std::list inserts; //!< The nozzle temperature command inserts, to be inserted in between segments - double heated_pre_travel_time{ 0.0 }; //!< The time at the start of this ExtruderPlan during which the head travels and has a temperature of initial_print_temperature + std::vector paths_; //!< The paths planned for this extruder + std::list inserts_; //!< The nozzle temperature command inserts, to be inserted in between segments + double heated_pre_travel_time_{ 0.0 }; //!< The time at the start of this ExtruderPlan during which the head travels and has a temperature of initial_print_temperature /*! * The required temperature at the start of this extruder plan @@ -152,25 +152,21 @@ class ExtruderPlan * In that case no temperature (and wait) command will be inserted from this value, but a NozzleTempInsert is used instead. * In this case this member is only used as a way to convey information between different calls of \ref LayerPlanBuffer::processBuffer */ - double required_start_temperature{ -1.0 }; - std::optional extrusion_temperature{ std::nullopt }; //!< The normal temperature for printing this extruder plan. That start and end of this extruder plan may deviate - //!< because of the initial and final print temp (none if extruder plan has no extrusion moves) - std::optional::iterator> extrusion_temperature_command{ - std::nullopt - }; //!< The command to heat from the printing temperature of this extruder plan to the printing - //!< temperature of the next extruder plan (if it has the same extruder). - std::optional prev_extruder_standby_temp{ - std::nullopt - }; //!< The temperature to which to set the previous extruder. Not used if the previous extruder plan was the same extruder. - - TimeMaterialEstimates estimates{}; //!< Accumulated time and material estimates for all planned paths within this extruder plan. - double slowest_path_speed{ 0.0 }; - - double extraTime{ 0.0 }; //!< Extra waiting time at the and of this extruder plan, so that the filament can cool + double required_start_temperature_{ -1.0 }; + std::optional extrusion_temperature_{}; //!< The normal temperature for printing this extruder plan. That start and end of this extruder plan may deviate + //!< because of the initial and final print temp (none if extruder plan has no extrusion moves) + std::optional::iterator> extrusion_temperature_command_{}; //!< The command to heat from the printing temperature of this extruder plan to the + //!< printing temperature of the next extruder plan (if it has the same extruder). + std::optional prev_extruder_standby_temp_{}; //!< The temperature to which to set the previous extruder. Not used if the previous extruder plan was the same extruder. + + TimeMaterialEstimates estimates_{}; //!< Accumulated time and material estimates for all planned paths within this extruder plan. + double slowest_path_speed_{ 0.0 }; + + double extra_time_{ 0.0 }; //!< Extra waiting time at the and of this extruder plan, so that the filament can cool double fan_speed{ 0.0 }; //!< The fan speed to be used during this extruder plan - double temperatureFactor{ 0.0 }; //!< Temperature reduction factor for small layers + double temperature_factor_{ 0.0 }; //!< Temperature reduction factor for small layers /*! * Set the fan speed to be used while printing this extruder plan diff --git a/include/utils/PolygonsPointIndex.h b/include/utils/PolygonsPointIndex.h index 773bf74622..a72a33af2c 100644 --- a/include/utils/PolygonsPointIndex.h +++ b/include/utils/PolygonsPointIndex.h @@ -1,5 +1,5 @@ -//Copyright (c) 2018 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2018 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef UTILS_POLYGONS_POINT_INDEX_H #define UTILS_POLYGONS_POINT_INDEX_H @@ -10,7 +10,7 @@ #include "polygon.h" -namespace cura +namespace cura { /*! @@ -23,11 +23,9 @@ class PathsPointIndex /*! * The polygons into which this index is indexing. */ - const Paths* polygons; // (pointer to const polygons) - - unsigned int poly_idx; //!< The index of the polygon in \ref PolygonsPointIndex::polygons - - unsigned int point_idx; //!< The index of the point in the polygon in \ref PolygonsPointIndex::polygons + const Paths* polygons_; // (pointer to const polygons) + unsigned int poly_idx_; //!< The index of the polygon in \ref PolygonsPointIndex::polygons + unsigned int point_idx_; //!< The index of the point in the polygon in \ref PolygonsPointIndex::polygons /*! * Constructs an empty point index to no polygon. @@ -37,9 +35,9 @@ class PathsPointIndex * initialisation useful. */ PathsPointIndex() - : polygons(nullptr) - , poly_idx(0) - , point_idx(0) + : polygons_(nullptr) + , poly_idx_(0) + , point_idx_(0) { } @@ -50,9 +48,9 @@ class PathsPointIndex * \param point_idx The index of the vertex in the sub-polygon. */ PathsPointIndex(const Paths* polygons, unsigned int poly_idx, unsigned int point_idx) - : polygons(polygons) - , poly_idx(poly_idx) - , point_idx(point_idx) + : polygons_(polygons) + , poly_idx_(poly_idx) + , point_idx_(point_idx) { } @@ -63,11 +61,11 @@ class PathsPointIndex Point p() const { - if (!polygons) + if (! polygons_) { return Point(0, 0); } - return make_point((*polygons)[poly_idx][point_idx]); + return make_point((*polygons_)[poly_idx_][point_idx_]); } /*! @@ -75,10 +73,9 @@ class PathsPointIndex */ bool initialized() const { - return polygons; + return polygons_; } - /*! * Get the polygon to which this PolygonsPointIndex refers */ @@ -86,54 +83,61 @@ class PathsPointIndex /*! * Test whether two iterators refer to the same polygon in the same polygon list. - * + * * \param other The PolygonsPointIndex to test for equality * \return Wether the right argument refers to the same polygon in the same ListPolygon as the left argument. */ bool operator==(const PathsPointIndex& other) const { - return polygons == other.polygons && poly_idx == other.poly_idx && point_idx == other.point_idx; + return polygons_ == other.polygons_ && poly_idx_ == other.poly_idx_ && point_idx_ == other.point_idx_; } + bool operator!=(const PathsPointIndex& other) const { - return !(*this == other); + return ! (*this == other); } + bool operator<(const PathsPointIndex& other) const { return this->p() < other.p(); } + PathsPointIndex& operator=(const PathsPointIndex& other) { - polygons = other.polygons; - poly_idx = other.poly_idx; - point_idx = other.point_idx; + polygons_ = other.polygons_; + poly_idx_ = other.poly_idx_; + point_idx_ = other.point_idx_; return *this; } + //! move the iterator forward (and wrap around at the end) - PathsPointIndex& operator++() - { - point_idx = (point_idx + 1) % (*polygons)[poly_idx].size(); - return *this; + PathsPointIndex& operator++() + { + point_idx_ = (point_idx_ + 1) % (*polygons_)[poly_idx_].size(); + return *this; } + //! move the iterator backward (and wrap around at the beginning) - PathsPointIndex& operator--() - { - if (point_idx == 0) + PathsPointIndex& operator--() + { + if (point_idx_ == 0) { - point_idx = (*polygons)[poly_idx].size(); + point_idx_ = (*polygons_)[poly_idx_].size(); } - point_idx--; - return *this; + point_idx_--; + return *this; } + //! move the iterator forward (and wrap around at the end) - PathsPointIndex next() const + PathsPointIndex next() const { PathsPointIndex ret(*this); ++ret; return ret; } + //! move the iterator backward (and wrap around at the beginning) - PathsPointIndex prev() const + PathsPointIndex prev() const { PathsPointIndex ret(*this); --ret; @@ -151,16 +155,15 @@ struct PolygonsPointIndexSegmentLocator { std::pair operator()(const PolygonsPointIndex& val) const { - ConstPolygonRef poly = (*val.polygons)[val.poly_idx]; - Point start = poly[val.point_idx]; - unsigned int next_point_idx = (val.point_idx + 1) % poly.size(); + ConstPolygonRef poly = (*val.polygons_)[val.poly_idx_]; + Point start = poly[val.point_idx_]; + unsigned int next_point_idx = (val.point_idx_ + 1) % poly.size(); Point end = poly[next_point_idx]; return std::pair(start, end); } }; - /*! * Locator of a \ref PolygonsPointIndex */ @@ -175,14 +178,14 @@ struct PathsPointIndexLocator using PolygonsPointIndexLocator = PathsPointIndexLocator; -}//namespace cura +} // namespace cura namespace std { /*! * Hash function for \ref PolygonsPointIndex */ -template <> +template<> struct hash { size_t operator()(const cura::PolygonsPointIndex& lpi) const @@ -190,8 +193,7 @@ struct hash return std::hash()(lpi.p()); } }; -}//namespace std - +} // namespace std -#endif//UTILS_POLYGONS_POINT_INDEX_H +#endif // UTILS_POLYGONS_POINT_INDEX_H diff --git a/include/utils/PolylineStitcher.h b/include/utils/PolylineStitcher.h index cab9bf5eec..6a2063c1b9 100644 --- a/include/utils/PolylineStitcher.h +++ b/include/utils/PolylineStitcher.h @@ -128,17 +128,17 @@ class PolylineStitcher //Continue to see if closing segment is also the closest. } } - else if (processed[nearby.poly_idx]) + else if (processed[nearby.poly_idx_]) { // it was already moved to output return true; // keep looking for a connection } - bool nearby_would_be_reversed = nearby.point_idx != 0; + bool nearby_would_be_reversed = nearby.point_idx_ != 0; nearby_would_be_reversed = nearby_would_be_reversed != go_in_reverse_direction; // flip nearby_would_be_reversed when searching in the reverse direction if ( ! canReverse(nearby) && nearby_would_be_reversed) { // connecting the segment would reverse the polygon direction return true; // keep looking for a connection } - if ( ! canConnect(chain, (*nearby.polygons)[nearby.poly_idx])) + if ( ! canConnect(chain, (*nearby.polygons_)[nearby.poly_idx_])) { return true; // keep looking for a connection } @@ -167,31 +167,31 @@ class PolylineStitcher coord_t segment_dist = vSize(make_point(chain.back()) - closest.p()); assert(segment_dist <= max_stitch_distance + 10); const size_t old_size = chain.size(); - if (closest.point_idx == 0) + if (closest.point_idx_ == 0) { - auto start_pos = (*closest.polygons)[closest.poly_idx].begin(); + auto start_pos = (*closest.polygons_)[closest.poly_idx_].begin(); if (segment_dist < snap_distance) { ++start_pos; } - chain.insert(chain.end(), start_pos, (*closest.polygons)[closest.poly_idx].end()); + chain.insert(chain.end(), start_pos, (*closest.polygons_)[closest.poly_idx_].end()); } else { - auto start_pos = (*closest.polygons)[closest.poly_idx].rbegin(); + auto start_pos = (*closest.polygons_)[closest.poly_idx_].rbegin(); if (segment_dist < snap_distance) { ++start_pos; } - chain.insert(chain.end(), start_pos, (*closest.polygons)[closest.poly_idx].rend()); + chain.insert(chain.end(), start_pos, (*closest.polygons_)[closest.poly_idx_].rend()); } for(size_t i = old_size; i < chain.size(); ++i) //Update chain length. { chain_length += vSize(chain[i] - chain[i - 1]); } - should_close = should_close & !isOdd((*closest.polygons)[closest.poly_idx]); //If we connect an even to an odd line, we should no longer try to close it. - assert( ! processed[closest.poly_idx]); - processed[closest.poly_idx] = true; + should_close = should_close & !isOdd((*closest.polygons_)[closest.poly_idx_]); //If we connect an even to an odd line, we should no longer try to close it. + assert( ! processed[closest.poly_idx_]); + processed[closest.poly_idx_] = true; } if (closest_is_closing_polygon) diff --git a/src/ExtruderPlan.cpp b/src/ExtruderPlan.cpp index 1b59ff7af4..b492abc23e 100644 --- a/src/ExtruderPlan.cpp +++ b/src/ExtruderPlan.cpp @@ -13,37 +13,37 @@ ExtruderPlan::ExtruderPlan( const coord_t layer_thickness, const FanSpeedLayerTimeSettings& fan_speed_layer_time_settings, const RetractionConfig& retraction_config) - : extruder_nr(extruder) - , layer_nr(layer_nr) - , is_initial_layer(is_initial_layer) - , is_raft_layer(is_raft_layer) - , layer_thickness(layer_thickness) - , fan_speed_layer_time_settings(fan_speed_layer_time_settings) - , retraction_config(retraction_config) + : extruder_nr_(extruder) + , layer_nr_(layer_nr) + , is_initial_layer_(is_initial_layer) + , is_raft_layer_(is_raft_layer) + , layer_thickness_(layer_thickness) + , fan_speed_layer_time_settings_(fan_speed_layer_time_settings) + , retraction_config_(retraction_config) { } void ExtruderPlan::insertCommand(NozzleTempInsert&& insert) { - inserts.emplace_back(insert); + inserts_.emplace_back(insert); } void ExtruderPlan::handleInserts(const size_t path_idx, GCodeExport& gcode, const double cumulative_path_time) { - while (! inserts.empty() && path_idx >= inserts.front().path_idx && inserts.front().time_after_path_start < cumulative_path_time) + while (! inserts_.empty() && path_idx >= inserts_.front().path_idx && inserts_.front().time_after_path_start < cumulative_path_time) { // handle the Insert to be inserted before this path_idx (and all inserts not handled yet) - inserts.front().write(gcode); - inserts.pop_front(); + inserts_.front().write(gcode); + inserts_.pop_front(); } } void ExtruderPlan::handleAllRemainingInserts(GCodeExport& gcode) { - while (! inserts.empty()) + while (! inserts_.empty()) { // handle the Insert to be inserted before this path_idx (and all inserts not handled yet) - NozzleTempInsert& insert = inserts.front(); + NozzleTempInsert& insert = inserts_.front(); insert.write(gcode); - inserts.pop_front(); + inserts_.pop_front(); } } @@ -59,7 +59,7 @@ double ExtruderPlan::getFanSpeed() void ExtruderPlan::applyBackPressureCompensation(const Ratio back_pressure_compensation) { constexpr double epsilon_speed_factor = 0.001; // Don't put on actual 'limit double minimum', because we don't want printers to stall. - for (auto& path : paths) + for (auto& path : paths_) { const double nominal_width_for_path = static_cast(path.config.getLineWidth()); if (path.width_factor <= 0.0 || nominal_width_for_path <= 0.0 || path.config.isTravelPath() || path.config.isBridgePath()) @@ -70,4 +70,4 @@ void ExtruderPlan::applyBackPressureCompensation(const Ratio back_pressure_compe path.speed_back_pressure_factor = std::max(epsilon_speed_factor, 1.0 + (nominal_width_for_path / line_width_for_path - 1.0) * back_pressure_compensation); } } -} // namespace cura \ No newline at end of file +} // namespace cura diff --git a/src/LayerPlan.cpp b/src/LayerPlan.cpp index 36b6ef02d4..18655e5e72 100644 --- a/src/LayerPlan.cpp +++ b/src/LayerPlan.cpp @@ -45,7 +45,7 @@ GCodePath* LayerPlan::getLatestPathWithConfig( const bool spiralize, const Ratio speed_factor) { - std::vector& paths = extruder_plans.back().paths; + std::vector& paths = extruder_plans.back().paths_; if (paths.size() > 0 && paths.back().config == config && ! paths.back().done && paths.back().flow == flow && paths.back().width_factor == width_factor && paths.back().speed_factor == speed_factor && paths.back().z_offset == z_offset && paths.back().mesh == current_mesh) // spiralize can only change when a travel path is in between @@ -73,7 +73,7 @@ const Polygons* LayerPlan::getCombBoundaryInside() const void LayerPlan::forceNewPathStart() { - std::vector& paths = extruder_plans.back().paths; + std::vector& paths = extruder_plans.back().paths_; if (paths.size() > 0) paths[paths.size() - 1].done = true; } @@ -251,9 +251,9 @@ bool LayerPlan::setExtruder(const size_t extruder_nr) addTravel(end_pos); // + extruder_offset cause it } } - if (extruder_plans.back().paths.empty() && extruder_plans.back().inserts.empty()) + if (extruder_plans.back().paths_.empty() && extruder_plans.back().inserts_.empty()) { // first extruder plan in a layer might be empty, cause it is made with the last extruder planned in the previous layer - extruder_plans.back().extruder_nr = extruder_nr; + extruder_plans.back().extruder_nr_ = extruder_nr; } extruder_plans.emplace_back( extruder_nr, @@ -344,7 +344,7 @@ GCodePath& LayerPlan::addTravel(const Point& p, const bool force_retract, const const Settings& mesh_or_extruder_settings = current_mesh ? current_mesh->settings : extruder->settings; - const bool is_first_travel_of_extruder_after_switch = extruder_plans.back().paths.size() == 1 && (extruder_plans.size() > 1 || last_extruder_previous_layer != getExtruder()); + const bool is_first_travel_of_extruder_after_switch = extruder_plans.back().paths_.size() == 1 && (extruder_plans.size() > 1 || last_extruder_previous_layer != getExtruder()); bool bypass_combing = is_first_travel_of_extruder_after_switch && mesh_or_extruder_settings.get("retraction_hop_after_extruder_switch"); const bool is_first_travel_of_layer = ! static_cast(last_planned_position); @@ -1454,7 +1454,7 @@ void LayerPlan::spiralizeWallSlice( // normal slow down for quick layers mechanism can kick in and speed this layer up (because it is longer) but we prefer // the layer to be printed at a similar speed to the previous layer to avoid abrupt changes in extrusion rate so we slow it down - const FanSpeedLayerTimeSettings& layer_time_settings = extruder_plans.back().fan_speed_layer_time_settings; + const FanSpeedLayerTimeSettings& layer_time_settings = extruder_plans.back().fan_speed_layer_time_settings_; const double min_time = layer_time_settings.cool_min_layer_time; const double normal_layer_time = total_length / config.getSpeed(); @@ -1537,16 +1537,16 @@ void LayerPlan::spiralizeWallSlice( void ExtruderPlan::forceMinimalLayerTime(double minTime, double time_other_extr_plans) { - const double minimalSpeed = fan_speed_layer_time_settings.cool_min_speed; - const double travelTime = estimates.getTravelTime(); - const double extrudeTime = estimates.extrude_time; + const double minimalSpeed = fan_speed_layer_time_settings_.cool_min_speed; + const double travelTime = estimates_.getTravelTime(); + const double extrudeTime = estimates_.extrude_time; const double totalTime = travelTime + extrudeTime + time_other_extr_plans; constexpr double epsilon = 0.01; double total_extrude_time_at_minimum_speed = 0.0; double total_extrude_time_at_slowest_speed = 0.0; - for (GCodePath& path : paths) + for (GCodePath& path : paths_) { total_extrude_time_at_minimum_speed += path.estimates.extrude_time_at_minimum_speed; total_extrude_time_at_slowest_speed += path.estimates.extrude_time_at_slowest_path_speed; @@ -1567,13 +1567,13 @@ void ExtruderPlan::forceMinimalLayerTime(double minTime, double time_other_extr_ { // Even at cool min speed extrusion is not taken enough time. So speed is set to cool min speed. target_speed = minimalSpeed; - temperatureFactor = 1.0; + temperature_factor_ = 1.0; // Update stored naive time estimates - estimates.extrude_time = total_extrude_time_at_minimum_speed; + estimates_.extrude_time = total_extrude_time_at_minimum_speed; if (minTime - total_extrude_time_at_minimum_speed - travelTime > epsilon) { - extraTime = minTime - total_extrude_time_at_minimum_speed - travelTime; + extra_time_ = minTime - total_extrude_time_at_minimum_speed - travelTime; } } else if (minExtrudeTime >= total_extrude_time_at_slowest_speed && std::abs(total_extrude_time_at_minimum_speed - total_extrude_time_at_slowest_speed) >= epsilon) @@ -1582,28 +1582,28 @@ void ExtruderPlan::forceMinimalLayerTime(double minTime, double time_other_extr_ // Linear interpolate between total_extrude_time_at_slowest_speed and total_extrude_time_at_minimum_speed const double factor = (1 / total_extrude_time_at_minimum_speed - 1 / minExtrudeTime) / (1 / total_extrude_time_at_minimum_speed - 1 / total_extrude_time_at_slowest_speed); - target_speed = minimalSpeed * (1.0 - factor) + slowest_path_speed * factor; - temperatureFactor = 1.0 - factor; + target_speed = minimalSpeed * (1.0 - factor) + slowest_path_speed_ * factor; + temperature_factor_ = 1.0 - factor; // Update stored naive time estimates - estimates.extrude_time = minExtrudeTime; + estimates_.extrude_time = minExtrudeTime; } else { // Slowing down to the slowest_speed is sufficient to respect the minimum layer time. // Linear interpolate between extrudeTime and total_extrude_time_at_slowest_speed factor = (1 / total_extrude_time_at_slowest_speed - 1 / minExtrudeTime) / (1 / total_extrude_time_at_slowest_speed - 1 / extrudeTime); - slow_down_func = [&slowest_path_speed = slowest_path_speed, &factor](const GCodePath& path) + slow_down_func = [&slowest_path_speed = slowest_path_speed_, &factor](const GCodePath& path) { const double target_speed = slowest_path_speed * (1.0 - factor) + (path.config.getSpeed() * path.speed_factor) * factor; return std::min(target_speed / (path.config.getSpeed() * path.speed_factor), 1.0); }; // Update stored naive time estimates - estimates.extrude_time = minExtrudeTime; + estimates_.extrude_time = minExtrudeTime; } - for (GCodePath& path : paths) + for (GCodePath& path : paths_) { if (path.isTravelPath()) { @@ -1618,7 +1618,7 @@ void ExtruderPlan::forceMinimalLayerTime(double minTime, double time_other_extr_ double ExtruderPlan::getRetractTime(const GCodePath& path) { - return retraction_config.distance / (path.retract ? retraction_config.speed : retraction_config.primeSpeed); + return retraction_config_.distance / (path.retract ? retraction_config_.speed : retraction_config_.primeSpeed); } std::pair ExtruderPlan::getPointToPointTime(const Point& p0, const Point& p1, const GCodePath& path) @@ -1631,10 +1631,10 @@ TimeMaterialEstimates ExtruderPlan::computeNaiveTimeEstimates(Point starting_pos { Point p0 = starting_position; - const double min_path_speed = fan_speed_layer_time_settings.cool_min_speed; - slowest_path_speed = std::accumulate( - paths.begin(), - paths.end(), + const double min_path_speed = fan_speed_layer_time_settings_.cool_min_speed; + slowest_path_speed_ = std::accumulate( + paths_.begin(), + paths_.end(), std::numeric_limits::max(), [](double value, const GCodePath& path) { @@ -1642,7 +1642,7 @@ TimeMaterialEstimates ExtruderPlan::computeNaiveTimeEstimates(Point starting_pos }); bool was_retracted = false; // wrong assumption; won't matter that much. (TODO) - for (GCodePath& path : paths) + for (GCodePath& path : paths_) { bool is_extrusion_path = false; double* path_time_estimate; @@ -1671,11 +1671,11 @@ TimeMaterialEstimates ExtruderPlan::computeNaiveTimeEstimates(Point starting_pos double retract_unretract_time; if (path.retract) { - retract_unretract_time = retraction_config.distance / retraction_config.speed; + retract_unretract_time = retraction_config_.distance / retraction_config_.speed; } else { - retract_unretract_time = retraction_config.distance / retraction_config.primeSpeed; + retract_unretract_time = retraction_config_.distance / retraction_config_.primeSpeed; } path.estimates.retracted_travel_time += 0.5 * retract_unretract_time; path.estimates.unretracted_travel_time += 0.5 * retract_unretract_time; @@ -1689,17 +1689,17 @@ TimeMaterialEstimates ExtruderPlan::computeNaiveTimeEstimates(Point starting_pos if (length > 0) { path.estimates.extrude_time_at_minimum_speed += length / min_path_speed; - path.estimates.extrude_time_at_slowest_path_speed += length / slowest_path_speed; + path.estimates.extrude_time_at_slowest_path_speed += length / slowest_path_speed_; } - material_estimate += length * INT2MM(layer_thickness) * INT2MM(path.config.getLineWidth()); + material_estimate += length * INT2MM(layer_thickness_) * INT2MM(path.config.getLineWidth()); } double thisTime = length / (path.config.getSpeed() * path.speed_factor); *path_time_estimate += thisTime; p0 = p1; } - estimates += path.estimates; + estimates_ += path.estimates; } - return estimates; + return estimates_; } void ExtruderPlan::processFanSpeedForMinimalLayerTime(Point starting_position, Duration minTime, double time_other_extr_plans) @@ -1719,23 +1719,23 @@ void ExtruderPlan::processFanSpeedForMinimalLayerTime(Point starting_position, D */ // interpolate fan speed (for cool_fan_full_layer and for cool_min_layer_time_fan_speed_max) - double totalLayerTime = estimates.getTotalTime() + time_other_extr_plans; + double totalLayerTime = estimates_.getTotalTime() + time_other_extr_plans; if (totalLayerTime < minTime) { - fan_speed = fan_speed_layer_time_settings.cool_fan_speed_max; + fan_speed = fan_speed_layer_time_settings_.cool_fan_speed_max; } - else if (minTime >= fan_speed_layer_time_settings.cool_min_layer_time_fan_speed_max) + else if (minTime >= fan_speed_layer_time_settings_.cool_min_layer_time_fan_speed_max) { // ignore gradual increase of fan speed return; } - else if (totalLayerTime < fan_speed_layer_time_settings.cool_min_layer_time_fan_speed_max) + else if (totalLayerTime < fan_speed_layer_time_settings_.cool_min_layer_time_fan_speed_max) { // when forceMinimalLayerTime didn't change the extrusionSpeedFactor, we adjust the fan speed - double fan_speed_diff = fan_speed_layer_time_settings.cool_fan_speed_max - fan_speed; - double layer_time_diff = fan_speed_layer_time_settings.cool_min_layer_time_fan_speed_max - minTime; + double fan_speed_diff = fan_speed_layer_time_settings_.cool_fan_speed_max - fan_speed; + double layer_time_diff = fan_speed_layer_time_settings_.cool_min_layer_time_fan_speed_max - minTime; double fraction_of_slope = (totalLayerTime - minTime) / layer_time_diff; - fan_speed = fan_speed_layer_time_settings.cool_fan_speed_max - fan_speed_diff * fraction_of_slope; + fan_speed = fan_speed_layer_time_settings_.cool_fan_speed_max - fan_speed_diff * fraction_of_slope; } } @@ -1757,15 +1757,15 @@ void ExtruderPlan::processFanSpeedForFirstLayers() layer nr > */ - fan_speed = fan_speed_layer_time_settings.cool_fan_speed_min; - if (layer_nr < fan_speed_layer_time_settings.cool_fan_full_layer - && fan_speed_layer_time_settings.cool_fan_full_layer > 0 // don't apply initial layer fan speed speedup if disabled. - && ! is_raft_layer // don't apply initial layer fan speed speedup to raft, but to model layers + fan_speed = fan_speed_layer_time_settings_.cool_fan_speed_min; + if (layer_nr_ < fan_speed_layer_time_settings_.cool_fan_full_layer + && fan_speed_layer_time_settings_.cool_fan_full_layer > 0 // don't apply initial layer fan speed speedup if disabled. + && ! is_raft_layer_ // don't apply initial layer fan speed speedup to raft, but to model layers ) { // Slow down the fan on the layers below the [cool_fan_full_layer], where layer 0 is speed 0. - fan_speed = fan_speed_layer_time_settings.cool_fan_speed_0 - + (fan_speed - fan_speed_layer_time_settings.cool_fan_speed_0) * std::max(LayerIndex(0), layer_nr) / fan_speed_layer_time_settings.cool_fan_full_layer; + fan_speed = fan_speed_layer_time_settings_.cool_fan_speed_0 + + (fan_speed - fan_speed_layer_time_settings_.cool_fan_speed_0) * std::max(LayerIndex(0), layer_nr_) / fan_speed_layer_time_settings_.cool_fan_full_layer; } } @@ -1776,9 +1776,9 @@ void LayerPlan::processFanSpeedAndMinimalLayerTime(Point starting_position) extruder_plans, [](const ExtruderPlan& a, const ExtruderPlan& b) { - return a.extruder_nr < b.extruder_nr; + return a.extruder_nr_ < b.extruder_nr_; }) - ->extruder_nr; + ->extruder_nr_; Point starting_position_last_extruder; unsigned int last_extruder_idx; double other_extr_plan_time = 0.0; @@ -1791,23 +1791,23 @@ void LayerPlan::processFanSpeedAndMinimalLayerTime(Point starting_position) // Precalculate the time estimates. Don't call this function twice, since it is works cumulative. extruder_plan.computeNaiveTimeEstimates(starting_position); - if (extruder_plan.extruder_nr == last_extruder_nr) + if (extruder_plan.extruder_nr_ == last_extruder_nr) { starting_position_last_extruder = starting_position; last_extruder_idx = extr_plan_idx; } else { - other_extr_plan_time += extruder_plan.estimates.getTotalTime(); + other_extr_plan_time += extruder_plan.estimates_.getTotalTime(); } - maximum_cool_min_layer_time = std::max(maximum_cool_min_layer_time, extruder_plan.fan_speed_layer_time_settings.cool_min_layer_time); + maximum_cool_min_layer_time = std::max(maximum_cool_min_layer_time, extruder_plan.fan_speed_layer_time_settings_.cool_min_layer_time); // Modify fan speeds for the first layer(s) extruder_plan.processFanSpeedForFirstLayers(); - if (! extruder_plan.paths.empty() && ! extruder_plan.paths.back().points.empty()) + if (! extruder_plan.paths_.empty() && ! extruder_plan.paths_.back().points.empty()) { - starting_position = extruder_plan.paths.back().points.back(); + starting_position = extruder_plan.paths_.back().points.back(); } } } @@ -1857,13 +1857,13 @@ void LayerPlan::writeGCode(GCodeExport& gcode) ExtruderPlan& extruder_plan = extruder_plans[extruder_plan_idx]; const RetractionAndWipeConfig* retraction_config - = current_mesh ? ¤t_mesh->retraction_wipe_config : &storage.retraction_wipe_config_per_extruder[extruder_plan.extruder_nr]; + = current_mesh ? ¤t_mesh->retraction_wipe_config : &storage.retraction_wipe_config_per_extruder[extruder_plan.extruder_nr_]; coord_t z_hop_height = retraction_config->retraction_config.zHop; - if (extruder_nr != extruder_plan.extruder_nr) + if (extruder_nr != extruder_plan.extruder_nr_) { int prev_extruder = extruder_nr; - extruder_nr = extruder_plan.extruder_nr; + extruder_nr = extruder_plan.extruder_nr_; gcode.ResetLastEValueAfterWipe(prev_extruder); @@ -1880,13 +1880,13 @@ void LayerPlan::writeGCode(GCodeExport& gcode) { // require printing temperature to be met constexpr bool wait = true; - gcode.writeTemperatureCommand(extruder_nr, extruder_plan.required_start_temperature, wait); + gcode.writeTemperatureCommand(extruder_nr, extruder_plan.required_start_temperature_, wait); } - if (extruder_plan.prev_extruder_standby_temp) + if (extruder_plan.prev_extruder_standby_temp_) { // turn off previous extruder constexpr bool wait = false; - Temperature prev_extruder_temp = *extruder_plan.prev_extruder_standby_temp; + Temperature prev_extruder_temp = *extruder_plan.prev_extruder_standby_temp_; const LayerIndex prev_layer_nr = (extruder_plan_idx == 0) ? layer_nr - 1 : layer_nr; if (prev_layer_nr == storage.max_print_height_per_extruder[prev_extruder]) { @@ -1897,7 +1897,7 @@ void LayerPlan::writeGCode(GCodeExport& gcode) { // require printing temperature to be met constexpr bool wait = true; - gcode.writeTemperatureCommand(extruder_nr, extruder_plan.required_start_temperature, wait); + gcode.writeTemperatureCommand(extruder_nr, extruder_plan.required_start_temperature_, wait); } const double extra_prime_amount = retraction_config->retraction_config.distance ? retraction_config->switch_extruder_extra_prime_amount : 0; @@ -1905,7 +1905,7 @@ void LayerPlan::writeGCode(GCodeExport& gcode) } else if (extruder_plan_idx == 0) { - const WipeScriptConfig& wipe_config = storage.retraction_wipe_config_per_extruder[extruder_plan.extruder_nr].wipe_config; + const WipeScriptConfig& wipe_config = storage.retraction_wipe_config_per_extruder[extruder_plan.extruder_nr_].wipe_config; if (wipe_config.clean_between_layers && gcode.getExtrudedVolumeAfterLastWipe(extruder_nr) > wipe_config.max_extrusion_mm3) { gcode.insertWipeScript(wipe_config); @@ -1921,9 +1921,9 @@ void LayerPlan::writeGCode(GCodeExport& gcode) } } gcode.writeFanCommand(extruder_plan.getFanSpeed()); - std::vector& paths = extruder_plan.paths; + std::vector& paths = extruder_plan.paths_; - extruder_plan.inserts.sort(); + extruder_plan.inserts_.sort(); const ExtruderTrain& extruder = Application::getInstance().current_slice->scene.extruders[extruder_nr]; @@ -2168,7 +2168,7 @@ void LayerPlan::writeGCode(GCodeExport& gcode) } } // paths for this extruder /\ . - if (extruder.settings.get("cool_lift_head") && extruder_plan.extraTime > 0.0) + if (extruder.settings.get("cool_lift_head") && extruder_plan.extra_time_ > 0.0) { gcode.writeComment("Small layer, adding delay"); const RetractionAndWipeConfig& retraction_config @@ -2179,13 +2179,13 @@ void LayerPlan::writeGCode(GCodeExport& gcode) // or do it anyway when we switch extruder in-place gcode.writeZhopStart(MM2INT(3.0)); } - gcode.writeDelay(extruder_plan.extraTime); + gcode.writeDelay(extruder_plan.extra_time_); } extruder_plan.handleAllRemainingInserts(gcode); scripta::log( "extruder_plan_2", - extruder_plan.paths, + extruder_plan.paths_, SectionType::NA, layer_nr, scripta::CellVDI{ "flow", &GCodePath::flow }, @@ -2217,7 +2217,7 @@ void LayerPlan::overrideFanSpeeds(double speed) bool LayerPlan::makeRetractSwitchRetract(unsigned int extruder_plan_idx, unsigned int path_idx) { - std::vector& paths = extruder_plans[extruder_plan_idx].paths; + std::vector& paths = extruder_plans[extruder_plan_idx].paths_; for (unsigned int path_idx2 = path_idx + 1; path_idx2 < paths.size(); path_idx2++) { if (paths[path_idx2].getExtrusionMM3perMM() > 0) @@ -2231,7 +2231,7 @@ bool LayerPlan::makeRetractSwitchRetract(unsigned int extruder_plan_idx, unsigne return false; // TODO: check first extruder of the next layer! (generally only on the last layer of the second extruder) } - if (extruder_plans[extruder_plan_idx + 1].extruder_nr != extruder_plans[extruder_plan_idx].extruder_nr) + if (extruder_plans[extruder_plan_idx + 1].extruder_nr_ != extruder_plans[extruder_plan_idx].extruder_nr_) { return true; } @@ -2249,13 +2249,13 @@ bool LayerPlan::writePathWithCoasting( const std::function insertTempOnTime) { ExtruderPlan& extruder_plan = extruder_plans[extruder_plan_idx]; - const ExtruderTrain& extruder = Application::getInstance().current_slice->scene.extruders[extruder_plan.extruder_nr]; + const ExtruderTrain& extruder = Application::getInstance().current_slice->scene.extruders[extruder_plan.extruder_nr_]; const double coasting_volume = extruder.settings.get("coasting_volume"); if (coasting_volume <= 0) { return false; } - const std::vector& paths = extruder_plan.paths; + const std::vector& paths = extruder_plan.paths_; const GCodePath& path = paths[path_idx]; if (path_idx + 1 >= paths.size() || (path.isTravelPath() || ! paths[path_idx + 1].config.isTravelPath()) || path.points.size() < 2) { @@ -2377,7 +2377,7 @@ void LayerPlan::applyModifyPlugin() { scripta::log( "extruder_plan_0", - extruder_plan.paths, + extruder_plan.paths_, SectionType::NA, layer_nr, scripta::CellVDI{ "flow", &GCodePath::flow }, @@ -2393,11 +2393,11 @@ void LayerPlan::applyModifyPlugin() scripta::CellVDI{ "is_travel_path", &GCodePath::isTravelPath }, scripta::CellVDI{ "extrusion_mm3_per_mm", &GCodePath::getExtrusionMM3perMM }); - extruder_plan.paths = slots::instance().modify(extruder_plan.paths, extruder_plan.extruder_nr, layer_nr); + extruder_plan.paths_ = slots::instance().modify(extruder_plan.paths_, extruder_plan.extruder_nr_, layer_nr); scripta::log( "extruder_plan_1", - extruder_plan.paths, + extruder_plan.paths_, SectionType::NA, layer_nr, scripta::CellVDI{ "flow", &GCodePath::flow }, @@ -2420,7 +2420,7 @@ void LayerPlan::applyBackPressureCompensation() for (auto& extruder_plan : extruder_plans) { const Ratio back_pressure_compensation - = Application::getInstance().current_slice->scene.extruders[extruder_plan.extruder_nr].settings.get("speed_equalize_flow_width_factor"); + = Application::getInstance().current_slice->scene.extruders[extruder_plan.extruder_nr_].settings.get("speed_equalize_flow_width_factor"); if (back_pressure_compensation != 0.0) { extruder_plan.applyBackPressureCompensation(back_pressure_compensation); @@ -2455,7 +2455,7 @@ void LayerPlan::setSkirtBrimIsPlanned(unsigned int extruder_nr) size_t LayerPlan::getExtruder() const { - return extruder_plans.back().extruder_nr; + return extruder_plans.back().extruder_nr_; } void LayerPlan::setBridgeWallMask(const Polygons& polys) diff --git a/src/LayerPlanBuffer.cpp b/src/LayerPlanBuffer.cpp index d5a033a136..f3185deeeb 100644 --- a/src/LayerPlanBuffer.cpp +++ b/src/LayerPlanBuffer.cpp @@ -89,14 +89,14 @@ void LayerPlanBuffer::addConnectingTravelMove(LayerPlan* prev_layer, const Layer Point first_location_new_layer = new_layer_destination_state->first; - assert(newest_layer->extruder_plans.front().paths[0].points.size() == 1); - assert(newest_layer->extruder_plans.front().paths[0].points[0] == first_location_new_layer); + assert(newest_layer->extruder_plans.front().paths_[0].points.size() == 1); + assert(newest_layer->extruder_plans.front().paths_[0].points[0] == first_location_new_layer); // if the last planned position in the previous layer isn't the same as the first location of the new layer, travel to the new location if (! prev_layer->last_planned_position || *prev_layer->last_planned_position != first_location_new_layer) { const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; - const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[prev_layer->extruder_plans.back().extruder_nr].settings; + const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[prev_layer->extruder_plans.back().extruder_nr_].settings; prev_layer->setIsInside(new_layer_destination_state->second); const bool force_retract = extruder_settings.get("retract_at_layer_change") || (mesh_group_settings.get("travel_retract_before_outer_wall") @@ -140,9 +140,9 @@ void LayerPlanBuffer::processFanSpeedLayerTime() void LayerPlanBuffer::insertPreheatCommand(ExtruderPlan& extruder_plan_before, const Duration time_before_extruder_plan_end, const size_t extruder_nr, const Temperature temp) { Duration acc_time = 0.0; - for (unsigned int path_idx = extruder_plan_before.paths.size() - 1; int(path_idx) != -1; path_idx--) + for (unsigned int path_idx = extruder_plan_before.paths_.size() - 1; int(path_idx) != -1; path_idx--) { - GCodePath& path = extruder_plan_before.paths[path_idx]; + GCodePath& path = extruder_plan_before.paths_[path_idx]; acc_time += path.estimates.getTotalTime(); if (acc_time >= time_before_extruder_plan_end) { @@ -166,20 +166,20 @@ void LayerPlanBuffer::insertPreheatCommand(ExtruderPlan& extruder_plan_before, c Preheat::WarmUpResult LayerPlanBuffer::computeStandbyTempPlan(std::vector& extruder_plans, unsigned int extruder_plan_idx) { ExtruderPlan& extruder_plan = *extruder_plans[extruder_plan_idx]; - size_t extruder = extruder_plan.extruder_nr; + size_t extruder = extruder_plan.extruder_nr_; Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder].settings; - double initial_print_temp = extruder_plan.required_start_temperature; + double initial_print_temp = extruder_plan.required_start_temperature_; Duration in_between_time = 0.0_s; // the duration during which the extruder isn't used for (size_t extruder_plan_before_idx = extruder_plan_idx - 1; int(extruder_plan_before_idx) >= 0; extruder_plan_before_idx--) { // find a previous extruder plan where the same extruder is used to see what time this extruder wasn't used ExtruderPlan& extruder_plan_before = *extruder_plans[extruder_plan_before_idx]; - if (extruder_plan_before.extruder_nr == extruder) + if (extruder_plan_before.extruder_nr_ == extruder) { Temperature temp_before = extruder_settings.get("material_final_print_temperature"); if (temp_before == 0) { - temp_before = extruder_plan_before.extrusion_temperature.value_or(initial_print_temp); + temp_before = extruder_plan_before.extrusion_temperature_.value_or(initial_print_temp); } constexpr bool during_printing = false; Preheat::WarmUpResult warm_up = preheat_config.getWarmUpPointAfterCoolDown( @@ -192,7 +192,7 @@ Preheat::WarmUpResult LayerPlanBuffer::computeStandbyTempPlan(std::vector& extruder_plans, unsigned int extruder_plan_idx, double standby_temp) { ExtruderPlan& extruder_plan = *extruder_plans[extruder_plan_idx]; - size_t extruder = extruder_plan.extruder_nr; + size_t extruder = extruder_plan.extruder_nr_; for (size_t extruder_plan_before_idx = extruder_plan_idx - 2; int(extruder_plan_before_idx) >= 0; extruder_plan_before_idx--) { - if (extruder_plans[extruder_plan_before_idx]->extruder_nr == extruder) + if (extruder_plans[extruder_plan_before_idx]->extruder_nr_ == extruder) { - extruder_plans[extruder_plan_before_idx + 1]->prev_extruder_standby_temp = standby_temp; + extruder_plans[extruder_plan_before_idx + 1]->prev_extruder_standby_temp_ = standby_temp; return; } } @@ -247,13 +247,13 @@ void LayerPlanBuffer::handleStandbyTemp(std::vector& extruder_pla void LayerPlanBuffer::insertPreheatCommand_multiExtrusion(std::vector& extruder_plans, unsigned int extruder_plan_idx) { ExtruderPlan& extruder_plan = *extruder_plans[extruder_plan_idx]; - const size_t extruder = extruder_plan.extruder_nr; + const size_t extruder = extruder_plan.extruder_nr_; const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder].settings; if (! extruder_settings.get("machine_nozzle_temp_enabled")) { return; } - double initial_print_temp = extruder_plan.required_start_temperature; + double initial_print_temp = extruder_plan.required_start_temperature_; Preheat::WarmUpResult heating_time_and_from_temp = computeStandbyTempPlan(extruder_plans, extruder_plan_idx); @@ -272,9 +272,9 @@ void LayerPlanBuffer::insertPreheatCommand_multiExtrusion(std::vector= 0; extruder_plan_before_idx--) { ExtruderPlan& extruder_plan_before = *extruder_plans[extruder_plan_before_idx]; - assert(extruder_plan_before.extruder_nr != extruder); + assert(extruder_plan_before.extruder_nr_ != extruder); - double time_here = extruder_plan_before.estimates.getTotalTime(); + double time_here = extruder_plan_before.estimates_.getTotalTime(); if (time_here >= time_before_extruder_plan_to_insert) { insertPreheatCommand(extruder_plan_before, time_before_extruder_plan_to_insert, extruder, initial_print_temp); @@ -293,27 +293,27 @@ void LayerPlanBuffer::insertPreheatCommand_multiExtrusion(std::vector& extruder_plans, unsigned int extruder_plan_idx) { ExtruderPlan& extruder_plan = *extruder_plans[extruder_plan_idx]; - const size_t extruder = extruder_plan.extruder_nr; + const size_t extruder = extruder_plan.extruder_nr_; ExtruderPlan* prev_extruder_plan = extruder_plans[extruder_plan_idx - 1]; - const size_t prev_extruder = prev_extruder_plan->extruder_nr; + const size_t prev_extruder = prev_extruder_plan->extruder_nr_; if (prev_extruder != extruder) { // set previous extruder to standby temperature const Settings& previous_extruder_settings = Application::getInstance().current_slice->scene.extruders[prev_extruder].settings; - extruder_plan.prev_extruder_standby_temp = previous_extruder_settings.get("material_standby_temperature"); + extruder_plan.prev_extruder_standby_temp_ = previous_extruder_settings.get("material_standby_temperature"); } if (prev_extruder == extruder) { - insertPreheatCommand_singleExtrusion(*prev_extruder_plan, extruder, extruder_plan.required_start_temperature); - prev_extruder_plan->extrusion_temperature_command = --prev_extruder_plan->inserts.end(); + insertPreheatCommand_singleExtrusion(*prev_extruder_plan, extruder, extruder_plan.required_start_temperature_); + prev_extruder_plan->extrusion_temperature_command_ = --prev_extruder_plan->inserts_.end(); } else if (Application::getInstance().current_slice->scene.extruders[extruder].settings.get("machine_extruders_share_heater")) { // extruders share a heater so command the previous extruder to change to the temperature required for this extruder - insertPreheatCommand_singleExtrusion(*prev_extruder_plan, prev_extruder, extruder_plan.required_start_temperature); + insertPreheatCommand_singleExtrusion(*prev_extruder_plan, prev_extruder, extruder_plan.required_start_temperature_); } else { @@ -325,14 +325,14 @@ void LayerPlanBuffer::insertTempCommands(std::vector& extruder_pl void LayerPlanBuffer::insertPrintTempCommand(ExtruderPlan& extruder_plan) { - if (! extruder_plan.extrusion_temperature) + if (! extruder_plan.extrusion_temperature_) { spdlog::warn("Empty extruder plan detected! Discarding extrusion temperature command."); return; } - const double print_temp = *extruder_plan.extrusion_temperature; + const double print_temp = *extruder_plan.extrusion_temperature_; - const unsigned int extruder = extruder_plan.extruder_nr; + const unsigned int extruder = extruder_plan.extruder_nr_; const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder].settings; if (! extruder_settings.get("machine_nozzle_temp_enabled")) { @@ -343,9 +343,9 @@ void LayerPlanBuffer::insertPrintTempCommand(ExtruderPlan& extruder_plan) if (extruder_settings.get("material_initial_print_temperature") != 0) { // handle heating from initial_print_temperature to printing_tempreature unsigned int path_idx; - for (path_idx = 0; path_idx < extruder_plan.paths.size(); path_idx++) + for (path_idx = 0; path_idx < extruder_plan.paths_.size(); path_idx++) { - GCodePath& path = extruder_plan.paths[path_idx]; + GCodePath& path = extruder_plan.paths_[path_idx]; heated_pre_travel_time += path.estimates.getTotalTime(); if (! path.isTravelPath()) { @@ -355,13 +355,13 @@ void LayerPlanBuffer::insertPrintTempCommand(ExtruderPlan& extruder_plan) bool wait = false; extruder_plan.insertCommand(NozzleTempInsert{ .path_idx = path_idx, .extruder = extruder, .temperature = print_temp, .wait = wait }); } - extruder_plan.heated_pre_travel_time = heated_pre_travel_time; + extruder_plan.heated_pre_travel_time_ = heated_pre_travel_time; } void LayerPlanBuffer::insertFinalPrintTempCommand(std::vector& extruder_plans, unsigned int last_extruder_plan_idx) { ExtruderPlan& last_extruder_plan = *extruder_plans[last_extruder_plan_idx]; - const size_t extruder = last_extruder_plan.extruder_nr; + const size_t extruder = last_extruder_plan.extruder_nr_; const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder].settings; if (! extruder_settings.get("machine_nozzle_temp_enabled")) { @@ -377,9 +377,9 @@ void LayerPlanBuffer::insertFinalPrintTempCommand(std::vector& ex double heated_post_travel_time = 0; // The time after the last extrude move toward the end of the extruder plan during which the nozzle is stable at the final print temperature { // compute heated_post_travel_time unsigned int path_idx; - for (path_idx = last_extruder_plan.paths.size() - 1; int(path_idx) >= 0; path_idx--) + for (path_idx = last_extruder_plan.paths_.size() - 1; int(path_idx) >= 0; path_idx--) { - GCodePath& path = last_extruder_plan.paths[path_idx]; + GCodePath& path = last_extruder_plan.paths_[path_idx]; if (! path.isTravelPath()) { break; @@ -399,18 +399,18 @@ void LayerPlanBuffer::insertFinalPrintTempCommand(std::vector& ex for (unsigned int prev_extruder_plan_idx = last_extruder_plan_idx; (int)prev_extruder_plan_idx >= 0; prev_extruder_plan_idx--) { ExtruderPlan& prev_extruder_plan = *extruder_plans[prev_extruder_plan_idx]; - if (prev_extruder_plan.extruder_nr != extruder) + if (prev_extruder_plan.extruder_nr_ != extruder) { break; } - double prev_extruder_plan_time = prev_extruder_plan.estimates.getTotalTime(); + double prev_extruder_plan_time = prev_extruder_plan.estimates_.getTotalTime(); time_window += prev_extruder_plan_time; - heated_pre_travel_time = prev_extruder_plan.heated_pre_travel_time; + heated_pre_travel_time = prev_extruder_plan.heated_pre_travel_time_; - if (prev_extruder_plan.estimates.getTotalUnretractedTime() > 0) + if (prev_extruder_plan.estimates_.getTotalUnretractedTime() > 0) { // handle temp statistics - weighted_average_extrusion_temp += prev_extruder_plan.extrusion_temperature.value_or(prev_extruder_plan.required_start_temperature) * prev_extruder_plan_time; - initial_print_temp = prev_extruder_plan.required_start_temperature; + weighted_average_extrusion_temp += prev_extruder_plan.extrusion_temperature_.value_or(prev_extruder_plan.required_start_temperature_) * prev_extruder_plan_time; + initial_print_temp = prev_extruder_plan.required_start_temperature_; } } if (time_window <= 0.0) // There was a move in this plan but it was length 0. @@ -429,7 +429,7 @@ void LayerPlanBuffer::insertFinalPrintTempCommand(std::vector& ex return; } - assert((time_window >= -0.001 || last_extruder_plan.estimates.material == 0) && "Time window should always be positive if we actually extrude"); + assert((time_window >= -0.001 || last_extruder_plan.estimates_.material == 0) && "Time window should always be positive if we actually extrude"); // ,layer change . // : ,precool command ,layer change . @@ -455,11 +455,11 @@ void LayerPlanBuffer::insertFinalPrintTempCommand(std::vector& ex for (unsigned int precool_extruder_plan_idx = last_extruder_plan_idx; (int)precool_extruder_plan_idx >= 0; precool_extruder_plan_idx--) { precool_extruder_plan = extruder_plans[precool_extruder_plan_idx]; - if (precool_extruder_plan->extrusion_temperature_command) + if (precool_extruder_plan->extrusion_temperature_command_) { // the precool command ends up before the command to go to the print temperature of the next extruder plan, so remove that print temp command - precool_extruder_plan->inserts.erase(*precool_extruder_plan->extrusion_temperature_command); + precool_extruder_plan->inserts_.erase(*precool_extruder_plan->extrusion_temperature_command_); } - double time_here = precool_extruder_plan->estimates.getTotalTime(); + double time_here = precool_extruder_plan->estimates_.getTotalTime(); if (cool_down_time < time_here) { break; @@ -474,9 +474,9 @@ void LayerPlanBuffer::insertFinalPrintTempCommand(std::vector& ex { // insert temp command in precool_extruder_plan double extrusion_time_seen = 0; unsigned int path_idx; - for (path_idx = precool_extruder_plan->paths.size() - 1; int(path_idx) >= 0; path_idx--) + for (path_idx = precool_extruder_plan->paths_.size() - 1; int(path_idx) >= 0; path_idx--) { - GCodePath& path = precool_extruder_plan->paths[path_idx]; + GCodePath& path = precool_extruder_plan->paths_[path_idx]; extrusion_time_seen += path.estimates.getTotalTime(); if (extrusion_time_seen >= cool_down_time) { @@ -492,7 +492,7 @@ void LayerPlanBuffer::insertFinalPrintTempCommand(std::vector& ex void LayerPlanBuffer::insertTempCommands() { - if (buffer.back()->extruder_plans.size() == 0 || (buffer.back()->extruder_plans.size() == 1 && buffer.back()->extruder_plans[0].paths.size() == 0)) + if (buffer.back()->extruder_plans.size() == 0 || (buffer.back()->extruder_plans.size() == 1 && buffer.back()->extruder_plans[0].paths_.size() == 0)) { // disregard empty layer buffer.pop_back(); return; @@ -515,49 +515,49 @@ void LayerPlanBuffer::insertTempCommands() { const size_t overall_extruder_plan_idx = extruder_plans.size() - layer_plan.extruder_plans.size() + extruder_plan_idx; ExtruderPlan& extruder_plan = layer_plan.extruder_plans[extruder_plan_idx]; - size_t extruder = extruder_plan.extruder_nr; + size_t extruder = extruder_plan.extruder_nr_; const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder].settings; - Duration time = extruder_plan.estimates.getTotalUnretractedTime(); + Duration time = extruder_plan.estimates_.getTotalUnretractedTime(); Ratio avg_flow; if (time > 0.0) { - avg_flow = extruder_plan.estimates.material / time; + avg_flow = extruder_plan.estimates_.material / time; } else { - assert(extruder_plan.estimates.material == 0.0 && "No extrusion time should mean no material usage!"); + assert(extruder_plan.estimates_.material == 0.0 && "No extrusion time should mean no material usage!"); avg_flow = 0.0; } - Temperature print_temp = preheat_config.getTemp(extruder, avg_flow, extruder_plan.is_initial_layer); + Temperature print_temp = preheat_config.getTemp(extruder, avg_flow, extruder_plan.is_initial_layer_); Temperature initial_print_temp = extruder_settings.get("material_initial_print_temperature"); - if (extruder_plan.temperatureFactor > 0) // force lower printing temperatures due to minimum layer time + if (extruder_plan.temperature_factor_ > 0) // force lower printing temperatures due to minimum layer time { - print_temp = print_temp * (1 - extruder_plan.temperatureFactor) + extruder_plan.temperatureFactor * extruder_settings.get("cool_min_temperature"); + print_temp = print_temp * (1 - extruder_plan.temperature_factor_) + extruder_plan.temperature_factor_ * extruder_settings.get("cool_min_temperature"); initial_print_temp = std::min(initial_print_temp, print_temp); } if (initial_print_temp == 0.0 // user doesn't want to use initial print temp feature || extruder_settings.get("machine_extruders_share_heater") // ignore initial print temps when extruders share a heater || ! extruder_used_in_meshgroup[extruder] // prime blob uses print temp rather than initial print temp - || (overall_extruder_plan_idx > 0 && extruder_plans[overall_extruder_plan_idx - 1]->extruder_nr == extruder // prev plan has same extruder .. - && extruder_plans[overall_extruder_plan_idx - 1]->estimates.getTotalUnretractedTime() > 0.0) // and prev extruder plan already heated to printing temperature + || (overall_extruder_plan_idx > 0 && extruder_plans[overall_extruder_plan_idx - 1]->extruder_nr_ == extruder // prev plan has same extruder .. + && extruder_plans[overall_extruder_plan_idx - 1]->estimates_.getTotalUnretractedTime() > 0.0) // and prev extruder plan already heated to printing temperature ) { - extruder_plan.required_start_temperature = print_temp; + extruder_plan.required_start_temperature_ = print_temp; extruder_used_in_meshgroup[extruder] = true; } else { - extruder_plan.required_start_temperature = initial_print_temp; - extruder_plan.extrusion_temperature = print_temp; + extruder_plan.required_start_temperature_ = initial_print_temp; + extruder_plan.extrusion_temperature_ = print_temp; } - assert(extruder_plan.required_start_temperature != -1 && "extruder_plan.required_start_temperature should now have been set"); + assert(extruder_plan.required_start_temperature_ != -1 && "extruder_plan.required_start_temperature should now have been set"); if (buffer.size() == 1 && extruder_plan_idx == 0) { // the very first extruder plan of the current meshgroup - size_t extruder = extruder_plan.extruder_nr; + size_t extruder = extruder_plan.extruder_nr_; for (size_t extruder_idx = 0; extruder_idx < scene.extruders.size(); extruder_idx++) { // set temperature of the first nozzle, turn other nozzles down const Settings& other_extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder_idx].settings; @@ -568,7 +568,7 @@ void LayerPlanBuffer::insertTempCommands() // see FffGcodeWriter::processStartingCode if (extruder_idx == extruder) { - gcode.setInitialTemp(extruder_idx, extruder_plan.extrusion_temperature.value_or(extruder_plan.required_start_temperature)); + gcode.setInitialTemp(extruder_idx, extruder_plan.extrusion_temperature_.value_or(extruder_plan.required_start_temperature_)); } else { @@ -579,7 +579,7 @@ void LayerPlanBuffer::insertTempCommands() { if (extruder_idx != extruder) { // TODO: do we need to do this? - extruder_plan.prev_extruder_standby_temp = other_extruder_settings.get("material_standby_temperature"); + extruder_plan.prev_extruder_standby_temp_ = other_extruder_settings.get("material_standby_temperature"); } } } diff --git a/src/pathPlanning/Comb.cpp b/src/pathPlanning/Comb.cpp index d98ec095b6..96f961e4c0 100644 --- a/src/pathPlanning/Comb.cpp +++ b/src/pathPlanning/Comb.cpp @@ -466,7 +466,7 @@ void Comb::Crossing::findCrossingInOrMid(const PartsView& partsView_inside, cons std::function line_processor = [close_to, _dest_point, &boundary_crossing_point, &dist2_score, &dest_part_poly_indices](const PolygonsPointIndex& boundary_segment) { - if (dest_part_poly_indices.find(boundary_segment.poly_idx) == dest_part_poly_indices.end()) + if (dest_part_poly_indices.find(boundary_segment.poly_idx_) == dest_part_poly_indices.end()) { // we're not looking at a polygon from the dest_part return true; // a.k.a. continue; } @@ -475,7 +475,7 @@ void Comb::Crossing::findCrossingInOrMid(const PartsView& partsView_inside, cons if (dist2_score_here < dist2_score) { dist2_score = dist2_score_here; - boundary_crossing_point = ClosestPolygonPoint(closest_here, boundary_segment.point_idx, boundary_segment.getPolygon(), boundary_segment.poly_idx); + boundary_crossing_point = ClosestPolygonPoint(closest_here, boundary_segment.point_idx_, boundary_segment.getPolygon(), boundary_segment.poly_idx_); } return true; }; diff --git a/src/utils/PolygonsPointIndex.cpp b/src/utils/PolygonsPointIndex.cpp index cdd64f7d5e..9cc2d3cf18 100644 --- a/src/utils/PolygonsPointIndex.cpp +++ b/src/utils/PolygonsPointIndex.cpp @@ -9,7 +9,7 @@ namespace cura template<> ConstPolygonRef PathsPointIndex::getPolygon() const { - return (*polygons)[poly_idx]; + return (*polygons_)[poly_idx_]; } } diff --git a/src/utils/PolylineStitcher.cpp b/src/utils/PolylineStitcher.cpp index 8d101e99da..5bec622839 100644 --- a/src/utils/PolylineStitcher.cpp +++ b/src/utils/PolylineStitcher.cpp @@ -12,7 +12,7 @@ namespace cura template<> bool PolylineStitcher::canReverse(const PathsPointIndex& ppi) { - if ((*ppi.polygons)[ppi.poly_idx].is_odd) + if ((*ppi.polygons_)[ppi.poly_idx_].is_odd) { return true; } diff --git a/src/utils/polygonUtils.cpp b/src/utils/polygonUtils.cpp index 40a1a29d58..574f9061b2 100644 --- a/src/utils/polygonUtils.cpp +++ b/src/utils/polygonUtils.cpp @@ -31,17 +31,17 @@ const std::function PolygonUtils::no_penalty_function = [](Point) int64_t PolygonUtils::segmentLength(PolygonsPointIndex start, PolygonsPointIndex end) { - assert(start.poly_idx == end.poly_idx); + assert(start.poly_idx_ == end.poly_idx_); int64_t segment_length = 0; Point prev_vert = start.p(); - ConstPolygonRef poly = (*start.polygons)[start.poly_idx]; + ConstPolygonRef poly = (*start.polygons_)[start.poly_idx_]; for (unsigned int point_idx = 1; point_idx <= poly.size(); point_idx++) { - unsigned int vert_idx = (start.point_idx + point_idx) % poly.size(); + unsigned int vert_idx = (start.point_idx_ + point_idx) % poly.size(); Point vert = poly[vert_idx]; segment_length += vSize(vert - prev_vert); - if (vert_idx == end.point_idx) + if (vert_idx == end.point_idx_) { // break at the end of the loop, so that [end] and [start] may be the same return segment_length; } @@ -53,14 +53,14 @@ int64_t PolygonUtils::segmentLength(PolygonsPointIndex start, PolygonsPointIndex void PolygonUtils::spreadDots(PolygonsPointIndex start, PolygonsPointIndex end, unsigned int n_dots, std::vector& result) { - assert(start.poly_idx == end.poly_idx); + assert(start.poly_idx_ == end.poly_idx_); int64_t segment_length = segmentLength(start, end); - ConstPolygonRef poly = (*start.polygons)[start.poly_idx]; + ConstPolygonRef poly = (*start.polygons_)[start.poly_idx_]; unsigned int n_dots_in_between = n_dots; if (start == end) { - result.emplace_back(start.p(), start.point_idx, poly); + result.emplace_back(start.p(), start.point_idx_, poly); n_dots_in_between--; // generate one less below, because we already pushed a point to the result } @@ -78,7 +78,7 @@ void PolygonUtils::spreadDots(PolygonsPointIndex start, PolygonsPointIndex end, for (; dist_past_vert_to_insert_point < p0p1_length && n_points_generated < n_dots_in_between; dist_past_vert_to_insert_point += wipe_point_dist) { - result.emplace_back(p0 + normal(p0p1, dist_past_vert_to_insert_point), vert.point_idx, poly); + result.emplace_back(p0 + normal(p0p1, dist_past_vert_to_insert_point), vert.point_idx_, poly); n_points_generated++; } dist_past_vert_to_insert_point -= p0p1_length; @@ -1013,9 +1013,9 @@ std::optional PolygonsPointIndex best_point_poly_idx(nullptr, NO_INDEX, NO_INDEX); for (PolygonsPointIndex& point_poly_index : near_lines) { - ConstPolygonRef poly = polygons[point_poly_index.poly_idx]; - const Point& p1 = poly[point_poly_index.point_idx]; - const Point& p2 = poly[(point_poly_index.point_idx + 1) % poly.size()]; + ConstPolygonRef poly = polygons[point_poly_index.poly_idx_]; + const Point& p1 = poly[point_poly_index.point_idx_]; + const Point& p2 = poly[(point_poly_index.point_idx_ + 1) % poly.size()]; Point closest_here = LinearAlg2D::getClosestOnLineSegment(from, p1, p2); int64_t dist2_score = vSize2(from - closest_here) + penalty_function(closest_here); @@ -1026,13 +1026,13 @@ std::optional best_point_poly_idx = point_poly_index; } } - if (best_point_poly_idx.poly_idx == NO_INDEX) + if (best_point_poly_idx.poly_idx_ == NO_INDEX) { return std::optional(); } else { - return std::optional(std::in_place, best, best_point_poly_idx.point_idx, polygons[best_point_poly_idx.poly_idx], best_point_poly_idx.poly_idx); + return std::optional(std::in_place, best, best_point_poly_idx.point_idx_, polygons[best_point_poly_idx.poly_idx_], best_point_poly_idx.poly_idx_); } } @@ -1497,14 +1497,14 @@ void PolygonUtils::fixSelfIntersections(const coord_t epsilon, Polygons& thiss) Point& pt = thiss[poly_idx][point_idx]; for (const auto& line : query_grid->getNearby(pt, epsilon * 2)) { - const size_t line_next_idx = (line.point_idx + 1) % thiss[line.poly_idx].size(); - if (poly_idx == line.poly_idx && (point_idx == line.point_idx || point_idx == line_next_idx)) + const size_t line_next_idx = (line.point_idx_ + 1) % thiss[line.poly_idx_].size(); + if (poly_idx == line.poly_idx_ && (point_idx == line.point_idx_ || point_idx == line_next_idx)) { continue; } - const Point& a = thiss[line.poly_idx][line.point_idx]; - const Point& b = thiss[line.poly_idx][line_next_idx]; + const Point& a = thiss[line.poly_idx_][line.point_idx_]; + const Point& b = thiss[line.poly_idx_][line_next_idx]; if (half_epsilon_sqrd >= vSize2(pt - LinearAlg2D::getClosestOnLineSegment(pt, a, b))) { From 14ace62866b5b710b550a0d7a7957578d1392a1a Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Tue, 21 Nov 2023 09:04:18 +0100 Subject: [PATCH 08/48] Fixed variable shadowing warnings --- include/mesh.h | 28 +++--- src/ConicalOverhang.cpp | 6 +- src/FffPolygonGenerator.cpp | 10 +- src/InterlockingGenerator.cpp | 12 +-- src/MeshGroup.cpp | 20 ++-- src/Mold.cpp | 18 ++-- src/Scene.cpp | 4 +- .../ArcusCommunicationPrivate.cpp | 8 +- src/communication/CommandLine.cpp | 2 +- src/mesh.cpp | 92 +++++++++---------- src/multiVolumes.cpp | 36 ++++---- src/settings/AdaptiveLayerHeights.cpp | 16 ++-- src/sliceDataStorage.cpp | 4 +- src/slicer.cpp | 80 ++++++++-------- tests/arcus/ArcusCommunicationPrivateTest.cpp | 16 ++-- 15 files changed, 176 insertions(+), 176 deletions(-) diff --git a/include/mesh.h b/include/mesh.h index 37fe3f3e10..8a48c41e28 100644 --- a/include/mesh.h +++ b/include/mesh.h @@ -19,10 +19,10 @@ Keeps track of which faces connect to it. class MeshVertex { public: - Point3 p; //!< location of the vertex - std::vector connected_faces; //!< list of the indices of connected faces + Point3 p_; //!< location of the vertex + std::vector connected_faces_; //!< list of the indices of connected faces - MeshVertex(Point3 p) : p(p) {connected_faces.reserve(8);} //!< doesn't set connected_faces + MeshVertex(Point3 p) : p_(p) {connected_faces_.reserve(8);} //!< doesn't set connected_faces }; /*! A MeshFace is a 3 dimensional model triangle with 3 points. These points are already converted to integers @@ -49,8 +49,8 @@ In such a case the face_index stored in connected_face_index is the one connecte class MeshFace { public: - int vertex_index[3] = {-1}; //!< counter-clockwise ordering - int connected_face_index[3]; //!< same ordering as vertex_index (connected_face 0 is connected via vertex 0 and 1, etc.) + int vertex_index_[3] = {-1}; //!< counter-clockwise ordering + int connected_face_index_[3]; //!< same ordering as vertex_index (connected_face 0 is connected via vertex 0 and 1, etc.) }; @@ -62,13 +62,13 @@ See MeshFace for the specifics of how/when faces are connected. class Mesh { //! The vertex_hash_map stores a index reference of each vertex for the hash of that location. Allows for quick retrieval of points with the same location. - std::unordered_map > vertex_hash_map; - AABB3D aabb; + std::unordered_map > vertex_hash_map_; + AABB3D aabb_; public: - std::vector vertices;//!< list of all vertices in the mesh - std::vector faces; //!< list of all faces in the mesh - Settings settings; - std::string mesh_name; + std::vector vertices_;//!< list of all vertices in the mesh + std::vector faces_; //!< list of all faces in the mesh + Settings settings_; + std::string mesh_name_; Mesh(Settings& parent); Mesh(); @@ -89,9 +89,9 @@ class Mesh void translate(Point3 offset) { if (offset == Point3(0,0,0)) { return; } - for(MeshVertex& v : vertices) - v.p += offset; - aabb.translate(offset); + for(MeshVertex& v : vertices_) + v.p_ += offset; + aabb_.translate(offset); } /*! diff --git a/src/ConicalOverhang.cpp b/src/ConicalOverhang.cpp index 03b3b80222..f0afc15af9 100644 --- a/src/ConicalOverhang.cpp +++ b/src/ConicalOverhang.cpp @@ -15,10 +15,10 @@ namespace cura void ConicalOverhang::apply(Slicer* slicer, const Mesh& mesh) { - const AngleRadians angle = mesh.settings.get("conical_overhang_angle"); - const double maxHoleArea = mesh.settings.get("conical_overhang_hole_size"); + const AngleRadians angle = mesh.settings_.get("conical_overhang_angle"); + const double maxHoleArea = mesh.settings_.get("conical_overhang_hole_size"); const double tan_angle = tan(angle); // the XY-component of the angle - const coord_t layer_thickness = mesh.settings.get("layer_height"); + const coord_t layer_thickness = mesh.settings_.get("layer_height"); coord_t max_dist_from_lower_layer = tan_angle * layer_thickness; // max dist which can be bridged for (LayerIndex layer_nr = slicer->layers.size() - 2; static_cast(layer_nr) >= 0; layer_nr--) diff --git a/src/FffPolygonGenerator.cpp b/src/FffPolygonGenerator.cpp index 0ac8e5ce1b..4e59f05ab8 100644 --- a/src/FffPolygonGenerator.cpp +++ b/src/FffPolygonGenerator.cpp @@ -146,7 +146,7 @@ bool FffPolygonGenerator::sliceModel(MeshGroup* meshgroup, TimeKeeper& timeKeepe continue; } const coord_t mesh_height = mesh.max().z_; - switch (mesh.settings.get("slicing_tolerance")) + switch (mesh.settings_.get("slicing_tolerance")) { case SlicingTolerance::MIDDLE: if (storage.model_max.z_ < initial_layer_thickness) @@ -232,7 +232,7 @@ bool FffPolygonGenerator::sliceModel(MeshGroup* meshgroup, TimeKeeper& timeKeepe for (unsigned int mesh_idx = 0; mesh_idx < slicerList.size(); mesh_idx++) { Mesh& mesh = scene.current_mesh_group->meshes[mesh_idx]; - if (mesh.settings.get("conical_overhang_enabled") && ! mesh.settings.get("anti_overhang_mesh")) + if (mesh.settings_.get("conical_overhang_enabled") && ! mesh.settings_.get("anti_overhang_mesh")) { ConicalOverhang::apply(slicerList[mesh_idx], mesh); } @@ -260,7 +260,7 @@ bool FffPolygonGenerator::sliceModel(MeshGroup* meshgroup, TimeKeeper& timeKeepe { Mesh& mesh = scene.current_mesh_group->meshes[meshIdx]; Slicer* slicer = slicerList[meshIdx]; - if (! mesh.settings.get("anti_overhang_mesh") && ! mesh.settings.get("infill_mesh") && ! mesh.settings.get("cutting_mesh")) + if (! mesh.settings_.get("anti_overhang_mesh") && ! mesh.settings_.get("infill_mesh") && ! mesh.settings_.get("cutting_mesh")) { storage.print_layer_count = std::max(storage.print_layer_count, slicer->layers.size()); } @@ -279,7 +279,7 @@ bool FffPolygonGenerator::sliceModel(MeshGroup* meshgroup, TimeKeeper& timeKeepe SliceMeshStorage& meshStorage = *storage.meshes.back(); // only create layer parts for normal meshes - const bool is_support_modifier = AreaSupport::handleSupportModifierMesh(storage, mesh.settings, slicer); + const bool is_support_modifier = AreaSupport::handleSupportModifierMesh(storage, mesh.settings_, slicer); if (! is_support_modifier) { createLayerParts(meshStorage, slicer); @@ -288,7 +288,7 @@ bool FffPolygonGenerator::sliceModel(MeshGroup* meshgroup, TimeKeeper& timeKeepe // Do not add and process support _modifier_ meshes further, and ONLY skip support _modifiers_. They have been // processed in AreaSupport::handleSupportModifierMesh(), but other helper meshes such as infill meshes are // processed in a later stage, except for support mesh itself, so an exception is made for that. - if (is_support_modifier && ! mesh.settings.get("support_mesh")) + if (is_support_modifier && ! mesh.settings_.get("support_mesh")) { storage.meshes.pop_back(); continue; diff --git a/src/InterlockingGenerator.cpp b/src/InterlockingGenerator.cpp index 3392f4ee31..86bb724ceb 100644 --- a/src/InterlockingGenerator.cpp +++ b/src/InterlockingGenerator.cpp @@ -33,11 +33,11 @@ void InterlockingGenerator::generateInterlockingStructure(std::vector& for (size_t mesh_a_idx = 0; mesh_a_idx < volumes.size(); mesh_a_idx++) { Slicer& mesh_a = *volumes[mesh_a_idx]; - size_t extruder_nr_a = mesh_a.mesh->settings.get("wall_0_extruder_nr").extruder_nr; + size_t extruder_nr_a = mesh_a.mesh->settings_.get("wall_0_extruder_nr").extruder_nr; for (size_t mesh_b_idx = mesh_a_idx + 1; mesh_b_idx < volumes.size(); mesh_b_idx++) { Slicer& mesh_b = *volumes[mesh_b_idx]; - size_t extruder_nr_b = mesh_b.mesh->settings.get("wall_0_extruder_nr").extruder_nr; + size_t extruder_nr_b = mesh_b.mesh->settings_.get("wall_0_extruder_nr").extruder_nr; if (! mesh_a.mesh->canInterlock() || ! mesh_b.mesh->canInterlock()) { @@ -50,8 +50,8 @@ void InterlockingGenerator::generateInterlockingStructure(std::vector& continue; } - coord_t beam_width_a = mesh_a.mesh->settings.get("interlocking_beam_width"); - coord_t beam_width_b = mesh_b.mesh->settings.get("interlocking_beam_width"); + coord_t beam_width_a = mesh_a.mesh->settings_.get("interlocking_beam_width"); + coord_t beam_width_b = mesh_b.mesh->settings_.get("interlocking_beam_width"); // TODO: why are these two kernels different kernel types?! const DilationKernel interface_dilation(GridPoint3(interface_depth, interface_depth, interface_depth), DilationKernel::Type::PRISM); @@ -70,7 +70,7 @@ void InterlockingGenerator::generateInterlockingStructure(std::vector& std::pair InterlockingGenerator::growBorderAreasPerpendicular(const Polygons& a, const Polygons& b, const coord_t& detect) const { - const coord_t min_line = std::min(mesh_a.mesh->settings.get("min_wall_line_width"), mesh_b.mesh->settings.get("min_wall_line_width")); + const coord_t min_line = std::min(mesh_a.mesh->settings_.get("min_wall_line_width"), mesh_b.mesh->settings_.get("min_wall_line_width")); const Polygons total_shrunk = a.offset(min_line).unionPolygons(b.offset(min_line)).offset(2 * -min_line); @@ -101,7 +101,7 @@ void InterlockingGenerator::handleThinAreas(const std::unordered_set const coord_t max_beam_width = std::max(beam_width_a, beam_width_b); const coord_t detect = (max_beam_width * number_of_beams_detect) + rounding_errors; const coord_t expand = (max_beam_width * number_of_beams_expand) + rounding_errors; - const coord_t close_gaps = std::min(mesh_a.mesh->settings.get("line_width"), mesh_b.mesh->settings.get("line_width")) / 4; + const coord_t close_gaps = std::min(mesh_a.mesh->settings_.get("line_width"), mesh_b.mesh->settings_.get("line_width")) / 4; // Make an inclusionary polygon, to only actually handle thin areas near actual microstructures (so not in skin for example). std::vector near_interlock_per_layer; diff --git a/src/MeshGroup.cpp b/src/MeshGroup.cpp index e14fcc3600..b70e04c45e 100644 --- a/src/MeshGroup.cpp +++ b/src/MeshGroup.cpp @@ -49,8 +49,8 @@ Point3 MeshGroup::min() const Point3 ret(std::numeric_limits::max(), std::numeric_limits::max(), std::numeric_limits::max()); for (const Mesh& mesh : meshes) { - if (mesh.settings.get("infill_mesh") || mesh.settings.get("cutting_mesh") - || mesh.settings.get("anti_overhang_mesh")) // Don't count pieces that are not printed. + if (mesh.settings_.get("infill_mesh") || mesh.settings_.get("cutting_mesh") + || mesh.settings_.get("anti_overhang_mesh")) // Don't count pieces that are not printed. { continue; } @@ -71,8 +71,8 @@ Point3 MeshGroup::max() const Point3 ret(std::numeric_limits::min(), std::numeric_limits::min(), std::numeric_limits::min()); for (const Mesh& mesh : meshes) { - if (mesh.settings.get("infill_mesh") || mesh.settings.get("cutting_mesh") - || mesh.settings.get("anti_overhang_mesh")) // Don't count pieces that are not printed. + if (mesh.settings_.get("infill_mesh") || mesh.settings_.get("cutting_mesh") + || mesh.settings_.get("anti_overhang_mesh")) // Don't count pieces that are not printed. { continue; } @@ -105,8 +105,8 @@ void MeshGroup::finalize() // If a mesh position was given, put the mesh at this position in 3D space. for (Mesh& mesh : meshes) { - Point3 mesh_offset(mesh.settings.get("mesh_position_x"), mesh.settings.get("mesh_position_y"), mesh.settings.get("mesh_position_z")); - if (mesh.settings.get("center_object")) + Point3 mesh_offset(mesh.settings_.get("mesh_position_x"), mesh.settings_.get("mesh_position_y"), mesh.settings_.get("mesh_position_z")); + if (mesh.settings_.get("center_object")) { Point3 object_min = mesh.min(); Point3 object_max = mesh.max(); @@ -201,8 +201,8 @@ bool loadMeshSTL_binary(Mesh* mesh, const char* filename, const FMatrix4x3& matr // For each face read: // float(x,y,z) = normal, float(X,Y,Z)*3 = vertexes, uint16_t = flags // Every Face is 50 Bytes: Normal(3*float), Vertices(9*float), 2 Bytes Spacer - mesh->faces.reserve(face_count); - mesh->vertices.reserve(face_count); + mesh->faces_.reserve(face_count); + mesh->vertices_.reserve(face_count); for (unsigned int i = 0; i < face_count; i++) { if (fread(buffer, 50, 1, f) != 1) @@ -231,7 +231,7 @@ bool loadMeshSTL(Mesh* mesh, const char* filename, const FMatrix4x3& matrix) } // assign filename to mesh_name - mesh->mesh_name = filename; + mesh->mesh_name_ = filename; // Skip any whitespace at the beginning of the file. unsigned long long num_whitespace = 0; // Number of whitespace characters. @@ -269,7 +269,7 @@ bool loadMeshSTL(Mesh* mesh, const char* filename, const FMatrix4x3& matrix) // This logic is used to handle the case where the file starts with // "solid" but is a binary file. - if (mesh->faces.size() < 1) + if (mesh->faces_.size() < 1) { mesh->clear(); return loadMeshSTL_binary(mesh, filename, matrix); diff --git a/src/Mold.cpp b/src/Mold.cpp index ccf5ec0cd6..fe5bebe849 100644 --- a/src/Mold.cpp +++ b/src/Mold.cpp @@ -23,10 +23,10 @@ void Mold::process(std::vector& slicer_list) for (unsigned int mesh_idx = 0; mesh_idx < slicer_list.size(); mesh_idx++) { Mesh& mesh = scene.current_mesh_group->meshes[mesh_idx]; - if (mesh.settings.get("mold_enabled")) + if (mesh.settings_.get("mold_enabled")) { has_any_mold = true; - mesh.expandXY(mesh.settings.get("mold_width")); + mesh.expandXY(mesh.settings_.get("mold_width")); } } if (! has_any_mold) @@ -57,19 +57,19 @@ void Mold::process(std::vector& slicer_list) { const Mesh& mesh = scene.current_mesh_group->meshes[mesh_idx]; Slicer& slicer = *slicer_list[mesh_idx]; - if (! mesh.settings.get("mold_enabled") || layer_nr >= static_cast(slicer.layers.size())) + if (! mesh.settings_.get("mold_enabled") || layer_nr >= static_cast(slicer.layers.size())) { continue; } - coord_t width = mesh.settings.get("mold_width"); - coord_t open_polyline_width = mesh.settings.get("wall_line_width_0"); + coord_t width = mesh.settings_.get("mold_width"); + coord_t open_polyline_width = mesh.settings_.get("wall_line_width_0"); if (layer_nr == 0) { - const ExtruderTrain& train_wall_0 = mesh.settings.get("wall_0_extruder_nr"); + const ExtruderTrain& train_wall_0 = mesh.settings_.get("wall_0_extruder_nr"); open_polyline_width *= train_wall_0.settings.get("initial_layer_line_width_factor"); } - const AngleDegrees angle = mesh.settings.get("mold_angle"); - const coord_t roof_height = mesh.settings.get("mold_roof_height"); + const AngleDegrees angle = mesh.settings_.get("mold_angle"); + const coord_t roof_height = mesh.settings_.get("mold_roof_height"); const coord_t inset = tan(angle / 180 * std::numbers::pi) * layer_height; const size_t roof_layer_count = roof_height / layer_height; @@ -108,7 +108,7 @@ void Mold::process(std::vector& slicer_list) for (unsigned int mesh_idx = 0; mesh_idx < slicer_list.size(); mesh_idx++) { const Mesh& mesh = scene.current_mesh_group->meshes[mesh_idx]; - if (! mesh.settings.get("mold_enabled")) + if (! mesh.settings_.get("mold_enabled")) { continue; // only cut original models out of all molds } diff --git a/src/Scene.cpp b/src/Scene.cpp index ac50185b6d..1e8416181e 100644 --- a/src/Scene.cpp +++ b/src/Scene.cpp @@ -54,7 +54,7 @@ const std::string Scene::getAllSettingsString() const for (size_t mesh_index = 0; mesh_index < mesh_group.meshes.size(); mesh_index++) { const Mesh& mesh = mesh_group.meshes[mesh_index]; - output << " -e" << mesh.settings.get("extruder_nr") << " -l \"" << mesh_index << "\"" << mesh.settings.getAllSettingsString(); + output << " -e" << mesh.settings_.get("extruder_nr") << " -l \"" << mesh_index << "\"" << mesh.settings_.getAllSettingsString(); } } output << "\n"; @@ -72,7 +72,7 @@ void Scene::processMeshGroup(MeshGroup& mesh_group) bool empty = true; for (Mesh& mesh : mesh_group.meshes) { - if (! mesh.settings.get("infill_mesh") && ! mesh.settings.get("anti_overhang_mesh")) + if (! mesh.settings_.get("infill_mesh") && ! mesh.settings_.get("anti_overhang_mesh")) { empty = false; break; diff --git a/src/communication/ArcusCommunicationPrivate.cpp b/src/communication/ArcusCommunicationPrivate.cpp index 90b23c1e64..3d33f43e74 100644 --- a/src/communication/ArcusCommunicationPrivate.cpp +++ b/src/communication/ArcusCommunicationPrivate.cpp @@ -117,10 +117,10 @@ void ArcusCommunication::Private::readMeshGroupMessage(const proto::ObjectList& // Load the settings for the mesh. for (const cura::proto::Setting& setting : object.settings()) { - mesh.settings.add(setting.name(), setting.value()); + mesh.settings_.add(setting.name(), setting.value()); } - ExtruderTrain& extruder = mesh.settings.get("extruder_nr"); // Set the parent setting to the correct extruder. - mesh.settings.setParent(&extruder.settings); + ExtruderTrain& extruder = mesh.settings_.get("extruder_nr"); // Set the parent setting to the correct extruder. + mesh.settings_.setParent(&extruder.settings); for (size_t face = 0; face < face_count; face++) { @@ -134,7 +134,7 @@ void ArcusCommunication::Private::readMeshGroupMessage(const proto::ObjectList& mesh.addFace(verts[0], verts[1], verts[2]); } - mesh.mesh_name = object.name(); + mesh.mesh_name_ = object.name(); mesh.finish(); } object_count++; diff --git a/src/communication/CommandLine.cpp b/src/communication/CommandLine.cpp index 7b7c0f7163..12b338305f 100644 --- a/src/communication/CommandLine.cpp +++ b/src/communication/CommandLine.cpp @@ -266,7 +266,7 @@ void CommandLine::sliceNext() } else { - last_settings = &slice.scene.mesh_groups[mesh_group_index].meshes.back().settings; + last_settings = &slice.scene.mesh_groups[mesh_group_index].meshes.back().settings_; } break; } diff --git a/src/mesh.cpp b/src/mesh.cpp index eba67cf02c..5e2ca66224 100644 --- a/src/mesh.cpp +++ b/src/mesh.cpp @@ -22,14 +22,14 @@ static inline uint32_t pointHash(const Point3& p) } Mesh::Mesh(Settings& parent) - : settings(parent) + : settings_(parent) , has_disconnected_faces(false) , has_overlapping_faces(false) { } Mesh::Mesh() - : settings() + : settings_() , has_disconnected_faces(false) , has_overlapping_faces(false) { @@ -43,98 +43,98 @@ void Mesh::addFace(Point3& v0, Point3& v1, Point3& v2) if (vi0 == vi1 || vi1 == vi2 || vi0 == vi2) return; // the face has two vertices which get assigned the same location. Don't add the face. - int idx = faces.size(); // index of face to be added - faces.emplace_back(); - MeshFace& face = faces[idx]; - face.vertex_index[0] = vi0; - face.vertex_index[1] = vi1; - face.vertex_index[2] = vi2; - vertices[face.vertex_index[0]].connected_faces.push_back(idx); - vertices[face.vertex_index[1]].connected_faces.push_back(idx); - vertices[face.vertex_index[2]].connected_faces.push_back(idx); + int idx = faces_.size(); // index of face to be added + faces_.emplace_back(); + MeshFace& face = faces_[idx]; + face.vertex_index_[0] = vi0; + face.vertex_index_[1] = vi1; + face.vertex_index_[2] = vi2; + vertices_[face.vertex_index_[0]].connected_faces_.push_back(idx); + vertices_[face.vertex_index_[1]].connected_faces_.push_back(idx); + vertices_[face.vertex_index_[2]].connected_faces_.push_back(idx); } void Mesh::clear() { - faces.clear(); - vertices.clear(); - vertex_hash_map.clear(); + faces_.clear(); + vertices_.clear(); + vertex_hash_map_.clear(); } void Mesh::finish() { // Finish up the mesh, clear the vertex_hash_map, as it's no longer needed from this point on and uses quite a bit of memory. - vertex_hash_map.clear(); + vertex_hash_map_.clear(); // For each face, store which other face is connected with it. - for (unsigned int i = 0; i < faces.size(); i++) + for (unsigned int i = 0; i < faces_.size(); i++) { - MeshFace& face = faces[i]; + MeshFace& face = faces_[i]; // faces are connected via the outside - face.connected_face_index[0] = getFaceIdxWithPoints(face.vertex_index[0], face.vertex_index[1], i, face.vertex_index[2]); - face.connected_face_index[1] = getFaceIdxWithPoints(face.vertex_index[1], face.vertex_index[2], i, face.vertex_index[0]); - face.connected_face_index[2] = getFaceIdxWithPoints(face.vertex_index[2], face.vertex_index[0], i, face.vertex_index[1]); + face.connected_face_index_[0] = getFaceIdxWithPoints(face.vertex_index_[0], face.vertex_index_[1], i, face.vertex_index_[2]); + face.connected_face_index_[1] = getFaceIdxWithPoints(face.vertex_index_[1], face.vertex_index_[2], i, face.vertex_index_[0]); + face.connected_face_index_[2] = getFaceIdxWithPoints(face.vertex_index_[2], face.vertex_index_[0], i, face.vertex_index_[1]); } } Point3 Mesh::min() const { - return aabb.min; + return aabb_.min; } Point3 Mesh::max() const { - return aabb.max; + return aabb_.max; } AABB3D Mesh::getAABB() const { - return aabb; + return aabb_; } void Mesh::expandXY(int64_t offset) { if (offset) { - aabb.expandXY(offset); + aabb_.expandXY(offset); } } void Mesh::transform(const FMatrix4x3& transformation) { - for (MeshVertex& v : vertices) + for (MeshVertex& v : vertices_) { - v.p = transformation.apply(v.p); + v.p_ = transformation.apply(v.p_); } - aabb.min = transformation.apply(aabb.min); - aabb.max = transformation.apply(aabb.max); + aabb_.min = transformation.apply(aabb_.min); + aabb_.max = transformation.apply(aabb_.max); } bool Mesh::isPrinted() const { - return ! settings.get("infill_mesh") && ! settings.get("cutting_mesh") && ! settings.get("anti_overhang_mesh"); + return ! settings_.get("infill_mesh") && ! settings_.get("cutting_mesh") && ! settings_.get("anti_overhang_mesh"); } bool Mesh::canInterlock() const { - return ! settings.get("infill_mesh") && ! settings.get("anti_overhang_mesh"); + return ! settings_.get("infill_mesh") && ! settings_.get("anti_overhang_mesh"); } int Mesh::findIndexOfVertex(const Point3& v) { uint32_t hash = pointHash(v); - for (unsigned int idx = 0; idx < vertex_hash_map[hash].size(); idx++) + for (unsigned int idx = 0; idx < vertex_hash_map_[hash].size(); idx++) { - if ((vertices[vertex_hash_map[hash][idx]].p - v).testLength(vertex_meld_distance)) + if ((vertices_[vertex_hash_map_[hash][idx]].p_ - v).testLength(vertex_meld_distance)) { - return vertex_hash_map[hash][idx]; + return vertex_hash_map_[hash][idx]; } } - vertex_hash_map[hash].push_back(vertices.size()); - vertices.emplace_back(v); + vertex_hash_map_[hash].push_back(vertices_.size()); + vertices_.emplace_back(v); - aabb.include(v); + aabb_.include(v); - return vertices.size() - 1; + return vertices_.size() - 1; } /*! @@ -164,15 +164,15 @@ See mesh->settings.get("infill_mesh_order"); + return volume_1->mesh->settings_.get("infill_mesh_order") < volume_2->mesh->settings_.get("infill_mesh_order"); }); for (unsigned int volume_1_idx = 1; volume_1_idx < volumes.size(); volume_1_idx++) { Slicer& volume_1 = *ranked_volumes[volume_1_idx]; - if (volume_1.mesh->settings.get("infill_mesh") || volume_1.mesh->settings.get("anti_overhang_mesh") || volume_1.mesh->settings.get("support_mesh") - || volume_1.mesh->settings.get("magic_mesh_surface_mode") == ESurfaceMode::SURFACE) + if (volume_1.mesh->settings_.get("infill_mesh") || volume_1.mesh->settings_.get("anti_overhang_mesh") || volume_1.mesh->settings_.get("support_mesh") + || volume_1.mesh->settings_.get("magic_mesh_surface_mode") == ESurfaceMode::SURFACE) { continue; } for (unsigned int volume_2_idx = 0; volume_2_idx < volume_1_idx; volume_2_idx++) { Slicer& volume_2 = *ranked_volumes[volume_2_idx]; - if (volume_2.mesh->settings.get("infill_mesh") || volume_2.mesh->settings.get("anti_overhang_mesh") || volume_2.mesh->settings.get("support_mesh") - || volume_2.mesh->settings.get("magic_mesh_surface_mode") == ESurfaceMode::SURFACE) + if (volume_2.mesh->settings_.get("infill_mesh") || volume_2.mesh->settings_.get("anti_overhang_mesh") || volume_2.mesh->settings_.get("support_mesh") + || volume_2.mesh->settings_.get("magic_mesh_surface_mode") == ESurfaceMode::SURFACE) { continue; } @@ -51,7 +51,7 @@ void carveMultipleVolumes(std::vector& volumes) { SlicerLayer& layer1 = volume_1.layers[layerNr]; SlicerLayer& layer2 = volume_2.layers[layerNr]; - if (alternate_carve_order && layerNr % 2 == 0 && volume_1.mesh->settings.get("infill_mesh_order") == volume_2.mesh->settings.get("infill_mesh_order")) + if (alternate_carve_order && layerNr % 2 == 0 && volume_1.mesh->settings_.get("infill_mesh_order") == volume_2.mesh->settings_.get("infill_mesh_order")) { layer2.polygons = layer2.polygons.difference(layer1.polygons); } @@ -76,10 +76,10 @@ void generateMultipleVolumesOverlap(std::vector& volumes) int offset_to_merge_other_merged_volumes = 20; for (Slicer* volume : volumes) { - ClipperLib::PolyFillType fill_type = volume->mesh->settings.get("meshfix_union_all") ? ClipperLib::pftNonZero : ClipperLib::pftEvenOdd; + ClipperLib::PolyFillType fill_type = volume->mesh->settings_.get("meshfix_union_all") ? ClipperLib::pftNonZero : ClipperLib::pftEvenOdd; - coord_t overlap = volume->mesh->settings.get("multiple_mesh_overlap"); - if (volume->mesh->settings.get("infill_mesh") || volume->mesh->settings.get("anti_overhang_mesh") || volume->mesh->settings.get("support_mesh") + coord_t overlap = volume->mesh->settings_.get("multiple_mesh_overlap"); + if (volume->mesh->settings_.get("infill_mesh") || volume->mesh->settings_.get("anti_overhang_mesh") || volume->mesh->settings_.get("support_mesh") || overlap == 0) { continue; @@ -91,8 +91,8 @@ void generateMultipleVolumesOverlap(std::vector& volumes) Polygons all_other_volumes; for (Slicer* other_volume : volumes) { - if (other_volume->mesh->settings.get("infill_mesh") || other_volume->mesh->settings.get("anti_overhang_mesh") - || other_volume->mesh->settings.get("support_mesh") || ! other_volume->mesh->getAABB().hit(aabb) || other_volume == volume) + if (other_volume->mesh->settings_.get("infill_mesh") || other_volume->mesh->settings_.get("anti_overhang_mesh") + || other_volume->mesh->settings_.get("support_mesh") || ! other_volume->mesh->getAABB().hit(aabb) || other_volume == volume) { continue; } @@ -111,7 +111,7 @@ void MultiVolumes::carveCuttingMeshes(std::vector& volumes, const std:: for (unsigned int carving_mesh_idx = 0; carving_mesh_idx < volumes.size(); carving_mesh_idx++) { const Mesh& cutting_mesh = meshes[carving_mesh_idx]; - if (! cutting_mesh.settings.get("cutting_mesh")) + if (! cutting_mesh.settings_.get("cutting_mesh")) { continue; } @@ -122,14 +122,14 @@ void MultiVolumes::carveCuttingMeshes(std::vector& volumes, const std:: Polygons& cutting_mesh_polylines = cutting_mesh_volume.layers[layer_nr].openPolylines; Polygons cutting_mesh_area_recomputed; Polygons* cutting_mesh_area; - coord_t surface_line_width = cutting_mesh.settings.get("wall_line_width_0"); + coord_t surface_line_width = cutting_mesh.settings_.get("wall_line_width_0"); { // compute cutting_mesh_area - if (cutting_mesh.settings.get("magic_mesh_surface_mode") == ESurfaceMode::BOTH) + if (cutting_mesh.settings_.get("magic_mesh_surface_mode") == ESurfaceMode::BOTH) { cutting_mesh_area_recomputed = cutting_mesh_polygons.unionPolygons(cutting_mesh_polylines.offsetPolyLine(surface_line_width / 2)); cutting_mesh_area = &cutting_mesh_area_recomputed; } - else if (cutting_mesh.settings.get("magic_mesh_surface_mode") == ESurfaceMode::SURFACE) + else if (cutting_mesh.settings_.get("magic_mesh_surface_mode") == ESurfaceMode::SURFACE) { // break up polygons into polylines // they have to be polylines, because they might break up further when doing the cutting @@ -154,7 +154,7 @@ void MultiVolumes::carveCuttingMeshes(std::vector& volumes, const std:: { const Mesh& carved_mesh = meshes[carved_mesh_idx]; // Do not apply cutting_mesh for meshes which have settings (cutting_mesh, anti_overhang_mesh, support_mesh). - if (carved_mesh.settings.get("cutting_mesh") || carved_mesh.settings.get("anti_overhang_mesh") || carved_mesh.settings.get("support_mesh")) + if (carved_mesh.settings_.get("cutting_mesh") || carved_mesh.settings_.get("anti_overhang_mesh") || carved_mesh.settings_.get("support_mesh")) { continue; } @@ -163,7 +163,7 @@ void MultiVolumes::carveCuttingMeshes(std::vector& volumes, const std:: Polygons intersection = cutting_mesh_polygons.intersection(carved_mesh_layer); new_outlines.add(intersection); - if (cutting_mesh.settings.get("magic_mesh_surface_mode") != ESurfaceMode::NORMAL) // niet te geleuven + if (cutting_mesh.settings_.get("magic_mesh_surface_mode") != ESurfaceMode::NORMAL) // niet te geleuven { new_polylines.add(carved_mesh_layer.intersectionPolyLines(cutting_mesh_polylines)); } @@ -171,7 +171,7 @@ void MultiVolumes::carveCuttingMeshes(std::vector& volumes, const std:: carved_mesh_layer = carved_mesh_layer.difference(*cutting_mesh_area); } cutting_mesh_polygons = new_outlines.unionPolygons(); - if (cutting_mesh.settings.get("magic_mesh_surface_mode") != ESurfaceMode::NORMAL) + if (cutting_mesh.settings_.get("magic_mesh_surface_mode") != ESurfaceMode::NORMAL) { cutting_mesh_polylines.clear(); PolylineStitcher::stitch(new_polylines, cutting_mesh_polylines, cutting_mesh_polygons, surface_line_width); diff --git a/src/settings/AdaptiveLayerHeights.cpp b/src/settings/AdaptiveLayerHeights.cpp index e2ebe6e37b..25f1cca535 100644 --- a/src/settings/AdaptiveLayerHeights.cpp +++ b/src/settings/AdaptiveLayerHeights.cpp @@ -190,20 +190,20 @@ void AdaptiveLayerHeights::calculateMeshTriangleSlopes() for (const Mesh& mesh : Application::getInstance().current_slice->scene.current_mesh_group->meshes) { // Skip meshes that are not printable - if (mesh.settings.get("infill_mesh") || mesh.settings.get("cutting_mesh") || mesh.settings.get("anti_overhang_mesh")) + if (mesh.settings_.get("infill_mesh") || mesh.settings_.get("cutting_mesh") || mesh.settings_.get("anti_overhang_mesh")) { continue; } - for (const MeshFace& face : mesh.faces) + for (const MeshFace& face : mesh.faces_) { - const MeshVertex& v0 = mesh.vertices[face.vertex_index[0]]; - const MeshVertex& v1 = mesh.vertices[face.vertex_index[1]]; - const MeshVertex& v2 = mesh.vertices[face.vertex_index[2]]; + const MeshVertex& v0 = mesh.vertices_[face.vertex_index_[0]]; + const MeshVertex& v1 = mesh.vertices_[face.vertex_index_[1]]; + const MeshVertex& v2 = mesh.vertices_[face.vertex_index_[2]]; - const FPoint3 p0 = v0.p; - const FPoint3 p1 = v1.p; - const FPoint3 p2 = v2.p; + const FPoint3 p0 = v0.p_; + const FPoint3 p1 = v1.p_; + const FPoint3 p2 = v2.p_; float min_z = p0.z; min_z = std::min(min_z, p1.z); diff --git a/src/sliceDataStorage.cpp b/src/sliceDataStorage.cpp index ff69b9d009..2d2741ad8a 100644 --- a/src/sliceDataStorage.cpp +++ b/src/sliceDataStorage.cpp @@ -91,8 +91,8 @@ void SliceLayer::getOutlines(Polygons& result, bool external_polys_only) const } SliceMeshStorage::SliceMeshStorage(Mesh* mesh, const size_t slice_layer_count) - : settings(mesh->settings) - , mesh_name(mesh->mesh_name) + : settings(mesh->settings_) + , mesh_name(mesh->mesh_name_) , layer_nr_max_filled_layer(0) , bounding_box(mesh->getAABB()) , base_subdiv_cube(nullptr) diff --git a/src/slicer.cpp b/src/slicer.cpp index 94dc2aeb64..832589deb1 100644 --- a/src/slicer.cpp +++ b/src/slicer.cpp @@ -108,7 +108,7 @@ int SlicerLayer::getNextSegmentIdx(const SlicerSegment& segment, const size_t st { // segment ended at vertex - const std::vector& faces_to_try = segment.endVertex->connected_faces; + const std::vector& faces_to_try = segment.endVertex->connected_faces_; for (int face_to_try : faces_to_try) { const int result_segment_idx = tryFaceNextSegmentIdx(segment, face_to_try, start_segment_idx); @@ -743,18 +743,18 @@ void SlicerLayer::makePolygons(const Mesh* mesh) // TODO: (?) for mesh surface mode: connect open polygons. Maybe the above algorithm can create two open polygons which are actually connected when the starting segment is in // the middle between the two open polygons. - if (mesh->settings.get("magic_mesh_surface_mode") == ESurfaceMode::NORMAL) + if (mesh->settings_.get("magic_mesh_surface_mode") == ESurfaceMode::NORMAL) { // don't stitch when using (any) mesh surface mode, i.e. also don't stitch when using mixed mesh surface and closed polygons, because then polylines which are supposed to be // open will be closed stitch(open_polylines); } - if (mesh->settings.get("meshfix_extensive_stitching")) + if (mesh->settings_.get("meshfix_extensive_stitching")) { stitch_extensive(open_polylines); } - if (mesh->settings.get("meshfix_keep_open_polygons")) + if (mesh->settings_.get("meshfix_keep_open_polygons")) { for (PolygonRef polyline : open_polylines) { @@ -772,7 +772,7 @@ void SlicerLayer::makePolygons(const Mesh* mesh) } // Remove all the tiny polygons, or polygons that are not closed. As they do not contribute to the actual print. - const coord_t snap_distance = std::max(mesh->settings.get("minimum_polygon_circumference"), static_cast(1)); + const coord_t snap_distance = std::max(mesh->settings_.get("minimum_polygon_circumference"), static_cast(1)); auto it = std::remove_if( polygons.begin(), polygons.end(), @@ -786,9 +786,9 @@ void SlicerLayer::makePolygons(const Mesh* mesh) // polygons = Simplify(mesh->settings).polygon(polygons); polygons = slots::instance().modify( polygons, - mesh->settings.get("meshfix_maximum_resolution"), - mesh->settings.get("meshfix_maximum_deviation"), - static_cast(mesh->settings.get("meshfix_maximum_extrusion_area_deviation"))); + mesh->settings_.get("meshfix_maximum_resolution"), + mesh->settings_.get("meshfix_maximum_deviation"), + static_cast(mesh->settings_.get("meshfix_maximum_extrusion_area_deviation"))); polygons.removeDegenerateVerts(); // remove verts connected to overlapping line segments // Clean up polylines for Surface Mode printing @@ -807,7 +807,7 @@ void SlicerLayer::makePolygons(const Mesh* mesh) Slicer::Slicer(Mesh* i_mesh, const coord_t thickness, const size_t slice_layer_count, bool use_variable_layer_heights, std::vector* adaptive_layers) : mesh(i_mesh) { - const SlicingTolerance slicing_tolerance = mesh->settings.get("slicing_tolerance"); + const SlicingTolerance slicing_tolerance = mesh->settings_.get("slicing_tolerance"); const coord_t initial_layer_thickness = Application::getInstance().current_slice->scene.current_mesh_group->settings.get("layer_height_0"); assert(slice_layer_count > 0); @@ -817,14 +817,14 @@ Slicer::Slicer(Mesh* i_mesh, const coord_t thickness, const size_t slice_layer_c layers = buildLayersWithHeight(slice_layer_count, slicing_tolerance, initial_layer_thickness, thickness, use_variable_layer_heights, adaptive_layers); scripta::setAll( layers, - static_cast(mesh->settings.get("adhesion_type")), - mesh->settings.get("raft_surface_layers"), - mesh->settings.get("raft_surface_thickness"), - mesh->settings.get("raft_interface_layers"), - mesh->settings.get("raft_interface_thickness"), - mesh->settings.get("raft_base_thickness"), - mesh->settings.get("raft_airgap"), - mesh->settings.get("layer_0_z_overlap")); + static_cast(mesh->settings_.get("adhesion_type")), + mesh->settings_.get("raft_surface_layers"), + mesh->settings_.get("raft_surface_thickness"), + mesh->settings_.get("raft_interface_layers"), + mesh->settings_.get("raft_interface_thickness"), + mesh->settings_.get("raft_base_thickness"), + mesh->settings_.get("raft_airgap"), + mesh->settings_.get("layer_0_z_overlap")); std::vector> zbbox = buildZHeightsForFaces(*mesh); @@ -848,7 +848,7 @@ void Slicer::buildSegments(const Mesh& mesh, const std::vector zbbox[mesh_idx].second)) { @@ -856,15 +856,15 @@ void Slicer::buildSegments(const Mesh& mesh, const std::vector 0 && layers[0].polygons.size() == 0 && ! mesh.settings.get("support_mesh") && ! mesh.settings.get("anti_overhang_mesh") - && ! mesh.settings.get("cutting_mesh") && ! mesh.settings.get("infill_mesh")) + if (layers.size() > 0 && layers[0].polygons.size() == 0 && ! mesh.settings_.get("support_mesh") && ! mesh.settings_.get("anti_overhang_mesh") + && ! mesh.settings_.get("cutting_mesh") && ! mesh.settings_.get("infill_mesh")) { layer_apply_initial_xy_offset = 1; } - const coord_t xy_offset = mesh.settings.get("xy_offset"); - const coord_t xy_offset_0 = mesh.settings.get("xy_offset_layer_0"); - const coord_t xy_offset_hole = mesh.settings.get("hole_xy_offset"); - const coord_t hole_offset_max_diameter = mesh.settings.get("hole_xy_offset_max_diameter"); + const coord_t xy_offset = mesh.settings_.get("xy_offset"); + const coord_t xy_offset_0 = mesh.settings_.get("xy_offset_layer_0"); + const coord_t xy_offset_hole = mesh.settings_.get("hole_xy_offset"); + const coord_t hole_offset_max_diameter = mesh.settings_.get("hole_xy_offset_max_diameter"); const auto max_hole_area = std::numbers::pi / 4 * static_cast(hole_offset_max_diameter * hole_offset_max_diameter); @@ -1113,18 +1113,18 @@ void Slicer::makePolygons(Mesh& mesh, SlicingTolerance slicing_tolerance, std::v std::vector> Slicer::buildZHeightsForFaces(const Mesh& mesh) { std::vector> zHeights; - zHeights.reserve(mesh.faces.size()); - for (const auto& face : mesh.faces) + zHeights.reserve(mesh.faces_.size()); + for (const auto& face : mesh.faces_) { // const MeshFace& face = mesh.faces[mesh_idx]; - const MeshVertex& v0 = mesh.vertices[face.vertex_index[0]]; - const MeshVertex& v1 = mesh.vertices[face.vertex_index[1]]; - const MeshVertex& v2 = mesh.vertices[face.vertex_index[2]]; + const MeshVertex& v0 = mesh.vertices_[face.vertex_index_[0]]; + const MeshVertex& v1 = mesh.vertices_[face.vertex_index_[1]]; + const MeshVertex& v2 = mesh.vertices_[face.vertex_index_[2]]; // get all vertices represented as 3D point - Point3 p0 = v0.p; - Point3 p1 = v1.p; - Point3 p2 = v2.p; + Point3 p0 = v0.p_; + Point3 p1 = v1.p_; + Point3 p2 = v2.p_; // find the minimum and maximum z point int32_t minZ = p0.z_; diff --git a/tests/arcus/ArcusCommunicationPrivateTest.cpp b/tests/arcus/ArcusCommunicationPrivateTest.cpp index b96dd840ff..1538269483 100644 --- a/tests/arcus/ArcusCommunicationPrivateTest.cpp +++ b/tests/arcus/ArcusCommunicationPrivateTest.cpp @@ -212,10 +212,10 @@ TEST_F(ArcusCommunicationPrivateTest, ReadMeshGroupMessage) auto& meshes = scene.mesh_groups[0].meshes; ASSERT_FALSE(meshes.empty()); - auto& vertices = meshes[0].vertices; + auto& vertices = meshes[0].vertices_; ASSERT_FALSE(vertices.empty()); ASSERT_EQ(vertices.size(), size_t(8)); // A cube should have 8 unique vertices. - ASSERT_EQ(meshes[0].faces.size(), size_t(12)); // A cube should have 12 tri-s (2 for each 6 sides of the dice). + ASSERT_EQ(meshes[0].faces_.size(), size_t(12)); // A cube should have 12 tri-s (2 for each 6 sides of the dice). // Distances should be the same: @@ -234,12 +234,12 @@ TEST_F(ArcusCommunicationPrivateTest, ReadMeshGroupMessage) std::array max_coords = { std::numeric_limits::min(), std::numeric_limits::min(), std::numeric_limits::min() }; for (const auto& vertex : vertices) { - min_coords[0] = std::min(vertex.p.x, min_coords[0]); - min_coords[1] = std::min(vertex.p.y, min_coords[1]); - min_coords[2] = std::min(vertex.p.z, min_coords[2]); - max_coords[0] = std::max(vertex.p.x, max_coords[0]); - max_coords[1] = std::max(vertex.p.y, max_coords[1]); - max_coords[2] = std::max(vertex.p.z, max_coords[2]); + min_coords[0] = std::min(vertex.p_.x, min_coords[0]); + min_coords[1] = std::min(vertex.p_.y, min_coords[1]); + min_coords[2] = std::min(vertex.p_.z, min_coords[2]); + max_coords[0] = std::max(vertex.p_.x, max_coords[0]); + max_coords[1] = std::max(vertex.p_.y, max_coords[1]); + max_coords[2] = std::max(vertex.p_.z, max_coords[2]); } // - Then, just compare: From cdb108f0e76d5e9142f5f0ba48820881af6fcbf4 Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Tue, 21 Nov 2023 09:33:03 +0100 Subject: [PATCH 09/48] Fixed variable shadowing warnings --- include/ExtruderTrain.h | 4 +- include/utils/SparseLineGrid.h | 8 +- include/utils/SquareGrid.h | 2 +- include/utils/VoxelUtils.h | 16 +- src/ExtruderTrain.cpp | 6 +- src/FffGcodeWriter.cpp | 228 +++++++++--------- src/FffPolygonGenerator.cpp | 32 +-- src/InterlockingGenerator.cpp | 4 +- src/LayerPlan.cpp | 38 +-- src/LayerPlanBuffer.cpp | 20 +- src/Mold.cpp | 2 +- src/Preheat.cpp | 8 +- src/PrimeTower.cpp | 22 +- src/Scene.cpp | 2 +- src/SkirtBrim.cpp | 34 +-- src/Slice.cpp | 2 +- src/TopSurface.cpp | 2 +- src/WallsComputation.cpp | 35 +-- src/communication/ArcusCommunication.cpp | 4 +- .../ArcusCommunicationPrivate.cpp | 4 +- src/communication/CommandLine.cpp | 10 +- src/gcodeExport.cpp | 52 ++-- src/infill/LightningGenerator.cpp | 29 +-- src/pathPlanning/Comb.cpp | 30 +-- src/raft.cpp | 20 +- src/settings/MeshPathConfigs.cpp | 28 +-- src/settings/PathConfigStorage.cpp | 118 ++++----- src/settings/Settings.cpp | 24 +- src/skin.cpp | 2 +- src/sliceDataStorage.cpp | 76 +++--- src/support.cpp | 76 +++--- src/utils/SquareGrid.cpp | 8 +- src/utils/VoxelUtils.cpp | 14 +- tests/GCodeExportTest.cpp | 32 +-- tests/arcus/ArcusCommunicationPrivateTest.cpp | 6 +- 35 files changed, 502 insertions(+), 496 deletions(-) diff --git a/include/ExtruderTrain.h b/include/ExtruderTrain.h index 59679203cb..14ede169f4 100644 --- a/include/ExtruderTrain.h +++ b/include/ExtruderTrain.h @@ -21,7 +21,7 @@ class ExtruderTrain /* * \brief The settings that this extruder overwrites. */ - Settings settings; + Settings settings_; /* * \brief The position of this extruder. @@ -29,7 +29,7 @@ class ExtruderTrain * This may be used by g-code commands such as T to indicate to which * tool we must switch. */ - const size_t extruder_nr; + const size_t extruder_nr_; }; }//namespace cura diff --git a/include/utils/SparseLineGrid.h b/include/utils/SparseLineGrid.h index 20c0ca3626..385b129df5 100644 --- a/include/utils/SparseLineGrid.h +++ b/include/utils/SparseLineGrid.h @@ -104,13 +104,13 @@ void SGI_THIS::debugHTML(std::string filename) Point rb = SparseGrid::toLowerCorner(cell.first + GridPoint(SparseGrid::nonzero_sign(cell.first.X), 0)); if (lb.X == 0) { - lb.X = -SparseGrid::cell_size; - lt.X = -SparseGrid::cell_size; + lb.X = -SparseGrid::cell_size_; + lt.X = -SparseGrid::cell_size_; } if (lb.Y == 0) { - lb.Y = -SparseGrid::cell_size; - rb.Y = -SparseGrid::cell_size; + lb.Y = -SparseGrid::cell_size_; + rb.Y = -SparseGrid::cell_size_; } // svg.writePoint(lb, true, 1); svg.writeLine(lb, lt, SVG::Color::GRAY); diff --git a/include/utils/SquareGrid.h b/include/utils/SquareGrid.h index 41a23fe5f7..0ed6e7305a 100644 --- a/include/utils/SquareGrid.h +++ b/include/utils/SquareGrid.h @@ -137,7 +137,7 @@ class SquareGrid protected: /*! \brief The cell (square) size. */ - coord_t cell_size; + coord_t cell_size_; /*! * Compute the sign of a number. diff --git a/include/utils/VoxelUtils.h b/include/utils/VoxelUtils.h index b080a4d5b6..30078b51b3 100644 --- a/include/utils/VoxelUtils.h +++ b/include/utils/VoxelUtils.h @@ -63,11 +63,13 @@ class VoxelUtils { public: using grid_coord_t = coord_t; + + Point3 cell_size_; + VoxelUtils(Point3 cell_size) - : cell_size(cell_size) + : cell_size_(cell_size) { } - Point3 cell_size; /*! * Process voxels which a line segment crosses. @@ -156,7 +158,7 @@ class VoxelUtils grid_coord_t toGridCoord(const coord_t& coord, const size_t dim) const { assert(dim < 3); - return coord / cell_size[dim] - (coord < 0); + return coord / cell_size_[dim] - (coord < 0); } Point3 toLowerCorner(const GridPoint3& location) const @@ -167,7 +169,7 @@ class VoxelUtils coord_t toLowerCoord(const grid_coord_t& grid_coord, const size_t dim) const { assert(dim < 3); - return grid_coord * cell_size[dim]; + return grid_coord * cell_size_[dim]; } /*! @@ -178,9 +180,9 @@ class VoxelUtils Polygon ret; Point3 c = toLowerCorner(p); ret.emplace_back(c.x_, c.y_); - ret.emplace_back(c.x_ + cell_size.x_, c.y_); - ret.emplace_back(c.x_ + cell_size.x_, c.y_ + cell_size.y_); - ret.emplace_back(c.x_, c.y_ + cell_size.y_); + ret.emplace_back(c.x_ + cell_size_.x_, c.y_); + ret.emplace_back(c.x_ + cell_size_.x_, c.y_ + cell_size_.y_); + ret.emplace_back(c.x_, c.y_ + cell_size_.y_); return ret; } }; diff --git a/src/ExtruderTrain.cpp b/src/ExtruderTrain.cpp index cb911cda02..a06131472c 100644 --- a/src/ExtruderTrain.cpp +++ b/src/ExtruderTrain.cpp @@ -6,9 +6,9 @@ namespace cura { -ExtruderTrain::ExtruderTrain(const size_t extruder_nr, Settings* parent_settings) : extruder_nr(extruder_nr) +ExtruderTrain::ExtruderTrain(const size_t extruder_nr, Settings* parent_settings) : extruder_nr_(extruder_nr) { - settings.setParent(parent_settings); + settings_.setParent(parent_settings); } -}//namespace cura \ No newline at end of file +}//namespace cura diff --git a/src/FffGcodeWriter.cpp b/src/FffGcodeWriter.cpp index aced5673aa..1376f48a23 100644 --- a/src/FffGcodeWriter.cpp +++ b/src/FffGcodeWriter.cpp @@ -302,14 +302,14 @@ void FffGcodeWriter::setConfigFanSpeedLayerTime() { fan_speed_layer_time_settings_per_extruder.emplace_back(); FanSpeedLayerTimeSettings& fan_speed_layer_time_settings = fan_speed_layer_time_settings_per_extruder.back(); - fan_speed_layer_time_settings.cool_min_layer_time = train.settings.get("cool_min_layer_time"); - fan_speed_layer_time_settings.cool_min_layer_time_fan_speed_max = train.settings.get("cool_min_layer_time_fan_speed_max"); - fan_speed_layer_time_settings.cool_fan_speed_0 = train.settings.get("cool_fan_speed_0") * 100.0; - fan_speed_layer_time_settings.cool_fan_speed_min = train.settings.get("cool_fan_speed_min") * 100.0; - fan_speed_layer_time_settings.cool_fan_speed_max = train.settings.get("cool_fan_speed_max") * 100.0; - fan_speed_layer_time_settings.cool_min_speed = train.settings.get("cool_min_speed"); - fan_speed_layer_time_settings.cool_fan_full_layer = train.settings.get("cool_fan_full_layer"); - if (! train.settings.get("cool_fan_enabled")) + fan_speed_layer_time_settings.cool_min_layer_time = train.settings_.get("cool_min_layer_time"); + fan_speed_layer_time_settings.cool_min_layer_time_fan_speed_max = train.settings_.get("cool_min_layer_time_fan_speed_max"); + fan_speed_layer_time_settings.cool_fan_speed_0 = train.settings_.get("cool_fan_speed_0") * 100.0; + fan_speed_layer_time_settings.cool_fan_speed_min = train.settings_.get("cool_fan_speed_min") * 100.0; + fan_speed_layer_time_settings.cool_fan_speed_max = train.settings_.get("cool_fan_speed_max") * 100.0; + fan_speed_layer_time_settings.cool_min_speed = train.settings_.get("cool_min_speed"); + fan_speed_layer_time_settings.cool_fan_full_layer = train.settings_.get("cool_fan_full_layer"); + if (! train.settings_.get("cool_fan_enabled")) { fan_speed_layer_time_settings.cool_fan_speed_0 = 0; fan_speed_layer_time_settings.cool_fan_speed_min = 0; @@ -374,7 +374,7 @@ void FffGcodeWriter::setConfigRetractionAndWipe(SliceDataStorage& storage) for (size_t extruder_index = 0; extruder_index < scene.extruders.size(); extruder_index++) { ExtruderTrain& train = scene.extruders[extruder_index]; - retractionAndWipeConfigFromSettings(train.settings, &storage.retraction_wipe_config_per_extruder[extruder_index]); + retractionAndWipeConfigFromSettings(train.settings_, &storage.retraction_wipe_config_per_extruder[extruder_index]); } for (std::shared_ptr& mesh : storage.meshes) { @@ -391,26 +391,26 @@ size_t FffGcodeWriter::getStartExtruder(const SliceDataStorage& storage) size_t start_extruder_nr; if (adhesion_type == EPlatformAdhesion::SKIRT && skirt_brim_extruder - && (skirt_brim_extruder->settings.get("skirt_line_count") > 0 || skirt_brim_extruder->settings.get("skirt_brim_minimal_length") > 0)) + && (skirt_brim_extruder->settings_.get("skirt_line_count") > 0 || skirt_brim_extruder->settings_.get("skirt_brim_minimal_length") > 0)) { - start_extruder_nr = skirt_brim_extruder->extruder_nr; + start_extruder_nr = skirt_brim_extruder->extruder_nr_; } else if ( (adhesion_type == EPlatformAdhesion::BRIM || mesh_group_settings.get("prime_tower_brim_enable")) && skirt_brim_extruder - && (skirt_brim_extruder->settings.get("brim_line_count") > 0 || skirt_brim_extruder->settings.get("skirt_brim_minimal_length") > 0)) + && (skirt_brim_extruder->settings_.get("brim_line_count") > 0 || skirt_brim_extruder->settings_.get("skirt_brim_minimal_length") > 0)) { - start_extruder_nr = skirt_brim_extruder->extruder_nr; + start_extruder_nr = skirt_brim_extruder->extruder_nr_; } else if (adhesion_type == EPlatformAdhesion::RAFT && skirt_brim_extruder) { - start_extruder_nr = mesh_group_settings.get("raft_base_extruder_nr").extruder_nr; + start_extruder_nr = mesh_group_settings.get("raft_base_extruder_nr").extruder_nr_; } else // No adhesion. { if (mesh_group_settings.get("support_enable") && mesh_group_settings.get("support_brim_enable")) { - start_extruder_nr = mesh_group_settings.get("support_infill_extruder_nr").extruder_nr; + start_extruder_nr = mesh_group_settings.get("support_infill_extruder_nr").extruder_nr_; } else { @@ -481,14 +481,14 @@ void FffGcodeWriter::setSupportAngles(SliceDataStorage& storage) { const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; const ExtruderTrain& support_infill_extruder = mesh_group_settings.get("support_infill_extruder_nr"); - storage.support.support_infill_angles = support_infill_extruder.settings.get>("support_infill_angles"); + storage.support.support_infill_angles = support_infill_extruder.settings_.get>("support_infill_angles"); if (storage.support.support_infill_angles.empty()) { storage.support.support_infill_angles.push_back(0); } const ExtruderTrain& support_extruder_nr_layer_0 = mesh_group_settings.get("support_extruder_nr_layer_0"); - storage.support.support_infill_angles_layer_0 = support_extruder_nr_layer_0.settings.get>("support_infill_angles"); + storage.support.support_infill_angles_layer_0 = support_extruder_nr_layer_0.settings_.get>("support_infill_angles"); if (storage.support.support_infill_angles_layer_0.empty()) { storage.support.support_infill_angles_layer_0.push_back(0); @@ -497,7 +497,7 @@ void FffGcodeWriter::setSupportAngles(SliceDataStorage& storage) auto getInterfaceAngles = [&storage](const ExtruderTrain& extruder, const std::string& interface_angles_setting, const EFillMethod pattern, const std::string& interface_height_setting) { - std::vector angles = extruder.settings.get>(interface_angles_setting); + std::vector angles = extruder.settings_.get>(interface_angles_setting); if (angles.empty()) { if (pattern == EFillMethod::CONCENTRIC) @@ -532,11 +532,11 @@ void FffGcodeWriter::setSupportAngles(SliceDataStorage& storage) const ExtruderTrain& roof_extruder = mesh_group_settings.get("support_roof_extruder_nr"); storage.support.support_roof_angles - = getInterfaceAngles(roof_extruder, "support_roof_angles", roof_extruder.settings.get("support_roof_pattern"), "support_roof_height"); + = getInterfaceAngles(roof_extruder, "support_roof_angles", roof_extruder.settings_.get("support_roof_pattern"), "support_roof_height"); const ExtruderTrain& bottom_extruder = mesh_group_settings.get("support_bottom_extruder_nr"); storage.support.support_bottom_angles - = getInterfaceAngles(bottom_extruder, "support_bottom_angles", bottom_extruder.settings.get("support_bottom_pattern"), "support_bottom_height"); + = getInterfaceAngles(bottom_extruder, "support_bottom_angles", bottom_extruder.settings_.get("support_bottom_pattern"), "support_bottom_height"); } void FffGcodeWriter::processNextMeshGroupCode(const SliceDataStorage& storage) @@ -545,9 +545,9 @@ void FffGcodeWriter::processNextMeshGroupCode(const SliceDataStorage& storage) gcode.setZ(max_object_height + MM2INT(5)); Application::getInstance().communication->sendCurrentPosition(gcode.getPositionXY()); - gcode.writeTravel(gcode.getPositionXY(), Application::getInstance().current_slice->scene.extruders[gcode.getExtruderNr()].settings.get("speed_travel")); + gcode.writeTravel(gcode.getPositionXY(), Application::getInstance().current_slice->scene.extruders[gcode.getExtruderNr()].settings_.get("speed_travel")); Point start_pos(storage.model_min.x_, storage.model_min.y_); - gcode.writeTravel(start_pos, Application::getInstance().current_slice->scene.extruders[gcode.getExtruderNr()].settings.get("speed_travel")); + gcode.writeTravel(start_pos, Application::getInstance().current_slice->scene.extruders[gcode.getExtruderNr()].settings_.get("speed_travel")); gcode.processInitialLayerTemperature(storage, gcode.getExtruderNr()); } @@ -555,16 +555,16 @@ void FffGcodeWriter::processNextMeshGroupCode(const SliceDataStorage& storage) void FffGcodeWriter::processRaft(const SliceDataStorage& storage) { Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; - const size_t base_extruder_nr = mesh_group_settings.get("raft_base_extruder_nr").extruder_nr; - const size_t interface_extruder_nr = mesh_group_settings.get("raft_interface_extruder_nr").extruder_nr; - const size_t surface_extruder_nr = mesh_group_settings.get("raft_surface_extruder_nr").extruder_nr; + const size_t base_extruder_nr = mesh_group_settings.get("raft_base_extruder_nr").extruder_nr_; + const size_t interface_extruder_nr = mesh_group_settings.get("raft_interface_extruder_nr").extruder_nr_; + const size_t surface_extruder_nr = mesh_group_settings.get("raft_surface_extruder_nr").extruder_nr_; const size_t prime_tower_extruder_nr = storage.primeTower.extruder_order.front(); coord_t z = 0; const LayerIndex initial_raft_layer_nr = -Raft::getTotalExtraLayers(); - const Settings& interface_settings = mesh_group_settings.get("raft_interface_extruder_nr").settings; + const Settings& interface_settings = mesh_group_settings.get("raft_interface_extruder_nr").settings_; const size_t num_interface_layers = interface_settings.get("raft_interface_layers"); - const Settings& surface_settings = mesh_group_settings.get("raft_surface_extruder_nr").settings; + const Settings& surface_settings = mesh_group_settings.get("raft_surface_extruder_nr").settings_; const size_t num_surface_layers = surface_settings.get("raft_surface_layers"); // some infill config for all lines infill generation below @@ -579,7 +579,7 @@ void FffGcodeWriter::processRaft(const SliceDataStorage& storage) unsigned int current_extruder_nr = base_extruder_nr; { // raft base layer - const Settings& base_settings = mesh_group_settings.get("raft_base_extruder_nr").settings; + const Settings& base_settings = mesh_group_settings.get("raft_base_extruder_nr").settings_; LayerIndex layer_nr = initial_raft_layer_nr; const coord_t layer_height = base_settings.get("raft_base_thickness"); z += layer_height; @@ -998,9 +998,9 @@ FffGcodeWriter::ProcessLayerResult FffGcodeWriter::processLayer(const SliceDataS { const ExtruderTrain& extruder = scene.extruders[extruder_nr]; - if (extruder.settings.get("travel_avoid_other_parts")) + if (extruder.settings_.get("travel_avoid_other_parts")) { - avoid_distance = std::max(avoid_distance, extruder.settings.get("travel_avoid_distance")); + avoid_distance = std::max(avoid_distance, extruder.settings_.get("travel_avoid_distance")); } } } @@ -1013,7 +1013,7 @@ FffGcodeWriter::ProcessLayerResult FffGcodeWriter::processLayer(const SliceDataS if (layer_nr == 0) { const ExtruderTrain& train = mesh.settings.get((mesh.settings.get("wall_line_count") > 1) ? "wall_0_extruder_nr" : "wall_x_extruder_nr"); - mesh_inner_wall_width *= train.settings.get("initial_layer_line_width_factor"); + mesh_inner_wall_width *= train.settings_.get("initial_layer_line_width_factor"); } max_inner_wall_width = std::max(max_inner_wall_width, mesh_inner_wall_width); } @@ -1024,7 +1024,7 @@ FffGcodeWriter::ProcessLayerResult FffGcodeWriter::processLayer(const SliceDataS const std::vector& extruder_order = (layer_nr < 0) ? extruder_order_per_layer_negative_layers[extruder_order_per_layer_negative_layers.size() + layer_nr] : extruder_order_per_layer[layer_nr]; - const coord_t first_outer_wall_line_width = scene.extruders[extruder_order.front()].settings.get("wall_line_width_0"); + const coord_t first_outer_wall_line_width = scene.extruders[extruder_order.front()].settings_.get("wall_line_width_0"); LayerPlan& gcode_layer = *new LayerPlan( storage, layer_nr, @@ -1055,10 +1055,10 @@ FffGcodeWriter::ProcessLayerResult FffGcodeWriter::processLayer(const SliceDataS time_keeper.registerTime("Draft shield"); } - const size_t support_roof_extruder_nr = mesh_group_settings.get("support_roof_extruder_nr").extruder_nr; - const size_t support_bottom_extruder_nr = mesh_group_settings.get("support_bottom_extruder_nr").extruder_nr; - const size_t support_infill_extruder_nr = (layer_nr <= 0) ? mesh_group_settings.get("support_extruder_nr_layer_0").extruder_nr - : mesh_group_settings.get("support_infill_extruder_nr").extruder_nr; + const size_t support_roof_extruder_nr = mesh_group_settings.get("support_roof_extruder_nr").extruder_nr_; + const size_t support_bottom_extruder_nr = mesh_group_settings.get("support_bottom_extruder_nr").extruder_nr_; + const size_t support_infill_extruder_nr = (layer_nr <= 0) ? mesh_group_settings.get("support_extruder_nr_layer_0").extruder_nr_ + : mesh_group_settings.get("support_infill_extruder_nr").extruder_nr_; for (const size_t& extruder_nr : extruder_order) { @@ -1089,7 +1089,7 @@ FffGcodeWriter::ProcessLayerResult FffGcodeWriter::processLayer(const SliceDataS const MeshPathConfigs& mesh_config = gcode_layer.configs_storage.mesh_configs[mesh_idx]; if (mesh->settings.get("magic_mesh_surface_mode") == ESurfaceMode::SURFACE && extruder_nr - == mesh->settings.get("wall_0_extruder_nr").extruder_nr // mesh surface mode should always only be printed with the outer wall extruder! + == mesh->settings.get("wall_0_extruder_nr").extruder_nr_ // mesh surface mode should always only be printed with the outer wall extruder! ) { addMeshLayerToGCode_meshSurfaceMode(storage, *mesh, mesh_config, gcode_layer); @@ -1139,8 +1139,8 @@ bool FffGcodeWriter::getExtruderNeedPrimeBlobDuringFirstLayer(const SliceDataSto void FffGcodeWriter::processSkirtBrim(const SliceDataStorage& storage, LayerPlan& gcode_layer, unsigned int extruder_nr, LayerIndex layer_nr) const { const ExtruderTrain& train = Application::getInstance().current_slice->scene.extruders[extruder_nr]; - const int skirt_height = train.settings.get("skirt_height"); - const bool is_skirt = train.settings.get("adhesion_type") == EPlatformAdhesion::SKIRT; + const int skirt_height = train.settings_.get("skirt_height"); + const bool is_skirt = train.settings_.get("adhesion_type") == EPlatformAdhesion::SKIRT; // only create a multilayer SkirtBrim for a skirt for the height of skirt_height if (layer_nr != 0 && (layer_nr >= skirt_height || ! is_skirt)) { @@ -1160,10 +1160,10 @@ void FffGcodeWriter::processSkirtBrim(const SliceDataStorage& storage, LayerPlan // Start brim close to the prime location Point start_close_to; - if (train.settings.get("prime_blob_enable")) + if (train.settings_.get("prime_blob_enable")) { - const auto prime_pos_is_abs = train.settings.get("extruder_prime_pos_abs"); - const auto prime_pos = Point(train.settings.get("extruder_prime_pos_x"), train.settings.get("extruder_prime_pos_y")); + const auto prime_pos_is_abs = train.settings_.get("extruder_prime_pos_abs"); + const auto prime_pos = Point(train.settings_.get("extruder_prime_pos_x"), train.settings_.get("extruder_prime_pos_y")); start_close_to = prime_pos_is_abs ? prime_pos : gcode_layer.getLastPlannedPositionOrStartingPosition() + prime_pos; } else @@ -1189,7 +1189,7 @@ void FffGcodeWriter::processSkirtBrim(const SliceDataStorage& storage, LayerPlan all_brim_lines.reserve(total_line_count); - const coord_t line_w = train.settings.get("skirt_brim_line_width") * train.settings.get("initial_layer_line_width_factor"); + const coord_t line_w = train.settings_.get("skirt_brim_line_width") * train.settings_.get("initial_layer_line_width_factor"); const coord_t searching_radius = line_w * 2; using GridT = SparsePointGridInclusive; GridT grid(searching_radius); @@ -1222,7 +1222,7 @@ void FffGcodeWriter::processSkirtBrim(const SliceDataStorage& storage, LayerPlan } } - const auto smart_brim_ordering = train.settings.get("brim_smart_ordering") && train.settings.get("adhesion_type") == EPlatformAdhesion::BRIM; + const auto smart_brim_ordering = train.settings_.get("brim_smart_ordering") && train.settings_.get("adhesion_type") == EPlatformAdhesion::BRIM; std::unordered_multimap order_requirements; for (const std::pair>& p : grid) { @@ -1301,7 +1301,7 @@ void FffGcodeWriter::processSkirtBrim(const SliceDataStorage& storage, LayerPlan // Support brim is only added in layer 0 // For support brim we don't care about the order, because support doesn't need to be accurate. const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; - if ((layer_nr == 0) && (extruder_nr == mesh_group_settings.get("support_extruder_nr_layer_0").extruder_nr)) + if ((layer_nr == 0) && (extruder_nr == mesh_group_settings.get("support_extruder_nr_layer_0").extruder_nr_)) { total_line_count += storage.support_brim.size(); Polygons support_brim_lines = storage.support_brim; @@ -1462,7 +1462,7 @@ std::vector FffGcodeWriter::calculateMeshOrder(const SliceDataStorage& s } } const ExtruderTrain& train = Application::getInstance().current_slice->scene.extruders[extruder_nr]; - const Point layer_start_position(train.settings.get("layer_start_x"), train.settings.get("layer_start_y")); + const Point layer_start_position(train.settings_.get("layer_start_x"), train.settings_.get("layer_start_y")); std::list mesh_indices_order = mesh_idx_order_optimizer.optimize(layer_start_position); std::vector ret; @@ -1566,11 +1566,11 @@ void FffGcodeWriter::addMeshLayerToGCode( } const std::string extruder_identifier = (mesh.settings.get("roofing_layer_count") > 0) ? "roofing_extruder_nr" : "top_bottom_extruder_nr"; - if (extruder_nr == mesh.settings.get(extruder_identifier).extruder_nr) + if (extruder_nr == mesh.settings.get(extruder_identifier).extruder_nr_) { processIroning(storage, mesh, layer, mesh_config.ironing_config, gcode_layer); } - if (mesh.settings.get("magic_mesh_surface_mode") != ESurfaceMode::NORMAL && extruder_nr == mesh.settings.get("wall_0_extruder_nr").extruder_nr) + if (mesh.settings.get("magic_mesh_surface_mode") != ESurfaceMode::NORMAL && extruder_nr == mesh.settings.get("wall_0_extruder_nr").extruder_nr_) { addMeshOpenPolyLinesToGCode(mesh, mesh_config, gcode_layer); } @@ -1626,7 +1626,7 @@ bool FffGcodeWriter::processInfill( const MeshPathConfigs& mesh_config, const SliceLayerPart& part) const { - if (extruder_nr != mesh.settings.get("infill_extruder_nr").extruder_nr) + if (extruder_nr != mesh.settings.get("infill_extruder_nr").extruder_nr_) { return false; } @@ -1643,7 +1643,7 @@ bool FffGcodeWriter::processMultiLayerInfill( const MeshPathConfigs& mesh_config, const SliceLayerPart& part) const { - if (extruder_nr != mesh.settings.get("infill_extruder_nr").extruder_nr) + if (extruder_nr != mesh.settings.get("infill_extruder_nr").extruder_nr_) { return false; } @@ -1780,7 +1780,7 @@ bool FffGcodeWriter::processSingleLayerInfill( const MeshPathConfigs& mesh_config, const SliceLayerPart& part) const { - if (extruder_nr != mesh.settings.get("infill_extruder_nr").extruder_nr) + if (extruder_nr != mesh.settings.get("infill_extruder_nr").extruder_nr_) { return false; } @@ -2283,7 +2283,7 @@ bool FffGcodeWriter::processInsets( const SliceLayerPart& part) const { bool added_something = false; - if (extruder_nr != mesh.settings.get("wall_0_extruder_nr").extruder_nr && extruder_nr != mesh.settings.get("wall_x_extruder_nr").extruder_nr) + if (extruder_nr != mesh.settings.get("wall_0_extruder_nr").extruder_nr_ && extruder_nr != mesh.settings.get("wall_x_extruder_nr").extruder_nr_) { return added_something; } @@ -2309,7 +2309,7 @@ bool FffGcodeWriter::processInsets( spiralize = true; } if (spiralize && gcode_layer.getLayerNr() == static_cast(initial_bottom_layers) - && extruder_nr == mesh.settings.get("wall_0_extruder_nr").extruder_nr) + && extruder_nr == mesh.settings.get("wall_0_extruder_nr").extruder_nr_) { // on the last normal layer first make the outer wall normally and then start a second outer wall from the same hight, but gradually moving upward added_something = true; gcode_layer.setIsInside(true); // going to print stuff inside print object @@ -2438,7 +2438,7 @@ bool FffGcodeWriter::processInsets( gcode_layer.setOverhangMask(Polygons()); } - if (spiralize && extruder_nr == mesh.settings.get("wall_0_extruder_nr").extruder_nr && ! part.spiral_wall.empty()) + if (spiralize && extruder_nr == mesh.settings.get("wall_0_extruder_nr").extruder_nr_ && ! part.spiral_wall.empty()) { added_something = true; gcode_layer.setIsInside(true); // going to print stuff inside print object @@ -2573,8 +2573,8 @@ bool FffGcodeWriter::processInsets( mesh.settings.get("travel_retract_before_outer_wall"), mesh.settings.get("wall_0_wipe_dist"), wall_x_wipe_dist, - mesh.settings.get("wall_0_extruder_nr").extruder_nr, - mesh.settings.get("wall_x_extruder_nr").extruder_nr, + mesh.settings.get("wall_0_extruder_nr").extruder_nr_, + mesh.settings.get("wall_x_extruder_nr").extruder_nr_, z_seam_config, part.wall_toolpaths); added_something |= wall_orderer.addToLayer(); @@ -2623,9 +2623,9 @@ bool FffGcodeWriter::processSkin( const MeshPathConfigs& mesh_config, const SliceLayerPart& part) const { - const size_t top_bottom_extruder_nr = mesh.settings.get("top_bottom_extruder_nr").extruder_nr; - const size_t roofing_extruder_nr = mesh.settings.get("roofing_extruder_nr").extruder_nr; - const size_t wall_0_extruder_nr = mesh.settings.get("wall_0_extruder_nr").extruder_nr; + const size_t top_bottom_extruder_nr = mesh.settings.get("top_bottom_extruder_nr").extruder_nr_; + const size_t roofing_extruder_nr = mesh.settings.get("roofing_extruder_nr").extruder_nr_; + const size_t wall_0_extruder_nr = mesh.settings.get("wall_0_extruder_nr").extruder_nr_; const size_t roofing_layer_count = std::min(mesh.settings.get("roofing_layer_count"), mesh.settings.get("top_layers")); if (extruder_nr != top_bottom_extruder_nr && extruder_nr != wall_0_extruder_nr && (extruder_nr != roofing_extruder_nr || roofing_layer_count <= 0)) { @@ -2678,7 +2678,7 @@ void FffGcodeWriter::processRoofing( const SkinPart& skin_part, bool& added_something) const { - const size_t roofing_extruder_nr = mesh.settings.get("roofing_extruder_nr").extruder_nr; + const size_t roofing_extruder_nr = mesh.settings.get("roofing_extruder_nr").extruder_nr_; if (extruder_nr != roofing_extruder_nr) { return; @@ -2723,7 +2723,7 @@ void FffGcodeWriter::processTopBottom( { return; // bridgeAngle requires a non-empty skin_fill. } - const size_t top_bottom_extruder_nr = mesh.settings.get("top_bottom_extruder_nr").extruder_nr; + const size_t top_bottom_extruder_nr = mesh.settings.get("top_bottom_extruder_nr").extruder_nr_; if (extruder_nr != top_bottom_extruder_nr) { return; @@ -2976,7 +2976,7 @@ void FffGcodeWriter::processSkinPrintFeature( if (! skin_paths.empty()) { // Add skin-walls a.k.a. skin-perimeters, skin-insets. - const size_t skin_extruder_nr = mesh.settings.get("top_bottom_extruder_nr").extruder_nr; + const size_t skin_extruder_nr = mesh.settings.get("top_bottom_extruder_nr").extruder_nr_; if (extruder_nr == skin_extruder_nr) { constexpr bool retract_before_outer_wall = false; @@ -3111,10 +3111,10 @@ bool FffGcodeWriter::addSupportToGCode(const SliceDataStorage& storage, LayerPla } const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; - const size_t support_roof_extruder_nr = mesh_group_settings.get("support_roof_extruder_nr").extruder_nr; - const size_t support_bottom_extruder_nr = mesh_group_settings.get("support_bottom_extruder_nr").extruder_nr; - size_t support_infill_extruder_nr = (gcode_layer.getLayerNr() <= 0) ? mesh_group_settings.get("support_extruder_nr_layer_0").extruder_nr - : mesh_group_settings.get("support_infill_extruder_nr").extruder_nr; + const size_t support_roof_extruder_nr = mesh_group_settings.get("support_roof_extruder_nr").extruder_nr_; + const size_t support_bottom_extruder_nr = mesh_group_settings.get("support_bottom_extruder_nr").extruder_nr_; + size_t support_infill_extruder_nr = (gcode_layer.getLayerNr() <= 0) ? mesh_group_settings.get("support_extruder_nr_layer_0").extruder_nr_ + : mesh_group_settings.get("support_infill_extruder_nr").extruder_nr_; const SupportLayer& support_layer = storage.support.supportLayers[std::max(LayerIndex{ 0 }, gcode_layer.getLayerNr())]; if (support_layer.support_bottom.empty() && support_layer.support_roof.empty() && support_layer.support_infill_parts.empty()) @@ -3158,19 +3158,19 @@ bool FffGcodeWriter::processSupportInfill(const SliceDataStorage& storage, Layer } const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; - const size_t extruder_nr = (gcode_layer.getLayerNr() <= 0) ? mesh_group_settings.get("support_extruder_nr_layer_0").extruder_nr - : mesh_group_settings.get("support_infill_extruder_nr").extruder_nr; + const size_t extruder_nr = (gcode_layer.getLayerNr() <= 0) ? mesh_group_settings.get("support_extruder_nr_layer_0").extruder_nr_ + : mesh_group_settings.get("support_infill_extruder_nr").extruder_nr_; const ExtruderTrain& infill_extruder = Application::getInstance().current_slice->scene.extruders[extruder_nr]; - coord_t default_support_line_distance = infill_extruder.settings.get("support_line_distance"); + coord_t default_support_line_distance = infill_extruder.settings_.get("support_line_distance"); // To improve adhesion for the "support initial layer" the first layer might have different properties if (gcode_layer.getLayerNr() == 0) { - default_support_line_distance = infill_extruder.settings.get("support_initial_layer_line_distance"); + default_support_line_distance = infill_extruder.settings_.get("support_initial_layer_line_distance"); } - const coord_t default_support_infill_overlap = infill_extruder.settings.get("infill_overlap_mm"); + const coord_t default_support_infill_overlap = infill_extruder.settings_.get("infill_overlap_mm"); // Helper to get the support infill angle const auto get_support_infill_angle = [](const SupportStorage& support_storage, const int layer_nr) @@ -3187,13 +3187,13 @@ bool FffGcodeWriter::processSupportInfill(const SliceDataStorage& storage, Layer const AngleDegrees support_infill_angle = get_support_infill_angle(storage.support, gcode_layer.getLayerNr()); constexpr size_t infill_multiplier = 1; // there is no frontend setting for this (yet) - const size_t wall_line_count = infill_extruder.settings.get("support_wall_count"); - const coord_t max_resolution = infill_extruder.settings.get("meshfix_maximum_resolution"); - const coord_t max_deviation = infill_extruder.settings.get("meshfix_maximum_deviation"); - coord_t default_support_line_width = infill_extruder.settings.get("support_line_width"); + const size_t wall_line_count = infill_extruder.settings_.get("support_wall_count"); + const coord_t max_resolution = infill_extruder.settings_.get("meshfix_maximum_resolution"); + const coord_t max_deviation = infill_extruder.settings_.get("meshfix_maximum_deviation"); + coord_t default_support_line_width = infill_extruder.settings_.get("support_line_width"); if (gcode_layer.getLayerNr() == 0 && mesh_group_settings.get("adhesion_type") != EPlatformAdhesion::RAFT) { - default_support_line_width *= infill_extruder.settings.get("initial_layer_line_width_factor"); + default_support_line_width *= infill_extruder.settings_.get("initial_layer_line_width_factor"); } // Helper to get the support pattern @@ -3205,11 +3205,11 @@ bool FffGcodeWriter::processSupportInfill(const SliceDataStorage& storage, Layer } return pattern; }; - const EFillMethod support_pattern = get_support_pattern(infill_extruder.settings.get("support_pattern"), gcode_layer.getLayerNr()); + const EFillMethod support_pattern = get_support_pattern(infill_extruder.settings_.get("support_pattern"), gcode_layer.getLayerNr()); - const auto zig_zaggify_infill = infill_extruder.settings.get("zig_zaggify_support"); - const auto skip_some_zags = infill_extruder.settings.get("support_skip_some_zags"); - const auto zag_skip_count = infill_extruder.settings.get("support_zag_skip_count"); + const auto zig_zaggify_infill = infill_extruder.settings_.get("zig_zaggify_support"); + const auto skip_some_zags = infill_extruder.settings_.get("support_skip_some_zags"); + const auto zag_skip_count = infill_extruder.settings_.get("support_zag_skip_count"); // create a list of outlines and use PathOrderOptimizer to optimize the travel move PathOrderOptimizer island_order_optimizer_initial(gcode_layer.getLastPlannedPositionOrStartingPosition()); @@ -3221,8 +3221,8 @@ bool FffGcodeWriter::processSupportInfill(const SliceDataStorage& storage, Layer island_order_optimizer_initial.optimize(); island_order_optimizer.optimize(); - const auto support_connect_zigzags = infill_extruder.settings.get("support_connect_zigzags"); - const auto support_structure = infill_extruder.settings.get("support_structure"); + const auto support_connect_zigzags = infill_extruder.settings_.get("support_connect_zigzags"); + const auto support_structure = infill_extruder.settings_.get("support_structure"); const Point infill_origin; constexpr bool use_endpieces = true; @@ -3252,7 +3252,7 @@ bool FffGcodeWriter::processSupportInfill(const SliceDataStorage& storage, Layer *this, storage, gcode_layer, - infill_extruder.settings, + infill_extruder.settings_, extruder_nr, config, config, @@ -3298,7 +3298,7 @@ bool FffGcodeWriter::processSupportInfill(const SliceDataStorage& storage, Layer { support_line_distance_here /= 2; } - const Polygons& area = Simplify(infill_extruder.settings).polygon(part.infill_area_per_combine_per_density[density_idx][combine_idx]); + const Polygons& area = Simplify(infill_extruder.settings_).polygon(part.infill_area_per_combine_per_density[density_idx][combine_idx]); constexpr size_t wall_count = 0; // Walls are generated somewhere else, so their layers aren't vertically combined. const coord_t small_area_width = 0; @@ -3332,18 +3332,18 @@ bool FffGcodeWriter::processSupportInfill(const SliceDataStorage& storage, Layer wall_toolpaths_here, support_polygons, support_lines, - infill_extruder.settings, + infill_extruder.settings_, gcode_layer.getLayerNr(), SectionType::SUPPORT, storage.support.cross_fill_provider); } - if (need_travel_to_end_of_last_spiral && infill_extruder.settings.get("magic_spiralize")) + if (need_travel_to_end_of_last_spiral && infill_extruder.settings_.get("magic_spiralize")) { if ((! wall_toolpaths.empty() || ! support_polygons.empty() || ! support_lines.empty())) { int layer_nr = gcode_layer.getLayerNr(); - if (layer_nr > (int)infill_extruder.settings.get("initial_bottom_layers")) + if (layer_nr > (int)infill_extruder.settings_.get("initial_bottom_layers")) { // bit of subtlety here... support is being used on a spiralized model and to ensure the travel move from the end of the last spiral // to the start of the support does not go through the model we have to tell the slicer what the current location of the nozzle is @@ -3361,7 +3361,7 @@ bool FffGcodeWriter::processSupportInfill(const SliceDataStorage& storage, Layer gcode_layer.setIsInside(false); // going to print stuff outside print object, i.e. support - const bool alternate_inset_direction = infill_extruder.settings.get("material_alternate_walls"); + const bool alternate_inset_direction = infill_extruder.settings_.get("material_alternate_walls"); const bool alternate_layer_print_direction = alternate_inset_direction && gcode_layer.getLayerNr() % 2 == 1; if (! support_polygons.empty()) @@ -3428,7 +3428,7 @@ bool FffGcodeWriter::processSupportInfill(const SliceDataStorage& storage, Layer *this, storage, gcode_layer, - infill_extruder.settings, + infill_extruder.settings_, extruder_nr, config, config, @@ -3463,10 +3463,10 @@ bool FffGcodeWriter::addSupportRoofsToGCode( return false; // No need to generate support roof if there's no support. } - const size_t roof_extruder_nr = Application::getInstance().current_slice->scene.current_mesh_group->settings.get("support_roof_extruder_nr").extruder_nr; + const size_t roof_extruder_nr = Application::getInstance().current_slice->scene.current_mesh_group->settings.get("support_roof_extruder_nr").extruder_nr_; const ExtruderTrain& roof_extruder = Application::getInstance().current_slice->scene.extruders[roof_extruder_nr]; - const EFillMethod pattern = roof_extruder.settings.get("support_roof_pattern"); + const EFillMethod pattern = roof_extruder.settings_.get("support_roof_pattern"); AngleDegrees fill_angle = 0; if (! storage.support.support_roof_angles.empty()) { @@ -3480,8 +3480,8 @@ bool FffGcodeWriter::addSupportRoofsToGCode( constexpr coord_t support_roof_overlap = 0; // the roofs should never be expanded outwards constexpr size_t infill_multiplier = 1; constexpr coord_t extra_infill_shift = 0; - const auto wall_line_count = roof_extruder.settings.get("support_roof_wall_count"); - const coord_t small_area_width = roof_extruder.settings.get("min_even_wall_line_width") * 2; // Maximum width of a region that can still be filled with one wall. + const auto wall_line_count = roof_extruder.settings_.get("support_roof_wall_count"); + const coord_t small_area_width = roof_extruder.settings_.get("min_even_wall_line_width") * 2; // Maximum width of a region that can still be filled with one wall. const Point infill_origin; constexpr bool skip_stitching = false; constexpr bool fill_gaps = true; @@ -3490,14 +3490,14 @@ bool FffGcodeWriter::addSupportRoofsToGCode( constexpr bool skip_some_zags = false; constexpr size_t zag_skip_count = 0; constexpr coord_t pocket_size = 0; - const coord_t max_resolution = roof_extruder.settings.get("meshfix_maximum_resolution"); - const coord_t max_deviation = roof_extruder.settings.get("meshfix_maximum_deviation"); + const coord_t max_resolution = roof_extruder.settings_.get("meshfix_maximum_resolution"); + const coord_t max_deviation = roof_extruder.settings_.get("meshfix_maximum_deviation"); - coord_t support_roof_line_distance = roof_extruder.settings.get("support_roof_line_distance"); - const coord_t support_roof_line_width = roof_extruder.settings.get("support_roof_line_width"); + coord_t support_roof_line_distance = roof_extruder.settings_.get("support_roof_line_distance"); + const coord_t support_roof_line_width = roof_extruder.settings_.get("support_roof_line_width"); if (gcode_layer.getLayerNr() == 0 && support_roof_line_distance < 2 * support_roof_line_width) { // if roof is dense - support_roof_line_distance *= roof_extruder.settings.get("initial_layer_line_width_factor"); + support_roof_line_distance *= roof_extruder.settings_.get("initial_layer_line_width_factor"); } Polygons infill_outline = support_roof_outlines; @@ -3508,7 +3508,7 @@ bool FffGcodeWriter::addSupportRoofsToGCode( wall = support_layer.support_roof.offset(-support_roof_line_width / 2); infill_outline = wall.offset(-support_roof_line_width / 2); } - infill_outline = Simplify(roof_extruder.settings).polygon(infill_outline); + infill_outline = Simplify(roof_extruder.settings_).polygon(infill_outline); Infill roof_computation( pattern, @@ -3537,7 +3537,7 @@ bool FffGcodeWriter::addSupportRoofsToGCode( Polygons roof_polygons; std::vector roof_paths; Polygons roof_lines; - roof_computation.generate(roof_paths, roof_polygons, roof_lines, roof_extruder.settings, gcode_layer.getLayerNr(), SectionType::SUPPORT); + roof_computation.generate(roof_paths, roof_polygons, roof_lines, roof_extruder.settings_, gcode_layer.getLayerNr(), SectionType::SUPPORT); if ((gcode_layer.getLayerNr() == 0 && wall.empty()) || (gcode_layer.getLayerNr() > 0 && roof_paths.empty() && roof_polygons.empty() && roof_lines.empty())) { return false; // We didn't create any support roof. @@ -3564,7 +3564,7 @@ bool FffGcodeWriter::addSupportRoofsToGCode( *this, storage, gcode_layer, - roof_extruder.settings, + roof_extruder.settings_, roof_extruder_nr, config, config, @@ -3592,10 +3592,10 @@ bool FffGcodeWriter::addSupportBottomsToGCode(const SliceDataStorage& storage, L return false; // No need to generate support bottoms if there's no support. } - const size_t bottom_extruder_nr = Application::getInstance().current_slice->scene.current_mesh_group->settings.get("support_bottom_extruder_nr").extruder_nr; + const size_t bottom_extruder_nr = Application::getInstance().current_slice->scene.current_mesh_group->settings.get("support_bottom_extruder_nr").extruder_nr_; const ExtruderTrain& bottom_extruder = Application::getInstance().current_slice->scene.extruders[bottom_extruder_nr]; - const EFillMethod pattern = bottom_extruder.settings.get("support_bottom_pattern"); + const EFillMethod pattern = bottom_extruder.settings_.get("support_bottom_pattern"); AngleDegrees fill_angle = 0; if (! storage.support.support_bottom_angles.empty()) { @@ -3609,8 +3609,8 @@ bool FffGcodeWriter::addSupportBottomsToGCode(const SliceDataStorage& storage, L constexpr coord_t support_bottom_overlap = 0; // the bottoms should never be expanded outwards constexpr size_t infill_multiplier = 1; constexpr coord_t extra_infill_shift = 0; - const auto wall_line_count = bottom_extruder.settings.get("support_bottom_wall_count"); - const coord_t small_area_width = bottom_extruder.settings.get("min_even_wall_line_width") * 2; // Maximum width of a region that can still be filled with one wall. + const auto wall_line_count = bottom_extruder.settings_.get("support_bottom_wall_count"); + const coord_t small_area_width = bottom_extruder.settings_.get("min_even_wall_line_width") * 2; // Maximum width of a region that can still be filled with one wall. const Point infill_origin; constexpr bool skip_stitching = false; @@ -3620,10 +3620,10 @@ bool FffGcodeWriter::addSupportBottomsToGCode(const SliceDataStorage& storage, L constexpr bool skip_some_zags = false; constexpr int zag_skip_count = 0; constexpr coord_t pocket_size = 0; - const coord_t max_resolution = bottom_extruder.settings.get("meshfix_maximum_resolution"); - const coord_t max_deviation = bottom_extruder.settings.get("meshfix_maximum_deviation"); + const coord_t max_resolution = bottom_extruder.settings_.get("meshfix_maximum_resolution"); + const coord_t max_deviation = bottom_extruder.settings_.get("meshfix_maximum_deviation"); - const coord_t support_bottom_line_distance = bottom_extruder.settings.get( + const coord_t support_bottom_line_distance = bottom_extruder.settings_.get( "support_bottom_line_distance"); // note: no need to apply initial line width factor; support bottoms cannot exist on the first layer Infill bottom_computation( pattern, @@ -3652,7 +3652,7 @@ bool FffGcodeWriter::addSupportBottomsToGCode(const SliceDataStorage& storage, L Polygons bottom_polygons; std::vector bottom_paths; Polygons bottom_lines; - bottom_computation.generate(bottom_paths, bottom_polygons, bottom_lines, bottom_extruder.settings, gcode_layer.getLayerNr(), SectionType::SUPPORT); + bottom_computation.generate(bottom_paths, bottom_polygons, bottom_lines, bottom_extruder.settings_, gcode_layer.getLayerNr(), SectionType::SUPPORT); if (bottom_paths.empty() && bottom_polygons.empty() && bottom_lines.empty()) { return false; @@ -3675,7 +3675,7 @@ bool FffGcodeWriter::addSupportBottomsToGCode(const SliceDataStorage& storage, L *this, storage, gcode_layer, - bottom_extruder.settings, + bottom_extruder.settings_, bottom_extruder_nr, config, config, @@ -3710,10 +3710,10 @@ void FffGcodeWriter::setExtruder_addPrime(const SliceDataStorage& storage, Layer // We always prime an extruder, but whether it will be a prime blob/poop depends on if prime blob is enabled. // This is decided in GCodeExport::writePrimeTrain(). - if (train.settings.get("prime_blob_enable")) // Don't travel to the prime-blob position if not enabled though. + if (train.settings_.get("prime_blob_enable")) // Don't travel to the prime-blob position if not enabled though. { - bool prime_pos_is_abs = train.settings.get("extruder_prime_pos_abs"); - Point prime_pos = Point(train.settings.get("extruder_prime_pos_x"), train.settings.get("extruder_prime_pos_y")); + bool prime_pos_is_abs = train.settings_.get("extruder_prime_pos_abs"); + Point prime_pos = Point(train.settings_.get("extruder_prime_pos_x"), train.settings_.get("extruder_prime_pos_y")); gcode_layer.addTravel(prime_pos_is_abs ? prime_pos : gcode_layer.getLastPlannedPositionOrStartingPosition() + prime_pos); gcode_layer.planPrime(); } @@ -3764,7 +3764,7 @@ void FffGcodeWriter::finalize() for (size_t extruder_nr = 0; extruder_nr < scene.extruders.size(); extruder_nr++) { filament_used.emplace_back(gcode.getTotalFilamentUsed(extruder_nr)); - material_ids.emplace_back(scene.extruders[extruder_nr].settings.get("material_guid")); + material_ids.emplace_back(scene.extruders[extruder_nr].settings_.get("material_guid")); extruder_is_used.push_back(gcode.getExtruderIsUsed(extruder_nr)); } std::string prefix = gcode.getFileHeader(extruder_is_used, &print_time, filament_used, material_ids); diff --git a/src/FffPolygonGenerator.cpp b/src/FffPolygonGenerator.cpp index 4e59f05ab8..c4a7259538 100644 --- a/src/FffPolygonGenerator.cpp +++ b/src/FffPolygonGenerator.cpp @@ -325,12 +325,12 @@ bool FffPolygonGenerator::sliceModel(MeshGroup* meshgroup, TimeKeeper& timeKeepe if (has_raft) { const ExtruderTrain& train = mesh_group_settings.get("raft_surface_extruder_nr"); - layer.printZ += Raft::getTotalThickness() + train.settings.get("raft_airgap") - - train.settings.get("layer_0_z_overlap"); // shift all layers (except 0) down + layer.printZ += Raft::getTotalThickness() + train.settings_.get("raft_airgap") + - train.settings_.get("layer_0_z_overlap"); // shift all layers (except 0) down if (layer_nr == 0) { - layer.printZ += train.settings.get("layer_0_z_overlap"); // undo shifting down of first layer + layer.printZ += train.settings_.get("layer_0_z_overlap"); // undo shifting down of first layer } } } @@ -879,13 +879,13 @@ void FffPolygonGenerator::computePrintHeightStatistics(SliceDataStorage& storage Scene& scene = Application::getInstance().current_slice->scene; const Settings& mesh_group_settings = scene.current_mesh_group->settings; const size_t support_infill_extruder_nr - = mesh_group_settings.get("support_infill_extruder_nr").extruder_nr; // TODO: Support extruder should be configurable per object. + = mesh_group_settings.get("support_infill_extruder_nr").extruder_nr_; // TODO: Support extruder should be configurable per object. max_print_height_per_extruder[support_infill_extruder_nr] = std::max(max_print_height_per_extruder[support_infill_extruder_nr], storage.support.layer_nr_max_filled_layer); const size_t support_roof_extruder_nr - = mesh_group_settings.get("support_roof_extruder_nr").extruder_nr; // TODO: Support roof extruder should be configurable per object. + = mesh_group_settings.get("support_roof_extruder_nr").extruder_nr_; // TODO: Support roof extruder should be configurable per object. max_print_height_per_extruder[support_roof_extruder_nr] = std::max(max_print_height_per_extruder[support_roof_extruder_nr], storage.support.layer_nr_max_filled_layer); const size_t support_bottom_extruder_nr - = mesh_group_settings.get("support_bottom_extruder_nr").extruder_nr; // TODO: Support bottom extruder should be configurable per object. + = mesh_group_settings.get("support_bottom_extruder_nr").extruder_nr_; // TODO: Support bottom extruder should be configurable per object. max_print_height_per_extruder[support_bottom_extruder_nr] = std::max(max_print_height_per_extruder[support_bottom_extruder_nr], storage.support.layer_nr_max_filled_layer); // Height of where the platform adhesion reaches. @@ -898,19 +898,19 @@ void FffPolygonGenerator::computePrintHeightStatistics(SliceDataStorage& storage const std::vector skirt_brim_extruder_trains = mesh_group_settings.get>("skirt_brim_extruder_nr"); for (ExtruderTrain* train : skirt_brim_extruder_trains) { - const size_t skirt_brim_extruder_nr = train->extruder_nr; + const size_t skirt_brim_extruder_nr = train->extruder_nr_; max_print_height_per_extruder[skirt_brim_extruder_nr] = std::max(0, max_print_height_per_extruder[skirt_brim_extruder_nr]); // Includes layer 0. } break; } case EPlatformAdhesion::RAFT: { - const size_t base_extruder_nr = mesh_group_settings.get("raft_base_extruder_nr").extruder_nr; + const size_t base_extruder_nr = mesh_group_settings.get("raft_base_extruder_nr").extruder_nr_; max_print_height_per_extruder[base_extruder_nr] = std::max(-raft_layers, max_print_height_per_extruder[base_extruder_nr]); // Includes the lowest raft layer. - const size_t interface_extruder_nr = mesh_group_settings.get("raft_interface_extruder_nr").extruder_nr; + const size_t interface_extruder_nr = mesh_group_settings.get("raft_interface_extruder_nr").extruder_nr_; max_print_height_per_extruder[interface_extruder_nr] = std::max(-raft_layers + 1, max_print_height_per_extruder[interface_extruder_nr]); // Includes the second-lowest raft layer. - const size_t surface_extruder_nr = mesh_group_settings.get("raft_surface_extruder_nr").extruder_nr; + const size_t surface_extruder_nr = mesh_group_settings.get("raft_surface_extruder_nr").extruder_nr_; max_print_height_per_extruder[surface_extruder_nr] = std::max(-1, max_print_height_per_extruder[surface_extruder_nr]); // Includes up to the first layer below the model (so -1). break; @@ -980,7 +980,7 @@ void FffPolygonGenerator::processOozeShield(SliceDataStorage& storage) { if (! extruder_is_used[extruder_nr]) continue; - max_line_width = std::max(max_line_width, extruders[extruder_nr].settings.get("skirt_brim_line_width")); + max_line_width = std::max(max_line_width, extruders[extruder_nr].settings_.get("skirt_brim_line_width")); } } for (LayerIndex layer_nr = 0; layer_nr <= storage.max_print_height_second_to_last_extruder; layer_nr++) @@ -1018,8 +1018,8 @@ void FffPolygonGenerator::processDraftShield(SliceDataStorage& storage) coord_t maximum_deviation = std::numeric_limits::max(); for (const ExtruderTrain& extruder : Application::getInstance().current_slice->scene.extruders) { - maximum_resolution = std::max(maximum_resolution, extruder.settings.get("meshfix_maximum_resolution")); - maximum_deviation = std::min(maximum_deviation, extruder.settings.get("meshfix_maximum_deviation")); + maximum_resolution = std::max(maximum_resolution, extruder.settings_.get("meshfix_maximum_resolution")); + maximum_deviation = std::min(maximum_deviation, extruder.settings_.get("meshfix_maximum_deviation")); } storage.draft_protection_shield = Simplify(maximum_resolution, maximum_deviation, 0).polygon(storage.draft_protection_shield); if (mesh_group_settings.get("prime_tower_enable")) @@ -1032,7 +1032,7 @@ void FffPolygonGenerator::processDraftShield(SliceDataStorage& storage) { if (! extruder_is_used[extruder_nr]) continue; - max_line_width = std::max(max_line_width, extruders[extruder_nr].settings.get("skirt_brim_line_width")); + max_line_width = std::max(max_line_width, extruders[extruder_nr].settings_.get("skirt_brim_line_width")); } } storage.draft_protection_shield = storage.draft_protection_shield.difference(storage.primeTower.getGroundPoly().offset(max_line_width / 2)); @@ -1063,8 +1063,8 @@ void FffPolygonGenerator::processPlatformAdhesion(SliceDataStorage& storage) for (const auto& extruder : Application::getInstance().current_slice->scene.extruders) { - Simplify simplifier(extruder.settings); - for (auto skirt_brim_line : storage.skirt_brim[extruder.extruder_nr]) + Simplify simplifier(extruder.settings_); + for (auto skirt_brim_line : storage.skirt_brim[extruder.extruder_nr_]) { skirt_brim_line.closed_polygons = simplifier.polygon(skirt_brim_line.closed_polygons); skirt_brim_line.open_polylines = simplifier.polyline(skirt_brim_line.open_polylines); diff --git a/src/InterlockingGenerator.cpp b/src/InterlockingGenerator.cpp index 86bb724ceb..2cafc9b691 100644 --- a/src/InterlockingGenerator.cpp +++ b/src/InterlockingGenerator.cpp @@ -33,11 +33,11 @@ void InterlockingGenerator::generateInterlockingStructure(std::vector& for (size_t mesh_a_idx = 0; mesh_a_idx < volumes.size(); mesh_a_idx++) { Slicer& mesh_a = *volumes[mesh_a_idx]; - size_t extruder_nr_a = mesh_a.mesh->settings_.get("wall_0_extruder_nr").extruder_nr; + size_t extruder_nr_a = mesh_a.mesh->settings_.get("wall_0_extruder_nr").extruder_nr_; for (size_t mesh_b_idx = mesh_a_idx + 1; mesh_b_idx < volumes.size(); mesh_b_idx++) { Slicer& mesh_b = *volumes[mesh_b_idx]; - size_t extruder_nr_b = mesh_b.mesh->settings_.get("wall_0_extruder_nr").extruder_nr; + size_t extruder_nr_b = mesh_b.mesh->settings_.get("wall_0_extruder_nr").extruder_nr_; if (! mesh_a.mesh->canInterlock() || ! mesh_b.mesh->canInterlock()) { diff --git a/src/LayerPlan.cpp b/src/LayerPlan.cpp index 18655e5e72..da66aa7601 100644 --- a/src/LayerPlan.cpp +++ b/src/LayerPlan.cpp @@ -121,7 +121,7 @@ LayerPlan::LayerPlan( } for (const ExtruderTrain& extruder : Application::getInstance().current_slice->scene.extruders) { - layer_start_pos_per_extruder.emplace_back(extruder.settings.get("layer_start_x"), extruder.settings.get("layer_start_y")); + layer_start_pos_per_extruder.emplace_back(extruder.settings_.get("layer_start_x"), extruder.settings_.get("layer_start_y")); } extruder_plans.reserve(Application::getInstance().current_slice->scene.extruders.size()); extruder_plans.emplace_back( @@ -235,15 +235,15 @@ bool LayerPlan::setExtruder(const size_t extruder_nr) setIsInside(false); { // handle end position of the prev extruder ExtruderTrain* extruder = getLastPlannedExtruderTrain(); - const bool end_pos_absolute = extruder->settings.get("machine_extruder_end_pos_abs"); - Point end_pos(extruder->settings.get("machine_extruder_end_pos_x"), extruder->settings.get("machine_extruder_end_pos_y")); + const bool end_pos_absolute = extruder->settings_.get("machine_extruder_end_pos_abs"); + Point end_pos(extruder->settings_.get("machine_extruder_end_pos_x"), extruder->settings_.get("machine_extruder_end_pos_y")); if (! end_pos_absolute) { end_pos += getLastPlannedPositionOrStartingPosition(); } else { - const Point extruder_offset(extruder->settings.get("machine_nozzle_offset_x"), extruder->settings.get("machine_nozzle_offset_y")); + const Point extruder_offset(extruder->settings_.get("machine_nozzle_offset_x"), extruder->settings_.get("machine_nozzle_offset_y")); end_pos += extruder_offset; // absolute end pos is given as a head position } if (end_pos_absolute || last_planned_position) @@ -268,15 +268,15 @@ bool LayerPlan::setExtruder(const size_t extruder_nr) { // handle starting pos of the new extruder ExtruderTrain* extruder = getLastPlannedExtruderTrain(); - const bool start_pos_absolute = extruder->settings.get("machine_extruder_start_pos_abs"); - Point start_pos(extruder->settings.get("machine_extruder_start_pos_x"), extruder->settings.get("machine_extruder_start_pos_y")); + const bool start_pos_absolute = extruder->settings_.get("machine_extruder_start_pos_abs"); + Point start_pos(extruder->settings_.get("machine_extruder_start_pos_x"), extruder->settings_.get("machine_extruder_start_pos_y")); if (! start_pos_absolute) { start_pos += getLastPlannedPositionOrStartingPosition(); } else { - Point extruder_offset(extruder->settings.get("machine_nozzle_offset_x"), extruder->settings.get("machine_nozzle_offset_y")); + Point extruder_offset(extruder->settings_.get("machine_nozzle_offset_x"), extruder->settings_.get("machine_nozzle_offset_y")); start_pos += extruder_offset; // absolute start pos is given as a head position } if (start_pos_absolute || last_planned_position) @@ -341,7 +341,7 @@ GCodePath& LayerPlan::addTravel(const Point& p, const bool force_retract, const bool combed = false; const ExtruderTrain* extruder = getLastPlannedExtruderTrain(); - const Settings& mesh_or_extruder_settings = current_mesh ? current_mesh->settings : extruder->settings; + const Settings& mesh_or_extruder_settings = current_mesh ? current_mesh->settings : extruder->settings_; const bool is_first_travel_of_extruder_after_switch = extruder_plans.back().paths_.size() == 1 && (extruder_plans.size() > 1 || last_extruder_previous_layer != getExtruder()); @@ -999,7 +999,7 @@ void LayerPlan::addWall( const coord_t small_feature_max_length = settings.get("small_feature_max_length"); const bool is_small_feature = (small_feature_max_length > 0) && (layer_nr == 0 || wall.inset_idx == 0) && cura::shorterThan(wall, small_feature_max_length); Ratio small_feature_speed_factor = settings.get((layer_nr == 0) ? "small_feature_speed_factor_0" : "small_feature_speed_factor"); - const Velocity min_speed = fan_speed_layer_time_settings_per_extruder[getLastPlannedExtruderTrain()->extruder_nr].cool_min_speed; + const Velocity min_speed = fan_speed_layer_time_settings_per_extruder[getLastPlannedExtruderTrain()->extruder_nr_].cool_min_speed; small_feature_speed_factor = std::max((double)small_feature_speed_factor, (double)(min_speed / non_bridge_config.getSpeed())); const coord_t max_area_deviation = std::max(settings.get("meshfix_maximum_extrusion_area_deviation"), 1); // Square micrometres! const coord_t max_resolution = std::max(settings.get("meshfix_maximum_resolution"), coord_t(1)); @@ -1911,7 +1911,7 @@ void LayerPlan::writeGCode(GCodeExport& gcode) gcode.insertWipeScript(wipe_config); gcode.ResetLastEValueAfterWipe(extruder_nr); } - else if (layer_nr != 0 && Application::getInstance().current_slice->scene.extruders[extruder_nr].settings.get("retract_at_layer_change")) + else if (layer_nr != 0 && Application::getInstance().current_slice->scene.extruders[extruder_nr].settings_.get("retract_at_layer_change")) { // only do the retract if the paths are not spiralized if (! mesh_group_settings.get("magic_spiralize")) @@ -1945,7 +1945,7 @@ void LayerPlan::writeGCode(GCodeExport& gcode) if (path.perform_prime) { - gcode.writePrimeTrain(extruder.settings.get("speed_travel")); + gcode.writePrimeTrain(extruder.settings_.get("speed_travel")); // Don't update cumulative path time, as ComputeNaiveTimeEstimates also doesn't. gcode.writeRetraction(retraction_config->retraction_config); } @@ -2074,7 +2074,7 @@ void LayerPlan::writeGCode(GCodeExport& gcode) // Before the final travel, move up to the next layer height, on the current spot, with a sensible speed. Point3 current_position = gcode.getPosition(); current_position.z_ = final_travel_z; - gcode.writeTravel(current_position, extruder.settings.get("speed_z_hop")); + gcode.writeTravel(current_position, extruder.settings_.get("speed_z_hop")); // Prevent the final travel(s) from resetting to the 'previous' layer height. gcode.setZ(final_travel_z); @@ -2099,7 +2099,7 @@ void LayerPlan::writeGCode(GCodeExport& gcode) const double path_fan_speed = path.getFanSpeed(); gcode.writeFanCommand(path_fan_speed != GCodePathConfig::FAN_SPEED_DEFAULT ? path_fan_speed : extruder_plan.getFanSpeed()); - bool coasting = extruder.settings.get("coasting_enable"); + bool coasting = extruder.settings_.get("coasting_enable"); if (coasting) { coasting = writePathWithCoasting(gcode, extruder_plan_idx, path_idx, layer_thickness, insertTempOnTime); @@ -2168,13 +2168,13 @@ void LayerPlan::writeGCode(GCodeExport& gcode) } } // paths for this extruder /\ . - if (extruder.settings.get("cool_lift_head") && extruder_plan.extra_time_ > 0.0) + if (extruder.settings_.get("cool_lift_head") && extruder_plan.extra_time_ > 0.0) { gcode.writeComment("Small layer, adding delay"); const RetractionAndWipeConfig& retraction_config = current_mesh ? current_mesh->retraction_wipe_config : storage.retraction_wipe_config_per_extruder[gcode.getExtruderNr()]; gcode.writeRetraction(retraction_config.retraction_config); - if (extruder_plan_idx == extruder_plans.size() - 1 || ! extruder.settings.get("machine_extruder_end_pos_abs")) + if (extruder_plan_idx == extruder_plans.size() - 1 || ! extruder.settings_.get("machine_extruder_end_pos_abs")) { // only do the z-hop if it's the last extruder plan; otherwise it's already at the switching bay area // or do it anyway when we switch extruder in-place gcode.writeZhopStart(MM2INT(3.0)); @@ -2250,7 +2250,7 @@ bool LayerPlan::writePathWithCoasting( { ExtruderPlan& extruder_plan = extruder_plans[extruder_plan_idx]; const ExtruderTrain& extruder = Application::getInstance().current_slice->scene.extruders[extruder_plan.extruder_nr_]; - const double coasting_volume = extruder.settings.get("coasting_volume"); + const double coasting_volume = extruder.settings_.get("coasting_volume"); if (coasting_volume <= 0) { return false; @@ -2268,7 +2268,7 @@ bool LayerPlan::writePathWithCoasting( const coord_t coasting_dist = MM2INT(MM2_2INT(coasting_volume) / layer_thickness) / path.config.getLineWidth(); // closing brackets of MM2INT at weird places for precision issues - const double coasting_min_volume = extruder.settings.get("coasting_min_volume"); + const double coasting_min_volume = extruder.settings_.get("coasting_min_volume"); const coord_t coasting_min_dist = MM2INT(MM2_2INT(coasting_min_volume + coasting_volume) / layer_thickness) / path.config.getLineWidth(); // closing brackets of MM2INT at weird places for precision issues // /\ the minimal distance when coasting will coast the full coasting volume instead of linearly less with linearly smaller paths @@ -2362,7 +2362,7 @@ bool LayerPlan::writePathWithCoasting( auto [_, time] = extruder_plan.getPointToPointTime(prev_pt, path.points[point_idx], path); insertTempOnTime(time, path_idx); - const Ratio coasting_speed_modifier = extruder.settings.get("coasting_speed"); + const Ratio coasting_speed_modifier = extruder.settings_.get("coasting_speed"); const Velocity speed = Velocity(coasting_speed_modifier * path.config.getSpeed()); gcode.writeTravel(path.points[point_idx], speed); @@ -2420,7 +2420,7 @@ void LayerPlan::applyBackPressureCompensation() for (auto& extruder_plan : extruder_plans) { const Ratio back_pressure_compensation - = Application::getInstance().current_slice->scene.extruders[extruder_plan.extruder_nr_].settings.get("speed_equalize_flow_width_factor"); + = Application::getInstance().current_slice->scene.extruders[extruder_plan.extruder_nr_].settings_.get("speed_equalize_flow_width_factor"); if (back_pressure_compensation != 0.0) { extruder_plan.applyBackPressureCompensation(back_pressure_compensation); diff --git a/src/LayerPlanBuffer.cpp b/src/LayerPlanBuffer.cpp index f3185deeeb..7502bf2cc2 100644 --- a/src/LayerPlanBuffer.cpp +++ b/src/LayerPlanBuffer.cpp @@ -96,7 +96,7 @@ void LayerPlanBuffer::addConnectingTravelMove(LayerPlan* prev_layer, const Layer if (! prev_layer->last_planned_position || *prev_layer->last_planned_position != first_location_new_layer) { const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; - const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[prev_layer->extruder_plans.back().extruder_nr_].settings; + const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[prev_layer->extruder_plans.back().extruder_nr_].settings_; prev_layer->setIsInside(new_layer_destination_state->second); const bool force_retract = extruder_settings.get("retract_at_layer_change") || (mesh_group_settings.get("travel_retract_before_outer_wall") @@ -167,7 +167,7 @@ Preheat::WarmUpResult LayerPlanBuffer::computeStandbyTempPlan(std::vectorscene.extruders[extruder].settings; + Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder].settings_; double initial_print_temp = extruder_plan.required_start_temperature_; Duration in_between_time = 0.0_s; // the duration during which the extruder isn't used @@ -212,7 +212,7 @@ Preheat::WarmUpResult LayerPlanBuffer::computeStandbyTempPlan(std::vectorscene.extruders[extruder_nr].settings.get("machine_nozzle_temp_enabled")) + if (! Application::getInstance().current_slice->scene.extruders[extruder_nr].settings_.get("machine_nozzle_temp_enabled")) { return; } @@ -248,7 +248,7 @@ void LayerPlanBuffer::insertPreheatCommand_multiExtrusion(std::vectorscene.extruders[extruder].settings; + const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder].settings_; if (! extruder_settings.get("machine_nozzle_temp_enabled")) { return; @@ -301,7 +301,7 @@ void LayerPlanBuffer::insertTempCommands(std::vector& extruder_pl if (prev_extruder != extruder) { // set previous extruder to standby temperature - const Settings& previous_extruder_settings = Application::getInstance().current_slice->scene.extruders[prev_extruder].settings; + const Settings& previous_extruder_settings = Application::getInstance().current_slice->scene.extruders[prev_extruder].settings_; extruder_plan.prev_extruder_standby_temp_ = previous_extruder_settings.get("material_standby_temperature"); } @@ -310,7 +310,7 @@ void LayerPlanBuffer::insertTempCommands(std::vector& extruder_pl insertPreheatCommand_singleExtrusion(*prev_extruder_plan, extruder, extruder_plan.required_start_temperature_); prev_extruder_plan->extrusion_temperature_command_ = --prev_extruder_plan->inserts_.end(); } - else if (Application::getInstance().current_slice->scene.extruders[extruder].settings.get("machine_extruders_share_heater")) + else if (Application::getInstance().current_slice->scene.extruders[extruder].settings_.get("machine_extruders_share_heater")) { // extruders share a heater so command the previous extruder to change to the temperature required for this extruder insertPreheatCommand_singleExtrusion(*prev_extruder_plan, prev_extruder, extruder_plan.required_start_temperature_); @@ -333,7 +333,7 @@ void LayerPlanBuffer::insertPrintTempCommand(ExtruderPlan& extruder_plan) const double print_temp = *extruder_plan.extrusion_temperature_; const unsigned int extruder = extruder_plan.extruder_nr_; - const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder].settings; + const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder].settings_; if (! extruder_settings.get("machine_nozzle_temp_enabled")) { return; @@ -362,7 +362,7 @@ void LayerPlanBuffer::insertFinalPrintTempCommand(std::vector& ex { ExtruderPlan& last_extruder_plan = *extruder_plans[last_extruder_plan_idx]; const size_t extruder = last_extruder_plan.extruder_nr_; - const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder].settings; + const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder].settings_; if (! extruder_settings.get("machine_nozzle_temp_enabled")) { return; @@ -516,7 +516,7 @@ void LayerPlanBuffer::insertTempCommands() const size_t overall_extruder_plan_idx = extruder_plans.size() - layer_plan.extruder_plans.size() + extruder_plan_idx; ExtruderPlan& extruder_plan = layer_plan.extruder_plans[extruder_plan_idx]; size_t extruder = extruder_plan.extruder_nr_; - const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder].settings; + const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder].settings_; Duration time = extruder_plan.estimates_.getTotalUnretractedTime(); Ratio avg_flow; if (time > 0.0) @@ -560,7 +560,7 @@ void LayerPlanBuffer::insertTempCommands() size_t extruder = extruder_plan.extruder_nr_; for (size_t extruder_idx = 0; extruder_idx < scene.extruders.size(); extruder_idx++) { // set temperature of the first nozzle, turn other nozzles down - const Settings& other_extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder_idx].settings; + const Settings& other_extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder_idx].settings_; if (scene.current_mesh_group == scene.mesh_groups.begin()) // First mesh group. { // override values from GCodeExport::setInitialTemps diff --git a/src/Mold.cpp b/src/Mold.cpp index fe5bebe849..2ef6ce7561 100644 --- a/src/Mold.cpp +++ b/src/Mold.cpp @@ -66,7 +66,7 @@ void Mold::process(std::vector& slicer_list) if (layer_nr == 0) { const ExtruderTrain& train_wall_0 = mesh.settings_.get("wall_0_extruder_nr"); - open_polyline_width *= train_wall_0.settings.get("initial_layer_line_width_factor"); + open_polyline_width *= train_wall_0.settings_.get("initial_layer_line_width_factor"); } const AngleDegrees angle = mesh.settings_.get("mold_angle"); const coord_t roof_height = mesh.settings_.get("mold_roof_height"); diff --git a/src/Preheat.cpp b/src/Preheat.cpp index e00926144c..6b3b8c3ee9 100644 --- a/src/Preheat.cpp +++ b/src/Preheat.cpp @@ -15,7 +15,7 @@ namespace cura Duration Preheat::getTimeToGoFromTempToTemp(const size_t extruder, const Temperature& temp_before, const Temperature& temp_after, const bool during_printing) { - const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder].settings; + const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder].settings_; Duration time; if (temp_after > temp_before) { @@ -40,7 +40,7 @@ Duration Preheat::getTimeToGoFromTempToTemp(const size_t extruder, const Tempera Temperature Preheat::getTemp(const size_t extruder, const Ratio& flow, const bool is_initial_layer) { - const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder].settings; + const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder].settings_; if (is_initial_layer && extruder_settings.get("material_print_temperature_layer_0") != 0) { return extruder_settings.get("material_print_temperature_layer_0"); @@ -51,7 +51,7 @@ Temperature Preheat::getTemp(const size_t extruder, const Ratio& flow, const boo Preheat::WarmUpResult Preheat::getWarmUpPointAfterCoolDown(double time_window, unsigned int extruder, double temp_start, double temp_mid, double temp_end, bool during_printing) { WarmUpResult result; - const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder].settings; + const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder].settings_; Temperature cool_down_speed = extruder_settings.get("machine_nozzle_cool_down_speed"); if (during_printing) { @@ -121,7 +121,7 @@ Preheat::WarmUpResult Preheat::getWarmUpPointAfterCoolDown(double time_window, u Preheat::CoolDownResult Preheat::getCoolDownPointAfterWarmUp(double time_window, unsigned int extruder, double temp_start, double temp_mid, double temp_end, bool during_printing) { CoolDownResult result; - const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder].settings; + const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder].settings_; Temperature cool_down_speed = extruder_settings.get("machine_nozzle_cool_down_speed"); if (during_printing) { diff --git a/src/PrimeTower.cpp b/src/PrimeTower.cpp index bc62d17a46..5ffbd200c7 100644 --- a/src/PrimeTower.cpp +++ b/src/PrimeTower.cpp @@ -60,8 +60,8 @@ PrimeTower::PrimeTower() extruder_order.end(), [scene_pointer](const unsigned int& extruder_nr_a, const unsigned int& extruder_nr_b) -> bool { - const Ratio adhesion_a = scene_pointer->extruders[extruder_nr_a].settings.get("material_adhesion_tendency"); - const Ratio adhesion_b = scene_pointer->extruders[extruder_nr_b].settings.get("material_adhesion_tendency"); + const Ratio adhesion_a = scene_pointer->extruders[extruder_nr_a].settings_.get("material_adhesion_tendency"); + const Ratio adhesion_b = scene_pointer->extruders[extruder_nr_b].settings_.get("material_adhesion_tendency"); return adhesion_a < adhesion_b; }); } @@ -122,7 +122,7 @@ void PrimeTower::generatePaths_denseInfill() const bool has_raft = mesh_group_settings.get("adhesion_type") == EPlatformAdhesion::RAFT; const coord_t base_height = std::max(scene.settings.get("prime_tower_base_height"), has_raft ? layer_height : 0); const double base_curve_magnitude = mesh_group_settings.get("prime_tower_base_curve_magnitude"); - const coord_t line_width = scene.extruders[extruder_order.front()].settings.get("prime_tower_line_width"); + const coord_t line_width = scene.extruders[extruder_order.front()].settings_.get("prime_tower_line_width"); prime_moves.resize(extruder_count); base_extra_moves.resize(extruder_count); @@ -130,9 +130,9 @@ void PrimeTower::generatePaths_denseInfill() coord_t cumulative_inset = 0; // Each tower shape is going to be printed inside the other. This is the inset we're doing for each extruder. for (size_t extruder_nr : extruder_order) { - const coord_t line_width = scene.extruders[extruder_nr].settings.get("prime_tower_line_width"); - const coord_t required_volume = MM3_2INT(scene.extruders[extruder_nr].settings.get("prime_tower_min_volume")); - const Ratio flow = scene.extruders[extruder_nr].settings.get("prime_tower_flow"); + const coord_t line_width = scene.extruders[extruder_nr].settings_.get("prime_tower_line_width"); + const coord_t required_volume = MM3_2INT(scene.extruders[extruder_nr].settings_.get("prime_tower_min_volume")); + const Ratio flow = scene.extruders[extruder_nr].settings_.get("prime_tower_flow"); coord_t current_volume = 0; Polygons& pattern = prime_moves[extruder_nr]; @@ -210,7 +210,7 @@ void PrimeTower::addToGcode(const SliceDataStorage& storage, LayerPlan& gcode_la return; } - bool post_wipe = Application::getInstance().current_slice->scene.extruders[prev_extruder].settings.get("prime_tower_wipe_enabled"); + bool post_wipe = Application::getInstance().current_slice->scene.extruders[prev_extruder].settings_.get("prime_tower_wipe_enabled"); // Do not wipe on the first layer, we will generate non-hollow prime tower there for better bed adhesion. if (prev_extruder == new_extruder || layer_nr == 0) @@ -230,9 +230,9 @@ void PrimeTower::addToGcode(const SliceDataStorage& storage, LayerPlan& gcode_la if (post_wipe) { // Make sure we wipe the old extruder on the prime tower. - const Settings& previous_settings = Application::getInstance().current_slice->scene.extruders[prev_extruder].settings; + const Settings& previous_settings = Application::getInstance().current_slice->scene.extruders[prev_extruder].settings_; const Point previous_nozzle_offset = Point(previous_settings.get("machine_nozzle_offset_x"), previous_settings.get("machine_nozzle_offset_y")); - const Settings& new_settings = Application::getInstance().current_slice->scene.extruders[new_extruder].settings; + const Settings& new_settings = Application::getInstance().current_slice->scene.extruders[new_extruder].settings_; const Point new_nozzle_offset = Point(new_settings.get("machine_nozzle_offset_x"), new_settings.get("machine_nozzle_offset_y")); gcode_layer.addTravel(post_wipe_point - previous_nozzle_offset + new_nozzle_offset); } @@ -302,8 +302,8 @@ void PrimeTower::gotoStartLocation(LayerPlan& gcode_layer, const int extruder_nr const ClosestPolygonPoint wipe_location = prime_tower_start_locations[current_start_location_idx]; const ExtruderTrain& train = Application::getInstance().current_slice->scene.extruders[extruder_nr]; - const coord_t inward_dist = train.settings.get("machine_nozzle_size") * 3 / 2; - const coord_t start_dist = train.settings.get("machine_nozzle_size") * 2; + const coord_t inward_dist = train.settings_.get("machine_nozzle_size") * 3 / 2; + const coord_t start_dist = train.settings_.get("machine_nozzle_size") * 2; const Point prime_end = PolygonUtils::moveInsideDiagonally(wipe_location, inward_dist); const Point outward_dir = wipe_location.location_ - prime_end; const Point prime_start = wipe_location.location_ + normal(outward_dir, start_dist); diff --git a/src/Scene.cpp b/src/Scene.cpp index 1e8416181e..f7c81777f6 100644 --- a/src/Scene.cpp +++ b/src/Scene.cpp @@ -32,7 +32,7 @@ const std::string Scene::getAllSettingsString() const // Per-extruder settings. for (size_t extruder_nr = 0; extruder_nr < extruders.size(); extruder_nr++) { - output << " -e" << extruder_nr << extruders[extruder_nr].settings.getAllSettingsString(); + output << " -e" << extruder_nr << extruders[extruder_nr].settings_.getAllSettingsString(); } for (size_t mesh_group_index = 0; mesh_group_index < mesh_groups.size(); mesh_group_index++) diff --git a/src/SkirtBrim.cpp b/src/SkirtBrim.cpp index 4b77b449d3..3769760253 100644 --- a/src/SkirtBrim.cpp +++ b/src/SkirtBrim.cpp @@ -56,11 +56,11 @@ SkirtBrim::SkirtBrim(SliceDataStorage& storage) } const ExtruderTrain& extruder = extruders[extruder_nr]; - line_widths[extruder_nr] = extruder.settings.get("skirt_brim_line_width") * extruder.settings.get("initial_layer_line_width_factor"); - skirt_brim_minimal_length[extruder_nr] = extruder.settings.get("skirt_brim_minimal_length"); - external_polys_only[extruder_nr] = adhesion_type == EPlatformAdhesion::SKIRT || extruder.settings.get("brim_outside_only"); - line_count[extruder_nr] = extruder.settings.get(adhesion_type == EPlatformAdhesion::BRIM ? "brim_line_count" : "skirt_line_count"); - gap[extruder_nr] = extruder.settings.get(adhesion_type == EPlatformAdhesion::BRIM ? "brim_gap" : "skirt_gap"); + line_widths[extruder_nr] = extruder.settings_.get("skirt_brim_line_width") * extruder.settings_.get("initial_layer_line_width_factor"); + skirt_brim_minimal_length[extruder_nr] = extruder.settings_.get("skirt_brim_minimal_length"); + external_polys_only[extruder_nr] = adhesion_type == EPlatformAdhesion::SKIRT || extruder.settings_.get("brim_outside_only"); + line_count[extruder_nr] = extruder.settings_.get(adhesion_type == EPlatformAdhesion::BRIM ? "brim_line_count" : "skirt_line_count"); + gap[extruder_nr] = extruder.settings_.get(adhesion_type == EPlatformAdhesion::BRIM ? "brim_gap" : "skirt_gap"); } } @@ -226,7 +226,7 @@ std::vector SkirtBrim::generatePrimaryBrim(std::vector& all_bri Polygons SkirtBrim::getInternalHoleExclusionArea(const Polygons& outline, const int extruder_nr) { assert(extruder_nr >= 0); - const Settings& settings = Application::getInstance().current_slice->scene.extruders[extruder_nr].settings; + const Settings& settings = Application::getInstance().current_slice->scene.extruders[extruder_nr].settings_; // If brim is external_only, the distance between the external brim of a part inside a hole and the inside hole of the outer part. const coord_t hole_brim_distance = settings.get("brim_inside_margin"); @@ -300,7 +300,7 @@ coord_t SkirtBrim::generateOffset(const Offset& offset, Polygons& covered_area, } { // limit brim lines to allowed areas, stitch them and store them in the result - brim = Simplify(Application::getInstance().current_slice->scene.extruders[offset.extruder_nr].settings).polygon(brim); + brim = Simplify(Application::getInstance().current_slice->scene.extruders[offset.extruder_nr].settings_).polygon(brim); brim.toPolylines(); Polygons brim_lines = allowed_areas_per_extruder[offset.extruder_nr].intersectionPolyLines(brim, false); length_added = brim_lines.polyLineLength(); @@ -361,9 +361,9 @@ Polygons SkirtBrim::getFirstLayerOutline(const int extruder_nr /* = -1 */) int skirt_height = 0; for (const auto& extruder : Application::getInstance().current_slice->scene.extruders) { - if (extruder_nr == -1 || extruder_nr == extruder.extruder_nr) + if (extruder_nr == -1 || extruder_nr == extruder.extruder_nr_) { - skirt_height = std::max(skirt_height, extruder.settings.get("skirt_height")); + skirt_height = std::max(skirt_height, extruder.settings_.get("skirt_height")); } } skirt_height = std::min(skirt_height, static_cast(storage.print_layer_count)); @@ -373,7 +373,7 @@ Polygons SkirtBrim::getFirstLayerOutline(const int extruder_nr /* = -1 */) for (const auto& extruder : Application::getInstance().current_slice->scene.extruders) { first_layer_outline - = first_layer_outline.unionPolygons(storage.getLayerOutlines(i_layer, include_support, include_prime_tower, external_only, extruder.extruder_nr)); + = first_layer_outline.unionPolygons(storage.getLayerOutlines(i_layer, include_support, include_prime_tower, external_only, extruder.extruder_nr_)); } } @@ -418,7 +418,7 @@ Polygons SkirtBrim::getFirstLayerOutline(const int extruder_nr /* = -1 */) { // remove model-brim from support SupportLayer& support_layer = storage.support.supportLayers[0]; const ExtruderTrain& support_infill_extruder = global_settings.get("support_infill_extruder_nr"); - if (support_infill_extruder.settings.get("brim_replaces_support")) + if (support_infill_extruder.settings_.get("brim_replaces_support")) { // avoid gap in the middle // V @@ -581,9 +581,9 @@ void SkirtBrim::generateSupportBrim() Scene& scene = Application::getInstance().current_slice->scene; const ExtruderTrain& support_infill_extruder = scene.current_mesh_group->settings.get("support_infill_extruder_nr"); const coord_t brim_line_width - = support_infill_extruder.settings.get("skirt_brim_line_width") * support_infill_extruder.settings.get("initial_layer_line_width_factor"); - size_t line_count = support_infill_extruder.settings.get("support_brim_line_count"); - const coord_t minimal_length = support_infill_extruder.settings.get("skirt_brim_minimal_length"); + = support_infill_extruder.settings_.get("skirt_brim_line_width") * support_infill_extruder.settings_.get("initial_layer_line_width_factor"); + size_t line_count = support_infill_extruder.settings_.get("support_brim_line_count"); + const coord_t minimal_length = support_infill_extruder.settings_.get("skirt_brim_minimal_length"); if (! storage.support.generated || line_count <= 0 || storage.support.supportLayers.empty()) { return; @@ -592,12 +592,12 @@ void SkirtBrim::generateSupportBrim() const coord_t brim_width = brim_line_width * line_count; coord_t skirt_brim_length = 0; - if (storage.skirt_brim[support_infill_extruder.extruder_nr].empty()) + if (storage.skirt_brim[support_infill_extruder.extruder_nr_].empty()) { - storage.skirt_brim[support_infill_extruder.extruder_nr].emplace_back(); + storage.skirt_brim[support_infill_extruder.extruder_nr_].emplace_back(); } - for (const SkirtBrimLine& brim_line : storage.skirt_brim[support_infill_extruder.extruder_nr]) + for (const SkirtBrimLine& brim_line : storage.skirt_brim[support_infill_extruder.extruder_nr_]) { skirt_brim_length += brim_line.closed_polygons.polygonLength(); skirt_brim_length += brim_line.open_polylines.polyLineLength(); diff --git a/src/Slice.cpp b/src/Slice.cpp index c95321d0de..4782604e00 100644 --- a/src/Slice.cpp +++ b/src/Slice.cpp @@ -21,7 +21,7 @@ void Slice::compute() scene.current_mesh_group = mesh_group; for (ExtruderTrain& extruder : scene.extruders) { - extruder.settings.setParent(&scene.current_mesh_group->settings); + extruder.settings_.setParent(&scene.current_mesh_group->settings); } scene.processMeshGroup(*mesh_group); } diff --git a/src/TopSurface.cpp b/src/TopSurface.cpp index 9ed9cc7ede..2e5a2a4465 100644 --- a/src/TopSurface.cpp +++ b/src/TopSurface.cpp @@ -48,7 +48,7 @@ bool TopSurface::ironing(const SliceDataStorage& storage, const SliceMeshStorage return false; // Nothing to do. } // Generate the lines to cover the surface. - const int extruder_nr = mesh.settings.get("top_bottom_extruder_nr").extruder_nr; + const int extruder_nr = mesh.settings.get("top_bottom_extruder_nr").extruder_nr_; const EFillMethod pattern = mesh.settings.get("ironing_pattern"); const bool zig_zaggify_infill = pattern == EFillMethod::ZIG_ZAG; constexpr bool connect_polygons = false; // midway connections can make the surface less smooth diff --git a/src/WallsComputation.cpp b/src/WallsComputation.cpp index 09dfa368ed..f0415ce0d1 100644 --- a/src/WallsComputation.cpp +++ b/src/WallsComputation.cpp @@ -2,6 +2,7 @@ // CuraEngine is released under the terms of the AGPLv3 or higher #include "WallsComputation.h" + #include "Application.h" #include "ExtruderTrain.h" #include "Slice.h" @@ -13,7 +14,9 @@ namespace cura { -WallsComputation::WallsComputation(const Settings& settings, const LayerIndex layer_nr) : settings(settings), layer_nr(layer_nr) +WallsComputation::WallsComputation(const Settings& settings, const LayerIndex layer_nr) + : settings(settings) + , layer_nr(layer_nr) { } @@ -35,7 +38,8 @@ void WallsComputation::generateWalls(SliceLayerPart* part, SectionType section_t const bool spiralize = settings.get("magic_spiralize"); const size_t alternate = ((layer_nr % 2) + 2) % 2; - if (spiralize && layer_nr < LayerIndex(settings.get("initial_bottom_layers")) && alternate == 1) //Add extra insets every 2 layers when spiralizing. This makes bottoms of cups watertight. + if (spiralize && layer_nr < LayerIndex(settings.get("initial_bottom_layers")) + && alternate == 1) // Add extra insets every 2 layers when spiralizing. This makes bottoms of cups watertight. { wall_count += 5; } @@ -45,18 +49,17 @@ void WallsComputation::generateWalls(SliceLayerPart* part, SectionType section_t } const bool first_layer = layer_nr == 0; - const Ratio line_width_0_factor = first_layer ? settings.get("wall_0_extruder_nr").settings.get("initial_layer_line_width_factor") : 1.0_r; + const Ratio line_width_0_factor = first_layer ? settings.get("wall_0_extruder_nr").settings_.get("initial_layer_line_width_factor") : 1.0_r; const coord_t line_width_0 = settings.get("wall_line_width_0") * line_width_0_factor; const coord_t wall_0_inset = settings.get("wall_0_inset"); - const Ratio line_width_x_factor = first_layer ? settings.get("wall_x_extruder_nr").settings.get("initial_layer_line_width_factor") : 1.0_r; + const Ratio line_width_x_factor = first_layer ? settings.get("wall_x_extruder_nr").settings_.get("initial_layer_line_width_factor") : 1.0_r; const coord_t line_width_x = settings.get("wall_line_width_x") * line_width_x_factor; // When spiralizing, generate the spiral insets using simple offsets instead of generating toolpaths if (spiralize) { - const bool recompute_outline_based_on_outer_wall = - settings.get("support_enable") && !settings.get("fill_outline_gaps"); + const bool recompute_outline_based_on_outer_wall = settings.get("support_enable") && ! settings.get("fill_outline_gaps"); generateSpiralInsets(part, line_width_0, wall_0_inset, recompute_outline_based_on_outer_wall); if (layer_nr <= static_cast(settings.get("initial_bottom_layers"))) @@ -72,7 +75,7 @@ void WallsComputation::generateWalls(SliceLayerPart* part, SectionType section_t part->wall_toolpaths = wall_tool_paths.getToolPaths(); part->inner_area = wall_tool_paths.getInnerContour(); } - part->outline = PolygonsPart { Simplify(settings).polygon(part->outline) }; + part->outline = PolygonsPart{ Simplify(settings).polygon(part->outline) }; part->print_outline = part->outline; } @@ -84,16 +87,16 @@ void WallsComputation::generateWalls(SliceLayerPart* part, SectionType section_t */ void WallsComputation::generateWalls(SliceLayer* layer, SectionType section) { - for(SliceLayerPart& part : layer->parts) + for (SliceLayerPart& part : layer->parts) { generateWalls(&part, section); } - //Remove the parts which did not generate a wall. As these parts are too small to print, - // and later code can now assume that there is always minimal 1 wall line. - if(settings.get("wall_line_count") >= 1 && !settings.get("fill_outline_gaps")) + // Remove the parts which did not generate a wall. As these parts are too small to print, + // and later code can now assume that there is always minimal 1 wall line. + if (settings.get("wall_line_count") >= 1 && ! settings.get("fill_outline_gaps")) { - for(size_t part_idx = 0; part_idx < layer->parts.size(); part_idx++) + for (size_t part_idx = 0; part_idx < layer->parts.size(); part_idx++) { if (layer->parts[part_idx].wall_toolpaths.empty() && layer->parts[part_idx].spiral_wall.empty()) { @@ -108,13 +111,13 @@ void WallsComputation::generateWalls(SliceLayer* layer, SectionType section) } } -void WallsComputation::generateSpiralInsets(SliceLayerPart *part, coord_t line_width_0, coord_t wall_0_inset, bool recompute_outline_based_on_outer_wall) +void WallsComputation::generateSpiralInsets(SliceLayerPart* part, coord_t line_width_0, coord_t wall_0_inset, bool recompute_outline_based_on_outer_wall) { part->spiral_wall = part->outline.offset(-line_width_0 / 2 - wall_0_inset); - //Optimize the wall. This prevents buffer underruns in the printer firmware, and reduces processing time in CuraEngine. + // Optimize the wall. This prevents buffer underruns in the printer firmware, and reduces processing time in CuraEngine. const ExtruderTrain& train_wall = settings.get("wall_0_extruder_nr"); - part->spiral_wall = Simplify(train_wall.settings).polygon(part->spiral_wall); + part->spiral_wall = Simplify(train_wall.settings_).polygon(part->spiral_wall); part->spiral_wall.removeDegenerateVerts(); if (recompute_outline_based_on_outer_wall) { @@ -126,4 +129,4 @@ void WallsComputation::generateSpiralInsets(SliceLayerPart *part, coord_t line_w } } -}//namespace cura +} // namespace cura diff --git a/src/communication/ArcusCommunication.cpp b/src/communication/ArcusCommunication.cpp index 44cc58cbe2..54ace60375 100644 --- a/src/communication/ArcusCommunication.cpp +++ b/src/communication/ArcusCommunication.cpp @@ -116,10 +116,10 @@ class ArcusCommunication::PathCompiler */ void setExtruder(const ExtruderTrain& new_extruder) { - if (extruder != new_extruder.extruder_nr) + if (extruder != new_extruder.extruder_nr_) { flushPathSegments(); - extruder = new_extruder.extruder_nr; + extruder = new_extruder.extruder_nr_; } } diff --git a/src/communication/ArcusCommunicationPrivate.cpp b/src/communication/ArcusCommunicationPrivate.cpp index 3d33f43e74..afff5800fa 100644 --- a/src/communication/ArcusCommunicationPrivate.cpp +++ b/src/communication/ArcusCommunicationPrivate.cpp @@ -78,7 +78,7 @@ void ArcusCommunication::Private::readExtruderSettingsMessage(const google::prot .extruders[extruder_nr]; // Extruder messages may arrive out of order, so don't iteratively get the next extruder but take the extruder_nr from this message. for (const cura::proto::Setting& setting_message : extruder_message.settings().settings()) { - extruder.settings.add(setting_message.name(), setting_message.value()); + extruder.settings_.add(setting_message.name(), setting_message.value()); } } } @@ -120,7 +120,7 @@ void ArcusCommunication::Private::readMeshGroupMessage(const proto::ObjectList& mesh.settings_.add(setting.name(), setting.value()); } ExtruderTrain& extruder = mesh.settings_.get("extruder_nr"); // Set the parent setting to the correct extruder. - mesh.settings_.setParent(&extruder.settings); + mesh.settings_.setParent(&extruder.settings_); for (size_t face = 0; face < face_count; face++) { diff --git a/src/communication/CommandLine.cpp b/src/communication/CommandLine.cpp index 12b338305f..ae9fd28ee6 100644 --- a/src/communication/CommandLine.cpp +++ b/src/communication/CommandLine.cpp @@ -229,9 +229,9 @@ void CommandLine::sliceNext() } } // If this was an extruder stack, make sure that the extruder_nr setting is correct. - if (last_settings == &last_extruder->settings) + if (last_settings == &last_extruder->settings_) { - last_extruder->settings.add("extruder_nr", std::to_string(last_extruder->extruder_nr)); + last_extruder->settings_.add("extruder_nr", std::to_string(last_extruder->extruder_nr_)); } break; } @@ -242,7 +242,7 @@ void CommandLine::sliceNext() { slice.scene.extruders.emplace_back(extruder_nr, &slice.scene.settings); } - last_settings = &slice.scene.extruders[extruder_nr].settings; + last_settings = &slice.scene.extruders[extruder_nr].settings_; last_settings->add("extruder_nr", argument.substr(2)); last_extruder = &slice.scene.extruders[extruder_nr]; break; @@ -259,7 +259,7 @@ void CommandLine::sliceNext() const FMatrix4x3 transformation = last_settings->get("mesh_rotation_matrix"); // The transformation applied to the model when loaded. - if (! loadMeshIntoMeshGroup(&slice.scene.mesh_groups[mesh_group_index], argument.c_str(), transformation, last_extruder->settings)) + if (! loadMeshIntoMeshGroup(&slice.scene.mesh_groups[mesh_group_index], argument.c_str(), transformation, last_extruder->settings_)) { spdlog::error("Failed to load model: {}. (error number {})", argument, errno); exit(1); @@ -462,7 +462,7 @@ int CommandLine::loadJSON( } const std::string extruder_definition_id(extruder_id.GetString()); const std::string extruder_file = findDefinitionFile(extruder_definition_id, search_directories); - loadJSON(extruder_file, scene.extruders[extruder_nr].settings, force_read_parent, force_read_nondefault); + loadJSON(extruder_file, scene.extruders[extruder_nr].settings_, force_read_parent, force_read_nondefault); } } } diff --git a/src/gcodeExport.cpp b/src/gcodeExport.cpp index 210c319c8d..deb58664dc 100644 --- a/src/gcodeExport.cpp +++ b/src/gcodeExport.cpp @@ -88,14 +88,14 @@ void GCodeExport::preSetup(const size_t start_extruder) for (size_t extruder_nr = 0; extruder_nr < extruder_count; extruder_nr++) { const ExtruderTrain& train = scene.extruders[extruder_nr]; - setFilamentDiameter(extruder_nr, train.settings.get("material_diameter")); + setFilamentDiameter(extruder_nr, train.settings_.get("material_diameter")); extruder_attr[extruder_nr].last_retraction_prime_speed - = train.settings.get("retraction_prime_speed"); // the alternative would be switch_extruder_prime_speed, but dual extrusion might not even be configured... - extruder_attr[extruder_nr].fan_number = train.settings.get("machine_extruder_cooling_fan_number"); + = train.settings_.get("retraction_prime_speed"); // the alternative would be switch_extruder_prime_speed, but dual extrusion might not even be configured... + extruder_attr[extruder_nr].fan_number = train.settings_.get("machine_extruder_cooling_fan_number"); // Cache some settings that we use frequently. - const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder_nr].settings; + const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder_nr].settings_; if (use_extruder_offset_to_offset_coords) { extruder_attr[extruder_nr].nozzle_offset = Point(extruder_settings.get("machine_nozzle_offset_x"), extruder_settings.get("machine_nozzle_offset_y")); @@ -150,9 +150,9 @@ void GCodeExport::setInitialAndBuildVolumeTemps(const unsigned int start_extrude { const ExtruderTrain& train = scene.extruders[extruder_nr]; - const Temperature print_temp_0 = train.settings.get("material_print_temperature_layer_0"); - const Temperature print_temp_here = (print_temp_0 != 0) ? print_temp_0 : train.settings.get("material_print_temperature"); - const Temperature temp = (extruder_nr == start_extruder_nr) ? print_temp_here : train.settings.get("material_standby_temperature"); + const Temperature print_temp_0 = train.settings_.get("material_print_temperature_layer_0"); + const Temperature print_temp_here = (print_temp_0 != 0) ? print_temp_0 : train.settings_.get("material_print_temperature"); + const Temperature temp = (extruder_nr == start_extruder_nr) ? print_temp_here : train.settings_.get("material_standby_temperature"); setInitialTemp(extruder_nr, temp); } @@ -231,7 +231,7 @@ std::string GCodeExport::getFileHeader( { prefix << ";EXTRUDER_TRAIN." << extr_nr << ".MATERIAL.GUID:" << mat_ids[extr_nr] << new_line; } - const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extr_nr].settings; + const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extr_nr].settings_; prefix << ";EXTRUDER_TRAIN." << extr_nr << ".NOZZLE.DIAMETER:" << extruder_settings.get("machine_nozzle_size") << new_line; prefix << ";EXTRUDER_TRAIN." << extr_nr << ".NOZZLE.NAME:" << extruder_settings.get("machine_nozzle_id") << new_line; } @@ -272,7 +272,7 @@ std::string GCodeExport::getFileHeader( prefix << ";MATERIAL:" << ((filament_used.size() >= 1) ? static_cast(filament_used[0]) : 6666) << new_line; prefix << ";MATERIAL2:" << ((filament_used.size() >= 2) ? static_cast(filament_used[1]) : 0) << new_line; - prefix << ";NOZZLE_DIAMETER:" << Application::getInstance().current_slice->scene.extruders[0].settings.get("machine_nozzle_size") << new_line; + prefix << ";NOZZLE_DIAMETER:" << Application::getInstance().current_slice->scene.extruders[0].settings_.get("machine_nozzle_size") << new_line; } else if (flavor == EGCodeFlavor::REPRAP || flavor == EGCodeFlavor::MARLIN || flavor == EGCodeFlavor::MARLIN_VOLUMATRIC) { @@ -676,7 +676,7 @@ bool GCodeExport::initializeExtruderTrains(const SliceDataStorage& storage, cons { for (const ExtruderTrain& train : Application::getInstance().current_slice->scene.extruders) { - resetExtruderToPrimed(train.extruder_nr, train.settings.get("machine_extruders_shared_nozzle_initial_retraction")); + resetExtruderToPrimed(train.extruder_nr_, train.settings_.get("machine_extruders_shared_nozzle_initial_retraction")); } } @@ -699,7 +699,7 @@ bool GCodeExport::initializeExtruderTrains(const SliceDataStorage& storage, cons { // initialize extruder trains ExtruderTrain& train = Application::getInstance().current_slice->scene.extruders[start_extruder_nr]; processInitialLayerTemperature(storage, start_extruder_nr); - writePrimeTrain(train.settings.get("speed_travel")); + writePrimeTrain(train.settings_.get("speed_travel")); should_prime_extruder = false; const RetractionConfig& retraction_config = storage.retraction_wipe_config_per_extruder[start_extruder_nr].retraction_config; writeRetraction(retraction_config); @@ -748,8 +748,8 @@ void GCodeExport::processInitialLayerTemperature(const SliceDataStorage& storage ExtruderTrain& train = scene.extruders[start_extruder_nr]; constexpr bool wait = true; - const Temperature print_temp_0 = train.settings.get("material_print_temperature_layer_0"); - const Temperature print_temp_here = (print_temp_0 != 0) ? print_temp_0 : train.settings.get("material_print_temperature"); + const Temperature print_temp_0 = train.settings_.get("material_print_temperature_layer_0"); + const Temperature print_temp_here = (print_temp_0 != 0) ? print_temp_0 : train.settings_.get("material_print_temperature"); writeTemperatureCommand(start_extruder_nr, print_temp_here, wait); } else if (getFlavor() != EGCodeFlavor::ULTIGCODE) @@ -773,12 +773,12 @@ void GCodeExport::processInitialLayerTemperature(const SliceDataStorage& storage Temperature extruder_temp; if (extruder_nr == start_extruder_nr) { - const Temperature print_temp_0 = train.settings.get("material_print_temperature_layer_0"); - extruder_temp = (print_temp_0 != 0) ? print_temp_0 : train.settings.get("material_print_temperature"); + const Temperature print_temp_0 = train.settings_.get("material_print_temperature_layer_0"); + extruder_temp = (print_temp_0 != 0) ? print_temp_0 : train.settings_.get("material_print_temperature"); } else { - extruder_temp = train.settings.get("material_standby_temperature"); + extruder_temp = train.settings_.get("material_standby_temperature"); } writeTemperatureCommand(extruder_nr, extruder_temp); } @@ -793,12 +793,12 @@ void GCodeExport::processInitialLayerTemperature(const SliceDataStorage& storage Temperature extruder_temp; if (extruder_nr == start_extruder_nr) { - const Temperature print_temp_0 = train.settings.get("material_print_temperature_layer_0"); - extruder_temp = (print_temp_0 != 0) ? print_temp_0 : train.settings.get("material_print_temperature"); + const Temperature print_temp_0 = train.settings_.get("material_print_temperature_layer_0"); + extruder_temp = (print_temp_0 != 0) ? print_temp_0 : train.settings_.get("material_print_temperature"); } else { - extruder_temp = train.settings.get("material_standby_temperature"); + extruder_temp = train.settings_.get("material_standby_temperature"); } writeTemperatureCommand(extruder_nr, extruder_temp, true); } @@ -1207,7 +1207,7 @@ void GCodeExport::writeZhopStart(const coord_t hop_height, Velocity speed /*= 0* if (speed == 0) { const ExtruderTrain& extruder = Application::getInstance().current_slice->scene.extruders[current_extruder]; - speed = extruder.settings.get("speed_z_hop"); + speed = extruder.settings_.get("speed_z_hop"); } is_z_hopped = hop_height; currentSpeed = speed; @@ -1224,7 +1224,7 @@ void GCodeExport::writeZhopEnd(Velocity speed /*= 0*/) if (speed == 0) { const ExtruderTrain& extruder = Application::getInstance().current_slice->scene.extruders[current_extruder]; - speed = extruder.settings.get("speed_z_hop"); + speed = extruder.settings_.get("speed_z_hop"); } is_z_hopped = 0; currentPosition.z_ = current_layer_z; @@ -1254,7 +1254,7 @@ void GCodeExport::startExtruder(const size_t new_extruder) assert(getCurrentExtrudedVolume() == 0.0 && "Just after an extruder switch we haven't extruded anything yet!"); resetExtrusionValue(); // zero the E value on the new extruder, just to be sure - const std::string start_code = Application::getInstance().current_slice->scene.extruders[new_extruder].settings.get("machine_extruder_start_code"); + const std::string start_code = Application::getInstance().current_slice->scene.extruders[new_extruder].settings_.get("machine_extruder_start_code"); if (! start_code.empty()) { @@ -1287,7 +1287,7 @@ void GCodeExport::switchExtruder(size_t new_extruder, const RetractionConfig& re return; } - const Settings& old_extruder_settings = Application::getInstance().current_slice->scene.extruders[current_extruder].settings; + const Settings& old_extruder_settings = Application::getInstance().current_slice->scene.extruders[current_extruder].settings_; if (old_extruder_settings.get("retraction_enable")) { constexpr bool force = true; @@ -1340,7 +1340,7 @@ void GCodeExport::writePrimeTrain(const Velocity& travel_speed) { // extruder is already primed once! return; } - const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[current_extruder].settings; + const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[current_extruder].settings_; if (extruder_settings.get("prime_blob_enable")) { // only move to prime position if we do a blob/poop // ideally the prime position would be respected whether we do a blob or not, @@ -1442,12 +1442,12 @@ void GCodeExport::writeTemperatureCommand(const size_t extruder, const Temperatu { const ExtruderTrain& extruder_train = Application::getInstance().current_slice->scene.extruders[extruder]; - if (! extruder_train.settings.get("machine_nozzle_temp_enabled")) + if (! extruder_train.settings_.get("machine_nozzle_temp_enabled")) { return; } - if (extruder_train.settings.get("machine_extruders_share_heater")) + if (extruder_train.settings_.get("machine_extruders_share_heater")) { // extruders share a single heater if (extruder != current_extruder) diff --git a/src/infill/LightningGenerator.cpp b/src/infill/LightningGenerator.cpp index e3ec58436f..a5a7749655 100644 --- a/src/infill/LightningGenerator.cpp +++ b/src/infill/LightningGenerator.cpp @@ -1,14 +1,14 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #include "infill/LightningGenerator.h" -#include "infill/LightningLayer.h" -#include "infill/LightningTreeNode.h" #include "ExtruderTrain.h" +#include "infill/LightningLayer.h" +#include "infill/LightningTreeNode.h" #include "sliceDataStorage.h" -#include "utils/linearAlg2D.h" #include "utils/SparsePointGridInclusive.h" +#include "utils/linearAlg2D.h" /* Possible future tasks/optimizations,etc.: * - Improve connecting heuristic to favor connecting to shorter trees @@ -29,12 +29,13 @@ using namespace cura; LightningGenerator::LightningGenerator(const SliceMeshStorage& mesh) { const auto infill_extruder = mesh.settings.get("infill_extruder_nr"); - const auto layer_thickness = infill_extruder.settings.get("layer_height"); // Note: There's not going to be a layer below the first one, so the 'initial layer height' doesn't have to be taken into account. + const auto layer_thickness = infill_extruder.settings_.get( + "layer_height"); // Note: There's not going to be a layer below the first one, so the 'initial layer height' doesn't have to be taken into account. - supporting_radius = std::max(infill_extruder.settings.get("infill_line_distance"), infill_extruder.settings.get("infill_line_width")) / 2; - wall_supporting_radius = layer_thickness * std::tan(infill_extruder.settings.get("lightning_infill_overhang_angle")); - prune_length = layer_thickness * std::tan(infill_extruder.settings.get("lightning_infill_prune_angle")); - straightening_max_distance = layer_thickness * std::tan(infill_extruder.settings.get("lightning_infill_straightening_angle")); + supporting_radius = std::max(infill_extruder.settings_.get("infill_line_distance"), infill_extruder.settings_.get("infill_line_width")) / 2; + wall_supporting_radius = layer_thickness * std::tan(infill_extruder.settings_.get("lightning_infill_overhang_angle")); + prune_length = layer_thickness * std::tan(infill_extruder.settings_.get("lightning_infill_prune_angle")); + straightening_max_distance = layer_thickness * std::tan(infill_extruder.settings_.get("lightning_infill_straightening_angle")); generateInitialInternalOverhangs(mesh); generateTrees(mesh); @@ -45,10 +46,10 @@ void LightningGenerator::generateInitialInternalOverhangs(const SliceMeshStorage overhang_per_layer.resize(mesh.layers.size()); const auto infill_wall_line_count = static_cast(mesh.settings.get("infill_wall_line_count")); const auto infill_line_width = mesh.settings.get("infill_line_width"); - const coord_t infill_wall_offset = - infill_wall_line_count * infill_line_width; + const coord_t infill_wall_offset = -infill_wall_line_count * infill_line_width; Polygons infill_area_above; - //Iterate from top to bottom, to subtract the overhang areas above from the overhang areas on the layer below, to get only overhang in the top layer where it is overhanging. + // Iterate from top to bottom, to subtract the overhang areas above from the overhang areas on the layer below, to get only overhang in the top layer where it is overhanging. for (int layer_nr = mesh.layers.size() - 1; layer_nr >= 0; layer_nr--) { const SliceLayer& current_layer = mesh.layers[layer_nr]; @@ -58,7 +59,7 @@ void LightningGenerator::generateInitialInternalOverhangs(const SliceMeshStorage infill_area_here.add(part.getOwnInfillArea().offset(infill_wall_offset)); } - //Remove the part of the infill area that is already supported by the walls. + // Remove the part of the infill area that is already supported by the walls. Polygons overhang = infill_area_here.offset(-wall_supporting_radius).difference(infill_area_above); overhang_per_layer[layer_nr] = overhang; @@ -77,7 +78,7 @@ void LightningGenerator::generateTrees(const SliceMeshStorage& mesh) lightning_layers.resize(mesh.layers.size()); const auto infill_wall_line_count = static_cast(mesh.settings.get("infill_wall_line_count")); const auto infill_line_width = mesh.settings.get("infill_line_width"); - const coord_t infill_wall_offset = - infill_wall_line_count * infill_line_width; + const coord_t infill_wall_offset = -infill_wall_line_count * infill_line_width; std::vector infill_outlines; infill_outlines.insert(infill_outlines.end(), mesh.layers.size(), Polygons()); diff --git a/src/pathPlanning/Comb.cpp b/src/pathPlanning/Comb.cpp index 96f961e4c0..328ec18b97 100644 --- a/src/pathPlanning/Comb.cpp +++ b/src/pathPlanning/Comb.cpp @@ -22,40 +22,40 @@ namespace cura LocToLineGrid& Comb::getOutsideLocToLine(const ExtruderTrain& train) { - if (outside_loc_to_line[train.extruder_nr] == nullptr) + if (outside_loc_to_line[train.extruder_nr_] == nullptr) { - outside_loc_to_line[train.extruder_nr] = PolygonUtils::createLocToLineGrid(getBoundaryOutside(train), offset_from_inside_to_outside * 3 / 2); + outside_loc_to_line[train.extruder_nr_] = PolygonUtils::createLocToLineGrid(getBoundaryOutside(train), offset_from_inside_to_outside * 3 / 2); } - return *outside_loc_to_line[train.extruder_nr]; + return *outside_loc_to_line[train.extruder_nr_]; } Polygons& Comb::getBoundaryOutside(const ExtruderTrain& train) { - if (boundary_outside[train.extruder_nr].empty()) + if (boundary_outside[train.extruder_nr_].empty()) { - bool travel_avoid_supports = train.settings.get("travel_avoid_supports"); - boundary_outside[train.extruder_nr] = storage.getLayerOutlines(layer_nr, travel_avoid_supports, travel_avoid_supports).offset(travel_avoid_distance); + bool travel_avoid_supports = train.settings_.get("travel_avoid_supports"); + boundary_outside[train.extruder_nr_] = storage.getLayerOutlines(layer_nr, travel_avoid_supports, travel_avoid_supports).offset(travel_avoid_distance); } - return boundary_outside[train.extruder_nr]; + return boundary_outside[train.extruder_nr_]; } Polygons& Comb::getModelBoundary(const ExtruderTrain& train) { - if (model_boundary[train.extruder_nr].empty()) + if (model_boundary[train.extruder_nr_].empty()) { - bool travel_avoid_supports = train.settings.get("travel_avoid_supports"); - model_boundary[train.extruder_nr] = storage.getLayerOutlines(layer_nr, travel_avoid_supports, travel_avoid_supports); + bool travel_avoid_supports = train.settings_.get("travel_avoid_supports"); + model_boundary[train.extruder_nr_] = storage.getLayerOutlines(layer_nr, travel_avoid_supports, travel_avoid_supports); } - return boundary_outside[train.extruder_nr]; + return boundary_outside[train.extruder_nr_]; } LocToLineGrid& Comb::getModelBoundaryLocToLine(const ExtruderTrain& train) { - if (model_boundary_loc_to_line[train.extruder_nr] == nullptr) + if (model_boundary_loc_to_line[train.extruder_nr_] == nullptr) { - model_boundary_loc_to_line[train.extruder_nr] = PolygonUtils::createLocToLineGrid(getModelBoundary(train), offset_from_inside_to_outside * 3 / 2); + model_boundary_loc_to_line[train.extruder_nr_] = PolygonUtils::createLocToLineGrid(getModelBoundary(train), offset_from_inside_to_outside * 3 / 2); } - return *model_boundary_loc_to_line[train.extruder_nr]; + return *model_boundary_loc_to_line[train.extruder_nr_]; } Comb::Comb( @@ -202,7 +202,7 @@ bool Comb::calc( skip_avoid_other_parts_path = true; } - const bool travel_avoid_other_parts = train.settings.get("travel_avoid_other_parts"); + const bool travel_avoid_other_parts = train.settings_.get("travel_avoid_other_parts"); if (travel_avoid_other_parts && ! skip_avoid_other_parts_path) { // compute the crossing points when moving through air diff --git a/src/raft.cpp b/src/raft.cpp index e13836b43f..aed16063f8 100644 --- a/src/raft.cpp +++ b/src/raft.cpp @@ -18,7 +18,7 @@ namespace cura void Raft::generate(SliceDataStorage& storage) { assert(storage.raftOutline.size() == 0 && "Raft polygon isn't generated yet, so should be empty!"); - const Settings& settings = Application::getInstance().current_slice->scene.current_mesh_group->settings.get("raft_base_extruder_nr").settings; + const Settings& settings = Application::getInstance().current_slice->scene.current_mesh_group->settings.get("raft_base_extruder_nr").settings_; const coord_t distance = settings.get("raft_margin"); constexpr bool include_support = true; constexpr bool dont_include_prime_tower = false; // Prime tower raft will be handled separately in 'storage.primeRaftOutline'; see below. @@ -56,9 +56,9 @@ void Raft::generate(SliceDataStorage& storage) // Find out if the prime-tower part of the raft still needs to be printed, even if there is no actual tower. // This will only happen if the different raft layers are printed by different extruders. const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; - const size_t base_extruder_nr = mesh_group_settings.get("raft_base_extruder_nr").extruder_nr; - const size_t interface_extruder_nr = mesh_group_settings.get("raft_interface_extruder_nr").extruder_nr; - const size_t surface_extruder_nr = mesh_group_settings.get("raft_surface_extruder_nr").extruder_nr; + const size_t base_extruder_nr = mesh_group_settings.get("raft_base_extruder_nr").extruder_nr_; + const size_t interface_extruder_nr = mesh_group_settings.get("raft_interface_extruder_nr").extruder_nr_; + const size_t surface_extruder_nr = mesh_group_settings.get("raft_surface_extruder_nr").extruder_nr_; if (base_extruder_nr == interface_extruder_nr && base_extruder_nr == surface_extruder_nr) { return; @@ -72,9 +72,9 @@ coord_t Raft::getTotalThickness() const ExtruderTrain& base_train = mesh_group_settings.get("raft_base_extruder_nr"); const ExtruderTrain& interface_train = mesh_group_settings.get("raft_interface_extruder_nr"); const ExtruderTrain& surface_train = mesh_group_settings.get("raft_surface_extruder_nr"); - return base_train.settings.get("raft_base_thickness") - + interface_train.settings.get("raft_interface_layers") * interface_train.settings.get("raft_interface_thickness") - + surface_train.settings.get("raft_surface_layers") * surface_train.settings.get("raft_surface_thickness"); + return base_train.settings_.get("raft_base_thickness") + + interface_train.settings_.get("raft_interface_layers") * interface_train.settings_.get("raft_interface_thickness") + + surface_train.settings_.get("raft_surface_layers") * surface_train.settings_.get("raft_surface_thickness"); } coord_t Raft::getZdiffBetweenRaftAndLayer0() @@ -85,7 +85,7 @@ coord_t Raft::getZdiffBetweenRaftAndLayer0() { return 0; } - const coord_t airgap = std::max(coord_t(0), train.settings.get("raft_airgap")); + const coord_t airgap = std::max(coord_t(0), train.settings_.get("raft_airgap")); return airgap; } @@ -114,11 +114,11 @@ size_t Raft::getTotalExtraLayers() const ExtruderTrain& base_train = mesh_group_settings.get("raft_base_extruder_nr"); const ExtruderTrain& interface_train = mesh_group_settings.get("raft_interface_extruder_nr"); const ExtruderTrain& surface_train = mesh_group_settings.get("raft_surface_extruder_nr"); - if (base_train.settings.get("adhesion_type") != EPlatformAdhesion::RAFT) + if (base_train.settings_.get("adhesion_type") != EPlatformAdhesion::RAFT) { return 0; } - return 1 + interface_train.settings.get("raft_interface_layers") + surface_train.settings.get("raft_surface_layers") + getFillerLayerCount(); + return 1 + interface_train.settings_.get("raft_interface_layers") + surface_train.settings_.get("raft_surface_layers") + getFillerLayerCount(); } diff --git a/src/settings/MeshPathConfigs.cpp b/src/settings/MeshPathConfigs.cpp index d91595ce37..fffc0d311a 100644 --- a/src/settings/MeshPathConfigs.cpp +++ b/src/settings/MeshPathConfigs.cpp @@ -3,18 +3,18 @@ #include "settings/MeshPathConfigs.h" +#include + #include "ExtruderTrain.h" #include "PrintFeature.h" -#include - namespace cura { MeshPathConfigs::MeshPathConfigs(const SliceMeshStorage& mesh, const coord_t layer_thickness, const LayerIndex layer_nr, const std::vector& line_width_factor_per_extruder) : inset0_config{ .type = PrintFeatureType::OuterWall, .line_width = static_cast( - mesh.settings.get("wall_line_width_0") * line_width_factor_per_extruder[mesh.settings.get("wall_0_extruder_nr").extruder_nr]), + mesh.settings.get("wall_line_width_0") * line_width_factor_per_extruder[mesh.settings.get("wall_0_extruder_nr").extruder_nr_]), .layer_thickness = layer_thickness, .flow = mesh.settings.get("wall_0_material_flow") * (layer_nr == 0 ? mesh.settings.get("wall_0_material_flow_layer_0") : Ratio{ 1.0 }), .speed_derivatives = { .speed = mesh.settings.get("speed_wall_0"), @@ -22,7 +22,7 @@ MeshPathConfigs::MeshPathConfigs(const SliceMeshStorage& mesh, const coord_t lay .jerk = mesh.settings.get("jerk_wall_0") } } , insetX_config{ .type = PrintFeatureType::InnerWall, .line_width = static_cast( - mesh.settings.get("wall_line_width_x") * line_width_factor_per_extruder[mesh.settings.get("wall_x_extruder_nr").extruder_nr]), + mesh.settings.get("wall_line_width_x") * line_width_factor_per_extruder[mesh.settings.get("wall_x_extruder_nr").extruder_nr_]), .layer_thickness = layer_thickness, .flow = mesh.settings.get("wall_x_material_flow") * (layer_nr == 0 ? mesh.settings.get("wall_x_material_flow_layer_0") : Ratio{ 1.0 }), .speed_derivatives = { .speed = mesh.settings.get("speed_wall_x"), @@ -31,7 +31,7 @@ MeshPathConfigs::MeshPathConfigs(const SliceMeshStorage& mesh, const coord_t lay , inset0_roofing_config{ .type = PrintFeatureType::OuterWall, .line_width = static_cast( mesh.settings.get("wall_line_width_0") - * line_width_factor_per_extruder[mesh.settings.get("wall_0_extruder_nr").extruder_nr]), + * line_width_factor_per_extruder[mesh.settings.get("wall_0_extruder_nr").extruder_nr_]), .layer_thickness = layer_thickness, .flow = mesh.settings.get("wall_0_material_flow_roofing") * (layer_nr == 0 ? mesh.settings.get("wall_0_material_flow_layer_0") : Ratio{ 1.0 }), @@ -41,7 +41,7 @@ MeshPathConfigs::MeshPathConfigs(const SliceMeshStorage& mesh, const coord_t lay , insetX_roofing_config{ .type = PrintFeatureType::InnerWall, .line_width = static_cast( mesh.settings.get("wall_line_width_x") - * line_width_factor_per_extruder[mesh.settings.get("wall_x_extruder_nr").extruder_nr]), + * line_width_factor_per_extruder[mesh.settings.get("wall_x_extruder_nr").extruder_nr_]), .layer_thickness = layer_thickness, .flow = mesh.settings.get("wall_x_material_flow_roofing") * (layer_nr == 0 ? mesh.settings.get("wall_x_material_flow_layer_0") : Ratio{ 1.0 }), @@ -51,7 +51,7 @@ MeshPathConfigs::MeshPathConfigs(const SliceMeshStorage& mesh, const coord_t lay , bridge_inset0_config{ .type = PrintFeatureType::OuterWall, .line_width = static_cast( mesh.settings.get("wall_line_width_0") - * line_width_factor_per_extruder[mesh.settings.get("wall_0_extruder_nr").extruder_nr]), + * line_width_factor_per_extruder[mesh.settings.get("wall_0_extruder_nr").extruder_nr_]), .layer_thickness = layer_thickness, .flow = mesh.settings.get("bridge_wall_material_flow"), .speed_derivatives = { .speed = mesh.settings.get("bridge_wall_speed"), @@ -62,7 +62,7 @@ MeshPathConfigs::MeshPathConfigs(const SliceMeshStorage& mesh, const coord_t lay , bridge_insetX_config{ .type = PrintFeatureType::InnerWall, .line_width = static_cast( mesh.settings.get("wall_line_width_x") - * line_width_factor_per_extruder[mesh.settings.get("wall_x_extruder_nr").extruder_nr]), + * line_width_factor_per_extruder[mesh.settings.get("wall_x_extruder_nr").extruder_nr_]), .layer_thickness = layer_thickness, .flow = mesh.settings.get("bridge_wall_material_flow"), .speed_derivatives = { .speed = mesh.settings.get("bridge_wall_speed"), @@ -72,7 +72,7 @@ MeshPathConfigs::MeshPathConfigs(const SliceMeshStorage& mesh, const coord_t lay .fan_speed = mesh.settings.get("bridge_fan_speed") * 100.0 } , skin_config{ .type = PrintFeatureType::Skin, .line_width = static_cast( - mesh.settings.get("skin_line_width") * line_width_factor_per_extruder[mesh.settings.get("top_bottom_extruder_nr").extruder_nr]), + mesh.settings.get("skin_line_width") * line_width_factor_per_extruder[mesh.settings.get("top_bottom_extruder_nr").extruder_nr_]), .layer_thickness = layer_thickness, .flow = mesh.settings.get("skin_material_flow") * (layer_nr == 0 ? mesh.settings.get("skin_material_flow_layer_0") : Ratio{ 1.0 }), .speed_derivatives = { .speed = mesh.settings.get("speed_topbottom"), @@ -81,7 +81,7 @@ MeshPathConfigs::MeshPathConfigs(const SliceMeshStorage& mesh, const coord_t lay , bridge_skin_config{ .type = PrintFeatureType::Skin, .line_width = static_cast( mesh.settings.get("skin_line_width") - * line_width_factor_per_extruder[mesh.settings.get("top_bottom_extruder_nr").extruder_nr]), + * line_width_factor_per_extruder[mesh.settings.get("top_bottom_extruder_nr").extruder_nr_]), .layer_thickness = layer_thickness, .flow = mesh.settings.get("bridge_skin_material_flow"), .speed_derivatives = { .speed = mesh.settings.get("bridge_skin_speed"), @@ -92,7 +92,7 @@ MeshPathConfigs::MeshPathConfigs(const SliceMeshStorage& mesh, const coord_t lay , bridge_skin_config2{ .type = PrintFeatureType::Skin, .line_width = static_cast( mesh.settings.get("skin_line_width") - * line_width_factor_per_extruder[mesh.settings.get("top_bottom_extruder_nr").extruder_nr]), + * line_width_factor_per_extruder[mesh.settings.get("top_bottom_extruder_nr").extruder_nr_]), .layer_thickness = layer_thickness, .flow = mesh.settings.get("bridge_skin_material_flow_2"), .speed_derivatives = { .speed = mesh.settings.get("bridge_skin_speed_2"), @@ -103,7 +103,7 @@ MeshPathConfigs::MeshPathConfigs(const SliceMeshStorage& mesh, const coord_t lay , bridge_skin_config3{ .type = PrintFeatureType::Skin, .line_width = static_cast( mesh.settings.get("skin_line_width") - * line_width_factor_per_extruder[mesh.settings.get("top_bottom_extruder_nr").extruder_nr]), + * line_width_factor_per_extruder[mesh.settings.get("top_bottom_extruder_nr").extruder_nr_]), .layer_thickness = layer_thickness, .flow = mesh.settings.get("bridge_skin_material_flow_3"), .speed_derivatives = { .speed = mesh.settings.get("bridge_skin_speed_3"), @@ -134,7 +134,7 @@ MeshPathConfigs::MeshPathConfigs(const SliceMeshStorage& mesh, const coord_t lay infill_config.emplace_back(GCodePathConfig{ .type = PrintFeatureType::Infill, .line_width = static_cast( - mesh.settings.get("infill_line_width") * line_width_factor_per_extruder[mesh.settings.get("infill_extruder_nr").extruder_nr]), + mesh.settings.get("infill_line_width") * line_width_factor_per_extruder[mesh.settings.get("infill_extruder_nr").extruder_nr_]), .layer_thickness = layer_thickness, .flow = mesh.settings.get("infill_material_flow") * (layer_nr == 0 ? mesh.settings.get("material_flow_layer_0") : Ratio{ 1.0 }) * combine_idx, .speed_derivatives = { .speed = mesh.settings.get("speed_infill"), @@ -143,4 +143,4 @@ MeshPathConfigs::MeshPathConfigs(const SliceMeshStorage& mesh, const coord_t lay } } -} // namespace cura \ No newline at end of file +} // namespace cura diff --git a/src/settings/PathConfigStorage.cpp b/src/settings/PathConfigStorage.cpp index 2ecf94eb70..5ac58e7950 100644 --- a/src/settings/PathConfigStorage.cpp +++ b/src/settings/PathConfigStorage.cpp @@ -21,7 +21,7 @@ std::vector PathConfigStorage::getLineWidthFactorPerExtruder(const LayerI { if (layer_nr <= 0) { - const Ratio factor = train.settings.get("initial_layer_line_width_factor"); + const Ratio factor = train.settings_.get("initial_layer_line_width_factor"); ret.push_back(factor); } else @@ -33,9 +33,9 @@ std::vector PathConfigStorage::getLineWidthFactorPerExtruder(const LayerI } PathConfigStorage::PathConfigStorage(const SliceDataStorage& storage, const LayerIndex& layer_nr, const coord_t layer_thickness) - : support_infill_extruder_nr(Application::getInstance().current_slice->scene.current_mesh_group->settings.get("support_infill_extruder_nr").extruder_nr) - , support_roof_extruder_nr(Application::getInstance().current_slice->scene.current_mesh_group->settings.get("support_roof_extruder_nr").extruder_nr) - , support_bottom_extruder_nr(Application::getInstance().current_slice->scene.current_mesh_group->settings.get("support_bottom_extruder_nr").extruder_nr) + : support_infill_extruder_nr(Application::getInstance().current_slice->scene.current_mesh_group->settings.get("support_infill_extruder_nr").extruder_nr_) + , support_roof_extruder_nr(Application::getInstance().current_slice->scene.current_mesh_group->settings.get("support_roof_extruder_nr").extruder_nr_) + , support_bottom_extruder_nr(Application::getInstance().current_slice->scene.current_mesh_group->settings.get("support_bottom_extruder_nr").extruder_nr_) , raft_base_train(Application::getInstance().current_slice->scene.current_mesh_group->settings.get("raft_base_extruder_nr")) , raft_interface_train(Application::getInstance().current_slice->scene.current_mesh_group->settings.get("raft_interface_extruder_nr")) , raft_surface_train(Application::getInstance().current_slice->scene.current_mesh_group->settings.get("raft_surface_extruder_nr")) @@ -44,44 +44,44 @@ PathConfigStorage::PathConfigStorage(const SliceDataStorage& storage, const Laye , support_bottom_train(Application::getInstance().current_slice->scene.extruders[support_bottom_extruder_nr]) , line_width_factor_per_extruder(PathConfigStorage::getLineWidthFactorPerExtruder(layer_nr)) , raft_base_config(GCodePathConfig{ .type = PrintFeatureType::SupportInterface, - .line_width = raft_base_train.settings.get("raft_base_line_width"), - .layer_thickness = raft_base_train.settings.get("raft_base_thickness"), + .line_width = raft_base_train.settings_.get("raft_base_line_width"), + .layer_thickness = raft_base_train.settings_.get("raft_base_thickness"), .flow = Ratio(1.0), - .speed_derivatives = SpeedDerivatives{ .speed = raft_base_train.settings.get("raft_base_speed"), - .acceleration = raft_base_train.settings.get("raft_base_acceleration"), - .jerk = raft_base_train.settings.get("raft_base_jerk") } }) + .speed_derivatives = SpeedDerivatives{ .speed = raft_base_train.settings_.get("raft_base_speed"), + .acceleration = raft_base_train.settings_.get("raft_base_acceleration"), + .jerk = raft_base_train.settings_.get("raft_base_jerk") } }) , raft_interface_config(GCodePathConfig{ .type = PrintFeatureType::Support, - .line_width = raft_interface_train.settings.get("raft_interface_line_width"), - .layer_thickness = raft_interface_train.settings.get("raft_interface_thickness"), + .line_width = raft_interface_train.settings_.get("raft_interface_line_width"), + .layer_thickness = raft_interface_train.settings_.get("raft_interface_thickness"), .flow = Ratio(1.0), - .speed_derivatives = SpeedDerivatives{ .speed = raft_interface_train.settings.get("raft_interface_speed"), - .acceleration = raft_interface_train.settings.get("raft_interface_acceleration"), - .jerk = raft_interface_train.settings.get("raft_interface_jerk") } }) + .speed_derivatives = SpeedDerivatives{ .speed = raft_interface_train.settings_.get("raft_interface_speed"), + .acceleration = raft_interface_train.settings_.get("raft_interface_acceleration"), + .jerk = raft_interface_train.settings_.get("raft_interface_jerk") } }) , raft_surface_config(GCodePathConfig{ .type = PrintFeatureType::SupportInterface, - .line_width = raft_surface_train.settings.get("raft_surface_line_width"), - .layer_thickness = raft_surface_train.settings.get("raft_surface_thickness"), + .line_width = raft_surface_train.settings_.get("raft_surface_line_width"), + .layer_thickness = raft_surface_train.settings_.get("raft_surface_thickness"), .flow = Ratio(1.0), - .speed_derivatives = SpeedDerivatives{ .speed = raft_surface_train.settings.get("raft_surface_speed"), - .acceleration = raft_surface_train.settings.get("raft_surface_acceleration"), - .jerk = raft_surface_train.settings.get("raft_surface_jerk") } }) + .speed_derivatives = SpeedDerivatives{ .speed = raft_surface_train.settings_.get("raft_surface_speed"), + .acceleration = raft_surface_train.settings_.get("raft_surface_acceleration"), + .jerk = raft_surface_train.settings_.get("raft_surface_jerk") } }) , support_roof_config(GCodePathConfig{ .type = PrintFeatureType::SupportInterface, - .line_width = static_cast(support_roof_train.settings.get("support_roof_line_width") * line_width_factor_per_extruder[support_roof_extruder_nr]), + .line_width = static_cast(support_roof_train.settings_.get("support_roof_line_width") * line_width_factor_per_extruder[support_roof_extruder_nr]), .layer_thickness = layer_thickness, - .flow - = support_roof_train.settings.get("support_roof_material_flow") * ((layer_nr == 0) ? support_roof_train.settings.get("material_flow_layer_0") : Ratio(1.0)), - .speed_derivatives = { .speed = support_roof_train.settings.get("speed_support_roof"), - .acceleration = support_roof_train.settings.get("acceleration_support_roof"), - .jerk = support_roof_train.settings.get("jerk_support_roof") } }) + .flow = support_roof_train.settings_.get("support_roof_material_flow") + * ((layer_nr == 0) ? support_roof_train.settings_.get("material_flow_layer_0") : Ratio(1.0)), + .speed_derivatives = { .speed = support_roof_train.settings_.get("speed_support_roof"), + .acceleration = support_roof_train.settings_.get("acceleration_support_roof"), + .jerk = support_roof_train.settings_.get("jerk_support_roof") } }) , support_bottom_config(GCodePathConfig{ .type = PrintFeatureType::SupportInterface, - .line_width = static_cast(support_bottom_train.settings.get("support_bottom_line_width") * line_width_factor_per_extruder[support_bottom_extruder_nr]), + .line_width = static_cast(support_bottom_train.settings_.get("support_bottom_line_width") * line_width_factor_per_extruder[support_bottom_extruder_nr]), .layer_thickness = layer_thickness, - .flow = support_roof_train.settings.get("support_bottom_material_flow") - * ((layer_nr == 0) ? support_roof_train.settings.get("material_flow_layer_0") : Ratio(1.0)), - .speed_derivatives = SpeedDerivatives{ .speed = support_bottom_train.settings.get("speed_support_bottom"), - .acceleration = support_bottom_train.settings.get("acceleration_support_bottom"), - .jerk = support_bottom_train.settings.get("jerk_support_bottom") } }) + .flow = support_roof_train.settings_.get("support_bottom_material_flow") + * ((layer_nr == 0) ? support_roof_train.settings_.get("material_flow_layer_0") : Ratio(1.0)), + .speed_derivatives = SpeedDerivatives{ .speed = support_bottom_train.settings_.get("speed_support_bottom"), + .acceleration = support_bottom_train.settings_.get("acceleration_support_bottom"), + .jerk = support_bottom_train.settings_.get("jerk_support_bottom") } }) { const size_t extruder_count = Application::getInstance().current_slice->scene.extruders.size(); travel_config_per_extruder.reserve(extruder_count); @@ -95,32 +95,32 @@ PathConfigStorage::PathConfigStorage(const SliceDataStorage& storage, const Laye .line_width = 0, .layer_thickness = 0, .flow = 0.0, - .speed_derivatives = SpeedDerivatives{ .speed = train.settings.get("speed_travel"), - .acceleration = train.settings.get("acceleration_travel"), - .jerk = train.settings.get("jerk_travel") } }); + .speed_derivatives = SpeedDerivatives{ .speed = train.settings_.get("speed_travel"), + .acceleration = train.settings_.get("acceleration_travel"), + .jerk = train.settings_.get("jerk_travel") } }); skirt_brim_config_per_extruder.emplace_back( GCodePathConfig{ .type = PrintFeatureType::SkirtBrim, .line_width = static_cast( - train.settings.get("skirt_brim_line_width") + train.settings_.get("skirt_brim_line_width") * ((mesh_group_settings.get("adhesion_type") == EPlatformAdhesion::RAFT) ? 1.0_r : line_width_factor_per_extruder[extruder_nr])) // cause it's also used for the draft/ooze shield , .layer_thickness = layer_thickness, - .flow = train.settings.get("skirt_brim_material_flow") * ((layer_nr == 0) ? train.settings.get("material_flow_layer_0") : Ratio(1.0)), - .speed_derivatives = SpeedDerivatives{ .speed = train.settings.get("skirt_brim_speed"), - .acceleration = train.settings.get("acceleration_skirt_brim"), - .jerk = train.settings.get("jerk_skirt_brim") } }); + .flow = train.settings_.get("skirt_brim_material_flow") * ((layer_nr == 0) ? train.settings_.get("material_flow_layer_0") : Ratio(1.0)), + .speed_derivatives = SpeedDerivatives{ .speed = train.settings_.get("skirt_brim_speed"), + .acceleration = train.settings_.get("acceleration_skirt_brim"), + .jerk = train.settings_.get("jerk_skirt_brim") } }); prime_tower_config_per_extruder.emplace_back(GCodePathConfig{ .type = PrintFeatureType::PrimeTower, .line_width = static_cast( - train.settings.get("prime_tower_line_width") + train.settings_.get("prime_tower_line_width") * ((mesh_group_settings.get("adhesion_type") == EPlatformAdhesion::RAFT) ? 1.0_r : line_width_factor_per_extruder[extruder_nr])), .layer_thickness = layer_thickness, - .flow = train.settings.get("prime_tower_flow") * ((layer_nr == 0) ? train.settings.get("material_flow_layer_0") : Ratio(1.0)), - .speed_derivatives = SpeedDerivatives{ .speed = train.settings.get("speed_prime_tower"), - .acceleration = train.settings.get("acceleration_prime_tower"), - .jerk = train.settings.get("jerk_prime_tower") } }); + .flow = train.settings_.get("prime_tower_flow") * ((layer_nr == 0) ? train.settings_.get("material_flow_layer_0") : Ratio(1.0)), + .speed_derivatives = SpeedDerivatives{ .speed = train.settings_.get("speed_prime_tower"), + .acceleration = train.settings_.get("acceleration_prime_tower"), + .jerk = train.settings_.get("jerk_prime_tower") } }); } mesh_configs.reserve(storage.meshes.size()); @@ -136,13 +136,13 @@ PathConfigStorage::PathConfigStorage(const SliceDataStorage& storage, const Laye { support_infill_config.emplace_back( GCodePathConfig{ .type = PrintFeatureType::Support, - .line_width = static_cast(support_infill_train.settings.get("support_line_width") * support_infill_line_width_factor), + .line_width = static_cast(support_infill_train.settings_.get("support_line_width") * support_infill_line_width_factor), .layer_thickness = layer_thickness, - .flow = support_infill_train.settings.get("support_material_flow") - * ((layer_nr == 0) ? support_infill_train.settings.get("material_flow_layer_0") : Ratio(1.0)) * (combine_idx + 1), - .speed_derivatives = SpeedDerivatives{ .speed = support_infill_train.settings.get("speed_support_infill"), - .acceleration = support_infill_train.settings.get("acceleration_support_infill"), - .jerk = support_infill_train.settings.get("jerk_support_infill") } }); + .flow = support_infill_train.settings_.get("support_material_flow") + * ((layer_nr == 0) ? support_infill_train.settings_.get("material_flow_layer_0") : Ratio(1.0)) * (combine_idx + 1), + .speed_derivatives = SpeedDerivatives{ .speed = support_infill_train.settings_.get("speed_support_infill"), + .acceleration = support_infill_train.settings_.get("acceleration_support_infill"), + .jerk = support_infill_train.settings_.get("jerk_support_infill") } }); } const size_t initial_speedup_layer_count = mesh_group_settings.get("speed_slowdown_layers"); @@ -186,9 +186,9 @@ void PathConfigStorage::handleInitialLayerSpeedup(const SliceDataStorage& storag global_first_layer_config_per_extruder.reserve(Application::getInstance().current_slice->scene.extruders.size()); for (const ExtruderTrain& extruder : Application::getInstance().current_slice->scene.extruders) { - global_first_layer_config_per_extruder.emplace_back(SpeedDerivatives{ .speed = extruder.settings.get("speed_print_layer_0"), - .acceleration = extruder.settings.get("acceleration_print_layer_0"), - .jerk = extruder.settings.get("jerk_print_layer_0") }); + global_first_layer_config_per_extruder.emplace_back(SpeedDerivatives{ .speed = extruder.settings_.get("speed_print_layer_0"), + .acceleration = extruder.settings_.get("acceleration_print_layer_0"), + .jerk = extruder.settings_.get("jerk_print_layer_0") }); } { // support @@ -196,7 +196,7 @@ void PathConfigStorage::handleInitialLayerSpeedup(const SliceDataStorage& storag { const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; const size_t extruder_nr_support_infill - = mesh_group_settings.get((layer_nr <= 0) ? "support_extruder_nr_layer_0" : "support_infill_extruder_nr").extruder_nr; + = mesh_group_settings.get((layer_nr <= 0) ? "support_extruder_nr_layer_0" : "support_infill_extruder_nr").extruder_nr_; for (unsigned int idx = 0; idx < MAX_INFILL_COMBINE; idx++) { support_infill_config[idx].speed_derivatives.smoothSpeed( @@ -204,12 +204,12 @@ void PathConfigStorage::handleInitialLayerSpeedup(const SliceDataStorage& storag std::max(LayerIndex(0), layer_nr), initial_speedup_layer_count); } - const size_t extruder_nr_support_roof = mesh_group_settings.get("support_roof_extruder_nr").extruder_nr; + const size_t extruder_nr_support_roof = mesh_group_settings.get("support_roof_extruder_nr").extruder_nr_; support_roof_config.speed_derivatives.smoothSpeed( global_first_layer_config_per_extruder[extruder_nr_support_roof], std::max(LayerIndex(0), layer_nr), initial_speedup_layer_count); - const size_t extruder_nr_support_bottom = mesh_group_settings.get("support_bottom_extruder_nr").extruder_nr; + const size_t extruder_nr_support_bottom = mesh_group_settings.get("support_bottom_extruder_nr").extruder_nr_; support_bottom_config.speed_derivatives.smoothSpeed( global_first_layer_config_per_extruder[extruder_nr_support_bottom], std::max(LayerIndex(0), layer_nr), @@ -221,9 +221,9 @@ void PathConfigStorage::handleInitialLayerSpeedup(const SliceDataStorage& storag for (size_t extruder_nr = 0; extruder_nr < Application::getInstance().current_slice->scene.extruders.size(); extruder_nr++) { const ExtruderTrain& train = Application::getInstance().current_slice->scene.extruders[extruder_nr]; - const SpeedDerivatives initial_layer_travel_speed_config{ .speed = train.settings.get("speed_travel_layer_0"), - .acceleration = train.settings.get("acceleration_travel_layer_0"), - .jerk = train.settings.get("jerk_travel_layer_0") }; + const SpeedDerivatives initial_layer_travel_speed_config{ .speed = train.settings_.get("speed_travel_layer_0"), + .acceleration = train.settings_.get("acceleration_travel_layer_0"), + .jerk = train.settings_.get("jerk_travel_layer_0") }; GCodePathConfig& travel = travel_config_per_extruder[extruder_nr]; travel.speed_derivatives.smoothSpeed(initial_layer_travel_speed_config, std::max(LayerIndex(0), layer_nr), initial_speedup_layer_count); diff --git a/src/settings/Settings.cpp b/src/settings/Settings.cpp index 22cf7d1c8b..9b8e609df4 100644 --- a/src/settings/Settings.cpp +++ b/src/settings/Settings.cpp @@ -3,6 +3,17 @@ #include "settings/Settings.h" +#include +#include +#include // regex parsing for temp flow graph +#include // ostringstream +#include +#include //Parsing strings (stod, stoul). + +#include +#include +#include + #include "Application.h" //To get the extruders. #include "BeadingStrategy/BeadingStrategyFactory.h" #include "ExtruderTrain.h" @@ -20,17 +31,6 @@ #include "utils/string.h" //For Escaped. #include "utils/types/string_switch.h" //For string switch. -#include -#include -#include - -#include -#include -#include // regex parsing for temp flow graph -#include // ostringstream -#include -#include //Parsing strings (stod, stoul). - namespace cura { @@ -63,7 +63,7 @@ std::string Settings::get(const std::string& key) const const std::unordered_map& limit_to_extruder = Application::getInstance().current_slice->scene.limit_to_extruder; if (limit_to_extruder.find(key) != limit_to_extruder.end()) { - return limit_to_extruder.at(key)->settings.getWithoutLimiting(key); + return limit_to_extruder.at(key)->settings_.getWithoutLimiting(key); } if (parent) diff --git a/src/skin.cpp b/src/skin.cpp index 28fc60c238..3b01559d4e 100644 --- a/src/skin.cpp +++ b/src/skin.cpp @@ -28,7 +28,7 @@ coord_t SkinInfillAreaComputation::getSkinLineWidth(const SliceMeshStorage& mesh if (layer_nr == 0) { const ExtruderTrain& train_skin = mesh.settings.get("top_bottom_extruder_nr"); - skin_line_width *= train_skin.settings.get("initial_layer_line_width_factor"); + skin_line_width *= train_skin.settings_.get("initial_layer_line_width_factor"); } return skin_line_width; } diff --git a/src/sliceDataStorage.cpp b/src/sliceDataStorage.cpp index 2d2741ad8a..bbffb53e7d 100644 --- a/src/sliceDataStorage.cpp +++ b/src/sliceDataStorage.cpp @@ -111,7 +111,7 @@ bool SliceMeshStorage::getExtruderIsUsed(const size_t extruder_nr) const } if (settings.get("magic_spiralize")) { - if (settings.get("wall_0_extruder_nr").extruder_nr == extruder_nr) + if (settings.get("wall_0_extruder_nr").extruder_nr_ == extruder_nr) { return true; } @@ -120,29 +120,29 @@ bool SliceMeshStorage::getExtruderIsUsed(const size_t extruder_nr) const return false; } } - if (settings.get("magic_mesh_surface_mode") != ESurfaceMode::NORMAL && settings.get("wall_0_extruder_nr").extruder_nr == extruder_nr) + if (settings.get("magic_mesh_surface_mode") != ESurfaceMode::NORMAL && settings.get("wall_0_extruder_nr").extruder_nr_ == extruder_nr) { return true; } - if (settings.get("wall_line_count") > 0 && settings.get("wall_0_extruder_nr").extruder_nr == extruder_nr) + if (settings.get("wall_line_count") > 0 && settings.get("wall_0_extruder_nr").extruder_nr_ == extruder_nr) { return true; } if ((settings.get("wall_line_count") > 1 || settings.get("alternate_extra_perimeter")) - && settings.get("wall_x_extruder_nr").extruder_nr == extruder_nr) + && settings.get("wall_x_extruder_nr").extruder_nr_ == extruder_nr) { return true; } - if (settings.get("infill_line_distance") > 0 && settings.get("infill_extruder_nr").extruder_nr == extruder_nr) + if (settings.get("infill_line_distance") > 0 && settings.get("infill_extruder_nr").extruder_nr_ == extruder_nr) { return true; } - if ((settings.get("top_layers") > 0 || settings.get("bottom_layers") > 0) && settings.get("top_bottom_extruder_nr").extruder_nr == extruder_nr) + if ((settings.get("top_layers") > 0 || settings.get("bottom_layers") > 0) && settings.get("top_bottom_extruder_nr").extruder_nr_ == extruder_nr) { return true; } const size_t roofing_layer_count = std::min(settings.get("roofing_layer_count"), settings.get("top_layers")); - if (roofing_layer_count > 0 && settings.get("roofing_extruder_nr").extruder_nr == extruder_nr) + if (roofing_layer_count > 0 && settings.get("roofing_extruder_nr").extruder_nr_ == extruder_nr) { return true; } @@ -160,7 +160,7 @@ bool SliceMeshStorage::getExtruderIsUsed(const size_t extruder_nr, const LayerIn return false; } const SliceLayer& layer = layers[layer_nr]; - if (settings.get("wall_0_extruder_nr").extruder_nr == extruder_nr + if (settings.get("wall_0_extruder_nr").extruder_nr_ == extruder_nr && (settings.get("wall_line_count") > 0 || settings.get("skin_outline_count") > 0)) { for (const SliceLayerPart& part : layer.parts) @@ -171,13 +171,13 @@ bool SliceMeshStorage::getExtruderIsUsed(const size_t extruder_nr, const LayerIn } } } - if (settings.get("magic_mesh_surface_mode") != ESurfaceMode::NORMAL && settings.get("wall_0_extruder_nr").extruder_nr == extruder_nr + if (settings.get("magic_mesh_surface_mode") != ESurfaceMode::NORMAL && settings.get("wall_0_extruder_nr").extruder_nr_ == extruder_nr && layer.openPolyLines.size() > 0) { return true; } if ((settings.get("wall_line_count") > 1 || settings.get("alternate_extra_perimeter")) - && settings.get("wall_x_extruder_nr").extruder_nr == extruder_nr) + && settings.get("wall_x_extruder_nr").extruder_nr_ == extruder_nr) { for (const SliceLayerPart& part : layer.parts) { @@ -187,7 +187,7 @@ bool SliceMeshStorage::getExtruderIsUsed(const size_t extruder_nr, const LayerIn } } } - if (settings.get("infill_line_distance") > 0 && settings.get("infill_extruder_nr").extruder_nr == extruder_nr) + if (settings.get("infill_line_distance") > 0 && settings.get("infill_extruder_nr").extruder_nr_ == extruder_nr) { for (const SliceLayerPart& part : layer.parts) { @@ -197,7 +197,7 @@ bool SliceMeshStorage::getExtruderIsUsed(const size_t extruder_nr, const LayerIn } } } - if (settings.get("top_bottom_extruder_nr").extruder_nr == extruder_nr) + if (settings.get("top_bottom_extruder_nr").extruder_nr_ == extruder_nr) { for (const SliceLayerPart& part : layer.parts) { @@ -210,7 +210,7 @@ bool SliceMeshStorage::getExtruderIsUsed(const size_t extruder_nr, const LayerIn } } } - if (settings.get("roofing_extruder_nr").extruder_nr == extruder_nr) + if (settings.get("roofing_extruder_nr").extruder_nr_ == extruder_nr) { for (const SliceLayerPart& part : layer.parts) { @@ -273,7 +273,7 @@ Polygons const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; if (layer_nr < 0 && layer_nr < -static_cast(Raft::getFillerLayerCount())) { // when processing raft - if (include_support && (extruder_nr == -1 || extruder_nr == int(mesh_group_settings.get("adhesion_extruder_nr").extruder_nr))) + if (include_support && (extruder_nr == -1 || extruder_nr == int(mesh_group_settings.get("adhesion_extruder_nr").extruder_nr_))) { if (external_polys_only) { @@ -303,7 +303,7 @@ Polygons for (const std::shared_ptr& mesh : meshes) { if (mesh->settings.get("infill_mesh") || mesh->settings.get("anti_overhang_mesh") - || (extruder_nr != -1 && extruder_nr != int(mesh->settings.get("wall_0_extruder_nr").extruder_nr))) + || (extruder_nr != -1 && extruder_nr != int(mesh->settings.get("wall_0_extruder_nr").extruder_nr_))) { continue; } @@ -315,7 +315,7 @@ Polygons } } } - if (include_support && (extruder_nr == -1 || extruder_nr == int(mesh_group_settings.get("support_infill_extruder_nr").extruder_nr))) + if (include_support && (extruder_nr == -1 || extruder_nr == int(mesh_group_settings.get("support_infill_extruder_nr").extruder_nr_))) { const SupportLayer& support_layer = support.supportLayers[std::max(LayerIndex(0), layer_nr)]; if (support.generated) @@ -364,16 +364,16 @@ std::vector SliceDataStorage::getExtrudersUsed() const } else if (adhesion_type == EPlatformAdhesion::RAFT) { - ret[mesh_group_settings.get("raft_base_extruder_nr").extruder_nr] = true; - const size_t num_interface_layers = mesh_group_settings.get("raft_interface_extruder_nr").settings.get("raft_interface_layers"); + ret[mesh_group_settings.get("raft_base_extruder_nr").extruder_nr_] = true; + const size_t num_interface_layers = mesh_group_settings.get("raft_interface_extruder_nr").settings_.get("raft_interface_layers"); if (num_interface_layers > 0) { - ret[mesh_group_settings.get("raft_interface_extruder_nr").extruder_nr] = true; + ret[mesh_group_settings.get("raft_interface_extruder_nr").extruder_nr_] = true; } - const size_t num_surface_layers = mesh_group_settings.get("raft_surface_extruder_nr").settings.get("raft_surface_layers"); + const size_t num_surface_layers = mesh_group_settings.get("raft_surface_extruder_nr").settings_.get("raft_surface_layers"); if (num_surface_layers > 0) { - ret[mesh_group_settings.get("raft_surface_extruder_nr").extruder_nr] = true; + ret[mesh_group_settings.get("raft_surface_extruder_nr").extruder_nr_] = true; } } @@ -385,15 +385,15 @@ std::vector SliceDataStorage::getExtrudersUsed() const { if (mesh->settings.get("support_enable") || mesh->settings.get("support_mesh")) { - ret[mesh_group_settings.get("support_extruder_nr_layer_0").extruder_nr] = true; - ret[mesh_group_settings.get("support_infill_extruder_nr").extruder_nr] = true; + ret[mesh_group_settings.get("support_extruder_nr_layer_0").extruder_nr_] = true; + ret[mesh_group_settings.get("support_infill_extruder_nr").extruder_nr_] = true; if (mesh_group_settings.get("support_roof_enable")) { - ret[mesh_group_settings.get("support_roof_extruder_nr").extruder_nr] = true; + ret[mesh_group_settings.get("support_roof_extruder_nr").extruder_nr_] = true; } if (mesh_group_settings.get("support_bottom_enable")) { - ret[mesh_group_settings.get("support_bottom_extruder_nr").extruder_nr] = true; + ret[mesh_group_settings.get("support_bottom_extruder_nr").extruder_nr_] = true; } } } @@ -451,11 +451,11 @@ std::vector SliceDataStorage::getExtrudersUsed(const LayerIndex layer_nr) const LayerIndex raft_layers = Raft::getTotalExtraLayers(); if (layer_nr == -raft_layers) // Base layer. { - ret[mesh_group_settings.get("raft_base_extruder_nr").extruder_nr] = true; + ret[mesh_group_settings.get("raft_base_extruder_nr").extruder_nr_] = true; // When using a raft, all prime blobs need to be on the lowest layer (the build plate). for (size_t extruder_nr = 0; extruder_nr < extruders.size(); ++extruder_nr) { - if (extruders[extruder_nr].settings.get("prime_blob_enable")) + if (extruders[extruder_nr].settings_.get("prime_blob_enable")) { ret[extruder_nr] = true; } @@ -463,11 +463,11 @@ std::vector SliceDataStorage::getExtrudersUsed(const LayerIndex layer_nr) } else if (layer_nr == -raft_layers + 1) // Interface layer. { - ret[mesh_group_settings.get("raft_interface_extruder_nr").extruder_nr] = true; + ret[mesh_group_settings.get("raft_interface_extruder_nr").extruder_nr_] = true; } else if (layer_nr < -static_cast(Raft::getFillerLayerCount())) // Any of the surface layers. { - ret[mesh_group_settings.get("raft_surface_extruder_nr").extruder_nr] = true; + ret[mesh_group_settings.get("raft_surface_extruder_nr").extruder_nr_] = true; } } } @@ -485,23 +485,23 @@ std::vector SliceDataStorage::getExtrudersUsed(const LayerIndex layer_nr) { if (! support_layer.support_infill_parts.empty()) { - ret[mesh_group_settings.get("support_extruder_nr_layer_0").extruder_nr] = true; + ret[mesh_group_settings.get("support_extruder_nr_layer_0").extruder_nr_] = true; } } else { if (! support_layer.support_infill_parts.empty()) { - ret[mesh_group_settings.get("support_infill_extruder_nr").extruder_nr] = true; + ret[mesh_group_settings.get("support_infill_extruder_nr").extruder_nr_] = true; } } if (! support_layer.support_bottom.empty()) { - ret[mesh_group_settings.get("support_bottom_extruder_nr").extruder_nr] = true; + ret[mesh_group_settings.get("support_bottom_extruder_nr").extruder_nr_] = true; } if (! support_layer.support_roof.empty()) { - ret[mesh_group_settings.get("support_roof_extruder_nr").extruder_nr] = true; + ret[mesh_group_settings.get("support_roof_extruder_nr").extruder_nr_] = true; } } } @@ -527,7 +527,7 @@ bool SliceDataStorage::getExtruderPrimeBlobEnabled(const size_t extruder_nr) con } const ExtruderTrain& train = Application::getInstance().current_slice->scene.extruders[extruder_nr]; - return train.settings.get("prime_blob_enable"); + return train.settings_.get("prime_blob_enable"); } Polygons SliceDataStorage::getMachineBorder(int checking_extruder_nr) const @@ -583,7 +583,7 @@ Polygons SliceDataStorage::getMachineBorder(int checking_extruder_nr) const { continue; } - Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder_nr].settings; + Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder_nr].settings_; if (! (extruder_settings.get("prime_blob_enable") && mesh_group_settings.get("extruder_prime_pos_abs"))) { continue; @@ -608,7 +608,7 @@ Polygons SliceDataStorage::getMachineBorder(int checking_extruder_nr) const { continue; } - Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder_nr].settings; + Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder_nr].settings_; Point translation(extruder_settings.get("machine_nozzle_offset_x"), extruder_settings.get("machine_nozzle_offset_y")); Polygons extruder_border = disallowed_areas; extruder_border.translate(translation); @@ -633,7 +633,7 @@ Polygons SliceDataStorage::getMachineBorder(int checking_extruder_nr) const { continue; } - Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder_nr].settings; + Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder_nr].settings_; Point translation(extruder_settings.get("machine_nozzle_offset_x"), extruder_settings.get("machine_nozzle_offset_y")); for (size_t other_extruder_nr = 0; other_extruder_nr < extruder_is_used.size(); other_extruder_nr++) { @@ -642,7 +642,7 @@ Polygons SliceDataStorage::getMachineBorder(int checking_extruder_nr) const { continue; } - Settings& other_extruder_settings = Application::getInstance().current_slice->scene.extruders[other_extruder_nr].settings; + Settings& other_extruder_settings = Application::getInstance().current_slice->scene.extruders[other_extruder_nr].settings_; Point other_translation(other_extruder_settings.get("machine_nozzle_offset_x"), other_extruder_settings.get("machine_nozzle_offset_y")); Polygons translated_border = border; translated_border.translate(translation - other_translation); diff --git a/src/support.cpp b/src/support.cpp index 233c8ab499..fb896445ce 100644 --- a/src/support.cpp +++ b/src/support.cpp @@ -92,11 +92,11 @@ void AreaSupport::splitGlobalSupportAreasIntoSupportInfillParts( const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; const ExtruderTrain& infill_extruder = mesh_group_settings.get("support_infill_extruder_nr"); - const EFillMethod support_pattern = infill_extruder.settings.get("support_pattern"); - const coord_t support_line_width = infill_extruder.settings.get("support_line_width"); + const EFillMethod support_pattern = infill_extruder.settings_.get("support_pattern"); + const coord_t support_line_width = infill_extruder.settings_.get("support_line_width"); // The wall line count is used for calculating insets, and we generate support infill patterns within the insets - const size_t wall_line_count = infill_extruder.settings.get("support_wall_count"); + const size_t wall_line_count = infill_extruder.settings_.get("support_wall_count"); // Generate separate support islands for (LayerIndex layer_nr = 0; layer_nr < total_layer_count - 1; ++layer_nr) @@ -118,7 +118,7 @@ void AreaSupport::splitGlobalSupportAreasIntoSupportInfillParts( coord_t support_line_width_here = support_line_width; if (layer_nr == 0 && mesh_group_settings.get("adhesion_type") != EPlatformAdhesion::RAFT) { - support_line_width_here *= infill_extruder.settings.get("initial_layer_line_width_factor"); + support_line_width_here *= infill_extruder.settings_.get("initial_layer_line_width_factor"); } // We don't generate insets and infill area for the parts yet because later the skirt/brim and prime // tower will remove themselves from the support, so the outlines of the parts can be changed. @@ -183,11 +183,11 @@ void AreaSupport::generateGradualSupport(SliceDataStorage& storage) const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; const size_t total_layer_count = storage.print_layer_count; const ExtruderTrain& infill_extruder = mesh_group_settings.get("support_infill_extruder_nr"); - const coord_t gradual_support_step_height = infill_extruder.settings.get("gradual_support_infill_step_height"); - const size_t max_density_steps = infill_extruder.settings.get("gradual_support_infill_steps"); + const coord_t gradual_support_step_height = infill_extruder.settings_.get("gradual_support_infill_step_height"); + const size_t max_density_steps = infill_extruder.settings_.get("gradual_support_infill_steps"); - const coord_t wall_count = infill_extruder.settings.get("support_wall_count"); - const coord_t wall_width = infill_extruder.settings.get("support_line_width"); + const coord_t wall_count = infill_extruder.settings_.get("support_wall_count"); + const coord_t wall_width = infill_extruder.settings_.get("support_line_width"); // no early-out for this function; it needs to initialize the [infill_area_per_combine_per_density] double layer_skip_count{ 8.0 }; // skip every so many layers as to ignore small gaps in the model making computation more easy @@ -228,7 +228,7 @@ void AreaSupport::generateGradualSupport(SliceDataStorage& storage) support_infill_part.inset_count_to_generate, wall_width, 0, - infill_extruder.settings, + infill_extruder.settings_, layer_nr, SectionType::SUPPORT); const AABB& this_part_boundary_box = support_infill_part.outline_boundary_box; @@ -320,7 +320,7 @@ void AreaSupport::combineSupportInfillLayers(SliceDataStorage& storage) // How many support infill layers to combine to obtain the requested sparse thickness. const ExtruderTrain& infill_extruder = mesh_group_settings.get("support_infill_extruder_nr"); const size_t combine_layers_amount - = std::max(uint64_t(1), round_divide(infill_extruder.settings.get("support_infill_sparse_thickness"), std::max(layer_height, coord_t(1)))); + = std::max(uint64_t(1), round_divide(infill_extruder.settings_.get("support_infill_sparse_thickness"), std::max(layer_height, coord_t(1)))); if (combine_layers_amount <= 1) { return; @@ -462,7 +462,7 @@ Polygons AreaSupport::join(const SliceDataStorage& storage, const Polygons& supp { Polygons joined; - const Settings& infill_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings.get("support_infill_extruder_nr").settings; + const Settings& infill_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings.get("support_infill_extruder_nr").settings_; const AngleRadians conical_support_angle = infill_settings.get("support_conical_angle"); const coord_t layer_thickness = infill_settings.get("layer_height"); coord_t conical_support_offset; @@ -515,7 +515,7 @@ Polygons AreaSupport::join(const SliceDataStorage& storage, const Polygons& supp continue; } const ExtruderTrain& other_extruder = Application::getInstance().current_slice->scene.extruders[extruder_nr]; - extra_skirt_line_width += other_extruder.settings.get("skirt_brim_line_width") * other_extruder.settings.get("initial_layer_line_width_factor"); + extra_skirt_line_width += other_extruder.settings_.get("skirt_brim_line_width") * other_extruder.settings_.get("initial_layer_line_width_factor"); } const std::vector skirt_brim_extruders = mesh_group_settings.get>("skirt_brim_extruder_nr"); auto adhesion_width_str{ "brim_width" }; @@ -533,18 +533,18 @@ Polygons AreaSupport::join(const SliceDataStorage& storage, const Polygons& supp adhesion_size = std::max( adhesion_size, coord_t( - skirt_brim_extruder.settings.get(adhesion_width_str) - + skirt_brim_extruder.settings.get("skirt_brim_line_width") - * (skirt_brim_extruder.settings.get(adhesion_line_count_str) - 1) // - 1 because the line is also included in extra_skirt_line_width - * skirt_brim_extruder.settings.get("initial_layer_line_width_factor") + skirt_brim_extruder.settings_.get(adhesion_width_str) + + skirt_brim_extruder.settings_.get("skirt_brim_line_width") + * (skirt_brim_extruder.settings_.get(adhesion_line_count_str) - 1) // - 1 because the line is also included in extra_skirt_line_width + * skirt_brim_extruder.settings_.get("initial_layer_line_width_factor") + extra_skirt_line_width)); } break; case EPlatformAdhesion::RAFT: { - adhesion_size = std::max({ mesh_group_settings.get("raft_base_extruder_nr").settings.get("raft_margin"), - mesh_group_settings.get("raft_interface_extruder_nr").settings.get("raft_margin"), - mesh_group_settings.get("raft_surface_extruder_nr").settings.get("raft_margin") }); + adhesion_size = std::max({ mesh_group_settings.get("raft_base_extruder_nr").settings_.get("raft_margin"), + mesh_group_settings.get("raft_interface_extruder_nr").settings_.get("raft_margin"), + mesh_group_settings.get("raft_surface_extruder_nr").settings_.get("raft_margin") }); break; } case EPlatformAdhesion::NONE: @@ -657,9 +657,9 @@ void AreaSupport::generateSupportAreas(SliceDataStorage& storage) // use extruder train settings rather than the per-object settings of the first support mesh encountered. // because all support meshes are processed at the same time it doesn't make sense to use the per-object settings of the first support mesh encountered. // instead we must use the support extruder settings, which is the settings base common to all support meshes. - infill_settings = &mesh_group_settings.get("support_infill_extruder_nr").settings; - roof_settings = &mesh_group_settings.get("support_roof_extruder_nr").settings; - bottom_settings = &mesh_group_settings.get("support_bottom_extruder_nr").settings; + infill_settings = &mesh_group_settings.get("support_infill_extruder_nr").settings_; + roof_settings = &mesh_group_settings.get("support_roof_extruder_nr").settings_; + bottom_settings = &mesh_group_settings.get("support_bottom_extruder_nr").settings_; if (mesh.settings.get("support_mesh_drop_down")) { support_meshes_drop_down_handled = true; @@ -711,8 +711,8 @@ void AreaSupport::precomputeCrossInfillTree(SliceDataStorage& storage) { const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; const ExtruderTrain& infill_extruder = mesh_group_settings.get("support_infill_extruder_nr"); - const EFillMethod& support_pattern = infill_extruder.settings.get("support_pattern"); - if ((support_pattern == EFillMethod::CROSS || support_pattern == EFillMethod::CROSS_3D) && infill_extruder.settings.get("support_line_distance") > 0) + const EFillMethod& support_pattern = infill_extruder.settings_.get("support_pattern"); + if ((support_pattern == EFillMethod::CROSS || support_pattern == EFillMethod::CROSS_3D) && infill_extruder.settings_.get("support_line_distance") > 0) { AABB3D aabb; for (unsigned int mesh_idx = 0; mesh_idx < storage.meshes.size(); mesh_idx++) @@ -728,7 +728,7 @@ void AreaSupport::precomputeCrossInfillTree(SliceDataStorage& storage) // use extruder train settings rather than the per-object settings of the first support mesh encountered. // because all support meshes are processed at the same time it doesn't make sense to use the per-object settings of the first support mesh encountered. // instead we must use the support extruder settings, which is the settings base common to all support meshes. - infill_settings = mesh_group_settings.get("support_infill_extruder_nr").settings; + infill_settings = mesh_group_settings.get("support_infill_extruder_nr").settings_; } const coord_t aabb_expansion = infill_settings.get("support_offset"); AABB3D aabb_here(mesh.bounding_box); @@ -737,14 +737,14 @@ void AreaSupport::precomputeCrossInfillTree(SliceDataStorage& storage) aabb.include(aabb_here); } - std::string cross_subdisivion_spec_image_file = infill_extruder.settings.get("cross_support_density_image"); + std::string cross_subdisivion_spec_image_file = infill_extruder.settings_.get("cross_support_density_image"); std::ifstream cross_fs(cross_subdisivion_spec_image_file.c_str()); if (cross_subdisivion_spec_image_file != "" && cross_fs.good()) { storage.support.cross_fill_provider = std::make_shared( aabb, - infill_extruder.settings.get("support_line_distance"), - infill_extruder.settings.get("support_line_width"), + infill_extruder.settings_.get("support_line_distance"), + infill_extruder.settings_.get("support_line_width"), cross_subdisivion_spec_image_file); } else @@ -755,8 +755,8 @@ void AreaSupport::precomputeCrossInfillTree(SliceDataStorage& storage) } storage.support.cross_fill_provider = std::make_shared( aabb, - infill_extruder.settings.get("support_line_distance"), - infill_extruder.settings.get("support_line_width")); + infill_extruder.settings_.get("support_line_distance"), + infill_extruder.settings_.get("support_line_width")); } } } @@ -1071,7 +1071,7 @@ void AreaSupport::generateSupportAreasForMesh( const double tan_angle = tan(angle) - 0.01; // the XY-component of the supportAngle constexpr bool no_support = false; constexpr bool no_prime_tower = false; - const coord_t support_line_width = mesh_group_settings.get("support_infill_extruder_nr").settings.get("support_line_width"); + const coord_t support_line_width = mesh_group_settings.get("support_infill_extruder_nr").settings_.get("support_line_width"); const double sloped_areas_angle = mesh.settings.get("support_bottom_stair_step_min_slope"); const coord_t sloped_area_detection_width = 10 + static_cast(layer_thickness / std::tan(sloped_areas_angle)) / 2; const double minimum_support_area = mesh.settings.get("minimum_support_area"); @@ -1144,19 +1144,19 @@ void AreaSupport::generateSupportAreasForMesh( coord_t smoothing_distance; { // compute best smoothing_distance const ExtruderTrain& infill_train = mesh_group_settings.get("support_infill_extruder_nr"); - const coord_t infill_line_width = infill_train.settings.get("support_line_width"); + const coord_t infill_line_width = infill_train.settings_.get("support_line_width"); smoothing_distance = infill_line_width; if (mesh.settings.get("support_roof_enable")) { const ExtruderTrain& roof_train = mesh_group_settings.get("support_roof_extruder_nr"); - const coord_t roof_line_width = roof_train.settings.get("support_roof_line_width"); + const coord_t roof_line_width = roof_train.settings_.get("support_roof_line_width"); smoothing_distance = std::max(smoothing_distance, roof_line_width); } if (mesh.settings.get("support_bottom_enable")) { const ExtruderTrain& bottom_train = mesh_group_settings.get("support_bottom_extruder_nr"); - const coord_t bottom_line_width = bottom_train.settings.get("support_bottom_line_width"); + const coord_t bottom_line_width = bottom_train.settings_.get("support_bottom_line_width"); smoothing_distance = std::max(smoothing_distance, bottom_line_width); } } @@ -1749,8 +1749,8 @@ void AreaSupport::generateSupportBottom(SliceDataStorage& storage, const SliceMe const coord_t z_distance_bottom = round_up_divide(mesh.settings.get("support_bottom_distance"), layer_height); // Number of layers between support bottom and model. const size_t skip_layer_count = std::max(uint64_t(1), round_divide(mesh.settings.get("support_interface_skip_height"), layer_height)); // Resolution of generating support bottoms above model. - const coord_t bottom_line_width = mesh_group_settings.get("support_bottom_extruder_nr").settings.get("support_bottom_line_width"); - const coord_t bottom_outline_offset = mesh_group_settings.get("support_bottom_extruder_nr").settings.get("support_bottom_offset"); + const coord_t bottom_line_width = mesh_group_settings.get("support_bottom_extruder_nr").settings_.get("support_bottom_line_width"); + const coord_t bottom_outline_offset = mesh_group_settings.get("support_bottom_extruder_nr").settings_.get("support_bottom_offset"); const size_t scan_count = std::max(size_t(1), (bottom_layer_count - 1) / skip_layer_count); // How many measurements to take to generate bottom areas. const float z_skip = std::max( @@ -1786,8 +1786,8 @@ void AreaSupport::generateSupportRoof(SliceDataStorage& storage, const SliceMesh const coord_t z_distance_top = round_up_divide(mesh.settings.get("support_top_distance"), layer_height); // Number of layers between support roof and model. const size_t skip_layer_count = std::max(uint64_t(1), round_divide(mesh.settings.get("support_interface_skip_height"), layer_height)); // Resolution of generating support roof below model. - const coord_t roof_line_width = mesh_group_settings.get("support_roof_extruder_nr").settings.get("support_roof_line_width"); - const coord_t roof_outline_offset = mesh_group_settings.get("support_roof_extruder_nr").settings.get("support_roof_offset"); + const coord_t roof_line_width = mesh_group_settings.get("support_roof_extruder_nr").settings_.get("support_roof_line_width"); + const coord_t roof_outline_offset = mesh_group_settings.get("support_roof_extruder_nr").settings_.get("support_roof_offset"); const size_t scan_count = std::max(size_t(1), (roof_layer_count - 1) / skip_layer_count); // How many measurements to take to generate roof areas. const float z_skip = std::max( diff --git a/src/utils/SquareGrid.cpp b/src/utils/SquareGrid.cpp index c02c2cde59..46f7a41534 100644 --- a/src/utils/SquareGrid.cpp +++ b/src/utils/SquareGrid.cpp @@ -8,7 +8,7 @@ using namespace cura; -SquareGrid::SquareGrid(coord_t cell_size) : cell_size(cell_size) +SquareGrid::SquareGrid(coord_t cell_size) : cell_size_(cell_size) { assert(cell_size > 0U); } @@ -28,7 +28,7 @@ SquareGrid::grid_coord_t SquareGrid::toGridCoord(const coord_t& coord) const // just changes the running time slightly. The change in running // time from this is probably not worth doing a proper floor // operation. - return coord / cell_size; + return coord / cell_size_; } @@ -46,7 +46,7 @@ cura::coord_t SquareGrid::toLowerCoord(const grid_coord_t& grid_coord) const // just changes the running time slightly. The change in running // time from this is probably not worth doing a proper floor // operation. - return grid_coord * cell_size; + return grid_coord * cell_size_; } @@ -199,5 +199,5 @@ SquareGrid::grid_coord_t SquareGrid::nonzeroSign(const grid_coord_t z) const coord_t SquareGrid::getCellSize() const { - return cell_size; + return cell_size_; } diff --git a/src/utils/VoxelUtils.cpp b/src/utils/VoxelUtils.cpp index 22150a2b95..0c006ba910 100644 --- a/src/utils/VoxelUtils.cpp +++ b/src/utils/VoxelUtils.cpp @@ -75,7 +75,7 @@ bool VoxelUtils::walkLine(Point3 start, Point3 end, const std::function 0) * cell_size[dim]; + coord_t crossing_boundary = toLowerCoord(current_cell[dim], dim) + (diff[dim] > 0) * cell_size_[dim]; float percentage_along_line_here = (crossing_boundary - start[dim]) / static_cast(diff[dim]); if (percentage_along_line_here < percentage_along_line) { @@ -116,7 +116,7 @@ bool VoxelUtils::walkPolygons(const Polygons& polys, coord_t z, const std::funct bool VoxelUtils::walkDilatedPolygons(const Polygons& polys, coord_t z, const DilationKernel& kernel, const std::function& process_cell_func) const { Polygons translated = polys; - const Point3 translation = (Point3(1, 1, 1) - kernel.kernel_size % 2) * cell_size / 2; + const Point3 translation = (Point3(1, 1, 1) - kernel.kernel_size % 2) * cell_size_ / 2; if (translation.x_ && translation.y_) { translated.translate(Point(translation.x_, translation.y_)); @@ -127,7 +127,7 @@ bool VoxelUtils::walkDilatedPolygons(const Polygons& polys, coord_t z, const Dil bool VoxelUtils::walkAreas(const Polygons& polys, coord_t z, const std::function& process_cell_func) const { Polygons translated = polys; - const Point3 translation = -cell_size / 2; // offset half a cell so that the dots of spreadDotsArea are centered on the middle of the cell isntead of the lower corners. + const Point3 translation = -cell_size_ / 2; // offset half a cell so that the dots of spreadDotsArea are centered on the middle of the cell isntead of the lower corners. if (translation.x_ && translation.y_) { translated.translate(Point(translation.x_, translation.y_)); @@ -137,10 +137,10 @@ bool VoxelUtils::walkAreas(const Polygons& polys, coord_t z, const std::function bool VoxelUtils::_walkAreas(const Polygons& polys, coord_t z, const std::function& process_cell_func) const { - std::vector skin_points = PolygonUtils::spreadDotsArea(polys, Point(cell_size.x_, cell_size.y_)); + std::vector skin_points = PolygonUtils::spreadDotsArea(polys, Point(cell_size_.x_, cell_size_.y_)); for (Point p : skin_points) { - bool continue_ = process_cell_func(toGridPoint(Point3(p.X + cell_size.x_ / 2, p.Y + cell_size.y_ / 2, z))); + bool continue_ = process_cell_func(toGridPoint(Point3(p.X + cell_size_.x_ / 2, p.Y + cell_size_.y_ / 2, z))); if (! continue_) { return false; @@ -152,8 +152,8 @@ bool VoxelUtils::_walkAreas(const Polygons& polys, coord_t z, const std::functio bool VoxelUtils::walkDilatedAreas(const Polygons& polys, coord_t z, const DilationKernel& kernel, const std::function& process_cell_func) const { Polygons translated = polys; - const Point3 translation = (Point3(1, 1, 1) - kernel.kernel_size % 2) * cell_size / 2 // offset half a cell when using a n even kernel - - cell_size / 2; // offset half a cell so that the dots of spreadDotsArea are centered on the middle of the cell isntead of the lower corners. + const Point3 translation = (Point3(1, 1, 1) - kernel.kernel_size % 2) * cell_size_ / 2 // offset half a cell when using a n even kernel + - cell_size_ / 2; // offset half a cell so that the dots of spreadDotsArea are centered on the middle of the cell isntead of the lower corners. if (translation.x_ && translation.y_) { translated.translate(Point(translation.x_, translation.y_)); diff --git a/tests/GCodeExportTest.cpp b/tests/GCodeExportTest.cpp index 3fb07c9be9..696bbaffcf 100644 --- a/tests/GCodeExportTest.cpp +++ b/tests/GCodeExportTest.cpp @@ -246,8 +246,8 @@ TEST_P(GriffinHeaderTest, HeaderGriffinFormat) { Application::getInstance().current_slice->scene.extruders.emplace_back(extruder_index, nullptr); ExtruderTrain& train = Application::getInstance().current_slice->scene.extruders.back(); - train.settings.add("machine_nozzle_size", "0.4"); - train.settings.add("machine_nozzle_id", "TestNozzle"); + train.settings_.add("machine_nozzle_size", "0.4"); + train.settings_.add("machine_nozzle_id", "TestNozzle"); } const std::vector extruder_is_used(num_extruders, true); @@ -326,7 +326,7 @@ TEST_F(GCodeExportTest, HeaderUltiGCode) { Application::getInstance().current_slice->scene.extruders.emplace_back(extruder_index, nullptr); ExtruderTrain& train = Application::getInstance().current_slice->scene.extruders.back(); - train.settings.add("machine_nozzle_size", "0.4"); + train.settings_.add("machine_nozzle_size", "0.4"); } gcode.total_bounding_box = AABB3D(Point3(0, 0, 0), Point3(1000, 1000, 1000)); @@ -459,16 +459,16 @@ TEST_F(GCodeExportTest, SwitchExtruderSimple) scene.extruders.emplace_back(0, nullptr); ExtruderTrain& train1 = scene.extruders.back(); - train1.settings.add("machine_extruder_start_code", ";FIRST EXTRUDER START G-CODE!"); - train1.settings.add("machine_extruder_end_code", ";FIRST EXTRUDER END G-CODE!"); - train1.settings.add("machine_firmware_retract", "True"); - train1.settings.add("retraction_enable", "True"); + train1.settings_.add("machine_extruder_start_code", ";FIRST EXTRUDER START G-CODE!"); + train1.settings_.add("machine_extruder_end_code", ";FIRST EXTRUDER END G-CODE!"); + train1.settings_.add("machine_firmware_retract", "True"); + train1.settings_.add("retraction_enable", "True"); scene.extruders.emplace_back(1, nullptr); ExtruderTrain& train2 = scene.extruders.back(); - train2.settings.add("machine_extruder_start_code", ";SECOND EXTRUDER START G-CODE!"); - train2.settings.add("machine_extruder_end_code", ";SECOND EXTRUDER END G-CODE!"); - train2.settings.add("machine_firmware_retract", "True"); - train2.settings.add("retraction_enable", "True"); + train2.settings_.add("machine_extruder_start_code", ";SECOND EXTRUDER START G-CODE!"); + train2.settings_.add("machine_extruder_end_code", ";SECOND EXTRUDER END G-CODE!"); + train2.settings_.add("machine_firmware_retract", "True"); + train2.settings_.add("retraction_enable", "True"); RetractionConfig no_retraction; no_retraction.distance = 0; @@ -489,7 +489,7 @@ TEST_F(GCodeExportTest, WriteZHopStartZero) TEST_F(GCodeExportTest, WriteZHopStartDefaultSpeed) { Application::getInstance().current_slice->scene.extruders.emplace_back(0, nullptr); - Application::getInstance().current_slice->scene.extruders[gcode.current_extruder].settings.add("speed_z_hop", "1"); // 60mm/min. + Application::getInstance().current_slice->scene.extruders[gcode.current_extruder].settings_.add("speed_z_hop", "1"); // 60mm/min. gcode.current_layer_z = 2000; constexpr coord_t hop_height = 3000; gcode.writeZhopStart(hop_height); @@ -499,7 +499,7 @@ TEST_F(GCodeExportTest, WriteZHopStartDefaultSpeed) TEST_F(GCodeExportTest, WriteZHopStartCustomSpeed) { Application::getInstance().current_slice->scene.extruders.emplace_back(0, nullptr); - Application::getInstance().current_slice->scene.extruders[gcode.current_extruder].settings.add("speed_z_hop", "1"); // 60mm/min. + Application::getInstance().current_slice->scene.extruders[gcode.current_extruder].settings_.add("speed_z_hop", "1"); // 60mm/min. gcode.current_layer_z = 2000; constexpr coord_t hop_height = 3000; constexpr Velocity speed{ 4.0 }; // 240 mm/min. @@ -517,7 +517,7 @@ TEST_F(GCodeExportTest, WriteZHopEndZero) TEST_F(GCodeExportTest, WriteZHopEndDefaultSpeed) { Application::getInstance().current_slice->scene.extruders.emplace_back(0, nullptr); - Application::getInstance().current_slice->scene.extruders[gcode.current_extruder].settings.add("speed_z_hop", "1"); // 60mm/min. + Application::getInstance().current_slice->scene.extruders[gcode.current_extruder].settings_.add("speed_z_hop", "1"); // 60mm/min. gcode.current_layer_z = 2000; gcode.is_z_hopped = 3000; gcode.writeZhopEnd(); @@ -527,7 +527,7 @@ TEST_F(GCodeExportTest, WriteZHopEndDefaultSpeed) TEST_F(GCodeExportTest, WriteZHopEndCustomSpeed) { Application::getInstance().current_slice->scene.extruders.emplace_back(0, nullptr); - Application::getInstance().current_slice->scene.extruders[gcode.current_extruder].settings.add("speed_z_hop", "1"); + Application::getInstance().current_slice->scene.extruders[gcode.current_extruder].settings_.add("speed_z_hop", "1"); gcode.current_layer_z = 2000; gcode.is_z_hopped = 3000; constexpr Velocity speed{ 4.0 }; // 240 mm/min. @@ -649,7 +649,7 @@ TEST_F(GCodeExportTest, insertWipeScriptRetractionEnable) gcode.currentSpeed = 1.0; Application::getInstance().current_slice->scene.current_mesh_group->settings.add("layer_height", "0.2"); Application::getInstance().current_slice->scene.extruders.emplace_back(0, &Application::getInstance().current_slice->scene.current_mesh_group->settings); - Application::getInstance().current_slice->scene.extruders.back().settings.add("machine_firmware_retract", "false"); + Application::getInstance().current_slice->scene.extruders.back().settings_.add("machine_firmware_retract", "false"); WipeScriptConfig config; config.retraction_enable = true; diff --git a/tests/arcus/ArcusCommunicationPrivateTest.cpp b/tests/arcus/ArcusCommunicationPrivateTest.cpp index 1538269483..b35f7fdf25 100644 --- a/tests/arcus/ArcusCommunicationPrivateTest.cpp +++ b/tests/arcus/ArcusCommunicationPrivateTest.cpp @@ -119,7 +119,7 @@ TEST_F(ArcusCommunicationPrivateTest, ReadSingleExtruderSettingsMessage) instance->readExtruderSettingsMessage(messages); ASSERT_EQ(size_t(1), Application::getInstance().current_slice->scene.extruders.size()) << "Reading the extruders must construct the correct amount of extruders in the scene."; - EXPECT_EQ(setting_value, Application::getInstance().current_slice->scene.extruders[0].settings.get("test_setting")); + EXPECT_EQ(setting_value, Application::getInstance().current_slice->scene.extruders[0].settings_.get("test_setting")); } TEST_F(ArcusCommunicationPrivateTest, ReadMultiExtruderSettingsMessage) @@ -147,8 +147,8 @@ TEST_F(ArcusCommunicationPrivateTest, ReadMultiExtruderSettingsMessage) instance->readExtruderSettingsMessage(messages); ASSERT_EQ(size_t(2), Application::getInstance().current_slice->scene.extruders.size()) << "Reading the extruders must construct the correct amount of extruders in the scene."; - EXPECT_EQ(std::string("First"), Application::getInstance().current_slice->scene.extruders[0].settings.get("What extruder are you?")); - EXPECT_EQ(std::string("Second"), Application::getInstance().current_slice->scene.extruders[1].settings.get("What extruder are you?")); + EXPECT_EQ(std::string("First"), Application::getInstance().current_slice->scene.extruders[0].settings_.get("What extruder are you?")); + EXPECT_EQ(std::string("Second"), Application::getInstance().current_slice->scene.extruders[1].settings_.get("What extruder are you?")); } TEST_F(ArcusCommunicationPrivateTest, ReadMeshGroupMessage) From 5e849dc8c1d3112d3929223746c6aa5b4dbda42a Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Tue, 21 Nov 2023 10:13:16 +0100 Subject: [PATCH 10/48] Fixed variable shadowing warnings --- include/PathOrder.h | 8 +- include/PathOrderMonotonic.h | 94 +++++++------- include/PathOrderOptimizer.h | 124 +++++++++---------- include/PathOrdering.h | 20 +-- include/gcodeExport.h | 8 +- include/pathPlanning/LinePolygonsCrossings.h | 34 ++--- src/FffGcodeWriter.cpp | 6 +- src/InsetOrderOptimizer.cpp | 16 +-- src/LayerPlan.cpp | 22 ++-- src/PathOrderPath.cpp | 16 +-- src/gcodeExport.cpp | 2 +- src/pathPlanning/LinePolygonsCrossings.cpp | 98 +++++++-------- tests/PathOrderMonotonicTest.cpp | 4 +- 13 files changed, 226 insertions(+), 226 deletions(-) diff --git a/include/PathOrder.h b/include/PathOrder.h index 5861d7aeb0..9b909a6605 100644 --- a/include/PathOrder.h +++ b/include/PathOrder.h @@ -110,18 +110,18 @@ class PathOrder { for(PathOrdering& path : paths) { - if(path.is_closed) //Already a polygon. No need to detect loops. + if(path.is_closed_) //Already a polygon. No need to detect loops. { continue; } - if(path.converted->size() < 3) //Not enough vertices to really be a closed loop. + if(path.converted_->size() < 3) //Not enough vertices to really be a closed loop. { continue; } - if(vSize2(path.converted->back() - path.converted->front()) < coincident_point_distance * coincident_point_distance) + if(vSize2(path.converted_->back() - path.converted_->front()) < coincident_point_distance * coincident_point_distance) { //Endpoints are really close to one another. Consider it a closed loop. - path.is_closed = true; + path.is_closed_ = true; } } } diff --git a/include/PathOrderMonotonic.h b/include/PathOrderMonotonic.h index 9501ca7e32..fa35bb513a 100644 --- a/include/PathOrderMonotonic.h +++ b/include/PathOrderMonotonic.h @@ -62,7 +62,7 @@ class PathOrderMonotonic : public PathOrder //Get the vertex data and store it in the paths. for(Path& path : this->paths) { - path.converted = path.getVertexData(); + path.converted_ = path.getVertexData(); } std::vector reordered; //To store the result in. At the end, we'll std::swap with the real paths. @@ -73,7 +73,7 @@ class PathOrderMonotonic : public PathOrder this->detectLoops(); //Always filter out loops. We don't specifically want to print those in monotonic order. for(Path& path : this->paths) { - if(path.is_closed || path.vertices->size() <= 1) + if(path.is_closed_ || path.vertices_->size() <= 1) { reordered.push_back(path); } @@ -81,18 +81,18 @@ class PathOrderMonotonic : public PathOrder { polylines.push_back(&path); // Assign an invalid starting vertex to indicate we don't know the starting point yet. - polylines.back()->start_vertex = polylines.back()->converted->size(); + polylines.back()->start_vertex_ = polylines.back()->converted_->size(); } } //Sort the polylines by their projection on the monotonic vector. This helps find adjacent lines quickly. std::sort(polylines.begin(), polylines.end(), [this](Path* a, Path* b) { - const coord_t a_start_projection = dot(a->converted->front(), monotonic_vector); - const coord_t a_end_projection = dot(a->converted->back(), monotonic_vector); + const coord_t a_start_projection = dot(a->converted_->front(), monotonic_vector); + const coord_t a_end_projection = dot(a->converted_->back(), monotonic_vector); const coord_t a_projection = std::min(a_start_projection, a_end_projection); //The projection of a path is the endpoint furthest back of the two endpoints. - const coord_t b_start_projection = dot(b->converted->front(), monotonic_vector); - const coord_t b_end_projection = dot(b->converted->back(), monotonic_vector); + const coord_t b_start_projection = dot(b->converted_->front(), monotonic_vector); + const coord_t b_end_projection = dot(b->converted_->back(), monotonic_vector); const coord_t b_projection = std::min(b_start_projection, b_end_projection); return a_projection < b_projection; @@ -101,10 +101,10 @@ class PathOrderMonotonic : public PathOrder SparsePointGridInclusive line_bucket_grid(MM2INT(2)); //Grid size of 2mm. for(Path* polyline : polylines) { - if(! polyline->converted->empty()) + if(! polyline->converted_->empty()) { - line_bucket_grid.insert(polyline->converted->front(), polyline); - line_bucket_grid.insert(polyline->converted->back(), polyline); + line_bucket_grid.insert(polyline->converted_->front(), polyline); + line_bucket_grid.insert(polyline->converted_->back(), polyline); } } @@ -191,13 +191,13 @@ class PathOrderMonotonic : public PathOrder std::vector starting_lines_monotonic; starting_lines_monotonic.resize(starting_lines.size()); std::partial_sort_copy(starting_lines.begin(), starting_lines.end(), starting_lines_monotonic.begin(), starting_lines_monotonic.end(), [this](Path* a, Path* b) { - const coord_t a_start_projection = dot(a->converted->front(), monotonic_vector); - const coord_t a_end_projection = dot(a->converted->back(), monotonic_vector); + const coord_t a_start_projection = dot(a->converted_->front(), monotonic_vector); + const coord_t a_end_projection = dot(a->converted_->back(), monotonic_vector); const coord_t a_projection_min = std::min(a_start_projection, a_end_projection); //The projection of a path is the endpoint furthest back of the two endpoints. const coord_t a_projection_max = std::max(a_start_projection, a_end_projection); //But in case of ties, the other endpoint counts too. Important for polylines where multiple endpoints have the same position! - const coord_t b_start_projection = dot(b->converted->front(), monotonic_vector); - const coord_t b_end_projection = dot(b->converted->back(), monotonic_vector); + const coord_t b_start_projection = dot(b->converted_->front(), monotonic_vector); + const coord_t b_end_projection = dot(b->converted_->back(), monotonic_vector); const coord_t b_projection_min = std::min(b_start_projection, b_end_projection); const coord_t b_projection_max = std::max(b_start_projection, b_end_projection); @@ -266,22 +266,22 @@ class PathOrderMonotonic : public PathOrder */ void optimizeClosestStartPoint(Path& path, Point& current_pos) { - if(path.start_vertex == path.converted->size()) + if(path.start_vertex_ == path.converted_->size()) { - const coord_t dist_start = vSize2(current_pos - path.converted->front()); - const coord_t dist_end = vSize2(current_pos - path.converted->back()); + const coord_t dist_start = vSize2(current_pos - path.converted_->front()); + const coord_t dist_end = vSize2(current_pos - path.converted_->back()); if(dist_start < dist_end) { - path.start_vertex = 0; - path.backwards = false; + path.start_vertex_ = 0; + path.backwards_ = false; } else { - path.start_vertex = path.converted->size() - 1; - path.backwards = true; + path.start_vertex_ = path.converted_->size() - 1; + path.backwards_ = true; } } - current_pos = (*path.converted)[path.converted->size() - 1 - path.start_vertex]; //Opposite of the start vertex. + current_pos = (*path.converted_)[path.converted_->size() - 1 - path.start_vertex_]; //Opposite of the start vertex. } /*! @@ -298,16 +298,16 @@ class PathOrderMonotonic : public PathOrder std::deque findPolylineString(Path* polyline, const SparsePointGridInclusive& line_bucket_grid, const Point monotonic_vector) { std::deque result; - if(polyline->converted->empty()) + if(polyline->converted_->empty()) { return result; } //Find the two endpoints of the polyline string, on either side. result.push_back(polyline); - polyline->start_vertex = 0; - Point first_endpoint = polyline->converted->front(); - Point last_endpoint = polyline->converted->back(); + polyline->start_vertex_ = 0; + Point first_endpoint = polyline->converted_->front(); + Point last_endpoint = polyline->converted_->back(); std::vector> lines_before = line_bucket_grid.getNearby(first_endpoint, coincident_point_distance); auto close_line_before = std::find_if(lines_before.begin(), lines_before.end(), [first_endpoint](SparsePointGridInclusiveImpl::SparsePointGridInclusiveElem found_path) { return canConnectToPolyline(first_endpoint, found_path); @@ -322,9 +322,9 @@ class PathOrderMonotonic : public PathOrder Path* first = close_line_before->val; result.push_front(first); //Store this one in the sequence. It's a good one. size_t farthest_vertex = getFarthestEndpoint(first, close_line_before->point); //Get to the opposite side. - first->start_vertex = farthest_vertex; - first->backwards = farthest_vertex != 0; - first_endpoint = (*first->converted)[farthest_vertex]; + first->start_vertex_ = farthest_vertex; + first->backwards_ = farthest_vertex != 0; + first_endpoint = (*first->converted_)[farthest_vertex]; lines_before = line_bucket_grid.getNearby(first_endpoint, coincident_point_distance); close_line_before = std::find_if(lines_before.begin(), lines_before.end(), [first_endpoint](SparsePointGridInclusiveImpl::SparsePointGridInclusiveElem found_path) { return canConnectToPolyline(first_endpoint, found_path); @@ -335,9 +335,9 @@ class PathOrderMonotonic : public PathOrder Path* last = close_line_after->val; result.push_back(last); size_t farthest_vertex = getFarthestEndpoint(last, close_line_after->point); //Get to the opposite side. - last->start_vertex = (farthest_vertex == 0) ? last->converted->size() - 1 : 0; - last->backwards = farthest_vertex != 0; - last_endpoint = (*last->converted)[farthest_vertex]; + last->start_vertex_ = (farthest_vertex == 0) ? last->converted_->size() - 1 : 0; + last->backwards_ = farthest_vertex != 0; + last_endpoint = (*last->converted_)[farthest_vertex]; lines_after = line_bucket_grid.getNearby(last_endpoint, coincident_point_distance); close_line_after = std::find_if(lines_after.begin(), lines_after.end(), [last_endpoint](SparsePointGridInclusiveImpl::SparsePointGridInclusiveElem found_path) { return canConnectToPolyline(last_endpoint, found_path); @@ -353,14 +353,14 @@ class PathOrderMonotonic : public PathOrder std::reverse(result.begin(), result.end()); for(Path* path : result) //Also reverse their start_vertex. { - path->start_vertex = (path->start_vertex == 0) ? path->converted->size() - 1 : 0; - path->backwards = !path->backwards; + path->start_vertex_ = (path->start_vertex_ == 0) ? path->converted_->size() - 1 : 0; + path->backwards_ = !path->backwards_; } } if(result.size() == 1) { - result[0]->start_vertex = result[0]->converted->size(); //Reset start vertex as "unknown" again if it's not a string of polylines. + result[0]->start_vertex_ = result[0]->converted_->size(); //Reset start vertex as "unknown" again if it's not a string of polylines. } return result; } @@ -374,11 +374,11 @@ class PathOrderMonotonic : public PathOrder */ size_t getFarthestEndpoint(Path* polyline, const Point point) { - const coord_t front_dist = vSize2(polyline->converted->front() - point); - const coord_t back_dist = vSize2(polyline->converted->back() - point); + const coord_t front_dist = vSize2(polyline->converted_->front() - point); + const coord_t back_dist = vSize2(polyline->converted_->back() - point); if(front_dist < back_dist) { - return polyline->converted->size() - 1; + return polyline->converted_->size() - 1; } else { @@ -400,15 +400,15 @@ class PathOrderMonotonic : public PathOrder { const coord_t max_adjacent_projected_distance = max_adjacent_distance * monotonic_vector_resolution; //How far this extends in the monotonic direction, to make sure we only go up to max_adjacent_distance in that direction. - const coord_t start_monotonic = dot((*polyline_it)->converted->front(), monotonic_vector); - const coord_t end_monotonic = dot((*polyline_it)->converted->back(), monotonic_vector); + const coord_t start_monotonic = dot((*polyline_it)->converted_->front(), monotonic_vector); + const coord_t end_monotonic = dot((*polyline_it)->converted_->back(), monotonic_vector); const coord_t my_farthest_monotonic = std::max(start_monotonic, end_monotonic); const coord_t my_closest_monotonic = std::min(start_monotonic, end_monotonic); const coord_t my_farthest_monotonic_padded = my_farthest_monotonic + max_adjacent_projected_distance; const coord_t my_closest_monotonic_padded = my_closest_monotonic - max_adjacent_projected_distance; //How far this line reaches in the perpendicular direction -- the range at which the line overlaps other lines. - const coord_t my_start = dot((*polyline_it)->converted->front(), perpendicular); - const coord_t my_end = dot((*polyline_it)->converted->back(), perpendicular); + const coord_t my_start = dot((*polyline_it)->converted_->front(), perpendicular); + const coord_t my_end = dot((*polyline_it)->converted_->back(), perpendicular); const coord_t my_farthest = std::max(my_start, my_end); const coord_t my_closest = std::min(my_start, my_end); const coord_t my_farthest_padded = my_farthest + max_adjacent_projected_distance; @@ -418,8 +418,8 @@ class PathOrderMonotonic : public PathOrder for(auto overlapping_line = polyline_it + 1; overlapping_line != polylines.end(); overlapping_line++) { //Don't go beyond the maximum adjacent distance. - const coord_t start_their_projection = dot((*overlapping_line)->converted->front(), monotonic_vector); - const coord_t end_their_projection = dot((*overlapping_line)->converted->back(), monotonic_vector); + const coord_t start_their_projection = dot((*overlapping_line)->converted_->front(), monotonic_vector); + const coord_t end_their_projection = dot((*overlapping_line)->converted_->back(), monotonic_vector); const coord_t their_farthest_projection = std::max(start_their_projection, end_their_projection); const coord_t their_closest_projection = std::min(start_their_projection, end_their_projection); // Multiply by the length of the vector since we need to compare actual distances here. @@ -429,8 +429,8 @@ class PathOrderMonotonic : public PathOrder } //Does this one overlap? - const coord_t their_start = dot((*overlapping_line)->converted->front(), perpendicular); - const coord_t their_end = dot((*overlapping_line)->converted->back(), perpendicular); + const coord_t their_start = dot((*overlapping_line)->converted_->front(), perpendicular); + const coord_t their_end = dot((*overlapping_line)->converted_->back(), perpendicular); const coord_t their_farthest = std::max(their_start, their_end); const coord_t their_closest = std::min(their_start, their_end); /*There are 5 possible cases of overlapping: @@ -476,7 +476,7 @@ class PathOrderMonotonic : public PathOrder */ static bool canConnectToPolyline(const Point nearby_endpoint, SparsePointGridInclusiveImpl::SparsePointGridInclusiveElem found_path) { - return found_path.val->start_vertex == found_path.val->converted->size() //Don't find any line already in the string. + return found_path.val->start_vertex_ == found_path.val->converted_->size() //Don't find any line already in the string. && vSize2(found_path.point - nearby_endpoint) < coincident_point_distance * coincident_point_distance; //And only find close lines. } }; diff --git a/include/PathOrderOptimizer.h b/include/PathOrderOptimizer.h index ae7591db45..8072a501a8 100644 --- a/include/PathOrderOptimizer.h +++ b/include/PathOrderOptimizer.h @@ -4,15 +4,7 @@ #ifndef PATHORDEROPTIMIZER_H #define PATHORDEROPTIMIZER_H -#include "InsetOrderOptimizer.h" // for makeOrderIncludeTransitive -#include "PathOrdering.h" -#include "pathPlanning/CombPath.h" //To calculate the combing distance if we want to use combing. -#include "pathPlanning/LinePolygonsCrossings.h" //To prevent calculating combing distances if we don't cross the combing borders. -#include "settings/EnumSettings.h" //To get the seam settings. -#include "settings/ZSeamConfig.h" //To read the seam configuration. -#include "utils/linearAlg2D.h" //To find the angle of corners to hide seams. -#include "utils/polygonUtils.h" -#include "utils/views/dfs.h" +#include #include #include @@ -23,7 +15,15 @@ #include #include -#include +#include "InsetOrderOptimizer.h" // for makeOrderIncludeTransitive +#include "PathOrdering.h" +#include "pathPlanning/CombPath.h" //To calculate the combing distance if we want to use combing. +#include "pathPlanning/LinePolygonsCrossings.h" //To prevent calculating combing distances if we don't cross the combing borders. +#include "settings/EnumSettings.h" //To get the seam settings. +#include "settings/ZSeamConfig.h" //To read the seam configuration. +#include "utils/linearAlg2D.h" //To find the angle of corners to hide seams. +#include "utils/polygonUtils.h" +#include "utils/views/dfs.h" namespace cura { @@ -155,8 +155,8 @@ class PathOrderOptimizer // Get the vertex data and store it in the paths. for (auto& path : paths) { - path.converted = path.getVertexData(); - vertices_to_paths.emplace(path.vertices, &path); + path.converted_ = path.getVertexData(); + vertices_to_paths.emplace(path.vertices_, &path); } // If necessary, check polylines to see if they are actually polygons. @@ -164,10 +164,10 @@ class PathOrderOptimizer { for (auto& path : paths) { - if (! path.is_closed) + if (! path.is_closed_) { // If we want to detect chains, first check if some of the polylines are secretly polygons. - path.is_closed = isLoopingPolyline(path); // If it is, we'll set the seam position correctly later. + path.is_closed_ = isLoopingPolyline(path); // If it is, we'll set the seam position correctly later. } } } @@ -177,21 +177,21 @@ class PathOrderOptimizer SparsePointGridInclusive line_bucket_grid(snap_radius); for (const auto& [i, path] : paths | ranges::views::enumerate) { - if (path.converted->empty()) + if (path.converted_->empty()) { continue; } - if (path.is_closed) + if (path.is_closed_) { - for (const Point& point : *path.converted) + for (const Point& point : *path.converted_) { line_bucket_grid.insert(point, i); // Store by index so that we can also mark them down in the `picked` vector. } } else // For polylines, only insert the endpoints. Those are the only places we can start from so the only relevant vertices to be near to. { - line_bucket_grid.insert(path.converted->front(), i); - line_bucket_grid.insert(path.converted->back(), i); + line_bucket_grid.insert(path.converted_->front(), i); + line_bucket_grid.insert(path.converted_->back(), i); } } @@ -202,11 +202,11 @@ class PathOrderOptimizer { for (auto& path : paths) { - if (! path.is_closed || path.converted->empty()) + if (! path.is_closed_ || path.converted_->empty()) { continue; // Can't pre-compute the seam for open polylines since they're at the endpoint nearest to the current position. } - path.start_vertex = findStartLocation(path, seam_config.pos); + path.start_vertex_ = findStartLocation(path, seam_config.pos); } } @@ -331,16 +331,16 @@ class PathOrderOptimizer optimized_order.push_back(*best_path); picked[best_path] = true; - if (! best_path->converted->empty()) // If all paths were empty, the best path is still empty. We don't upate the current position then. + if (! best_path->converted_->empty()) // If all paths were empty, the best path is still empty. We don't upate the current position then. { - if (best_path->is_closed) + if (best_path->is_closed_) { - current_position = (*best_path->converted)[best_path->start_vertex]; // We end where we started. + current_position = (*best_path->converted_)[best_path->start_vertex_]; // We end where we started. } else { // Pick the other end from where we started. - current_position = best_path->start_vertex == 0 ? best_path->converted->back() : best_path->converted->front(); + current_position = best_path->start_vertex_ == 0 ? best_path->converted_->back() : best_path->converted_->front(); } } } @@ -358,8 +358,8 @@ class PathOrderOptimizer std::unordered_set leaves; for (const auto& path : paths) { - roots.insert(path.vertices); - leaves.insert(path.vertices); + roots.insert(path.vertices_); + leaves.insert(path.vertices_); } // remove all edges from roots with an incoming edge @@ -399,14 +399,14 @@ class PathOrderOptimizer // update local_current_position auto path = vertices_to_paths[best_candidate]; - if (path->is_closed) + if (path->is_closed_) { - local_current_position = (*path->converted)[path->start_vertex]; // We end where we started. + local_current_position = (*path->converted_)[path->start_vertex_]; // We end where we started. } else { // Pick the other end from where we started. - local_current_position = path->start_vertex == 0 ? path->converted->back() : path->converted->front(); + local_current_position = path->start_vertex_ == 0 ? path->converted_->back() : path->converted_->front(); } } @@ -419,16 +419,16 @@ class PathOrderOptimizer // We should make map from node <-> path for this stuff for (auto& path : paths) { - if (path.vertices == current_node) + if (path.vertices_ == current_node) { - if (path.is_closed) + if (path.is_closed_) { - current_position = (*path.converted)[path.start_vertex]; // We end where we started. + current_position = (*path.converted_)[path.start_vertex_]; // We end where we started. } else { // Pick the other end from where we started. - current_position = path.start_vertex == 0 ? path.converted->back() : path.converted->front(); + current_position = path.start_vertex_ == 0 ? path.converted_->back() : path.converted_->front(); } // Add to optimized order @@ -518,10 +518,10 @@ class PathOrderOptimizer for (auto& path : pathsOrderPaths | ranges::views::reverse) { reversed.push_back(path); - reversed.back().backwards = ! reversed.back().backwards; - if (! reversed.back().is_closed) + reversed.back().backwards_ = ! reversed.back().backwards_; + if (! reversed.back().is_closed_) { - reversed.back().start_vertex = reversed.back().converted->size() - 1 - reversed.back().start_vertex; + reversed.back().start_vertex_ = reversed.back().converted_->size() - 1 - reversed.back().start_vertex_; } } @@ -538,7 +538,7 @@ class PathOrderOptimizer } OrderablePath* best_candidate = findClosestPath(start_position, candidate_orderable_paths); - return best_candidate->vertices; + return best_candidate->vertices_; } OrderablePath* findClosestPath(Point start_position, std::vector candidate_paths) @@ -548,7 +548,7 @@ class PathOrderOptimizer for (OrderablePath* path : candidate_paths) { - if (path->converted->empty()) // No vertices in the path. Can't find the start position then or really plan it in. Put that at the end. + if (path->converted_->empty()) // No vertices in the path. Can't find the start position then or really plan it in. Put that at the end. { if (best_distance2 == std::numeric_limits::max()) { @@ -559,15 +559,15 @@ class PathOrderOptimizer const bool precompute_start = seam_config.type == EZSeamType::RANDOM || seam_config.type == EZSeamType::USER_SPECIFIED || seam_config.type == EZSeamType::SHARPEST_CORNER; - if (! path->is_closed || ! precompute_start) // Find the start location unless we've already precomputed it. + if (! path->is_closed_ || ! precompute_start) // Find the start location unless we've already precomputed it. { - path->start_vertex = findStartLocation(*path, start_position); - if (! path->is_closed) // Open polylines start at vertex 0 or vertex N-1. Indicate that they should be reversed if they start at N-1. + path->start_vertex_ = findStartLocation(*path, start_position); + if (! path->is_closed_) // Open polylines start at vertex 0 or vertex N-1. Indicate that they should be reversed if they start at N-1. { - path->backwards = path->start_vertex > 0; + path->backwards_ = path->start_vertex_ > 0; } } - const Point candidate_position = (*path->converted)[path->start_vertex]; + const Point candidate_position = (*path->converted_)[path->start_vertex_]; coord_t distance2 = getDirectDistance(start_position, candidate_position); if (distance2 < best_distance2 && combing_boundary) // If direct distance is longer than best combing distance, the combing distance can never be better, so only compute combing if necessary. @@ -612,16 +612,16 @@ class PathOrderOptimizer */ size_t findStartLocation(const OrderablePath& path, const Point& target_pos) { - if (! path.is_closed) + if (! path.is_closed_) { // For polylines, the seam settings are not applicable. Simply choose the position closest to target_pos then. const coord_t back_distance - = (combing_boundary == nullptr) ? getDirectDistance(path.converted->back(), target_pos) : getCombingDistance(path.converted->back(), target_pos); - if (back_distance < getDirectDistance(path.converted->front(), target_pos) + = (combing_boundary == nullptr) ? getDirectDistance(path.converted_->back(), target_pos) : getCombingDistance(path.converted_->back(), target_pos); + if (back_distance < getDirectDistance(path.converted_->front(), target_pos) || (combing_boundary - && back_distance < getCombingDistance(path.converted->front(), target_pos))) // Lazy or: Only compute combing distance if direct distance is closer. + && back_distance < getCombingDistance(path.converted_->front(), target_pos))) // Lazy or: Only compute combing distance if direct distance is closer. { - return path.converted->size() - 1; // Back end is closer. + return path.converted_->size() - 1; // Back end is closer. } else { @@ -633,16 +633,16 @@ class PathOrderOptimizer if (seam_config.type == EZSeamType::RANDOM) { - size_t vert = getRandomPointInPolygon(*path.converted); + size_t vert = getRandomPointInPolygon(*path.converted_); return vert; } // Precompute segments lengths because we are going to need them multiple times - std::vector segments_sizes(path.converted->size()); + std::vector segments_sizes(path.converted_->size()); coord_t total_length = 0; - for (const auto& [i, here] : **path.converted | ranges::views::enumerate) + for (const auto& [i, here] : **path.converted_ | ranges::views::enumerate) { - const Point& next = (*path.converted)[(i + 1) % path.converted->size()]; + const Point& next = (*path.converted_)[(i + 1) % path.converted_->size()]; const coord_t segment_size = vSize(next - here); segments_sizes[i] = segment_size; total_length += segment_size; @@ -650,7 +650,7 @@ class PathOrderOptimizer size_t best_i; float best_score = std::numeric_limits::infinity(); - for (const auto& [i, here] : **path.converted | ranges::views::drop_last(1) | ranges::views::enumerate) + for (const auto& [i, here] : **path.converted_ | ranges::views::drop_last(1) | ranges::views::enumerate) { // For most seam types, the shortest distance matters. Not for SHARPEST_CORNER though. // For SHARPEST_CORNER, use a fixed starting score of 0. @@ -716,7 +716,7 @@ class PathOrderOptimizer // ties are broken by favouring points with lower x-coord // if x-coord for both points are equal then break ties by // favouring points with lower y-coord - const Point& best_point = (*path.converted)[best_i]; + const Point& best_point = (*path.converted_)[best_i]; if (std::abs(here.Y - best_point.Y) <= EPSILON ? best_point.X < here.X : best_point.Y < here.Y) { best_score = std::min(best_score, score); @@ -762,17 +762,17 @@ class PathOrderOptimizer while (travelled_distance < distance) { actual_delta += direction; - segment_size = segments_sizes[(here + actual_delta + size_delta + path.converted->size()) % path.converted->size()]; + segment_size = segments_sizes[(here + actual_delta + size_delta + path.converted_->size()) % path.converted_->size()]; travelled_distance += segment_size; } - const Point& next_pos = (*path.converted)[(here + actual_delta + path.converted->size()) % path.converted->size()]; + const Point& next_pos = (*path.converted_)[(here + actual_delta + path.converted_->size()) % path.converted_->size()]; if (travelled_distance > distance) [[likely]] { // We have overtaken the required distance, go backward on the last segment - int prev = (here + actual_delta - direction + path.converted->size()) % path.converted->size(); - const Point& prev_pos = (*path.converted)[prev]; + int prev = (here + actual_delta - direction + path.converted_->size()) % path.converted_->size(); + const Point& prev_pos = (*path.converted_)[prev]; const Point vector = next_pos - prev_pos; const Point unit_vector = (vector * 1000) / segment_size; @@ -802,7 +802,7 @@ class PathOrderOptimizer static float cornerAngle(const OrderablePath& path, int i, const std::vector& segments_sizes, coord_t total_length, const coord_t angle_query_distance = 1000) { const coord_t bounded_distance = std::min(angle_query_distance, total_length / 2); - const Point& here = (*path.converted)[i]; + const Point& here = (*path.converted_)[i]; const Point next = findNeighbourPoint(path, i, bounded_distance, segments_sizes); const Point previous = findNeighbourPoint(path, i, -bounded_distance, segments_sizes); @@ -881,11 +881,11 @@ class PathOrderOptimizer bool isLoopingPolyline(const OrderablePath& path) { - if (path.converted->empty()) + if (path.converted_->empty()) { return false; } - return vSize2(path.converted->back() - path.converted->front()) < coincident_point_distance * coincident_point_distance; + return vSize2(path.converted_->back() - path.converted_->front()) < coincident_point_distance * coincident_point_distance; } }; diff --git a/include/PathOrdering.h b/include/PathOrdering.h index 4893195786..96ce53863d 100644 --- a/include/PathOrdering.h +++ b/include/PathOrdering.h @@ -34,22 +34,22 @@ struct PathOrdering * invalidating the pointers. */ PathOrdering(const PathType& vertices, const bool is_closed = false, const size_t start_vertex = 0, const bool backwards = false) - : vertices(vertices) - , start_vertex(start_vertex) - , is_closed(is_closed) - , backwards(backwards) + : vertices_(vertices) + , start_vertex_(start_vertex) + , is_closed_(is_closed) + , backwards_(backwards) {} /*! * The vertex data of the path. */ - PathType vertices; + PathType vertices_; /*! * Vertex data, converted into a Polygon so that the orderer knows how * to deal with this data. */ - ConstPolygonPointer converted; + ConstPolygonPointer converted_; /*! * Which vertex along the path to start printing with. @@ -57,7 +57,7 @@ struct PathOrdering * If this path represents a polyline, this will always be one of the * endpoints of the path; either 0 or ``vertices->size() - 1``. */ - size_t start_vertex; + size_t start_vertex_; /*! * Whether the path should be closed at the ends or not. @@ -65,7 +65,7 @@ struct PathOrdering * If this path should be closed, it represents a polygon. If it should * not be closed, it represents a polyline. */ - bool is_closed; + bool is_closed_; /*! * Whether the path should be traversed in backwards direction. @@ -73,7 +73,7 @@ struct PathOrdering * For a polyline it may be more efficient to print the path in * backwards direction, if the last vertex is closer than the first. */ - bool backwards; + bool backwards_; /*! @@ -99,7 +99,7 @@ struct PathOrdering * For example, if the ``PathType`` is a list of ``ExtrusionJunction``s, * this will store the coordinates of those junctions. */ - std::optional cached_vertices; + std::optional cached_vertices_; }; } diff --git a/include/gcodeExport.h b/include/gcodeExport.h index c332ef0f52..b16512569b 100644 --- a/include/gcodeExport.h +++ b/include/gcodeExport.h @@ -8,6 +8,9 @@ #ifdef BUILD_TESTS #include //To allow tests to use protected members. #endif +#include // for stream.str() +#include + #include "settings/EnumSettings.h" #include "settings/Settings.h" //For MAX_EXTRUDERS. #include "settings/types/LayerIndex.h" @@ -19,9 +22,6 @@ #include "utils/IntPoint.h" #include "utils/NoCopy.h" -#include // for stream.str() -#include - namespace cura { @@ -223,7 +223,7 @@ class GCodeExport : public NoCopy * \param flavor The g-code flavor to print. * \return A serialized form of this flavor. */ - const std::string flavorToString(const EGCodeFlavor& flavor) const; + static std::string flavorToString(const EGCodeFlavor& flavor); /*! * Get the gcode file header (e.g. ";FLAVOR:UltiGCode\n") diff --git a/include/pathPlanning/LinePolygonsCrossings.h b/include/pathPlanning/LinePolygonsCrossings.h index 13a0115964..70802800f2 100644 --- a/include/pathPlanning/LinePolygonsCrossings.h +++ b/include/pathPlanning/LinePolygonsCrossings.h @@ -33,9 +33,9 @@ class LinePolygonsCrossings */ struct Crossing { - size_t poly_idx; //!< The index of the polygon which crosses the scanline - coord_t x; //!< x coordinate of crossings between the polygon and the scanline. - size_t point_idx; //!< The index of the first point of the line segment which crosses the scanline + size_t poly_idx_; //!< The index of the polygon which crosses the scanline + coord_t x_; //!< x coordinate of crossings between the polygon and the scanline. + size_t point_idx_; //!< The index of the first point of the line segment which crosses the scanline /*! * Creates a Crossing with minimal initialization @@ -46,18 +46,18 @@ class LinePolygonsCrossings Crossing(const size_t poly_idx, const coord_t x, const size_t point_idx); }; - std::vector crossings; //!< All crossings of polygons in the LinePolygonsCrossings::boundary with the scanline. + std::vector crossings_; //!< All crossings of polygons in the LinePolygonsCrossings::boundary with the scanline. - const Polygons& boundary; //!< The boundary not to cross during combing. - LocToLineGrid& loc_to_line_grid; //!< Mapping from locations to line segments of \ref LinePolygonsCrossings::boundary - Point startPoint; //!< The start point of the scanline. - Point endPoint; //!< The end point of the scanline. + const Polygons& boundary_; //!< The boundary not to cross during combing. + LocToLineGrid& loc_to_line_grid_; //!< Mapping from locations to line segments of \ref LinePolygonsCrossings::boundary + Point start_point_; //!< The start point of the scanline. + Point end_point_; //!< The end point of the scanline. - int64_t dist_to_move_boundary_point_outside; //!< The distance used to move outside or inside so that a boundary point doesn't intersect with the boundary anymore. Neccesary due to computational rounding problems. Use negative value for insicde combing. + int64_t dist_to_move_boundary_point_outside_; //!< The distance used to move outside or inside so that a boundary point doesn't intersect with the boundary anymore. Neccesary due to computational rounding problems. Use negative value for insicde combing. - PointMatrix transformation_matrix; //!< The transformation which rotates everything such that the scanline is aligned with the x-axis. - Point transformed_startPoint; //!< The LinePolygonsCrossings::startPoint as transformed by Comb::transformation_matrix such that it has (roughly) the same Y as transformed_endPoint - Point transformed_endPoint; //!< The LinePolygonsCrossings::endPoint as transformed by Comb::transformation_matrix such that it has (roughly) the same Y as transformed_startPoint + PointMatrix transformation_matrix_; //!< The transformation which rotates everything such that the scanline is aligned with the x-axis. + Point transformed_start_point_; //!< The LinePolygonsCrossings::startPoint as transformed by Comb::transformation_matrix such that it has (roughly) the same Y as transformed_endPoint + Point transformed_end_point_; //!< The LinePolygonsCrossings::endPoint as transformed by Comb::transformation_matrix such that it has (roughly) the same Y as transformed_startPoint /*! @@ -123,11 +123,11 @@ class LinePolygonsCrossings * \param dist_to_move_boundary_point_outside Distance used to move a point from a boundary so that it doesn't intersect with it anymore. (Precision issue) */ LinePolygonsCrossings(const Polygons& boundary, LocToLineGrid& loc_to_line_grid, Point& start, Point& end, int64_t dist_to_move_boundary_point_outside) - : boundary(boundary) - , loc_to_line_grid(loc_to_line_grid) - , startPoint(start) - , endPoint(end) - , dist_to_move_boundary_point_outside(dist_to_move_boundary_point_outside) + : boundary_(boundary) + , loc_to_line_grid_(loc_to_line_grid) + , start_point_(start) + , end_point_(end) + , dist_to_move_boundary_point_outside_(dist_to_move_boundary_point_outside) { } diff --git a/src/FffGcodeWriter.cpp b/src/FffGcodeWriter.cpp index 1376f48a23..1167cc0168 100644 --- a/src/FffGcodeWriter.cpp +++ b/src/FffGcodeWriter.cpp @@ -1562,7 +1562,7 @@ void FffGcodeWriter::addMeshLayerToGCode( part_order_optimizer.optimize(false); for (const PathOrdering& path : part_order_optimizer.paths) { - addMeshPartToGCode(storage, mesh, extruder_nr, mesh_config, *path.vertices, gcode_layer); + addMeshPartToGCode(storage, mesh, extruder_nr, mesh_config, *path.vertices_, gcode_layer); } const std::string extruder_identifier = (mesh.settings.get("roofing_layer_count") > 0) ? "roofing_extruder_nr" : "top_bottom_extruder_nr"; @@ -2642,7 +2642,7 @@ bool FffGcodeWriter::processSkin( for (const PathOrdering& path : part_order_optimizer.paths) { - const SkinPart& skin_part = *path.vertices; + const SkinPart& skin_part = *path.vertices_; added_something = added_something | processSkinPart(storage, gcode_layer, mesh, extruder_nr, mesh_config, skin_part); } @@ -3233,7 +3233,7 @@ bool FffGcodeWriter::processSupportInfill(const SliceDataStorage& storage, Layer // Print the thicker infill lines first. (double or more layer thickness, infill combined with previous layers) for (const PathOrdering& path : ranges::views::concat(island_order_optimizer_initial.paths, island_order_optimizer.paths)) { - const SupportInfillPart& part = *path.vertices; + const SupportInfillPart& part = *path.vertices_; const auto& configs = part.use_fractional_config ? gcode_layer.configs_storage.support_fractional_infill_config : gcode_layer.configs_storage.support_infill_config; // always process the wall overlap if walls are generated diff --git a/src/InsetOrderOptimizer.cpp b/src/InsetOrderOptimizer.cpp index 05b1fa3f3f..62d9382e62 100644 --- a/src/InsetOrderOptimizer.cpp +++ b/src/InsetOrderOptimizer.cpp @@ -115,24 +115,24 @@ bool InsetOrderOptimizer::addToLayer() for (const PathOrdering& path : order_optimizer.paths) { - if (path.vertices->empty()) + if (path.vertices_->empty()) continue; - const bool is_outer_wall = path.vertices->inset_idx == 0; // or thin wall 'gap filler' - const bool is_gap_filler = path.vertices->is_odd; + const bool is_outer_wall = path.vertices_->inset_idx == 0; // or thin wall 'gap filler' + const bool is_gap_filler = path.vertices_->is_odd; const GCodePathConfig& non_bridge_config = is_outer_wall ? inset_0_non_bridge_config : inset_X_non_bridge_config; const GCodePathConfig& bridge_config = is_outer_wall ? inset_0_bridge_config : inset_X_bridge_config; const coord_t wipe_dist = is_outer_wall && ! is_gap_filler ? wall_0_wipe_dist : wall_x_wipe_dist; const bool retract_before = is_outer_wall ? retract_before_outer_wall : false; - const bool revert_inset = alternate_walls && (path.vertices->inset_idx % 2); + const bool revert_inset = alternate_walls && (path.vertices_->inset_idx % 2); const bool revert_layer = alternate_walls && (layer_nr % 2); - const bool backwards = path.backwards != (revert_inset != revert_layer); - const size_t start_index = (backwards != path.backwards) ? path.vertices->size() - (path.start_vertex + 1) : path.start_vertex; - const bool linked_path = ! path.is_closed; + const bool backwards = path.backwards_ != (revert_inset != revert_layer); + const size_t start_index = (backwards != path.backwards_) ? path.vertices_->size() - (path.start_vertex_ + 1) : path.start_vertex_; + const bool linked_path = ! path.is_closed_; gcode_layer.setIsInside(true); // Going to print walls, which are always inside. - gcode_layer.addWall(*path.vertices, start_index, settings, non_bridge_config, bridge_config, wipe_dist, flow, retract_before, path.is_closed, backwards, linked_path); + gcode_layer.addWall(*path.vertices_, start_index, settings, non_bridge_config, bridge_config, wipe_dist, flow, retract_before, path.is_closed_, backwards, linked_path); added_something = true; } return added_something; diff --git a/src/LayerPlan.cpp b/src/LayerPlan.cpp index da66aa7601..7774241e5d 100644 --- a/src/LayerPlan.cpp +++ b/src/LayerPlan.cpp @@ -610,7 +610,7 @@ void LayerPlan::addPolygonsByOptimizer( { for (const PathOrdering& path : orderOptimizer.paths) { - addPolygon(*path.vertices, path.start_vertex, path.backwards, config, wall_0_wipe_dist, spiralize, flow_ratio, always_retract); + addPolygon(*path.vertices_, path.start_vertex_, path.backwards_, config, wall_0_wipe_dist, spiralize, flow_ratio, always_retract); } } else @@ -618,7 +618,7 @@ void LayerPlan::addPolygonsByOptimizer( for (int index = orderOptimizer.paths.size() - 1; index >= 0; --index) { const PathOrdering& path = orderOptimizer.paths[index]; - addPolygon(**path.vertices, path.start_vertex, path.backwards, config, wall_0_wipe_dist, spiralize, flow_ratio, always_retract); + addPolygon(**path.vertices_, path.start_vertex_, path.backwards_, config, wall_0_wipe_dist, spiralize, flow_ratio, always_retract); } } } @@ -1166,7 +1166,7 @@ void LayerPlan::addWalls( orderOptimizer.optimize(); for (const PathOrdering& path : orderOptimizer.paths) { - addWall(**path.vertices, path.start_vertex, settings, non_bridge_config, bridge_config, wall_0_wipe_dist, flow_ratio, always_retract); + addWall(**path.vertices_, path.start_vertex_, settings, non_bridge_config, bridge_config, wall_0_wipe_dist, flow_ratio, always_retract); } } @@ -1236,9 +1236,9 @@ void LayerPlan::addLinesInGivenOrder( for (size_t order_idx = 0; order_idx < paths.size(); order_idx++) { const PathOrdering& path = paths[order_idx]; - ConstPolygonRef polyline = *path.vertices; - const size_t start_idx = path.start_vertex; - assert(start_idx == 0 || start_idx == polyline.size() - 1 || path.is_closed); + ConstPolygonRef polyline = *path.vertices_; + const size_t start_idx = path.start_vertex_; + assert(start_idx == 0 || start_idx == polyline.size() - 1 || path.is_closed_); const Point start = polyline[start_idx]; if (vSize2(getLastPlannedPositionOrStartingPosition() - start) < line_width_2) @@ -1260,7 +1260,7 @@ void LayerPlan::addLinesInGivenOrder( for (size_t idx = 0; idx < polyline.size(); idx++) { size_t point_idx; - if (path.is_closed) + if (path.is_closed_) { point_idx = (start_idx + idx + 1) % polyline.size(); } @@ -1305,8 +1305,8 @@ void LayerPlan::addLinesInGivenOrder( if (wipe && (order_idx < paths.size() - 1)) { const PathOrdering& next_path = paths[order_idx + 1]; - ConstPolygonRef next_polygon = *next_path.vertices; - const size_t next_start = next_path.start_vertex; + ConstPolygonRef next_polygon = *next_path.vertices_; + const size_t next_start = next_path.start_vertex_; const Point& next_p0 = next_polygon[next_start]; if (vSize2(next_p0 - p1) <= line_width * line_width * 4) { @@ -1361,9 +1361,9 @@ void LayerPlan::addLinesMonotonic( bool last_would_have_been_excluded = false; for (size_t line_idx = 0; line_idx < line_order.paths.size(); ++line_idx) { - const ConstPolygonRef polyline = *line_order.paths[line_idx].vertices; + const ConstPolygonRef polyline = *line_order.paths[line_idx].vertices_; const bool inside_exclusion = is_inside_exclusion(polyline); - const bool next_would_have_been_included = inside_exclusion && (line_idx < line_order.paths.size() - 1 && is_inside_exclusion(*line_order.paths[line_idx + 1].vertices)); + const bool next_would_have_been_included = inside_exclusion && (line_idx < line_order.paths.size() - 1 && is_inside_exclusion(*line_order.paths[line_idx + 1].vertices_)); if (inside_exclusion && last_would_have_been_excluded && next_would_have_been_included) { left_over.add(polyline); diff --git a/src/PathOrderPath.cpp b/src/PathOrderPath.cpp index 510b52e31e..45039c98d4 100644 --- a/src/PathOrderPath.cpp +++ b/src/PathOrderPath.cpp @@ -11,40 +11,40 @@ namespace cura template<> ConstPolygonRef PathOrdering::getVertexData() { - return *vertices; + return *vertices_; } template<> ConstPolygonRef PathOrdering::getVertexData() { - return *vertices; + return *vertices_; } template<> ConstPolygonRef PathOrdering::getVertexData() { - return vertices->outline.outerPolygon(); + return vertices_->outline.outerPolygon(); } template<> ConstPolygonRef PathOrdering::getVertexData() { - return vertices->outline.outerPolygon(); + return vertices_->outline.outerPolygon(); } template<> ConstPolygonRef PathOrdering::getVertexData() { - return vertices->outline.outerPolygon(); + return vertices_->outline.outerPolygon(); } template<> ConstPolygonRef PathOrdering::getVertexData() { - if ( ! cached_vertices) + if ( ! cached_vertices_) { - cached_vertices = vertices->toPolygon(); + cached_vertices_ = vertices_->toPolygon(); } - return ConstPolygonRef(*cached_vertices); + return ConstPolygonRef(*cached_vertices_); } } diff --git a/src/gcodeExport.cpp b/src/gcodeExport.cpp index deb58664dc..68c060dc61 100644 --- a/src/gcodeExport.cpp +++ b/src/gcodeExport.cpp @@ -170,7 +170,7 @@ void GCodeExport::setInitialTemp(int extruder_nr, double temp) } } -const std::string GCodeExport::flavorToString(const EGCodeFlavor& flavor) const +std::string GCodeExport::flavorToString(const EGCodeFlavor& flavor) { switch (flavor) { diff --git a/src/pathPlanning/LinePolygonsCrossings.cpp b/src/pathPlanning/LinePolygonsCrossings.cpp index 4d5ef8d5dd..85896739b2 100644 --- a/src/pathPlanning/LinePolygonsCrossings.cpp +++ b/src/pathPlanning/LinePolygonsCrossings.cpp @@ -11,77 +11,77 @@ namespace cura { LinePolygonsCrossings::Crossing::Crossing(const size_t poly_idx, const coord_t x, const size_t point_idx) -: poly_idx(poly_idx) -, x(x) -, point_idx(point_idx) +: poly_idx_(poly_idx) +, x_(x) +, point_idx_(point_idx) { } bool LinePolygonsCrossings::calcScanlineCrossings(bool fail_on_unavoidable_obstacles) { - for(unsigned int poly_idx = 0; poly_idx < boundary.size(); poly_idx++) + for(unsigned int poly_idx = 0; poly_idx < boundary_.size(); poly_idx++) { - ConstPolygonRef poly = boundary[poly_idx]; - Point p0 = transformation_matrix.apply(poly[poly.size() - 1]); + ConstPolygonRef poly = boundary_[poly_idx]; + Point p0 = transformation_matrix_.apply(poly[poly.size() - 1]); for(unsigned int point_idx = 0; point_idx < poly.size(); point_idx++) { - Point p1 = transformation_matrix.apply(poly[point_idx]); - if ((p0.Y >= transformed_startPoint.Y && p1.Y <= transformed_startPoint.Y) || (p1.Y >= transformed_startPoint.Y && p0.Y <= transformed_startPoint.Y)) + Point p1 = transformation_matrix_.apply(poly[point_idx]); + if ((p0.Y >= transformed_start_point_.Y && p1.Y <= transformed_start_point_.Y) || (p1.Y >= transformed_start_point_.Y && p0.Y <= transformed_start_point_.Y)) { // if line segment crosses the line through the transformed start and end point (aka scanline) if (p1.Y == p0.Y) //Line segment is parallel with the scanline. That means that both endpoints lie on the scanline, so they will have intersected with the adjacent line. { p0 = p1; continue; } - const coord_t x = p0.X + (p1.X - p0.X) * (transformed_startPoint.Y - p0.Y) / (p1.Y - p0.Y); // intersection point between line segment and the scanline + const coord_t x = p0.X + (p1.X - p0.X) * (transformed_start_point_.Y - p0.Y) / (p1.Y - p0.Y); // intersection point between line segment and the scanline - if (x >= transformed_startPoint.X && x <= transformed_endPoint.X) + if (x >= transformed_start_point_.X && x <= transformed_end_point_.X) { - if (!((p1.Y == transformed_startPoint.Y && p1.Y < p0.Y) || (p0.Y == transformed_startPoint.Y && p0.Y < p1.Y))) + if (!((p1.Y == transformed_start_point_.Y && p1.Y < p0.Y) || (p0.Y == transformed_start_point_.Y && p0.Y < p1.Y))) { // perform edge case only for line segments on and below the scanline, not for line segments on and above. // \/ will be no crossings and /\ two, but most importantly | will be one crossing. - crossings.emplace_back(poly_idx, x, point_idx); + crossings_.emplace_back(poly_idx, x, point_idx); } } } p0 = p1; } - if (fail_on_unavoidable_obstacles && crossings.size() % 2 == 1) + if (fail_on_unavoidable_obstacles && crossings_.size() % 2 == 1) { // if start area and end area are not the same return false; } } // order crossings by increasing x - std::sort(crossings.begin(), crossings.end(), [](const Crossing& a, const Crossing& b) -> bool { return a.x < b.x; }); + std::sort(crossings_.begin(), crossings_.end(), [](const Crossing& a, const Crossing& b) -> bool { return a.x_ < b.x_; }); return true; } bool LinePolygonsCrossings::lineSegmentCollidesWithBoundary() { - Point diff = endPoint - startPoint; + Point diff = end_point_ - start_point_; - transformation_matrix = PointMatrix(diff); - transformed_startPoint = transformation_matrix.apply(startPoint); - transformed_endPoint = transformation_matrix.apply(endPoint); + transformation_matrix_ = PointMatrix(diff); + transformed_start_point_ = transformation_matrix_.apply(start_point_); + transformed_end_point_ = transformation_matrix_.apply(end_point_); - for(ConstPolygonRef poly : boundary) + for(ConstPolygonRef poly : boundary_) { - Point p0 = transformation_matrix.apply(poly.back()); + Point p0 = transformation_matrix_.apply(poly.back()); for(Point p1_ : poly) { - Point p1 = transformation_matrix.apply(p1_); + Point p1 = transformation_matrix_.apply(p1_); // when the boundary just touches the line don't disambiguate between the boundary moving on to actually cross the line // and the boundary bouncing back, resulting in not a real collision - to keep the algorithm simple. // // disregard overlapping line segments; probably the next or previous line segment is not overlapping, but will give a collision // when the boundary line segment fully overlaps with the line segment this edge case is not viewed as a collision - if (p1.Y != p0.Y && ((p0.Y >= transformed_startPoint.Y && p1.Y <= transformed_startPoint.Y) || (p1.Y >= transformed_startPoint.Y && p0.Y <= transformed_startPoint.Y))) + if (p1.Y != p0.Y && ((p0.Y >= transformed_start_point_.Y && p1.Y <= transformed_start_point_.Y) || (p1.Y >= transformed_start_point_.Y && p0.Y <= transformed_start_point_.Y))) { - int64_t x = p0.X + (p1.X - p0.X) * (transformed_startPoint.Y - p0.Y) / (p1.Y - p0.Y); + int64_t x = p0.X + (p1.X - p0.X) * (transformed_start_point_.Y - p0.Y) / (p1.Y - p0.Y); - if (x > transformed_startPoint.X && x < transformed_endPoint.X) + if (x > transformed_start_point_.X && x < transformed_end_point_.X) { return true; } @@ -96,11 +96,11 @@ bool LinePolygonsCrossings::lineSegmentCollidesWithBoundary() bool LinePolygonsCrossings::generateCombingPath(CombPath& combPath, int64_t max_comb_distance_ignored, bool fail_on_unavoidable_obstacles) { - if (shorterThen(endPoint - startPoint, max_comb_distance_ignored) || !lineSegmentCollidesWithBoundary()) + if (shorterThen(end_point_ - start_point_, max_comb_distance_ignored) || !lineSegmentCollidesWithBoundary()) { //We're not crossing any boundaries. So skip the comb generation. - combPath.push_back(startPoint); - combPath.push_back(endPoint); + combPath.push_back(start_point_); + combPath.push_back(end_point_); return true; } @@ -121,46 +121,46 @@ bool LinePolygonsCrossings::generateCombingPath(CombPath& combPath, int64_t max_ void LinePolygonsCrossings::generateBasicCombingPath(CombPath& combPath) { // crossings are ordered by increasing x - for (unsigned i = 0; i < crossings.size(); ++i) + for (unsigned i = 0; i < crossings_.size(); ++i) { // find the next crossing that belongs to the same polygon - for (unsigned j = i + 1; j < crossings.size(); ++j) + for (unsigned j = i + 1; j < crossings_.size(); ++j) { - if (crossings[i].poly_idx == crossings[j].poly_idx) + if (crossings_[i].poly_idx_ == crossings_[j].poly_idx_) { // comb between the two crossings - generateBasicCombingPath(crossings[i], crossings[j], combPath); + generateBasicCombingPath(crossings_[i], crossings_[j], combPath); // update outer loop variable to skip any crossings on other polygons i = j; break; } } } - combPath.push_back(endPoint); + combPath.push_back(end_point_); } void LinePolygonsCrossings::generateBasicCombingPath(const Crossing& min, const Crossing& max, CombPath& combPath) { // minimise the path length by measuring the length of both paths around the polygon so we can determine the shorter path - ConstPolygonRef poly = boundary[min.poly_idx]; - combPath.push_back(transformation_matrix.unapply(Point(min.x - std::abs(dist_to_move_boundary_point_outside), transformed_startPoint.Y))); + ConstPolygonRef poly = boundary_[min.poly_idx_]; + combPath.push_back(transformation_matrix_.unapply(Point(min.x_ - std::abs(dist_to_move_boundary_point_outside_), transformed_start_point_.Y))); // follow the path in the same direction as the winding order of the boundary polygon std::vector fwd_points; Point prev = combPath.back(); coord_t fwd_len = 0; - for (unsigned int point_idx = min.point_idx - ; point_idx != max.point_idx + for (unsigned int point_idx = min.point_idx_ + ; point_idx != max.point_idx_ ; point_idx = (point_idx < poly.size() - 1) ? (point_idx + 1) : (0)) { - const Point p = PolygonUtils::getBoundaryPointWithOffset(poly, point_idx, dist_to_move_boundary_point_outside); + const Point p = PolygonUtils::getBoundaryPointWithOffset(poly, point_idx, dist_to_move_boundary_point_outside_); fwd_points.push_back(p); fwd_len += vSize(p - prev); prev = p; } - const Point last = transformation_matrix.unapply(Point(max.x + std::abs(dist_to_move_boundary_point_outside), transformed_startPoint.Y)); + const Point last = transformation_matrix_.unapply(Point(max.x_ + std::abs(dist_to_move_boundary_point_outside_), transformed_start_point_.Y)); if (fwd_points.size() > 0) { @@ -171,13 +171,13 @@ void LinePolygonsCrossings::generateBasicCombingPath(const Crossing& min, const std::vector rev_points; prev = combPath.back(); coord_t rev_len = 0; - unsigned int min_idx = (min.point_idx == 0)? poly.size() - 1 : min.point_idx - 1; - unsigned int max_idx = (max.point_idx == 0)? poly.size() - 1 : max.point_idx - 1; + unsigned int min_idx = (min.point_idx_ == 0)? poly.size() - 1 : min.point_idx_ - 1; + unsigned int max_idx = (max.point_idx_ == 0)? poly.size() - 1 : max.point_idx_ - 1; for (unsigned int point_idx = min_idx ; point_idx != max_idx ; point_idx = (point_idx > 0) ? (point_idx - 1) : (poly.size() - 1)) { - const Point p = PolygonUtils::getBoundaryPointWithOffset(poly, point_idx, dist_to_move_boundary_point_outside); + const Point p = PolygonUtils::getBoundaryPointWithOffset(poly, point_idx, dist_to_move_boundary_point_outside_); rev_points.push_back(p); rev_len += vSize(p - prev); prev = p; @@ -203,7 +203,7 @@ void LinePolygonsCrossings::generateBasicCombingPath(const Crossing& min, const bool LinePolygonsCrossings::optimizePath(CombPath& comb_path, CombPath& optimized_comb_path) { - optimized_comb_path.push_back(startPoint); + optimized_comb_path.push_back(start_point_); for(unsigned int point_idx = 1; point_idx 0; n >>= 1) { - if (optimized_comb_path.size() > n && !PolygonUtils::polygonCollidesWithLineSegment(optimized_comb_path[optimized_comb_path.size() - n - 1], comb_path[point_idx - 1], loc_to_line_grid)) + if (optimized_comb_path.size() > n && !PolygonUtils::polygonCollidesWithLineSegment(optimized_comb_path[optimized_comb_path.size() - n - 1], comb_path[point_idx - 1], loc_to_line_grid_)) { // we can remove n points from the path without it clashing with the combing boundary for (unsigned i = 0; i < n; ++i) @@ -254,7 +254,7 @@ bool LinePolygonsCrossings::optimizePath(CombPath& comb_path, CombPath& optimize { // slide p towards the second point in the comb path p = comb_path[1] + (p - comb_path[1]) * frac; - if (!PolygonUtils::polygonCollidesWithLineSegment(startPoint, p, loc_to_line_grid)) + if (!PolygonUtils::polygonCollidesWithLineSegment(start_point_, p, loc_to_line_grid_)) { // using the new corner doesn't cause a conflict optimized_comb_path.back() = p; @@ -274,7 +274,7 @@ bool LinePolygonsCrossings::optimizePath(CombPath& comb_path, CombPath& optimize // TODO: add the below extra optimization? (+/- 7% extra computation time, +/- 2% faster print for Dual_extrusion_support_generation.stl) while (optimized_comb_path.size() > 1) { - if (PolygonUtils::polygonCollidesWithLineSegment(optimized_comb_path[optimized_comb_path.size() - 2], comb_path[point_idx], loc_to_line_grid)) + if (PolygonUtils::polygonCollidesWithLineSegment(optimized_comb_path[optimized_comb_path.size() - 2], comb_path[point_idx], loc_to_line_grid_)) { break; } @@ -290,7 +290,7 @@ bool LinePolygonsCrossings::optimizePath(CombPath& comb_path, CombPath& optimize { const unsigned n = optimized_comb_path.size(); // the penultimate corner may be deleted if the resulting path doesn't conflict with the boundary - if (!PolygonUtils::polygonCollidesWithLineSegment(optimized_comb_path[n - 2], comb_path.back(), loc_to_line_grid)) + if (!PolygonUtils::polygonCollidesWithLineSegment(optimized_comb_path[n - 2], comb_path.back(), loc_to_line_grid_)) { optimized_comb_path.pop_back(); } @@ -301,7 +301,7 @@ bool LinePolygonsCrossings::optimizePath(CombPath& comb_path, CombPath& optimize { // make a new point between the penultimate corner and the corner before that Point p = optimized_comb_path[n - 2] + (optimized_comb_path[n - 1] - optimized_comb_path[n - 2]) * frac; - if (!PolygonUtils::polygonCollidesWithLineSegment(p, comb_path.back(), loc_to_line_grid)) + if (!PolygonUtils::polygonCollidesWithLineSegment(p, comb_path.back(), loc_to_line_grid_)) { // using the new corner doesn't cause a conflict optimized_comb_path[n - 1] = p; diff --git a/tests/PathOrderMonotonicTest.cpp b/tests/PathOrderMonotonicTest.cpp index 1a0ca213a4..775376c7d1 100644 --- a/tests/PathOrderMonotonicTest.cpp +++ b/tests/PathOrderMonotonicTest.cpp @@ -32,12 +32,12 @@ class PathOrderMonotonicTest : public testing::TestWithParam& path) { - return (*path.vertices)[path.start_vertex]; + return (*path.vertices_)[path.start_vertex_]; } inline Point endVertex(const PathOrdering& path) { - return (*path.vertices)[path.vertices->size() - (1 + path.start_vertex)]; + return (*path.vertices_)[path.vertices_->size() - (1 + path.start_vertex_)]; } coord_t projectPathAlongAxis(const PathOrdering& path, const Point& vector) From 01b03243710875836fbe241e89b06735bab1da76 Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Tue, 21 Nov 2023 10:37:04 +0100 Subject: [PATCH 11/48] Fixed variable shadowing warnings --- include/LayerPlan.h | 2 +- include/PathOrderOptimizer.h | 144 +++++++++++++++++------------------ include/utils/views/dfs.h | 28 +++---- src/FffGcodeWriter.cpp | 6 +- src/InsetOrderOptimizer.cpp | 2 +- src/LayerPlan.cpp | 16 ++-- 6 files changed, 98 insertions(+), 100 deletions(-) diff --git a/include/LayerPlan.h b/include/LayerPlan.h index 972af3e6d3..4ad62a6584 100644 --- a/include/LayerPlan.h +++ b/include/LayerPlan.h @@ -530,7 +530,7 @@ class LayerPlan : public NoCopy const std::optional near_start_location = std::optional(), const double fan_speed = GCodePathConfig::FAN_SPEED_DEFAULT, const bool reverse_print_direction = false, - const std::unordered_multimap& order_requirements = PathOrderOptimizer::no_order_requirements); + const std::unordered_multimap& order_requirements = PathOrderOptimizer::no_order_requirements_); /*! * Add polygons to the g-code with monotonic order. diff --git a/include/PathOrderOptimizer.h b/include/PathOrderOptimizer.h index 8072a501a8..2206ece605 100644 --- a/include/PathOrderOptimizer.h +++ b/include/PathOrderOptimizer.h @@ -69,23 +69,25 @@ class PathOrderOptimizer * pointer to the vertex data, whether or not to close the loop, the * direction in which to print the path and where to start the path. */ - std::vector paths; + std::vector paths_; /*! * Maps the path implementation to it's orderable path container */ - std::unordered_map vertices_to_paths; + std::unordered_map vertices_to_paths_; /*! * The location where the nozzle is assumed to start from before printing * these parts. */ - Point start_point; + const Point start_point_; /*! * Seam settings. */ - ZSeamConfig seam_config; + const ZSeamConfig seam_config_; + + static const std::unordered_multimap no_order_requirements_; /*! * Construct a new optimizer. @@ -107,15 +109,15 @@ class PathOrderOptimizer const bool detect_loops = false, const Polygons* combing_boundary = nullptr, const bool reverse_direction = false, - const std::unordered_multimap& order_requirements = no_order_requirements, + const std::unordered_multimap& order_requirements = no_order_requirements_, const bool group_outer_walls = false) - : start_point(start_point) - , seam_config(seam_config) - , combing_boundary((combing_boundary != nullptr && ! combing_boundary->empty()) ? combing_boundary : nullptr) - , detect_loops(detect_loops) - , reverse_direction(reverse_direction) - , order_requirements(&order_requirements) - , group_outer_walls(group_outer_walls) + : start_point_(start_point) + , seam_config_(seam_config) + , combing_boundary_((combing_boundary != nullptr && ! combing_boundary->empty()) ? combing_boundary : nullptr) + , detect_loops_(detect_loops) + , reverse_direction_(reverse_direction) + , order_requirements_(&order_requirements) + , _group_outer_walls(group_outer_walls) { } @@ -126,7 +128,7 @@ class PathOrderOptimizer void addPolygon(const Path& polygon) { constexpr bool is_closed = true; - paths.emplace_back(polygon, is_closed); + paths_.emplace_back(polygon, is_closed); } /*! @@ -136,7 +138,7 @@ class PathOrderOptimizer void addPolyline(const Path& polyline) { constexpr bool is_closed = false; - paths.emplace_back(polyline, is_closed); + paths_.emplace_back(polyline, is_closed); } /*! @@ -147,22 +149,22 @@ class PathOrderOptimizer */ void optimize(bool precompute_start = true) { - if (paths.empty()) + if (paths_.empty()) { return; } // Get the vertex data and store it in the paths. - for (auto& path : paths) + for (auto& path : paths_) { path.converted_ = path.getVertexData(); - vertices_to_paths.emplace(path.vertices_, &path); + vertices_to_paths_.emplace(path.vertices_, &path); } // If necessary, check polylines to see if they are actually polygons. - if (detect_loops) + if (detect_loops_) { - for (auto& path : paths) + for (auto& path : paths_) { if (! path.is_closed_) { @@ -175,7 +177,7 @@ class PathOrderOptimizer // Add all vertices to a bucket grid so that we can find nearby endpoints quickly. const coord_t snap_radius = 10_mu; // 0.01mm grid cells. Chaining only needs to consider polylines which are next to each other. SparsePointGridInclusive line_bucket_grid(snap_radius); - for (const auto& [i, path] : paths | ranges::views::enumerate) + for (const auto& [i, path] : paths_ | ranges::views::enumerate) { if (path.converted_->empty()) { @@ -197,42 +199,42 @@ class PathOrderOptimizer // For some Z seam types the start position can be pre-computed. // This is faster since we don't need to re-compute the start position at each step then. - precompute_start &= seam_config.type == EZSeamType::RANDOM || seam_config.type == EZSeamType::USER_SPECIFIED || seam_config.type == EZSeamType::SHARPEST_CORNER; + precompute_start &= seam_config_.type == EZSeamType::RANDOM || seam_config_.type == EZSeamType::USER_SPECIFIED || seam_config_.type == EZSeamType::SHARPEST_CORNER; if (precompute_start) { - for (auto& path : paths) + for (auto& path : paths_) { if (! path.is_closed_ || path.converted_->empty()) { continue; // Can't pre-compute the seam for open polylines since they're at the endpoint nearest to the current position. } - path.start_vertex_ = findStartLocation(path, seam_config.pos); + path.start_vertex_ = findStartLocation(path, seam_config_.pos); } } std::vector optimized_order; // To store our result in. At the end we'll std::swap. - if (order_requirements->empty()) + if (order_requirements_->empty()) { optimized_order = getOptimizedOrder(line_bucket_grid, snap_radius); } else { - optimized_order = getOptimizerOrderWithConstraints(line_bucket_grid, snap_radius, *order_requirements); + optimized_order = getOptimizerOrderWithConstraints(line_bucket_grid, snap_radius, *order_requirements_); } - if (reverse_direction && order_requirements->empty()) + if (reverse_direction_ && order_requirements_->empty()) { std::vector reversed = reverseOrderPaths(optimized_order); // Reverse-insert the optimized order, to invert the ordering. - std::swap(reversed, paths); + std::swap(reversed, paths_); } else { - std::swap(optimized_order, paths); + std::swap(optimized_order, paths_); } - combing_grid.reset(); + combing_grid_.reset(); } protected: @@ -241,7 +243,7 @@ class PathOrderOptimizer * than this distance together will be considered to be coincident, closing * that polyline into a polygon. */ - constexpr static coord_t coincident_point_distance = 10; + constexpr static coord_t _coincident_point_distance = 10; /*! * Bucket grid to store the locations of the combing boundary. @@ -250,12 +252,12 @@ class PathOrderOptimizer * combing boundary. We only need to generate this mapping once for the * combing boundary, since the combing boundary can't change. */ - std::unique_ptr combing_grid; + std::unique_ptr combing_grid_; /*! * Boundary to avoid when making travel moves. */ - const Polygons* combing_boundary; + const Polygons* combing_boundary_; /*! * Whether to check polylines to see if they are closed, before optimizing. @@ -266,7 +268,7 @@ class PathOrderOptimizer * polygons. This then allows the optimizer to decide on a seam location * that is not one of the endpoints of the polyline. */ - bool detect_loops; + const bool detect_loops_; /*! * Whether to reverse the ordering completely. @@ -274,7 +276,7 @@ class PathOrderOptimizer * This reverses the order in which parts are printed, and inverts the * direction of each path as well. */ - bool reverse_direction; + const bool reverse_direction_; /* * Whether to print all outer walls in a group, one after another. @@ -282,15 +284,21 @@ class PathOrderOptimizer * If this is enabled outer walls will be printed first and then all other * walls will be printed. If reversed they will be printed last. */ - bool group_outer_walls; + const bool _group_outer_walls; + + /*! + * Order requirements on the paths. + * For each pair the first needs to be printe before the second. + */ + const std::unordered_multimap* order_requirements_; std::vector getOptimizedOrder(SparsePointGridInclusive line_bucket_grid, size_t snap_radius) { std::vector optimized_order; // To store our result in. - Point current_position = start_point; + Point current_position = start_point_; - std::unordered_map picked(paths.size()); // Fixed size boolean flag for whether each path is already in the optimized vector. + std::unordered_map picked(paths_.size()); // Fixed size boolean flag for whether each path is already in the optimized vector. auto isPicked = [&picked](OrderablePath* c) { @@ -301,13 +309,13 @@ class PathOrderOptimizer return ! picked[c]; }; - while (optimized_order.size() < paths.size()) + while (optimized_order.size() < paths_.size()) { // Use bucket grid to find paths within snap_radius std::vector nearby_candidates; for (const auto i : line_bucket_grid.getNearbyVals(current_position, snap_radius)) { - nearby_candidates.push_back(&paths[i]); // Convert bucket indexes to corresponding paths + nearby_candidates.push_back(&paths_[i]); // Convert bucket indexes to corresponding paths } std::vector available_candidates; @@ -319,7 +327,7 @@ class PathOrderOptimizer if (available_candidates.empty()) // We need to broaden our search through all candidates { - for (auto path : paths | ranges::views::addressof | ranges::views::filter(notPicked)) + for (auto path : paths_ | ranges::views::addressof | ranges::views::filter(notPicked)) { available_candidates.push_back(path); } @@ -356,7 +364,7 @@ class PathOrderOptimizer // initialize the roots set with all possible nodes std::unordered_set roots; std::unordered_set leaves; - for (const auto& path : paths) + for (const auto& path : paths_) { roots.insert(path.vertices_); leaves.insert(path.vertices_); @@ -373,7 +381,7 @@ class PathOrderOptimizer // We used a shared visited set between runs of dfs. This is for the case when we reverse the ordering tree. // In this case two roots can share the same children nodes, but we don't want to print them twice. std::unordered_set visited; - Point current_position = start_point; + Point current_position = start_point_; std::function(const Path, const std::unordered_multimap&)> get_neighbours = [current_position, this](const Path current_node, const std::unordered_multimap& graph) @@ -397,7 +405,7 @@ class PathOrderOptimizer order.push_back(best_candidate); // update local_current_position - auto path = vertices_to_paths[best_candidate]; + auto path = vertices_to_paths_[best_candidate]; if (path->is_closed_) { @@ -417,7 +425,7 @@ class PathOrderOptimizer = [¤t_position, &optimized_order, this](const Path current_node, const std::nullptr_t _state) { // We should make map from node <-> path for this stuff - for (auto& path : paths) + for (auto& path : paths_) { if (path.vertices_ == current_node) { @@ -441,9 +449,9 @@ class PathOrderOptimizer return nullptr; }; - if (group_outer_walls) + if (_group_outer_walls) { - if (reverse_direction) + if (reverse_direction_) { // When the order is reverse the leaves of the order requirement are the outer walls std::unordered_set outer_walls = leaves; @@ -534,7 +542,7 @@ class PathOrderOptimizer for (auto& path : candidate_paths) { - candidate_orderable_paths.push_back(vertices_to_paths.at(path)); + candidate_orderable_paths.push_back(vertices_to_paths_.at(path)); } OrderablePath* best_candidate = findClosestPath(start_position, candidate_orderable_paths); @@ -558,7 +566,7 @@ class PathOrderOptimizer } const bool precompute_start - = seam_config.type == EZSeamType::RANDOM || seam_config.type == EZSeamType::USER_SPECIFIED || seam_config.type == EZSeamType::SHARPEST_CORNER; + = seam_config_.type == EZSeamType::RANDOM || seam_config_.type == EZSeamType::USER_SPECIFIED || seam_config_.type == EZSeamType::SHARPEST_CORNER; if (! path->is_closed_ || ! precompute_start) // Find the start location unless we've already precomputed it. { path->start_vertex_ = findStartLocation(*path, start_position); @@ -570,7 +578,7 @@ class PathOrderOptimizer const Point candidate_position = (*path->converted_)[path->start_vertex_]; coord_t distance2 = getDirectDistance(start_position, candidate_position); if (distance2 < best_distance2 - && combing_boundary) // If direct distance is longer than best combing distance, the combing distance can never be better, so only compute combing if necessary. + && combing_boundary_) // If direct distance is longer than best combing distance, the combing distance can never be better, so only compute combing if necessary. { distance2 = getCombingDistance(start_position, candidate_position); } @@ -584,16 +592,6 @@ class PathOrderOptimizer return best_candidate; } -public: - static const std::unordered_multimap no_order_requirements; - -protected: - /*! - * Order requirements on the paths. - * For each pair the first needs to be printe before the second. - */ - const std::unordered_multimap* order_requirements; - /*! * Find the vertex which will be the starting point of printing a polygon or * polyline. @@ -616,9 +614,9 @@ class PathOrderOptimizer { // For polylines, the seam settings are not applicable. Simply choose the position closest to target_pos then. const coord_t back_distance - = (combing_boundary == nullptr) ? getDirectDistance(path.converted_->back(), target_pos) : getCombingDistance(path.converted_->back(), target_pos); + = (combing_boundary_ == nullptr) ? getDirectDistance(path.converted_->back(), target_pos) : getCombingDistance(path.converted_->back(), target_pos); if (back_distance < getDirectDistance(path.converted_->front(), target_pos) - || (combing_boundary + || (combing_boundary_ && back_distance < getCombingDistance(path.converted_->front(), target_pos))) // Lazy or: Only compute combing distance if direct distance is closer. { return path.converted_->size() - 1; // Back end is closer. @@ -631,7 +629,7 @@ class PathOrderOptimizer // Rest of the function only deals with (closed) polygons. We need to be able to find the seam location of those polygons. - if (seam_config.type == EZSeamType::RANDOM) + if (seam_config_.type == EZSeamType::RANDOM) { size_t vert = getRandomPointInPolygon(*path.converted_); return vert; @@ -654,8 +652,8 @@ class PathOrderOptimizer { // For most seam types, the shortest distance matters. Not for SHARPEST_CORNER though. // For SHARPEST_CORNER, use a fixed starting score of 0. - const coord_t distance = (combing_boundary == nullptr) ? getDirectDistance(here, target_pos) : getCombingDistance(here, target_pos); - const float score_distance = (seam_config.type == EZSeamType::SHARPEST_CORNER && seam_config.corner_pref != EZSeamCornerPrefType::Z_SEAM_CORNER_PREF_NONE) + const coord_t distance = (combing_boundary_ == nullptr) ? getDirectDistance(here, target_pos) : getCombingDistance(here, target_pos); + const float score_distance = (seam_config_.type == EZSeamType::SHARPEST_CORNER && seam_config_.corner_pref != EZSeamCornerPrefType::Z_SEAM_CORNER_PREF_NONE) ? MM2INT(10) : vSize2(here - target_pos); @@ -664,7 +662,7 @@ class PathOrderOptimizer // angles > 0 are convex (right turning) float corner_shift; - if (seam_config.type == EZSeamType::SHORTEST) + if (seam_config_.type == EZSeamType::SHORTEST) { // the more a corner satisfies our criteria, the closer it appears to be // shift 10mm for a very acute corner @@ -680,7 +678,7 @@ class PathOrderOptimizer } float score = score_distance; - switch (seam_config.corner_pref) + switch (seam_config_.corner_pref) { default: case EZSeamCornerPrefType::Z_SEAM_CORNER_PREF_INNER: @@ -835,11 +833,11 @@ class PathOrderOptimizer */ coord_t getCombingDistance(const Point& a, const Point& b) { - if (! PolygonUtils::polygonCollidesWithLineSegment(*combing_boundary, a, b)) + if (! PolygonUtils::polygonCollidesWithLineSegment(*combing_boundary_, a, b)) { return getDirectDistance(a, b); // No collision with any line. Just compute the direct distance then. } - if (paths.size() > 100) + if (paths_.size() > 100) { /* If we have many paths to optimize the order for, this combing calculation can become very expensive. Instead, penalize travels @@ -847,17 +845,17 @@ class PathOrderOptimizer return getDirectDistance(a, b) * 5; } - if (combing_grid == nullptr) + if (combing_grid_ == nullptr) { constexpr coord_t grid_size = 2000; // 2mm grid cells. Smaller will use more memory, but reduce chance of unnecessary collision checks. - combing_grid = PolygonUtils::createLocToLineGrid(*combing_boundary, grid_size); + combing_grid_ = PolygonUtils::createLocToLineGrid(*combing_boundary_, grid_size); } CombPath comb_path; // Output variable. constexpr coord_t rounding_error = -25; constexpr coord_t tiny_travel_threshold = 0; constexpr bool fail_on_unavoidable_obstacles = false; - LinePolygonsCrossings::comb(*combing_boundary, *combing_grid, a, b, comb_path, rounding_error, tiny_travel_threshold, fail_on_unavoidable_obstacles); + LinePolygonsCrossings::comb(*combing_boundary_, *combing_grid_, a, b, comb_path, rounding_error, tiny_travel_threshold, fail_on_unavoidable_obstacles); coord_t sum = 0; Point last_point = a; @@ -885,12 +883,12 @@ class PathOrderOptimizer { return false; } - return vSize2(path.converted_->back() - path.converted_->front()) < coincident_point_distance * coincident_point_distance; + return vSize2(path.converted_->back() - path.converted_->front()) < _coincident_point_distance * _coincident_point_distance; } }; template -const std::unordered_multimap PathOrderOptimizer::no_order_requirements; +const std::unordered_multimap PathOrderOptimizer::no_order_requirements_; } // namespace cura diff --git a/include/utils/views/dfs.h b/include/utils/views/dfs.h index 0d509b8004..3a64e8c8d8 100644 --- a/include/utils/views/dfs.h +++ b/include/utils/views/dfs.h @@ -36,17 +36,17 @@ std::function(const Node, const Graph&)> get_neighbours = [](c } return neighbours; }; -}; +} template -constexpr void dfs( - const Node& current_node, - const Graph& graph, - std::function handle_node, - std::unordered_set& visited, - const State& state = nullptr, - std::function(const Node, const Graph&)> get_neighbours = details::get_neighbours -) { +constexpr void + dfs(const Node& current_node, + const Graph& graph, + std::function handle_node, + std::unordered_set& visited, + const State& state = nullptr, + std::function(const Node, const Graph&)> get_neighbours = details::get_neighbours) +{ if (visited.contains(current_node)) { return; @@ -64,10 +64,10 @@ constexpr void dfs( template constexpr void dfs_parent_state(const Node& current_node, const Graph& graph, std::function handle_node) { - const std::function parent_view = [handle_node](auto current_node, auto parent_node) + const std::function parent_view = [handle_node](auto node, auto parent_node) { - handle_node(current_node, parent_node); - return current_node; + handle_node(node, parent_node); + return node; }; auto visited = std::unordered_set(); @@ -77,9 +77,9 @@ constexpr void dfs_parent_state(const Node& current_node, const Graph& graph, st template constexpr void dfs_depth_state(const Node& current_node, const Graph& graph, std::function handle_node) { - const std::function depth_view = [handle_node](auto current_node, auto depth) + const std::function depth_view = [handle_node](auto node, auto depth) { - handle_node(current_node, depth); + handle_node(node, depth); return depth + 1; }; auto visited = std::unordered_set(); diff --git a/src/FffGcodeWriter.cpp b/src/FffGcodeWriter.cpp index 1167cc0168..406b365eab 100644 --- a/src/FffGcodeWriter.cpp +++ b/src/FffGcodeWriter.cpp @@ -1560,7 +1560,7 @@ void FffGcodeWriter::addMeshLayerToGCode( part_order_optimizer.addPolygon(&part); } part_order_optimizer.optimize(false); - for (const PathOrdering& path : part_order_optimizer.paths) + for (const PathOrdering& path : part_order_optimizer.paths_) { addMeshPartToGCode(storage, mesh, extruder_nr, mesh_config, *path.vertices_, gcode_layer); } @@ -2640,7 +2640,7 @@ bool FffGcodeWriter::processSkin( } part_order_optimizer.optimize(); - for (const PathOrdering& path : part_order_optimizer.paths) + for (const PathOrdering& path : part_order_optimizer.paths_) { const SkinPart& skin_part = *path.vertices_; @@ -3231,7 +3231,7 @@ bool FffGcodeWriter::processSupportInfill(const SliceDataStorage& storage, Layer bool need_travel_to_end_of_last_spiral = true; // Print the thicker infill lines first. (double or more layer thickness, infill combined with previous layers) - for (const PathOrdering& path : ranges::views::concat(island_order_optimizer_initial.paths, island_order_optimizer.paths)) + for (const PathOrdering& path : ranges::views::concat(island_order_optimizer_initial.paths_, island_order_optimizer.paths_)) { const SupportInfillPart& part = *path.vertices_; const auto& configs = part.use_fractional_config ? gcode_layer.configs_storage.support_fractional_infill_config : gcode_layer.configs_storage.support_infill_config; diff --git a/src/InsetOrderOptimizer.cpp b/src/InsetOrderOptimizer.cpp index 62d9382e62..7549ae53da 100644 --- a/src/InsetOrderOptimizer.cpp +++ b/src/InsetOrderOptimizer.cpp @@ -113,7 +113,7 @@ bool InsetOrderOptimizer::addToLayer() order_optimizer.optimize(); - for (const PathOrdering& path : order_optimizer.paths) + for (const PathOrdering& path : order_optimizer.paths_) { if (path.vertices_->empty()) continue; diff --git a/src/LayerPlan.cpp b/src/LayerPlan.cpp index 7774241e5d..a9ff85c5e6 100644 --- a/src/LayerPlan.cpp +++ b/src/LayerPlan.cpp @@ -608,16 +608,16 @@ void LayerPlan::addPolygonsByOptimizer( if (! reverse_order) { - for (const PathOrdering& path : orderOptimizer.paths) + for (const PathOrdering& path : orderOptimizer.paths_) { addPolygon(*path.vertices_, path.start_vertex_, path.backwards_, config, wall_0_wipe_dist, spiralize, flow_ratio, always_retract); } } else { - for (int index = orderOptimizer.paths.size() - 1; index >= 0; --index) + for (int index = orderOptimizer.paths_.size() - 1; index >= 0; --index) { - const PathOrdering& path = orderOptimizer.paths[index]; + const PathOrdering& path = orderOptimizer.paths_[index]; addPolygon(**path.vertices_, path.start_vertex_, path.backwards_, config, wall_0_wipe_dist, spiralize, flow_ratio, always_retract); } } @@ -1164,7 +1164,7 @@ void LayerPlan::addWalls( orderOptimizer.addPolygon(walls[poly_idx]); } orderOptimizer.optimize(); - for (const PathOrdering& path : orderOptimizer.paths) + for (const PathOrdering& path : orderOptimizer.paths_) { addWall(**path.vertices_, path.start_vertex_, settings, non_bridge_config, bridge_config, wall_0_wipe_dist, flow_ratio, always_retract); } @@ -1219,7 +1219,7 @@ void LayerPlan::addLinesByOptimizer( } order_optimizer.optimize(); - addLinesInGivenOrder(order_optimizer.paths, config, space_fill_type, wipe_dist, flow_ratio, fan_speed); + addLinesInGivenOrder(order_optimizer.paths_, config, space_fill_type, wipe_dist, flow_ratio, fan_speed); } @@ -1359,11 +1359,11 @@ void LayerPlan::addLinesMonotonic( PathOrderMonotonic order(monotonic_direction, max_adjacent_distance, last_position); Polygons left_over; bool last_would_have_been_excluded = false; - for (size_t line_idx = 0; line_idx < line_order.paths.size(); ++line_idx) + for (size_t line_idx = 0; line_idx < line_order.paths_.size(); ++line_idx) { - const ConstPolygonRef polyline = *line_order.paths[line_idx].vertices_; + const ConstPolygonRef polyline = *line_order.paths_[line_idx].vertices_; const bool inside_exclusion = is_inside_exclusion(polyline); - const bool next_would_have_been_included = inside_exclusion && (line_idx < line_order.paths.size() - 1 && is_inside_exclusion(*line_order.paths[line_idx + 1].vertices_)); + const bool next_would_have_been_included = inside_exclusion && (line_idx < line_order.paths_.size() - 1 && is_inside_exclusion(*line_order.paths_[line_idx + 1].vertices_)); if (inside_exclusion && last_would_have_been_excluded && next_would_have_been_included) { left_over.add(polyline); From f40e6c31d4d009529ed5b70770ea9354138effa2 Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Tue, 21 Nov 2023 11:06:33 +0100 Subject: [PATCH 12/48] Fixed variable shadowing warnings --- include/InterlockingGenerator.h | 46 +-- include/LayerPlanBuffer.h | 19 +- include/infill.h | 270 ++++++++--------- include/infill/ZigzagConnectorProcessor.h | 108 +++---- src/InterlockingGenerator.cpp | 72 ++--- src/LayerPlanBuffer.cpp | 68 ++--- src/infill.cpp | 342 +++++++++++----------- src/infill/ZigzagConnectorProcessor.cpp | 54 ++-- 8 files changed, 493 insertions(+), 486 deletions(-) diff --git a/include/InterlockingGenerator.h b/include/InterlockingGenerator.h index 4f780f3fd5..5ff35fd9fc 100644 --- a/include/InterlockingGenerator.h +++ b/include/InterlockingGenerator.h @@ -74,17 +74,17 @@ class InterlockingGenerator * \param air_filtering Whether to fully remove all of the interlocking cells which would be visible on the outside (i.e. touching air). If no air filtering then those cells will be cut off in the middle of a beam. */ InterlockingGenerator(Slicer& mesh_a, Slicer& mesh_b, coord_t beam_width_a, coord_t beam_width_b, const PointMatrix& rotation, Point3 cell_size, coord_t beam_layer_count, DilationKernel interface_dilation, DilationKernel air_dilation, bool air_filtering) - : mesh_a(mesh_a) - , mesh_b(mesh_b) - , beam_width_a(beam_width_a) - , beam_width_b(beam_width_b) - , vu(cell_size) - , rotation(rotation) - , cell_size(cell_size) - , beam_layer_count(beam_layer_count) - , interface_dilation(interface_dilation) - , air_dilation(air_dilation) - , air_filtering(air_filtering) + : mesh_a_(mesh_a) + , mesh_b_(mesh_b) + , beam_width_a_(beam_width_a) + , beam_width_b_(beam_width_b) + , vu_(cell_size) + , rotation_(rotation) + , cell_size_(cell_size) + , beam_layer_count_(beam_layer_count) + , interface_dilation_(interface_dilation) + , air_dilation_(air_dilation) + , air_filtering_(air_filtering) {} /*! Given two polygons, return the parts that border on air, and grow 'perpendicular' up to 'detect' distance. @@ -144,21 +144,21 @@ class InterlockingGenerator */ void applyMicrostructureToOutlines(const std::unordered_set& cells, const std::vector& layer_regions) const; - static const coord_t ignored_gap = 100u; //!< Distance between models to be considered next to each other so that an interlocking structure will be generated there + static const coord_t ignored_gap_ = 100u; //!< Distance between models to be considered next to each other so that an interlocking structure will be generated there - Slicer& mesh_a; - Slicer& mesh_b; - coord_t beam_width_a; - coord_t beam_width_b; + Slicer& mesh_a_; + Slicer& mesh_b_; + coord_t beam_width_a_; + coord_t beam_width_b_; - const VoxelUtils vu; + const VoxelUtils vu_; - const PointMatrix rotation; - const Point3 cell_size; - const coord_t beam_layer_count; - const DilationKernel interface_dilation; - const DilationKernel air_dilation; - const bool air_filtering; //!< Whether to fully remove all of the interlocking cells which would be visible on the outside. If no air filtering then those cells will be cut off midway in a beam. + const PointMatrix rotation_; + const Point3 cell_size_; + const coord_t beam_layer_count_; + const DilationKernel interface_dilation_; + const DilationKernel air_dilation_; + const bool air_filtering_; //!< Whether to fully remove all of the interlocking cells which would be visible on the outside. If no air filtering then those cells will be cut off midway in a beam. }; }//namespace cura diff --git a/include/LayerPlanBuffer.h b/include/LayerPlanBuffer.h index 2b1ce8cefc..14a97219a6 100644 --- a/include/LayerPlanBuffer.h +++ b/include/LayerPlanBuffer.h @@ -36,19 +36,20 @@ class GCodeExport; class LayerPlanBuffer { friend class LayerPlan; - GCodeExport& gcode; - Preheat preheat_config; //!< the nozzle and material temperature settings for each extruder train. + GCodeExport& gcode_; - static constexpr size_t buffer_size + Preheat preheat_config_; //!< the nozzle and material temperature settings for each extruder train. + + static constexpr size_t buffer_size_ = 5; // should be as low as possible while still allowing enough time in the buffer to heat up from standby temp to printing temp // TODO: hardcoded value // this value should be higher than 1, cause otherwise each layer is viewed as the first layer and no temp commands are inserted. - static constexpr Duration extra_preheat_time + static constexpr Duration extra_preheat_time_ = 1.0_s; //!< Time to start heating earlier than computed to avoid accummulative discrepancy between actual heating times and computed ones. - std::vector extruder_used_in_meshgroup; //!< For each extruder whether it has already been planned once in this meshgroup. This is used to see whether we should heat to - //!< the initial_print_temp or to the extrusion_temperature + std::vector extruder_used_in_meshgroup_; //!< For each extruder whether it has already been planned once in this meshgroup. This is used to see whether we should heat to + //!< the initial_print_temp or to the extrusion_temperature /*! * The buffer containing several layer plans (LayerPlan) before writing them to gcode. @@ -56,12 +57,12 @@ class LayerPlanBuffer * The front is the lowest/oldest layer. * The back is the highest/newest layer. */ - std::list buffer; + std::list buffer_; public: LayerPlanBuffer(GCodeExport& gcode) - : gcode(gcode) - , extruder_used_in_meshgroup(MAX_EXTRUDERS, false) + : gcode_(gcode) + , extruder_used_in_meshgroup_(MAX_EXTRUDERS, false) { } diff --git a/include/infill.h b/include/infill.h index 289a0850bb..d8d2f83768 100644 --- a/include/infill.h +++ b/include/infill.h @@ -4,6 +4,10 @@ #ifndef INFILL_H #define INFILL_H +#include + +#include + #include "infill/LightningGenerator.h" #include "infill/ZigzagConnectorProcessor.h" #include "settings/EnumSettings.h" //For infill types. @@ -14,10 +18,6 @@ #include "utils/IntPoint.h" #include "utils/section_type.h" -#include - -#include - namespace cura { @@ -28,35 +28,35 @@ class Infill { friend class InfillTest; - EFillMethod pattern{}; //!< the space filling pattern of the infill to generate - bool zig_zaggify{}; //!< Whether to connect the end pieces of the support lines via the wall - bool connect_lines{ calcConnectLines(pattern, zig_zaggify) }; //!< Whether the lines and zig_zaggification are generated by the connectLines algorithm + EFillMethod pattern_{}; //!< the space filling pattern of the infill to generate + bool zig_zaggify_{}; //!< Whether to connect the end pieces of the support lines via the wall + bool connect_lines_{ calcConnectLines(pattern_, zig_zaggify_) }; //!< Whether the lines and zig_zaggification are generated by the connectLines algorithm // TODO: The connected lines algorithm is only available for linear-based infill, for now. // We skip ZigZag, Cross and Cross3D because they have their own algorithms. Eventually we want to replace all that with the new algorithm. // Cubic Subdivision ends lines in the center of the infill so it won't be effective. - bool connect_polygons{}; //!< Whether to connect as much polygons together into a single path - Polygons outer_contour{}; //!< The area that originally needs to be filled with infill. The input of the algorithm. - Polygons inner_contour{}; //!< The part of the contour that will get filled with an infill pattern. Equals outer_contour minus the extra infill walls. - coord_t infill_line_width{}; //!< The line width of the infill lines to generate - coord_t line_distance{}; //!< The distance between two infill lines / polygons - coord_t infill_overlap{}; //!< the distance by which to overlap with the actual area within which to generate infill - size_t infill_multiplier{}; //!< the number of infill lines next to each other - AngleDegrees fill_angle{}; //!< for linear infill types: the angle of the infill lines (or the angle of the grid) - coord_t z{}; //!< height of the layer for which we generate infill - coord_t shift{}; //!< shift of the scanlines in the direction perpendicular to the fill_angle - coord_t max_resolution{}; //!< Min feature size of the output - coord_t max_deviation{}; //!< Max deviation fro the original poly when enforcing max_resolution - size_t wall_line_count{}; //!< Number of walls to generate at the boundary of the infill region, spaced \ref infill_line_width apart - coord_t small_area_width{}; //!< Maximum width of a small infill region to be filled with walls - Point infill_origin{}; //!< origin of the infill pattern - bool skip_line_stitching{ false }; //!< Whether to bypass the line stitching normally performed for polyline type infills - bool fill_gaps{ true }; //!< Whether to fill gaps in strips of infill that would be too thin to fit the infill lines. If disabled, those areas are left empty. - bool connected_zigzags{ false }; //!< (ZigZag) Whether endpieces of zigzag infill should be connected to the nearest infill line on both sides of the zigzag connector - bool use_endpieces{ false }; //!< (ZigZag) Whether to include endpieces: zigzag connector segments from one infill line to itself - bool skip_some_zags{ false }; //!< (ZigZag) Whether to skip some zags - size_t zag_skip_count{}; //!< (ZigZag) To skip one zag in every N if skip some zags is enabled - coord_t pocket_size{}; //!< The size of the pockets at the intersections of the fractal in the cross 3d pattern - bool mirror_offset{}; //!< Indication in which offset direction the extra infill lines are made + bool connect_polygons_{}; //!< Whether to connect as much polygons together into a single path + Polygons outer_contour_{}; //!< The area that originally needs to be filled with infill. The input of the algorithm. + Polygons inner_contour_{}; //!< The part of the contour that will get filled with an infill pattern. Equals outer_contour minus the extra infill walls. + coord_t infill_line_width_{}; //!< The line width of the infill lines to generate + coord_t line_distance_{}; //!< The distance between two infill lines / polygons + coord_t infill_overlap_{}; //!< the distance by which to overlap with the actual area within which to generate infill + size_t infill_multiplier_{}; //!< the number of infill lines next to each other + AngleDegrees fill_angle_{}; //!< for linear infill types: the angle of the infill lines (or the angle of the grid) + coord_t z_{}; //!< height of the layer for which we generate infill + coord_t shift_{}; //!< shift of the scanlines in the direction perpendicular to the fill_angle + coord_t max_resolution_{}; //!< Min feature size of the output + coord_t max_deviation_{}; //!< Max deviation fro the original poly when enforcing max_resolution + size_t wall_line_count_{}; //!< Number of walls to generate at the boundary of the infill region, spaced \ref infill_line_width apart + coord_t small_area_width_{}; //!< Maximum width of a small infill region to be filled with walls + Point infill_origin_{}; //!< origin of the infill pattern + bool skip_line_stitching_{ false }; //!< Whether to bypass the line stitching normally performed for polyline type infills + bool fill_gaps_{ true }; //!< Whether to fill gaps in strips of infill that would be too thin to fit the infill lines. If disabled, those areas are left empty. + bool connected_zigzags_{ false }; //!< (ZigZag) Whether endpieces of zigzag infill should be connected to the nearest infill line on both sides of the zigzag connector + bool use_endpieces_{ false }; //!< (ZigZag) Whether to include endpieces: zigzag connector segments from one infill line to itself + bool skip_some_zags_{ false }; //!< (ZigZag) Whether to skip some zags + size_t zag_skip_count_{}; //!< (ZigZag) To skip one zag in every N if skip some zags is enabled + coord_t pocket_size_{}; //!< The size of the pockets at the intersections of the fractal in the cross 3d pattern + bool mirror_offset_{}; //!< Indication in which offset direction the extra infill lines are made static constexpr auto one_over_sqrt_2 = 1.0 / std::numbers::sqrt2; @@ -84,19 +84,21 @@ class Infill coord_t shift, coord_t max_resolution, coord_t max_deviation) noexcept - : pattern{ pattern } - , zig_zaggify{ zig_zaggify } - , connect_polygons{ connect_polygons } - , outer_contour{ in_outline } - , infill_line_width{ infill_line_width } - , line_distance{ line_distance } - , infill_overlap{ infill_overlap } - , infill_multiplier{ infill_multiplier } - , fill_angle{ fill_angle } - , z{ z } - , shift{ shift } - , max_resolution{ max_resolution } - , max_deviation{ max_deviation } {}; + : pattern_{ pattern } + , zig_zaggify_{ zig_zaggify } + , connect_polygons_{ connect_polygons } + , outer_contour_{ in_outline } + , infill_line_width_{ infill_line_width } + , line_distance_{ line_distance } + , infill_overlap_{ infill_overlap } + , infill_multiplier_{ infill_multiplier } + , fill_angle_{ fill_angle } + , z_{ z } + , shift_{ shift } + , max_resolution_{ max_resolution } + , max_deviation_{ max_deviation } + { + } Infill( EFillMethod pattern, @@ -116,23 +118,25 @@ class Infill coord_t small_area_width, Point infill_origin, bool skip_line_stitching) noexcept - : pattern{ pattern } - , zig_zaggify{ zig_zaggify } - , connect_polygons{ connect_polygons } - , outer_contour{ in_outline } - , infill_line_width{ infill_line_width } - , line_distance{ line_distance } - , infill_overlap{ infill_overlap } - , infill_multiplier{ infill_multiplier } - , fill_angle{ fill_angle } - , z{ z } - , shift{ shift } - , max_resolution{ max_resolution } - , max_deviation{ max_deviation } - , wall_line_count{ wall_line_count } - , small_area_width{ small_area_width } - , infill_origin{ infill_origin } - , skip_line_stitching{ skip_line_stitching } {}; + : pattern_{ pattern } + , zig_zaggify_{ zig_zaggify } + , connect_polygons_{ connect_polygons } + , outer_contour_{ in_outline } + , infill_line_width_{ infill_line_width } + , line_distance_{ line_distance } + , infill_overlap_{ infill_overlap } + , infill_multiplier_{ infill_multiplier } + , fill_angle_{ fill_angle } + , z_{ z } + , shift_{ shift } + , max_resolution_{ max_resolution } + , max_deviation_{ max_deviation } + , wall_line_count_{ wall_line_count } + , small_area_width_{ small_area_width } + , infill_origin_{ infill_origin } + , skip_line_stitching_{ skip_line_stitching } + { + } Infill( EFillMethod pattern, @@ -158,30 +162,30 @@ class Infill bool skip_some_zags, size_t zag_skip_count, coord_t pocket_size) noexcept - : pattern{ pattern } - , zig_zaggify{ zig_zaggify } - , connect_polygons{ connect_polygons } - , outer_contour{ in_outline } - , infill_line_width{ infill_line_width } - , line_distance{ line_distance } - , infill_overlap{ infill_overlap } - , infill_multiplier{ infill_multiplier } - , fill_angle{ fill_angle } - , z{ z } - , shift{ shift } - , max_resolution{ max_resolution } - , max_deviation{ max_deviation } - , wall_line_count{ wall_line_count } - , small_area_width{ small_area_width } - , infill_origin{ infill_origin } - , skip_line_stitching{ skip_line_stitching } - , fill_gaps{ fill_gaps } - , connected_zigzags{ connected_zigzags } - , use_endpieces{ use_endpieces } - , skip_some_zags{ skip_some_zags } - , zag_skip_count{ zag_skip_count } - , pocket_size{ pocket_size } - , mirror_offset{ zig_zaggify } + : pattern_{ pattern } + , zig_zaggify_{ zig_zaggify } + , connect_polygons_{ connect_polygons } + , outer_contour_{ in_outline } + , infill_line_width_{ infill_line_width } + , line_distance_{ line_distance } + , infill_overlap_{ infill_overlap } + , infill_multiplier_{ infill_multiplier } + , fill_angle_{ fill_angle } + , z_{ z } + , shift_{ shift } + , max_resolution_{ max_resolution } + , max_deviation_{ max_deviation } + , wall_line_count_{ wall_line_count } + , small_area_width_{ small_area_width } + , infill_origin_{ infill_origin } + , skip_line_stitching_{ skip_line_stitching } + , fill_gaps_{ fill_gaps } + , connected_zigzags_{ connected_zigzags } + , use_endpieces_{ use_endpieces } + , skip_some_zags_{ skip_some_zags } + , zag_skip_count_{ zag_skip_count } + , pocket_size_{ pocket_size } + , mirror_offset_{ zig_zaggify } { } @@ -231,31 +235,6 @@ class Infill SectionType section_type); private: - /*! - * Generate the infill pattern without the infill_multiplier functionality - */ - void _generate( - std::vector& toolpaths, - Polygons& result_polygons, - Polygons& result_lines, - const Settings& settings, - const std::shared_ptr& cross_fill_pattern = nullptr, - const std::shared_ptr& lightning_layer = nullptr, - const SliceMeshStorage* mesh = nullptr); - - /*! - * Multiply the infill lines, so that any single line becomes [infill_multiplier] lines next to each other. - * - * This is done in a way such that there is not overlap between the lines - * except the middle original one if the multiplier is odd. - * - * This introduces a lot of line segments. - * - * \param[in,out] result_polygons The polygons to be multiplied (input and output) - * \param[in,out] result_lines The lines to be multiplied (input and output) - */ - void multiplyInfill(Polygons& result_polygons, Polygons& result_lines); - struct InfillLineSegment { /*! @@ -267,28 +246,30 @@ class Infill * \param end Where the line segment ends. */ InfillLineSegment(const Point start, const size_t start_segment, const size_t start_polygon, const Point end, const size_t end_segment, const size_t end_polygon) - : start(start) - , altered_start(start) - , start_segment(start_segment) - , start_polygon(start_polygon) - , end(end) - , altered_end(end) - , end_segment(end_segment) - , end_polygon(end_polygon) - , previous(nullptr) - , next(nullptr){}; + : start_(start) + , altered_start_(start) + , start_segment_(start_segment) + , start_polygon_(start_polygon) + , end_(end) + , altered_end_(end) + , end_segment_(end_segment) + , end_polygon_(end_polygon) + , previous_(nullptr) + , next_(nullptr) + { + } /*! * Where the line segment starts. */ - Point start; + Point start_; /*! * If the line-segment starts at a different point due to prevention of crossing near the boundary, it gets saved here. * * The original start-point is still used to determine ordering then, so it can't just be overwritten. */ - Point altered_start; + Point altered_start_; /*! * Which polygon line segment the start of this infill line belongs to. @@ -297,7 +278,7 @@ class Infill * is inside. It is used to disambiguate between the start and end of * the line segment. */ - size_t start_segment; + size_t start_segment_; /*! * Which polygon the start of this infill line belongs to. @@ -305,24 +286,24 @@ class Infill * This is an index of a PolygonRef that this infill line * is inside. It is used to know which polygon the start segment belongs to. */ - size_t start_polygon; + size_t start_polygon_; /*! * If the line-segment needs to prevent crossing with another line near its start, a point is inserted near the start. */ - std::optional start_bend; + std::optional start_bend_; /*! * Where the line segment ends. */ - Point end; + Point end_; /*! * If the line-segment ends at a different point due to prevention of crossing near the boundary, it gets saved here. * * The original end-point is still used to determine ordering then, so it can't just be overwritten. */ - Point altered_end; + Point altered_end_; /*! * Which polygon line segment the end of this infill line belongs to. @@ -331,7 +312,7 @@ class Infill * is inside. It is used to disambiguate between the start and end of * the line segment. */ - size_t end_segment; + size_t end_segment_; /*! * Which polygon the end of this infill line belongs to. @@ -339,23 +320,23 @@ class Infill * This is an index of a PolygonRef that this infill line * is inside. It is used to know which polygon the end segment belongs to. */ - size_t end_polygon; + size_t end_polygon_; /*! * If the line-segment needs to prevent crossing with another line near its end, a point is inserted near the end. */ - std::optional end_bend; + std::optional end_bend_; /*! * The previous line segment that this line segment is connected to, if * any. */ - InfillLineSegment* previous; + InfillLineSegment* previous_; /*! * The next line segment that this line segment is connected to, if any. */ - InfillLineSegment* next; + InfillLineSegment* next_; /*! * Compares two infill line segments for equality. @@ -385,7 +366,32 @@ class Infill * for each polygon in a Polygons object that we create a zig-zaggified * infill pattern for. */ - std::vector>> crossings_on_line; + std::vector>> crossings_on_line_; + + /*! + * Generate the infill pattern without the infill_multiplier functionality + */ + void _generate( + std::vector& toolpaths, + Polygons& result_polygons, + Polygons& result_lines, + const Settings& settings, + const std::shared_ptr& cross_fill_pattern = nullptr, + const std::shared_ptr& lightning_layer = nullptr, + const SliceMeshStorage* mesh = nullptr); + + /*! + * Multiply the infill lines, so that any single line becomes [infill_multiplier] lines next to each other. + * + * This is done in a way such that there is not overlap between the lines + * except the middle original one if the multiplier is odd. + * + * This introduces a lot of line segments. + * + * \param[in,out] result_polygons The polygons to be multiplied (input and output) + * \param[in,out] result_lines The lines to be multiplied (input and output) + */ + void multiplyInfill(Polygons& result_polygons, Polygons& result_lines); /*! * Generate gyroid infill diff --git a/include/infill/ZigzagConnectorProcessor.h b/include/infill/ZigzagConnectorProcessor.h index 7da5c2e043..46761af97a 100644 --- a/include/infill/ZigzagConnectorProcessor.h +++ b/include/infill/ZigzagConnectorProcessor.h @@ -1,5 +1,5 @@ -//Copyright (c) 2018 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2018 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef INFILL_ZIGZAG_CONNECTOR_PROCESSOR_H #define INFILL_ZIGZAG_CONNECTOR_PROCESSOR_H @@ -11,8 +11,8 @@ namespace cura /*! * Processor class for processing the connections between lines which makes the infill a zigzag pattern. - * - * During the creation of the infill lines, calls are made to a ZigzagConnectorProcessor so that the zigzag connector segments are created + * + * During the creation of the infill lines, calls are made to a ZigzagConnectorProcessor so that the zigzag connector segments are created * at the same time as the lines are created. * * generate lines within the area of [in_outline], at regular intervals of [line_distance] @@ -20,17 +20,17 @@ namespace cura * intersect a regular grid of 'scanlines' with the area inside [in_outline] (see generateLineInfill) * zigzag: * include pieces of boundary, connecting the lines, forming an accordion like zigzag instead of separate lines |_|^|_| - * + * * we call the areas between two consecutive scanlines a 'scansegment' - * + * * algorithm: * 1. for each line segment of each polygon: * store the intersections of that line segment with all scanlines in a mapping (vector of vectors) from scanline to intersections * (zigzag): add boundary segments to result * 2. for each scanline: - * sort the associated intersections + * sort the associated intersections * and connect them using the even-odd rule - * + * * zigzag algorithm: * while walking around (each) polygon (1.) * if polygon intersects with even scanline @@ -39,13 +39,13 @@ namespace cura * stop boundary segment (stop adding segments to the [result]) * if polygon intersects with even scanline again (instead of odd) * dont add the last line segment to the boundary (unless [connected_zigzags]) - * + * * Note that ZigZag consists of 3 types: * - without endpieces * - with disconnected endpieces * - with connected endpieces * <> there is also a NoZigzagConnector which creates no zags. It is used for the Line infill pattern - * + * * v v zigzag connectors * <-- * :___: : < scanlines @@ -54,29 +54,29 @@ namespace cura * | |___| * : : : * --> winding order of polygon - * + * * ^ = even scanline * ^ ^ no endpieces - * + * * start boundary from even scanline! :D * include only a boundary segment if it starts in an even scanline and ends in an odd scanline - * + * * ________ * | | | \ . * | | | | * |_____| |__/ . - * + * * ^ ^ ^ scanlines * ^ connected end piece - * include a boundary segment also if it starts in an odd scanline and ends odd, + * include a boundary segment also if it starts in an odd scanline and ends odd, * or starts in an even scanline and ends in an even scanline, * but not when it starts in an odd and ends in an even scanline (see top left or bottom middle). - * + * * _____ * | | | \ . * | | | | * |_____| |__/ - * + * * ^ ^ ^ scanlines * ^ disconnected end piece * Leave out the last line segment of the boundary polygon: from a vertex to the linesegment-scanline intersection. @@ -95,12 +95,12 @@ namespace cura * the first point (the "from" point) will be kept as the starting point until there is a line that is * long enough, and then that line will be added. */ -class ZigzagConnectorProcessor +class ZigzagConnectorProcessor { public: /*! * Constructor. - * + * * \param rotation_matrix The rotation matrix used to enforce the infill angle * \param result The resulting line segments (Each line segment is a Polygon with 2 points) * \param use_endpieces Whether to include end pieces or not @@ -108,22 +108,22 @@ class ZigzagConnectorProcessor * \param skip_some_zags Whether to skip some zags * \param zag_skip_count Skip 1 zag in every N zags */ - ZigzagConnectorProcessor(const PointMatrix& rotation_matrix, Polygons& result, - bool use_endpieces, bool connected_endpieces, - bool skip_some_zags, int zag_skip_count) - : rotation_matrix(rotation_matrix) - , result(result) - , use_endpieces(use_endpieces) - , connected_endpieces(connected_endpieces) - , skip_some_zags(skip_some_zags) - , zag_skip_count(zag_skip_count) - , is_first_connector(true) - , first_connector_end_scanline_index(0) - , last_connector_index(0) - {} + ZigzagConnectorProcessor(const PointMatrix& rotation_matrix, Polygons& result, bool use_endpieces, bool connected_endpieces, bool skip_some_zags, int zag_skip_count) + : rotation_matrix_(rotation_matrix) + , result_(result) + , use_endpieces_(use_endpieces) + , connected_endpieces_(connected_endpieces) + , skip_some_zags_(skip_some_zags) + , zag_skip_count_(zag_skip_count) + , is_first_connector_(true) + , first_connector_end_scanline_index_(0) + , last_connector_index_(0) + { + } virtual ~ZigzagConnectorProcessor() - {} + { + } /*! * Handle the next vertex on the outer boundary. @@ -133,7 +133,7 @@ class ZigzagConnectorProcessor /*! * Handle the next intersection between a scanline and the outer boundary. - * + * * \param intersection The intersection * \param scanline_index Index of the current scanline */ @@ -153,7 +153,7 @@ class ZigzagConnectorProcessor /*! * Add a line to the result while reverse-applying the rotation matrix. - * + * * \param polyline The polyline to add */ void addPolyline(PolygonRef polyline); @@ -187,17 +187,17 @@ class ZigzagConnectorProcessor void addZagConnector(std::vector& points, bool is_endpiece); protected: - const PointMatrix& rotation_matrix; //!< The rotation matrix used to enforce the infill angle - Polygons& result; //!< The result of the computation + const PointMatrix& rotation_matrix_; //!< The rotation matrix used to enforce the infill angle + Polygons& result_; //!< The result of the computation - bool use_endpieces; //!< Whether to include end pieces or not - bool connected_endpieces; //!< Whether the end pieces should be connected with the rest part of the infill - int skip_some_zags; //!< Whether to skip some zags - int zag_skip_count; //!< Skip 1 zag in every N zags + const bool use_endpieces_; //!< Whether to include end pieces or not + const bool connected_endpieces_; //!< Whether the end pieces should be connected with the rest part of the infill + const int skip_some_zags_; //!< Whether to skip some zags + const int zag_skip_count_; //!< Skip 1 zag in every N zags - bool is_first_connector; //!< indicating whether we are still looking for the first connector or not - int first_connector_end_scanline_index; //!< scanline segment index of the first connector - int last_connector_index; //!< scanline segment index of the last connector + bool is_first_connector_; //!< indicating whether we are still looking for the first connector or not + int first_connector_end_scanline_index_; //!< scanline segment index of the first connector + int last_connector_index_; //!< scanline segment index of the last connector /*! * The line segments belonging the zigzag connector to which the very first vertex belongs. @@ -205,11 +205,11 @@ class ZigzagConnectorProcessor * * Because the boundary polygon may start in in the middle of a zigzag connector, */ - std::vector first_connector; + std::vector first_connector_; /*! * The currently built up zigzag connector (not the first/last) or end piece or discarded boundary segment */ - std::vector current_connector; + std::vector current_connector_; }; // @@ -218,19 +218,19 @@ class ZigzagConnectorProcessor inline void ZigzagConnectorProcessor::reset() { - is_first_connector = true; - first_connector_end_scanline_index = 0; - last_connector_index = 0; - first_connector.clear(); - current_connector.clear(); + is_first_connector_ = true; + first_connector_end_scanline_index_ = 0; + last_connector_index_ = 0; + first_connector_.clear(); + current_connector_.clear(); } inline void ZigzagConnectorProcessor::addPolyline(PolygonRef polyline) { - result.emplace_back(polyline); - for (Point& p : result.back()) + result_.emplace_back(polyline); + for (Point& p : result_.back()) { - p = rotation_matrix.unapply(p); + p = rotation_matrix_.unapply(p); } } diff --git a/src/InterlockingGenerator.cpp b/src/InterlockingGenerator.cpp index 2cafc9b691..fc0c2bc54a 100644 --- a/src/InterlockingGenerator.cpp +++ b/src/InterlockingGenerator.cpp @@ -44,7 +44,7 @@ void InterlockingGenerator::generateInterlockingStructure(std::vector& continue; } - if (extruder_nr_a == extruder_nr_b || ! mesh_a.mesh->getAABB().expand(ignored_gap).hit(mesh_b.mesh->getAABB())) + if (extruder_nr_a == extruder_nr_b || ! mesh_a.mesh->getAABB().expand(ignored_gap_).hit(mesh_b.mesh->getAABB())) { // early out for when meshes don't share any overlap in their bounding box continue; @@ -70,7 +70,7 @@ void InterlockingGenerator::generateInterlockingStructure(std::vector& std::pair InterlockingGenerator::growBorderAreasPerpendicular(const Polygons& a, const Polygons& b, const coord_t& detect) const { - const coord_t min_line = std::min(mesh_a.mesh->settings_.get("min_wall_line_width"), mesh_b.mesh->settings_.get("min_wall_line_width")); + const coord_t min_line = std::min(mesh_a_.mesh->settings_.get("min_wall_line_width"), mesh_b_.mesh->settings_.get("min_wall_line_width")); const Polygons total_shrunk = a.offset(min_line).unionPolygons(b.offset(min_line)).offset(2 * -min_line); @@ -98,30 +98,30 @@ void InterlockingGenerator::handleThinAreas(const std::unordered_set const coord_t number_of_beams_expand = boundary_avoidance - 1; constexpr coord_t rounding_errors = 5; - const coord_t max_beam_width = std::max(beam_width_a, beam_width_b); + const coord_t max_beam_width = std::max(beam_width_a_, beam_width_b_); const coord_t detect = (max_beam_width * number_of_beams_detect) + rounding_errors; const coord_t expand = (max_beam_width * number_of_beams_expand) + rounding_errors; - const coord_t close_gaps = std::min(mesh_a.mesh->settings_.get("line_width"), mesh_b.mesh->settings_.get("line_width")) / 4; + const coord_t close_gaps = std::min(mesh_a_.mesh->settings_.get("line_width"), mesh_b_.mesh->settings_.get("line_width")) / 4; // Make an inclusionary polygon, to only actually handle thin areas near actual microstructures (so not in skin for example). std::vector near_interlock_per_layer; - near_interlock_per_layer.assign(std::min(mesh_a.layers.size(), mesh_b.layers.size()), Polygons()); + near_interlock_per_layer.assign(std::min(mesh_a_.layers.size(), mesh_b_.layers.size()), Polygons()); for (const auto& cell : has_all_meshes) { - const Point3 bottom_corner = vu.toLowerCorner(cell); - for (int layer_nr = bottom_corner.z_; layer_nr < bottom_corner.z_ + cell_size.z_ && layer_nr < near_interlock_per_layer.size(); ++layer_nr) + const Point3 bottom_corner = vu_.toLowerCorner(cell); + for (int layer_nr = bottom_corner.z_; layer_nr < bottom_corner.z_ + cell_size_.z_ && layer_nr < near_interlock_per_layer.size(); ++layer_nr) { - near_interlock_per_layer[layer_nr].add(vu.toPolygon(cell)); + near_interlock_per_layer[layer_nr].add(vu_.toPolygon(cell)); } } for (auto& near_interlock : near_interlock_per_layer) { near_interlock = near_interlock.offset(rounding_errors).offset(-rounding_errors).unionPolygons().offset(detect); - near_interlock.applyMatrix(rotation.inverse()); + near_interlock.applyMatrix(rotation_.inverse()); } // Only alter layers when they are present in both meshes, zip should take care if that. - for (auto [layer_nr, layer] : ranges::views::zip(mesh_a.layers, mesh_b.layers) | ranges::views::enumerate) + for (auto [layer_nr, layer] : ranges::views::zip(mesh_a_.layers, mesh_b_.layers) | ranges::views::enumerate) { Polygons& polys_a = std::get<0>(layer).polygons; Polygons& polys_b = std::get<1>(layer).polygons; @@ -149,7 +149,7 @@ void InterlockingGenerator::handleThinAreas(const std::unordered_set void InterlockingGenerator::generateInterlockingStructure() const { - std::vector> voxels_per_mesh = getShellVoxels(interface_dilation); + std::vector> voxels_per_mesh = getShellVoxels(interface_dilation_); std::unordered_set& has_any_mesh = voxels_per_mesh[0]; std::unordered_set& has_all_meshes = voxels_per_mesh[1]; @@ -157,10 +157,10 @@ void InterlockingGenerator::generateInterlockingStructure() const const std::vector layer_regions = computeUnionedVolumeRegions(); - if (air_filtering) + if (air_filtering_) { std::unordered_set air_cells; - addBoundaryCells(layer_regions, air_dilation, air_cells); + addBoundaryCells(layer_regions, air_dilation_, air_cells); for (const GridPoint3& p : air_cells) { @@ -180,7 +180,7 @@ std::vector> InterlockingGenerator::getShellVoxel // mark all cells which contain some boundary for (size_t mesh_idx = 0; mesh_idx < 2; mesh_idx++) { - Slicer* mesh = (mesh_idx == 0) ? &mesh_a : &mesh_b; + Slicer* mesh = (mesh_idx == 0) ? &mesh_a_ : &mesh_b_; std::unordered_set& mesh_voxels = voxels_per_mesh[mesh_idx]; std::vector rotated_polygons_per_layer(mesh->layers.size()); @@ -188,7 +188,7 @@ std::vector> InterlockingGenerator::getShellVoxel { SlicerLayer& layer = mesh->layers[layer_nr]; rotated_polygons_per_layer[layer_nr] = layer.polygons; - rotated_polygons_per_layer[layer_nr].applyMatrix(rotation); + rotated_polygons_per_layer[layer_nr].applyMatrix(rotation_); } addBoundaryCells(rotated_polygons_per_layer, kernel, mesh_voxels); @@ -208,26 +208,26 @@ void InterlockingGenerator::addBoundaryCells(const std::vector& layers for (size_t layer_nr = 0; layer_nr < layers.size(); layer_nr++) { const coord_t z = layer_nr; - vu.walkDilatedPolygons(layers[layer_nr], z, kernel, voxel_emplacer); + vu_.walkDilatedPolygons(layers[layer_nr], z, kernel, voxel_emplacer); Polygons skin = layers[layer_nr]; if (layer_nr > 0) { skin = skin.xorPolygons(layers[layer_nr - 1]); } - skin = skin.offset(-cell_size.x_ / 2).offset(cell_size.x_ / 2); // remove superfluous small areas, which would anyway be included because of walkPolygons - vu.walkDilatedAreas(skin, z, kernel, voxel_emplacer); + skin = skin.offset(-cell_size_.x_ / 2).offset(cell_size_.x_ / 2); // remove superfluous small areas, which would anyway be included because of walkPolygons + vu_.walkDilatedAreas(skin, z, kernel, voxel_emplacer); } } std::vector InterlockingGenerator::computeUnionedVolumeRegions() const { - const size_t max_layer_count = std::max(mesh_a.layers.size(), mesh_b.layers.size()) + 1; // introduce ghost layer on top for correct skin computation of topmost layer. + const size_t max_layer_count = std::max(mesh_a_.layers.size(), mesh_b_.layers.size()) + 1; // introduce ghost layer on top for correct skin computation of topmost layer. std::vector layer_regions(max_layer_count); for (LayerIndex layer_nr = 0; layer_nr < max_layer_count; layer_nr++) { Polygons& layer_region = layer_regions[layer_nr]; - for (Slicer* mesh : { &mesh_a, &mesh_b }) + for (Slicer* mesh : { &mesh_a_, &mesh_b_ }) { if (layer_nr >= mesh->layers.size()) { @@ -236,8 +236,8 @@ std::vector InterlockingGenerator::computeUnionedVolumeRegions() const const SlicerLayer& layer = mesh->layers[layer_nr]; layer_region.add(layer.polygons); } - layer_region = layer_region.offset(ignored_gap).offset(-ignored_gap); // Morphological close to merge meshes into single volume - layer_region.applyMatrix(rotation); + layer_region = layer_region.offset(ignored_gap_).offset(-ignored_gap_); // Morphological close to merge meshes into single volume + layer_region.applyMatrix(rotation_); } return layer_regions; } @@ -247,13 +247,13 @@ std::vector> InterlockingGenerator::generateMicrostructure std::vector> cell_area_per_mesh_per_layer; cell_area_per_mesh_per_layer.resize(2); cell_area_per_mesh_per_layer[0].resize(2); - const coord_t beam_w_sum = beam_width_a + beam_width_b; - const coord_t middle = cell_size.x_ * beam_width_a / beam_w_sum; - const coord_t width[2] = { middle, cell_size.x_ - middle }; + const coord_t beam_w_sum = beam_width_a_ + beam_width_b_; + const coord_t middle = cell_size_.x_ * beam_width_a_ / beam_w_sum; + const coord_t width[2] = { middle, cell_size_.x_ - middle }; for (size_t mesh_idx : { 0, 1 }) { Point offset(mesh_idx ? middle : 0, 0); - Point area_size(width[mesh_idx], cell_size.y_); + Point area_size(width[mesh_idx], cell_size_.y_); PolygonRef poly = cell_area_per_mesh_per_layer[0][mesh_idx].newPoly(); poly.emplace_back(offset); @@ -279,29 +279,29 @@ void InterlockingGenerator::applyMicrostructureToOutlines(const std::unordered_s { std::vector> cell_area_per_mesh_per_layer = generateMicrostructure(); - const PointMatrix unapply_rotation = rotation.inverse(); - const size_t max_layer_count = std::max(mesh_a.layers.size(), mesh_b.layers.size()); + const PointMatrix unapply_rotation = rotation_.inverse(); + const size_t max_layer_count = std::max(mesh_a_.layers.size(), mesh_b_.layers.size()); std::vector structure_per_layer[2]; // for each mesh the structure on each layer // Every `beam_layer_count` number of layers are combined to an interlocking beam layer // to store these we need ceil(max_layer_count / beam_layer_count) of these layers // the formula is rewritten as (max_layer_count + beam_layer_count - 1) / beam_layer_count, so it works for integer division - size_t num_interlocking_layers = (max_layer_count + beam_layer_count - 1) / beam_layer_count; + size_t num_interlocking_layers = (max_layer_count + beam_layer_count_ - 1) / beam_layer_count_; structure_per_layer[0].resize(num_interlocking_layers); structure_per_layer[1].resize(num_interlocking_layers); // Only compute cell structure for half the layers, because since our beams are two layers high, every odd layer of the structure will be the same as the layer below. for (const GridPoint3& grid_loc : cells) { - Point3 bottom_corner = vu.toLowerCorner(grid_loc); + Point3 bottom_corner = vu_.toLowerCorner(grid_loc); for (size_t mesh_idx = 0; mesh_idx < 2; mesh_idx++) { - for (LayerIndex layer_nr = bottom_corner.z_; layer_nr < bottom_corner.z_ + cell_size.z_ && layer_nr < max_layer_count; layer_nr += beam_layer_count) + for (LayerIndex layer_nr = bottom_corner.z_; layer_nr < bottom_corner.z_ + cell_size_.z_ && layer_nr < max_layer_count; layer_nr += beam_layer_count_) { - Polygons areas_here = cell_area_per_mesh_per_layer[(layer_nr / beam_layer_count) % cell_area_per_mesh_per_layer.size()][mesh_idx]; + Polygons areas_here = cell_area_per_mesh_per_layer[(layer_nr / beam_layer_count_) % cell_area_per_mesh_per_layer.size()][mesh_idx]; areas_here.translate(Point(bottom_corner.x_, bottom_corner.y_)); - structure_per_layer[mesh_idx][layer_nr / beam_layer_count].add(areas_here); + structure_per_layer[mesh_idx][layer_nr / beam_layer_count_].add(areas_here); } } } @@ -318,7 +318,7 @@ void InterlockingGenerator::applyMicrostructureToOutlines(const std::unordered_s for (size_t mesh_idx = 0; mesh_idx < 2; mesh_idx++) { - Slicer* mesh = (mesh_idx == 0) ? &mesh_a : &mesh_b; + Slicer* mesh = (mesh_idx == 0) ? &mesh_a_ : &mesh_b_; for (size_t layer_nr = 0; layer_nr < max_layer_count; layer_nr++) { if (layer_nr >= mesh->layers.size()) @@ -329,8 +329,8 @@ void InterlockingGenerator::applyMicrostructureToOutlines(const std::unordered_s Polygons layer_outlines = layer_regions[layer_nr]; layer_outlines.applyMatrix(unapply_rotation); - const Polygons areas_here = structure_per_layer[mesh_idx][layer_nr / beam_layer_count].intersection(layer_outlines); - const Polygons& areas_other = structure_per_layer[! mesh_idx][layer_nr / beam_layer_count]; + const Polygons areas_here = structure_per_layer[mesh_idx][layer_nr / beam_layer_count_].intersection(layer_outlines); + const Polygons& areas_other = structure_per_layer[! mesh_idx][layer_nr / beam_layer_count_]; SlicerLayer& layer = mesh->layers[layer_nr]; layer.polygons = layer.polygons diff --git a/src/LayerPlanBuffer.cpp b/src/LayerPlanBuffer.cpp index 7502bf2cc2..aa339d5836 100644 --- a/src/LayerPlanBuffer.cpp +++ b/src/LayerPlanBuffer.cpp @@ -17,11 +17,11 @@ namespace cura { -constexpr Duration LayerPlanBuffer::extra_preheat_time; +constexpr Duration LayerPlanBuffer::extra_preheat_time_; void LayerPlanBuffer::push(LayerPlan& layer_plan) { - buffer.push_back(&layer_plan); + buffer_.push_back(&layer_plan); } void LayerPlanBuffer::handle(LayerPlan& layer_plan, GCodeExport& gcode) @@ -38,24 +38,24 @@ void LayerPlanBuffer::handle(LayerPlan& layer_plan, GCodeExport& gcode) LayerPlan* LayerPlanBuffer::processBuffer() { - if (buffer.empty()) + if (buffer_.empty()) { return nullptr; } processFanSpeedLayerTime(); - if (buffer.size() >= 2) + if (buffer_.size() >= 2) { - addConnectingTravelMove(*--(--buffer.end()), *--buffer.end()); + addConnectingTravelMove(*--(--buffer_.end()), *--buffer_.end()); } - if (buffer.size() > 0) + if (buffer_.size() > 0) { insertTempCommands(); // insert preheat commands of the just completed layer plan (not the newly emplaced one) } - if (buffer.size() > buffer_size) + if (buffer_.size() > buffer_size_) { - LayerPlan* ret = buffer.front(); + LayerPlan* ret = buffer_.front(); Application::getInstance().communication->flushGCode(); - buffer.pop_front(); + buffer_.pop_front(); return ret; } return nullptr; @@ -64,16 +64,16 @@ LayerPlan* LayerPlanBuffer::processBuffer() void LayerPlanBuffer::flush() { Application::getInstance().communication->flushGCode(); // If there was still g-code in a layer, flush that as a separate layer. Don't want to group them together accidentally. - if (buffer.size() > 0) + if (buffer_.size() > 0) { insertTempCommands(); // insert preheat commands of the very last layer } - while (! buffer.empty()) + while (! buffer_.empty()) { - buffer.front()->writeGCode(gcode); + buffer_.front()->writeGCode(gcode_); Application::getInstance().communication->flushGCode(); - delete buffer.front(); - buffer.pop_front(); + delete buffer_.front(); + buffer_.pop_front(); } } @@ -119,13 +119,13 @@ void LayerPlanBuffer::addConnectingTravelMove(LayerPlan* prev_layer, const Layer void LayerPlanBuffer::processFanSpeedLayerTime() { - assert(buffer.size() > 0); - auto newest_layer_it = --buffer.end(); + assert(buffer_.size() > 0); + auto newest_layer_it = --buffer_.end(); // Assume the print head is homed at the start of a mesh group. // This introduces small inaccuracies for the naive layer time estimates of the first layer of the second mesh group. // It's not that bad, though. They are naive estimates any way. Point starting_position(0, 0); - if (buffer.size() >= 2) + if (buffer_.size() >= 2) { auto prev_layer_it = newest_layer_it; prev_layer_it--; @@ -182,14 +182,14 @@ Preheat::WarmUpResult LayerPlanBuffer::computeStandbyTempPlan(std::vector("material_standby_temperature"), initial_print_temp, during_printing); - warm_up.heating_time = std::min(in_between_time, warm_up.heating_time + extra_preheat_time); + warm_up.heating_time = std::min(in_between_time, warm_up.heating_time + extra_preheat_time_); return warm_up; } in_between_time += extruder_plan_before.estimates_.getTotalTime(); @@ -200,13 +200,13 @@ Preheat::WarmUpResult LayerPlanBuffer::computeStandbyTempPlan(std::vector("material_standby_temperature"); constexpr bool during_printing = false; - warm_up.heating_time = preheat_config.getTimeToGoFromTempToTemp(extruder, warm_up.lowest_temperature, initial_print_temp, during_printing); + warm_up.heating_time = preheat_config_.getTimeToGoFromTempToTemp(extruder, warm_up.lowest_temperature, initial_print_temp, during_printing); if (warm_up.heating_time > in_between_time) { warm_up.heating_time = in_between_time; warm_up.lowest_temperature = initial_print_temp - in_between_time * extruder_settings.get("machine_nozzle_heat_up_speed"); } - warm_up.heating_time = warm_up.heating_time + extra_preheat_time; + warm_up.heating_time = warm_up.heating_time + extra_preheat_time_; return warm_up; } @@ -219,7 +219,7 @@ void LayerPlanBuffer::insertPreheatCommand_singleExtrusion(ExtruderPlan& prev_ex // time_before_extruder_plan_end is halved, so that at the layer change the temperature will be half way betewen the two requested temperatures constexpr bool during_printing = true; const double prev_extrusion_temp = prev_extruder_plan.extrusion_temperature_.value_or(prev_extruder_plan.required_start_temperature_); - double time_before_extruder_plan_end = 0.5 * preheat_config.getTimeToGoFromTempToTemp(extruder_nr, prev_extrusion_temp, required_temp, during_printing); + double time_before_extruder_plan_end = 0.5 * preheat_config_.getTimeToGoFromTempToTemp(extruder_nr, prev_extrusion_temp, required_temp, during_printing); time_before_extruder_plan_end = std::min(prev_extruder_plan.estimates_.getTotalTime(), time_before_extruder_plan_end); insertPreheatCommand(prev_extruder_plan, time_before_extruder_plan_end, extruder_nr, required_temp); @@ -445,7 +445,7 @@ void LayerPlanBuffer::insertFinalPrintTempCommand(std::vector& ex // which means the stable temperature of the previous extruder plan and the stable temperature of the next extruder plan couldn't be reached constexpr bool during_printing = true; Preheat::CoolDownResult warm_cool_result - = preheat_config.getCoolDownPointAfterWarmUp(time_window, extruder, *initial_print_temp, weighted_average_extrusion_temp, final_print_temp, during_printing); + = preheat_config_.getCoolDownPointAfterWarmUp(time_window, extruder, *initial_print_temp, weighted_average_extrusion_temp, final_print_temp, during_printing); double cool_down_time = warm_cool_result.cooling_time; assert(cool_down_time >= 0); @@ -492,15 +492,15 @@ void LayerPlanBuffer::insertFinalPrintTempCommand(std::vector& ex void LayerPlanBuffer::insertTempCommands() { - if (buffer.back()->extruder_plans.size() == 0 || (buffer.back()->extruder_plans.size() == 1 && buffer.back()->extruder_plans[0].paths_.size() == 0)) + if (buffer_.back()->extruder_plans.size() == 0 || (buffer_.back()->extruder_plans.size() == 1 && buffer_.back()->extruder_plans[0].paths_.size() == 0)) { // disregard empty layer - buffer.pop_back(); + buffer_.pop_back(); return; } std::vector extruder_plans; // sorted in print order - extruder_plans.reserve(buffer.size() * 2); - for (LayerPlan* layer_plan : buffer) + extruder_plans.reserve(buffer_.size() * 2); + for (LayerPlan* layer_plan : buffer_) { for (ExtruderPlan& extr_plan : layer_plan->extruder_plans) { @@ -510,7 +510,7 @@ void LayerPlanBuffer::insertTempCommands() // insert commands for all extruder plans on this layer Scene& scene = Application::getInstance().current_slice->scene; - LayerPlan& layer_plan = *buffer.back(); + LayerPlan& layer_plan = *buffer_.back(); for (size_t extruder_plan_idx = 0; extruder_plan_idx < layer_plan.extruder_plans.size(); extruder_plan_idx++) { const size_t overall_extruder_plan_idx = extruder_plans.size() - layer_plan.extruder_plans.size() + extruder_plan_idx; @@ -529,7 +529,7 @@ void LayerPlanBuffer::insertTempCommands() avg_flow = 0.0; } - Temperature print_temp = preheat_config.getTemp(extruder, avg_flow, extruder_plan.is_initial_layer_); + Temperature print_temp = preheat_config_.getTemp(extruder, avg_flow, extruder_plan.is_initial_layer_); Temperature initial_print_temp = extruder_settings.get("material_initial_print_temperature"); if (extruder_plan.temperature_factor_ > 0) // force lower printing temperatures due to minimum layer time @@ -540,13 +540,13 @@ void LayerPlanBuffer::insertTempCommands() if (initial_print_temp == 0.0 // user doesn't want to use initial print temp feature || extruder_settings.get("machine_extruders_share_heater") // ignore initial print temps when extruders share a heater - || ! extruder_used_in_meshgroup[extruder] // prime blob uses print temp rather than initial print temp + || ! extruder_used_in_meshgroup_[extruder] // prime blob uses print temp rather than initial print temp || (overall_extruder_plan_idx > 0 && extruder_plans[overall_extruder_plan_idx - 1]->extruder_nr_ == extruder // prev plan has same extruder .. && extruder_plans[overall_extruder_plan_idx - 1]->estimates_.getTotalUnretractedTime() > 0.0) // and prev extruder plan already heated to printing temperature ) { extruder_plan.required_start_temperature_ = print_temp; - extruder_used_in_meshgroup[extruder] = true; + extruder_used_in_meshgroup_[extruder] = true; } else { @@ -555,7 +555,7 @@ void LayerPlanBuffer::insertTempCommands() } assert(extruder_plan.required_start_temperature_ != -1 && "extruder_plan.required_start_temperature should now have been set"); - if (buffer.size() == 1 && extruder_plan_idx == 0) + if (buffer_.size() == 1 && extruder_plan_idx == 0) { // the very first extruder plan of the current meshgroup size_t extruder = extruder_plan.extruder_nr_; for (size_t extruder_idx = 0; extruder_idx < scene.extruders.size(); extruder_idx++) @@ -568,11 +568,11 @@ void LayerPlanBuffer::insertTempCommands() // see FffGcodeWriter::processStartingCode if (extruder_idx == extruder) { - gcode.setInitialTemp(extruder_idx, extruder_plan.extrusion_temperature_.value_or(extruder_plan.required_start_temperature_)); + gcode_.setInitialTemp(extruder_idx, extruder_plan.extrusion_temperature_.value_or(extruder_plan.required_start_temperature_)); } else { - gcode.setInitialTemp(extruder_idx, other_extruder_settings.get("material_standby_temperature")); + gcode_.setInitialTemp(extruder_idx, other_extruder_settings.get("material_standby_temperature")); } } else diff --git a/src/infill.cpp b/src/infill.cpp index 645c3f653e..0c7dd8b641 100644 --- a/src/infill.cpp +++ b/src/infill.cpp @@ -92,40 +92,40 @@ void Infill::generate( const SliceMeshStorage* mesh, const Polygons& prevent_small_exposed_to_air) { - if (outer_contour.empty()) + if (outer_contour_.empty()) { return; } - inner_contour = generateWallToolPaths(toolpaths, outer_contour, wall_line_count, infill_line_width, infill_overlap, settings, layer_idx, section_type); - scripta::log("infill_inner_contour_0", inner_contour, section_type, layer_idx); + inner_contour_ = generateWallToolPaths(toolpaths, outer_contour_, wall_line_count_, infill_line_width_, infill_overlap_, settings, layer_idx, section_type); + scripta::log("infill_inner_contour_0", inner_contour_, section_type, layer_idx); // It does not make sense to print a pattern in a small region. So the infill region // is split into a small region that will be filled with walls and the normal region // that will be filled with the pattern. This split of regions is not needed if the // infill pattern is concentric or if the small_area_width is zero. - if (pattern != EFillMethod::CONCENTRIC && small_area_width > 0) + if (pattern_ != EFillMethod::CONCENTRIC && small_area_width_ > 0) { - const auto too_small_length = INT2MM(static_cast(infill_line_width) / 2.0); + const auto too_small_length = INT2MM(static_cast(infill_line_width_) / 2.0); // Split the infill region in a narrow region and the normal region. - Polygons small_infill = inner_contour; - inner_contour = inner_contour.offset(-small_area_width / 2); - inner_contour.removeSmallAreas(too_small_length * too_small_length, true); - inner_contour = inner_contour.offset(small_area_width / 2); - inner_contour = inner_contour.unionPolygons(prevent_small_exposed_to_air).intersection(small_infill); - inner_contour = Simplify(max_resolution, max_deviation, 0).polygon(inner_contour); - small_infill = small_infill.difference(inner_contour); + Polygons small_infill = inner_contour_; + inner_contour_ = inner_contour_.offset(-small_area_width_ / 2); + inner_contour_.removeSmallAreas(too_small_length * too_small_length, true); + inner_contour_ = inner_contour_.offset(small_area_width_ / 2); + inner_contour_ = inner_contour_.unionPolygons(prevent_small_exposed_to_air).intersection(small_infill); + inner_contour_ = Simplify(max_resolution_, max_deviation_, 0).polygon(inner_contour_); + small_infill = small_infill.difference(inner_contour_); // Small corners of a bigger area should not be considered narrow and are therefore added to the bigger area again. auto small_infill_parts = small_infill.splitIntoParts(); small_infill.clear(); for (const auto& small_infill_part : small_infill_parts) { - if (small_infill_part.offset(-infill_line_width / 2).offset(infill_line_width / 2).area() < infill_line_width * infill_line_width * 10 - && ! inner_contour.intersection(small_infill_part.offset(infill_line_width / 4)).empty()) + if (small_infill_part.offset(-infill_line_width_ / 2).offset(infill_line_width_ / 2).area() < infill_line_width_ * infill_line_width_ * 10 + && ! inner_contour_.intersection(small_infill_part.offset(infill_line_width_ / 4)).empty()) { - inner_contour.add(small_infill_part); + inner_contour_.add(small_infill_part); } else { @@ -133,11 +133,11 @@ void Infill::generate( small_infill.add(small_infill_part); } } - inner_contour.unionPolygons(); + inner_contour_.unionPolygons(); // Fill narrow area with walls. - const size_t narrow_wall_count = small_area_width / infill_line_width + 1; - WallToolPaths wall_toolpaths(small_infill, infill_line_width, narrow_wall_count, 0, settings, layer_idx, section_type); + const size_t narrow_wall_count = small_area_width_ / infill_line_width_ + 1; + WallToolPaths wall_toolpaths(small_infill, infill_line_width_, narrow_wall_count, 0, settings, layer_idx, section_type); std::vector small_infill_paths = wall_toolpaths.getToolPaths(); scripta::log( "infill_small_infill_paths_0", @@ -154,36 +154,36 @@ void Infill::generate( toolpaths.emplace_back(small_infill_path); } } - scripta::log("infill_inner_contour_1", inner_contour, section_type, layer_idx); + scripta::log("infill_inner_contour_1", inner_contour_, section_type, layer_idx); // apply an extra offset in case the pattern prints along the sides of the area. - if (pattern == EFillMethod::ZIG_ZAG // Zig-zag prints the zags along the walls. - || (zig_zaggify - && (pattern == EFillMethod::LINES // Zig-zaggified infill patterns print their zags along the walls. - || pattern == EFillMethod::TRIANGLES || pattern == EFillMethod::GRID || pattern == EFillMethod::CUBIC || pattern == EFillMethod::TETRAHEDRAL - || pattern == EFillMethod::QUARTER_CUBIC || pattern == EFillMethod::TRIHEXAGON || pattern == EFillMethod::GYROID || pattern == EFillMethod::CROSS - || pattern == EFillMethod::CROSS_3D)) - || infill_multiplier % 2 + if (pattern_ == EFillMethod::ZIG_ZAG // Zig-zag prints the zags along the walls. + || (zig_zaggify_ + && (pattern_ == EFillMethod::LINES // Zig-zaggified infill patterns print their zags along the walls. + || pattern_ == EFillMethod::TRIANGLES || pattern_ == EFillMethod::GRID || pattern_ == EFillMethod::CUBIC || pattern_ == EFillMethod::TETRAHEDRAL + || pattern_ == EFillMethod::QUARTER_CUBIC || pattern_ == EFillMethod::TRIHEXAGON || pattern_ == EFillMethod::GYROID || pattern_ == EFillMethod::CROSS + || pattern_ == EFillMethod::CROSS_3D)) + || infill_multiplier_ % 2 == 0) // Multiplied infill prints loops of infill, partly along the walls, if even. For odd multipliers >1 it gets offset by the multiply algorithm itself. { - inner_contour = inner_contour.offset(-infill_line_width / 2); - inner_contour = Simplify(max_resolution, max_deviation, 0).polygon(inner_contour); + inner_contour_ = inner_contour_.offset(-infill_line_width_ / 2); + inner_contour_ = Simplify(max_resolution_, max_deviation_, 0).polygon(inner_contour_); } - scripta::log("infill_inner_contour_2", inner_contour, section_type, layer_idx); + scripta::log("infill_inner_contour_2", inner_contour_, section_type, layer_idx); - if (infill_multiplier > 1) + if (infill_multiplier_ > 1) { - bool zig_zaggify_real = zig_zaggify; - if (infill_multiplier % 2 == 0) + bool zig_zaggify_real = zig_zaggify_; + if (infill_multiplier_ % 2 == 0) { - zig_zaggify = false; + zig_zaggify_ = false; } Polygons generated_result_polygons; Polygons generated_result_lines; _generate(toolpaths, generated_result_polygons, generated_result_lines, settings, cross_fill_provider, lightning_trees, mesh); - zig_zaggify = zig_zaggify_real; + zig_zaggify_ = zig_zaggify_real; multiplyInfill(generated_result_polygons, generated_result_lines); result_polygons.add(generated_result_polygons); result_lines.add(generated_result_lines); @@ -212,10 +212,10 @@ void Infill::generate( scripta::CellVDI{ "inset_idx", &ExtrusionLine::inset_idx }, scripta::PointVDI{ "width", &ExtrusionJunction::w }, scripta::PointVDI{ "perimeter_index", &ExtrusionJunction::perimeter_index }); - if (connect_polygons) + if (connect_polygons_) { // remove too small polygons - coord_t snap_distance = infill_line_width * 2; // polygons with a span of max 1 * nozzle_size are too small + coord_t snap_distance = infill_line_width_ * 2; // polygons with a span of max 1 * nozzle_size are too small auto it = std::remove_if( result_polygons.begin(), result_polygons.end(), @@ -225,7 +225,7 @@ void Infill::generate( }); result_polygons.erase(it, result_polygons.end()); - PolygonConnector connector(infill_line_width); + PolygonConnector connector(infill_line_width_); connector.add(result_polygons); connector.add(toolpaths); Polygons connected_polygons; @@ -257,18 +257,18 @@ void Infill::_generate( const std::shared_ptr& lightning_trees, const SliceMeshStorage* mesh) { - if (inner_contour.empty()) + if (inner_contour_.empty()) return; - if (line_distance == 0) + if (line_distance_ == 0) return; - switch (pattern) + switch (pattern_) { case EFillMethod::GRID: generateGridInfill(result_lines); break; case EFillMethod::LINES: - generateLineInfill(result_lines, line_distance, fill_angle, 0); + generateLineInfill(result_lines, line_distance_, fill_angle_, 0); break; case EFillMethod::CUBIC: generateCubicInfill(result_lines); @@ -289,7 +289,7 @@ void Infill::_generate( generateConcentricInfill(toolpaths, settings); break; case EFillMethod::ZIG_ZAG: - generateZigZagInfill(result_lines, line_distance, fill_angle); + generateZigZagInfill(result_lines, line_distance_, fill_angle_); break; case EFillMethod::CUBICSUBDIV: if (! mesh) @@ -318,7 +318,7 @@ void Infill::_generate( case EFillMethod::PLUGIN: { auto [toolpaths_, generated_result_polygons_, generated_result_lines_] = slots::instance().generate( - inner_contour, + inner_contour_, mesh ? mesh->settings.get("infill_pattern") : settings.get("infill_pattern"), mesh ? mesh->settings : settings); toolpaths.insert(toolpaths.end(), toolpaths_.begin(), toolpaths_.end()); @@ -331,7 +331,7 @@ void Infill::_generate( break; } - if (connect_lines) + if (connect_lines_) { // The list should be empty because it will be again filled completely. Otherwise, might have double lines. assert(result_lines.empty()); @@ -339,15 +339,15 @@ void Infill::_generate( connectLines(result_lines); } - Simplify simplifier(max_resolution, max_deviation, 0); + Simplify simplifier(max_resolution_, max_deviation_, 0); result_polygons = simplifier.polygon(result_polygons); - if (! skip_line_stitching - && (zig_zaggify || pattern == EFillMethod::CROSS || pattern == EFillMethod::CROSS_3D || pattern == EFillMethod::CUBICSUBDIV || pattern == EFillMethod::GYROID - || pattern == EFillMethod::ZIG_ZAG)) + if (! skip_line_stitching_ + && (zig_zaggify_ || pattern_ == EFillMethod::CROSS || pattern_ == EFillMethod::CROSS_3D || pattern_ == EFillMethod::CUBICSUBDIV || pattern_ == EFillMethod::GYROID + || pattern_ == EFillMethod::ZIG_ZAG)) { // don't stich for non-zig-zagged line infill types Polygons stitched_lines; - PolylineStitcher::stitch(result_lines, stitched_lines, result_polygons, infill_line_width); + PolylineStitcher::stitch(result_lines, stitched_lines, result_polygons, infill_line_width_); result_lines = stitched_lines; } result_lines = simplifier.polyline(result_lines); @@ -355,13 +355,13 @@ void Infill::_generate( void Infill::multiplyInfill(Polygons& result_polygons, Polygons& result_lines) { - if (pattern == EFillMethod::CONCENTRIC) + if (pattern_ == EFillMethod::CONCENTRIC) { result_polygons = result_polygons.processEvenOdd(); // make into areas } - bool odd_multiplier = infill_multiplier % 2 == 1; - coord_t offset = (odd_multiplier) ? infill_line_width : infill_line_width / 2; + bool odd_multiplier = infill_multiplier_ % 2 == 1; + coord_t offset = (odd_multiplier) ? infill_line_width_ : infill_line_width_ / 2; // Get the first offset these are mirrored from the original center line Polygons result; @@ -373,21 +373,21 @@ void Infill::multiplyInfill(Polygons& result_polygons, Polygons& result_lines) const Polygons first_offset_polygons = first_offset_polygons_outward.difference(first_offset_polygons_inward); first_offset = first_offset_lines.unionPolygons( first_offset_polygons); // usually we only have either lines or polygons, but this code also handles an infill pattern which generates both - if (zig_zaggify) + if (zig_zaggify_) { - first_offset = inner_contour.difference(first_offset); + first_offset = inner_contour_.difference(first_offset); } } result.add(first_offset); // Create the additional offsets from the first offsets, generated earlier, the direction of these offsets is // depended on whether these lines should be connected or not. - if (infill_multiplier > 3) + if (infill_multiplier_ > 3) { Polygons reference_polygons = first_offset; - const size_t multiplier = static_cast(infill_multiplier / 2); + const size_t multiplier = static_cast(infill_multiplier_ / 2); - const int extra_offset = mirror_offset ? -infill_line_width : infill_line_width; + const int extra_offset = mirror_offset_ ? -infill_line_width_ : infill_line_width_; for (size_t infill_line = 1; infill_line < multiplier; ++infill_line) { Polygons extra_polys = reference_polygons.offset(extra_offset); @@ -395,9 +395,9 @@ void Infill::multiplyInfill(Polygons& result_polygons, Polygons& result_lines) reference_polygons = std::move(extra_polys); } } - if (zig_zaggify) + if (zig_zaggify_) { - result = result.intersection(inner_contour); + result = result.intersection(inner_contour_); } // Remove the original center lines when there are an even number of lines required. @@ -407,7 +407,7 @@ void Infill::multiplyInfill(Polygons& result_polygons, Polygons& result_lines) result_lines.clear(); } result_polygons.add(result); - if (! zig_zaggify) + if (! zig_zaggify_) { for (PolygonRef poly : result_polygons) { // make polygons into polylines @@ -417,40 +417,40 @@ void Infill::multiplyInfill(Polygons& result_polygons, Polygons& result_lines) } poly.add(poly[0]); } - Polygons polylines = inner_contour.intersectionPolyLines(result_polygons); + Polygons polylines = inner_contour_.intersectionPolyLines(result_polygons); result_polygons.clear(); - PolylineStitcher::stitch(polylines, result_lines, result_polygons, infill_line_width); + PolylineStitcher::stitch(polylines, result_lines, result_polygons, infill_line_width_); } } void Infill::generateGyroidInfill(Polygons& result_lines, Polygons& result_polygons) { Polygons line_segments; - GyroidInfill::generateTotalGyroidInfill(line_segments, zig_zaggify, line_distance, inner_contour, z); - PolylineStitcher::stitch(line_segments, result_lines, result_polygons, infill_line_width); + GyroidInfill::generateTotalGyroidInfill(line_segments, zig_zaggify_, line_distance_, inner_contour_, z_); + PolylineStitcher::stitch(line_segments, result_lines, result_polygons, infill_line_width_); } void Infill::generateLightningInfill(const std::shared_ptr& trees, Polygons& result_lines) { // Don't need to support areas smaller than line width, as they are always within radius: - if (std::abs(inner_contour.area()) < infill_line_width || ! trees) + if (std::abs(inner_contour_.area()) < infill_line_width_ || ! trees) { return; } - result_lines.add(trees->convertToLines(inner_contour, infill_line_width)); + result_lines.add(trees->convertToLines(inner_contour_, infill_line_width_)); } void Infill::generateConcentricInfill(std::vector& toolpaths, const Settings& settings) { - const coord_t min_area = infill_line_width * infill_line_width; + const coord_t min_area = infill_line_width_ * infill_line_width_; - Polygons current_inset = inner_contour; + Polygons current_inset = inner_contour_; Simplify simplifier(settings); while (true) { // If line_distance is 0, start from the same contour as the previous line, except where the previous line closed up the shape. // So we add the whole nominal line width first (to allow lines to be closer together than 1 line width if the line distance is smaller) and then subtract line_distance. - current_inset = current_inset.offset(infill_line_width - line_distance); + current_inset = current_inset.offset(infill_line_width_ - line_distance_); current_inset = simplifier.polygon(current_inset); // Many insets lead to increasingly detailed shapes. Simplify to speed up processing. if (current_inset.area() < min_area) // So small that it's inconsequential. Stop here. { @@ -459,7 +459,7 @@ void Infill::generateConcentricInfill(std::vector& toolpaths constexpr size_t inset_wall_count = 1; // 1 wall at a time. constexpr coord_t wall_0_inset = 0; // Don't apply any outer wall inset for these. That's just for the outer wall. - WallToolPaths wall_toolpaths(current_inset, infill_line_width, inset_wall_count, wall_0_inset, settings, 0, SectionType::CONCENTRIC_INFILL); // FIXME: @jellespijker pass + WallToolPaths wall_toolpaths(current_inset, infill_line_width_, inset_wall_count, wall_0_inset, settings, 0, SectionType::CONCENTRIC_INFILL); // FIXME: @jellespijker pass // the correct layer const std::vector inset_paths = wall_toolpaths.getToolPaths(); toolpaths.insert(toolpaths.end(), inset_paths.begin(), inset_paths.end()); @@ -470,16 +470,16 @@ void Infill::generateConcentricInfill(std::vector& toolpaths void Infill::generateGridInfill(Polygons& result) { - generateLineInfill(result, line_distance, fill_angle, 0); - generateLineInfill(result, line_distance, fill_angle + 90, 0); + generateLineInfill(result, line_distance_, fill_angle_, 0); + generateLineInfill(result, line_distance_, fill_angle_ + 90, 0); } void Infill::generateCubicInfill(Polygons& result) { - const coord_t shift = one_over_sqrt_2 * z; - generateLineInfill(result, line_distance, fill_angle, shift); - generateLineInfill(result, line_distance, fill_angle + 120, shift); - generateLineInfill(result, line_distance, fill_angle + 240, shift); + const coord_t shift = one_over_sqrt_2 * z_; + generateLineInfill(result, line_distance_, fill_angle_, shift); + generateLineInfill(result, line_distance_, fill_angle_ + 120, shift); + generateLineInfill(result, line_distance_, fill_angle_ + 240, shift); } void Infill::generateTetrahedralInfill(Polygons& result) @@ -496,51 +496,51 @@ void Infill::generateQuarterCubicInfill(Polygons& result) void Infill::generateHalfTetrahedralInfill(float pattern_z_shift, int angle_shift, Polygons& result) { - const coord_t period = line_distance * 2; - coord_t shift = coord_t(one_over_sqrt_2 * (z + pattern_z_shift * period * 2)) % period; + const coord_t period = line_distance_ * 2; + coord_t shift = coord_t(one_over_sqrt_2 * (z_ + pattern_z_shift * period * 2)) % period; shift = std::min(shift, period - shift); // symmetry due to the fact that we are applying the shift in both directions - shift = std::min(shift, period / 2 - infill_line_width / 2); // don't put lines too close to each other - shift = std::max(shift, infill_line_width / 2); // don't put lines too close to each other - generateLineInfill(result, period, fill_angle + angle_shift, shift); - generateLineInfill(result, period, fill_angle + angle_shift, -shift); + shift = std::min(shift, period / 2 - infill_line_width_ / 2); // don't put lines too close to each other + shift = std::max(shift, infill_line_width_ / 2); // don't put lines too close to each other + generateLineInfill(result, period, fill_angle_ + angle_shift, shift); + generateLineInfill(result, period, fill_angle_ + angle_shift, -shift); } void Infill::generateTriangleInfill(Polygons& result) { - generateLineInfill(result, line_distance, fill_angle, 0); - generateLineInfill(result, line_distance, fill_angle + 60, 0); - generateLineInfill(result, line_distance, fill_angle + 120, 0); + generateLineInfill(result, line_distance_, fill_angle_, 0); + generateLineInfill(result, line_distance_, fill_angle_ + 60, 0); + generateLineInfill(result, line_distance_, fill_angle_ + 120, 0); } void Infill::generateTrihexagonInfill(Polygons& result) { - generateLineInfill(result, line_distance, fill_angle, 0); - generateLineInfill(result, line_distance, fill_angle + 60, 0); - generateLineInfill(result, line_distance, fill_angle + 120, line_distance / 2); + generateLineInfill(result, line_distance_, fill_angle_, 0); + generateLineInfill(result, line_distance_, fill_angle_ + 60, 0); + generateLineInfill(result, line_distance_, fill_angle_ + 120, line_distance_ / 2); } void Infill::generateCubicSubDivInfill(Polygons& result, const SliceMeshStorage& mesh) { Polygons uncropped; - mesh.base_subdiv_cube->generateSubdivisionLines(z, uncropped); + mesh.base_subdiv_cube->generateSubdivisionLines(z_, uncropped); constexpr bool restitch = false; // cubic subdivision lines are always single line segments - not polylines consisting of multiple segments. - result = outer_contour.offset(infill_overlap).intersectionPolyLines(uncropped, restitch); + result = outer_contour_.offset(infill_overlap_).intersectionPolyLines(uncropped, restitch); } void Infill::generateCrossInfill(const SierpinskiFillProvider& cross_fill_provider, Polygons& result_polygons, Polygons& result_lines) { - Polygon cross_pattern_polygon = cross_fill_provider.generate(pattern, z, infill_line_width, pocket_size); + Polygon cross_pattern_polygon = cross_fill_provider.generate(pattern_, z_, infill_line_width_, pocket_size_); if (cross_pattern_polygon.empty()) { return; } - if (zig_zaggify) + if (zig_zaggify_) { Polygons cross_pattern_polygons; cross_pattern_polygons.add(cross_pattern_polygon); - result_polygons.add(inner_contour.intersection(cross_pattern_polygons)); + result_polygons.add(inner_contour_.intersection(cross_pattern_polygons)); } else { @@ -549,8 +549,8 @@ void Infill::generateCrossInfill(const SierpinskiFillProvider& cross_fill_provid Polygons cross_pattern_polylines; cross_pattern_polylines.add(cross_pattern_polygon); - Polygons poly_lines = inner_contour.intersectionPolyLines(cross_pattern_polylines); - PolylineStitcher::stitch(poly_lines, result_lines, result_polygons, infill_line_width); + Polygons poly_lines = inner_contour_.intersectionPolyLines(cross_pattern_polylines); + PolylineStitcher::stitch(poly_lines, result_lines, result_polygons, infill_line_width_); } } @@ -563,7 +563,7 @@ void Infill::addLineInfill( std::vector>& cut_list, coord_t shift) { - assert(! connect_lines && "connectLines() should add the infill lines, not addLineInfill"); + assert(! connect_lines_ && "connectLines() should add the infill lines, not addLineInfill"); unsigned int scanline_idx = 0; for (coord_t x = scanline_min_idx * line_distance + shift; x < boundary.max.X; x += line_distance) @@ -576,7 +576,7 @@ void Infill::addLineInfill( std::sort(crossings.begin(), crossings.end()); // sort by increasing Y coordinates for (unsigned int crossing_idx = 0; crossing_idx + 1 < crossings.size(); crossing_idx += 2) { - if (crossings[crossing_idx + 1] - crossings[crossing_idx] < infill_line_width / 5) + if (crossings[crossing_idx + 1] - crossings[crossing_idx] < infill_line_width_ / 5) { // segment is too short to create infill continue; } @@ -588,10 +588,10 @@ void Infill::addLineInfill( coord_t Infill::getShiftOffsetFromInfillOriginAndRotation(const double& infill_rotation) { - if (infill_origin.X != 0 || infill_origin.Y != 0) + if (infill_origin_.X != 0 || infill_origin_.Y != 0) { const double rotation_rads = infill_rotation * std::numbers::pi / 180; - return infill_origin.X * std::cos(rotation_rads) - infill_origin.Y * std::sin(rotation_rads); + return infill_origin_.X * std::cos(rotation_rads) - infill_origin_.Y * std::sin(rotation_rads); } return 0; } @@ -611,8 +611,8 @@ void Infill::generateZigZagInfill(Polygons& result, const coord_t line_distance, const coord_t shift = getShiftOffsetFromInfillOriginAndRotation(infill_rotation); PointMatrix rotation_matrix(infill_rotation); - ZigzagConnectorProcessor zigzag_processor(rotation_matrix, result, use_endpieces, connected_zigzags, skip_some_zags, zag_skip_count); - generateLinearBasedInfill(result, line_distance, rotation_matrix, zigzag_processor, connected_zigzags, shift); + ZigzagConnectorProcessor zigzag_processor(rotation_matrix, result, use_endpieces_, connected_zigzags_, skip_some_zags_, zag_skip_count_); + generateLinearBasedInfill(result, line_distance, rotation_matrix, zigzag_processor, connected_zigzags_, shift); } /* @@ -646,15 +646,15 @@ void Infill::generateLinearBasedInfill( const bool connected_zigzags, coord_t extra_shift) { - if (line_distance == 0 || inner_contour.empty()) // No infill to generate (0% density) or no area to generate it in. + if (line_distance == 0 || inner_contour_.empty()) // No infill to generate (0% density) or no area to generate it in. { return; } - Polygons outline = inner_contour; // Make a copy. We'll be rotating this outline to make intersections always horizontal, for better performance. + Polygons outline = inner_contour_; // Make a copy. We'll be rotating this outline to make intersections always horizontal, for better performance. outline.applyMatrix(rotation_matrix); - coord_t shift = extra_shift + this->shift; + coord_t shift = extra_shift + this->shift_; if (shift < 0) { shift = line_distance - (-shift) % line_distance; @@ -691,17 +691,17 @@ void Infill::generateLinearBasedInfill( const int min_scanline_index = computeScanSegmentIdx(boundary.min.X - shift, line_distance) + 1; const int max_scanline_index = computeScanSegmentIdx(boundary.max.X - shift, line_distance) + 1; crossings_per_scanline.resize(max_scanline_index - min_scanline_index); - if (connect_lines) + if (connect_lines_) { - crossings_on_line.resize(outline.size()); // One for each polygon. + crossings_on_line_.resize(outline.size()); // One for each polygon. } for (size_t poly_idx = 0; poly_idx < outline.size(); poly_idx++) { PolygonRef poly = outline[poly_idx]; - if (connect_lines) + if (connect_lines_) { - crossings_on_line[poly_idx].resize(poly.size()); // One for each line in this polygon. + crossings_on_line_[poly_idx].resize(poly.size()); // One for each line in this polygon. } Point p0 = poly.back(); zigzag_connector_processor.registerVertex(p0); // always adds the first point to ZigzagConnectorProcessorEndPieces::first_zigzag_connector when using a zigzag infill type @@ -754,7 +754,7 @@ void Infill::generateLinearBasedInfill( zigzag_connector_processor.registerPolyFinished(); } - if (connect_lines) + if (connect_lines_) { // Gather all crossings per scanline and find out which crossings belong together, then store them in crossings_on_line. for (int scanline_index = min_scanline_index; scanline_index < max_scanline_index; scanline_index++) @@ -777,8 +777,8 @@ void Infill::generateLinearBasedInfill( InfillLineSegment* new_segment = new InfillLineSegment(unrotated_first, first.vertex_index, first.polygon_index, unrotated_second, second.vertex_index, second.polygon_index); // Put the same line segment in the data structure twice: Once for each of the polygon line segment that it crosses. - crossings_on_line[first.polygon_index][first.vertex_index].push_back(new_segment); - crossings_on_line[second.polygon_index][second.vertex_index].push_back(new_segment); + crossings_on_line_[first.polygon_index][first.vertex_index].push_back(new_segment); + crossings_on_line_[second.polygon_index][second.vertex_index].push_back(new_segment); } } } @@ -801,12 +801,12 @@ void Infill::generateLinearBasedInfill( void Infill::resolveIntersection(const coord_t at_distance, const Point& intersect, Point& connect_start, Point& connect_end, InfillLineSegment* a, InfillLineSegment* b) { // Select wich ends of the line need to 'bend'. - const bool forward_line_a = a->end == connect_start; - const bool forward_line_b = b->start == connect_end; - auto& bend_a = forward_line_a ? a->end_bend : a->start_bend; - auto& bend_b = forward_line_b ? b->start_bend : b->end_bend; - auto& end_a = forward_line_a ? a->altered_end : a->altered_start; - auto& end_b = forward_line_b ? b->altered_start : b->altered_end; + const bool forward_line_a = a->end_ == connect_start; + const bool forward_line_b = b->start_ == connect_end; + auto& bend_a = forward_line_a ? a->end_bend_ : a->start_bend_; + auto& bend_b = forward_line_b ? b->start_bend_ : b->end_bend_; + auto& end_a = forward_line_a ? a->altered_end_ : a->altered_start_; + auto& end_b = forward_line_b ? b->altered_start_ : b->altered_end_; // Set values ('pre existing' values are needed when feeding these as reference parameters to functions that need a value). assert(! bend_a.has_value()); @@ -827,8 +827,8 @@ void Infill::resolveIntersection(const coord_t at_distance, const Point& interse bool is_resolved = true; // Use both of the resulting lines to place the 'bends' by intersecting with the original line-segments. - is_resolved &= LinearAlg2D::lineLineIntersection(q, r, a->start, a->end, bend_a.value()) && LinearAlg2D::pointIsProjectedBeyondLine(bend_a.value(), a->start, a->end) == 0; - is_resolved &= LinearAlg2D::lineLineIntersection(s, t, b->start, b->end, bend_b.value()) && LinearAlg2D::pointIsProjectedBeyondLine(bend_b.value(), b->start, b->end) == 0; + is_resolved &= LinearAlg2D::lineLineIntersection(q, r, a->start_, a->end_, bend_a.value()) && LinearAlg2D::pointIsProjectedBeyondLine(bend_a.value(), a->start_, a->end_) == 0; + is_resolved &= LinearAlg2D::lineLineIntersection(s, t, b->start_, b->end_, bend_b.value()) && LinearAlg2D::pointIsProjectedBeyondLine(bend_b.value(), b->start_, b->end_) == 0; // Also set the new end-points is_resolved &= LinearAlg2D::lineLineIntersection(connect_start, connect_end, q, r, end_a) && LinearAlg2D::pointIsProjectedBeyondLine(end_a, connect_start, connect_end) == 0; @@ -851,7 +851,7 @@ void Infill::resolveIntersection(const coord_t at_distance, const Point& interse void Infill::connectLines(Polygons& result_lines) { UnionFind connected_lines; // Keeps track of which lines are connected to which. - for (const std::vector>& crossings_on_polygon : crossings_on_line) + for (const std::vector>& crossings_on_polygon : crossings_on_line_) { for (const std::vector& crossings_on_polygon_segment : crossings_on_polygon) { @@ -865,16 +865,16 @@ void Infill::connectLines(Polygons& result_lines) } } - const auto half_line_distance_squared = (line_distance * line_distance) / 4; - for (size_t polygon_index = 0; polygon_index < inner_contour.size(); polygon_index++) + const auto half_line_distance_squared = (line_distance_ * line_distance_) / 4; + for (size_t polygon_index = 0; polygon_index < inner_contour_.size(); polygon_index++) { - ConstPolygonRef inner_contour_polygon = inner_contour[polygon_index]; + ConstPolygonRef inner_contour_polygon = inner_contour_[polygon_index]; if (inner_contour_polygon.empty()) { continue; } - assert(crossings_on_line.size() > polygon_index && "crossings dimension should be bigger then polygon index"); - std::vector>& crossings_on_polygon = crossings_on_line[polygon_index]; + assert(crossings_on_line_.size() > polygon_index && "crossings dimension should be bigger then polygon index"); + std::vector>& crossings_on_polygon = crossings_on_line_[polygon_index]; InfillLineSegment* previous_crossing = nullptr; // The crossing that we should connect to. If nullptr, we have been skipping until we find the next crossing. InfillLineSegment* previous_segment = nullptr; // The last segment we were connecting while drawing a line along the border. Point vertex_before = inner_contour_polygon.back(); @@ -891,10 +891,10 @@ void Infill::connectLines(Polygons& result_lines) [&vertex_before, polygon_index, vertex_index](InfillLineSegment* left_hand_side, InfillLineSegment* right_hand_side) { // Find the two endpoints that are relevant. - const bool choose_left = (left_hand_side->start_segment == vertex_index && left_hand_side->start_polygon == polygon_index); - const bool choose_right = (right_hand_side->start_segment == vertex_index && right_hand_side->start_polygon == polygon_index); - const Point left_hand_point = choose_left ? left_hand_side->start : left_hand_side->end; - const Point right_hand_point = choose_right ? right_hand_side->start : right_hand_side->end; + const bool choose_left = (left_hand_side->start_segment_ == vertex_index && left_hand_side->start_polygon_ == polygon_index); + const bool choose_right = (right_hand_side->start_segment_ == vertex_index && right_hand_side->start_polygon_ == polygon_index); + const Point left_hand_point = choose_left ? left_hand_side->start_ : left_hand_side->end_; + const Point right_hand_point = choose_right ? right_hand_side->start_ : right_hand_side->end_; return vSize(left_hand_point - vertex_before) < vSize(right_hand_point - vertex_before); }); @@ -919,16 +919,16 @@ void Infill::connectLines(Polygons& result_lines) // Join two infill lines together with a connecting line. // Here the InfillLineSegments function as a linked list, so that they can easily be joined. - const bool previous_forward = (previous_segment->start_segment == vertex_index && previous_segment->start_polygon == polygon_index); - const bool next_forward = (crossing->start_segment == vertex_index && crossing->start_polygon == polygon_index); - Point& previous_point = previous_forward ? previous_segment->start : previous_segment->end; - Point& next_point = next_forward ? crossing->start : crossing->end; + const bool previous_forward = (previous_segment->start_segment_ == vertex_index && previous_segment->start_polygon_ == polygon_index); + const bool next_forward = (crossing->start_segment_ == vertex_index && crossing->start_polygon_ == polygon_index); + Point& previous_point = previous_forward ? previous_segment->start_ : previous_segment->end_; + Point& next_point = next_forward ? crossing->start_ : crossing->end_; InfillLineSegment* new_segment; // If the segment is near length, we avoid creating it but still want to connect the crossing with the previous segment. if (previous_point == next_point) { - (previous_forward ? previous_segment->previous : previous_segment->next) = crossing; + (previous_forward ? previous_segment->previous_ : previous_segment->next_) = crossing; new_segment = previous_segment; } else @@ -936,23 +936,23 @@ void Infill::connectLines(Polygons& result_lines) // Resolve any intersections of the fill lines close to the boundary, by inserting extra points so the lines don't create a tiny 'loop'. Point intersect; if (vSize2(previous_point - next_point) < half_line_distance_squared - && LinearAlg2D::lineLineIntersection(previous_segment->start, previous_segment->end, crossing->start, crossing->end, intersect) - && LinearAlg2D::pointIsProjectedBeyondLine(intersect, previous_segment->start, previous_segment->end) == 0 - && LinearAlg2D::pointIsProjectedBeyondLine(intersect, crossing->start, crossing->end) == 0) + && LinearAlg2D::lineLineIntersection(previous_segment->start_, previous_segment->end_, crossing->start_, crossing->end_, intersect) + && LinearAlg2D::pointIsProjectedBeyondLine(intersect, previous_segment->start_, previous_segment->end_) == 0 + && LinearAlg2D::pointIsProjectedBeyondLine(intersect, crossing->start_, crossing->end_) == 0) { - resolveIntersection(infill_line_width, intersect, previous_point, next_point, previous_segment, crossing); + resolveIntersection(infill_line_width_, intersect, previous_point, next_point, previous_segment, crossing); } // A connecting line between them. new_segment = new InfillLineSegment(previous_point, vertex_index, polygon_index, next_point, vertex_index, polygon_index); - new_segment->altered_start = previous_point; - new_segment->altered_end = next_point; - new_segment->previous = previous_segment; - (previous_forward ? previous_segment->previous : previous_segment->next) = new_segment; - new_segment->next = crossing; + new_segment->altered_start_ = previous_point; + new_segment->altered_end_ = next_point; + new_segment->previous_ = previous_segment; + (previous_forward ? previous_segment->previous_ : previous_segment->next_) = new_segment; + new_segment->next_ = crossing; } - (next_forward ? crossing->previous : crossing->next) = new_segment; + (next_forward ? crossing->previous_ : crossing->next_) = new_segment; connected_lines.unite(crossing_handle, previous_crossing_handle); previous_crossing = nullptr; previous_segment = nullptr; @@ -964,8 +964,8 @@ void Infill::connectLines(Polygons& result_lines) { InfillLineSegment* new_segment; - const bool choose_side = (vertex_index == previous_segment->start_segment && polygon_index == previous_segment->start_polygon); - const auto& previous_side = choose_side ? previous_segment->start : previous_segment->end; + const bool choose_side = (vertex_index == previous_segment->start_segment_ && polygon_index == previous_segment->start_polygon_); + const auto& previous_side = choose_side ? previous_segment->start_ : previous_segment->end_; if (previous_side == vertex_after) { // Edge case when an infill line ends directly on top of vertex_after: We skip the extra connecting line segment, as that would be 0-length. @@ -975,9 +975,9 @@ void Infill::connectLines(Polygons& result_lines) else { new_segment - = new InfillLineSegment(previous_side, vertex_index, polygon_index, vertex_after, (vertex_index + 1) % inner_contour[polygon_index].size(), polygon_index); - (choose_side ? previous_segment->previous : previous_segment->next) = new_segment; - new_segment->previous = previous_segment; + = new InfillLineSegment(previous_side, vertex_index, polygon_index, vertex_after, (vertex_index + 1) % inner_contour_[polygon_index].size(), polygon_index); + (choose_side ? previous_segment->previous_ : previous_segment->next_) = new_segment; + new_segment->previous_ = previous_segment; previous_segment = new_segment; } } @@ -999,38 +999,38 @@ void Infill::connectLines(Polygons& result_lines) // Find where the polyline ends by searching through previous and next lines. // Note that the "previous" and "next" lines don't necessarily match up though, because the direction while connecting infill lines was not yet known. - Point previous_vertex = infill_line->start; // Take one side arbitrarily to start from. This variable indicates the vertex that connects to the previous line. + Point previous_vertex = infill_line->start_; // Take one side arbitrarily to start from. This variable indicates the vertex that connects to the previous line. InfillLineSegment* current_infill_line = infill_line; - while (current_infill_line->next && current_infill_line->previous) // Until we reached an endpoint. + while (current_infill_line->next_ && current_infill_line->previous_) // Until we reached an endpoint. { - const bool choose_side = (previous_vertex == current_infill_line->start); - const Point next_vertex = choose_side ? current_infill_line->end : current_infill_line->start; - current_infill_line = choose_side ? current_infill_line->next : current_infill_line->previous; + const bool choose_side = (previous_vertex == current_infill_line->start_); + const Point next_vertex = choose_side ? current_infill_line->end_ : current_infill_line->start_; + current_infill_line = choose_side ? current_infill_line->next_ : current_infill_line->previous_; previous_vertex = next_vertex; } // Now go along the linked list of infill lines and output the infill lines to the actual result. PolygonRef result_line = result_lines.newPoly(); InfillLineSegment* old_line = current_infill_line; - if (current_infill_line->previous) + if (current_infill_line->previous_) { current_infill_line->swapDirection(); } current_infill_line->appendTo(result_line); - previous_vertex = current_infill_line->end; - current_infill_line = current_infill_line->next; + previous_vertex = current_infill_line->end_; + current_infill_line = current_infill_line->next_; delete old_line; while (current_infill_line) { old_line = current_infill_line; // We'll delete this after we've traversed to the next line. - if (previous_vertex != current_infill_line->start) + if (previous_vertex != current_infill_line->start_) { current_infill_line->swapDirection(); } - const Point next_vertex = current_infill_line->end; // Opposite side of the line. + const Point next_vertex = current_infill_line->end_; // Opposite side of the line. constexpr bool polyline_break = false; current_infill_line->appendTo(result_line, polyline_break); - current_infill_line = current_infill_line->next; + current_infill_line = current_infill_line->next_; previous_vertex = next_vertex; delete old_line; } @@ -1041,32 +1041,32 @@ void Infill::connectLines(Polygons& result_lines) bool Infill::InfillLineSegment::operator==(const InfillLineSegment& other) const { - return start == other.start && end == other.end; + return start_ == other.start_ && end_ == other.end_; } void Infill::InfillLineSegment::swapDirection() { - std::swap(start, end); - std::swap(altered_start, altered_end); - std::swap(start_bend, end_bend); - std::swap(next, previous); + std::swap(start_, end_); + std::swap(altered_start_, altered_end_); + std::swap(start_bend_, end_bend_); + std::swap(next_, previous_); } void Infill::InfillLineSegment::appendTo(PolygonRef& result_polyline, const bool include_start) { if (include_start) { - result_polyline.add(altered_start); + result_polyline.add(altered_start_); } - if (start_bend.has_value()) + if (start_bend_.has_value()) { - result_polyline.add(start_bend.value()); + result_polyline.add(start_bend_.value()); } - if (end_bend.has_value()) + if (end_bend_.has_value()) { - result_polyline.add(end_bend.value()); + result_polyline.add(end_bend_.value()); } - result_polyline.add(altered_end); + result_polyline.add(altered_end_); } } // namespace cura diff --git a/src/infill/ZigzagConnectorProcessor.cpp b/src/infill/ZigzagConnectorProcessor.cpp index 4bab85b550..1853ff77a5 100644 --- a/src/infill/ZigzagConnectorProcessor.cpp +++ b/src/infill/ZigzagConnectorProcessor.cpp @@ -9,13 +9,13 @@ using namespace cura; void ZigzagConnectorProcessor::registerVertex(const Point& vertex) { - if (is_first_connector) + if (is_first_connector_) { - first_connector.push_back(vertex); + first_connector_.push_back(vertex); } else { // it's yet unclear whether the polygon segment should be included, so we store it until we know - current_connector.push_back(vertex); + current_connector_.push_back(vertex); } } @@ -41,7 +41,7 @@ bool ZigzagConnectorProcessor::shouldAddCurrentConnector(int start_scanline_idx, const bool is_this_endpiece = start_scanline_idx == end_scanline_idx; const bool is_this_connection_even = start_scanline_idx % 2 == 0; bool should_skip_this_connection = false; - if (skip_some_zags && zag_skip_count > 0) + if (skip_some_zags_ && zag_skip_count_ > 0) { // // Here is an illustration of how the zags will be removed. @@ -68,17 +68,17 @@ bool ZigzagConnectorProcessor::shouldAddCurrentConnector(int start_scanline_idx, // if (direction > 0) { - should_skip_this_connection = start_scanline_idx % zag_skip_count == 0; + should_skip_this_connection = start_scanline_idx % zag_skip_count_ == 0; } else { - should_skip_this_connection = (start_scanline_idx - 1) % zag_skip_count == 0; + should_skip_this_connection = (start_scanline_idx - 1) % zag_skip_count_ == 0; } } const bool should_add = (is_this_connection_even && !is_this_endpiece && !should_skip_this_connection) // normal connections that should be added - || (use_endpieces && is_this_endpiece); // end piece if it is enabled; + || (use_endpieces_ && is_this_endpiece); // end piece if it is enabled; return should_add; } @@ -86,50 +86,50 @@ bool ZigzagConnectorProcessor::shouldAddCurrentConnector(int start_scanline_idx, void ZigzagConnectorProcessor::registerScanlineSegmentIntersection(const Point& intersection, int scanline_index) { - if (is_first_connector) + if (is_first_connector_) { // process as the first connector if we haven't found one yet // this will be processed with the last remaining piece at the end (when the polygon finishes) - first_connector.push_back(intersection); - first_connector_end_scanline_index = scanline_index; - is_first_connector = false; + first_connector_.push_back(intersection); + first_connector_end_scanline_index_ = scanline_index; + is_first_connector_ = false; } else { // add the current connector if needed - if (shouldAddCurrentConnector(last_connector_index, scanline_index)) + if (shouldAddCurrentConnector(last_connector_index_, scanline_index)) { - const bool is_this_endpiece = scanline_index == last_connector_index; - current_connector.push_back(intersection); - addZagConnector(current_connector, is_this_endpiece); + const bool is_this_endpiece = scanline_index == last_connector_index_; + current_connector_.push_back(intersection); + addZagConnector(current_connector_, is_this_endpiece); } } // update state - current_connector.clear(); // we're starting a new (odd) zigzag connector, so clear the old one - current_connector.push_back(intersection); - last_connector_index = scanline_index; + current_connector_.clear(); // we're starting a new (odd) zigzag connector, so clear the old one + current_connector_.push_back(intersection); + last_connector_index_ = scanline_index; } void ZigzagConnectorProcessor::registerPolyFinished() { - int scanline_start_index = last_connector_index; - int scanline_end_index = first_connector_end_scanline_index; - const bool is_endpiece = is_first_connector || (!is_first_connector && scanline_start_index == scanline_end_index); + int scanline_start_index = last_connector_index_; + int scanline_end_index = first_connector_end_scanline_index_; + const bool is_endpiece = is_first_connector_ || (!is_first_connector_ && scanline_start_index == scanline_end_index); // decides whether to add this zag according to the following rules - if ((is_endpiece && use_endpieces) + if ((is_endpiece && use_endpieces_) || (!is_endpiece && shouldAddCurrentConnector(scanline_start_index, scanline_end_index))) { // for convenience, put every point in one vector - for (const Point& point : first_connector) + for (const Point& point : first_connector_) { - current_connector.push_back(point); + current_connector_.push_back(point); } - first_connector.clear(); + first_connector_.clear(); - addZagConnector(current_connector, is_endpiece); + addZagConnector(current_connector_, is_endpiece); } // reset member variables @@ -145,7 +145,7 @@ void ZigzagConnectorProcessor::addZagConnector(std::vector& points, bool return; } Polygon polyline(points); - if (is_endpiece && !connected_endpieces) + if (is_endpiece && !connected_endpieces_) { polyline.pop_back(); } From 32d17c54643dec09dc39902efaefb4d14f88f49a Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Tue, 21 Nov 2023 11:14:48 +0100 Subject: [PATCH 13/48] Fix variable shadowing warnings --- include/Application.h | 20 +- include/plugins/pluginproxy.h | 2 +- include/utils/ThreadPool.h | 196 ++++++++++-------- src/Application.cpp | 60 +++--- src/FffGcodeWriter.cpp | 98 ++++----- src/FffPolygonGenerator.cpp | 34 +-- src/InterlockingGenerator.cpp | 4 +- src/LayerPlan.cpp | 34 +-- src/LayerPlanBuffer.cpp | 30 +-- src/Mold.cpp | 2 +- src/Preheat.cpp | 8 +- src/PrimeTower.cpp | 14 +- src/Scene.cpp | 4 +- src/SkirtBrim.cpp | 20 +- src/communication/ArcusCommunication.cpp | 4 +- .../ArcusCommunicationPrivate.cpp | 6 +- src/communication/CommandLine.cpp | 6 +- src/gcodeExport.cpp | 60 +++--- src/multiVolumes.cpp | 2 +- src/progress/Progress.cpp | 2 +- src/raft.cpp | 14 +- src/settings/AdaptiveLayerHeights.cpp | 4 +- src/settings/PathConfigStorage.cpp | 40 ++-- src/settings/Settings.cpp | 8 +- src/sliceDataStorage.cpp | 30 +-- src/slicer.cpp | 2 +- src/support.cpp | 30 +-- tests/GCodeExportTest.cpp | 60 +++--- tests/LayerPlanTest.cpp | 8 +- tests/arcus/ArcusCommunicationPrivateTest.cpp | 22 +- tests/integration/SlicePhaseTest.cpp | 8 +- tests/settings/SettingsTest.cpp | 6 +- 32 files changed, 433 insertions(+), 405 deletions(-) diff --git a/include/Application.h b/include/Application.h index 4a3f793daf..a301f3565b 100644 --- a/include/Application.h +++ b/include/Application.h @@ -4,12 +4,12 @@ #ifndef APPLICATION_H #define APPLICATION_H -#include "utils/NoCopy.h" - #include #include #include +#include "utils/NoCopy.h" + namespace cura { @@ -38,19 +38,21 @@ class Application : NoCopy * can assume that it is safe to access this without checking whether it is * initialised. */ - Communication* communication = nullptr; + Communication* communication_ = nullptr; /* * \brief The slice that is currently ongoing. * * If no slice has started yet, this will be a nullptr. */ - Slice* current_slice = nullptr; + Slice* current_slice_ = nullptr; /*! * \brief ThreadPool with lifetime tied to Application */ - ThreadPool* thread_pool = nullptr; + ThreadPool* thread_pool_ = nullptr; + + std::string instance_uuid_; /*! * Gets the instance of this application class. @@ -92,8 +94,6 @@ class Application : NoCopy */ void startThreadPool(int nworkers = 0); - std::string instance_uuid; - protected: #ifdef ARCUS /*! @@ -120,13 +120,13 @@ class Application : NoCopy /* * \brief The number of arguments that the application was called with. */ - size_t argc; + size_t argc_; /* * \brief An array of C strings containing the arguments that the * application was called with. */ - char** argv; + char** argv_; /*! * \brief Constructs a new Application instance. @@ -147,4 +147,4 @@ class Application : NoCopy } // namespace cura -#endif // APPLICATION_H \ No newline at end of file +#endif // APPLICATION_H diff --git a/include/plugins/pluginproxy.h b/include/plugins/pluginproxy.h index 2ff7b5c0c3..3059287b4a 100644 --- a/include/plugins/pluginproxy.h +++ b/include/plugins/pluginproxy.h @@ -341,7 +341,7 @@ class PluginProxy rsp_converter_type rsp_{}; ///< The Invoke response converter object. slot_metadata slot_info_{ .slot_id = SlotID, .version = SlotVersion.value, - .engine_uuid = Application::getInstance().instance_uuid }; ///< Holds information about the plugin slot. + .engine_uuid = Application::getInstance().instance_uuid_ }; ///< Holds information about the plugin slot. std::optional plugin_info_{ std::optional(std::nullopt) }; ///< Optional object that holds the plugin metadata, set after handshake }; diff --git a/include/utils/ThreadPool.h b/include/utils/ThreadPool.h index 28f17b8080..ed8db06c92 100644 --- a/include/utils/ThreadPool.h +++ b/include/utils/ThreadPool.h @@ -1,12 +1,9 @@ -//Copyright (c) 2021 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2021 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef THREADPOOL_H #define THREADPOOL_H -#include "../Application.h" // accessing singleton's Application::thread_pool -#include "../utils/math.h" // round_up_divide - #include #include #include @@ -15,6 +12,9 @@ #include #include +#include "../Application.h" // accessing singleton's Application::thread_pool +#include "../utils/math.h" // round_up_divide + namespace cura { @@ -27,20 +27,29 @@ namespace cura */ class ThreadPool { - public: +public: using lock_t = std::unique_lock; using task_t = std::function; //! Spawns a thread pool with `nthreads` threads ThreadPool(size_t nthreads); - ~ThreadPool() { join(); } + ~ThreadPool() + { + join(); + } //! Returns the number of threads - size_t thread_count() const { return threads.size(); } + size_t thread_count() const + { + return threads.size(); + } //! Gets a lock on the queue, stopping the queuing or execution of new tasks while held - lock_t get_lock() { return lock_t(mutex); } + lock_t get_lock() + { + return lock_t(mutex); + } /*! * \brief Pushes a new task while the queue is locked. @@ -58,12 +67,13 @@ class ThreadPool * \brief Executes pending tasks while the predicates returns true * This method doesn't wait unless predicate does (like implementation of ThreadPool::worker()) */ - template void work_while(lock_t& lock, P predicate) + template + void work_while(lock_t& lock, P predicate) { assert(lock); - while(predicate() && !tasks.empty()) // Order is important: predicate() might wait on an empty queue + while (predicate() && ! tasks.empty()) // Order is important: predicate() might wait on an empty queue { - assert(!tasks.empty()); + assert(! tasks.empty()); task_t task = std::move(tasks.front()); tasks.pop_front(); @@ -72,7 +82,7 @@ class ThreadPool } } - private: +private: void worker(); void join(); @@ -86,10 +96,11 @@ class ThreadPool /// `std::make_signed_t` fails for non integral types in a way that doesn't allows SFINAE fallbacks. This alias solves that. -template using make_signed_if_integral_t = typename std::enable_if_t, std::make_signed>::type; +template +using make_signed_if_integral_t = typename std::enable_if_t, std::make_signed>::type; /// Overloads `std::distance()` to work on integral types -template> +template> inline Signed distance(const Int& first, const Int& last) { return static_cast(last) - static_cast(first); @@ -109,7 +120,7 @@ inline Signed distance(const Int& first, const Int& last) * \param chunks_per_worker Maximum number of tasks that are queue at once (defaults to 4 times the number of workers). */ template -void parallel_for(T first, T last, F&& loop_body, size_t chunk_size_factor=1, const size_t chunks_per_worker=8) +void parallel_for(T first, T last, F&& loop_body, size_t chunk_size_factor = 1, const size_t chunks_per_worker = 8) { using lock_t = ThreadPool::lock_t; @@ -121,7 +132,7 @@ void parallel_for(T first, T last, F&& loop_body, size_t chunk_size_factor=1, co } const size_t nitems = dist; - ThreadPool* const thread_pool = Application::getInstance().thread_pool; + ThreadPool* const thread_pool = Application::getInstance().thread_pool_; assert(thread_pool); const size_t nworkers = thread_pool->thread_count() + 1; // One task per std::thread + 1 for main thread @@ -132,7 +143,7 @@ void parallel_for(T first, T last, F&& loop_body, size_t chunk_size_factor=1, co blocks = nitems; } else - { // User wants to divide the work in blocks of chunk_size_factor items + { // User wants to divide the work in blocks of chunk_size_factor items blocks = round_up_divide(nitems, chunk_size_factor); } @@ -155,21 +166,23 @@ void parallel_for(T first, T last, F&& loop_body, size_t chunk_size_factor=1, co // Schedules a task per chunk on the thread pool lock_t lock = thread_pool->get_lock(); T chunk_last; - for (T chunk_first = first ; chunk_first < last ; chunk_first = chunk_last) + for (T chunk_first = first; chunk_first < last; chunk_first = chunk_last) { if (distance(chunk_first, last) > chunk_increment) - { // Full size chunk + { // Full size chunk chunk_last = chunk_first + chunk_increment; } else - { // Adjust for the size of the last chunk + { // Adjust for the size of the last chunk chunk_last = last; } - thread_pool->push(lock, [&shared_state, chunk_first, chunk_last](lock_t& th_lock) + thread_pool->push( + lock, + [&shared_state, chunk_first, chunk_last](lock_t& th_lock) { th_lock.unlock(); // Enter unsynchronized region - for (T i = chunk_first ; i < chunk_last ; ++i) + for (T i = chunk_first; i < chunk_last; ++i) { shared_state.loop_body(i); } @@ -182,8 +195,13 @@ void parallel_for(T first, T last, F&& loop_body, size_t chunk_size_factor=1, co } // Do work while parallel_for's tasks are running - thread_pool->work_while(lock, [&]{ return shared_state.chunks_remaining > 0; }); - while(shared_state.chunks_remaining > 0) // Wait until all the task are completed + thread_pool->work_while( + lock, + [&] + { + return shared_state.chunks_remaining > 0; + }); + while (shared_state.chunks_remaining > 0) // Wait until all the task are completed { shared_state.work_done.wait(lock); } @@ -194,15 +212,15 @@ void parallel_for(T first, T last, F&& loop_body, size_t chunk_size_factor=1, co * Overload for iterating over containers with random access iterators. */ template -auto parallel_for(Container& container, F&& loop_body, size_t chunk_size_factor=1, size_t chunks_per_worker=8) - -> std::void_t +auto parallel_for(Container& container, F&& loop_body, size_t chunk_size_factor = 1, size_t chunks_per_worker = 8) -> std::void_t { parallel_for(container.begin(), container.end(), std::forward(loop_body), chunk_size_factor, chunks_per_worker); } //! \private Internal state for run_multiple_producers_ordered_consumer() -template class MultipleProducersOrderedConsumer; +template +class MultipleProducersOrderedConsumer; /*! * \brief Runs parallel producers and buffers the results to be consumed serially in indices order. @@ -223,9 +241,9 @@ template class MultipleProducersOrderedCon * \param max_pending_per_worker Number of allocated slots per worker for items waiting to be consumed. */ template -void run_multiple_producers_ordered_consumer(ptrdiff_t first, ptrdiff_t last, P&& producer, C&& consumer, size_t max_pending_per_worker=8) +void run_multiple_producers_ordered_consumer(ptrdiff_t first, ptrdiff_t last, P&& producer, C&& consumer, size_t max_pending_per_worker = 8) { - ThreadPool* thread_pool = Application::getInstance().thread_pool; + ThreadPool* thread_pool = Application::getInstance().thread_pool_; assert(thread_pool); assert(max_pending_per_worker > 0); const size_t max_pending = max_pending_per_worker * (thread_pool->thread_count() + 1); @@ -238,59 +256,69 @@ class MultipleProducersOrderedConsumer using item_t = std::invoke_result_t; using lock_t = ThreadPool::lock_t; - public: +public: /*! * \see run_multiple_producers_ordered_consumer * \param max_pending Number of allocated slots for items waiting to be consumed. */ template MultipleProducersOrderedConsumer(ptrdiff_t first, ptrdiff_t last, P&& producer, C&& consumer, size_t max_pending) - : producer(std::forward

(producer)), consumer(std::forward(consumer)), - max_pending(max_pending), - queue(std::make_unique(max_pending)), - last_idx(last), write_idx(first), read_idx(first), consumer_wait_idx(first) - {} + : producer_(std::forward

(producer)) + , consumer_(std::forward(consumer)) + , max_pending_(max_pending) + , queue_(std::make_unique(max_pending)) + , last_idx_(last) + , write_idx_(first) + , read_idx_(first) + , consumer_wait_idx_(first) + { + } //! Schedules the tasks on thread_pool, then run one on the main thread until completion. void run(ThreadPool& thread_pool) { - if (write_idx >= last_idx) + if (write_idx_ >= last_idx_) { return; } - workers_count = thread_pool.thread_count() + 1; + workers_count_ = thread_pool.thread_count() + 1; // Start thread_pool.thread_count() workers on the thread pool auto lock = thread_pool.get_lock(); - for (size_t i = 1 ; i < workers_count ; i++) + for (size_t i = 1; i < workers_count_; i++) { - thread_pool.push(lock, [this](lock_t& th_lock){ worker(th_lock); }); + thread_pool.push( + lock, + [this](lock_t& th_lock) + { + worker(th_lock); + }); } // Run a worker on the main thread worker(lock); // Wait for completion of all workers - if (workers_count > 0) + if (workers_count_ > 0) { - work_done_cond.wait(lock); + work_done_cond_.wait(lock); } } - protected: +protected: //! Waits for free space in the ring. Returns false when work is completed. bool wait(lock_t& lock) { - while(true) + while (true) { - if (write_idx >= last_idx) - { // Work completed: stop worker + if (write_idx_ >= last_idx_) + { // Work completed: stop worker return false; } - if (write_idx - read_idx < max_pending) - { // Continue as a producer + if (write_idx_ - read_idx_ < max_pending_) + { // Continue as a producer return true; } else - { // Queue is full, wait for consumer signal - free_slot_cond.wait(lock); // Signaled by consume_many() and worker() completion + { // Queue is full, wait for consumer signal + free_slot_cond_.wait(lock); // Signaled by consume_many() and worker() completion } } } @@ -298,16 +326,16 @@ class MultipleProducersOrderedConsumer //! Produces an item and store in in the ring buffer. Assumes that there is items to produce and free space in the ring ptrdiff_t produce(lock_t& lock) { - ptrdiff_t produced_idx = write_idx++; - item_t* slot = &queue[(produced_idx + max_pending) % max_pending]; - assert(produced_idx < last_idx); + ptrdiff_t produced_idx = write_idx_++; + item_t* slot = &queue_[(produced_idx + max_pending_) % max_pending_]; + assert(produced_idx < last_idx_); // Unlocks global mutex while producing an item lock.unlock(); - item_t item = producer(produced_idx); + item_t item = producer_(produced_idx); lock.lock(); - assert(!*slot); + assert(! *slot); *slot = std::move(item); assert(*slot); @@ -317,68 +345,68 @@ class MultipleProducersOrderedConsumer //! Consumes items, until an empty slot (not yet produced) is found. void consume_many(lock_t& lock) { - assert(read_idx < write_idx); - for (item_t* slot = &queue[(read_idx + max_pending) % max_pending]; *slot ; slot = &queue[(read_idx + max_pending) % max_pending]) + assert(read_idx_ < write_idx_); + for (item_t* slot = &queue_[(read_idx_ + max_pending_) % max_pending_]; *slot; slot = &queue_[(read_idx_ + max_pending_) % max_pending_]) { // Unlocks global mutex while consuming an item lock.unlock(); - consumer(std::move(*slot)); + consumer_(std::move(*slot)); *slot = {}; lock.lock(); // Increment read index and signal a waiting worker if there is one - bool queue_was_full = write_idx - read_idx >= max_pending; - read_idx++; + bool queue_was_full = write_idx_ - read_idx_ >= max_pending_; + read_idx_++; // Notify producers that are waiting for a queue slot if (queue_was_full) { - free_slot_cond.notify_one(); + free_slot_cond_.notify_one(); } } - consumer_wait_idx = read_idx; // The producer filling this slot will resume consumption + consumer_wait_idx_ = read_idx_; // The producer filling this slot will resume consumption } //! Task pushed on the ThreadPool void worker(lock_t& lock) { - while(wait(lock)) // While there is work to do + while (wait(lock)) // While there is work to do { ptrdiff_t produced_idx = produce(lock); - if (produced_idx == consumer_wait_idx) - { // This thread just produced the item that was waited for by the consumer + if (produced_idx == consumer_wait_idx_) + { // This thread just produced the item that was waited for by the consumer consume_many(lock); // Consume a contiguous block starting at consumer_wait_idx } } // Notify eventual workers waiting for a free slot but never got one during the interval of producing the last items - free_slot_cond.notify_all(); + free_slot_cond_.notify_all(); - if (--workers_count == 0) - { // Last worker exiting: signal run() about workers completion - work_done_cond.notify_one(); + if (--workers_count_ == 0) + { // Last worker exiting: signal run() about workers completion + work_done_cond_.notify_one(); } } // Tracks worker completion - size_t workers_count; - std::condition_variable work_done_cond; - - Producer producer; - Consumer consumer; - const ptrdiff_t max_pending; // Number of produced items that can wait in the queue - const std::unique_ptr queue; // Ring buffer mapping each intermediary result to a slot - const ptrdiff_t last_idx; - - ptrdiff_t write_idx; // Next slot to produce - ptrdiff_t read_idx; // Next slot to consume - ptrdiff_t consumer_wait_idx; // First slot that is waited for by the consumer - std::condition_variable free_slot_cond; // Condition to wait for available space in the buffer + size_t workers_count_; + std::condition_variable work_done_cond_; + + Producer producer_; + Consumer consumer_; + const ptrdiff_t max_pending_; // Number of produced items that can wait in the queue + const std::unique_ptr queue_; // Ring buffer mapping each intermediary result to a slot + const ptrdiff_t last_idx_; + + ptrdiff_t write_idx_; // Next slot to produce + ptrdiff_t read_idx_; // Next slot to consume + ptrdiff_t consumer_wait_idx_; // First slot that is waited for by the consumer + std::condition_variable free_slot_cond_; // Condition to wait for available space in the buffer }; //! \private Template deduction guide: defaults to inlining closures into the class layout template -MultipleProducersOrderedConsumer(ptrdiff_t, ptrdiff_t, P , C, size_t) -> MultipleProducersOrderedConsumer; +MultipleProducersOrderedConsumer(ptrdiff_t, ptrdiff_t, P, C, size_t) -> MultipleProducersOrderedConsumer; -} //Cura namespace. +} // namespace cura #endif // THREADPOOL_H diff --git a/src/Application.cpp b/src/Application.cpp index 0074940150..440bb09f3c 100644 --- a/src/Application.cpp +++ b/src/Application.cpp @@ -3,13 +3,9 @@ #include "Application.h" -#include "FffProcessor.h" -#include "communication/ArcusCommunication.h" //To connect via Arcus to the front-end. -#include "communication/CommandLine.h" //To use the command line to slice stuff. -#include "plugins/slots.h" -#include "progress/Progress.h" -#include "utils/ThreadPool.h" -#include "utils/string.h" //For stringcasecompare. +#include +#include +#include #include //For generating a UUID. #include //For generating a UUID. @@ -22,15 +18,19 @@ #include #include -#include -#include -#include +#include "FffProcessor.h" +#include "communication/ArcusCommunication.h" //To connect via Arcus to the front-end. +#include "communication/CommandLine.h" //To use the command line to slice stuff. +#include "plugins/slots.h" +#include "progress/Progress.h" +#include "utils/ThreadPool.h" +#include "utils/string.h" //For stringcasecompare. namespace cura { Application::Application() - : instance_uuid(boost::uuids::to_string(boost::uuids::random_generator()())) + : instance_uuid_(boost::uuids::to_string(boost::uuids::random_generator()())) { auto dup_sink = std::make_shared(std::chrono::seconds{ 10 }); auto base_sink = std::make_shared(); @@ -47,8 +47,8 @@ Application::Application() Application::~Application() { - delete communication; - delete thread_pool; + delete communication_; + delete thread_pool_; } Application& Application::getInstance() @@ -64,7 +64,7 @@ void Application::connect() int port = 49674; // Parse port number from IP address. - std::string ip_port(argv[2]); + std::string ip_port(argv_[2]); std::size_t found_pos = ip_port.find(':'); if (found_pos != std::string::npos) { @@ -74,9 +74,9 @@ void Application::connect() int n_threads; - for (size_t argn = 3; argn < argc; argn++) + for (size_t argn = 3; argn < argc_; argn++) { - char* str = argv[argn]; + char* str = argv_[argn]; if (str[0] == '-') { for (str++; *str; str++) @@ -104,13 +104,13 @@ void Application::connect() ArcusCommunication* arcus_communication = new ArcusCommunication(); arcus_communication->connect(ip, port); - communication = arcus_communication; + communication_ = arcus_communication; } #endif // ARCUS void Application::printCall() const { - spdlog::error("Command called: {}", *argv); + spdlog::error("Command called: {}", *argv_); } void Application::printHelp() const @@ -171,18 +171,18 @@ void Application::printLicense() const void Application::slice() { std::vector arguments; - for (size_t argument_index = 0; argument_index < argc; argument_index++) + for (size_t argument_index = 0; argument_index < argc_; argument_index++) { - arguments.emplace_back(argv[argument_index]); + arguments.emplace_back(argv_[argument_index]); } - communication = new CommandLine(arguments); + communication_ = new CommandLine(arguments); } void Application::run(const size_t argc, char** argv) { - this->argc = argc; - this->argv = argv; + argc_ = argc; + argv_ = argv; printLicense(); Progress::init(); @@ -216,7 +216,7 @@ void Application::run(const size_t argc, char** argv) exit(1); } - if (! communication) + if (! communication_) { // No communication channel is open any more, so either: //- communication failed to connect, or @@ -225,9 +225,9 @@ void Application::run(const size_t argc, char** argv) exit(0); } startThreadPool(); // Start the thread pool - while (communication->hasSlice()) + while (communication_->hasSlice()) { - communication->sliceNext(); + communication_->sliceNext(); } } @@ -236,7 +236,7 @@ void Application::startThreadPool(int nworkers) size_t nthreads; if (nworkers <= 0) { - if (thread_pool) + if (thread_pool_) { return; // Keep the previous ThreadPool } @@ -246,12 +246,12 @@ void Application::startThreadPool(int nworkers) { nthreads = nworkers - 1; // Minus one for the main thread } - if (thread_pool && thread_pool->thread_count() == nthreads) + if (thread_pool_ && thread_pool_->thread_count() == nthreads) { return; // Keep the previous ThreadPool } - delete thread_pool; - thread_pool = new ThreadPool(nthreads); + delete thread_pool_; + thread_pool_ = new ThreadPool(nthreads); } } // namespace cura diff --git a/src/FffGcodeWriter.cpp b/src/FffGcodeWriter.cpp index 406b365eab..52aa1cd876 100644 --- a/src/FffGcodeWriter.cpp +++ b/src/FffGcodeWriter.cpp @@ -41,7 +41,7 @@ namespace cura FffGcodeWriter::FffGcodeWriter() : max_object_height(0) , layer_plan_buffer(gcode) - , slice_uuid(Application::getInstance().instance_uuid) + , slice_uuid(Application::getInstance().instance_uuid_) { for (unsigned int extruder_nr = 0; extruder_nr < MAX_EXTRUDERS; extruder_nr++) { // initialize all as max layer_nr, so that they get updated to the lowest layer on which they are used. @@ -81,14 +81,14 @@ void FffGcodeWriter::writeGCode(SliceDataStorage& storage, TimeKeeper& time_keep gcode.preSetup(start_extruder_nr); gcode.setSliceUUID(slice_uuid); - Scene& scene = Application::getInstance().current_slice->scene; + Scene& scene = Application::getInstance().current_slice_->scene; if (scene.current_mesh_group == scene.mesh_groups.begin()) // First mesh group. { gcode.resetTotalPrintTimeAndFilament(); gcode.setInitialAndBuildVolumeTemps(start_extruder_nr); } - Application::getInstance().communication->beginGCode(); + Application::getInstance().communication_->beginGCode(); setConfigFanSpeedLayerTime(); @@ -131,7 +131,7 @@ void FffGcodeWriter::writeGCode(SliceDataStorage& storage, TimeKeeper& time_keep gcode.writeLayerCountComment(total_layers); { // calculate the mesh order for each extruder - const size_t extruder_count = Application::getInstance().current_slice->scene.extruders.size(); + const size_t extruder_count = Application::getInstance().current_slice_->scene.extruders.size(); mesh_order_per_extruder.clear(); // Might be not empty in case of sequential printing. mesh_order_per_extruder.reserve(extruder_count); for (size_t extruder_nr = 0; extruder_nr < extruder_count; extruder_nr++) @@ -298,7 +298,7 @@ void FffGcodeWriter::findLayerSeamsForSpiralize(SliceDataStorage& storage, size_ void FffGcodeWriter::setConfigFanSpeedLayerTime() { - for (const ExtruderTrain& train : Application::getInstance().current_slice->scene.extruders) + for (const ExtruderTrain& train : Application::getInstance().current_slice_->scene.extruders) { fan_speed_layer_time_settings_per_extruder.emplace_back(); FanSpeedLayerTimeSettings& fan_speed_layer_time_settings = fan_speed_layer_time_settings_per_extruder.back(); @@ -370,7 +370,7 @@ static void retractionAndWipeConfigFromSettings(const Settings& settings, Retrac void FffGcodeWriter::setConfigRetractionAndWipe(SliceDataStorage& storage) { - Scene& scene = Application::getInstance().current_slice->scene; + Scene& scene = Application::getInstance().current_slice_->scene; for (size_t extruder_index = 0; extruder_index < scene.extruders.size(); extruder_index++) { ExtruderTrain& train = scene.extruders[extruder_index]; @@ -384,7 +384,7 @@ void FffGcodeWriter::setConfigRetractionAndWipe(SliceDataStorage& storage) size_t FffGcodeWriter::getStartExtruder(const SliceDataStorage& storage) { - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; const EPlatformAdhesion adhesion_type = mesh_group_settings.get("adhesion_type"); const int skirt_brim_extruder_nr = mesh_group_settings.get("skirt_brim_extruder_nr"); const ExtruderTrain* skirt_brim_extruder = (skirt_brim_extruder_nr < 0) ? nullptr : &mesh_group_settings.get("skirt_brim_extruder_nr"); @@ -425,7 +425,7 @@ size_t FffGcodeWriter::getStartExtruder(const SliceDataStorage& storage) } } } - assert(start_extruder_nr < Application::getInstance().current_slice->scene.extruders.size() && "start_extruder_nr must be a valid extruder"); + assert(start_extruder_nr < Application::getInstance().current_slice_->scene.extruders.size() && "start_extruder_nr must be a valid extruder"); return start_extruder_nr; } @@ -479,7 +479,7 @@ void FffGcodeWriter::setInfillAndSkinAngles(SliceMeshStorage& mesh) void FffGcodeWriter::setSupportAngles(SliceDataStorage& storage) { - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; const ExtruderTrain& support_infill_extruder = mesh_group_settings.get("support_infill_extruder_nr"); storage.support.support_infill_angles = support_infill_extruder.settings_.get>("support_infill_angles"); if (storage.support.support_infill_angles.empty()) @@ -513,7 +513,7 @@ void FffGcodeWriter::setSupportAngles(SliceDataStorage& storage) for (const auto& mesh : storage.meshes) { if (mesh->settings.get(interface_height_setting) - >= 2 * Application::getInstance().current_slice->scene.current_mesh_group->settings.get("layer_height")) + >= 2 * Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("layer_height")) { // Some roofs are quite thick. // Alternate between the two kinds of diagonal: / and \ . @@ -544,17 +544,17 @@ void FffGcodeWriter::processNextMeshGroupCode(const SliceDataStorage& storage) gcode.writeFanCommand(0); gcode.setZ(max_object_height + MM2INT(5)); - Application::getInstance().communication->sendCurrentPosition(gcode.getPositionXY()); - gcode.writeTravel(gcode.getPositionXY(), Application::getInstance().current_slice->scene.extruders[gcode.getExtruderNr()].settings_.get("speed_travel")); + Application::getInstance().communication_->sendCurrentPosition(gcode.getPositionXY()); + gcode.writeTravel(gcode.getPositionXY(), Application::getInstance().current_slice_->scene.extruders[gcode.getExtruderNr()].settings_.get("speed_travel")); Point start_pos(storage.model_min.x_, storage.model_min.y_); - gcode.writeTravel(start_pos, Application::getInstance().current_slice->scene.extruders[gcode.getExtruderNr()].settings_.get("speed_travel")); + gcode.writeTravel(start_pos, Application::getInstance().current_slice_->scene.extruders[gcode.getExtruderNr()].settings_.get("speed_travel")); gcode.processInitialLayerTemperature(storage, gcode.getExtruderNr()); } void FffGcodeWriter::processRaft(const SliceDataStorage& storage) { - Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; const size_t base_extruder_nr = mesh_group_settings.get("raft_base_extruder_nr").extruder_nr_; const size_t interface_extruder_nr = mesh_group_settings.get("raft_interface_extruder_nr").extruder_nr_; const size_t surface_extruder_nr = mesh_group_settings.get("raft_surface_extruder_nr").extruder_nr_; @@ -600,7 +600,7 @@ void FffGcodeWriter::processRaft(const SliceDataStorage& storage) = *new LayerPlan(storage, layer_nr, z, layer_height, base_extruder_nr, fan_speed_layer_time_settings_per_extruder_raft_base, comb_offset, line_width, avoid_distance); gcode_layer.setIsInside(true); - Application::getInstance().communication->sendLayerComplete(layer_nr, z, layer_height); + Application::getInstance().communication_->sendLayerComplete(layer_nr, z, layer_height); Polygons raftLines; AngleDegrees fill_angle = (num_surface_layers + num_interface_layers) % 2 ? 45 : 135; // 90 degrees rotated from the interface layer. @@ -756,7 +756,7 @@ void FffGcodeWriter::processRaft(const SliceDataStorage& storage) current_extruder_nr = interface_extruder_nr; } - Application::getInstance().communication->sendLayerComplete(layer_nr, z, interface_layer_height); + Application::getInstance().communication_->sendLayerComplete(layer_nr, z, interface_layer_height); Polygons raft_outline_path; const coord_t small_offset = gcode_layer.configs_storage.raft_interface_config.getLineWidth() @@ -875,7 +875,7 @@ void FffGcodeWriter::processRaft(const SliceDataStorage& storage) setExtruder_addPrime(storage, gcode_layer, surface_extruder_nr); current_extruder_nr = surface_extruder_nr; } - Application::getInstance().communication->sendLayerComplete(layer_nr, z, surface_layer_height); + Application::getInstance().communication_->sendLayerComplete(layer_nr, z, surface_layer_height); Polygons raft_outline_path; const coord_t small_offset = gcode_layer.configs_storage.raft_interface_config.getLineWidth() @@ -952,7 +952,7 @@ FffGcodeWriter::ProcessLayerResult FffGcodeWriter::processLayer(const SliceDataS TimeKeeper time_keeper; spdlog::stopwatch timer_total; - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; coord_t layer_thickness = mesh_group_settings.get("layer_height"); coord_t z; bool include_helper_parts = true; @@ -988,7 +988,7 @@ FffGcodeWriter::ProcessLayerResult FffGcodeWriter::processLayer(const SliceDataS } } - const Scene& scene = Application::getInstance().current_slice->scene; + const Scene& scene = Application::getInstance().current_slice_->scene; coord_t avoid_distance = 0; // minimal avoid distance is zero const std::vector extruder_is_used = storage.getExtrudersUsed(); @@ -1138,7 +1138,7 @@ bool FffGcodeWriter::getExtruderNeedPrimeBlobDuringFirstLayer(const SliceDataSto void FffGcodeWriter::processSkirtBrim(const SliceDataStorage& storage, LayerPlan& gcode_layer, unsigned int extruder_nr, LayerIndex layer_nr) const { - const ExtruderTrain& train = Application::getInstance().current_slice->scene.extruders[extruder_nr]; + const ExtruderTrain& train = Application::getInstance().current_slice_->scene.extruders[extruder_nr]; const int skirt_height = train.settings_.get("skirt_height"); const bool is_skirt = train.settings_.get("adhesion_type") == EPlatformAdhesion::SKIRT; // only create a multilayer SkirtBrim for a skirt for the height of skirt_height @@ -1300,7 +1300,7 @@ void FffGcodeWriter::processSkirtBrim(const SliceDataStorage& storage, LayerPlan // Add the support brim after the skirt_brim to gcode_layer // Support brim is only added in layer 0 // For support brim we don't care about the order, because support doesn't need to be accurate. - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; if ((layer_nr == 0) && (extruder_nr == mesh_group_settings.get("support_extruder_nr_layer_0").extruder_nr_)) { total_line_count += storage.support_brim.size(); @@ -1323,7 +1323,7 @@ void FffGcodeWriter::processSkirtBrim(const SliceDataStorage& storage, LayerPlan void FffGcodeWriter::processOozeShield(const SliceDataStorage& storage, LayerPlan& gcode_layer) const { LayerIndex layer_nr = std::max(LayerIndex{ 0 }, gcode_layer.getLayerNr()); - if (layer_nr == 0 && Application::getInstance().current_slice->scene.current_mesh_group->settings.get("adhesion_type") == EPlatformAdhesion::BRIM) + if (layer_nr == 0 && Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("adhesion_type") == EPlatformAdhesion::BRIM) { return; // ooze shield already generated by brim } @@ -1335,7 +1335,7 @@ void FffGcodeWriter::processOozeShield(const SliceDataStorage& storage, LayerPla void FffGcodeWriter::processDraftShield(const SliceDataStorage& storage, LayerPlan& gcode_layer) const { - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; const LayerIndex layer_nr = std::max(LayerIndex{ 0 }, gcode_layer.getLayerNr()); if (storage.draft_protection_shield.size() == 0) { @@ -1345,7 +1345,7 @@ void FffGcodeWriter::processDraftShield(const SliceDataStorage& storage, LayerPl { return; } - if (layer_nr == 0 && Application::getInstance().current_slice->scene.current_mesh_group->settings.get("adhesion_type") == EPlatformAdhesion::BRIM) + if (layer_nr == 0 && Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("adhesion_type") == EPlatformAdhesion::BRIM) { return; // draft shield already generated by brim } @@ -1369,7 +1369,7 @@ void FffGcodeWriter::calculateExtruderOrderPerLayer(const SliceDataStorage& stor { size_t last_extruder; // set the initial extruder of this meshgroup - Scene& scene = Application::getInstance().current_slice->scene; + Scene& scene = Application::getInstance().current_slice_->scene; if (scene.current_mesh_group == scene.mesh_groups.begin()) { // first meshgroup last_extruder = getStartExtruder(storage); @@ -1403,8 +1403,8 @@ void FffGcodeWriter::calculatePrimeLayerPerExtruder(const SliceDataStorage& stor std::vector FffGcodeWriter::getUsedExtrudersOnLayerExcludingStartingExtruder(const SliceDataStorage& storage, const size_t start_extruder, const LayerIndex& layer_nr) const { - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; - size_t extruder_count = Application::getInstance().current_slice->scene.extruders.size(); + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; + size_t extruder_count = Application::getInstance().current_slice_->scene.extruders.size(); assert(static_cast(extruder_count) > 0); std::vector ret; ret.push_back(start_extruder); @@ -1450,7 +1450,7 @@ std::vector FffGcodeWriter::calculateMeshOrder(const SliceDataStorage& s { OrderOptimizer mesh_idx_order_optimizer; - std::vector::iterator mesh_group = Application::getInstance().current_slice->scene.current_mesh_group; + std::vector::iterator mesh_group = Application::getInstance().current_slice_->scene.current_mesh_group; for (unsigned int mesh_idx = 0; mesh_idx < storage.meshes.size(); mesh_idx++) { const SliceMeshStorage& mesh = *storage.meshes[mesh_idx]; @@ -1461,7 +1461,7 @@ std::vector FffGcodeWriter::calculateMeshOrder(const SliceDataStorage& s mesh_idx_order_optimizer.addItem(Point(middle.x_, middle.y_), mesh_idx); } } - const ExtruderTrain& train = Application::getInstance().current_slice->scene.extruders[extruder_nr]; + const ExtruderTrain& train = Application::getInstance().current_slice_->scene.extruders[extruder_nr]; const Point layer_start_position(train.settings_.get("layer_start_x"), train.settings_.get("layer_start_y")); std::list mesh_indices_order = mesh_idx_order_optimizer.optimize(layer_start_position); @@ -1505,7 +1505,7 @@ void FffGcodeWriter::addMeshLayerToGCode_meshSurfaceMode(const SliceDataStorage& mesh.getZSeamHint(), mesh.settings.get("z_seam_corner"), mesh.settings.get("wall_line_width_0") * 2); - const bool spiralize = Application::getInstance().current_slice->scene.current_mesh_group->settings.get("magic_spiralize"); + const bool spiralize = Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("magic_spiralize"); gcode_layer.addPolygonsByOptimizer(polygons, mesh_config.inset0_config, z_seam_config, mesh.settings.get("wall_0_wipe_dist"), spiralize); addMeshOpenPolyLinesToGCode(mesh, mesh_config, gcode_layer); @@ -1585,7 +1585,7 @@ void FffGcodeWriter::addMeshPartToGCode( const SliceLayerPart& part, LayerPlan& gcode_layer) const { - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; bool added_something = false; @@ -2293,7 +2293,7 @@ bool FffGcodeWriter::processInsets( } bool spiralize = false; - if (Application::getInstance().current_slice->scene.current_mesh_group->settings.get("magic_spiralize")) + if (Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("magic_spiralize")) { const size_t initial_bottom_layers = mesh.settings.get("initial_bottom_layers"); const int layer_nr = gcode_layer.getLayerNr(); @@ -2350,7 +2350,7 @@ bool FffGcodeWriter::processInsets( // if support is enabled, add the support outlines also so we don't generate bridges over support - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; if (mesh_group_settings.get("support_enable")) { const coord_t z_distance_top = mesh.settings.get("support_top_distance"); @@ -2728,7 +2728,7 @@ void FffGcodeWriter::processTopBottom( { return; } - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; const size_t layer_nr = gcode_layer.getLayerNr(); @@ -3110,7 +3110,7 @@ bool FffGcodeWriter::addSupportToGCode(const SliceDataStorage& storage, LayerPla return support_added; } - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; const size_t support_roof_extruder_nr = mesh_group_settings.get("support_roof_extruder_nr").extruder_nr_; const size_t support_bottom_extruder_nr = mesh_group_settings.get("support_bottom_extruder_nr").extruder_nr_; size_t support_infill_extruder_nr = (gcode_layer.getLayerNr() <= 0) ? mesh_group_settings.get("support_extruder_nr_layer_0").extruder_nr_ @@ -3157,10 +3157,10 @@ bool FffGcodeWriter::processSupportInfill(const SliceDataStorage& storage, Layer return added_something; } - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; const size_t extruder_nr = (gcode_layer.getLayerNr() <= 0) ? mesh_group_settings.get("support_extruder_nr_layer_0").extruder_nr_ : mesh_group_settings.get("support_infill_extruder_nr").extruder_nr_; - const ExtruderTrain& infill_extruder = Application::getInstance().current_slice->scene.extruders[extruder_nr]; + const ExtruderTrain& infill_extruder = Application::getInstance().current_slice_->scene.extruders[extruder_nr]; coord_t default_support_line_distance = infill_extruder.settings_.get("support_line_distance"); @@ -3463,8 +3463,8 @@ bool FffGcodeWriter::addSupportRoofsToGCode( return false; // No need to generate support roof if there's no support. } - const size_t roof_extruder_nr = Application::getInstance().current_slice->scene.current_mesh_group->settings.get("support_roof_extruder_nr").extruder_nr_; - const ExtruderTrain& roof_extruder = Application::getInstance().current_slice->scene.extruders[roof_extruder_nr]; + const size_t roof_extruder_nr = Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("support_roof_extruder_nr").extruder_nr_; + const ExtruderTrain& roof_extruder = Application::getInstance().current_slice_->scene.extruders[roof_extruder_nr]; const EFillMethod pattern = roof_extruder.settings_.get("support_roof_pattern"); AngleDegrees fill_angle = 0; @@ -3592,8 +3592,8 @@ bool FffGcodeWriter::addSupportBottomsToGCode(const SliceDataStorage& storage, L return false; // No need to generate support bottoms if there's no support. } - const size_t bottom_extruder_nr = Application::getInstance().current_slice->scene.current_mesh_group->settings.get("support_bottom_extruder_nr").extruder_nr_; - const ExtruderTrain& bottom_extruder = Application::getInstance().current_slice->scene.extruders[bottom_extruder_nr]; + const size_t bottom_extruder_nr = Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("support_bottom_extruder_nr").extruder_nr_; + const ExtruderTrain& bottom_extruder = Application::getInstance().current_slice_->scene.extruders[bottom_extruder_nr]; const EFillMethod pattern = bottom_extruder.settings_.get("support_bottom_pattern"); AngleDegrees fill_angle = 0; @@ -3706,7 +3706,7 @@ void FffGcodeWriter::setExtruder_addPrime(const SliceDataStorage& storage, Layer { if (extruder_prime_layer_nr[extruder_nr] == gcode_layer.getLayerNr()) { - const ExtruderTrain& train = Application::getInstance().current_slice->scene.extruders[extruder_nr]; + const ExtruderTrain& train = Application::getInstance().current_slice_->scene.extruders[extruder_nr]; // We always prime an extruder, but whether it will be a prime blob/poop depends on if prime blob is enabled. // This is decided in GCodeExport::writePrimeTrain(). @@ -3735,7 +3735,7 @@ void FffGcodeWriter::setExtruder_addPrime(const SliceDataStorage& storage, Layer void FffGcodeWriter::addPrimeTower(const SliceDataStorage& storage, LayerPlan& gcode_layer, const size_t prev_extruder) const { - if (! Application::getInstance().current_slice->scene.current_mesh_group->settings.get("prime_tower_enable")) + if (! Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("prime_tower_enable")) { return; } @@ -3745,7 +3745,7 @@ void FffGcodeWriter::addPrimeTower(const SliceDataStorage& storage, LayerPlan& g void FffGcodeWriter::finalize() { - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; if (mesh_group_settings.get("machine_heated_bed")) { gcode.writeBedTemperatureCommand(0); // Cool down the bed (M140). @@ -3760,7 +3760,7 @@ void FffGcodeWriter::finalize() std::vector filament_used; std::vector material_ids; std::vector extruder_is_used; - const Scene& scene = Application::getInstance().current_slice->scene; + const Scene& scene = Application::getInstance().current_slice_->scene; for (size_t extruder_nr = 0; extruder_nr < scene.extruders.size(); extruder_nr++) { filament_used.emplace_back(gcode.getTotalFilamentUsed(extruder_nr)); @@ -3768,10 +3768,10 @@ void FffGcodeWriter::finalize() extruder_is_used.push_back(gcode.getExtruderIsUsed(extruder_nr)); } std::string prefix = gcode.getFileHeader(extruder_is_used, &print_time, filament_used, material_ids); - if (! Application::getInstance().communication->isSequential()) + if (! Application::getInstance().communication_->isSequential()) { - Application::getInstance().communication->sendGCodePrefix(prefix); - Application::getInstance().communication->sendSliceUUID(slice_uuid); + Application::getInstance().communication_->sendGCodePrefix(prefix); + Application::getInstance().communication_->sendSliceUUID(slice_uuid); } else { @@ -3798,7 +3798,7 @@ void FffGcodeWriter::finalize() // set extrusion mode back to "normal" gcode.resetExtrusionMode(); - for (size_t e = 0; e < Application::getInstance().current_slice->scene.extruders.size(); e++) + for (size_t e = 0; e < Application::getInstance().current_slice_->scene.extruders.size(); e++) { gcode.writeTemperatureCommand(e, 0, false); } diff --git a/src/FffPolygonGenerator.cpp b/src/FffPolygonGenerator.cpp index c4a7259538..dd9aedc002 100644 --- a/src/FffPolygonGenerator.cpp +++ b/src/FffPolygonGenerator.cpp @@ -70,7 +70,7 @@ bool FffPolygonGenerator::generateAreas(SliceDataStorage& storage, MeshGroup* me size_t FffPolygonGenerator::getDraftShieldLayerCount(const size_t total_layers) const { - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; if (! mesh_group_settings.get("draft_shield_enabled")) { return 0; @@ -99,7 +99,7 @@ bool FffPolygonGenerator::sliceModel(MeshGroup* meshgroup, TimeKeeper& timeKeepe spdlog::info("Slicing model..."); - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; // regular layers int slice_layer_count = 0; // Use signed int because we need to subtract the initial layer in a calculation temporarily. @@ -228,7 +228,7 @@ bool FffPolygonGenerator::sliceModel(MeshGroup* meshgroup, TimeKeeper& timeKeepe Mold::process(slicerList); - Scene& scene = Application::getInstance().current_slice->scene; + Scene& scene = Application::getInstance().current_slice_->scene; for (unsigned int mesh_idx = 0; mesh_idx < slicerList.size(); mesh_idx++) { Mesh& mesh = scene.current_mesh_group->meshes[mesh_idx]; @@ -250,7 +250,7 @@ bool FffPolygonGenerator::sliceModel(MeshGroup* meshgroup, TimeKeeper& timeKeepe generateMultipleVolumesOverlap(slicerList); - if (Application::getInstance().current_slice->scene.current_mesh_group->settings.get("interlocking_enable")) + if (Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("interlocking_enable")) { InterlockingGenerator::generateInterlockingStructure(slicerList); } @@ -383,7 +383,7 @@ void FffPolygonGenerator::slices2polygons(SliceDataStorage& storage, TimeKeeper& Progress::messageProgress(Progress::Stage::INSET_SKIN, mesh_order_idx + 1, storage.meshes.size()); } - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; // we need to remove empty layers after we have processed the insets // processInsets might throw away parts if they have no wall at all (cause it doesn't fit) @@ -510,7 +510,7 @@ void FffPolygonGenerator::processBasicWallsSkinInfill( bool process_infill = mesh.settings.get("infill_line_distance") > 0; if (! process_infill) { // do process infill anyway if it's modified by modifier meshes - const Scene& scene = Application::getInstance().current_slice->scene; + const Scene& scene = Application::getInstance().current_slice_->scene; for (size_t other_mesh_order_idx = mesh_order_idx + 1; other_mesh_order_idx < mesh_order.size(); ++other_mesh_order_idx) { const size_t other_mesh_idx = mesh_order[other_mesh_order_idx]; @@ -528,7 +528,7 @@ void FffPolygonGenerator::processBasicWallsSkinInfill( } // skin & infill - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; bool magic_spiralize = mesh_group_settings.get("magic_spiralize"); size_t mesh_max_initial_bottom_layer_count = 0; if (magic_spiralize) @@ -783,7 +783,7 @@ void FffPolygonGenerator::removeEmptyFirstLayers(SliceDataStorage& storage, size if (n_empty_first_layers > 0) { spdlog::info("Removing {} layers because they are empty", n_empty_first_layers); - const coord_t layer_height = Application::getInstance().current_slice->scene.current_mesh_group->settings.get("layer_height"); + const coord_t layer_height = Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("layer_height"); for (auto& mesh_ptr : storage.meshes) { auto& mesh = *mesh_ptr; @@ -847,7 +847,7 @@ void FffPolygonGenerator::processSkinsAndInfill(SliceMeshStorage& mesh, const La void FffPolygonGenerator::computePrintHeightStatistics(SliceDataStorage& storage) { - const size_t extruder_count = Application::getInstance().current_slice->scene.extruders.size(); + const size_t extruder_count = Application::getInstance().current_slice_->scene.extruders.size(); std::vector& max_print_height_per_extruder = storage.max_print_height_per_extruder; assert(max_print_height_per_extruder.size() == 0 && "storage.max_print_height_per_extruder shouldn't have been initialized yet!"); @@ -876,7 +876,7 @@ void FffPolygonGenerator::computePrintHeightStatistics(SliceDataStorage& storage } // Height of where the support reaches. - Scene& scene = Application::getInstance().current_slice->scene; + Scene& scene = Application::getInstance().current_slice_->scene; const Settings& mesh_group_settings = scene.current_mesh_group->settings; const size_t support_infill_extruder_nr = mesh_group_settings.get("support_infill_extruder_nr").extruder_nr_; // TODO: Support extruder should be configurable per object. @@ -935,7 +935,7 @@ void FffPolygonGenerator::computePrintHeightStatistics(SliceDataStorage& storage void FffPolygonGenerator::processOozeShield(SliceDataStorage& storage) { - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; if (! mesh_group_settings.get("ooze_shield_enabled")) { return; @@ -975,7 +975,7 @@ void FffPolygonGenerator::processOozeShield(SliceDataStorage& storage) coord_t max_line_width = 0; { // compute max_line_width const std::vector extruder_is_used = storage.getExtrudersUsed(); - const auto& extruders = Application::getInstance().current_slice->scene.extruders; + const auto& extruders = Application::getInstance().current_slice_->scene.extruders; for (int extruder_nr = 0; extruder_nr < int(extruders.size()); extruder_nr++) { if (! extruder_is_used[extruder_nr]) @@ -997,7 +997,7 @@ void FffPolygonGenerator::processDraftShield(SliceDataStorage& storage) { return; } - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; const coord_t layer_height = mesh_group_settings.get("layer_height"); const LayerIndex layer_skip{ 500 / layer_height + 1 }; @@ -1016,7 +1016,7 @@ void FffPolygonGenerator::processDraftShield(SliceDataStorage& storage) // Extra offset has rounded joints, so simplify again. coord_t maximum_resolution = 0; // Draft shield is printed with every extruder, so resolve with the max() or min() of them to meet the requirements of all extruders. coord_t maximum_deviation = std::numeric_limits::max(); - for (const ExtruderTrain& extruder : Application::getInstance().current_slice->scene.extruders) + for (const ExtruderTrain& extruder : Application::getInstance().current_slice_->scene.extruders) { maximum_resolution = std::max(maximum_resolution, extruder.settings_.get("meshfix_maximum_resolution")); maximum_deviation = std::min(maximum_deviation, extruder.settings_.get("meshfix_maximum_deviation")); @@ -1027,7 +1027,7 @@ void FffPolygonGenerator::processDraftShield(SliceDataStorage& storage) coord_t max_line_width = 0; { // compute max_line_width const std::vector extruder_is_used = storage.getExtrudersUsed(); - const auto& extruders = Application::getInstance().current_slice->scene.extruders; + const auto& extruders = Application::getInstance().current_slice_->scene.extruders; for (int extruder_nr = 0; extruder_nr < int(extruders.size()); extruder_nr++) { if (! extruder_is_used[extruder_nr]) @@ -1041,7 +1041,7 @@ void FffPolygonGenerator::processDraftShield(SliceDataStorage& storage) void FffPolygonGenerator::processPlatformAdhesion(SliceDataStorage& storage) { - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; EPlatformAdhesion adhesion_type = mesh_group_settings.get("adhesion_type"); if (adhesion_type == EPlatformAdhesion::RAFT) @@ -1061,7 +1061,7 @@ void FffPolygonGenerator::processPlatformAdhesion(SliceDataStorage& storage) skirt_brim.generateSupportBrim(); } - for (const auto& extruder : Application::getInstance().current_slice->scene.extruders) + for (const auto& extruder : Application::getInstance().current_slice_->scene.extruders) { Simplify simplifier(extruder.settings_); for (auto skirt_brim_line : storage.skirt_brim[extruder.extruder_nr_]) diff --git a/src/InterlockingGenerator.cpp b/src/InterlockingGenerator.cpp index fc0c2bc54a..13bd3141ae 100644 --- a/src/InterlockingGenerator.cpp +++ b/src/InterlockingGenerator.cpp @@ -24,7 +24,7 @@ namespace cura void InterlockingGenerator::generateInterlockingStructure(std::vector& volumes) { - Settings& global_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + Settings& global_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; const PointMatrix rotation(global_settings.get("interlocking_orientation")); const coord_t beam_layer_count = global_settings.get("interlocking_beam_layer_count"); const int interface_depth = global_settings.get("interlocking_depth"); @@ -91,7 +91,7 @@ std::pair InterlockingGenerator::growBorderAreasPerpendicula void InterlockingGenerator::handleThinAreas(const std::unordered_set& has_all_meshes) const { - Settings& global_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + Settings& global_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; const coord_t boundary_avoidance = global_settings.get("interlocking_boundary_avoidance"); const coord_t number_of_beams_detect = boundary_avoidance; diff --git a/src/LayerPlan.cpp b/src/LayerPlan.cpp index a9ff85c5e6..ae37348fc4 100644 --- a/src/LayerPlan.cpp +++ b/src/LayerPlan.cpp @@ -97,10 +97,10 @@ LayerPlan::LayerPlan( , is_initial_layer(layer_nr == 0 - static_cast(Raft::getTotalExtraLayers())) , is_raft_layer(layer_nr < 0 - static_cast(Raft::getFillerLayerCount())) , layer_thickness(layer_thickness) - , has_prime_tower_planned_per_extruder(Application::getInstance().current_slice->scene.extruders.size(), false) + , has_prime_tower_planned_per_extruder(Application::getInstance().current_slice_->scene.extruders.size(), false) , current_mesh(nullptr) , last_extruder_previous_layer(start_extruder) - , last_planned_extruder(&Application::getInstance().current_slice->scene.extruders[start_extruder]) + , last_planned_extruder(&Application::getInstance().current_slice_->scene.extruders[start_extruder]) , first_travel_destination_is_inside(false) , // set properly when addTravel is called for the first time (otherwise not set properly) comb_boundary_minimum(computeCombBoundary(CombBoundary::MINIMUM)) @@ -111,7 +111,7 @@ LayerPlan::LayerPlan( size_t current_extruder = start_extruder; was_inside = true; // not used, because the first travel move is bogus is_inside = false; // assumes the next move will not be to inside a layer part (overwritten just before going into a layer part) - if (Application::getInstance().current_slice->scene.current_mesh_group->settings.get("retraction_combing") != CombingMode::OFF) + if (Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("retraction_combing") != CombingMode::OFF) { comb = new Comb(storage, layer_nr, comb_boundary_minimum, comb_boundary_preferred, comb_boundary_offset, travel_avoid_distance, comb_move_inside_distance); } @@ -119,11 +119,11 @@ LayerPlan::LayerPlan( { comb = nullptr; } - for (const ExtruderTrain& extruder : Application::getInstance().current_slice->scene.extruders) + for (const ExtruderTrain& extruder : Application::getInstance().current_slice_->scene.extruders) { layer_start_pos_per_extruder.emplace_back(extruder.settings_.get("layer_start_x"), extruder.settings_.get("layer_start_y")); } - extruder_plans.reserve(Application::getInstance().current_slice->scene.extruders.size()); + extruder_plans.reserve(Application::getInstance().current_slice_->scene.extruders.size()); extruder_plans.emplace_back( current_extruder, layer_nr, @@ -133,7 +133,7 @@ LayerPlan::LayerPlan( fan_speed_layer_time_settings_per_extruder[current_extruder], storage.retraction_wipe_config_per_extruder[current_extruder].retraction_config); - for (size_t extruder_nr = 0; extruder_nr < Application::getInstance().current_slice->scene.extruders.size(); extruder_nr++) + for (size_t extruder_nr = 0; extruder_nr < Application::getInstance().current_slice_->scene.extruders.size(); extruder_nr++) { // Skirt and brim. skirt_brim_is_processed[extruder_nr] = false; } @@ -153,7 +153,7 @@ ExtruderTrain* LayerPlan::getLastPlannedExtruderTrain() Polygons LayerPlan::computeCombBoundary(const CombBoundary boundary_type) { Polygons comb_boundary; - const CombingMode mesh_combing_mode = Application::getInstance().current_slice->scene.current_mesh_group->settings.get("retraction_combing"); + const CombingMode mesh_combing_mode = Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("retraction_combing"); if (mesh_combing_mode != CombingMode::OFF && (layer_nr >= 0 || mesh_combing_mode != CombingMode::NO_SKIN)) { if (layer_nr < 0) @@ -263,8 +263,8 @@ bool LayerPlan::setExtruder(const size_t extruder_nr) layer_thickness, fan_speed_layer_time_settings_per_extruder[extruder_nr], storage.retraction_wipe_config_per_extruder[extruder_nr].retraction_config); - assert(extruder_plans.size() <= Application::getInstance().current_slice->scene.extruders.size() && "Never use the same extruder twice on one layer!"); - last_planned_extruder = &Application::getInstance().current_slice->scene.extruders[extruder_nr]; + assert(extruder_plans.size() <= Application::getInstance().current_slice_->scene.extruders.size() && "Never use the same extruder twice on one layer!"); + last_planned_extruder = &Application::getInstance().current_slice_->scene.extruders[extruder_nr]; { // handle starting pos of the new extruder ExtruderTrain* extruder = getLastPlannedExtruderTrain(); @@ -1392,7 +1392,7 @@ void LayerPlan::spiralizeWallSlice( const bool is_top_layer, const bool is_bottom_layer) { - const bool smooth_contours = Application::getInstance().current_slice->scene.current_mesh_group->settings.get("smooth_spiralized_contours"); + const bool smooth_contours = Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("smooth_spiralized_contours"); constexpr bool spiralize = true; // In addExtrusionMove calls, enable spiralize and use nominal line width. constexpr Ratio width_factor = 1.0_r; @@ -1821,7 +1821,7 @@ void LayerPlan::processFanSpeedAndMinimalLayerTime(Point starting_position) void LayerPlan::writeGCode(GCodeExport& gcode) { - Communication* communication = Application::getInstance().communication; + Communication* communication = Application::getInstance().communication_; communication->setLayerForSend(layer_nr); communication->sendCurrentPosition(gcode.getPositionXY()); gcode.setLayerNr(layer_nr); @@ -1829,7 +1829,7 @@ void LayerPlan::writeGCode(GCodeExport& gcode) gcode.writeLayerComment(layer_nr); // flow-rate compensation - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; gcode.setFlowRateExtrusionSettings( mesh_group_settings.get("flow_rate_max_extrusion_offset"), mesh_group_settings.get("flow_rate_extrusion_offset_factor")); // Offset is in mm. @@ -1911,7 +1911,7 @@ void LayerPlan::writeGCode(GCodeExport& gcode) gcode.insertWipeScript(wipe_config); gcode.ResetLastEValueAfterWipe(extruder_nr); } - else if (layer_nr != 0 && Application::getInstance().current_slice->scene.extruders[extruder_nr].settings_.get("retract_at_layer_change")) + else if (layer_nr != 0 && Application::getInstance().current_slice_->scene.extruders[extruder_nr].settings_.get("retract_at_layer_change")) { // only do the retract if the paths are not spiralized if (! mesh_group_settings.get("magic_spiralize")) @@ -1925,7 +1925,7 @@ void LayerPlan::writeGCode(GCodeExport& gcode) extruder_plan.inserts_.sort(); - const ExtruderTrain& extruder = Application::getInstance().current_slice->scene.extruders[extruder_nr]; + const ExtruderTrain& extruder = Application::getInstance().current_slice_->scene.extruders[extruder_nr]; bool update_extrusion_offset = true; @@ -2249,7 +2249,7 @@ bool LayerPlan::writePathWithCoasting( const std::function insertTempOnTime) { ExtruderPlan& extruder_plan = extruder_plans[extruder_plan_idx]; - const ExtruderTrain& extruder = Application::getInstance().current_slice->scene.extruders[extruder_plan.extruder_nr_]; + const ExtruderTrain& extruder = Application::getInstance().current_slice_->scene.extruders[extruder_plan.extruder_nr_]; const double coasting_volume = extruder.settings_.get("coasting_volume"); if (coasting_volume <= 0) { @@ -2341,7 +2341,7 @@ bool LayerPlan::writePathWithCoasting( Point prev_pt = gcode.getPositionXY(); { // write normal extrude path: - Communication* communication = Application::getInstance().communication; + Communication* communication = Application::getInstance().communication_; for (size_t point_idx = 0; point_idx <= point_idx_before_start; point_idx++) { auto [_, time] = extruder_plan.getPointToPointTime(prev_pt, path.points[point_idx], path); @@ -2420,7 +2420,7 @@ void LayerPlan::applyBackPressureCompensation() for (auto& extruder_plan : extruder_plans) { const Ratio back_pressure_compensation - = Application::getInstance().current_slice->scene.extruders[extruder_plan.extruder_nr_].settings_.get("speed_equalize_flow_width_factor"); + = Application::getInstance().current_slice_->scene.extruders[extruder_plan.extruder_nr_].settings_.get("speed_equalize_flow_width_factor"); if (back_pressure_compensation != 0.0) { extruder_plan.applyBackPressureCompensation(back_pressure_compensation); diff --git a/src/LayerPlanBuffer.cpp b/src/LayerPlanBuffer.cpp index aa339d5836..699f6ee54d 100644 --- a/src/LayerPlanBuffer.cpp +++ b/src/LayerPlanBuffer.cpp @@ -54,7 +54,7 @@ LayerPlan* LayerPlanBuffer::processBuffer() if (buffer_.size() > buffer_size_) { LayerPlan* ret = buffer_.front(); - Application::getInstance().communication->flushGCode(); + Application::getInstance().communication_->flushGCode(); buffer_.pop_front(); return ret; } @@ -63,7 +63,7 @@ LayerPlan* LayerPlanBuffer::processBuffer() void LayerPlanBuffer::flush() { - Application::getInstance().communication->flushGCode(); // If there was still g-code in a layer, flush that as a separate layer. Don't want to group them together accidentally. + Application::getInstance().communication_->flushGCode(); // If there was still g-code in a layer, flush that as a separate layer. Don't want to group them together accidentally. if (buffer_.size() > 0) { insertTempCommands(); // insert preheat commands of the very last layer @@ -71,7 +71,7 @@ void LayerPlanBuffer::flush() while (! buffer_.empty()) { buffer_.front()->writeGCode(gcode_); - Application::getInstance().communication->flushGCode(); + Application::getInstance().communication_->flushGCode(); delete buffer_.front(); buffer_.pop_front(); } @@ -95,8 +95,8 @@ void LayerPlanBuffer::addConnectingTravelMove(LayerPlan* prev_layer, const Layer // if the last planned position in the previous layer isn't the same as the first location of the new layer, travel to the new location if (! prev_layer->last_planned_position || *prev_layer->last_planned_position != first_location_new_layer) { - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; - const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[prev_layer->extruder_plans.back().extruder_nr_].settings_; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; + const Settings& extruder_settings = Application::getInstance().current_slice_->scene.extruders[prev_layer->extruder_plans.back().extruder_nr_].settings_; prev_layer->setIsInside(new_layer_destination_state->second); const bool force_retract = extruder_settings.get("retract_at_layer_change") || (mesh_group_settings.get("travel_retract_before_outer_wall") @@ -167,7 +167,7 @@ Preheat::WarmUpResult LayerPlanBuffer::computeStandbyTempPlan(std::vectorscene.extruders[extruder].settings_; + Settings& extruder_settings = Application::getInstance().current_slice_->scene.extruders[extruder].settings_; double initial_print_temp = extruder_plan.required_start_temperature_; Duration in_between_time = 0.0_s; // the duration during which the extruder isn't used @@ -212,7 +212,7 @@ Preheat::WarmUpResult LayerPlanBuffer::computeStandbyTempPlan(std::vectorscene.extruders[extruder_nr].settings_.get("machine_nozzle_temp_enabled")) + if (! Application::getInstance().current_slice_->scene.extruders[extruder_nr].settings_.get("machine_nozzle_temp_enabled")) { return; } @@ -248,7 +248,7 @@ void LayerPlanBuffer::insertPreheatCommand_multiExtrusion(std::vectorscene.extruders[extruder].settings_; + const Settings& extruder_settings = Application::getInstance().current_slice_->scene.extruders[extruder].settings_; if (! extruder_settings.get("machine_nozzle_temp_enabled")) { return; @@ -301,7 +301,7 @@ void LayerPlanBuffer::insertTempCommands(std::vector& extruder_pl if (prev_extruder != extruder) { // set previous extruder to standby temperature - const Settings& previous_extruder_settings = Application::getInstance().current_slice->scene.extruders[prev_extruder].settings_; + const Settings& previous_extruder_settings = Application::getInstance().current_slice_->scene.extruders[prev_extruder].settings_; extruder_plan.prev_extruder_standby_temp_ = previous_extruder_settings.get("material_standby_temperature"); } @@ -310,7 +310,7 @@ void LayerPlanBuffer::insertTempCommands(std::vector& extruder_pl insertPreheatCommand_singleExtrusion(*prev_extruder_plan, extruder, extruder_plan.required_start_temperature_); prev_extruder_plan->extrusion_temperature_command_ = --prev_extruder_plan->inserts_.end(); } - else if (Application::getInstance().current_slice->scene.extruders[extruder].settings_.get("machine_extruders_share_heater")) + else if (Application::getInstance().current_slice_->scene.extruders[extruder].settings_.get("machine_extruders_share_heater")) { // extruders share a heater so command the previous extruder to change to the temperature required for this extruder insertPreheatCommand_singleExtrusion(*prev_extruder_plan, prev_extruder, extruder_plan.required_start_temperature_); @@ -333,7 +333,7 @@ void LayerPlanBuffer::insertPrintTempCommand(ExtruderPlan& extruder_plan) const double print_temp = *extruder_plan.extrusion_temperature_; const unsigned int extruder = extruder_plan.extruder_nr_; - const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder].settings_; + const Settings& extruder_settings = Application::getInstance().current_slice_->scene.extruders[extruder].settings_; if (! extruder_settings.get("machine_nozzle_temp_enabled")) { return; @@ -362,7 +362,7 @@ void LayerPlanBuffer::insertFinalPrintTempCommand(std::vector& ex { ExtruderPlan& last_extruder_plan = *extruder_plans[last_extruder_plan_idx]; const size_t extruder = last_extruder_plan.extruder_nr_; - const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder].settings_; + const Settings& extruder_settings = Application::getInstance().current_slice_->scene.extruders[extruder].settings_; if (! extruder_settings.get("machine_nozzle_temp_enabled")) { return; @@ -509,14 +509,14 @@ void LayerPlanBuffer::insertTempCommands() } // insert commands for all extruder plans on this layer - Scene& scene = Application::getInstance().current_slice->scene; + Scene& scene = Application::getInstance().current_slice_->scene; LayerPlan& layer_plan = *buffer_.back(); for (size_t extruder_plan_idx = 0; extruder_plan_idx < layer_plan.extruder_plans.size(); extruder_plan_idx++) { const size_t overall_extruder_plan_idx = extruder_plans.size() - layer_plan.extruder_plans.size() + extruder_plan_idx; ExtruderPlan& extruder_plan = layer_plan.extruder_plans[extruder_plan_idx]; size_t extruder = extruder_plan.extruder_nr_; - const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder].settings_; + const Settings& extruder_settings = Application::getInstance().current_slice_->scene.extruders[extruder].settings_; Duration time = extruder_plan.estimates_.getTotalUnretractedTime(); Ratio avg_flow; if (time > 0.0) @@ -560,7 +560,7 @@ void LayerPlanBuffer::insertTempCommands() size_t extruder = extruder_plan.extruder_nr_; for (size_t extruder_idx = 0; extruder_idx < scene.extruders.size(); extruder_idx++) { // set temperature of the first nozzle, turn other nozzles down - const Settings& other_extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder_idx].settings_; + const Settings& other_extruder_settings = Application::getInstance().current_slice_->scene.extruders[extruder_idx].settings_; if (scene.current_mesh_group == scene.mesh_groups.begin()) // First mesh group. { // override values from GCodeExport::setInitialTemps diff --git a/src/Mold.cpp b/src/Mold.cpp index 2ef6ce7561..d46a9ef402 100644 --- a/src/Mold.cpp +++ b/src/Mold.cpp @@ -17,7 +17,7 @@ namespace cura void Mold::process(std::vector& slicer_list) { - Scene& scene = Application::getInstance().current_slice->scene; + Scene& scene = Application::getInstance().current_slice_->scene; { // check whether we even need to process molds bool has_any_mold = false; for (unsigned int mesh_idx = 0; mesh_idx < slicer_list.size(); mesh_idx++) diff --git a/src/Preheat.cpp b/src/Preheat.cpp index 6b3b8c3ee9..914da06595 100644 --- a/src/Preheat.cpp +++ b/src/Preheat.cpp @@ -15,7 +15,7 @@ namespace cura Duration Preheat::getTimeToGoFromTempToTemp(const size_t extruder, const Temperature& temp_before, const Temperature& temp_after, const bool during_printing) { - const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder].settings_; + const Settings& extruder_settings = Application::getInstance().current_slice_->scene.extruders[extruder].settings_; Duration time; if (temp_after > temp_before) { @@ -40,7 +40,7 @@ Duration Preheat::getTimeToGoFromTempToTemp(const size_t extruder, const Tempera Temperature Preheat::getTemp(const size_t extruder, const Ratio& flow, const bool is_initial_layer) { - const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder].settings_; + const Settings& extruder_settings = Application::getInstance().current_slice_->scene.extruders[extruder].settings_; if (is_initial_layer && extruder_settings.get("material_print_temperature_layer_0") != 0) { return extruder_settings.get("material_print_temperature_layer_0"); @@ -51,7 +51,7 @@ Temperature Preheat::getTemp(const size_t extruder, const Ratio& flow, const boo Preheat::WarmUpResult Preheat::getWarmUpPointAfterCoolDown(double time_window, unsigned int extruder, double temp_start, double temp_mid, double temp_end, bool during_printing) { WarmUpResult result; - const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder].settings_; + const Settings& extruder_settings = Application::getInstance().current_slice_->scene.extruders[extruder].settings_; Temperature cool_down_speed = extruder_settings.get("machine_nozzle_cool_down_speed"); if (during_printing) { @@ -121,7 +121,7 @@ Preheat::WarmUpResult Preheat::getWarmUpPointAfterCoolDown(double time_window, u Preheat::CoolDownResult Preheat::getCoolDownPointAfterWarmUp(double time_window, unsigned int extruder, double temp_start, double temp_mid, double temp_end, bool during_printing) { CoolDownResult result; - const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder].settings_; + const Settings& extruder_settings = Application::getInstance().current_slice_->scene.extruders[extruder].settings_; Temperature cool_down_speed = extruder_settings.get("machine_nozzle_cool_down_speed"); if (during_printing) { diff --git a/src/PrimeTower.cpp b/src/PrimeTower.cpp index 5ffbd200c7..41bf694f43 100644 --- a/src/PrimeTower.cpp +++ b/src/PrimeTower.cpp @@ -26,7 +26,7 @@ namespace cura PrimeTower::PrimeTower() : wipe_from_middle(false) { - const Scene& scene = Application::getInstance().current_slice->scene; + const Scene& scene = Application::getInstance().current_slice_->scene; { EPlatformAdhesion adhesion_type = scene.current_mesh_group->settings.get("adhesion_type"); @@ -87,7 +87,7 @@ void PrimeTower::generateGroundpoly() return; } - const Scene& scene = Application::getInstance().current_slice->scene; + const Scene& scene = Application::getInstance().current_slice_->scene; const Settings& mesh_group_settings = scene.current_mesh_group->settings; const coord_t tower_size = mesh_group_settings.get("prime_tower_size"); @@ -114,7 +114,7 @@ void PrimeTower::generatePaths(const SliceDataStorage& storage) void PrimeTower::generatePaths_denseInfill() { - const Scene& scene = Application::getInstance().current_slice->scene; + const Scene& scene = Application::getInstance().current_slice_->scene; const Settings& mesh_group_settings = scene.current_mesh_group->settings; const coord_t layer_height = mesh_group_settings.get("layer_height"); const bool base_enabled = mesh_group_settings.get("prime_tower_brim_enable"); @@ -210,7 +210,7 @@ void PrimeTower::addToGcode(const SliceDataStorage& storage, LayerPlan& gcode_la return; } - bool post_wipe = Application::getInstance().current_slice->scene.extruders[prev_extruder].settings_.get("prime_tower_wipe_enabled"); + bool post_wipe = Application::getInstance().current_slice_->scene.extruders[prev_extruder].settings_.get("prime_tower_wipe_enabled"); // Do not wipe on the first layer, we will generate non-hollow prime tower there for better bed adhesion. if (prev_extruder == new_extruder || layer_nr == 0) @@ -230,9 +230,9 @@ void PrimeTower::addToGcode(const SliceDataStorage& storage, LayerPlan& gcode_la if (post_wipe) { // Make sure we wipe the old extruder on the prime tower. - const Settings& previous_settings = Application::getInstance().current_slice->scene.extruders[prev_extruder].settings_; + const Settings& previous_settings = Application::getInstance().current_slice_->scene.extruders[prev_extruder].settings_; const Point previous_nozzle_offset = Point(previous_settings.get("machine_nozzle_offset_x"), previous_settings.get("machine_nozzle_offset_y")); - const Settings& new_settings = Application::getInstance().current_slice->scene.extruders[new_extruder].settings_; + const Settings& new_settings = Application::getInstance().current_slice_->scene.extruders[new_extruder].settings_; const Point new_nozzle_offset = Point(new_settings.get("machine_nozzle_offset_x"), new_settings.get("machine_nozzle_offset_y")); gcode_layer.addTravel(post_wipe_point - previous_nozzle_offset + new_nozzle_offset); } @@ -301,7 +301,7 @@ void PrimeTower::gotoStartLocation(LayerPlan& gcode_layer, const int extruder_nr const ClosestPolygonPoint wipe_location = prime_tower_start_locations[current_start_location_idx]; - const ExtruderTrain& train = Application::getInstance().current_slice->scene.extruders[extruder_nr]; + const ExtruderTrain& train = Application::getInstance().current_slice_->scene.extruders[extruder_nr]; const coord_t inward_dist = train.settings_.get("machine_nozzle_size") * 3 / 2; const coord_t start_dist = train.settings_.get("machine_nozzle_size") * 2; const Point prime_end = PolygonUtils::moveInsideDiagonally(wipe_location, inward_dist); diff --git a/src/Scene.cpp b/src/Scene.cpp index f7c81777f6..ead01544e8 100644 --- a/src/Scene.cpp +++ b/src/Scene.cpp @@ -95,8 +95,8 @@ void Scene::processMeshGroup(MeshGroup& mesh_group) fff_processor->gcode_writer.writeGCode(storage, fff_processor->time_keeper); Progress::messageProgress(Progress::Stage::FINISH, 1, 1); // 100% on this meshgroup - Application::getInstance().communication->flushGCode(); - Application::getInstance().communication->sendOptimizedLayerData(); + Application::getInstance().communication_->flushGCode(); + Application::getInstance().communication_->sendOptimizedLayerData(); spdlog::info("Total time elapsed {:03.3f}s\n", time_keeper_total.restart()); } diff --git a/src/SkirtBrim.cpp b/src/SkirtBrim.cpp index 3769760253..1e59c669d8 100644 --- a/src/SkirtBrim.cpp +++ b/src/SkirtBrim.cpp @@ -20,10 +20,10 @@ namespace cura SkirtBrim::SkirtBrim(SliceDataStorage& storage) : storage(storage) - , adhesion_type(Application::getInstance().current_slice->scene.current_mesh_group->settings.get("adhesion_type")) + , adhesion_type(Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("adhesion_type")) , has_ooze_shield(storage.oozeShield.size() > 0 && storage.oozeShield[0].size() > 0) , has_draft_shield(storage.draft_protection_shield.size() > 0) - , extruders(Application::getInstance().current_slice->scene.extruders) + , extruders(Application::getInstance().current_slice_->scene.extruders) , extruder_count(extruders.size()) , extruder_is_used(storage.getExtrudersUsed()) { @@ -36,7 +36,7 @@ SkirtBrim::SkirtBrim(SliceDataStorage& storage) break; } } - skirt_brim_extruder_nr = Application::getInstance().current_slice->scene.current_mesh_group->settings.get("skirt_brim_extruder_nr"); + skirt_brim_extruder_nr = Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("skirt_brim_extruder_nr"); if (skirt_brim_extruder_nr == -1 && adhesion_type == EPlatformAdhesion::SKIRT) { // Skirt is always printed with all extruders in order to satisfy minimum legnth constraint // NOTE: the line count will only be satisfied for the first extruder used. @@ -168,7 +168,7 @@ void SkirtBrim::generate() generateSecondarySkirtBrim(covered_area, allowed_areas_per_extruder, total_length); // simplify paths to prevent buffer unnerruns in firmware - const Settings& global_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& global_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; const coord_t maximum_resolution = global_settings.get("meshfix_maximum_resolution"); const coord_t maximum_deviation = global_settings.get("meshfix_maximum_deviation"); for (int extruder_nr = 0; extruder_nr < extruder_count; extruder_nr++) @@ -226,7 +226,7 @@ std::vector SkirtBrim::generatePrimaryBrim(std::vector& all_bri Polygons SkirtBrim::getInternalHoleExclusionArea(const Polygons& outline, const int extruder_nr) { assert(extruder_nr >= 0); - const Settings& settings = Application::getInstance().current_slice->scene.extruders[extruder_nr].settings_; + const Settings& settings = Application::getInstance().current_slice_->scene.extruders[extruder_nr].settings_; // If brim is external_only, the distance between the external brim of a part inside a hole and the inside hole of the outer part. const coord_t hole_brim_distance = settings.get("brim_inside_margin"); @@ -300,7 +300,7 @@ coord_t SkirtBrim::generateOffset(const Offset& offset, Polygons& covered_area, } { // limit brim lines to allowed areas, stitch them and store them in the result - brim = Simplify(Application::getInstance().current_slice->scene.extruders[offset.extruder_nr].settings_).polygon(brim); + brim = Simplify(Application::getInstance().current_slice_->scene.extruders[offset.extruder_nr].settings_).polygon(brim); brim.toPolylines(); Polygons brim_lines = allowed_areas_per_extruder[offset.extruder_nr].intersectionPolyLines(brim, false); length_added = brim_lines.polyLineLength(); @@ -340,7 +340,7 @@ coord_t SkirtBrim::generateOffset(const Offset& offset, Polygons& covered_area, Polygons SkirtBrim::getFirstLayerOutline(const int extruder_nr /* = -1 */) { Polygons first_layer_outline; - Settings& global_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + Settings& global_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; int reference_extruder_nr = skirt_brim_extruder_nr; assert(! (reference_extruder_nr == -1 && extruder_nr == -1) && "We should only request the outlines of all layers when the brim is being generated for only one material"); if (reference_extruder_nr == -1) @@ -359,7 +359,7 @@ Polygons SkirtBrim::getFirstLayerOutline(const int extruder_nr /* = -1 */) first_layer_outline = Polygons(); int skirt_height = 0; - for (const auto& extruder : Application::getInstance().current_slice->scene.extruders) + for (const auto& extruder : Application::getInstance().current_slice_->scene.extruders) { if (extruder_nr == -1 || extruder_nr == extruder.extruder_nr_) { @@ -370,7 +370,7 @@ Polygons SkirtBrim::getFirstLayerOutline(const int extruder_nr /* = -1 */) for (int i_layer = layer_nr; i_layer < skirt_height; ++i_layer) { - for (const auto& extruder : Application::getInstance().current_slice->scene.extruders) + for (const auto& extruder : Application::getInstance().current_slice_->scene.extruders) { first_layer_outline = first_layer_outline.unionPolygons(storage.getLayerOutlines(i_layer, include_support, include_prime_tower, external_only, extruder.extruder_nr_)); @@ -578,7 +578,7 @@ void SkirtBrim::generateSupportBrim() { constexpr coord_t brim_area_minimum_hole_size_multiplier = 100; - Scene& scene = Application::getInstance().current_slice->scene; + Scene& scene = Application::getInstance().current_slice_->scene; const ExtruderTrain& support_infill_extruder = scene.current_mesh_group->settings.get("support_infill_extruder_nr"); const coord_t brim_line_width = support_infill_extruder.settings_.get("skirt_brim_line_width") * support_infill_extruder.settings_.get("initial_layer_line_width_factor"); diff --git a/src/communication/ArcusCommunication.cpp b/src/communication/ArcusCommunication.cpp index 54ace60375..231f7e001d 100644 --- a/src/communication/ArcusCommunication.cpp +++ b/src/communication/ArcusCommunication.cpp @@ -468,7 +468,7 @@ void ArcusCommunication::sendPrintTimeMaterialEstimates() const message->set_time_travel(time_estimates[static_cast(PrintFeatureType::MoveCombing)]); message->set_time_prime_tower(time_estimates[static_cast(PrintFeatureType::PrimeTower)]); - for (size_t extruder_nr = 0; extruder_nr < Application::getInstance().current_slice->scene.extruders.size(); extruder_nr++) + for (size_t extruder_nr = 0; extruder_nr < Application::getInstance().current_slice_->scene.extruders.size(); extruder_nr++) { proto::MaterialEstimates* material_message = message->add_materialestimates(); material_message->set_id(extruder_nr); @@ -527,7 +527,7 @@ void ArcusCommunication::sliceNext() #endif // ENABLE_PLUGINS Slice slice(slice_message->object_lists().size()); - Application::getInstance().current_slice = &slice; + Application::getInstance().current_slice_ = &slice; private_data->readGlobalSettingsMessage(slice_message->global_settings()); private_data->readExtruderSettingsMessage(slice_message->extruders()); diff --git a/src/communication/ArcusCommunicationPrivate.cpp b/src/communication/ArcusCommunicationPrivate.cpp index afff5800fa..1e18cc81b0 100644 --- a/src/communication/ArcusCommunicationPrivate.cpp +++ b/src/communication/ArcusCommunicationPrivate.cpp @@ -47,7 +47,7 @@ std::shared_ptr ArcusCommunication::Private::getOptimized void ArcusCommunication::Private::readGlobalSettingsMessage(const proto::SettingList& global_settings_message) { - Slice* slice = Application::getInstance().current_slice; + Slice* slice = Application::getInstance().current_slice_; for (const cura::proto::Setting& setting_message : global_settings_message.settings()) { slice->scene.settings.add(setting_message.name(), setting_message.value()); @@ -57,7 +57,7 @@ void ArcusCommunication::Private::readGlobalSettingsMessage(const proto::Setting void ArcusCommunication::Private::readExtruderSettingsMessage(const google::protobuf::RepeatedPtrField& extruder_messages) { // Make sure we have enough extruders added currently. - Slice* slice = Application::getInstance().current_slice; + Slice* slice = Application::getInstance().current_slice_; const size_t extruder_count = slice->scene.settings.get("machine_extruder_count"); for (size_t extruder_nr = 0; extruder_nr < extruder_count; extruder_nr++) { @@ -90,7 +90,7 @@ void ArcusCommunication::Private::readMeshGroupMessage(const proto::ObjectList& return; // Don't slice empty mesh groups. } - Scene& scene = Application::getInstance().current_slice->scene; + Scene& scene = Application::getInstance().current_slice_->scene; MeshGroup& mesh_group = scene.mesh_groups.at(object_count); // Load the settings in the mesh group. diff --git a/src/communication/CommandLine.cpp b/src/communication/CommandLine.cpp index ae9fd28ee6..08b8600eae 100644 --- a/src/communication/CommandLine.cpp +++ b/src/communication/CommandLine.cpp @@ -92,7 +92,7 @@ void CommandLine::sendPrintTimeMaterialEstimates() const spdlog::info("Total print time: {:3}", sum); sum = 0.0; - for (size_t extruder_nr = 0; extruder_nr < Application::getInstance().current_slice->scene.extruders.size(); extruder_nr++) + for (size_t extruder_nr = 0; extruder_nr < Application::getInstance().current_slice_->scene.extruders.size(); extruder_nr++) { sum += FffProcessor::getInstance()->getTotalFilamentUsed(extruder_nr); } @@ -123,7 +123,7 @@ void CommandLine::sliceNext() } Slice slice(num_mesh_groups); - Application::getInstance().current_slice = &slice; + Application::getInstance().current_slice_ = &slice; size_t mesh_group_index = 0; Settings* last_settings = &slice.scene.settings; @@ -437,7 +437,7 @@ int CommandLine::loadJSON( // Extruders defined from here, if any. // Note that this always puts the extruder settings in the slice of the current extruder. It doesn't keep the nested structure of the JSON files, if extruders would have their // own sub-extruders. - Scene& scene = Application::getInstance().current_slice->scene; + Scene& scene = Application::getInstance().current_slice_->scene; if (document.HasMember("metadata") && document["metadata"].IsObject()) { const rapidjson::Value& metadata = document["metadata"]; diff --git a/src/gcodeExport.cpp b/src/gcodeExport.cpp index 68c060dc61..01d57a6357 100644 --- a/src/gcodeExport.cpp +++ b/src/gcodeExport.cpp @@ -79,11 +79,11 @@ void GCodeExport::preSetup(const size_t start_extruder) { current_extruder = start_extruder; - const Scene& scene = Application::getInstance().current_slice->scene; + const Scene& scene = Application::getInstance().current_slice_->scene; std::vector::iterator mesh_group = scene.current_mesh_group; setFlavor(mesh_group->settings.get("machine_gcode_flavor")); use_extruder_offset_to_offset_coords = mesh_group->settings.get("machine_use_extruder_offset_to_offset_coords"); - const size_t extruder_count = Application::getInstance().current_slice->scene.extruders.size(); + const size_t extruder_count = Application::getInstance().current_slice_->scene.extruders.size(); for (size_t extruder_nr = 0; extruder_nr < extruder_count; extruder_nr++) { @@ -95,7 +95,7 @@ void GCodeExport::preSetup(const size_t start_extruder) extruder_attr[extruder_nr].fan_number = train.settings_.get("machine_extruder_cooling_fan_number"); // Cache some settings that we use frequently. - const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder_nr].settings_; + const Settings& extruder_settings = Application::getInstance().current_slice_->scene.extruders[extruder_nr].settings_; if (use_extruder_offset_to_offset_coords) { extruder_attr[extruder_nr].nozzle_offset = Point(extruder_settings.get("machine_nozzle_offset_x"), extruder_settings.get("machine_nozzle_offset_y")); @@ -144,8 +144,8 @@ void GCodeExport::preSetup(const size_t start_extruder) void GCodeExport::setInitialAndBuildVolumeTemps(const unsigned int start_extruder_nr) { - const Scene& scene = Application::getInstance().current_slice->scene; - const size_t extruder_count = Application::getInstance().current_slice->scene.extruders.size(); + const Scene& scene = Application::getInstance().current_slice_->scene; + const size_t extruder_count = Application::getInstance().current_slice_->scene.extruders.size(); for (size_t extruder_nr = 0; extruder_nr < extruder_count; extruder_nr++) { const ExtruderTrain& train = scene.extruders[extruder_nr]; @@ -204,7 +204,7 @@ std::string GCodeExport::getFileHeader( { std::ostringstream prefix; - const size_t extruder_count = Application::getInstance().current_slice->scene.extruders.size(); + const size_t extruder_count = Application::getInstance().current_slice_->scene.extruders.size(); switch (flavor) { case EGCodeFlavor::GRIFFIN: @@ -231,7 +231,7 @@ std::string GCodeExport::getFileHeader( { prefix << ";EXTRUDER_TRAIN." << extr_nr << ".MATERIAL.GUID:" << mat_ids[extr_nr] << new_line; } - const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extr_nr].settings_; + const Settings& extruder_settings = Application::getInstance().current_slice_->scene.extruders[extr_nr].settings_; prefix << ";EXTRUDER_TRAIN." << extr_nr << ".NOZZLE.DIAMETER:" << extruder_settings.get("machine_nozzle_size") << new_line; prefix << ";EXTRUDER_TRAIN." << extr_nr << ".NOZZLE.NAME:" << extruder_settings.get("machine_nozzle_id") << new_line; } @@ -247,7 +247,7 @@ std::string GCodeExport::getFileHeader( prefix << ";PRINT.TIME:" << static_cast(*print_time) << new_line; } - prefix << ";PRINT.GROUPS:" << Application::getInstance().current_slice->scene.mesh_groups.size() << new_line; + prefix << ";PRINT.GROUPS:" << Application::getInstance().current_slice_->scene.mesh_groups.size() << new_line; if (total_bounding_box.min.x_ > total_bounding_box.max.x_) // We haven't encountered any movement (yet). This probably means we're command-line slicing. { @@ -272,7 +272,7 @@ std::string GCodeExport::getFileHeader( prefix << ";MATERIAL:" << ((filament_used.size() >= 1) ? static_cast(filament_used[0]) : 6666) << new_line; prefix << ";MATERIAL2:" << ((filament_used.size() >= 2) ? static_cast(filament_used[1]) : 0) << new_line; - prefix << ";NOZZLE_DIAMETER:" << Application::getInstance().current_slice->scene.extruders[0].settings_.get("machine_nozzle_size") << new_line; + prefix << ";NOZZLE_DIAMETER:" << Application::getInstance().current_slice_->scene.extruders[0].settings_.get("machine_nozzle_size") << new_line; } else if (flavor == EGCodeFlavor::REPRAP || flavor == EGCodeFlavor::MARLIN || flavor == EGCodeFlavor::MARLIN_VOLUMATRIC) { @@ -300,7 +300,7 @@ std::string GCodeExport::getFileHeader( prefix << "0m"; } prefix << new_line; - prefix << ";Layer height: " << Application::getInstance().current_slice->scene.current_mesh_group->settings.get("layer_height") << new_line; + prefix << ";Layer height: " << Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("layer_height") << new_line; } prefix << ";MINX:" << INT2MM(total_bounding_box.min.x_) << new_line; prefix << ";MINY:" << INT2MM(total_bounding_box.min.y_) << new_line; @@ -646,9 +646,9 @@ void GCodeExport::resetExtrusionValue() bool GCodeExport::initializeExtruderTrains(const SliceDataStorage& storage, const size_t start_extruder_nr) { bool should_prime_extruder = true; - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; - if (Application::getInstance().communication->isSequential()) // If we must output the g-code sequentially, we must already place the g-code header here even if we don't know + if (Application::getInstance().communication_->isSequential()) // If we must output the g-code sequentially, we must already place the g-code header here even if we don't know // the exact time/material usages yet. { std::string prefix = getFileHeader(storage.getExtrudersUsed()); @@ -672,9 +672,9 @@ bool GCodeExport::initializeExtruderTrains(const SliceDataStorage& storage, cons writeCode(mesh_group_settings.get("machine_start_gcode").c_str()); // in case of shared nozzle assume that the machine-start gcode reset the extruders as per machine description - if (Application::getInstance().current_slice->scene.settings.get("machine_extruders_share_nozzle")) + if (Application::getInstance().current_slice_->scene.settings.get("machine_extruders_share_nozzle")) { - for (const ExtruderTrain& train : Application::getInstance().current_slice->scene.extruders) + for (const ExtruderTrain& train : Application::getInstance().current_slice_->scene.extruders) { resetExtruderToPrimed(train.extruder_nr_, train.settings_.get("machine_extruders_shared_nozzle_initial_retraction")); } @@ -685,7 +685,7 @@ bool GCodeExport::initializeExtruderTrains(const SliceDataStorage& storage, cons writeBuildVolumeTemperatureCommand(mesh_group_settings.get("build_volume_temperature")); } - Application::getInstance().communication->sendCurrentPosition(getPositionXY()); + Application::getInstance().communication_->sendCurrentPosition(getPositionXY()); startExtruder(start_extruder_nr); if (getFlavor() == EGCodeFlavor::BFB) @@ -697,7 +697,7 @@ bool GCodeExport::initializeExtruderTrains(const SliceDataStorage& storage, cons } else if (getFlavor() == EGCodeFlavor::GRIFFIN) { // initialize extruder trains - ExtruderTrain& train = Application::getInstance().current_slice->scene.extruders[start_extruder_nr]; + ExtruderTrain& train = Application::getInstance().current_slice_->scene.extruders[start_extruder_nr]; processInitialLayerTemperature(storage, start_extruder_nr); writePrimeTrain(train.settings_.get("speed_travel")); should_prime_extruder = false; @@ -728,7 +728,7 @@ bool GCodeExport::initializeExtruderTrains(const SliceDataStorage& storage, cons void GCodeExport::processInitialLayerBedTemperature() { - const Scene& scene = Application::getInstance().current_slice->scene; + const Scene& scene = Application::getInstance().current_slice_->scene; const bool heated = scene.current_mesh_group->settings.get("machine_heated_bed"); const Temperature bed_temp = scene.current_mesh_group->settings.get("material_bed_temperature_layer_0"); if (heated && bed_temp != 0) @@ -739,7 +739,7 @@ void GCodeExport::processInitialLayerBedTemperature() void GCodeExport::processInitialLayerTemperature(const SliceDataStorage& storage, const size_t start_extruder_nr) { - Scene& scene = Application::getInstance().current_slice->scene; + Scene& scene = Application::getInstance().current_slice_->scene; const size_t num_extruders = scene.extruders.size(); if (getFlavor() == EGCodeFlavor::GRIFFIN) @@ -939,8 +939,8 @@ void GCodeExport::writeTravel(const coord_t x, const coord_t y, const coord_t z, const PrintFeatureType travel_move_type = extruder_attr[current_extruder].retraction_e_amount_current ? PrintFeatureType::MoveRetraction : PrintFeatureType::MoveCombing; const int display_width = extruder_attr[current_extruder].retraction_e_amount_current ? MM2INT(0.2) : MM2INT(0.1); - const double layer_height = Application::getInstance().current_slice->scene.current_mesh_group->settings.get("layer_height"); - Application::getInstance().communication->sendLineTo(travel_move_type, Point(x, y), display_width, layer_height, speed); + const double layer_height = Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("layer_height"); + Application::getInstance().communication_->sendLineTo(travel_move_type, Point(x, y), display_width, layer_height, speed); *output_stream << "G0"; writeFXYZE(speed, x, y, z, current_e_value, travel_move_type); @@ -1206,7 +1206,7 @@ void GCodeExport::writeZhopStart(const coord_t hop_height, Velocity speed /*= 0* { if (speed == 0) { - const ExtruderTrain& extruder = Application::getInstance().current_slice->scene.extruders[current_extruder]; + const ExtruderTrain& extruder = Application::getInstance().current_slice_->scene.extruders[current_extruder]; speed = extruder.settings_.get("speed_z_hop"); } is_z_hopped = hop_height; @@ -1223,7 +1223,7 @@ void GCodeExport::writeZhopEnd(Velocity speed /*= 0*/) { if (speed == 0) { - const ExtruderTrain& extruder = Application::getInstance().current_slice->scene.extruders[current_extruder]; + const ExtruderTrain& extruder = Application::getInstance().current_slice_->scene.extruders[current_extruder]; speed = extruder.settings_.get("speed_z_hop"); } is_z_hopped = 0; @@ -1254,7 +1254,7 @@ void GCodeExport::startExtruder(const size_t new_extruder) assert(getCurrentExtrudedVolume() == 0.0 && "Just after an extruder switch we haven't extruded anything yet!"); resetExtrusionValue(); // zero the E value on the new extruder, just to be sure - const std::string start_code = Application::getInstance().current_slice->scene.extruders[new_extruder].settings_.get("machine_extruder_start_code"); + const std::string start_code = Application::getInstance().current_slice_->scene.extruders[new_extruder].settings_.get("machine_extruder_start_code"); if (! start_code.empty()) { @@ -1271,8 +1271,8 @@ void GCodeExport::startExtruder(const size_t new_extruder) } } - Application::getInstance().communication->setExtruderForSend(Application::getInstance().current_slice->scene.extruders[new_extruder]); - Application::getInstance().communication->sendCurrentPosition(getPositionXY()); + Application::getInstance().communication_->setExtruderForSend(Application::getInstance().current_slice_->scene.extruders[new_extruder]); + Application::getInstance().communication_->sendCurrentPosition(getPositionXY()); // Change the Z position so it gets re-written again. We do not know if the switch code modified the Z position. currentPosition.z_ += 1; @@ -1287,7 +1287,7 @@ void GCodeExport::switchExtruder(size_t new_extruder, const RetractionConfig& re return; } - const Settings& old_extruder_settings = Application::getInstance().current_slice->scene.extruders[current_extruder].settings_; + const Settings& old_extruder_settings = Application::getInstance().current_slice_->scene.extruders[current_extruder].settings_; if (old_extruder_settings.get("retraction_enable")) { constexpr bool force = true; @@ -1340,7 +1340,7 @@ void GCodeExport::writePrimeTrain(const Velocity& travel_speed) { // extruder is already primed once! return; } - const Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[current_extruder].settings_; + const Settings& extruder_settings = Application::getInstance().current_slice_->scene.extruders[current_extruder].settings_; if (extruder_settings.get("prime_blob_enable")) { // only move to prime position if we do a blob/poop // ideally the prime position would be respected whether we do a blob or not, @@ -1417,7 +1417,7 @@ void GCodeExport::writeFanCommand(double speed) } else if (speed > 0) { - const bool should_scale_zero_to_one = Application::getInstance().current_slice->scene.settings.get("machine_scale_fan_speed_zero_to_one"); + const bool should_scale_zero_to_one = Application::getInstance().current_slice_->scene.settings.get("machine_scale_fan_speed_zero_to_one"); *output_stream << "M106 S" << PrecisionedDouble{ (should_scale_zero_to_one ? 2u : 1u), (should_scale_zero_to_one ? speed : speed * 255) / 100 }; if (fan_number) { @@ -1440,7 +1440,7 @@ void GCodeExport::writeFanCommand(double speed) void GCodeExport::writeTemperatureCommand(const size_t extruder, const Temperature& temperature, const bool wait) { - const ExtruderTrain& extruder_train = Application::getInstance().current_slice->scene.extruders[extruder]; + const ExtruderTrain& extruder_train = Application::getInstance().current_slice_->scene.extruders[extruder]; if (! extruder_train.settings_.get("machine_nozzle_temp_enabled")) { @@ -1457,7 +1457,7 @@ void GCodeExport::writeTemperatureCommand(const size_t extruder, const Temperatu } // sync all extruders with the change to the current extruder - const size_t extruder_count = Application::getInstance().current_slice->scene.extruders.size(); + const size_t extruder_count = Application::getInstance().current_slice_->scene.extruders.size(); for (size_t extruder_nr = 0; extruder_nr < extruder_count; extruder_nr++) { diff --git a/src/multiVolumes.cpp b/src/multiVolumes.cpp index c1cc6afdec..e4e5398725 100644 --- a/src/multiVolumes.cpp +++ b/src/multiVolumes.cpp @@ -18,7 +18,7 @@ namespace cura void carveMultipleVolumes(std::vector& volumes) { // Go trough all the volumes, and remove the previous volume outlines from our own outline, so we never have overlapped areas. - const bool alternate_carve_order = Application::getInstance().current_slice->scene.current_mesh_group->settings.get("alternate_carve_order"); + const bool alternate_carve_order = Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("alternate_carve_order"); std::vector ranked_volumes = volumes; std::sort( ranked_volumes.begin(), diff --git a/src/progress/Progress.cpp b/src/progress/Progress.cpp index e0cafbec02..a32b50ea94 100644 --- a/src/progress/Progress.cpp +++ b/src/progress/Progress.cpp @@ -40,7 +40,7 @@ void Progress::init() void Progress::messageProgress(Progress::Stage stage, int progress_in_stage, int progress_in_stage_max) { double percentage = calcOverallProgress(stage, static_cast(progress_in_stage / static_cast(progress_in_stage_max))); - Application::getInstance().communication->sendProgress(static_cast(percentage)); + Application::getInstance().communication_->sendProgress(static_cast(percentage)); } void Progress::messageProgressStage(Progress::Stage stage, TimeKeeper* time_keeper) diff --git a/src/raft.cpp b/src/raft.cpp index aed16063f8..74325690d0 100644 --- a/src/raft.cpp +++ b/src/raft.cpp @@ -18,7 +18,7 @@ namespace cura void Raft::generate(SliceDataStorage& storage) { assert(storage.raftOutline.size() == 0 && "Raft polygon isn't generated yet, so should be empty!"); - const Settings& settings = Application::getInstance().current_slice->scene.current_mesh_group->settings.get("raft_base_extruder_nr").settings_; + const Settings& settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("raft_base_extruder_nr").settings_; const coord_t distance = settings.get("raft_margin"); constexpr bool include_support = true; constexpr bool dont_include_prime_tower = false; // Prime tower raft will be handled separately in 'storage.primeRaftOutline'; see below. @@ -55,7 +55,7 @@ void Raft::generate(SliceDataStorage& storage) { // Find out if the prime-tower part of the raft still needs to be printed, even if there is no actual tower. // This will only happen if the different raft layers are printed by different extruders. - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; const size_t base_extruder_nr = mesh_group_settings.get("raft_base_extruder_nr").extruder_nr_; const size_t interface_extruder_nr = mesh_group_settings.get("raft_interface_extruder_nr").extruder_nr_; const size_t surface_extruder_nr = mesh_group_settings.get("raft_surface_extruder_nr").extruder_nr_; @@ -68,7 +68,7 @@ void Raft::generate(SliceDataStorage& storage) coord_t Raft::getTotalThickness() { - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; const ExtruderTrain& base_train = mesh_group_settings.get("raft_base_extruder_nr"); const ExtruderTrain& interface_train = mesh_group_settings.get("raft_interface_extruder_nr"); const ExtruderTrain& surface_train = mesh_group_settings.get("raft_surface_extruder_nr"); @@ -79,7 +79,7 @@ coord_t Raft::getTotalThickness() coord_t Raft::getZdiffBetweenRaftAndLayer0() { - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; const ExtruderTrain& train = mesh_group_settings.get("raft_surface_extruder_nr"); if (mesh_group_settings.get("adhesion_type") != EPlatformAdhesion::RAFT) { @@ -91,13 +91,13 @@ coord_t Raft::getZdiffBetweenRaftAndLayer0() size_t Raft::getFillerLayerCount() { - const coord_t normal_layer_height = Application::getInstance().current_slice->scene.current_mesh_group->settings.get("layer_height"); + const coord_t normal_layer_height = Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("layer_height"); return round_divide(getZdiffBetweenRaftAndLayer0(), normal_layer_height); } coord_t Raft::getFillerLayerHeight() { - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; if (mesh_group_settings.get("adhesion_type") != EPlatformAdhesion::RAFT) { const coord_t normal_layer_height = mesh_group_settings.get("layer_height"); @@ -110,7 +110,7 @@ coord_t Raft::getFillerLayerHeight() size_t Raft::getTotalExtraLayers() { - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; const ExtruderTrain& base_train = mesh_group_settings.get("raft_base_extruder_nr"); const ExtruderTrain& interface_train = mesh_group_settings.get("raft_interface_extruder_nr"); const ExtruderTrain& surface_train = mesh_group_settings.get("raft_surface_extruder_nr"); diff --git a/src/settings/AdaptiveLayerHeights.cpp b/src/settings/AdaptiveLayerHeights.cpp index 25f1cca535..09d2bf5682 100644 --- a/src/settings/AdaptiveLayerHeights.cpp +++ b/src/settings/AdaptiveLayerHeights.cpp @@ -61,7 +61,7 @@ void AdaptiveLayerHeights::calculateAllowedLayerHeights() void AdaptiveLayerHeights::calculateLayers() { const coord_t minimum_layer_height = *std::min_element(allowed_layer_heights.begin(), allowed_layer_heights.end()); - Settings const& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + Settings const& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; auto slicing_tolerance = mesh_group_settings.get("slicing_tolerance"); std::vector triangles_of_interest; const coord_t model_max_z = meshgroup->max().z_; @@ -187,7 +187,7 @@ void AdaptiveLayerHeights::calculateLayers() void AdaptiveLayerHeights::calculateMeshTriangleSlopes() { // loop over all mesh faces (triangles) and find their slopes - for (const Mesh& mesh : Application::getInstance().current_slice->scene.current_mesh_group->meshes) + for (const Mesh& mesh : Application::getInstance().current_slice_->scene.current_mesh_group->meshes) { // Skip meshes that are not printable if (mesh.settings_.get("infill_mesh") || mesh.settings_.get("cutting_mesh") || mesh.settings_.get("anti_overhang_mesh")) diff --git a/src/settings/PathConfigStorage.cpp b/src/settings/PathConfigStorage.cpp index 5ac58e7950..48ca20d6d2 100644 --- a/src/settings/PathConfigStorage.cpp +++ b/src/settings/PathConfigStorage.cpp @@ -17,7 +17,7 @@ namespace cura std::vector PathConfigStorage::getLineWidthFactorPerExtruder(const LayerIndex& layer_nr) { std::vector ret; - for (const ExtruderTrain& train : Application::getInstance().current_slice->scene.extruders) + for (const ExtruderTrain& train : Application::getInstance().current_slice_->scene.extruders) { if (layer_nr <= 0) { @@ -33,15 +33,15 @@ std::vector PathConfigStorage::getLineWidthFactorPerExtruder(const LayerI } PathConfigStorage::PathConfigStorage(const SliceDataStorage& storage, const LayerIndex& layer_nr, const coord_t layer_thickness) - : support_infill_extruder_nr(Application::getInstance().current_slice->scene.current_mesh_group->settings.get("support_infill_extruder_nr").extruder_nr_) - , support_roof_extruder_nr(Application::getInstance().current_slice->scene.current_mesh_group->settings.get("support_roof_extruder_nr").extruder_nr_) - , support_bottom_extruder_nr(Application::getInstance().current_slice->scene.current_mesh_group->settings.get("support_bottom_extruder_nr").extruder_nr_) - , raft_base_train(Application::getInstance().current_slice->scene.current_mesh_group->settings.get("raft_base_extruder_nr")) - , raft_interface_train(Application::getInstance().current_slice->scene.current_mesh_group->settings.get("raft_interface_extruder_nr")) - , raft_surface_train(Application::getInstance().current_slice->scene.current_mesh_group->settings.get("raft_surface_extruder_nr")) - , support_infill_train(Application::getInstance().current_slice->scene.extruders[support_infill_extruder_nr]) - , support_roof_train(Application::getInstance().current_slice->scene.extruders[support_roof_extruder_nr]) - , support_bottom_train(Application::getInstance().current_slice->scene.extruders[support_bottom_extruder_nr]) + : support_infill_extruder_nr(Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("support_infill_extruder_nr").extruder_nr_) + , support_roof_extruder_nr(Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("support_roof_extruder_nr").extruder_nr_) + , support_bottom_extruder_nr(Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("support_bottom_extruder_nr").extruder_nr_) + , raft_base_train(Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("raft_base_extruder_nr")) + , raft_interface_train(Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("raft_interface_extruder_nr")) + , raft_surface_train(Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("raft_surface_extruder_nr")) + , support_infill_train(Application::getInstance().current_slice_->scene.extruders[support_infill_extruder_nr]) + , support_roof_train(Application::getInstance().current_slice_->scene.extruders[support_roof_extruder_nr]) + , support_bottom_train(Application::getInstance().current_slice_->scene.extruders[support_bottom_extruder_nr]) , line_width_factor_per_extruder(PathConfigStorage::getLineWidthFactorPerExtruder(layer_nr)) , raft_base_config(GCodePathConfig{ .type = PrintFeatureType::SupportInterface, .line_width = raft_base_train.settings_.get("raft_base_line_width"), @@ -83,14 +83,14 @@ PathConfigStorage::PathConfigStorage(const SliceDataStorage& storage, const Laye .acceleration = support_bottom_train.settings_.get("acceleration_support_bottom"), .jerk = support_bottom_train.settings_.get("jerk_support_bottom") } }) { - const size_t extruder_count = Application::getInstance().current_slice->scene.extruders.size(); + const size_t extruder_count = Application::getInstance().current_slice_->scene.extruders.size(); travel_config_per_extruder.reserve(extruder_count); skirt_brim_config_per_extruder.reserve(extruder_count); prime_tower_config_per_extruder.reserve(extruder_count); - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; for (size_t extruder_nr = 0; extruder_nr < extruder_count; extruder_nr++) { - const ExtruderTrain& train = Application::getInstance().current_slice->scene.extruders[extruder_nr]; + const ExtruderTrain& train = Application::getInstance().current_slice_->scene.extruders[extruder_nr]; travel_config_per_extruder.emplace_back(GCodePathConfig{ .type = PrintFeatureType::MoveCombing, .line_width = 0, .layer_thickness = 0, @@ -151,8 +151,8 @@ PathConfigStorage::PathConfigStorage(const SliceDataStorage& storage, const Laye handleInitialLayerSpeedup(storage, layer_nr, initial_speedup_layer_count); } - const auto layer_height = Application::getInstance().current_slice->scene.current_mesh_group->settings.get("layer_height"); - const auto support_top_distance = Application::getInstance().current_slice->scene.current_mesh_group->settings.get("support_top_distance"); + const auto layer_height = Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("layer_height"); + const auto support_top_distance = Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("support_top_distance"); const coord_t leftover_support_distance = support_top_distance % layer_height; support_fractional_infill_config = support_infill_config; // copy @@ -183,8 +183,8 @@ void MeshPathConfigs::smoothAllSpeeds(const SpeedDerivatives& first_layer_config void PathConfigStorage::handleInitialLayerSpeedup(const SliceDataStorage& storage, const LayerIndex& layer_nr, const size_t initial_speedup_layer_count) { std::vector global_first_layer_config_per_extruder; - global_first_layer_config_per_extruder.reserve(Application::getInstance().current_slice->scene.extruders.size()); - for (const ExtruderTrain& extruder : Application::getInstance().current_slice->scene.extruders) + global_first_layer_config_per_extruder.reserve(Application::getInstance().current_slice_->scene.extruders.size()); + for (const ExtruderTrain& extruder : Application::getInstance().current_slice_->scene.extruders) { global_first_layer_config_per_extruder.emplace_back(SpeedDerivatives{ .speed = extruder.settings_.get("speed_print_layer_0"), .acceleration = extruder.settings_.get("acceleration_print_layer_0"), @@ -194,7 +194,7 @@ void PathConfigStorage::handleInitialLayerSpeedup(const SliceDataStorage& storag { // support if (layer_nr < static_cast(initial_speedup_layer_count)) { - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; const size_t extruder_nr_support_infill = mesh_group_settings.get((layer_nr <= 0) ? "support_extruder_nr_layer_0" : "support_infill_extruder_nr").extruder_nr_; for (unsigned int idx = 0; idx < MAX_INFILL_COMBINE; idx++) @@ -218,9 +218,9 @@ void PathConfigStorage::handleInitialLayerSpeedup(const SliceDataStorage& storag } { // extruder configs: travel, skirt/brim (= shield) - for (size_t extruder_nr = 0; extruder_nr < Application::getInstance().current_slice->scene.extruders.size(); extruder_nr++) + for (size_t extruder_nr = 0; extruder_nr < Application::getInstance().current_slice_->scene.extruders.size(); extruder_nr++) { - const ExtruderTrain& train = Application::getInstance().current_slice->scene.extruders[extruder_nr]; + const ExtruderTrain& train = Application::getInstance().current_slice_->scene.extruders[extruder_nr]; const SpeedDerivatives initial_layer_travel_speed_config{ .speed = train.settings_.get("speed_travel_layer_0"), .acceleration = train.settings_.get("acceleration_travel_layer_0"), .jerk = train.settings_.get("jerk_travel_layer_0") }; diff --git a/src/settings/Settings.cpp b/src/settings/Settings.cpp index 9b8e609df4..ffc89a274b 100644 --- a/src/settings/Settings.cpp +++ b/src/settings/Settings.cpp @@ -60,7 +60,7 @@ std::string Settings::get(const std::string& key) const return settings.at(key); } - const std::unordered_map& limit_to_extruder = Application::getInstance().current_slice->scene.limit_to_extruder; + const std::unordered_map& limit_to_extruder = Application::getInstance().current_slice_->scene.limit_to_extruder; if (limit_to_extruder.find(key) != limit_to_extruder.end()) { return limit_to_extruder.at(key)->settings_.getWithoutLimiting(key); @@ -113,7 +113,7 @@ ExtruderTrain& Settings::get(const std::string& key) const { extruder_nr = get("extruder_nr"); } - return Application::getInstance().current_slice->scene.extruders[extruder_nr]; + return Application::getInstance().current_slice_->scene.extruders[extruder_nr]; } template<> @@ -123,14 +123,14 @@ std::vector Settings::get>(const std std::vector ret; if (extruder_nr < 0) { - for (ExtruderTrain& train : Application::getInstance().current_slice->scene.extruders) + for (ExtruderTrain& train : Application::getInstance().current_slice_->scene.extruders) { ret.emplace_back(&train); } } else { - ret.emplace_back(&Application::getInstance().current_slice->scene.extruders[extruder_nr]); + ret.emplace_back(&Application::getInstance().current_slice_->scene.extruders[extruder_nr]); } return ret; } diff --git a/src/sliceDataStorage.cpp b/src/sliceDataStorage.cpp index bbffb53e7d..37453a303c 100644 --- a/src/sliceDataStorage.cpp +++ b/src/sliceDataStorage.cpp @@ -245,7 +245,7 @@ Point SliceMeshStorage::getZSeamHint() const std::vector SliceDataStorage::initializeRetractionAndWipeConfigs() { std::vector ret; - ret.resize(Application::getInstance().current_slice->scene.extruders.size()); // initializes with constructor RetractionConfig() + ret.resize(Application::getInstance().current_slice_->scene.extruders.size()); // initializes with constructor RetractionConfig() return ret; } @@ -254,7 +254,7 @@ SliceDataStorage::SliceDataStorage() , retraction_wipe_config_per_extruder(initializeRetractionAndWipeConfigs()) , max_print_height_second_to_last_extruder(-1) { - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; Point3 machine_max(mesh_group_settings.get("machine_width"), mesh_group_settings.get("machine_depth"), mesh_group_settings.get("machine_height")); Point3 machine_min(0, 0, 0); if (mesh_group_settings.get("machine_center_is_zero")) @@ -270,7 +270,7 @@ Polygons SliceDataStorage::getLayerOutlines(const LayerIndex layer_nr, const bool include_support, const bool include_prime_tower, const bool external_polys_only, const int extruder_nr) const { - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; if (layer_nr < 0 && layer_nr < -static_cast(Raft::getFillerLayerCount())) { // when processing raft if (include_support && (extruder_nr == -1 || extruder_nr == int(mesh_group_settings.get("adhesion_extruder_nr").extruder_nr_))) @@ -343,13 +343,13 @@ Polygons std::vector SliceDataStorage::getExtrudersUsed() const { std::vector ret; - ret.resize(Application::getInstance().current_slice->scene.extruders.size(), false); + ret.resize(Application::getInstance().current_slice_->scene.extruders.size(), false); - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; const EPlatformAdhesion adhesion_type = mesh_group_settings.get("adhesion_type"); if (adhesion_type == EPlatformAdhesion::SKIRT || adhesion_type == EPlatformAdhesion::BRIM) { - for (size_t extruder_nr = 0; extruder_nr < Application::getInstance().current_slice->scene.extruders.size(); extruder_nr++) + for (size_t extruder_nr = 0; extruder_nr < Application::getInstance().current_slice_->scene.extruders.size(); extruder_nr++) { if (! skirt_brim[extruder_nr].empty()) { @@ -411,10 +411,10 @@ std::vector SliceDataStorage::getExtrudersUsed() const std::vector SliceDataStorage::getExtrudersUsed(const LayerIndex layer_nr) const { - const std::vector& extruders = Application::getInstance().current_slice->scene.extruders; + const std::vector& extruders = Application::getInstance().current_slice_->scene.extruders; std::vector ret; ret.resize(extruders.size(), false); - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; const EPlatformAdhesion adhesion_type = mesh_group_settings.get("adhesion_type"); bool include_adhesion = true; @@ -521,18 +521,18 @@ std::vector SliceDataStorage::getExtrudersUsed(const LayerIndex layer_nr) bool SliceDataStorage::getExtruderPrimeBlobEnabled(const size_t extruder_nr) const { - if (extruder_nr >= Application::getInstance().current_slice->scene.extruders.size()) + if (extruder_nr >= Application::getInstance().current_slice_->scene.extruders.size()) { return false; } - const ExtruderTrain& train = Application::getInstance().current_slice->scene.extruders[extruder_nr]; + const ExtruderTrain& train = Application::getInstance().current_slice_->scene.extruders[extruder_nr]; return train.settings_.get("prime_blob_enable"); } Polygons SliceDataStorage::getMachineBorder(int checking_extruder_nr) const { - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; Polygons border; border.emplace_back(); @@ -583,7 +583,7 @@ Polygons SliceDataStorage::getMachineBorder(int checking_extruder_nr) const { continue; } - Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder_nr].settings_; + Settings& extruder_settings = Application::getInstance().current_slice_->scene.extruders[extruder_nr].settings_; if (! (extruder_settings.get("prime_blob_enable") && mesh_group_settings.get("extruder_prime_pos_abs"))) { continue; @@ -608,7 +608,7 @@ Polygons SliceDataStorage::getMachineBorder(int checking_extruder_nr) const { continue; } - Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder_nr].settings_; + Settings& extruder_settings = Application::getInstance().current_slice_->scene.extruders[extruder_nr].settings_; Point translation(extruder_settings.get("machine_nozzle_offset_x"), extruder_settings.get("machine_nozzle_offset_y")); Polygons extruder_border = disallowed_areas; extruder_border.translate(translation); @@ -633,7 +633,7 @@ Polygons SliceDataStorage::getMachineBorder(int checking_extruder_nr) const { continue; } - Settings& extruder_settings = Application::getInstance().current_slice->scene.extruders[extruder_nr].settings_; + Settings& extruder_settings = Application::getInstance().current_slice_->scene.extruders[extruder_nr].settings_; Point translation(extruder_settings.get("machine_nozzle_offset_x"), extruder_settings.get("machine_nozzle_offset_y")); for (size_t other_extruder_nr = 0; other_extruder_nr < extruder_is_used.size(); other_extruder_nr++) { @@ -642,7 +642,7 @@ Polygons SliceDataStorage::getMachineBorder(int checking_extruder_nr) const { continue; } - Settings& other_extruder_settings = Application::getInstance().current_slice->scene.extruders[other_extruder_nr].settings_; + Settings& other_extruder_settings = Application::getInstance().current_slice_->scene.extruders[other_extruder_nr].settings_; Point other_translation(other_extruder_settings.get("machine_nozzle_offset_x"), other_extruder_settings.get("machine_nozzle_offset_y")); Polygons translated_border = border; translated_border.translate(translation - other_translation); diff --git a/src/slicer.cpp b/src/slicer.cpp index 832589deb1..c2d62866ff 100644 --- a/src/slicer.cpp +++ b/src/slicer.cpp @@ -808,7 +808,7 @@ Slicer::Slicer(Mesh* i_mesh, const coord_t thickness, const size_t slice_layer_c : mesh(i_mesh) { const SlicingTolerance slicing_tolerance = mesh->settings_.get("slicing_tolerance"); - const coord_t initial_layer_thickness = Application::getInstance().current_slice->scene.current_mesh_group->settings.get("layer_height_0"); + const coord_t initial_layer_thickness = Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("layer_height_0"); assert(slice_layer_count > 0); diff --git a/src/support.cpp b/src/support.cpp index fb896445ce..bfbd4ab8f9 100644 --- a/src/support.cpp +++ b/src/support.cpp @@ -90,7 +90,7 @@ void AreaSupport::splitGlobalSupportAreasIntoSupportInfillParts( size_t min_layer = 0; size_t max_layer = total_layer_count - 1; - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; const ExtruderTrain& infill_extruder = mesh_group_settings.get("support_infill_extruder_nr"); const EFillMethod support_pattern = infill_extruder.settings_.get("support_pattern"); const coord_t support_line_width = infill_extruder.settings_.get("support_line_width"); @@ -180,7 +180,7 @@ void AreaSupport::generateGradualSupport(SliceDataStorage& storage) // -> Note that this function only does the above, which is identifying and storing support infill areas with densities. // The actual printing part is done in FffGcodeWriter. // - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; const size_t total_layer_count = storage.print_layer_count; const ExtruderTrain& infill_extruder = mesh_group_settings.get("support_infill_extruder_nr"); const coord_t gradual_support_step_height = infill_extruder.settings_.get("gradual_support_infill_step_height"); @@ -314,7 +314,7 @@ void AreaSupport::generateGradualSupport(SliceDataStorage& storage) void AreaSupport::combineSupportInfillLayers(SliceDataStorage& storage) { - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; const unsigned int total_layer_count = storage.print_layer_count; const coord_t layer_height = mesh_group_settings.get("layer_height"); // How many support infill layers to combine to obtain the requested sparse thickness. @@ -417,7 +417,7 @@ void AreaSupport::combineSupportInfillLayers(SliceDataStorage& storage) void AreaSupport::cleanup(SliceDataStorage& storage) { - const coord_t support_line_width = Application::getInstance().current_slice->scene.current_mesh_group->settings.get("support_line_width"); + const coord_t support_line_width = Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("support_line_width"); for (LayerIndex layer_nr = 0; layer_nr < storage.support.supportLayers.size(); layer_nr++) { SupportLayer& layer = storage.support.supportLayers[layer_nr]; @@ -462,7 +462,7 @@ Polygons AreaSupport::join(const SliceDataStorage& storage, const Polygons& supp { Polygons joined; - const Settings& infill_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings.get("support_infill_extruder_nr").settings_; + const Settings& infill_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("support_infill_extruder_nr").settings_; const AngleRadians conical_support_angle = infill_settings.get("support_conical_angle"); const coord_t layer_thickness = infill_settings.get("layer_height"); coord_t conical_support_offset; @@ -477,7 +477,7 @@ Polygons AreaSupport::join(const SliceDataStorage& storage, const Polygons& supp const bool conical_support = infill_settings.get("support_conical_enabled") && conical_support_angle != 0; if (conical_support) { - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; // Don't go outside the build volume. Polygons machine_volume_border; switch (mesh_group_settings.get("machine_shape")) @@ -508,13 +508,13 @@ Polygons AreaSupport::join(const SliceDataStorage& storage, const Polygons& supp coord_t adhesion_size = 0; // Make sure there is enough room for the platform adhesion around support. coord_t extra_skirt_line_width = 0; const std::vector is_extruder_used = storage.getExtrudersUsed(); - for (size_t extruder_nr = 0; extruder_nr < Application::getInstance().current_slice->scene.extruders.size(); extruder_nr++) + for (size_t extruder_nr = 0; extruder_nr < Application::getInstance().current_slice_->scene.extruders.size(); extruder_nr++) { if (! is_extruder_used[extruder_nr]) // Unused extruders and the primary adhesion extruder don't generate an extra skirt line. { continue; } - const ExtruderTrain& other_extruder = Application::getInstance().current_slice->scene.extruders[extruder_nr]; + const ExtruderTrain& other_extruder = Application::getInstance().current_slice_->scene.extruders[extruder_nr]; extra_skirt_line_width += other_extruder.settings_.get("skirt_brim_line_width") * other_extruder.settings_.get("initial_layer_line_width_factor"); } const std::vector skirt_brim_extruders = mesh_group_settings.get>("skirt_brim_extruder_nr"); @@ -636,7 +636,7 @@ void AreaSupport::generateSupportAreas(SliceDataStorage& storage) // generate support areas bool support_meshes_drop_down_handled = false; bool support_meshes_handled = false; - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; for (unsigned int mesh_idx = 0; mesh_idx < storage.meshes.size(); mesh_idx++) { SliceMeshStorage& mesh = *storage.meshes[mesh_idx]; @@ -709,7 +709,7 @@ void AreaSupport::generateSupportAreas(SliceDataStorage& storage) void AreaSupport::precomputeCrossInfillTree(SliceDataStorage& storage) { - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; const ExtruderTrain& infill_extruder = mesh_group_settings.get("support_infill_extruder_nr"); const EFillMethod& support_pattern = infill_extruder.settings_.get("support_pattern"); if ((support_pattern == EFillMethod::CROSS || support_pattern == EFillMethod::CROSS_3D) && infill_extruder.settings_.get("support_line_distance") > 0) @@ -783,7 +783,7 @@ void AreaSupport::generateOverhangAreasForMesh(SliceDataStorage& storage, SliceM } // Don't generate overhang areas if the Z distance is higher than the objects we're generating support for. - const coord_t layer_height = Application::getInstance().current_slice->scene.current_mesh_group->settings.get("layer_height"); + const coord_t layer_height = Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("layer_height"); const coord_t z_distance_top = mesh.settings.get("support_top_distance"); const size_t z_distance_top_layers = (z_distance_top / layer_height) + 1; if (z_distance_top_layers + 1 > storage.print_layer_count) @@ -815,7 +815,7 @@ void AreaSupport::generateOverhangAreasForMesh(SliceDataStorage& storage, SliceM Polygons AreaSupport::generateVaryingXYDisallowedArea(const SliceMeshStorage& storage, const Settings& infill_settings, const LayerIndex layer_idx) { - const auto& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const auto& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; const Simplify simplify{ mesh_group_settings }; const auto layer_thickness = mesh_group_settings.get("layer_height"); const auto support_distance_top = static_cast(mesh_group_settings.get("support_top_distance")); @@ -1040,7 +1040,7 @@ void AreaSupport::generateSupportAreasForMesh( { return; } - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; const ESupportType support_type = mesh_group_settings.get("support_type"); if (support_type == ESupportType::NONE && ! is_support_mesh_place_holder) { @@ -1739,7 +1739,7 @@ void AreaSupport::handleWallStruts(const Settings& settings, Polygons& supportLa void AreaSupport::generateSupportBottom(SliceDataStorage& storage, const SliceMeshStorage& mesh, std::vector& global_support_areas_per_layer) { - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; const coord_t layer_height = mesh_group_settings.get("layer_height"); const size_t bottom_layer_count = round_divide(mesh.settings.get("support_bottom_height"), layer_height); // Number of layers in support bottom. if (bottom_layer_count <= 0) @@ -1776,7 +1776,7 @@ void AreaSupport::generateSupportBottom(SliceDataStorage& storage, const SliceMe void AreaSupport::generateSupportRoof(SliceDataStorage& storage, const SliceMeshStorage& mesh, std::vector& global_support_areas_per_layer) { - const Settings& mesh_group_settings = Application::getInstance().current_slice->scene.current_mesh_group->settings; + const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; const coord_t layer_height = mesh_group_settings.get("layer_height"); const size_t roof_layer_count = round_divide(mesh.settings.get("support_roof_height"), layer_height); // Number of layers in support roof. if (roof_layer_count <= 0) diff --git a/tests/GCodeExportTest.cpp b/tests/GCodeExportTest.cpp index 696bbaffcf..e85b6fb2da 100644 --- a/tests/GCodeExportTest.cpp +++ b/tests/GCodeExportTest.cpp @@ -70,16 +70,16 @@ class GCodeExportTest : public testing::Test gcode.machine_name = "Your favourite 3D printer"; // Set up a scene so that we may request settings. - Application::getInstance().current_slice = new Slice(1); + Application::getInstance().current_slice_ = new Slice(1); mock_communication = new MockCommunication(); - Application::getInstance().communication = mock_communication; + Application::getInstance().communication_ = mock_communication; } void TearDown() override { - delete Application::getInstance().current_slice; - delete Application::getInstance().communication; - Application::getInstance().communication = nullptr; + delete Application::getInstance().current_slice_; + delete Application::getInstance().communication_; + Application::getInstance().communication_ = nullptr; } }; // NOLINTEND(misc-non-private-member-variables-in-classes) @@ -228,12 +228,12 @@ class GriffinHeaderTest : public testing::TestWithParam gcode.machine_name = "Your favourite 3D printer"; // Set up a scene so that we may request settings. - Application::getInstance().current_slice = new Slice(0); + Application::getInstance().current_slice_ = new Slice(0); } void TearDown() override { - delete Application::getInstance().current_slice; + delete Application::getInstance().current_slice_; } }; // NOLINTEND(misc-non-private-member-variables-in-classes) @@ -244,8 +244,8 @@ TEST_P(GriffinHeaderTest, HeaderGriffinFormat) gcode.flavor = EGCodeFlavor::GRIFFIN; for (size_t extruder_index = 0; extruder_index < num_extruders; extruder_index++) { - Application::getInstance().current_slice->scene.extruders.emplace_back(extruder_index, nullptr); - ExtruderTrain& train = Application::getInstance().current_slice->scene.extruders.back(); + Application::getInstance().current_slice_->scene.extruders.emplace_back(extruder_index, nullptr); + ExtruderTrain& train = Application::getInstance().current_slice_->scene.extruders.back(); train.settings_.add("machine_nozzle_size", "0.4"); train.settings_.add("machine_nozzle_id", "TestNozzle"); } @@ -324,8 +324,8 @@ TEST_F(GCodeExportTest, HeaderUltiGCode) const std::vector filament_used = { 100, 200 }; for (size_t extruder_index = 0; extruder_index < num_extruders; extruder_index++) { - Application::getInstance().current_slice->scene.extruders.emplace_back(extruder_index, nullptr); - ExtruderTrain& train = Application::getInstance().current_slice->scene.extruders.back(); + Application::getInstance().current_slice_->scene.extruders.emplace_back(extruder_index, nullptr); + ExtruderTrain& train = Application::getInstance().current_slice_->scene.extruders.back(); train.settings_.add("machine_nozzle_size", "0.4"); } gcode.total_bounding_box = AABB3D(Point3(0, 0, 0), Point3(1000, 1000, 1000)); @@ -340,7 +340,7 @@ TEST_F(GCodeExportTest, HeaderUltiGCode) TEST_F(GCodeExportTest, HeaderRepRap) { - Application::getInstance().current_slice->scene.current_mesh_group->settings.add("layer_height", "0.123"); + Application::getInstance().current_slice_->scene.current_mesh_group->settings.add("layer_height", "0.123"); gcode.flavor = EGCodeFlavor::REPRAP; gcode.extruder_attr[0].filament_area = 5.0; gcode.extruder_attr[1].filament_area = 4.0; @@ -360,7 +360,7 @@ TEST_F(GCodeExportTest, HeaderRepRap) TEST_F(GCodeExportTest, HeaderMarlin) { - Application::getInstance().current_slice->scene.current_mesh_group->settings.add("layer_height", "0.123"); + Application::getInstance().current_slice_->scene.current_mesh_group->settings.add("layer_height", "0.123"); gcode.flavor = EGCodeFlavor::MARLIN; gcode.extruder_attr[0].filament_area = 5.0; gcode.extruder_attr[1].filament_area = 4.0; @@ -380,7 +380,7 @@ TEST_F(GCodeExportTest, HeaderMarlin) TEST_F(GCodeExportTest, HeaderMarlinVolumetric) { - Application::getInstance().current_slice->scene.current_mesh_group->settings.add("layer_height", "0.123"); + Application::getInstance().current_slice_->scene.current_mesh_group->settings.add("layer_height", "0.123"); gcode.flavor = EGCodeFlavor::MARLIN_VOLUMATRIC; constexpr size_t num_extruders = 2; const std::vector extruder_is_used(num_extruders, true); @@ -455,7 +455,7 @@ TEST_F(GCodeExportTest, EVsMmLinear) */ TEST_F(GCodeExportTest, SwitchExtruderSimple) { - Scene& scene = Application::getInstance().current_slice->scene; + Scene& scene = Application::getInstance().current_slice_->scene; scene.extruders.emplace_back(0, nullptr); ExtruderTrain& train1 = scene.extruders.back(); @@ -488,8 +488,8 @@ TEST_F(GCodeExportTest, WriteZHopStartZero) TEST_F(GCodeExportTest, WriteZHopStartDefaultSpeed) { - Application::getInstance().current_slice->scene.extruders.emplace_back(0, nullptr); - Application::getInstance().current_slice->scene.extruders[gcode.current_extruder].settings_.add("speed_z_hop", "1"); // 60mm/min. + Application::getInstance().current_slice_->scene.extruders.emplace_back(0, nullptr); + Application::getInstance().current_slice_->scene.extruders[gcode.current_extruder].settings_.add("speed_z_hop", "1"); // 60mm/min. gcode.current_layer_z = 2000; constexpr coord_t hop_height = 3000; gcode.writeZhopStart(hop_height); @@ -498,8 +498,8 @@ TEST_F(GCodeExportTest, WriteZHopStartDefaultSpeed) TEST_F(GCodeExportTest, WriteZHopStartCustomSpeed) { - Application::getInstance().current_slice->scene.extruders.emplace_back(0, nullptr); - Application::getInstance().current_slice->scene.extruders[gcode.current_extruder].settings_.add("speed_z_hop", "1"); // 60mm/min. + Application::getInstance().current_slice_->scene.extruders.emplace_back(0, nullptr); + Application::getInstance().current_slice_->scene.extruders[gcode.current_extruder].settings_.add("speed_z_hop", "1"); // 60mm/min. gcode.current_layer_z = 2000; constexpr coord_t hop_height = 3000; constexpr Velocity speed{ 4.0 }; // 240 mm/min. @@ -516,8 +516,8 @@ TEST_F(GCodeExportTest, WriteZHopEndZero) TEST_F(GCodeExportTest, WriteZHopEndDefaultSpeed) { - Application::getInstance().current_slice->scene.extruders.emplace_back(0, nullptr); - Application::getInstance().current_slice->scene.extruders[gcode.current_extruder].settings_.add("speed_z_hop", "1"); // 60mm/min. + Application::getInstance().current_slice_->scene.extruders.emplace_back(0, nullptr); + Application::getInstance().current_slice_->scene.extruders[gcode.current_extruder].settings_.add("speed_z_hop", "1"); // 60mm/min. gcode.current_layer_z = 2000; gcode.is_z_hopped = 3000; gcode.writeZhopEnd(); @@ -526,8 +526,8 @@ TEST_F(GCodeExportTest, WriteZHopEndDefaultSpeed) TEST_F(GCodeExportTest, WriteZHopEndCustomSpeed) { - Application::getInstance().current_slice->scene.extruders.emplace_back(0, nullptr); - Application::getInstance().current_slice->scene.extruders[gcode.current_extruder].settings_.add("speed_z_hop", "1"); + Application::getInstance().current_slice_->scene.extruders.emplace_back(0, nullptr); + Application::getInstance().current_slice_->scene.extruders[gcode.current_extruder].settings_.add("speed_z_hop", "1"); gcode.current_layer_z = 2000; gcode.is_z_hopped = 3000; constexpr Velocity speed{ 4.0 }; // 240 mm/min. @@ -540,7 +540,7 @@ TEST_F(GCodeExportTest, insertWipeScriptSingleMove) gcode.currentPosition = Point3(1000, 1000, 1000); gcode.current_layer_z = 1000; gcode.use_extruder_offset_to_offset_coords = false; - Application::getInstance().current_slice->scene.current_mesh_group->settings.add("layer_height", "0.2"); + Application::getInstance().current_slice_->scene.current_mesh_group->settings.add("layer_height", "0.2"); WipeScriptConfig config; config.retraction_enable = false; @@ -572,7 +572,7 @@ TEST_F(GCodeExportTest, insertWipeScriptMultipleMoves) gcode.currentPosition = Point3(1000, 1000, 1000); gcode.current_layer_z = 1000; gcode.use_extruder_offset_to_offset_coords = false; - Application::getInstance().current_slice->scene.current_mesh_group->settings.add("layer_height", "0.2"); + Application::getInstance().current_slice_->scene.current_mesh_group->settings.add("layer_height", "0.2"); WipeScriptConfig config; config.retraction_enable = false; @@ -610,7 +610,7 @@ TEST_F(GCodeExportTest, insertWipeScriptOptionalDelay) gcode.currentPosition = Point3(1000, 1000, 1000); gcode.current_layer_z = 1000; gcode.use_extruder_offset_to_offset_coords = false; - Application::getInstance().current_slice->scene.current_mesh_group->settings.add("layer_height", "0.2"); + Application::getInstance().current_slice_->scene.current_mesh_group->settings.add("layer_height", "0.2"); WipeScriptConfig config; config.retraction_enable = false; @@ -647,9 +647,9 @@ TEST_F(GCodeExportTest, insertWipeScriptRetractionEnable) gcode.extruder_attr[0].filament_area = 10.0; gcode.relative_extrusion = false; gcode.currentSpeed = 1.0; - Application::getInstance().current_slice->scene.current_mesh_group->settings.add("layer_height", "0.2"); - Application::getInstance().current_slice->scene.extruders.emplace_back(0, &Application::getInstance().current_slice->scene.current_mesh_group->settings); - Application::getInstance().current_slice->scene.extruders.back().settings_.add("machine_firmware_retract", "false"); + Application::getInstance().current_slice_->scene.current_mesh_group->settings.add("layer_height", "0.2"); + Application::getInstance().current_slice_->scene.extruders.emplace_back(0, &Application::getInstance().current_slice_->scene.current_mesh_group->settings); + Application::getInstance().current_slice_->scene.extruders.back().settings_.add("machine_firmware_retract", "false"); WipeScriptConfig config; config.retraction_enable = true; @@ -690,7 +690,7 @@ TEST_F(GCodeExportTest, insertWipeScriptHopEnable) gcode.current_layer_z = 1000; gcode.use_extruder_offset_to_offset_coords = false; gcode.currentSpeed = 1.0; - Application::getInstance().current_slice->scene.current_mesh_group->settings.add("layer_height", "0.2"); + Application::getInstance().current_slice_->scene.current_mesh_group->settings.add("layer_height", "0.2"); WipeScriptConfig config; config.retraction_enable = false; diff --git a/tests/LayerPlanTest.cpp b/tests/LayerPlanTest.cpp index e7428f421c..0cfecdec15 100644 --- a/tests/LayerPlanTest.cpp +++ b/tests/LayerPlanTest.cpp @@ -76,10 +76,10 @@ class LayerPlanTest : public testing::Test SliceDataStorage* setUpStorage() { constexpr size_t num_mesh_groups = 1; - Application::getInstance().current_slice = new Slice(num_mesh_groups); + Application::getInstance().current_slice_ = new Slice(num_mesh_groups); // Define all settings in the mesh group. The extruder train and model settings will fall back on that then. - settings = &Application::getInstance().current_slice->scene.current_mesh_group->settings; + settings = &Application::getInstance().current_slice_->scene.current_mesh_group->settings; // Default settings. These are not (always) the FDM printer defaults, but sometimes just setting values that can be recognised // uniquely as much as possible. settings->add("acceleration_prime_tower", "5008"); @@ -176,7 +176,7 @@ class LayerPlanTest : public testing::Test settings->add("travel_avoid_other_parts", "true"); settings->add("travel_avoid_supports", "true"); - Application::getInstance().current_slice->scene.extruders.emplace_back(0, settings); // Add an extruder train. + Application::getInstance().current_slice_->scene.extruders.emplace_back(0, settings); // Add an extruder train. // Set the fan speed layer time settings (since the LayerPlan constructor copies these). FanSpeedLayerTimeSettings fan_settings; @@ -216,7 +216,7 @@ class LayerPlanTest : public testing::Test void TearDown() override { delete storage; - delete Application::getInstance().current_slice; + delete Application::getInstance().current_slice_; } }; diff --git a/tests/arcus/ArcusCommunicationPrivateTest.cpp b/tests/arcus/ArcusCommunicationPrivateTest.cpp index b35f7fdf25..29d33d94c0 100644 --- a/tests/arcus/ArcusCommunicationPrivateTest.cpp +++ b/tests/arcus/ArcusCommunicationPrivateTest.cpp @@ -31,7 +31,7 @@ class ArcusCommunicationPrivateTest : public testing::Test { instance = new ArcusCommunication::Private(); instance->socket = new MockSocket(); - Application::getInstance().current_slice = new Slice(GK_TEST_NUM_MESH_GROUPS); + Application::getInstance().current_slice_ = new Slice(GK_TEST_NUM_MESH_GROUPS); } void TearDown() override @@ -39,7 +39,7 @@ class ArcusCommunicationPrivateTest : public testing::Test delete instance->socket; delete instance; - delete Application::getInstance().current_slice; + delete Application::getInstance().current_slice_; } /* @@ -92,7 +92,7 @@ TEST_F(ArcusCommunicationPrivateTest, ReadGlobalSettingsMessage) instance->readGlobalSettingsMessage(global_settings); // Check if they are equal in general: - const auto& settings = Application::getInstance().current_slice->scene.settings; + const auto& settings = Application::getInstance().current_slice_->scene.settings; for (const auto& entry : raw_settings) { EXPECT_EQ(settings.get(entry.first), entry.second); @@ -114,12 +114,12 @@ TEST_F(ArcusCommunicationPrivateTest, ReadSingleExtruderSettingsMessage) const std::string setting_value = "You put the 'sexy' in 'dyslexic'."; setting->set_value(setting_value); - Application::getInstance().current_slice->scene.settings.add("machine_extruder_count", "1"); + Application::getInstance().current_slice_->scene.settings.add("machine_extruder_count", "1"); // Run the call that we're testing. instance->readExtruderSettingsMessage(messages); - ASSERT_EQ(size_t(1), Application::getInstance().current_slice->scene.extruders.size()) << "Reading the extruders must construct the correct amount of extruders in the scene."; - EXPECT_EQ(setting_value, Application::getInstance().current_slice->scene.extruders[0].settings_.get("test_setting")); + ASSERT_EQ(size_t(1), Application::getInstance().current_slice_->scene.extruders.size()) << "Reading the extruders must construct the correct amount of extruders in the scene."; + EXPECT_EQ(setting_value, Application::getInstance().current_slice_->scene.extruders[0].settings_.get("test_setting")); } TEST_F(ArcusCommunicationPrivateTest, ReadMultiExtruderSettingsMessage) @@ -142,13 +142,13 @@ TEST_F(ArcusCommunicationPrivateTest, ReadMultiExtruderSettingsMessage) second_setting->set_name("What extruder are you?"); second_setting->set_value("Second"); - Application::getInstance().current_slice->scene.settings.add("machine_extruder_count", "2"); + Application::getInstance().current_slice_->scene.settings.add("machine_extruder_count", "2"); // Run the call that we're testing. instance->readExtruderSettingsMessage(messages); - ASSERT_EQ(size_t(2), Application::getInstance().current_slice->scene.extruders.size()) << "Reading the extruders must construct the correct amount of extruders in the scene."; - EXPECT_EQ(std::string("First"), Application::getInstance().current_slice->scene.extruders[0].settings_.get("What extruder are you?")); - EXPECT_EQ(std::string("Second"), Application::getInstance().current_slice->scene.extruders[1].settings_.get("What extruder are you?")); + ASSERT_EQ(size_t(2), Application::getInstance().current_slice_->scene.extruders.size()) << "Reading the extruders must construct the correct amount of extruders in the scene."; + EXPECT_EQ(std::string("First"), Application::getInstance().current_slice_->scene.extruders[0].settings_.get("What extruder are you?")); + EXPECT_EQ(std::string("Second"), Application::getInstance().current_slice_->scene.extruders[1].settings_.get("What extruder are you?")); } TEST_F(ArcusCommunicationPrivateTest, ReadMeshGroupMessage) @@ -206,7 +206,7 @@ TEST_F(ArcusCommunicationPrivateTest, ReadMeshGroupMessage) instance->readMeshGroupMessage(mesh_message); // Checks: - auto& scene = Application::getInstance().current_slice->scene; + auto& scene = Application::getInstance().current_slice_->scene; ASSERT_FALSE(scene.mesh_groups.empty()); auto& meshes = scene.mesh_groups[0].meshes; diff --git a/tests/integration/SlicePhaseTest.cpp b/tests/integration/SlicePhaseTest.cpp index 406554fd08..42508af961 100644 --- a/tests/integration/SlicePhaseTest.cpp +++ b/tests/integration/SlicePhaseTest.cpp @@ -30,10 +30,10 @@ class SlicePhaseTest : public testing::Test Application::getInstance().startThreadPool(); // Set up a scene so that we may request settings. - Application::getInstance().current_slice = new Slice(1); + Application::getInstance().current_slice_ = new Slice(1); // And a few settings that we want to default. - Scene& scene = Application::getInstance().current_slice->scene; + Scene& scene = Application::getInstance().current_slice_->scene; scene.settings.add("slicing_tolerance", "middle"); scene.settings.add("layer_height_0", "0.2"); scene.settings.add("layer_height", "0.1"); @@ -66,7 +66,7 @@ class SlicePhaseTest : public testing::Test TEST_F(SlicePhaseTest, Cube) { - Scene& scene = Application::getInstance().current_slice->scene; + Scene& scene = Application::getInstance().current_slice_->scene; MeshGroup& mesh_group = scene.mesh_groups.back(); const FMatrix4x3 transformation; @@ -126,7 +126,7 @@ TEST_F(SlicePhaseTest, Cube) TEST_F(SlicePhaseTest, Cylinder1000) { - Scene& scene = Application::getInstance().current_slice->scene; + Scene& scene = Application::getInstance().current_slice_->scene; MeshGroup& mesh_group = scene.mesh_groups.back(); const FMatrix4x3 transformation; diff --git a/tests/settings/SettingsTest.cpp b/tests/settings/SettingsTest.cpp index 648cca2e51..ecc9884a00 100644 --- a/tests/settings/SettingsTest.cpp +++ b/tests/settings/SettingsTest.cpp @@ -86,7 +86,7 @@ TEST_F(SettingsTest, AddSettingExtruderTrain) { // Add a slice with some extruder trains. std::shared_ptr current_slice = std::make_shared(0); - Application::getInstance().current_slice = current_slice.get(); + Application::getInstance().current_slice_ = current_slice.get(); current_slice->scene.extruders.emplace_back(0, nullptr); current_slice->scene.extruders.emplace_back(1, nullptr); current_slice->scene.extruders.emplace_back(2, nullptr); @@ -220,7 +220,7 @@ TEST_F(SettingsTest, OverwriteSetting) TEST_F(SettingsTest, Inheritance) { std::shared_ptr current_slice = std::make_shared(0); - Application::getInstance().current_slice = current_slice.get(); + Application::getInstance().current_slice_ = current_slice.get(); const std::string value = "To be frank, I'd have to change my name."; Settings parent; @@ -237,7 +237,7 @@ TEST_F(SettingsTest, Inheritance) TEST_F(SettingsTest, LimitToExtruder) { std::shared_ptr current_slice = std::make_shared(0); - Application::getInstance().current_slice = current_slice.get(); + Application::getInstance().current_slice_ = current_slice.get(); current_slice->scene.extruders.emplace_back(0, nullptr); current_slice->scene.extruders.emplace_back(1, nullptr); current_slice->scene.extruders.emplace_back(2, nullptr); From 38f4559612e05cbd03a1ad661eebb64ce392de47 Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Tue, 21 Nov 2023 11:24:50 +0100 Subject: [PATCH 14/48] Fixed variable shadowing warnings --- include/SkirtBrim.h | 58 ++--- include/TreeSupportElement.h | 352 +++++++++++++------------- include/TreeSupportSettings.h | 10 +- src/SkirtBrim.cpp | 272 ++++++++++---------- src/TreeSupport.cpp | 429 ++++++++++++++++---------------- src/TreeSupportTipGenerator.cpp | 16 +- 6 files changed, 569 insertions(+), 568 deletions(-) diff --git a/include/SkirtBrim.h b/include/SkirtBrim.h index 896e4aac45..af8cbe9f6e 100644 --- a/include/SkirtBrim.h +++ b/include/SkirtBrim.h @@ -35,23 +35,23 @@ class SkirtBrim const size_t inset_idx, const int extruder_nr, const bool is_last) - : reference_outline_or_index(reference_outline_or_index) - , external_only(external_only) - , offset_value(offset_value) - , total_offset(total_offset) - , inset_idx(inset_idx) - , extruder_nr(extruder_nr) - , is_last(is_last) + : reference_outline_or_index_(reference_outline_or_index) + , external_only_(external_only) + , offset_value_(offset_value) + , total_offset_(total_offset) + , inset_idx_(inset_idx) + , extruder_nr_(extruder_nr) + , is_last_(is_last) { } - std::variant reference_outline_or_index; - bool external_only; //!< Wether to only offset outward from the reference polygons - coord_t offset_value; //!< Distance by which to offset from the reference - coord_t total_offset; //!< Total distance from the model - int inset_idx; //!< The outset index of this brimline - int extruder_nr; //!< The extruder by which to print this brim line - bool is_last; //!< Whether this is the last planned offset for this extruder. + std::variant reference_outline_or_index_; + bool external_only_; //!< Wether to only offset outward from the reference polygons + coord_t offset_value_; //!< Distance by which to offset from the reference + coord_t total_offset_; //!< Total distance from the model + int inset_idx_; //!< The outset index of this brimline + int extruder_nr_; //!< The extruder by which to print this brim line + bool is_last_; //!< Whether this is the last planned offset for this extruder. }; /*! @@ -60,23 +60,23 @@ class SkirtBrim static inline const auto OffsetSorter{ [](const Offset& a, const Offset& b) { // Use extruder_nr in case both extruders have the same offset settings. - return a.total_offset != b.total_offset ? a.total_offset < b.total_offset : a.extruder_nr < b.extruder_nr; + return a.total_offset_ != b.total_offset_ ? a.total_offset_ < b.total_offset_ : a.extruder_nr_ < b.extruder_nr_; } }; - SliceDataStorage& storage; //!< Where to retrieve settings and store brim lines. - const EPlatformAdhesion adhesion_type; //!< Whether we are generating brim, skirt, or raft - const bool has_ooze_shield; //!< Whether the meshgroup has an ooze shield - const bool has_draft_shield; //!< Whether the meshgroup has a draft shield - const std::vector& extruders; //!< The extruders of the current slice - const int extruder_count; //!< The total number of extruders - const std::vector extruder_is_used; //!< For each extruder whether it is actually used in this print - int first_used_extruder_nr; //!< The first extruder which is used - int skirt_brim_extruder_nr; //!< The extruder with which the skirt/brim is printed or -1 if printed with both - std::vector external_polys_only; //!< For each extruder whether to only generate brim on the outside - std::vector line_widths; //!< For each extruder the skirt/brim line width - std::vector skirt_brim_minimal_length; //!< For each extruder the minimal brim length - std::vector line_count; //!< For each extruder the (minimal) number of brim lines to generate - std::vector gap; //!< For each extruder the gap between the part and the first brim/skirt line + SliceDataStorage& storage_; //!< Where to retrieve settings and store brim lines. + const EPlatformAdhesion adhesion_type_; //!< Whether we are generating brim, skirt, or raft + const bool has_ooze_shield_; //!< Whether the meshgroup has an ooze shield + const bool has_draft_shield_; //!< Whether the meshgroup has a draft shield + const std::vector& extruders_; //!< The extruders of the current slice + const int extruder_count_; //!< The total number of extruders + const std::vector extruder_is_used_; //!< For each extruder whether it is actually used in this print + int first_used_extruder_nr_; //!< The first extruder which is used + int skirt_brim_extruder_nr_; //!< The extruder with which the skirt/brim is printed or -1 if printed with both + std::vector external_polys_only_; //!< For each extruder whether to only generate brim on the outside + std::vector line_widths_; //!< For each extruder the skirt/brim line width + std::vector skirt_brim_minimal_length_; //!< For each extruder the minimal brim length + std::vector line_count_; //!< For each extruder the (minimal) number of brim lines to generate + std::vector gap_; //!< For each extruder the gap between the part and the first brim/skirt line public: /*! diff --git a/include/TreeSupportElement.h b/include/TreeSupportElement.h index 237e22baa2..a463ce30fe 100644 --- a/include/TreeSupportElement.h +++ b/include/TreeSupportElement.h @@ -19,12 +19,12 @@ namespace cura struct AreaIncreaseSettings { AreaIncreaseSettings() : - type(AvoidanceType::FAST), - increase_speed(0), - increase_radius(false), - no_error(false), - use_min_distance(false), - move(false) + type_(AvoidanceType::FAST), + increase_speed_(0), + increase_radius_(false), + no_error_(false), + use_min_distance_(false), + move_(false) { } @@ -37,31 +37,31 @@ struct AreaIncreaseSettings bool use_min_distance, bool move ) : - type(type), - increase_speed(increase_speed), - increase_radius(increase_radius), - no_error(simplify), - use_min_distance(use_min_distance), - move(move) + type_(type), + increase_speed_(increase_speed), + increase_radius_(increase_radius), + no_error_(simplify), + use_min_distance_(use_min_distance), + move_(move) { } - AvoidanceType type; - coord_t increase_speed; - bool increase_radius; - bool no_error; - bool use_min_distance; - bool move; + AvoidanceType type_; + coord_t increase_speed_; + bool increase_radius_; + bool no_error_; + bool use_min_distance_; + bool move_; bool operator==(const AreaIncreaseSettings& other) const { return - increase_radius == other.increase_radius && - increase_speed == other.increase_speed && - type == other.type && - no_error == other.no_error && - use_min_distance == other.use_min_distance && - move == other.move; + increase_radius_ == other.increase_radius_ && + increase_speed_ == other.increase_speed_ && + type_ == other.type_ && + no_error_ == other.no_error_ && + use_min_distance_ == other.use_min_distance_ && + move_ == other.move_; } }; @@ -83,90 +83,90 @@ struct TreeSupportElement bool influence_area_limit_active, coord_t influence_area_limit_range ) : - target_height(target_height), - target_position(target_position), - next_position(target_position), - next_height(target_height), - effective_radius_height(distance_to_top), - to_buildplate(to_buildplate), - distance_to_top(distance_to_top), - area(nullptr), - result_on_layer(target_position), - increased_to_model_radius(0), - to_model_gracious(to_model_gracious), - buildplate_radius_increases(0), - use_min_xy_dist(use_min_xy_dist), - supports_roof(supports_roof), - dont_move_until(dont_move_until), - can_use_safe_radius(can_use_safe_radius), - last_area_increase(AreaIncreaseSettings(AvoidanceType::FAST, 0, false, false, false, false)), - missing_roof_layers(force_tips_to_roof ? dont_move_until : 0), - skip_ovalisation(skip_ovalisation), - all_tips({ target_position }), - influence_area_limit_active(influence_area_limit_active), - influence_area_limit_range(influence_area_limit_range + target_height_(target_height), + target_position_(target_position), + next_position_(target_position), + next_height_(target_height), + effective_radius_height_(distance_to_top), + to_buildplate_(to_buildplate), + distance_to_top_(distance_to_top), + area_(nullptr), + result_on_layer_(target_position), + increased_to_model_radius_(0), + to_model_gracious_(to_model_gracious), + buildplate_radius_increases_(0), + use_min_xy_dist_(use_min_xy_dist), + supports_roof_(supports_roof), + dont_move_until_(dont_move_until), + can_use_safe_radius_(can_use_safe_radius), + last_area_increase_(AreaIncreaseSettings(AvoidanceType::FAST, 0, false, false, false, false)), + missing_roof_layers_(force_tips_to_roof ? dont_move_until : 0), + skip_ovalisation_(skip_ovalisation), + all_tips_({ target_position }), + influence_area_limit_active_(influence_area_limit_active), + influence_area_limit_range_(influence_area_limit_range ) { RecreateInfluenceLimitArea(); } TreeSupportElement(const TreeSupportElement& elem, Polygons* newArea = nullptr) : // copy constructor with possibility to set a new area - target_height(elem.target_height), - target_position(elem.target_position), - next_position(elem.next_position), - next_height(elem.next_height), - effective_radius_height(elem.effective_radius_height), - to_buildplate(elem.to_buildplate), - distance_to_top(elem.distance_to_top), - area(newArea != nullptr ? newArea : elem.area), - result_on_layer(elem.result_on_layer), - increased_to_model_radius(elem.increased_to_model_radius), - to_model_gracious(elem.to_model_gracious), - buildplate_radius_increases(elem.buildplate_radius_increases), - use_min_xy_dist(elem.use_min_xy_dist), - supports_roof(elem.supports_roof), - dont_move_until(elem.dont_move_until), - can_use_safe_radius(elem.can_use_safe_radius), - last_area_increase(elem.last_area_increase), - missing_roof_layers(elem.missing_roof_layers), - skip_ovalisation(elem.skip_ovalisation), - all_tips(elem.all_tips), - influence_area_limit_area(elem.influence_area_limit_area), - influence_area_limit_range(elem.influence_area_limit_range), - influence_area_limit_active(elem.influence_area_limit_active) + target_height_(elem.target_height_), + target_position_(elem.target_position_), + next_position_(elem.next_position_), + next_height_(elem.next_height_), + effective_radius_height_(elem.effective_radius_height_), + to_buildplate_(elem.to_buildplate_), + distance_to_top_(elem.distance_to_top_), + area_(newArea != nullptr ? newArea : elem.area_), + result_on_layer_(elem.result_on_layer_), + increased_to_model_radius_(elem.increased_to_model_radius_), + to_model_gracious_(elem.to_model_gracious_), + buildplate_radius_increases_(elem.buildplate_radius_increases_), + use_min_xy_dist_(elem.use_min_xy_dist_), + supports_roof_(elem.supports_roof_), + dont_move_until_(elem.dont_move_until_), + can_use_safe_radius_(elem.can_use_safe_radius_), + last_area_increase_(elem.last_area_increase_), + missing_roof_layers_(elem.missing_roof_layers_), + skip_ovalisation_(elem.skip_ovalisation_), + all_tips_(elem.all_tips_), + influence_area_limit_area_(elem.influence_area_limit_area_), + influence_area_limit_range_(elem.influence_area_limit_range_), + influence_area_limit_active_(elem.influence_area_limit_active_) { - parents.insert(parents.begin(), elem.parents.begin(), elem.parents.end()); + parents_.insert(parents_.begin(), elem.parents_.begin(), elem.parents_.end()); } /*! * \brief Create a new Element for one layer below the element of the pointer supplied. */ TreeSupportElement(TreeSupportElement* element_above) : - target_height(element_above->target_height), - target_position(element_above->target_position), - next_position(element_above->next_position), - next_height(element_above->next_height), - effective_radius_height(element_above->effective_radius_height), - to_buildplate(element_above->to_buildplate), - distance_to_top(element_above->distance_to_top + 1), - area(element_above->area), - result_on_layer(Point(-1, -1)), // set to invalid as we are a new node on a new layer - increased_to_model_radius(element_above->increased_to_model_radius), - to_model_gracious(element_above->to_model_gracious), - buildplate_radius_increases(element_above->buildplate_radius_increases), - use_min_xy_dist(element_above->use_min_xy_dist), - supports_roof(element_above->supports_roof), - dont_move_until(element_above->dont_move_until), - can_use_safe_radius(element_above->can_use_safe_radius), - last_area_increase(element_above->last_area_increase), - missing_roof_layers(element_above->missing_roof_layers), - skip_ovalisation(false), - all_tips(element_above->all_tips), - influence_area_limit_area(element_above->influence_area_limit_area), - influence_area_limit_range(element_above->influence_area_limit_range), - influence_area_limit_active(element_above->influence_area_limit_active) + target_height_(element_above->target_height_), + target_position_(element_above->target_position_), + next_position_(element_above->next_position_), + next_height_(element_above->next_height_), + effective_radius_height_(element_above->effective_radius_height_), + to_buildplate_(element_above->to_buildplate_), + distance_to_top_(element_above->distance_to_top_ + 1), + area_(element_above->area_), + result_on_layer_(Point(-1, -1)), // set to invalid as we are a new node on a new layer + increased_to_model_radius_(element_above->increased_to_model_radius_), + to_model_gracious_(element_above->to_model_gracious_), + buildplate_radius_increases_(element_above->buildplate_radius_increases_), + use_min_xy_dist_(element_above->use_min_xy_dist_), + supports_roof_(element_above->supports_roof_), + dont_move_until_(element_above->dont_move_until_), + can_use_safe_radius_(element_above->can_use_safe_radius_), + last_area_increase_(element_above->last_area_increase_), + missing_roof_layers_(element_above->missing_roof_layers_), + skip_ovalisation_(false), + all_tips_(element_above->all_tips_), + influence_area_limit_area_(element_above->influence_area_limit_area_), + influence_area_limit_range_(element_above->influence_area_limit_range_), + influence_area_limit_active_(element_above->influence_area_limit_active_) { - parents = { element_above }; + parents_ = { element_above }; } // ONLY to be called in merge as it assumes a few assurances made by it. @@ -182,37 +182,37 @@ struct TreeSupportElement coord_t branch_radius, double diameter_angle_scale_factor ) : - next_position(next_position), - next_height(next_height), - area(nullptr), - increased_to_model_radius(increased_to_model_radius), - use_min_xy_dist(first.use_min_xy_dist || second.use_min_xy_dist), - supports_roof(first.supports_roof || second.supports_roof), - dont_move_until(std::max(first.dont_move_until, second.dont_move_until)), - can_use_safe_radius(first.can_use_safe_radius || second.can_use_safe_radius), - missing_roof_layers(std::min(first.missing_roof_layers, second.missing_roof_layers)), - skip_ovalisation(false) + next_position_(next_position), + next_height_(next_height), + area_(nullptr), + increased_to_model_radius_(increased_to_model_radius), + use_min_xy_dist_(first.use_min_xy_dist_ || second.use_min_xy_dist_), + supports_roof_(first.supports_roof_ || second.supports_roof_), + dont_move_until_(std::max(first.dont_move_until_, second.dont_move_until_)), + can_use_safe_radius_(first.can_use_safe_radius_ || second.can_use_safe_radius_), + missing_roof_layers_(std::min(first.missing_roof_layers_, second.missing_roof_layers_)), + skip_ovalisation_(false) { - if (first.target_height > second.target_height) + if (first.target_height_ > second.target_height_) { - target_height = first.target_height; - target_position = first.target_position; + target_height_ = first.target_height_; + target_position_ = first.target_position_; } else { - target_height = second.target_height; - target_position = second.target_position; + target_height_ = second.target_height_; + target_position_ = second.target_position_; } - effective_radius_height = std::max(first.effective_radius_height, second.effective_radius_height); - distance_to_top = std::max(first.distance_to_top, second.distance_to_top); + effective_radius_height_ = std::max(first.effective_radius_height_, second.effective_radius_height_); + distance_to_top_ = std::max(first.distance_to_top_, second.distance_to_top_); - to_buildplate = first.to_buildplate && second.to_buildplate; - to_model_gracious = first.to_model_gracious && second.to_model_gracious; // valid as we do not merge non-gracious with gracious + to_buildplate_ = first.to_buildplate_ && second.to_buildplate_; + to_model_gracious_ = first.to_model_gracious_ && second.to_model_gracious_; // valid as we do not merge non-gracious with gracious - AddParents(first.parents); - AddParents(second.parents); + AddParents(first.parents_); + AddParents(second.parents_); - buildplate_radius_increases = 0; + buildplate_radius_increases_ = 0; if (diameter_scale_bp_radius > 0) { const coord_t foot_increase_radius = @@ -220,170 +220,170 @@ struct TreeSupportElement ( std::max ( - getRadius(second.effective_radius_height, second.buildplate_radius_increases), - getRadius(first.effective_radius_height, first.buildplate_radius_increases)) - getRadius(effective_radius_height, buildplate_radius_increases + getRadius(second.effective_radius_height_, second.buildplate_radius_increases_), + getRadius(first.effective_radius_height_, first.buildplate_radius_increases_)) - getRadius(effective_radius_height_, buildplate_radius_increases_ ) ); // 'buildplate_radius_increases' has to be recalculated, as when a smaller tree with a larger buildplate_radius_increases merge with a larger branch, // the buildplate_radius_increases may have to be lower as otherwise the radius suddenly increases. This results often in a non integer value. - buildplate_radius_increases = foot_increase_radius / (branch_radius * (diameter_scale_bp_radius - diameter_angle_scale_factor)); + buildplate_radius_increases_ = foot_increase_radius / (branch_radius * (diameter_scale_bp_radius - diameter_angle_scale_factor)); } // set last settings to the best out of both parents. If this is wrong, it will only cause a small performance penalty instead of weird behavior. - last_area_increase = + last_area_increase_ = AreaIncreaseSettings ( - std::min(first.last_area_increase.type, second.last_area_increase.type), - std::min(first.last_area_increase.increase_speed, second.last_area_increase.increase_speed), - first.last_area_increase.increase_radius || second.last_area_increase.increase_radius, - first.last_area_increase.no_error || second.last_area_increase.no_error, - first.last_area_increase.use_min_distance && second.last_area_increase.use_min_distance, - first.last_area_increase.move || second.last_area_increase.move + std::min(first.last_area_increase_.type_, second.last_area_increase_.type_), + std::min(first.last_area_increase_.increase_speed_, second.last_area_increase_.increase_speed_), + first.last_area_increase_.increase_radius_ || second.last_area_increase_.increase_radius_, + first.last_area_increase_.no_error_ || second.last_area_increase_.no_error_, + first.last_area_increase_.use_min_distance_ && second.last_area_increase_.use_min_distance_, + first.last_area_increase_.move_ || second.last_area_increase_.move_ ); - all_tips = first.all_tips; - all_tips.insert(all_tips.end(), second.all_tips.begin(), second.all_tips.end()); - influence_area_limit_range = std::max(first.influence_area_limit_range, second.influence_area_limit_range); - influence_area_limit_active = first.influence_area_limit_active || second.influence_area_limit_active; + all_tips_ = first.all_tips_; + all_tips_.insert(all_tips_.end(), second.all_tips_.begin(), second.all_tips_.end()); + influence_area_limit_range_ = std::max(first.influence_area_limit_range_, second.influence_area_limit_range_); + influence_area_limit_active_ = first.influence_area_limit_active_ || second.influence_area_limit_active_; RecreateInfluenceLimitArea(); - if(first.to_buildplate != second.to_buildplate) + if(first.to_buildplate_ != second.to_buildplate_) { - setToBuildplateForAllParents(to_buildplate); + setToBuildplateForAllParents(to_buildplate_); } } /*! * \brief The layer this support elements wants reach */ - LayerIndex target_height; + LayerIndex target_height_; /*! * \brief The position this support elements wants to support on layer=target_height */ - Point target_position; + Point target_position_; /*! * \brief The next position this support elements wants to reach. NOTE: This is mainly a suggestion regarding direction inside the influence area. */ - Point next_position; + Point next_position_; /*! * \brief The next height this support elements wants to reach */ - LayerIndex next_height; + LayerIndex next_height_; /*! * \brief The Effective distance to top of this element regarding radius increases and collision calculations. */ - size_t effective_radius_height; + size_t effective_radius_height_; /*! * \brief The element trys to reach the buildplate */ - bool to_buildplate; + bool to_buildplate_; /*! * \brief All elements in the layer above the current one that are supported by this element */ - std::vector parents; + std::vector parents_; /*! * \brief The amount of layers this element is below the topmost layer of this branch. */ - size_t distance_to_top; + size_t distance_to_top_; /*! * \brief The resulting influence area. * Will only be set in the results of createLayerPathing, and will be nullptr inside! */ - Polygons* area; + Polygons* area_; /*! * \brief The resulting center point around which a circle will be drawn later. * Will be set by setPointsOnAreas */ - Point result_on_layer = Point(-1, -1); + Point result_on_layer_ = Point(-1, -1); /*! * \brief The amount of extra radius we got from merging branches that could have reached the buildplate, but merged with ones that can not. */ - coord_t increased_to_model_radius; // how much to model we increased only relevant for merging + coord_t increased_to_model_radius_; // how much to model we increased only relevant for merging /*! * \brief Will the branch be able to rest completely on a flat surface, be it buildplate or model ? */ - bool to_model_gracious; + bool to_model_gracious_; /*! * \brief Counter about the times the radius was increased to reach the bp_radius. Can be fractions for merge reasons. */ - double buildplate_radius_increases; + double buildplate_radius_increases_; /*! * \brief Whether the min_xy_distance can be used to get avoidance or similar. Will only be true if support_xy_overrides_z=Z overrides X/Y. */ - bool use_min_xy_dist; + bool use_min_xy_dist_; /*! * \brief True if this Element or any parent provides support to a support roof. */ - bool supports_roof; + bool supports_roof_; /*! * \brief The element trys not to move until this dtt is reached, is set to 0 if the element had to move. */ - size_t dont_move_until; + size_t dont_move_until_; /*! * \brief An influence area is considered safe when it can use the holefree avoidance <=> It will not have to encounter holes on its way downward. */ - bool can_use_safe_radius; + bool can_use_safe_radius_; /*! * \brief Settings used to increase the influence area to its current state. */ - AreaIncreaseSettings last_area_increase; + AreaIncreaseSettings last_area_increase_; /*! * \brief Amount of roof layers that were not yet added, because the branch needed to move. */ - size_t missing_roof_layers; + size_t missing_roof_layers_; /*! * \brief Skip the ovalisation to parent and children when generating the final circles. */ - bool skip_ovalisation; + bool skip_ovalisation_; /*! * \brief The coordinates of all tips supported by this branch. */ - std::vector all_tips; + std::vector all_tips_; /*! * \brief Whether the range of an influence area is limited */ - bool influence_area_limit_active; + bool influence_area_limit_active_; /*! * \brief Maximum distance (x/y) the influence area should be from each tip. */ - coord_t influence_area_limit_range; + coord_t influence_area_limit_range_; /*! * \brief Area that influence area has to be inside to conform to influence_area_limit_range. */ - Polygons influence_area_limit_area; + Polygons influence_area_limit_area_; /*! * \brief Additional locations that the tip should reach */ - std::vector additional_ovalization_targets; + std::vector additional_ovalization_targets_; bool operator==(const TreeSupportElement& other) const { - return target_position == other.target_position && target_height == other.target_height; + return target_position_ == other.target_position_ && target_height_ == other.target_height_; } bool operator<(const TreeSupportElement& other) const // true if me < other @@ -398,54 +398,54 @@ struct TreeSupportElement { return false; } - if (other.target_height != target_height) + if (other.target_height_ != target_height_) { - return other.target_height < target_height; + return other.target_height_ < target_height_; } - return other.target_position.X == target_position.X ? other.target_position.Y < target_position.Y : other.target_position.X < target_position.X; + return other.target_position_.X == target_position_.X ? other.target_position_.Y < target_position_.Y : other.target_position_.X < target_position_.X; } void AddParents(const std::vector& adding) { for (TreeSupportElement* ptr : adding) { - parents.emplace_back(ptr); + parents_.emplace_back(ptr); } } void RecreateInfluenceLimitArea() { - if (influence_area_limit_active) + if (influence_area_limit_active_) { - influence_area_limit_area.clear(); + influence_area_limit_area_.clear(); - for (Point p : all_tips) + for (Point p : all_tips_) { Polygon circle; for (Point corner : TreeSupportBaseCircle::getBaseCircle()) { - circle.add(p + corner * influence_area_limit_range / double(TreeSupportBaseCircle::base_radius)); + circle.add(p + corner * influence_area_limit_range_ / double(TreeSupportBaseCircle::base_radius)); } - if (influence_area_limit_area.empty()) + if (influence_area_limit_area_.empty()) { - influence_area_limit_area = circle.offset(0); + influence_area_limit_area_ = circle.offset(0); } else { - influence_area_limit_area = influence_area_limit_area.intersection(circle.offset(0)); + influence_area_limit_area_ = influence_area_limit_area_.intersection(circle.offset(0)); } } } } void setToBuildplateForAllParents(bool new_value) { - to_buildplate = new_value; - std::vector grandparents {parents}; + to_buildplate_ = new_value; + std::vector grandparents {parents_}; while (!grandparents.empty()){ std::vector next_parents; for (TreeSupportElement* grandparent:grandparents){ - next_parents.insert(next_parents.end(),grandparent->parents.begin(),grandparent->parents.end()); - grandparent->to_buildplate = new_value; + next_parents.insert(next_parents.end(),grandparent->parents_.begin(),grandparent->parents_.end()); + grandparent->to_buildplate_ = new_value; } grandparents = next_parents; } @@ -453,7 +453,7 @@ struct TreeSupportElement inline bool isResultOnLayerSet() const { - return result_on_layer != Point(-1, -1); + return result_on_layer_ != Point(-1, -1); } }; @@ -467,8 +467,8 @@ struct hash { size_t operator()(const cura::TreeSupportElement& node) const { - size_t hash_node = hash()(node.target_position); - boost::hash_combine(hash_node, size_t(node.target_height)); + size_t hash_node = hash()(node.target_position_); + boost::hash_combine(hash_node, size_t(node.target_height_)); return hash_node; } }; diff --git a/include/TreeSupportSettings.h b/include/TreeSupportSettings.h index 06a6292230..4f973cc430 100644 --- a/include/TreeSupportSettings.h +++ b/include/TreeSupportSettings.h @@ -449,9 +449,9 @@ struct TreeSupportSettings [[nodiscard]] inline size_t getEffectiveDTT(const TreeSupportElement& elem) const { return - elem.effective_radius_height < increase_radius_until_dtt ? - (elem.distance_to_top < increase_radius_until_dtt ? elem.distance_to_top : increase_radius_until_dtt) : - elem.effective_radius_height; + elem.effective_radius_height_ < increase_radius_until_dtt ? + (elem.distance_to_top_ < increase_radius_until_dtt ? elem.distance_to_top_ : increase_radius_until_dtt) : + elem.effective_radius_height_; } /*! @@ -480,7 +480,7 @@ struct TreeSupportSettings */ [[nodiscard]] inline coord_t getRadius(const TreeSupportElement& elem) const { - return getRadius(getEffectiveDTT(elem), (elem.isResultOnLayerSet() || !support_rests_on_model) && elem.to_buildplate ? elem.buildplate_radius_increases : 0); + return getRadius(getEffectiveDTT(elem), (elem.isResultOnLayerSet() || !support_rests_on_model) && elem.to_buildplate_ ? elem.buildplate_radius_increases_ : 0); } /*! @@ -490,7 +490,7 @@ struct TreeSupportSettings */ [[nodiscard]] inline coord_t getCollisionRadius(const TreeSupportElement& elem) const { - return getRadius(elem.effective_radius_height, elem.buildplate_radius_increases); + return getRadius(elem.effective_radius_height_, elem.buildplate_radius_increases_); } /*! diff --git a/src/SkirtBrim.cpp b/src/SkirtBrim.cpp index 1e59c669d8..cd2ed3e907 100644 --- a/src/SkirtBrim.cpp +++ b/src/SkirtBrim.cpp @@ -19,48 +19,48 @@ namespace cura { SkirtBrim::SkirtBrim(SliceDataStorage& storage) - : storage(storage) - , adhesion_type(Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("adhesion_type")) - , has_ooze_shield(storage.oozeShield.size() > 0 && storage.oozeShield[0].size() > 0) - , has_draft_shield(storage.draft_protection_shield.size() > 0) - , extruders(Application::getInstance().current_slice_->scene.extruders) - , extruder_count(extruders.size()) - , extruder_is_used(storage.getExtrudersUsed()) + : storage_(storage) + , adhesion_type_(Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("adhesion_type")) + , has_ooze_shield_(storage.oozeShield.size() > 0 && storage.oozeShield[0].size() > 0) + , has_draft_shield_(storage.draft_protection_shield.size() > 0) + , extruders_(Application::getInstance().current_slice_->scene.extruders) + , extruder_count_(extruders_.size()) + , extruder_is_used_(storage.getExtrudersUsed()) { - first_used_extruder_nr = 0; - for (int extruder_nr = 0; extruder_nr < extruder_count; extruder_nr++) + first_used_extruder_nr_ = 0; + for (int extruder_nr = 0; extruder_nr < extruder_count_; extruder_nr++) { - if (extruder_is_used[extruder_nr]) + if (extruder_is_used_[extruder_nr]) { - first_used_extruder_nr = extruder_nr; + first_used_extruder_nr_ = extruder_nr; break; } } - skirt_brim_extruder_nr = Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("skirt_brim_extruder_nr"); - if (skirt_brim_extruder_nr == -1 && adhesion_type == EPlatformAdhesion::SKIRT) + skirt_brim_extruder_nr_ = Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("skirt_brim_extruder_nr"); + if (skirt_brim_extruder_nr_ == -1 && adhesion_type_ == EPlatformAdhesion::SKIRT) { // Skirt is always printed with all extruders in order to satisfy minimum legnth constraint // NOTE: the line count will only be satisfied for the first extruder used. - skirt_brim_extruder_nr = first_used_extruder_nr; + skirt_brim_extruder_nr_ = first_used_extruder_nr_; } - line_widths.resize(extruder_count); - skirt_brim_minimal_length.resize(extruder_count); - external_polys_only.resize(extruder_count); - line_count.resize(extruder_count); - gap.resize(extruder_count); - for (int extruder_nr = 0; extruder_nr < extruder_count; extruder_nr++) + line_widths_.resize(extruder_count_); + skirt_brim_minimal_length_.resize(extruder_count_); + external_polys_only_.resize(extruder_count_); + line_count_.resize(extruder_count_); + gap_.resize(extruder_count_); + for (int extruder_nr = 0; extruder_nr < extruder_count_; extruder_nr++) { - if (! extruder_is_used[extruder_nr]) + if (! extruder_is_used_[extruder_nr]) { continue; } - const ExtruderTrain& extruder = extruders[extruder_nr]; + const ExtruderTrain& extruder = extruders_[extruder_nr]; - line_widths[extruder_nr] = extruder.settings_.get("skirt_brim_line_width") * extruder.settings_.get("initial_layer_line_width_factor"); - skirt_brim_minimal_length[extruder_nr] = extruder.settings_.get("skirt_brim_minimal_length"); - external_polys_only[extruder_nr] = adhesion_type == EPlatformAdhesion::SKIRT || extruder.settings_.get("brim_outside_only"); - line_count[extruder_nr] = extruder.settings_.get(adhesion_type == EPlatformAdhesion::BRIM ? "brim_line_count" : "skirt_line_count"); - gap[extruder_nr] = extruder.settings_.get(adhesion_type == EPlatformAdhesion::BRIM ? "brim_gap" : "skirt_gap"); + line_widths_[extruder_nr] = extruder.settings_.get("skirt_brim_line_width") * extruder.settings_.get("initial_layer_line_width_factor"); + skirt_brim_minimal_length_[extruder_nr] = extruder.settings_.get("skirt_brim_minimal_length"); + external_polys_only_[extruder_nr] = adhesion_type_ == EPlatformAdhesion::SKIRT || extruder.settings_.get("brim_outside_only"); + line_count_[extruder_nr] = extruder.settings_.get(adhesion_type_ == EPlatformAdhesion::BRIM ? "brim_line_count" : "skirt_line_count"); + gap_[extruder_nr] = extruder.settings_.get(adhesion_type_ == EPlatformAdhesion::BRIM ? "brim_gap" : "skirt_gap"); } } @@ -68,15 +68,15 @@ std::vector SkirtBrim::generateBrimOffsetPlan(std::vector all_brim_offsets; - if (skirt_brim_extruder_nr >= 0) + if (skirt_brim_extruder_nr_ >= 0) { - starting_outlines[skirt_brim_extruder_nr] = getFirstLayerOutline(); + starting_outlines[skirt_brim_extruder_nr_] = getFirstLayerOutline(); } else { - for (int extruder_nr = 0; extruder_nr < extruder_count; extruder_nr++) + for (int extruder_nr = 0; extruder_nr < extruder_count_; extruder_nr++) { - if (! extruder_is_used[extruder_nr]) + if (! extruder_is_used_[extruder_nr]) { continue; } @@ -84,24 +84,24 @@ std::vector SkirtBrim::generateBrimOffsetPlan(std::vector= 0 && extruder_nr != skirt_brim_extruder_nr) || starting_outlines[extruder_nr].empty()) + if (! extruder_is_used_[extruder_nr] || (skirt_brim_extruder_nr_ >= 0 && extruder_nr != skirt_brim_extruder_nr_) || starting_outlines[extruder_nr].empty()) { continue; // only include offsets for brim extruder } - for (int line_idx = 0; line_idx < line_count[extruder_nr]; line_idx++) + for (int line_idx = 0; line_idx < line_count_[extruder_nr]; line_idx++) { - const bool is_last = line_idx == line_count[extruder_nr] - 1; - coord_t offset = gap[extruder_nr] + line_widths[extruder_nr] / 2 + line_widths[extruder_nr] * line_idx; + const bool is_last = line_idx == line_count_[extruder_nr] - 1; + coord_t offset = gap_[extruder_nr] + line_widths_[extruder_nr] / 2 + line_widths_[extruder_nr] * line_idx; if (line_idx == 0) { - all_brim_offsets.emplace_back(&starting_outlines[extruder_nr], external_polys_only[extruder_nr], offset, offset, line_idx, extruder_nr, is_last); + all_brim_offsets.emplace_back(&starting_outlines[extruder_nr], external_polys_only_[extruder_nr], offset, offset, line_idx, extruder_nr, is_last); } else { - all_brim_offsets.emplace_back(line_idx - 1, external_polys_only[extruder_nr], line_widths[extruder_nr], offset, line_idx, extruder_nr, is_last); + all_brim_offsets.emplace_back(line_idx - 1, external_polys_only_[extruder_nr], line_widths_[extruder_nr], offset, line_idx, extruder_nr, is_last); } } } @@ -112,25 +112,25 @@ std::vector SkirtBrim::generateBrimOffsetPlan(std::vector starting_outlines(extruder_count); + std::vector starting_outlines(extruder_count_); std::vector all_brim_offsets = generateBrimOffsetPlan(starting_outlines); constexpr LayerIndex layer_nr = 0; constexpr bool include_support = true; - const bool include_prime_tower = adhesion_type == EPlatformAdhesion::SKIRT; - const bool has_prime_tower = storage.primeTower.enabled; - Polygons covered_area = storage.getLayerOutlines(layer_nr, include_support, include_prime_tower, /*external_polys_only*/ false); + const bool include_prime_tower = adhesion_type_ == EPlatformAdhesion::SKIRT; + const bool has_prime_tower = storage_.primeTower.enabled; + Polygons covered_area = storage_.getLayerOutlines(layer_nr, include_support, include_prime_tower, /*external_polys_only*/ false); - std::vector allowed_areas_per_extruder(extruder_count); - for (int extruder_nr = 0; extruder_nr < extruder_count; extruder_nr++) + std::vector allowed_areas_per_extruder(extruder_count_); + for (int extruder_nr = 0; extruder_nr < extruder_count_; extruder_nr++) { - if (! extruder_is_used[extruder_nr]) + if (! extruder_is_used_[extruder_nr]) { continue; } - Polygons machine_area = storage.getMachineBorder(extruder_nr); + Polygons machine_area = storage_.getMachineBorder(extruder_nr); allowed_areas_per_extruder[extruder_nr] = machine_area.difference(covered_area); - if (external_polys_only[extruder_nr]) + if (external_polys_only_[extruder_nr]) { // Expand covered area on inside of holes when external_only is enabled for any extruder, // so that the brim lines don't overlap with the holes by half the line width @@ -139,14 +139,14 @@ void SkirtBrim::generate() if (has_prime_tower) { - allowed_areas_per_extruder[extruder_nr] = allowed_areas_per_extruder[extruder_nr].difference(storage.primeTower.getGroundPoly()); + allowed_areas_per_extruder[extruder_nr] = allowed_areas_per_extruder[extruder_nr].difference(storage_.primeTower.getGroundPoly()); } } // Apply 'approximate convex hull' if the adhesion is skirt _after_ any skirt but also prime-tower-brim adhesion. // Otherwise, the now expanded convex hull covered areas will mess with that brim. Fortunately this does not mess // with the other area calculation above, since they are either itself a simple/convex shape or relevant for brim. - if (adhesion_type == EPlatformAdhesion::SKIRT) + if (adhesion_type_ == EPlatformAdhesion::SKIRT) { covered_area = covered_area.approxConvexHull(); } @@ -158,7 +158,7 @@ void SkirtBrim::generate() { // only allow secondary skirt/brim to appear on the very outside covered_area = covered_area.getOutsidePolygons(); - for (int extruder_nr = 0; extruder_nr < extruder_count; extruder_nr++) + for (int extruder_nr = 0; extruder_nr < extruder_count_; extruder_nr++) { allowed_areas_per_extruder[extruder_nr] = allowed_areas_per_extruder[extruder_nr].difference(covered_area); } @@ -171,9 +171,9 @@ void SkirtBrim::generate() const Settings& global_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; const coord_t maximum_resolution = global_settings.get("meshfix_maximum_resolution"); const coord_t maximum_deviation = global_settings.get("meshfix_maximum_deviation"); - for (int extruder_nr = 0; extruder_nr < extruder_count; extruder_nr++) + for (int extruder_nr = 0; extruder_nr < extruder_count_; extruder_nr++) { - for (SkirtBrimLine& line : storage.skirt_brim[extruder_nr]) + for (SkirtBrimLine& line : storage_.skirt_brim[extruder_nr]) { constexpr coord_t max_area_dev = 0u; // No area deviation applied line.open_polylines = Simplify(maximum_resolution, maximum_deviation, max_area_dev).polyline(line.open_polylines); @@ -184,38 +184,38 @@ void SkirtBrim::generate() std::vector SkirtBrim::generatePrimaryBrim(std::vector& all_brim_offsets, Polygons& covered_area, std::vector& allowed_areas_per_extruder) { - std::vector total_length(extruder_count, 0U); + std::vector total_length(extruder_count_, 0U); for (size_t offset_idx = 0; offset_idx < all_brim_offsets.size(); offset_idx++) { Offset& offset = all_brim_offsets[offset_idx]; - if (storage.skirt_brim[offset.extruder_nr].size() <= offset.inset_idx) + if (storage_.skirt_brim[offset.extruder_nr_].size() <= offset.inset_idx_) { - storage.skirt_brim[offset.extruder_nr].resize(offset.inset_idx + 1); + storage_.skirt_brim[offset.extruder_nr_].resize(offset.inset_idx_ + 1); } - SkirtBrimLine& output_location = storage.skirt_brim[offset.extruder_nr][offset.inset_idx]; + SkirtBrimLine& output_location = storage_.skirt_brim[offset.extruder_nr_][offset.inset_idx_]; const coord_t added_length = generateOffset(offset, covered_area, allowed_areas_per_extruder, output_location); if (added_length == 0) { // no more place for more brim. Trying to satisfy minimum length constraint with generateSecondarySkirtBrim continue; } - total_length[offset.extruder_nr] += added_length; + total_length[offset.extruder_nr_] += added_length; - if (offset.is_last && total_length[offset.extruder_nr] < skirt_brim_minimal_length[offset.extruder_nr] + if (offset.is_last_ && total_length[offset.extruder_nr_] < skirt_brim_minimal_length_[offset.extruder_nr_] && // This was the last offset of this extruder, but the brim lines don't meet minimal length yet - total_length[offset.extruder_nr] > 0u // No lines got added; we have no extrusion lines to build on + total_length[offset.extruder_nr_] > 0u // No lines got added; we have no extrusion lines to build on ) { - offset.is_last = false; + offset.is_last_ = false; constexpr bool is_last = true; all_brim_offsets.emplace_back( - offset.inset_idx, - external_polys_only[offset.extruder_nr], - line_widths[offset.extruder_nr], - offset.total_offset + line_widths[offset.extruder_nr], - offset.inset_idx + 1, - offset.extruder_nr, + offset.inset_idx_, + external_polys_only_[offset.extruder_nr_], + line_widths_[offset.extruder_nr_], + offset.total_offset_ + line_widths_[offset.extruder_nr_], + offset.inset_idx_ + 1, + offset.extruder_nr_, is_last); std::sort(all_brim_offsets.begin() + offset_idx + 1, all_brim_offsets.end(), OffsetSorter); // reorder remaining offsets } @@ -238,7 +238,7 @@ Polygons SkirtBrim::getInternalHoleExclusionArea(const Polygons& outline, const { Polygon hole_poly = part[hole_idx]; hole_poly.reverse(); - Polygons disallowed_region = hole_poly.offset(10u).difference(hole_poly.offset(-line_widths[extruder_nr] / 2 - hole_brim_distance)); + Polygons disallowed_region = hole_poly.offset(10u).difference(hole_poly.offset(-line_widths_[extruder_nr] / 2 - hole_brim_distance)); ret = ret.unionPolygons(disallowed_region); } } @@ -251,10 +251,10 @@ coord_t SkirtBrim::generateOffset(const Offset& offset, Polygons& covered_area, Polygons brim; Polygons newly_covered; { - if (std::holds_alternative(offset.reference_outline_or_index)) + if (std::holds_alternative(offset.reference_outline_or_index_)) { - Polygons* reference_outline = std::get(offset.reference_outline_or_index); - if (offset.external_only) + Polygons* reference_outline = std::get(offset.reference_outline_or_index_); + if (offset.external_only_) { // prevent unioning of external polys enclosed by other parts, e.g. a small part inside a hollow cylinder. for (Polygons& polys : reference_outline->sortByNesting()) { // offset external polygons of islands contained within another part in each batch @@ -265,8 +265,8 @@ coord_t SkirtBrim::generateOffset(const Offset& offset, Polygons& covered_area, poly.reverse(); } } - brim.add(polys.offset(offset.offset_value, ClipperLib::jtRound)); - newly_covered.add(polys.offset(offset.offset_value + line_widths[offset.extruder_nr] / 2, ClipperLib::jtRound)); + brim.add(polys.offset(offset.offset_value_, ClipperLib::jtRound)); + newly_covered.add(polys.offset(offset.offset_value_ + line_widths_[offset.extruder_nr_] / 2, ClipperLib::jtRound)); for (PolygonRef poly : polys) { poly.reverse(); @@ -276,20 +276,20 @@ coord_t SkirtBrim::generateOffset(const Offset& offset, Polygons& covered_area, } else { - brim = reference_outline->offset(offset.offset_value, ClipperLib::jtRound); - newly_covered = reference_outline->offset(offset.offset_value + line_widths[offset.extruder_nr] / 2, ClipperLib::jtRound); + brim = reference_outline->offset(offset.offset_value_, ClipperLib::jtRound); + newly_covered = reference_outline->offset(offset.offset_value_ + line_widths_[offset.extruder_nr_] / 2, ClipperLib::jtRound); } } else { - const int reference_idx = std::get(offset.reference_outline_or_index); - auto offset_dist = line_widths[offset.extruder_nr]; + const int reference_idx = std::get(offset.reference_outline_or_index_); + auto offset_dist = line_widths_[offset.extruder_nr_]; Polygons local_brim; - auto closed_polygons_brim = storage.skirt_brim[offset.extruder_nr][reference_idx].closed_polygons.offsetPolyLine(offset_dist, ClipperLib::jtRound, true); + auto closed_polygons_brim = storage_.skirt_brim[offset.extruder_nr_][reference_idx].closed_polygons.offsetPolyLine(offset_dist, ClipperLib::jtRound, true); local_brim.add(closed_polygons_brim); - auto open_polylines_brim = storage.skirt_brim[offset.extruder_nr][reference_idx].open_polylines.offsetPolyLine(offset_dist, ClipperLib::jtRound); + auto open_polylines_brim = storage_.skirt_brim[offset.extruder_nr_][reference_idx].open_polylines.offsetPolyLine(offset_dist, ClipperLib::jtRound); local_brim.add(open_polylines_brim); local_brim.unionPolygons(); @@ -300,12 +300,12 @@ coord_t SkirtBrim::generateOffset(const Offset& offset, Polygons& covered_area, } { // limit brim lines to allowed areas, stitch them and store them in the result - brim = Simplify(Application::getInstance().current_slice_->scene.extruders[offset.extruder_nr].settings_).polygon(brim); + brim = Simplify(Application::getInstance().current_slice_->scene.extruders[offset.extruder_nr_].settings_).polygon(brim); brim.toPolylines(); - Polygons brim_lines = allowed_areas_per_extruder[offset.extruder_nr].intersectionPolyLines(brim, false); + Polygons brim_lines = allowed_areas_per_extruder[offset.extruder_nr_].intersectionPolyLines(brim, false); length_added = brim_lines.polyLineLength(); - const coord_t max_stitch_distance = line_widths[offset.extruder_nr]; + const coord_t max_stitch_distance = line_widths_[offset.extruder_nr_]; PolylineStitcher::stitch(brim_lines, result.open_polylines, result.closed_polygons, max_stitch_distance); // clean up too small lines @@ -324,9 +324,9 @@ coord_t SkirtBrim::generateOffset(const Offset& offset, Polygons& covered_area, } { // update allowed_areas_per_extruder - for (int extruder_nr = 0; extruder_nr < extruder_count; extruder_nr++) + for (int extruder_nr = 0; extruder_nr < extruder_count_; extruder_nr++) { - if (! extruder_is_used[extruder_nr]) + if (! extruder_is_used_[extruder_nr]) { continue; } @@ -341,18 +341,18 @@ Polygons SkirtBrim::getFirstLayerOutline(const int extruder_nr /* = -1 */) { Polygons first_layer_outline; Settings& global_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; - int reference_extruder_nr = skirt_brim_extruder_nr; + int reference_extruder_nr = skirt_brim_extruder_nr_; assert(! (reference_extruder_nr == -1 && extruder_nr == -1) && "We should only request the outlines of all layers when the brim is being generated for only one material"); if (reference_extruder_nr == -1) { reference_extruder_nr = extruder_nr; } - const int primary_line_count = line_count[reference_extruder_nr]; + const int primary_line_count = line_count_[reference_extruder_nr]; const bool external_only - = adhesion_type == EPlatformAdhesion::SKIRT || external_polys_only[reference_extruder_nr]; // Whether to include holes or not. Skirt doesn't have any holes. - const bool has_prime_tower = storage.primeTower.enabled; + = adhesion_type_ == EPlatformAdhesion::SKIRT || external_polys_only_[reference_extruder_nr]; // Whether to include holes or not. Skirt doesn't have any holes. + const bool has_prime_tower = storage_.primeTower.enabled; const LayerIndex layer_nr = 0; - if (adhesion_type == EPlatformAdhesion::SKIRT) + if (adhesion_type_ == EPlatformAdhesion::SKIRT) { constexpr bool include_support = true; const bool include_prime_tower = ! has_prime_tower; // include manually otherwise @@ -366,34 +366,34 @@ Polygons SkirtBrim::getFirstLayerOutline(const int extruder_nr /* = -1 */) skirt_height = std::max(skirt_height, extruder.settings_.get("skirt_height")); } } - skirt_height = std::min(skirt_height, static_cast(storage.print_layer_count)); + skirt_height = std::min(skirt_height, static_cast(storage_.print_layer_count)); for (int i_layer = layer_nr; i_layer < skirt_height; ++i_layer) { for (const auto& extruder : Application::getInstance().current_slice_->scene.extruders) { first_layer_outline - = first_layer_outline.unionPolygons(storage.getLayerOutlines(i_layer, include_support, include_prime_tower, external_only, extruder.extruder_nr_)); + = first_layer_outline.unionPolygons(storage_.getLayerOutlines(i_layer, include_support, include_prime_tower, external_only, extruder.extruder_nr_)); } } if (has_prime_tower) { - first_layer_outline = first_layer_outline.unionPolygons(storage.primeTower.getGroundPoly()); + first_layer_outline = first_layer_outline.unionPolygons(storage_.primeTower.getGroundPoly()); } Polygons shields; - if (has_ooze_shield) + if (has_ooze_shield_) { - shields = storage.oozeShield[0]; + shields = storage_.oozeShield[0]; } - if (has_draft_shield) + if (has_draft_shield_) { - shields = shields.unionPolygons(storage.draft_protection_shield); + shields = shields.unionPolygons(storage_.draft_protection_shield); } first_layer_outline = first_layer_outline.unionPolygons(shields.offset( - line_widths[reference_extruder_nr] / 2 // because the shield is printed *on* the stored polygons; not inside hteir area - - gap[reference_extruder_nr])); // so that when we apply the gap we will end up right next to the shield + line_widths_[reference_extruder_nr] / 2 // because the shield is printed *on* the stored polygons; not inside hteir area + - gap_[reference_extruder_nr])); // so that when we apply the gap we will end up right next to the shield // NOTE: offsetting by -gap here and by +gap in the main brim algorithm effectively performs a morphological close, // so in some cases with a large skirt gap and small models and small shield distance // the skirt lines can cross the shield lines. @@ -405,7 +405,7 @@ Polygons SkirtBrim::getFirstLayerOutline(const int extruder_nr /* = -1 */) constexpr bool include_support = false; // Include manually below. constexpr bool include_prime_tower = false; // Not included. constexpr bool external_outlines_only = false; // Remove manually below. - first_layer_outline = storage.getLayerOutlines(layer_nr, include_support, include_prime_tower, external_outlines_only, extruder_nr); + first_layer_outline = storage_.getLayerOutlines(layer_nr, include_support, include_prime_tower, external_outlines_only, extruder_nr); first_layer_outline = first_layer_outline.unionPolygons(); // To guard against overlapping outlines, which would produce holes according to the even-odd rule. Polygons first_layer_empty_holes; if (external_only) @@ -413,10 +413,10 @@ Polygons SkirtBrim::getFirstLayerOutline(const int extruder_nr /* = -1 */) first_layer_empty_holes = first_layer_outline.getEmptyHoles(); first_layer_outline = first_layer_outline.removeEmptyHoles(); } - if (storage.support.generated && primary_line_count > 0 && ! storage.support.supportLayers.empty() + if (storage_.support.generated && primary_line_count > 0 && ! storage_.support.supportLayers.empty() && (extruder_nr == -1 || extruder_nr == global_settings.get("support_infill_extruder_nr"))) { // remove model-brim from support - SupportLayer& support_layer = storage.support.supportLayers[0]; + SupportLayer& support_layer = storage_.support.supportLayers[0]; const ExtruderTrain& support_infill_extruder = global_settings.get("support_infill_extruder_nr"); if (support_infill_extruder.settings_.get("brim_replaces_support")) { @@ -427,7 +427,7 @@ Polygons SkirtBrim::getFirstLayerOutline(const int extruder_nr /* = -1 */) // || || ||[]|| > expand to fit an extra brim line // |+-+| |+--+| // +---+ +----+ - const coord_t primary_extruder_skirt_brim_line_width = line_widths[reference_extruder_nr]; + const coord_t primary_extruder_skirt_brim_line_width = line_widths_[reference_extruder_nr]; Polygons model_brim_covered_area = first_layer_outline.offset( primary_extruder_skirt_brim_line_width * (primary_line_count + primary_line_count % 2), ClipperLib::jtRound); // always leave a gap of an even number of brim lines, so that it fits if it's generating brim from both sides @@ -463,17 +463,17 @@ Polygons SkirtBrim::getFirstLayerOutline(const int extruder_nr /* = -1 */) void SkirtBrim::generateShieldBrim(Polygons& brim_covered_area, std::vector& allowed_areas_per_extruder) { - int extruder_nr = skirt_brim_extruder_nr; + int extruder_nr = skirt_brim_extruder_nr_; if (extruder_nr < 0) { // the shields are always printed with all extruders, so it doesn't really matter with which extruder we print the brim on the first layer - extruder_nr = first_used_extruder_nr; + extruder_nr = first_used_extruder_nr_; } // generate brim for ooze shield and draft shield - if (adhesion_type == EPlatformAdhesion::BRIM && (has_ooze_shield || has_draft_shield)) + if (adhesion_type_ == EPlatformAdhesion::BRIM && (has_ooze_shield_ || has_draft_shield_)) { - const coord_t primary_extruder_skirt_brim_line_width = line_widths[extruder_nr]; - int primary_line_count = line_count[extruder_nr]; + const coord_t primary_extruder_skirt_brim_line_width = line_widths_[extruder_nr]; + int primary_line_count = line_count_[extruder_nr]; // generate areas where to make extra brim for the shields // avoid gap in the middle @@ -487,17 +487,17 @@ void SkirtBrim::generateShieldBrim(Polygons& brim_covered_area, std::vector 0) { shield_brim = shield_brim.offset(-primary_extruder_skirt_brim_line_width); - storage.skirt_brim[extruder_nr].back().closed_polygons.add( + storage_.skirt_brim[extruder_nr].back().closed_polygons.add( shield_brim); // throw all polygons for the shileds onto one heap; because the brim lines are generated from both sides the order will not be important } } - if (adhesion_type == EPlatformAdhesion::SKIRT) + if (adhesion_type_ == EPlatformAdhesion::SKIRT) { - if (has_ooze_shield) + if (has_ooze_shield_) { - const Polygons covered_area = storage.oozeShield[0].offset(line_widths[extruder_nr] / 2); + const Polygons covered_area = storage_.oozeShield[0].offset(line_widths_[extruder_nr] / 2); brim_covered_area = brim_covered_area.unionPolygons(covered_area); allowed_areas_per_extruder[extruder_nr] = allowed_areas_per_extruder[extruder_nr].difference(covered_area); } - if (has_draft_shield) + if (has_draft_shield_) { - const Polygons covered_area = storage.draft_protection_shield.offset(line_widths[extruder_nr] / 2); + const Polygons covered_area = storage_.draft_protection_shield.offset(line_widths_[extruder_nr] / 2); brim_covered_area = brim_covered_area.unionPolygons(covered_area); allowed_areas_per_extruder[extruder_nr] = allowed_areas_per_extruder[extruder_nr].difference(covered_area); } @@ -536,29 +536,29 @@ void SkirtBrim::generateSecondarySkirtBrim(Polygons& covered_area, std::vector

(storage.skirt_brim[extruder_nr].size() - 1); - offset_from_reference = line_widths[extruder_nr]; + ref_polys_or_idx = static_cast(storage_.skirt_brim[extruder_nr].size() - 1); + offset_from_reference = line_widths_[extruder_nr]; } constexpr bool external_only = false; // The reference outline may contain both outlines and hole polygons. - Offset extra_offset(ref_polys_or_idx, external_only, offset_from_reference, bogus_total_offset, storage.skirt_brim[extruder_nr].size(), extruder_nr, is_last); + Offset extra_offset(ref_polys_or_idx, external_only, offset_from_reference, bogus_total_offset, storage_.skirt_brim[extruder_nr].size(), extruder_nr, is_last); - storage.skirt_brim[extruder_nr].emplace_back(); - SkirtBrimLine& output_location = storage.skirt_brim[extruder_nr].back(); + storage_.skirt_brim[extruder_nr].emplace_back(); + SkirtBrimLine& output_location = storage_.skirt_brim[extruder_nr].back(); coord_t added_length = generateOffset(extra_offset, covered_area, allowed_areas_per_extruder, output_location); if (! added_length) @@ -567,7 +567,7 @@ void SkirtBrim::generateSecondarySkirtBrim(Polygons& covered_area, std::vector

("skirt_brim_line_width") * support_infill_extruder.settings_.get("initial_layer_line_width_factor"); size_t line_count = support_infill_extruder.settings_.get("support_brim_line_count"); const coord_t minimal_length = support_infill_extruder.settings_.get("skirt_brim_minimal_length"); - if (! storage.support.generated || line_count <= 0 || storage.support.supportLayers.empty()) + if (! storage_.support.generated || line_count <= 0 || storage_.support.supportLayers.empty()) { return; } @@ -592,18 +592,18 @@ void SkirtBrim::generateSupportBrim() const coord_t brim_width = brim_line_width * line_count; coord_t skirt_brim_length = 0; - if (storage.skirt_brim[support_infill_extruder.extruder_nr_].empty()) + if (storage_.skirt_brim[support_infill_extruder.extruder_nr_].empty()) { - storage.skirt_brim[support_infill_extruder.extruder_nr_].emplace_back(); + storage_.skirt_brim[support_infill_extruder.extruder_nr_].emplace_back(); } - for (const SkirtBrimLine& brim_line : storage.skirt_brim[support_infill_extruder.extruder_nr_]) + for (const SkirtBrimLine& brim_line : storage_.skirt_brim[support_infill_extruder.extruder_nr_]) { skirt_brim_length += brim_line.closed_polygons.polygonLength(); skirt_brim_length += brim_line.open_polylines.polyLineLength(); } - SupportLayer& support_layer = storage.support.supportLayers[0]; + SupportLayer& support_layer = storage_.support.supportLayers[0]; Polygons support_outline; for (SupportInfillPart& part : support_layer.support_infill_parts) @@ -630,9 +630,9 @@ void SkirtBrim::generateSupportBrim() } } - storage.support_brim.add(brim_line); + storage_.support_brim.add(brim_line); // In case of adhesion::NONE length of support brim is only the length of the brims formed for the support - const coord_t length = (adhesion_type == EPlatformAdhesion::NONE) ? skirt_brim_length : skirt_brim_length + storage.support_brim.polygonLength(); + const coord_t length = (adhesion_type_ == EPlatformAdhesion::NONE) ? skirt_brim_length : skirt_brim_length + storage_.support_brim.polygonLength(); if (skirt_brim_number + 1 >= line_count && length > 0 && length < minimal_length) // Make brim or skirt have more lines when total length is too small. { line_count++; diff --git a/src/TreeSupport.cpp b/src/TreeSupport.cpp index bf876ec582..958a08f9fb 100644 --- a/src/TreeSupport.cpp +++ b/src/TreeSupport.cpp @@ -203,7 +203,7 @@ void TreeSupport::generateSupportAreas(SliceDataStorage& storage) { for (auto elem : layer) { - delete elem->area; + delete elem->area_; delete elem; } } @@ -287,15 +287,15 @@ void TreeSupport::mergeHelper( break; // Do not try to merge elements that already should have been merged. Done for potential performance improvement. } - const bool merging_gracious_and_non_gracious = reduced_check.first.to_model_gracious != influence.first.to_model_gracious; + const bool merging_gracious_and_non_gracious = reduced_check.first.to_model_gracious_ != influence.first.to_model_gracious_; // ^^^ We do not want to merge a gracious with a non gracious area as bad placement could negatively impact the dependability of the whole subtree. - const bool merging_to_bp = reduced_check.first.to_buildplate && influence.first.to_buildplate; - const bool merging_min_and_regular_xy = reduced_check.first.use_min_xy_dist != influence.first.use_min_xy_dist; + const bool merging_to_bp = reduced_check.first.to_buildplate_ && influence.first.to_buildplate_; + const bool merging_min_and_regular_xy = reduced_check.first.use_min_xy_dist_ != influence.first.use_min_xy_dist_; // ^^^ Could cause some issues with the increase of one area, as it is assumed that if the smaller is increased by the delta to the larger it is engulfed by it // already. // But because a different collision may be removed from the in drawArea generated circles, this assumption could be wrong. - const bool merging_different_range_limits = reduced_check.first.influence_area_limit_active && influence.first.influence_area_limit_active - && influence.first.influence_area_limit_range != reduced_check.first.influence_area_limit_range; + const bool merging_different_range_limits = reduced_check.first.influence_area_limit_active_ && influence.first.influence_area_limit_active_ + && influence.first.influence_area_limit_range_ != reduced_check.first.influence_area_limit_range_; coord_t increased_to_model_radius = 0; size_t larger_to_model_dtt = 0; @@ -303,30 +303,30 @@ void TreeSupport::mergeHelper( { const coord_t infl_radius = config.getRadius(influence.first); // Get the real radius increase as the user does not care for the collision model. const coord_t redu_radius = config.getRadius(reduced_check.first); - if (reduced_check.first.to_buildplate != influence.first.to_buildplate) + if (reduced_check.first.to_buildplate_ != influence.first.to_buildplate_) { - if (reduced_check.first.to_buildplate) + if (reduced_check.first.to_buildplate_) { if (infl_radius < redu_radius) { - increased_to_model_radius = influence.first.increased_to_model_radius + redu_radius - infl_radius; + increased_to_model_radius = influence.first.increased_to_model_radius_ + redu_radius - infl_radius; } } else { if (infl_radius > redu_radius) { - increased_to_model_radius = reduced_check.first.increased_to_model_radius + infl_radius - redu_radius; + increased_to_model_radius = reduced_check.first.increased_to_model_radius_ + infl_radius - redu_radius; } } } - larger_to_model_dtt = std::max(influence.first.distance_to_top, reduced_check.first.distance_to_top); + larger_to_model_dtt = std::max(influence.first.distance_to_top_, reduced_check.first.distance_to_top_); } // If a merge could place a stable branch on unstable ground, would be increasing the radius further than allowed to when merging to model and to_bp trees or // would merge to model before it is known they will even been drawn the merge is skipped if (merging_min_and_regular_xy || merging_gracious_and_non_gracious || increased_to_model_radius > config.max_to_model_radius_increase - || (! merging_to_bp && larger_to_model_dtt < config.min_dtt_to_model && ! reduced_check.first.supports_roof && ! influence.first.supports_roof) + || (! merging_to_bp && larger_to_model_dtt < config.min_dtt_to_model && ! reduced_check.first.supports_roof_ && ! influence.first.supports_roof_) || merging_different_range_limits) { continue; @@ -358,7 +358,7 @@ void TreeSupport::mergeHelper( const coord_t smaller_collision_radius = config.getCollisionRadius(smaller_rad.first); // the area of the bigger radius is used to ensure correct placement regarding the relevant avoidance, so if that would change an invalid area may be created - if (! bigger_rad.first.can_use_safe_radius && smaller_rad.first.can_use_safe_radius) + if (! bigger_rad.first.can_use_safe_radius_ && smaller_rad.first.can_use_safe_radius_) { continue; } @@ -366,7 +366,7 @@ void TreeSupport::mergeHelper( // The bigger radius is used to verify that the area is still valid after the increase with the delta. // If there were a point where the big influence area could be valid with can_use_safe_radius the element would already be can_use_safe_radius. // The smaller radius, which gets increased by delta may reach into the area where use_min_xy_dist is no longer required. - bool use_min_radius = bigger_rad.first.use_min_xy_dist && smaller_rad.first.use_min_xy_dist; + bool use_min_radius = bigger_rad.first.use_min_xy_dist_ && smaller_rad.first.use_min_xy_dist_; // The idea is that the influence area with the smaller collision radius is increased by the radius difference. // If this area has any intersections with the influence area of the larger collision radius, @@ -399,7 +399,7 @@ void TreeSupport::mergeHelper( // Calculate which point is closest to the point of the last merge (or tip center if no merge above it has happened) // Used at the end to estimate where to best place the branch on the bottom most layer // Could be replaced with a random point inside the new area - Point new_pos = reduced_check.first.next_position; + Point new_pos = reduced_check.first.next_position_; if (! intersect.inside(new_pos, true)) { PolygonUtils::moveInside(intersect, new_pos); @@ -407,7 +407,7 @@ void TreeSupport::mergeHelper( if (increased_to_model_radius == 0) { - increased_to_model_radius = std::max(reduced_check.first.increased_to_model_radius, influence.first.increased_to_model_radius); + increased_to_model_radius = std::max(reduced_check.first.increased_to_model_radius_, influence.first.increased_to_model_radius_); } const TreeSupportElement key( @@ -644,124 +644,125 @@ std::optional TreeSupport::increaseSingleArea( { TreeSupportElement current_elem(parent); // Also increases DTT by one. Polygons check_layer_data; - if (settings.increase_radius) + if (settings.increase_radius_) { - current_elem.effective_radius_height += 1; + current_elem.effective_radius_height_ += 1; } coord_t radius = config.getCollisionRadius(current_elem); - if (settings.move) + if (settings.move_) { increased = relevant_offset; if (overspeed > 0) { - const coord_t safe_movement_distance = (current_elem.use_min_xy_dist ? config.xy_min_distance : config.xy_distance) + const coord_t safe_movement_distance = (current_elem.use_min_xy_dist_ ? config.xy_min_distance : config.xy_distance) + (std::min(config.z_distance_top_layers, config.z_distance_bottom_layers) > 0 ? config.min_feature_size : 0); // The difference to ensure that the result not only conforms to wall_restriction, but collision/avoidance is done later. // The higher last_safe_step_movement_distance comes exactly from the fact that the collision will be subtracted later. increased = TreeSupportUtils::safeOffsetInc( increased, overspeed, - volumes_.getWallRestriction(config.getCollisionRadius(*parent), layer_idx, parent->use_min_xy_dist), + volumes_.getWallRestriction(config.getCollisionRadius(*parent), layer_idx, parent->use_min_xy_dist_), safe_movement_distance, safe_movement_distance + radius, 1, config.support_line_distance / 2, nullptr); } - if (settings.no_error && settings.move) + if (settings.no_error_ && settings.move_) { increased = config.simplifier.polygon(increased); // as ClipperLib::jtRound has to be used for offsets this simplify is VERY important for performance. } } else // if no movement is done the areas keep parent area as no move == offset(0) { - increased = *parent->area; + increased = *parent->area_; } - if ((mergelayer || current_elem.to_buildplate) && config.support_rest_preference == RestPreference::BUILDPLATE) + if ((mergelayer || current_elem.to_buildplate_) && config.support_rest_preference == RestPreference::BUILDPLATE) { - to_bp_data = TreeSupportUtils::safeUnion(increased.difference(volumes_.getAvoidance(radius, layer_idx - 1, settings.type, false, settings.use_min_distance))); - if (! current_elem.to_buildplate && to_bp_data.area() > 1) // mostly happening in the tip, but with merges one should check every time, just to be sure. + to_bp_data = TreeSupportUtils::safeUnion(increased.difference(volumes_.getAvoidance(radius, layer_idx - 1, settings.type_, false, settings.use_min_distance_))); + if (! current_elem.to_buildplate_ && to_bp_data.area() > 1) // mostly happening in the tip, but with merges one should check every time, just to be sure. { - current_elem.to_buildplate = true; // sometimes nodes that can reach the buildplate are marked as cant reach, tainting subtrees. This corrects it. - spdlog::debug("Corrected taint leading to a wrong to model value on layer {} targeting {} with radius {}", layer_idx - 1, current_elem.target_height, radius); + current_elem.to_buildplate_ = true; // sometimes nodes that can reach the buildplate are marked as cant reach, tainting subtrees. This corrects it. + spdlog::debug("Corrected taint leading to a wrong to model value on layer {} targeting {} with radius {}", layer_idx - 1, current_elem.target_height_, radius); } } if (config.support_rests_on_model) { - if (mergelayer || current_elem.to_model_gracious) + if (mergelayer || current_elem.to_model_gracious_) { - to_model_data = TreeSupportUtils::safeUnion(increased.difference(volumes_.getAvoidance(radius, layer_idx - 1, settings.type, true, settings.use_min_distance))); + to_model_data = TreeSupportUtils::safeUnion(increased.difference(volumes_.getAvoidance(radius, layer_idx - 1, settings.type_, true, settings.use_min_distance_))); } - if (! current_elem.to_model_gracious) + if (! current_elem.to_model_gracious_) { if (mergelayer && to_model_data.area() >= 1) { - current_elem.to_model_gracious = true; - spdlog::debug("Corrected taint leading to a wrong non gracious value on layer {} targeting {} with radius {}", layer_idx - 1, current_elem.target_height, radius); + current_elem.to_model_gracious_ = true; + spdlog::debug("Corrected taint leading to a wrong non gracious value on layer {} targeting {} with radius {}", layer_idx - 1, current_elem.target_height_, radius); } else { to_model_data - = TreeSupportUtils::safeUnion(increased.difference(volumes_.getAvoidance(radius, layer_idx - 1, AvoidanceType::COLLISION, true, settings.use_min_distance))); + = TreeSupportUtils::safeUnion(increased.difference(volumes_.getAvoidance(radius, layer_idx - 1, AvoidanceType::COLLISION, true, settings.use_min_distance_))); } } } - check_layer_data = current_elem.to_buildplate ? to_bp_data : to_model_data; + check_layer_data = current_elem.to_buildplate_ ? to_bp_data : to_model_data; - if (settings.increase_radius && check_layer_data.area() > 1) + if (settings.increase_radius_ && check_layer_data.area() > 1) { std::function validWithRadius = [&](coord_t next_radius) { - if (volumes_.ceilRadius(next_radius, settings.use_min_distance) <= volumes_.ceilRadius(radius, settings.use_min_distance)) + if (volumes_.ceilRadius(next_radius, settings.use_min_distance_) <= volumes_.ceilRadius(radius, settings.use_min_distance_)) { return true; } Polygons to_bp_data_2; - if (current_elem.to_buildplate) + if (current_elem.to_buildplate_) { // Regular union as output will not be used later => this area should always be a subset of the safeUnion one. - to_bp_data_2 = increased.difference(volumes_.getAvoidance(next_radius, layer_idx - 1, settings.type, false, settings.use_min_distance)).unionPolygons(); + to_bp_data_2 = increased.difference(volumes_.getAvoidance(next_radius, layer_idx - 1, settings.type_, false, settings.use_min_distance_)).unionPolygons(); } Polygons to_model_data_2; - if (config.support_rests_on_model && ! current_elem.to_buildplate) + if (config.support_rests_on_model && ! current_elem.to_buildplate_) { to_model_data_2 = increased .difference(volumes_.getAvoidance( next_radius, layer_idx - 1, - current_elem.to_model_gracious ? settings.type : AvoidanceType::COLLISION, + current_elem.to_model_gracious_ ? settings.type_ : AvoidanceType::COLLISION, true, - settings.use_min_distance)) + settings.use_min_distance_)) .unionPolygons(); } - Polygons check_layer_data_2 = current_elem.to_buildplate ? to_bp_data_2 : to_model_data_2; + Polygons check_layer_data_2 = current_elem.to_buildplate_ ? to_bp_data_2 : to_model_data_2; return check_layer_data_2.area() > 1; }; - coord_t ceil_radius_before = volumes_.ceilRadius(radius, settings.use_min_distance); + coord_t ceil_radius_before = volumes_.ceilRadius(radius, settings.use_min_distance_); // If the Collision Radius is smaller than the actual radius, check if it can catch up without violating the avoidance. if (config.getCollisionRadius(current_elem) < config.increase_radius_until_radius && config.getCollisionRadius(current_elem) < config.getRadius(current_elem)) { coord_t target_radius = std::min(config.getRadius(current_elem), config.increase_radius_until_radius); - coord_t current_ceil_radius = volumes_.getRadiusNextCeil(radius, settings.use_min_distance); + coord_t current_ceil_radius = volumes_.getRadiusNextCeil(radius, settings.use_min_distance_); - while (current_ceil_radius < target_radius && validWithRadius(volumes_.getRadiusNextCeil(current_ceil_radius + 1, settings.use_min_distance))) + while (current_ceil_radius < target_radius && validWithRadius(volumes_.getRadiusNextCeil(current_ceil_radius + 1, settings.use_min_distance_))) { - current_ceil_radius = volumes_.getRadiusNextCeil(current_ceil_radius + 1, settings.use_min_distance); + current_ceil_radius = volumes_.getRadiusNextCeil(current_ceil_radius + 1, settings.use_min_distance_); } - size_t resulting_eff_dtt = current_elem.effective_radius_height; - while (resulting_eff_dtt + 1 < current_elem.distance_to_top && config.getRadius(resulting_eff_dtt + 1, current_elem.buildplate_radius_increases) <= current_ceil_radius - && config.getRadius(resulting_eff_dtt + 1, current_elem.buildplate_radius_increases) <= config.getRadius(current_elem)) + size_t resulting_eff_dtt = current_elem.effective_radius_height_; + while (resulting_eff_dtt + 1 < current_elem.distance_to_top_ + && config.getRadius(resulting_eff_dtt + 1, current_elem.buildplate_radius_increases_) <= current_ceil_radius + && config.getRadius(resulting_eff_dtt + 1, current_elem.buildplate_radius_increases_) <= config.getRadius(current_elem)) { resulting_eff_dtt++; } - current_elem.effective_radius_height = resulting_eff_dtt; + current_elem.effective_radius_height_ = resulting_eff_dtt; // If catchup is not possible, it is likely that there is a hole below. Assuming the branches are in some kind of bowl, the branches should still stay away from the // wall of the bowl if possible. @@ -770,17 +771,17 @@ std::optional TreeSupport::increaseSingleArea( Polygons new_to_bp_data; Polygons new_to_model_data; - if (current_elem.to_buildplate) + if (current_elem.to_buildplate_) { - new_to_bp_data = to_bp_data.difference(volumes_.getCollision(config.getRadius(current_elem), layer_idx - 1, current_elem.use_min_xy_dist)); + new_to_bp_data = to_bp_data.difference(volumes_.getCollision(config.getRadius(current_elem), layer_idx - 1, current_elem.use_min_xy_dist_)); if (new_to_bp_data.area() > EPSILON) { to_bp_data = new_to_bp_data; } } - if (config.support_rests_on_model && (! current_elem.to_buildplate || mergelayer)) + if (config.support_rests_on_model && (! current_elem.to_buildplate_ || mergelayer)) { - new_to_model_data = to_model_data.difference(volumes_.getCollision(config.getRadius(current_elem), layer_idx - 1, current_elem.use_min_xy_dist)); + new_to_model_data = to_model_data.difference(volumes_.getCollision(config.getRadius(current_elem), layer_idx - 1, current_elem.use_min_xy_dist_)); if (new_to_model_data.area() > EPSILON) { to_model_data = new_to_model_data; @@ -804,42 +805,42 @@ std::optional TreeSupport::increaseSingleArea( // would only be relevant when support_rest_preference is GRACEFUL) Also unioning areas when an avoidance is requested may also have a relevant performance impact, so there // can be an argument made that the current workaround is preferable. const bool increase_bp_foot - = planned_foot_increase > 0 && (current_elem.to_buildplate || (current_elem.to_model_gracious && config.support_rest_preference == RestPreference::GRACEFUL)); + = planned_foot_increase > 0 && (current_elem.to_buildplate_ || (current_elem.to_model_gracious_ && config.support_rest_preference == RestPreference::GRACEFUL)); if (increase_bp_foot && config.getRadius(current_elem) >= config.branch_radius && config.getRadius(current_elem) >= config.increase_radius_until_radius) { - if (validWithRadius(config.getRadius(current_elem.effective_radius_height, current_elem.buildplate_radius_increases + planned_foot_increase))) + if (validWithRadius(config.getRadius(current_elem.effective_radius_height_, current_elem.buildplate_radius_increases_ + planned_foot_increase))) { - current_elem.buildplate_radius_increases += planned_foot_increase; + current_elem.buildplate_radius_increases_ += planned_foot_increase; radius = config.getCollisionRadius(current_elem); } } - if (ceil_radius_before != volumes_.ceilRadius(radius, settings.use_min_distance)) + if (ceil_radius_before != volumes_.ceilRadius(radius, settings.use_min_distance_)) { - if (current_elem.to_buildplate) + if (current_elem.to_buildplate_) { - to_bp_data = TreeSupportUtils::safeUnion(increased.difference(volumes_.getAvoidance(radius, layer_idx - 1, settings.type, false, settings.use_min_distance))); + to_bp_data = TreeSupportUtils::safeUnion(increased.difference(volumes_.getAvoidance(radius, layer_idx - 1, settings.type_, false, settings.use_min_distance_))); } - if (config.support_rests_on_model && (! current_elem.to_buildplate || mergelayer)) + if (config.support_rests_on_model && (! current_elem.to_buildplate_ || mergelayer)) { to_model_data = TreeSupportUtils::safeUnion(increased.difference( - volumes_.getAvoidance(radius, layer_idx - 1, current_elem.to_model_gracious ? settings.type : AvoidanceType::COLLISION, true, settings.use_min_distance))); + volumes_.getAvoidance(radius, layer_idx - 1, current_elem.to_model_gracious_ ? settings.type_ : AvoidanceType::COLLISION, true, settings.use_min_distance_))); } - check_layer_data = current_elem.to_buildplate ? to_bp_data : to_model_data; + check_layer_data = current_elem.to_buildplate_ ? to_bp_data : to_model_data; if (check_layer_data.area() < 1) { spdlog::error( "Lost area by doing catch up from {} to radius {}", ceil_radius_before, - volumes_.ceilRadius(config.getCollisionRadius(current_elem), settings.use_min_distance)); + volumes_.ceilRadius(config.getCollisionRadius(current_elem), settings.use_min_distance_)); } } } - if (current_elem.influence_area_limit_active && ! current_elem.use_min_xy_dist && check_layer_data.area() > 1 - && (current_elem.to_model_gracious || current_elem.distance_to_top <= config.min_dtt_to_model)) + if (current_elem.influence_area_limit_active_ && ! current_elem.use_min_xy_dist_ && check_layer_data.area() > 1 + && (current_elem.to_model_gracious_ || current_elem.distance_to_top_ <= config.min_dtt_to_model)) { const coord_t max_radius_increase = std::max( static_cast((config.branch_radius - config.min_radius) / config.tip_layers), @@ -852,30 +853,30 @@ std::optional TreeSupport::increaseSingleArea( to_model_data = TreeSupportUtils::safeUnion(to_model_data); while (! limit_range_validated) { - if (current_elem.to_buildplate) + if (current_elem.to_buildplate_) { - Polygons limited_to_bp = to_bp_data.intersection((current_elem.influence_area_limit_area)); + Polygons limited_to_bp = to_bp_data.intersection((current_elem.influence_area_limit_area_)); if (limited_to_bp.area() > 1) { to_bp_data = limited_to_bp; - to_model_data = to_model_data.intersection((current_elem.influence_area_limit_area)); + to_model_data = to_model_data.intersection((current_elem.influence_area_limit_area_)); limit_range_validated = true; } } else { - Polygons limited_to_model_data = to_model_data.intersection((current_elem.influence_area_limit_area)); + Polygons limited_to_model_data = to_model_data.intersection((current_elem.influence_area_limit_area_)); if (limited_to_model_data.area() > 1) { - to_bp_data = to_bp_data.intersection((current_elem.influence_area_limit_area)); + to_bp_data = to_bp_data.intersection((current_elem.influence_area_limit_area_)); to_model_data = limited_to_model_data; limit_range_validated = true; } } if (! limit_range_validated) { - const coord_t reach_increase = std::max(current_elem.influence_area_limit_range / 4, (config.maximum_move_distance + max_radius_increase)); - current_elem.influence_area_limit_range += reach_increase; + const coord_t reach_increase = std::max(current_elem.influence_area_limit_range_ / 4, (config.maximum_move_distance + max_radius_increase)); + current_elem.influence_area_limit_range_ += reach_increase; current_elem.RecreateInfluenceLimitArea(); } } @@ -902,7 +903,7 @@ void TreeSupport::increaseAreas( TreeSupportElement* parent = last_layer[idx]; TreeSupportElement elem(parent); // Also increases dtt. // Abstract representation of the model outline. If an influence area would move through it, it could teleport through a wall. - const Polygons wall_restriction = volumes_.getWallRestriction(config.getCollisionRadius(*parent), layer_idx, parent->use_min_xy_dist); + const Polygons wall_restriction = volumes_.getWallRestriction(config.getCollisionRadius(*parent), layer_idx, parent->use_min_xy_dist_); Polygons to_bp_data; Polygons to_model_data; @@ -917,8 +918,8 @@ void TreeSupport::increaseAreas( coord_t extra_speed = EPSILON; // The extra speed is added to both movement distances. Also move 5 microns faster than allowed to avoid rounding errors, this may cause // issues at VERY VERY small layer heights. coord_t extra_slow_speed = 0; // Only added to the slow movement distance. - const coord_t ceiled_parent_radius = volumes_.ceilRadius(config.getCollisionRadius(*parent), parent->use_min_xy_dist); - const coord_t projected_radius_increased = config.getRadius(parent->effective_radius_height + 1, parent->buildplate_radius_increases); + const coord_t ceiled_parent_radius = volumes_.ceilRadius(config.getCollisionRadius(*parent), parent->use_min_xy_dist_); + const coord_t projected_radius_increased = config.getRadius(parent->effective_radius_height_ + 1, parent->buildplate_radius_increases_); const coord_t projected_radius_delta = projected_radius_increased - config.getCollisionRadius(*parent); // When z distance is more than one layer up and down the Collision used to calculate the wall restriction will always include the wall (and not just the @@ -929,9 +930,9 @@ void TreeSupport::increaseAreas( * layer z-1:dddddxxxxxxxxxx * For more detailed visualisation see calculateWallRestrictions */ - const coord_t safe_movement_distance = (elem.use_min_xy_dist ? config.xy_min_distance : config.xy_distance) + const coord_t safe_movement_distance = (elem.use_min_xy_dist_ ? config.xy_min_distance : config.xy_distance) + (std::min(config.z_distance_top_layers, config.z_distance_bottom_layers) > 0 ? config.min_feature_size : 0); - if (ceiled_parent_radius == volumes_.ceilRadius(projected_radius_increased, parent->use_min_xy_dist) + if (ceiled_parent_radius == volumes_.ceilRadius(projected_radius_increased, parent->use_min_xy_dist_) || projected_radius_increased < config.increase_radius_until_radius) { // If it is guaranteed possible to increase the radius, the maximum movement speed can be increased, as it is assumed that the maximum movement speed is the one of @@ -946,11 +947,11 @@ void TreeSupport::increaseAreas( } if (config.layer_start_bp_radius > layer_idx - && config.recommendedMinRadius(layer_idx - 1) < config.getRadius(elem.effective_radius_height + 1, elem.buildplate_radius_increases)) + && config.recommendedMinRadius(layer_idx - 1) < config.getRadius(elem.effective_radius_height_ + 1, elem.buildplate_radius_increases_)) { // Can guarantee elephant foot radius increase. if (ceiled_parent_radius - == volumes_.ceilRadius(config.getRadius(parent->effective_radius_height + 1, parent->buildplate_radius_increases + 1), parent->use_min_xy_dist)) + == volumes_.ceilRadius(config.getRadius(parent->effective_radius_height_ + 1, parent->buildplate_radius_increases_ + 1), parent->use_min_xy_dist_)) { extra_speed += config.branch_radius * config.diameter_scale_bp_radius; } @@ -994,41 +995,41 @@ void TreeSupport::increaseAreas( } }; - const bool parent_moved_slow = elem.last_area_increase.increase_speed < config.maximum_move_distance; - const bool avoidance_speed_mismatch = parent_moved_slow && elem.last_area_increase.type != AvoidanceType::SLOW; - if (elem.last_area_increase.move && elem.last_area_increase.no_error && elem.can_use_safe_radius && ! mergelayer && ! avoidance_speed_mismatch - && (elem.distance_to_top >= config.tip_layers || parent_moved_slow)) + const bool parent_moved_slow = elem.last_area_increase_.increase_speed_ < config.maximum_move_distance; + const bool avoidance_speed_mismatch = parent_moved_slow && elem.last_area_increase_.type_ != AvoidanceType::SLOW; + if (elem.last_area_increase_.move_ && elem.last_area_increase_.no_error_ && elem.can_use_safe_radius_ && ! mergelayer && ! avoidance_speed_mismatch + && (elem.distance_to_top_ >= config.tip_layers || parent_moved_slow)) { // Assume that the avoidance type that was best for the parent is best for me. Makes this function about 7% faster. - const auto slow_or_fast = elem.last_area_increase.increase_speed < config.maximum_move_distance ? slow_speed : fast_speed; + const auto slow_or_fast = elem.last_area_increase_.increase_speed_ < config.maximum_move_distance ? slow_speed : fast_speed; insertSetting( AreaIncreaseSettings( - elem.last_area_increase.type, + elem.last_area_increase_.type_, slow_or_fast, increase_radius, - elem.last_area_increase.no_error, + elem.last_area_increase_.no_error_, ! use_min_radius, - elem.last_area_increase.move), + elem.last_area_increase_.move_), true); insertSetting( AreaIncreaseSettings( - elem.last_area_increase.type, + elem.last_area_increase_.type_, slow_or_fast, ! increase_radius, - elem.last_area_increase.no_error, + elem.last_area_increase_.no_error_, ! use_min_radius, - elem.last_area_increase.move), + elem.last_area_increase_.move_), true); } // Branch may still go though a hole, so a check has to be done whether the hole was already passed, and the regular avoidance can be used. - if (! elem.can_use_safe_radius) + if (! elem.can_use_safe_radius_) { // If the radius until which it is always increased can not be guaranteed, move fast. This is to avoid holes smaller than the real branch radius. // This does not guarantee the avoidance of such holes, but ensures they are avoided if possible. insertSetting(AreaIncreaseSettings(AvoidanceType::SLOW, slow_speed, increase_radius, no_error, ! use_min_radius, ! move), true); // Did we go through the hole. // In many cases the definition of hole is overly restrictive, so to avoid unnecessary fast movement in the tip, it is ignored there for a bit. // This CAN cause a branch to go though a hole it otherwise may have avoided. - if (elem.distance_to_top < round_up_divide(config.tip_layers, 2)) + if (elem.distance_to_top_ < round_up_divide(config.tip_layers, 2)) { insertSetting(AreaIncreaseSettings(AvoidanceType::FAST, slow_speed, increase_radius, no_error, ! use_min_radius, ! move), true); } @@ -1044,7 +1045,7 @@ void TreeSupport::increaseAreas( // While moving fast to be able to increase the radius (b) may seems preferable (over a) this can cause the a sudden skip in movement, which looks similar to a // layer shift and can reduce stability. As such idx have chosen to only use the user setting for radius increases as a friendly recommendation. insertSetting(AreaIncreaseSettings(AvoidanceType::SLOW, slow_speed, ! increase_radius, no_error, ! use_min_radius, move), true); // a (See above.) - if (elem.distance_to_top < config.tip_layers) + if (elem.distance_to_top_ < config.tip_layers) { insertSetting(AreaIncreaseSettings(AvoidanceType::FAST_SAFE, slow_speed, increase_radius, no_error, ! use_min_radius, move), true); } @@ -1052,7 +1053,7 @@ void TreeSupport::increaseAreas( insertSetting(AreaIncreaseSettings(AvoidanceType::FAST_SAFE, fast_speed, ! increase_radius, no_error, ! use_min_radius, move), true); } - if (elem.use_min_xy_dist) + if (elem.use_min_xy_dist_) { std::deque new_order; // If the branch currently has to use min_xy_dist check if the configuration would also be valid with the regular xy_distance before checking with use_min_radius. @@ -1060,26 +1061,26 @@ void TreeSupport::increaseAreas( for (AreaIncreaseSettings settings : order) { new_order.emplace_back(settings); - new_order.emplace_back(settings.type, settings.increase_speed, settings.increase_radius, settings.no_error, use_min_radius, settings.move); + new_order.emplace_back(settings.type_, settings.increase_speed_, settings.increase_radius_, settings.no_error_, use_min_radius, settings.move_); } order = new_order; } insertSetting( - AreaIncreaseSettings(AvoidanceType::FAST, fast_speed, ! increase_radius, ! no_error, elem.use_min_xy_dist, move), + AreaIncreaseSettings(AvoidanceType::FAST, fast_speed, ! increase_radius, ! no_error, elem.use_min_xy_dist_, move), true); // simplifying is very important for performance, but before an error is compensated by moving faster it makes sense to check to see if the simplifying has // caused issues // The getAccumulatedPlaceable0 intersection is just a quick and dirty check to see that at least a part of the branch would correctly rest on the model. // Proper way would be to offset getAccumulatedPlaceable0 by -radius first, but the small benefit to maybe detect an error, that should not be happening anyway is not // worth the performance impact in the expected case when a branch rests on the model. - if (elem.to_buildplate || (elem.to_model_gracious && (parent->area->intersection(volumes_.getPlaceableAreas(radius, layer_idx)).empty())) - || (! elem.to_model_gracious && (parent->area->intersection(volumes_.getAccumulatedPlaceable0(layer_idx)).empty()))) // Error case. + if (elem.to_buildplate_ || (elem.to_model_gracious_ && (parent->area_->intersection(volumes_.getPlaceableAreas(radius, layer_idx)).empty())) + || (! elem.to_model_gracious_ && (parent->area_->intersection(volumes_.getAccumulatedPlaceable0(layer_idx)).empty()))) // Error case. { // It is normal that we won't be able to find a new area at some point in time if we won't be able to reach layer 0 aka have to connect with the model. - insertSetting(AreaIncreaseSettings(AvoidanceType::FAST, fast_speed * 1.5, ! increase_radius, ! no_error, elem.use_min_xy_dist, move), true); + insertSetting(AreaIncreaseSettings(AvoidanceType::FAST, fast_speed * 1.5, ! increase_radius, ! no_error, elem.use_min_xy_dist_, move), true); } - if (elem.distance_to_top < elem.dont_move_until && elem.can_use_safe_radius) // Only do not move when holes would be avoided in every case. + if (elem.distance_to_top_ < elem.dont_move_until_ && elem.can_use_safe_radius_) // Only do not move when holes would be avoided in every case. { insertSetting( AreaIncreaseSettings(AvoidanceType::SLOW, 0, increase_radius, no_error, ! use_min_radius, ! move), @@ -1093,12 +1094,12 @@ void TreeSupport::increaseAreas( > (round_up_divide((extra_speed + extra_slow_speed + config.maximum_move_distance_slow), safe_movement_distance)); for (AreaIncreaseSettings settings : order) { - if (settings.move) + if (settings.move_) { - if (offset_slow.empty() && (settings.increase_speed == slow_speed || ! offset_independent_faster)) + if (offset_slow.empty() && (settings.increase_speed_ == slow_speed || ! offset_independent_faster)) { offset_slow = TreeSupportUtils::safeOffsetInc( - *parent->area, + *parent->area_, extra_speed + extra_slow_speed + config.maximum_move_distance_slow, wall_restriction, safe_movement_distance, @@ -1110,12 +1111,12 @@ void TreeSupport::increaseAreas( // At this point one can see that the Polygons class was never made for precision in the single digit micron range. } - if ((settings.increase_speed != slow_speed) && offset_fast.empty()) + if ((settings.increase_speed_ != slow_speed) && offset_fast.empty()) { if (offset_independent_faster) { offset_fast = TreeSupportUtils::safeOffsetInc( - *parent->area, + *parent->area_, extra_speed + config.maximum_move_distance, wall_restriction, safe_movement_distance, @@ -1144,15 +1145,15 @@ void TreeSupport::increaseAreas( std::optional result; // Check for errors! - if (! settings.no_error) + if (! settings.no_error_) { // If the area becomes for whatever reason something that clipper sees as a line, offset would stop working, so ensure that even if if wrongly would be a line, // it still actually has an area that can be increased - Polygons lines_offset = TreeSupportUtils::toPolylines(*parent->area).offsetPolyLine(EPSILON); - Polygons base_error_area = parent->area->unionPolygons(lines_offset); - result = increaseSingleArea(settings, layer_idx, parent, base_error_area, to_bp_data, to_model_data, inc_wo_collision, settings.increase_speed, mergelayer); + Polygons lines_offset = TreeSupportUtils::toPolylines(*parent->area_).offsetPolyLine(EPSILON); + Polygons base_error_area = parent->area_->unionPolygons(lines_offset); + result = increaseSingleArea(settings, layer_idx, parent, base_error_area, to_bp_data, to_model_data, inc_wo_collision, settings.increase_speed_, mergelayer); - if (fast_speed < settings.increase_speed) + if (fast_speed < settings.increase_speed_) { spdlog::warn( "Influence area could not be increased! Data about the Influence area: " @@ -1162,25 +1163,25 @@ void TreeSupport::increaseAreas( "safe {} until move {}", radius, layer_idx - 1, - elem.next_height, - elem.distance_to_top, - elem.buildplate_radius_increases, - elem.use_min_xy_dist, - elem.to_buildplate, - elem.to_model_gracious, - elem.can_use_safe_radius, - elem.dont_move_until, + elem.next_height_, + elem.distance_to_top_, + elem.buildplate_radius_increases_, + elem.use_min_xy_dist_, + elem.to_buildplate_, + elem.to_model_gracious_, + elem.can_use_safe_radius_, + elem.dont_move_until_, fmt::ptr(parent), config.getCollisionRadius(*parent), layer_idx, - parent->next_height, - parent->distance_to_top, - parent->buildplate_radius_increases, - parent->use_min_xy_dist, - parent->to_buildplate, - parent->to_model_gracious, - parent->can_use_safe_radius, - parent->dont_move_until); + parent->next_height_, + parent->distance_to_top_, + parent->buildplate_radius_increases_, + parent->use_min_xy_dist_, + parent->to_buildplate_, + parent->to_model_gracious_, + parent->can_use_safe_radius_, + parent->dont_move_until_); } } else @@ -1189,11 +1190,11 @@ void TreeSupport::increaseAreas( settings, layer_idx, parent, - settings.increase_speed == slow_speed ? offset_slow : offset_fast, + settings.increase_speed_ == slow_speed ? offset_slow : offset_fast, to_bp_data, to_model_data, inc_wo_collision, - std::max(settings.increase_speed - fast_speed, coord_t(0)), + std::max(settings.increase_speed_ - fast_speed, coord_t(0)), mergelayer); } @@ -1201,34 +1202,34 @@ void TreeSupport::increaseAreas( { elem = result.value(); radius = config.getCollisionRadius(elem); - elem.last_area_increase = settings; + elem.last_area_increase_ = settings; add = true; - bypass_merge - = ! settings.move - || (settings.use_min_distance - && elem.distance_to_top < config.tip_layers); // Do not merge if the branch should not move or the priority has to be to get farther away from the model. - if (settings.move) + bypass_merge = ! settings.move_ + || (settings.use_min_distance_ + && elem.distance_to_top_ + < config.tip_layers); // Do not merge if the branch should not move or the priority has to be to get farther away from the model. + if (settings.move_) { - elem.dont_move_until = 0; + elem.dont_move_until_ = 0; } else { - elem.result_on_layer = parent->result_on_layer; + elem.result_on_layer_ = parent->result_on_layer_; } - elem.can_use_safe_radius = settings.type != AvoidanceType::FAST; + elem.can_use_safe_radius_ = settings.type_ != AvoidanceType::FAST; - if (! settings.use_min_distance) + if (! settings.use_min_distance_) { - elem.use_min_xy_dist = false; + elem.use_min_xy_dist_ = false; } - if (! settings.no_error && fast_speed < settings.increase_speed) + if (! settings.no_error_ && fast_speed < settings.increase_speed_) { spdlog::warn("Trying to keep area by moving faster than intended: Success."); } break; } - else if (! settings.no_error && fast_speed < settings.increase_speed) + else if (! settings.no_error_ && fast_speed < settings.increase_speed_) { spdlog::error("Trying to keep area by moving faster than intended: FAILURE! Wrong branch likely!"); } @@ -1237,7 +1238,7 @@ void TreeSupport::increaseAreas( if (add) { Polygons max_influence_area = TreeSupportUtils::safeUnion( - inc_wo_collision.difference(volumes_.getCollision(radius, layer_idx - 1, elem.use_min_xy_dist)), + inc_wo_collision.difference(volumes_.getCollision(radius, layer_idx - 1, elem.use_min_xy_dist_)), TreeSupportUtils::safeUnion(to_bp_data, to_model_data)); // ^^^ Note: union seems useless, but some rounding errors somewhere can cause to_bp_data to be slightly bigger than it should be @@ -1252,7 +1253,7 @@ void TreeSupport::increaseAreas( else { influence_areas.emplace(elem, max_influence_area); - if (elem.to_buildplate) + if (elem.to_buildplate_) { to_bp_areas.emplace(elem, to_bp_data); } @@ -1268,7 +1269,7 @@ void TreeSupport::increaseAreas( // If the bottom most point of a branch is set, later functions will assume that the position is valid, and ignore it. // But as branches connecting with the model that are to small have to be culled, the bottom most point has to be not set. // A point can be set on the top most tip layer (maybe more if it should not move for a few layers). - parent->result_on_layer = Point(-1, -1); + parent->result_on_layer_ = Point(-1, -1); } }); } @@ -1351,14 +1352,14 @@ void TreeSupport::createLayerPathing(std::vector>& if (new_area->area() < 1) { - spdlog::error("Insert Error of Influence area on layer {}. Origin of {} areas. Was to bp {}", layer_idx - 1, elem.parents.size(), elem.to_buildplate); + spdlog::error("Insert Error of Influence area on layer {}. Origin of {} areas. Was to bp {}", layer_idx - 1, elem.parents_.size(), elem.to_buildplate_); } } // Place already fully constructed elements in the output. for (TreeSupportElement* elem : bypass_merge_areas) { - if (elem->area->area() < 1) + if (elem->area_->area() < 1) { spdlog::error("Insert Error of Influence area bypass on layer {}.", layer_idx - 1); } @@ -1376,38 +1377,38 @@ void TreeSupport::setPointsOnAreas(const TreeSupportElement* elem) { // Based on the branch center point of the current layer, the point on the next (further up) layer is calculated. - if (elem->result_on_layer == Point(-1, -1)) + if (elem->result_on_layer_ == Point(-1, -1)) { spdlog::error("Uninitialized support element"); return; } - for (TreeSupportElement* next_elem : elem->parents) + for (TreeSupportElement* next_elem : elem->parents_) { - if (next_elem->result_on_layer + if (next_elem->result_on_layer_ != Point(-1, -1)) // If the value was set somewhere else it it kept. This happens when a branch tries not to move after being unable to create a roof. { continue; } - Point from = elem->result_on_layer; - if (! (next_elem->area->inside(from, true))) + Point from = elem->result_on_layer_; + if (! (next_elem->area_->inside(from, true))) { PolygonUtils::moveInside( - *next_elem->area, + *next_elem->area_, from, 0); // Move inside has edgecases (see tests) so DONT use Polygons.inside to confirm correct move, Error with distance 0 is <= 1 // It is not required to check if how far this move moved a point as is can be larger than maximum_movement_distance. While this seems like a problem it may for example // occur after merges. } - next_elem->result_on_layer = from; + next_elem->result_on_layer_ = from; // Do not call recursive because then amount of layers would be restricted by the stack size. } } bool TreeSupport::setToModelContact(std::vector>& move_bounds, TreeSupportElement* first_elem, const LayerIndex layer_idx) { - if (first_elem->to_model_gracious) + if (first_elem->to_model_gracious_) { TreeSupportElement* check = first_elem; @@ -1424,9 +1425,9 @@ bool TreeSupport::setToModelContact(std::vector>& // Check for every layer upwards, up to the point where this influence area was created (either by initial insert or merge) if the branch could be placed on it, and highest // up layer index. - for (LayerIndex layer_check = layer_idx; check->next_height >= layer_check; layer_check++) + for (LayerIndex layer_check = layer_idx; check->next_height_ >= layer_check; layer_check++) { - Polygons check_valid_place_area = check->area->intersection(volumes_.getPlaceableAreas(config.getCollisionRadius(*check), layer_check)); + Polygons check_valid_place_area = check->area_->intersection(volumes_.getPlaceableAreas(config.getCollisionRadius(*check), layer_check)); if (! check_valid_place_area.empty()) { @@ -1435,9 +1436,9 @@ bool TreeSupport::setToModelContact(std::vector>& valid_place_area = check_valid_place_area; } checked.emplace_back(check); - if (check->parents.size() == 1) + if (check->parents_.size() == 1) { - check = check->parents[0]; + check = check->parents_[0]; } else { @@ -1451,10 +1452,10 @@ bool TreeSupport::setToModelContact(std::vector>& if (SUPPORT_TREE_ONLY_GRACIOUS_TO_MODEL) { spdlog::warn("No valid placement found for to model gracious element on layer {}: REMOVING BRANCH", layer_idx); - for (LayerIndex layer = layer_idx; layer <= first_elem->next_height; layer++) + for (LayerIndex layer = layer_idx; layer <= first_elem->next_height_; layer++) { move_bounds[layer].erase(checked[layer - layer_idx]); - delete checked[layer - layer_idx]->area; + delete checked[layer - layer_idx]->area_; delete checked[layer - layer_idx]; } return true; @@ -1462,7 +1463,7 @@ bool TreeSupport::setToModelContact(std::vector>& else { spdlog::warn("No valid placement found for to model gracious element on layer {}", layer_idx); - first_elem->to_model_gracious = false; + first_elem->to_model_gracious_ = false; return setToModelContact(move_bounds, first_elem, layer_idx); } } @@ -1471,7 +1472,7 @@ bool TreeSupport::setToModelContact(std::vector>& ++layer) // NOTE: Use of 'itoa' will make this crash in the loop, even though the operation should be equivalent. { move_bounds[layer].erase(checked[layer - layer_idx]); - delete checked[layer - layer_idx]->area; + delete checked[layer - layer_idx]->area_; delete checked[layer - layer_idx]; } @@ -1482,23 +1483,23 @@ bool TreeSupport::setToModelContact(std::vector>& } // Guess a point inside the influence area, in which the branch will be placed in. - Point best = checked[last_successfull_layer - layer_idx]->next_position; + Point best = checked[last_successfull_layer - layer_idx]->next_position_; if (! valid_place_area.inside(best, true)) { PolygonUtils::moveInside(valid_place_area, best); } - checked[last_successfull_layer - layer_idx]->result_on_layer = best; + checked[last_successfull_layer - layer_idx]->result_on_layer_ = best; spdlog::debug("Added gracious Support On Model Point ({},{}). The current layer is {}", best.X, best.Y, last_successfull_layer); return last_successfull_layer != layer_idx; } else // can not add graceful => just place it here and hope for the best { - Point best = first_elem->next_position; + Point best = first_elem->next_position_; Polygons valid_place_area - = first_elem->area->difference(volumes_.getAvoidance(config.getCollisionRadius(first_elem), layer_idx, AvoidanceType::COLLISION, first_elem->use_min_xy_dist)); + = first_elem->area_->difference(volumes_.getAvoidance(config.getCollisionRadius(first_elem), layer_idx, AvoidanceType::COLLISION, first_elem->use_min_xy_dist_)); if (! valid_place_area.inside(best, true)) { @@ -1513,7 +1514,7 @@ bool TreeSupport::setToModelContact(std::vector>& -config.getCollisionRadius(first_elem) / 2, coord_t(0) }) // Interestingly the first radius is working most of the time, even though it seems like it shouldn't. { - valid_place_area = first_elem->area->intersection(volumes_.getAccumulatedPlaceable0(layer_idx).offset(radius_offset)); + valid_place_area = first_elem->area_->intersection(volumes_.getAccumulatedPlaceable0(layer_idx).offset(radius_offset)); if (! valid_place_area.empty()) { PolygonUtils::moveInside(valid_place_area, best); @@ -1528,13 +1529,13 @@ bool TreeSupport::setToModelContact(std::vector>& } if (! found_partial_placement) { - PolygonUtils::moveInside(*first_elem->area, best); + PolygonUtils::moveInside(*first_elem->area_, best); spdlog::warn("Not able to place branch on non support blocker at layer {}", layer_idx); } } } - first_elem->result_on_layer = best; - first_elem->to_model_gracious = false; + first_elem->result_on_layer_ = best; + first_elem->to_model_gracious_ = false; spdlog::debug("Added NON gracious Support On Model Point ({},{}). The current layer is {}", best.X, best.Y, layer_idx); return false; } @@ -1547,12 +1548,12 @@ void TreeSupport::createNodesFromArea(std::vector> std::unordered_set remove; for (TreeSupportElement* init : move_bounds[0]) { - Point p = init->next_position; - if (! (init->area->inside(p, true))) + Point p = init->next_position_; + if (! (init->area_->inside(p, true))) { - PolygonUtils::moveInside(*init->area, p, 0); + PolygonUtils::moveInside(*init->area_, p, 0); } - init->result_on_layer = p; + init->result_on_layer_ = p; setPointsOnAreas(init); // Also set the parent nodes, as these will be required for the first iteration of the loop below. @@ -1574,7 +1575,7 @@ void TreeSupport::createNodesFromArea(std::vector> for (TreeSupportElement* del : remove) { move_bounds[0].erase(del); - delete del->area; + delete del->area_; delete del; } remove.clear(); @@ -1584,26 +1585,26 @@ void TreeSupport::createNodesFromArea(std::vector> for (TreeSupportElement* elem : move_bounds[layer_idx]) { bool removed = false; - if (elem->result_on_layer == Point(-1, -1)) // Check if the resulting center point is not yet set. + if (elem->result_on_layer_ == Point(-1, -1)) // Check if the resulting center point is not yet set. { - if (elem->to_buildplate || (! elem->to_buildplate && elem->distance_to_top < config.min_dtt_to_model && ! elem->supports_roof)) + if (elem->to_buildplate_ || (! elem->to_buildplate_ && elem->distance_to_top_ < config.min_dtt_to_model && ! elem->supports_roof_)) { - if (elem->to_buildplate) + if (elem->to_buildplate_) { spdlog::error( "Uninitialized Influence area targeting ({},{}) at target_height: {} layer: {}", - elem->target_position.X, - elem->target_position.Y, - elem->target_height, + elem->target_position_.X, + elem->target_position_.Y, + elem->target_height_, layer_idx); } remove.emplace(elem); // We dont need to remove yet the parents as they will have a lower dtt and also no result_on_layer set. removed = true; - for (TreeSupportElement* parent : elem->parents) + for (TreeSupportElement* parent : elem->parents_) { // When the roof was not able to generate downwards enough, the top elements may have not moved, and have result_on_layer already set. As this branch needs // to be removed => all parents result_on_layer have to be invalidated. - parent->result_on_layer = Point(-1, -1); + parent->result_on_layer_ = Point(-1, -1); } continue; } @@ -1628,7 +1629,7 @@ void TreeSupport::createNodesFromArea(std::vector> for (TreeSupportElement* del : remove) { move_bounds[layer_idx].erase(del); - delete del->area; + delete del->area_; delete del; } remove.clear(); @@ -1669,23 +1670,23 @@ void TreeSupport::generateBranchAreas( // Calculate multiple ovalized circles, to connect with every parent and child. Also generate regular circle for the current layer. Merge all these into one area. std::vector> movement_directions{ std::pair(Point(0, 0), radius) }; - if (! elem->skip_ovalisation) + if (! elem->skip_ovalisation_) { if (child_elem != nullptr) { - Point movement = (child_elem->result_on_layer - elem->result_on_layer); + Point movement = (child_elem->result_on_layer_ - elem->result_on_layer_); movement_directions.emplace_back(movement, radius); } - for (TreeSupportElement* parent : elem->parents) + for (TreeSupportElement* parent : elem->parents_) { - Point movement = (parent->result_on_layer - elem->result_on_layer); + Point movement = (parent->result_on_layer_ - elem->result_on_layer_); movement_directions.emplace_back(movement, std::max(config.getRadius(parent), config.support_line_width)); - parent_uses_min |= parent->use_min_xy_dist; + parent_uses_min |= parent->use_min_xy_dist_; } - for (Point target : elem->additional_ovalization_targets) + for (Point target : elem->additional_ovalization_targets_) { - Point movement = (target - elem->result_on_layer); + Point movement = (target - elem->result_on_layer_); movement_directions.emplace_back(movement, std::max(radius, config.support_line_width)); } } @@ -1702,7 +1703,7 @@ void TreeSupport::generateBranchAreas( // Visualization: https://jsfiddle.net/0zvcq39L/2/ // Ovalizes the circle to an ellipse, that contains both old center and new target position. double used_scale = (movement.second + offset) / (1.0 * config.branch_radius); - Point center_position = elem->result_on_layer + movement.first / 2; + Point center_position = elem->result_on_layer_ + movement.first / 2; const double moveX = movement.first.X / (used_scale * config.branch_radius); const double moveY = movement.first.Y / (used_scale * config.branch_radius); const double vsize_inv = 0.5 / (0.01 + std::sqrt(moveX * moveX + moveY * moveY)); @@ -1724,7 +1725,7 @@ void TreeSupport::generateBranchAreas( poly = poly.unionPolygons() .offset(std::min(static_cast(FUDGE_LENGTH), config.support_line_width / 4)) - .difference(volumes_.getCollision(0, linear_data[idx].first, parent_uses_min || elem->use_min_xy_dist)); + .difference(volumes_.getCollision(0, linear_data[idx].first, parent_uses_min || elem->use_min_xy_dist_)); // ^^^ There seem to be some rounding errors, causing a branch to be a tiny bit further away from the model that it has to be. This can cause the tip to be slightly // further away front the overhang (x/y wise) than optimal. // This fixes it, and for every other part, 0.05mm will not be noticed. @@ -1754,16 +1755,16 @@ void TreeSupport::generateBranchAreas( Polygons polygons_with_correct_center; for (PolygonsPart part : nozzle_path.splitIntoParts(false)) { - if (part.inside(elem->result_on_layer, true)) + if (part.inside(elem->result_on_layer_, true)) { polygons_with_correct_center = polygons_with_correct_center.unionPolygons(part); } else { // Try a fuzzy inside as sometimes the point should be on the border, but is not because of rounding errors... - Point from = elem->result_on_layer; + Point from = elem->result_on_layer_; PolygonUtils::moveInside(part, from, 0); - if (vSize2(elem->result_on_layer - from) < (FUDGE_LENGTH * FUDGE_LENGTH) / 4) + if (vSize2(elem->result_on_layer_ - from) < (FUDGE_LENGTH * FUDGE_LENGTH) / 4) { polygons_with_correct_center = polygons_with_correct_center.unionPolygons(part); } @@ -1772,7 +1773,7 @@ void TreeSupport::generateBranchAreas( // Increase the area again, to ensure the nozzle path when calculated later is very similar to the one assumed above. linear_inserts[idx] = polygons_with_correct_center.offset(config.support_line_width / 2).unionPolygons(); linear_inserts[idx] - = linear_inserts[idx].difference(volumes_.getCollision(0, linear_data[idx].first, parent_uses_min || elem->use_min_xy_dist)).unionPolygons(); + = linear_inserts[idx].difference(volumes_.getCollision(0, linear_data[idx].first, parent_uses_min || elem->use_min_xy_dist_)).unionPolygons(); } } } @@ -1814,14 +1815,14 @@ void TreeSupport::smoothBranchAreas(std::vectorparents) + for (TreeSupportElement* parent : data_pair.first->parents_) { if (config.getRadius(*parent) != config.getCollisionRadius(*parent)) { do_something = true; max_outer_wall_distance = std::max( max_outer_wall_distance, - vSize(data_pair.first->result_on_layer - parent->result_on_layer) - (config.getRadius(*data_pair.first) - config.getRadius(*parent))); + vSize(data_pair.first->result_on_layer_ - parent->result_on_layer_) - (config.getRadius(*data_pair.first) - config.getRadius(*parent))); } } max_outer_wall_distance @@ -1829,7 +1830,7 @@ void TreeSupport::smoothBranchAreas(std::vectorparents) + for (TreeSupportElement* parent : data_pair.first->parents_) { if (config.getRadius(*parent) != config.getCollisionRadius(*parent)) { @@ -1872,12 +1873,12 @@ void TreeSupport::smoothBranchAreas(std::vector data_pair = processing[processing_idx]; bool do_something = false; Polygons max_allowed_area; - for (size_t idx = 0; idx < data_pair.first->parents.size(); idx++) + for (size_t idx = 0; idx < data_pair.first->parents_.size(); idx++) { - TreeSupportElement* parent = data_pair.first->parents[idx]; + TreeSupportElement* parent = data_pair.first->parents_[idx]; const coord_t max_outer_line_increase = max_radius_change_per_layer; Polygons result = layer_tree_polygons[layer_idx + 1][parent].offset(max_outer_line_increase); - const Point direction = data_pair.first->result_on_layer - parent->result_on_layer; + const Point direction = data_pair.first->result_on_layer_ - parent->result_on_layer_; // Move the polygons object. for (auto& outer : result) { @@ -1928,7 +1929,7 @@ void TreeSupport::dropNonGraciousAreas( { TreeSupportElement* elem = linear_data[idx].second; bool non_gracious_model_contact - = ! elem->to_model_gracious + = ! elem->to_model_gracious_ && ! inverse_tree_order.count(elem); // If an element has no child, it connects to whatever is below as no support further down for it will exist. if (non_gracious_model_contact) { @@ -2261,15 +2262,15 @@ void TreeSupport::drawAreas(std::vector>& move_bou { // (Check if) We either come from nowhere at the final layer or we had invalid parents 2. should never happen but just to be sure: if ((layer_idx > 0 - && ((! inverse_tree_order.count(elem) && elem->target_height == layer_idx && config.min_dtt_to_model > 0 && ! elem->to_buildplate) - || (inverse_tree_order.count(elem) && inverse_tree_order[elem]->result_on_layer == Point(-1, -1))))) + && ((! inverse_tree_order.count(elem) && elem->target_height_ == layer_idx && config.min_dtt_to_model > 0 && ! elem->to_buildplate_) + || (inverse_tree_order.count(elem) && inverse_tree_order[elem]->result_on_layer_ == Point(-1, -1))))) { continue; } - for (TreeSupportElement* par : elem->parents) + for (TreeSupportElement* par : elem->parents_) { - if (par->result_on_layer == Point(-1, -1)) + if (par->result_on_layer_ == Point(-1, -1)) { continue; } @@ -2315,7 +2316,7 @@ void TreeSupport::drawAreas(std::vector>& move_bou { for (std::pair data_pair : layer_tree_polygons[layer_idx]) { - if (data_pair.first->missing_roof_layers > data_pair.first->distance_to_top + if (data_pair.first->missing_roof_layers_ > data_pair.first->distance_to_top_ && TreeSupportUtils::generateSupportInfillLines(data_pair.second, config, true, layer_idx, config.support_roof_line_distance, nullptr, true).empty()) { std::vector to_disable_roofs; @@ -2325,8 +2326,8 @@ void TreeSupport::drawAreas(std::vector>& move_bou std::vector to_disable_roofs_next; for (TreeSupportElement* elem : to_disable_roofs) { - elem->missing_roof_layers = 0; - if (data_pair.first->missing_roof_layers > data_pair.first->distance_to_top + 1) + elem->missing_roof_layers_ = 0; + if (data_pair.first->missing_roof_layers_ > data_pair.first->distance_to_top_ + 1) { to_disable_roofs_next.emplace_back(inverse_tree_order[elem]); } @@ -2343,7 +2344,7 @@ void TreeSupport::drawAreas(std::vector>& move_bou { for (std::pair data_pair : layer_tree_polygons[layer_idx]) { - ((data_pair.first->missing_roof_layers > data_pair.first->distance_to_top) ? support_roof_storage : support_layer_storage)[layer_idx].add(data_pair.second); + ((data_pair.first->missing_roof_layers_ > data_pair.first->distance_to_top_) ? support_roof_storage : support_layer_storage)[layer_idx].add(data_pair.second); } } diff --git a/src/TreeSupportTipGenerator.cpp b/src/TreeSupportTipGenerator.cpp index f1f2aed10c..c6c57d901f 100644 --- a/src/TreeSupportTipGenerator.cpp +++ b/src/TreeSupportTipGenerator.cpp @@ -662,11 +662,11 @@ void TreeSupportTipGenerator::addPointAsInfluenceArea( skip_ovalisation, support_tree_limit_branch_reach, support_tree_branch_reach_limit); - elem->area = new Polygons(area); + elem->area_ = new Polygons(area); for (Point p : additional_ovalization_targets) { - elem->additional_ovalization_targets.emplace_back(p); + elem->additional_ovalization_targets_.emplace_back(p); } move_bounds[insert_layer].emplace(elem); @@ -803,18 +803,18 @@ void TreeSupportTipGenerator::removeUselessAddedPoints( for (TreeSupportElement* elem : move_bounds[layer_idx]) { - if (roof_on_layer.inside(elem->result_on_layer)) // Remove branches that start inside of support interface + if (roof_on_layer.inside(elem->result_on_layer_)) // Remove branches that start inside of support interface { to_be_removed.emplace_back(elem); } - else if (elem->supports_roof) + else if (elem->supports_roof_) { - Point from = elem->result_on_layer; + Point from = elem->result_on_layer_; PolygonUtils::moveInside(roof_on_layer_above, from); // Remove branches should have interface above them, but dont. Should never happen. if (roof_on_layer_above.empty() - || (! roof_on_layer_above.inside(elem->result_on_layer) - && vSize2(from - elem->result_on_layer) > config.getRadius(0) * config.getRadius(0) + FUDGE_LENGTH * FUDGE_LENGTH)) + || (! roof_on_layer_above.inside(elem->result_on_layer_) + && vSize2(from - elem->result_on_layer_) > config.getRadius(0) * config.getRadius(0) + FUDGE_LENGTH * FUDGE_LENGTH)) { to_be_removed.emplace_back(elem); spdlog::warn("Removing already placed tip that should have roof above it?"); @@ -825,7 +825,7 @@ void TreeSupportTipGenerator::removeUselessAddedPoints( for (auto elem : to_be_removed) { move_bounds[layer_idx].erase(elem); - delete elem->area; + delete elem->area_; delete elem; } } From 403061a0bf94ad7ad20c336f84774e7648e3e905 Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Tue, 21 Nov 2023 11:40:23 +0100 Subject: [PATCH 15/48] Fixed variable shadowing warnings --- include/InsetOrderOptimizer.h | 38 +++---- include/infill/SierpinskiFill.h | 179 +++++++++++++++--------------- src/InsetOrderOptimizer.cpp | 72 ++++++------ src/infill/SierpinskiFill.cpp | 188 ++++++++++++++++---------------- 4 files changed, 241 insertions(+), 236 deletions(-) diff --git a/include/InsetOrderOptimizer.h b/include/InsetOrderOptimizer.h index f5bdba8f57..e5592806a2 100644 --- a/include/InsetOrderOptimizer.h +++ b/include/InsetOrderOptimizer.h @@ -85,26 +85,26 @@ class InsetOrderOptimizer static value_type getInsetOrder(const auto& input, const bool outer_to_inner); private: - const FffGcodeWriter& gcode_writer; - const SliceDataStorage& storage; - LayerPlan& gcode_layer; - const Settings& settings; - const size_t extruder_nr; - const GCodePathConfig& inset_0_non_bridge_config; - const GCodePathConfig& inset_X_non_bridge_config; - const GCodePathConfig& inset_0_bridge_config; - const GCodePathConfig& inset_X_bridge_config; - const bool retract_before_outer_wall; - const coord_t wall_0_wipe_dist; - const coord_t wall_x_wipe_dist; - const size_t wall_0_extruder_nr; - const size_t wall_x_extruder_nr; - const ZSeamConfig& z_seam_config; - const std::vector& paths; - const LayerIndex layer_nr; + const FffGcodeWriter& gcode_writer_; + const SliceDataStorage& storage_; + LayerPlan& gcode_layer_; + const Settings& settings_; + const size_t extruder_nr_; + const GCodePathConfig& inset_0_non_bridge_config_; + const GCodePathConfig& inset_X_non_bridge_config_; + const GCodePathConfig& inset_0_bridge_config_; + const GCodePathConfig& inset_X_bridge_config_; + const bool retract_before_outer_wall_; + const coord_t wall_0_wipe_dist_; + const coord_t wall_x_wipe_dist_; + const size_t wall_0_extruder_nr_; + const size_t wall_x_extruder_nr_; + const ZSeamConfig& z_seam_config_; + const std::vector& paths_; + const LayerIndex layer_nr_; - std::vector> inset_polys; // vector of vectors holding the inset polygons - Polygons retraction_region; // After printing an outer wall, move into this region so that retractions do not leave visible blobs. Calculated lazily if needed (see + std::vector> inset_polys_; // vector of vectors holding the inset polygons + Polygons retraction_region_; // After printing an outer wall, move into this region so that retractions do not leave visible blobs. Calculated lazily if needed (see // retraction_region_calculated). /*! diff --git a/include/infill/SierpinskiFill.h b/include/infill/SierpinskiFill.h index 9383155241..f5603bd509 100644 --- a/include/infill/SierpinskiFill.h +++ b/include/infill/SierpinskiFill.h @@ -1,6 +1,6 @@ -//Copyright (c) 2017 Tim Kuipers -//Copyright (c) 2018 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2017 Tim Kuipers +// Copyright (c) 2018 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef INFILL_SIERPINSKI_FILL_H #define INFILL_SIERPINSKI_FILL_H @@ -18,17 +18,17 @@ class SVG; /*! * A class for generating the Cross and Cross 3D infill patterns. - * - * + * + * * === BASIC SUBDIVISION === - * + * * The line is generated from a recurvive subdivision of the area of a square into triangles. * _______ _______ _______ _______ * | /| |\ /| |\ | /| |\ /|\ /| . * | / | | \ / | |__\|/__| |/_\|/_\| etc . * | / | | / \ | | /|\ | |\ /|\ /| . * |/______| |/_____\| |/__|__\| |/_\|/_\| . - * + * * Triangles are subdivided into two children like so: * |\ |\ . * |A \ |A \ . @@ -38,9 +38,9 @@ class SVG; * | / | / Note that the polygon direction flips between clockwise and CCW each subdivision * |B / |B / * |/ |/ - * + * * The direction of the space filling curve along each triangle is recorded: - * + * * |\ |\ . * |B \ AC_TO_BC |B \ AC_TO_AB . * | ↑ \ | ↑ \ . @@ -67,18 +67,18 @@ class SVG; * | / |↗ / . * |A / |A / AC_TO_BC . * |/ |/ . - * - * + * + * * Each triangle is associated with the length of the Sierpinski dual curve going through the triangle. * The realized density of a triangle is calculated using the length of the Sierpinski segment, * the line width and the area of the triangle. * The realized density is compared with the requested average density over the triangle according to * the volumetric density specification of the user. - * - * - * + * + * + * * === BALANCING === - * + * * If for any single triangle in the pattern the total realized length of all/both children is less than the average requested length of that parent triangle, * the parent triangle would definitely like to be subdivided. * (When dithering, we may subdivide at a lower threshold and a constraint may cause such a triangle not to be subdivided after all. See CONSTRAINTS.) @@ -86,14 +86,14 @@ class SVG; * namely when the other child has a surplus of requested length. * The error thus induced should be recorded. * Value will be transported from the child with a surplus to the child with a lack of requested length. - * + * * Example: * Parent cell realizes 10mm filament, but child 1 requests 100mm and child 2 requests 2mm. * Subdivision would lead to two cells with 14mm filament realized. * Cell 2 therefore obtains 12mm filament from cell 1, where 12mm is recorded as an error. - * + * * === CONSTRAINTS === - * + * * When subdividing an AC_TO_AB or an AB_TO_BC triangle, the place where the Sierpinski curve intersects AB changes. * In order to maintain a connected Sierpinski curve, we need to subdivide the (respectively) next / previous as well. * A triangle is said to be constrained by a preceding AC_TO_AB triangle or a consecutive AB_TO_BC triangle @@ -103,22 +103,22 @@ class SVG; * \⟶⟶⟶⟶|↘ \ . * \ | ↘/ . * \|/ . - * + * * ^^^ * constrained triangle * ^^^^^^^ * constraining triangle - * - * + * + * * This constraint means that sharp changes in output density are impossible. * Instead the output density changes with steps of 1 recursion depth difference at a time. * When the input requested density has a sharp contrast, we should try to keep the error introduced by the consecutivity constraint * as close to the contrast edge as possible. - * - * - * + * + * + * * === TREE VIEW === - * + * * The problem is easiest conceptualized when looking at the tree of all possible triangles. * The final sequence of triangles which are crossed by the Sierpinski dual curve can be seen as a cut through the tree. *. @@ -136,12 +136,12 @@ class SVG; *. / \ / \ / \ / \ . *. / \ / \ / \ / \ /#\ /#\ / \ / \ . *. /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\/#\/#\/#\/#\ . The chosen nodes # cut through the tree at a variable depth leading to variable density infill. - * - * - * - * + * + * + * + * * === ALGORITHM === - * + * * The algorithm runs as follows: * 1- We create the tree of all possible triangles * 2- We decide on the lower density boundary sequence of nodes (triangles) to cross @@ -154,7 +154,7 @@ class SVG; * - Bubble up the total requested line length from the leaves all teh way to the root * - Calculate the average length of the Cross Fractal crossing of each triangle and record it * - * + * * >> 2. Create lower boundary * ********************* * - Start the sequence of nodes with the starting triangles (We start with two triangles, which form a square) @@ -162,13 +162,13 @@ class SVG; * Each iteration: * 1- Move error length values introduced by constraining triangles from constrained triangle to constraining triangle. * 2- (Use errors to) subdivide each node where the total errored value is now large enough - * + * * 2.1 * From highest density cells currently in the sequence to lowest density: * - Calculate the difference between the actualized length and the requested length. * - Distribute this error over the constraining triangles. * - Cascade this error value further up toward the root when processing the next density of cells. - * + * * 2.2 * From lowest density cells currently in the sequence to highest density cells: * - Try to subdivide the node / two consecutive nodes which share an AB edge @@ -176,7 +176,7 @@ class SVG; * * Redistribute error to where it came from: cascade errors back down the tree toward teh leaves where the error came from. * * Balance children: make sure each newly introduced child has a positive error value. * - * + * * >> 3. Dithering * ********* * From begin to end of the sequence: @@ -184,17 +184,18 @@ class SVG; * If the errored value is high enough: * subdivide this/these triangle(s) * - Carry along the induced error to the next triangle in the sequence. - * - * + * + * * ------------------------------------------------------------------------------------------------------ - * - * + * + * * By following the path along the middle points of each triangle the Siepinski Curve will be generated. * By following the path along the middle of each edge the Cross Fractal curve will be generated, which is the dual of the Sierpinski curve. */ class SierpinskiFill { friend class SierpinskiFillTest; + public: /*! * Basic constructor @@ -206,12 +207,12 @@ class SierpinskiFill /*! * Generate the cross pattern curve */ - Polygon generateCross() const; + Polygon generateCross() const; /*! * Generate the Sierpinski space filling curve */ - Polygon generateCross(coord_t z, coord_t min_dist_to_side, coord_t pocket_size) const; + Polygon generateCross(coord_t z, coord_t min_dist_to_side, coord_t pocket_size) const; /*! * Output the triangles to a canvas @@ -228,13 +229,13 @@ class SierpinskiFill }; /*! * A node in the tree of all triangles. - * + * * Vertex C is the straight 90* corner. - * + * * Depending on the recursion depth the 90* corner is either on the left or on the right of the curve. - * + * * The direction in which this triangle is crossed by the Sierpinski curve is recorded. - * + * * Some statistics about the requested and realized polygon length are recorded on each node in the tree. */ struct SierpinskiTriangle @@ -249,43 +250,47 @@ class SierpinskiFill AC_TO_BC, AB_TO_BC }; - Point straight_corner; //!< C, the 90* corner of the triangle - Point a; //!< The corner closer to the start of the space filling curve - Point b; //!< The corner closer to the end of the space filling curve - SierpinskiDirection dir; //!< The (order in which) edges being crossed by the Sierpinski curve. - bool straight_corner_is_left; //!< Whether the \ref straight_corner is left of the curve, rather than right. I.e. whether triangle ABC is counter-clockwise - int depth; //!< The recursion depth at which this triangle is generated. Root is zero. - - float area; //!< The area of the triangle in mm^2 - float requested_length; //!< The polyline length corresponding to the average density requested by the volumetric density specification. - float realized_length; //!< The polyline length of the Cross Fractal line segment which would cross this triangle. - float total_child_realized_length; //!< The total of the \ref realized_length of all children. - float error_left; //!< Extra value modulating the \ref requested_length obtained from the triangle on the left / obtained by giving value to the triangle to the left. - float error_right; //!< Extra value modulating the \ref requested_length obtained from the triangle on the right / obtained by giving value to the triangle to the right. + const Point straight_corner_; //!< C, the 90* corner of the triangle + const Point a_; //!< The corner closer to the start of the space filling curve + const Point b_; //!< The corner closer to the end of the space filling curve + const SierpinskiDirection dir_; //!< The (order in which) edges being crossed by the Sierpinski curve. + const bool straight_corner_is_left_; //!< Whether the \ref straight_corner is left of the curve, rather than right. I.e. whether triangle ABC is counter-clockwise + const int depth_; //!< The recursion depth at which this triangle is generated. Root is zero. + + float area_; //!< The area of the triangle in mm^2 + float requested_length_; //!< The polyline length corresponding to the average density requested by the volumetric density specification. + float realized_length_; //!< The polyline length of the Cross Fractal line segment which would cross this triangle. + float total_child_realized_length_; //!< The total of the \ref realized_length of all children. + float error_left_; //!< Extra value modulating the \ref requested_length obtained from the triangle on the left / obtained by giving value to the triangle to the left. + float error_right_; //!< Extra value modulating the \ref requested_length obtained from the triangle on the right / obtained by giving value to the triangle to the right. SierpinskiTriangle(Point straight_corner, Point a, Point b, SierpinskiDirection dir, bool straight_corner_is_left, int depth) - : straight_corner(straight_corner) - , a(a) - , b(b) - , dir(dir) - , straight_corner_is_left(straight_corner_is_left) - , depth(depth) - , requested_length(0) - , total_child_realized_length(0) - , error_left(0) - , error_right(0) - {} + : straight_corner_(straight_corner) + , a_(a) + , b_(b) + , dir_(dir) + , straight_corner_is_left_(straight_corner_is_left) + , depth_(depth) + , requested_length_(0) + , total_child_realized_length_(0) + , error_left_(0) + , error_right_(0) + { + } //! Constructor for the root node. SierpinskiTriangle() - : straight_corner(no_point) - , a(no_point) - , b(no_point) - , depth(0) - , requested_length(0) - , total_child_realized_length(0) - , error_left(0) - , error_right(0) - {} + : straight_corner_(no_point) + , a_(no_point) + , b_(no_point) + , dir_(SierpinskiDirection::AB_TO_BC) + , straight_corner_is_left_(false) + , depth_(0) + , requested_length_(0) + , total_child_realized_length_(0) + , error_left_(0) + , error_right_(0) + { + } //! Get the first edge of this triangle crossed by the Sierpinski and/or Cross Fractal curve. Edge getFromEdge(); //! Get the second edge of this triangle crossed by the Sierpinski and/or Cross Fractal curve. @@ -368,9 +373,9 @@ class SierpinskiFill /*! * For each noe: subdivide if possible. - * + * * Start trying cells with lower recursion level before trying cells with deeper recursion depth, i.e. higher density value. - * + * * \return Whether the sequence has changed. */ bool subdivideAll(); @@ -378,15 +383,15 @@ class SierpinskiFill /*! * Bubble up errors from nodes which like to subdivide more, * but which are constrained by neighboring cells of lower recursion level. - * - * \return Whether we have redistributed errors which could cause a new subdivision + * + * \return Whether we have redistributed errors which could cause a new subdivision */ bool bubbleUpConstraintErrors(); /*! * Subdivide a node into its children. * Redistribute leftover errors needed for this subdivision and account for errors needed to keep the children balanced. - * + * * \param it iterator to the node to subdivide * \param redistribute_errors Whether to redistribute the accumulated errors to neighboring nodes and/or among children * \return The last child, so that we can iterate further through the sequence on the input iterator. @@ -398,28 +403,28 @@ class SierpinskiFill * Redistribute positive errors in as much as they aren't needed to subdivide this node. * If this node has received too much positive error then it will subdivide * and pass along the error from whence it came. - * + * * This is called just before performing a subdivision. */ void redistributeLeftoverErrors(std::list::iterator begin, std::list::iterator end, bool distribute_subdivision_errors); /*! * Balance child values such that they account for the minimum value of their recursion level. - * + * * Account for errors caused by unbalanced children. * Plain subdivision can lead to one child having a smaller value than the density_value associated with the recursion depth * if another child has a high enough value such that the parent value will cause subdivision. - * + * * In order to compensate for the error incurred, we more error value from the high child to the low child * such that the low child has an erroredValue of at least the density_value associated with the recusion depth. - * + * * \param node The parent node of the children to balance */ void balanceErrors(std::list::iterator begin, std::list::iterator end); /*! * Settle down unused errors which have been bubbled up, but haven't been used to subdivide any cell. - * + * * Should be called before dithering. */ void settleErrors(); diff --git a/src/InsetOrderOptimizer.cpp b/src/InsetOrderOptimizer.cpp index 7549ae53da..9b2358aa62 100644 --- a/src/InsetOrderOptimizer.cpp +++ b/src/InsetOrderOptimizer.cpp @@ -51,36 +51,36 @@ InsetOrderOptimizer::InsetOrderOptimizer( const size_t wall_x_extruder_nr, const ZSeamConfig& z_seam_config, const std::vector& paths) - : gcode_writer(gcode_writer) - , storage(storage) - , gcode_layer(gcode_layer) - , settings(settings) - , extruder_nr(extruder_nr) - , inset_0_non_bridge_config(inset_0_non_bridge_config) - , inset_X_non_bridge_config(inset_X_non_bridge_config) - , inset_0_bridge_config(inset_0_bridge_config) - , inset_X_bridge_config(inset_X_bridge_config) - , retract_before_outer_wall(retract_before_outer_wall) - , wall_0_wipe_dist(wall_0_wipe_dist) - , wall_x_wipe_dist(wall_x_wipe_dist) - , wall_0_extruder_nr(wall_0_extruder_nr) - , wall_x_extruder_nr(wall_x_extruder_nr) - , z_seam_config(z_seam_config) - , paths(paths) - , layer_nr(gcode_layer.getLayerNr()) + : gcode_writer_(gcode_writer) + , storage_(storage) + , gcode_layer_(gcode_layer) + , settings_(settings) + , extruder_nr_(extruder_nr) + , inset_0_non_bridge_config_(inset_0_non_bridge_config) + , inset_X_non_bridge_config_(inset_X_non_bridge_config) + , inset_0_bridge_config_(inset_0_bridge_config) + , inset_X_bridge_config_(inset_X_bridge_config) + , retract_before_outer_wall_(retract_before_outer_wall) + , wall_0_wipe_dist_(wall_0_wipe_dist) + , wall_x_wipe_dist_(wall_x_wipe_dist) + , wall_0_extruder_nr_(wall_0_extruder_nr) + , wall_x_extruder_nr_(wall_x_extruder_nr) + , z_seam_config_(z_seam_config) + , paths_(paths) + , layer_nr_(gcode_layer.getLayerNr()) { } bool InsetOrderOptimizer::addToLayer() { // Settings & configs: - const auto pack_by_inset = ! settings.get("optimize_wall_printing_order"); - const auto inset_direction = settings.get("inset_direction"); - const auto alternate_walls = settings.get("material_alternate_walls"); + const auto pack_by_inset = ! settings_.get("optimize_wall_printing_order"); + const auto inset_direction = settings_.get("inset_direction"); + const auto alternate_walls = settings_.get("material_alternate_walls"); const bool outer_to_inner = inset_direction == InsetDirection::OUTSIDE_IN; - const bool use_one_extruder = wall_0_extruder_nr == wall_x_extruder_nr; - const bool current_extruder_is_wall_x = wall_x_extruder_nr == extruder_nr; + const bool use_one_extruder = wall_0_extruder_nr_ == wall_x_extruder_nr_; + const bool current_extruder_is_wall_x = wall_x_extruder_nr_ == extruder_nr_; const bool reverse = shouldReversePath(use_one_extruder, current_extruder_is_wall_x, outer_to_inner); auto walls_to_be_added = getWallsToBeAdded(reverse, use_one_extruder); @@ -93,11 +93,11 @@ bool InsetOrderOptimizer::addToLayer() constexpr bool detect_loops = false; constexpr Polygons* combing_boundary = nullptr; - const auto group_outer_walls = settings.get("group_outer_walls"); + const auto group_outer_walls = settings_.get("group_outer_walls"); // When we alternate walls, also alternate the direction at which the first wall starts in. // On even layers we start with normal direction, on odd layers with inverted direction. PathOrderOptimizer - order_optimizer(gcode_layer.getLastPlannedPositionOrStartingPosition(), z_seam_config, detect_loops, combing_boundary, reverse, order, group_outer_walls); + order_optimizer(gcode_layer_.getLastPlannedPositionOrStartingPosition(), z_seam_config_, detect_loops, combing_boundary, reverse, order, group_outer_walls); for (const auto& line : walls_to_be_added) { @@ -120,19 +120,19 @@ bool InsetOrderOptimizer::addToLayer() const bool is_outer_wall = path.vertices_->inset_idx == 0; // or thin wall 'gap filler' const bool is_gap_filler = path.vertices_->is_odd; - const GCodePathConfig& non_bridge_config = is_outer_wall ? inset_0_non_bridge_config : inset_X_non_bridge_config; - const GCodePathConfig& bridge_config = is_outer_wall ? inset_0_bridge_config : inset_X_bridge_config; - const coord_t wipe_dist = is_outer_wall && ! is_gap_filler ? wall_0_wipe_dist : wall_x_wipe_dist; - const bool retract_before = is_outer_wall ? retract_before_outer_wall : false; + const GCodePathConfig& non_bridge_config = is_outer_wall ? inset_0_non_bridge_config_ : inset_X_non_bridge_config_; + const GCodePathConfig& bridge_config = is_outer_wall ? inset_0_bridge_config_ : inset_X_bridge_config_; + const coord_t wipe_dist = is_outer_wall && ! is_gap_filler ? wall_0_wipe_dist_ : wall_x_wipe_dist_; + const bool retract_before = is_outer_wall ? retract_before_outer_wall_ : false; const bool revert_inset = alternate_walls && (path.vertices_->inset_idx % 2); - const bool revert_layer = alternate_walls && (layer_nr % 2); + const bool revert_layer = alternate_walls && (layer_nr_ % 2); const bool backwards = path.backwards_ != (revert_inset != revert_layer); const size_t start_index = (backwards != path.backwards_) ? path.vertices_->size() - (path.start_vertex_ + 1) : path.start_vertex_; const bool linked_path = ! path.is_closed_; - gcode_layer.setIsInside(true); // Going to print walls, which are always inside. - gcode_layer.addWall(*path.vertices_, start_index, settings, non_bridge_config, bridge_config, wipe_dist, flow, retract_before, path.is_closed_, backwards, linked_path); + gcode_layer_.setIsInside(true); // Going to print walls, which are always inside. + gcode_layer_.addWall(*path.vertices_, start_index, settings_, non_bridge_config, bridge_config, wipe_dist, flow, retract_before, path.is_closed_, backwards, linked_path); added_something = true; } return added_something; @@ -357,7 +357,7 @@ constexpr bool InsetOrderOptimizer::shouldReversePath(const bool use_one_extrude std::vector InsetOrderOptimizer::getWallsToBeAdded(const bool reverse, const bool use_one_extruder) { - if (paths.empty()) + if (paths_.empty()) { return {}; } @@ -366,22 +366,22 @@ std::vector InsetOrderOptimizer::getWallsToBeAdded(const bool rev { if (use_one_extruder) { - view = paths | rv::reverse; + view = paths_ | rv::reverse; } else { - view = paths | rv::reverse | rv::drop_last(1); + view = paths_ | rv::reverse | rv::drop_last(1); } } else { if (use_one_extruder) { - view = paths | rv::all; + view = paths_ | rv::all; } else { - view = paths | rv::take_exactly(1); + view = paths_ | rv::take_exactly(1); } } return view | rv::join | rv::remove_if(rg::empty) | rg::to_vector; diff --git a/src/infill/SierpinskiFill.cpp b/src/infill/SierpinskiFill.cpp index d6b45fc86f..623f9ab9af 100644 --- a/src/infill/SierpinskiFill.cpp +++ b/src/infill/SierpinskiFill.cpp @@ -45,10 +45,10 @@ SierpinskiFill::SierpinskiFill(const DensityProvider& density_provider, const AA spdlog::error( "Node is subdivided without the appropriate value! value_error: {} from base {} el: {} er: {}, while the realized_length = {}", node->getValueError(), - node->requested_length, - node->error_left, - node->error_right, - node->realized_length); + node->requested_length_, + node->error_left_, + node->error_right_, + node->realized_length_); assert(false); } } @@ -86,14 +86,14 @@ void SierpinskiFill::createTree() void SierpinskiFill::createTree(SierpinskiTriangle& sub_root) { - if (sub_root.depth < max_depth) // We need to subdivide. + if (sub_root.depth_ < max_depth) // We need to subdivide. { SierpinskiTriangle& t = sub_root; - Point middle = (t.a + t.b) / 2; + Point middle = (t.a_ + t.b_) / 2; // At each subdivision we divide the triangle in two. // Figure out which sort of triangle each child will be: SierpinskiTriangle::SierpinskiDirection first_dir, second_dir; - switch (t.dir) + switch (t.dir_) { default: case SierpinskiTriangle::SierpinskiDirection::AB_TO_BC: @@ -109,8 +109,8 @@ void SierpinskiFill::createTree(SierpinskiTriangle& sub_root) second_dir = SierpinskiTriangle::SierpinskiDirection::AC_TO_AB; break; } - sub_root.children.emplace_back(middle, t.a, t.straight_corner, first_dir, ! t.straight_corner_is_left, t.depth + 1); - sub_root.children.emplace_back(middle, t.straight_corner, t.b, second_dir, ! t.straight_corner_is_left, t.depth + 1); + sub_root.children.emplace_back(middle, t.a_, t.straight_corner_, first_dir, ! t.straight_corner_is_left_, t.depth_ + 1); + sub_root.children.emplace_back(middle, t.straight_corner_, t.b_, second_dir, ! t.straight_corner_is_left_, t.depth_ + 1); for (SierpinskiTriangle& child : t.children) { createTree(child); @@ -119,12 +119,12 @@ void SierpinskiFill::createTree(SierpinskiTriangle& sub_root) } void SierpinskiFill::createTreeStatistics(SierpinskiTriangle& triangle) { - Point ac = triangle.straight_corner - triangle.a; + Point ac = triangle.straight_corner_ - triangle.a_; float area = 0.5 * INT2MM2(vSize2(ac)); float short_length = .5 * vSizeMM(ac); - float long_length = .5 * vSizeMM(triangle.b - triangle.a); - triangle.area = area; - triangle.realized_length = (triangle.dir == SierpinskiTriangle::SierpinskiDirection::AC_TO_BC) ? long_length : short_length; + float long_length = .5 * vSizeMM(triangle.b_ - triangle.a_); + triangle.area_ = area; + triangle.realized_length_ = (triangle.dir_ == SierpinskiTriangle::SierpinskiDirection::AC_TO_BC) ? long_length : short_length; for (SierpinskiTriangle& child : triangle.children) { createTreeStatistics(child); @@ -137,12 +137,12 @@ void SierpinskiFill::createTreeRequestedLengths(SierpinskiTriangle& triangle) if (triangle.children.empty()) { // set requested_length of leaves AABB triangle_aabb; - triangle_aabb.include(triangle.a); - triangle_aabb.include(triangle.b); - triangle_aabb.include(triangle.straight_corner); + triangle_aabb.include(triangle.a_); + triangle_aabb.include(triangle.b_); + triangle_aabb.include(triangle.straight_corner_); AABB3D triangle_aabb3d(Point3(triangle_aabb.min.X, triangle_aabb.min.Y, 0), Point3(triangle_aabb.max.X, triangle_aabb.max.Y, 1)); float density = density_provider(triangle_aabb3d); // The density of the square around the triangle is a rough estimate of the density of the triangle. - triangle.requested_length = density * triangle.area / INT2MM(line_width); + triangle.requested_length_ = density * triangle.area_ / INT2MM(line_width); } else { // bubble total up requested_length and total_child_realized_length @@ -150,8 +150,8 @@ void SierpinskiFill::createTreeRequestedLengths(SierpinskiTriangle& triangle) { createTreeRequestedLengths(child); - triangle.requested_length += child.requested_length; - triangle.total_child_realized_length += child.realized_length; + triangle.requested_length_ += child.requested_length_; + triangle.total_child_realized_length_ += child.realized_length_; } } } @@ -191,7 +191,7 @@ std::vector::iterator for (std::list::iterator it = sequence.begin(); it != sequence.end(); ++it) { SierpinskiTriangle* node = *it; - depth_ordered[node->depth].emplace_back(it); + depth_ordered[node->depth_].emplace_back(it); } return depth_ordered; } @@ -212,14 +212,14 @@ bool SierpinskiFill::subdivideAll() // so then the range will be two long rather than one. std::list::iterator begin = it; std::list::iterator end = std::next(it); - if (triangle.dir == SierpinskiTriangle::SierpinskiDirection::AC_TO_AB && end != sequence.end()) + if (triangle.dir_ == SierpinskiTriangle::SierpinskiDirection::AC_TO_AB && end != sequence.end()) { continue; // don't subdivide these two triangles just yet, wait till next iteration } - if (triangle.dir == SierpinskiTriangle::SierpinskiDirection::AB_TO_BC && begin != sequence.begin()) + if (triangle.dir_ == SierpinskiTriangle::SierpinskiDirection::AB_TO_BC && begin != sequence.begin()) { begin = std::prev(it); - assert((*begin)->depth == triangle.depth || isConstrainedBackward(it)); + assert((*begin)->depth_ == triangle.depth_ || isConstrainedBackward(it)); } else { @@ -229,7 +229,7 @@ bool SierpinskiFill::subdivideAll() // Don't check for constraining in between the cells in the range; // the range is defined as the range of triangles which are constraining each other simultaneously. - if (node->depth == max_depth) // Never subdivide beyond maximum depth. + if (node->depth_ == max_depth) // Never subdivide beyond maximum depth. continue; float total_subdiv_error = getSubdivisionError(begin, end); if (! node->children.empty() && total_subdiv_error >= 0 && ! is_constrained) @@ -275,14 +275,14 @@ bool SierpinskiFill::bubbleUpConstraintErrors() if (is_constrained_forward) { SierpinskiTriangle* next = *std::next(it); - node->error_right -= unresolvable_error; - next->error_left += unresolvable_error; + node->error_right_ -= unresolvable_error; + next->error_left_ += unresolvable_error; } if (is_constrained_backward) { SierpinskiTriangle* prev = *std::prev(it); - node->error_left -= unresolvable_error; - prev->error_right += unresolvable_error; + node->error_left_ -= unresolvable_error; + prev->error_right_ += unresolvable_error; } if (std::abs(unresolvable_error) > allowed_length_error) { @@ -309,8 +309,8 @@ std::list::iterator SierpinskiTriangle* first = *begin; SierpinskiTriangle* last = *std::prev(end); - (*begin)->children.front().error_left += first->error_left; - (*std::prev(end))->children.back().error_right += last->error_right; + (*begin)->children.front().error_left_ += first->error_left_; + (*std::prev(end))->children.back().error_right_ += last->error_right_; } if (redistribute_errors && deep_debug_checking) debugCheck(false); @@ -358,18 +358,18 @@ void SierpinskiFill::redistributeLeftoverErrors(std::list:: { SierpinskiTriangle* node = *it; SierpinskiTriangle* next = *std::next(it); - if (std::abs(node->error_right + next->error_left) > allowed_length_error) + if (std::abs(node->error_right_ + next->error_left_) > allowed_length_error) { - spdlog::warn("Nodes aren't balanced! er: {} next el: {}", node->error_right, next->error_left); + spdlog::warn("Nodes aren't balanced! er: {} next el: {}", node->error_right_, next->error_left_); assert(false); } - float exchange = node->error_right; - if (node->error_right < next->error_left) + float exchange = node->error_right_; + if (node->error_right_ < next->error_left_) { exchange *= -1; } - node->error_right -= exchange; - next->error_left += exchange; + node->error_right_ -= exchange; + next->error_left_ += exchange; } float total_superfluous_error = 0; @@ -387,30 +387,30 @@ void SierpinskiFill::redistributeLeftoverErrors(std::list:: } return; } - if (begin != sequence.begin() && end != sequence.end() && first->error_left > allowed_length_error && last->error_right > allowed_length_error) + if (begin != sequence.begin() && end != sequence.end() && first->error_left_ > allowed_length_error && last->error_right_ > allowed_length_error) { - float total_error_input = first->error_left + last->error_right; + float total_error_input = first->error_left_ + last->error_right_; total_superfluous_error = std::min(total_superfluous_error, total_error_input); // total superfluous error cannot be more than the influx of error - float left_spillover = total_superfluous_error * first->error_left / total_error_input; - float right_spillover = total_superfluous_error * last->error_right / total_error_input; - (*begin)->error_left -= left_spillover; - prev->error_right += left_spillover; - (*std::prev(end))->error_right -= right_spillover; - next->error_left += right_spillover; + float left_spillover = total_superfluous_error * first->error_left_ / total_error_input; + float right_spillover = total_superfluous_error * last->error_right_ / total_error_input; + (*begin)->error_left_ -= left_spillover; + prev->error_right_ += left_spillover; + (*std::prev(end))->error_right_ -= right_spillover; + next->error_left_ += right_spillover; } - else if (begin != sequence.begin() && first->error_left > allowed_length_error) + else if (begin != sequence.begin() && first->error_left_ > allowed_length_error) { - total_superfluous_error = std::min(total_superfluous_error, first->error_left); // total superfluous error cannot be more than the influx of error - (*begin)->error_left -= total_superfluous_error; - prev->error_right += total_superfluous_error; - assert(first->error_left > -allowed_length_error); + total_superfluous_error = std::min(total_superfluous_error, first->error_left_); // total superfluous error cannot be more than the influx of error + (*begin)->error_left_ -= total_superfluous_error; + prev->error_right_ += total_superfluous_error; + assert(first->error_left_ > -allowed_length_error); } - else if (end != sequence.end() && last->error_right > allowed_length_error) + else if (end != sequence.end() && last->error_right_ > allowed_length_error) { - total_superfluous_error = std::min(total_superfluous_error, last->error_right); // total superfluous error cannot be more than the influx of error - last->error_right -= total_superfluous_error; - next->error_left += total_superfluous_error; - assert(last->error_right > -allowed_length_error); + total_superfluous_error = std::min(total_superfluous_error, last->error_right_); // total superfluous error cannot be more than the influx of error + last->error_right_ -= total_superfluous_error; + next->error_left_ += total_superfluous_error; + assert(last->error_right_ > -allowed_length_error); } } @@ -505,9 +505,9 @@ void SierpinskiFill::balanceErrors(std::listerror_left -= energy; + nodes[node_idx]->error_left_ -= energy; energy += node_error_compensation[node_idx]; - nodes[node_idx]->error_right += energy; + nodes[node_idx]->error_right_ += energy; } assert(energy < allowed_length_error); } @@ -536,23 +536,23 @@ void SierpinskiFill::diffuseError() { SierpinskiTriangle& triangle = *(*it); - float boundary = (triangle.realized_length + triangle.total_child_realized_length) * .5f; + float boundary = (triangle.realized_length_ + triangle.total_child_realized_length_) * .5f; - float nodal_value = ((use_errors_in_dithering) ? triangle.getErroredValue() : triangle.requested_length); + float nodal_value = ((use_errors_in_dithering) ? triangle.getErroredValue() : triangle.requested_length_); float boundary_error = nodal_value - boundary + error; std::list::iterator begin = it; std::list::iterator end = std::next(it); - if (triangle.dir == SierpinskiTriangle::SierpinskiDirection::AC_TO_AB && end != sequence.end()) + if (triangle.dir_ == SierpinskiTriangle::SierpinskiDirection::AC_TO_AB && end != sequence.end()) { pair_constrained_nodes++; continue; // don't subdivide these two triangles just yet, wait till next iteration } - if (triangle.dir == SierpinskiTriangle::SierpinskiDirection::AB_TO_BC && begin != sequence.begin()) + if (triangle.dir_ == SierpinskiTriangle::SierpinskiDirection::AB_TO_BC && begin != sequence.begin()) { begin = std::prev(it); - assert((*begin)->depth == triangle.depth || isConstrainedBackward(it)); + assert((*begin)->depth_ == triangle.depth_ || isConstrainedBackward(it)); } @@ -573,12 +573,12 @@ void SierpinskiFill::diffuseError() subdivided_nodes++; it = subdivide(begin, end, false); if (dithering) - error += nodal_value - triangle.total_child_realized_length; + error += nodal_value - triangle.total_child_realized_length_; } else { if (dithering) - error += nodal_value - triangle.realized_length; + error += nodal_value - triangle.realized_length_; } } spdlog::debug( @@ -593,7 +593,7 @@ bool SierpinskiFill::isConstrainedBackward(std::list::itera { SierpinskiTriangle* node = *it; SierpinskiTriangle* prev = *std::prev(it); - if (it != sequence.begin() && node->dir == SierpinskiTriangle::SierpinskiDirection::AB_TO_BC && prev->depth < node->depth) + if (it != sequence.begin() && node->dir_ == SierpinskiTriangle::SierpinskiDirection::AB_TO_BC && prev->depth_ < node->depth_) return true; return false; } @@ -601,7 +601,7 @@ bool SierpinskiFill::isConstrainedForward(std::list::iterat { SierpinskiTriangle* node = *it; SierpinskiTriangle* next = *std::next(it); - if (std::next(it) != sequence.end() && node->dir == SierpinskiTriangle::SierpinskiDirection::AC_TO_AB && next->depth < node->depth) + if (std::next(it) != sequence.end() && node->dir_ == SierpinskiTriangle::SierpinskiDirection::AC_TO_AB && next->depth_ < node->depth_) return true; return false; } @@ -626,9 +626,9 @@ void SierpinskiFill::debugOutput(SVG& svg) for (SierpinskiTriangle* node : sequence) { SierpinskiTriangle& triangle = *node; - svg.writeLine(triangle.a, triangle.b, SVG::Color::GRAY); - svg.writeLine(triangle.a, triangle.straight_corner, SVG::Color::GRAY); - svg.writeLine(triangle.b, triangle.straight_corner, SVG::Color::GRAY); + svg.writeLine(triangle.a_, triangle.b_, SVG::Color::GRAY); + svg.writeLine(triangle.a_, triangle.straight_corner_, SVG::Color::GRAY); + svg.writeLine(triangle.b_, triangle.straight_corner_, SVG::Color::GRAY); } } @@ -636,19 +636,19 @@ void SierpinskiFill::debugOutput(SVG& svg) SierpinskiFill::Edge SierpinskiFill::SierpinskiTriangle::getFromEdge() { Edge ret; - switch (dir) + switch (dir_) { case SierpinskiDirection::AB_TO_BC: - ret = Edge{ a, b }; + ret = Edge{ a_, b_ }; break; case SierpinskiDirection::AC_TO_AB: - ret = Edge{ straight_corner, a }; + ret = Edge{ straight_corner_, a_ }; break; case SierpinskiDirection::AC_TO_BC: - ret = Edge{ straight_corner, a }; + ret = Edge{ straight_corner_, a_ }; break; } - if (! straight_corner_is_left) + if (! straight_corner_is_left_) { std::swap(ret.l, ret.r); } @@ -658,19 +658,19 @@ SierpinskiFill::Edge SierpinskiFill::SierpinskiTriangle::getFromEdge() SierpinskiFill::Edge SierpinskiFill::SierpinskiTriangle::getToEdge() { Edge ret; - switch (dir) + switch (dir_) { case SierpinskiDirection::AB_TO_BC: - ret = Edge{ straight_corner, b }; + ret = Edge{ straight_corner_, b_ }; break; case SierpinskiDirection::AC_TO_AB: - ret = Edge{ b, a }; + ret = Edge{ b_, a_ }; break; case SierpinskiDirection::AC_TO_BC: - ret = Edge{ straight_corner, b }; + ret = Edge{ straight_corner_, b_ }; break; } - if (! straight_corner_is_left) + if (! straight_corner_is_left_) { std::swap(ret.l, ret.r); } @@ -679,22 +679,22 @@ SierpinskiFill::Edge SierpinskiFill::SierpinskiTriangle::getToEdge() float SierpinskiFill::SierpinskiTriangle::getTotalError() { - return error_left + error_right; + return error_left_ + error_right_; } float SierpinskiFill::SierpinskiTriangle::getErroredValue() { - return requested_length + getTotalError(); + return requested_length_ + getTotalError(); } float SierpinskiFill::SierpinskiTriangle::getSubdivisionError() { - return getErroredValue() - total_child_realized_length; + return getErroredValue() - total_child_realized_length_; } float SierpinskiFill::SierpinskiTriangle::getValueError() { - return getErroredValue() - realized_length; + return getErroredValue() - realized_length_; } @@ -705,24 +705,24 @@ Polygon SierpinskiFill::generateCross() const for (SierpinskiTriangle* max_level_it : sequence) { SierpinskiTriangle& triangle = *max_level_it; - Point edge_middle = triangle.a + triangle.b + triangle.straight_corner; - switch (triangle.dir) + Point edge_middle = triangle.a_ + triangle.b_ + triangle.straight_corner_; + switch (triangle.dir_) { case SierpinskiTriangle::SierpinskiDirection::AB_TO_BC: - edge_middle -= triangle.a; + edge_middle -= triangle.a_; break; case SierpinskiTriangle::SierpinskiDirection::AC_TO_AB: - edge_middle -= triangle.straight_corner; + edge_middle -= triangle.straight_corner_; break; case SierpinskiTriangle::SierpinskiDirection::AC_TO_BC: - edge_middle -= triangle.a; + edge_middle -= triangle.a_; break; } ret.add(edge_middle / 2); } float realized_length = INT2MM(ret.polygonLength()); - float requested_length = root.requested_length; + float requested_length = root.requested_length_; float error = (realized_length - requested_length) / requested_length; spdlog::debug("realized_length: {}, requested_length: {} :: {}% error", realized_length, requested_length, .01 * static_cast(10000 * error)); return ret; @@ -758,13 +758,13 @@ Polygon SierpinskiFill::generateCross(coord_t z, coord_t min_dist_to_side, coord Cross pattern because the other side is sliding along the straight sides. The steeper overhang is then only in the corner, which is deemed acceptable since the corners are never too sharp. */ - const coord_t period = vSize(triangle.straight_corner - triangle.a); + const coord_t period = vSize(triangle.straight_corner_ - triangle.a_); ret.add(get_edge_crossing_location(period, triangle.getFromEdge())); last_triangle = ▵ } assert(last_triangle); - const coord_t period = vSize(last_triangle->straight_corner - last_triangle->a); + const coord_t period = vSize(last_triangle->straight_corner_ - last_triangle->a_); ret.add(get_edge_crossing_location(period, last_triangle->getToEdge())); if (pocket_size > 10) @@ -813,12 +813,12 @@ Polygon SierpinskiFill::generateCross(coord_t z, coord_t min_dist_to_side, coord void SierpinskiFill::debugCheck(bool check_subdivision) { - if (std::abs(sequence.front()->error_left) > allowed_length_error) + if (std::abs(sequence.front()->error_left_) > allowed_length_error) { spdlog::warn("First node has error left!"); assert(false); } - if (std::abs(sequence.back()->error_right) > allowed_length_error) + if (std::abs(sequence.back()->error_right_) > allowed_length_error) { spdlog::warn("Last node has error right!"); assert(false); @@ -833,9 +833,9 @@ void SierpinskiFill::debugCheck(bool check_subdivision) SierpinskiTriangle* node = *it; SierpinskiTriangle* next = *std::next(it); - if (std::abs(node->error_right + next->error_left) > allowed_length_error) + if (std::abs(node->error_right_ + next->error_left_) > allowed_length_error) { - spdlog::warn("Consecutive nodes in fractal don't have the same error! er: {} , nel: {}", node->error_right, next->error_left); + spdlog::warn("Consecutive nodes in fractal don't have the same error! er: {} , nel: {}", node->error_right_, next->error_left_); assert(false); } if (check_subdivision && node->getValueError() < -allowed_length_error) From 434d51b8b1b6acd6b6ad2fc95c88f191ca00805d Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Tue, 21 Nov 2023 11:46:51 +0100 Subject: [PATCH 16/48] Fixed variable shadowing warnings --- include/SupportInfillPart.h | 20 +++++----- include/infill/UniformDensityProvider.h | 6 +-- include/progress/ProgressEstimatorLinear.h | 8 ++-- include/settings/FlowTempGraph.h | 12 +++--- src/FffGcodeWriter.cpp | 24 ++++++------ src/PathOrderPath.cpp | 2 +- src/SkirtBrim.cpp | 4 +- src/SupportInfillPart.cpp | 14 +++---- src/TreeSupport.cpp | 2 +- src/settings/FlowTempGraph.cpp | 22 +++++------ src/settings/Settings.cpp | 2 +- src/sliceDataStorage.cpp | 10 ++--- src/support.cpp | 44 +++++++++++----------- 13 files changed, 85 insertions(+), 85 deletions(-) diff --git a/include/SupportInfillPart.h b/include/SupportInfillPart.h index 1767847cb7..9131165d3a 100644 --- a/include/SupportInfillPart.h +++ b/include/SupportInfillPart.h @@ -25,16 +25,16 @@ namespace cura class SupportInfillPart { public: - PolygonsPart outline; //!< The outline of the support infill area - AABB outline_boundary_box; //!< The boundary box for the infill area - coord_t support_line_width; //!< The support line width - int inset_count_to_generate; //!< The number of insets need to be generated from the outline. This is not the actual insets that will be generated. - std::vector> infill_area_per_combine_per_density; //!< a list of separated sub-areas which requires different infill densities and combined thicknesses - // for infill_areas[x][n], x means the density level and n means the thickness - std::vector wall_toolpaths; //!< Any walls go here, not in the areas, where they could be combined vertically (don't combine walls). Binned by inset_idx. + PolygonsPart outline_; //!< The outline of the support infill area + AABB outline_boundary_box_; //!< The boundary box for the infill area + coord_t support_line_width_; //!< The support line width + int inset_count_to_generate_; //!< The number of insets need to be generated from the outline. This is not the actual insets that will be generated. + std::vector> infill_area_per_combine_per_density_; //!< a list of separated sub-areas which requires different infill densities and combined thicknesses + // for infill_areas[x][n], x means the density level and n means the thickness + std::vector wall_toolpaths_; //!< Any walls go here, not in the areas, where they could be combined vertically (don't combine walls). Binned by inset_idx. - coord_t custom_line_distance; - bool use_fractional_config; //!< Request to use the configuration used to fill a partial layer height here, instead of the normal full layer height configuration. + coord_t custom_line_distance_; + bool use_fractional_config_; //!< Request to use the configuration used to fill a partial layer height here, instead of the normal full layer height configuration. SupportInfillPart(const PolygonsPart& outline, coord_t support_line_width, bool use_fractional_config, int inset_count_to_generate = 0, coord_t custom_line_distance = 0); @@ -44,7 +44,7 @@ class SupportInfillPart inline const Polygons& SupportInfillPart::getInfillArea() const { // if there is no wall, we use the original outline as the infill area - return outline; + return outline_; } } // namespace cura diff --git a/include/infill/UniformDensityProvider.h b/include/infill/UniformDensityProvider.h index 3dd2cd8f8f..be8c70e277 100644 --- a/include/infill/UniformDensityProvider.h +++ b/include/infill/UniformDensityProvider.h @@ -15,7 +15,7 @@ class UniformDensityProvider : public DensityProvider { public: UniformDensityProvider(float density) - : density(density) + : density_(density) { }; @@ -25,10 +25,10 @@ class UniformDensityProvider : public DensityProvider virtual float operator()(const AABB3D&) const { - return density; + return density_; }; protected: - float density; + float density_; }; } // namespace cura diff --git a/include/progress/ProgressEstimatorLinear.h b/include/progress/ProgressEstimatorLinear.h index 78c2b1c17d..178338a560 100644 --- a/include/progress/ProgressEstimatorLinear.h +++ b/include/progress/ProgressEstimatorLinear.h @@ -14,18 +14,18 @@ namespace cura class ProgressEstimatorLinear : public ProgressEstimator { - unsigned int total_steps; + unsigned int total_steps_; public: ProgressEstimatorLinear(unsigned int total_steps) - : total_steps(total_steps) + : total_steps_(total_steps) { } double progress(int current_step) { - return double(current_step) / double(total_steps); + return double(current_step) / double(total_steps_); } }; } // namespace cura -#endif // PROGRESS_PROGRESS_ESTIMATOR_LINEAR_H \ No newline at end of file +#endif // PROGRESS_PROGRESS_ESTIMATOR_LINEAR_H diff --git a/include/settings/FlowTempGraph.h b/include/settings/FlowTempGraph.h index c232579d41..3cb26e91dd 100644 --- a/include/settings/FlowTempGraph.h +++ b/include/settings/FlowTempGraph.h @@ -21,15 +21,15 @@ class FlowTempGraph public: struct Datum { - const double flow; //!< The flow in mm^3/s - const Temperature temp; //!< The temperature in *C + const double flow_; //!< The flow in mm^3/s + const Temperature temp_; //!< The temperature in *C Datum(const double flow, const Temperature temp) - : flow(flow) - , temp(temp) + : flow_(flow) + , temp_(temp) {} }; - std::vector data; //!< The points of the graph between which the graph is linearly interpolated + std::vector data_; //!< The points of the graph between which the graph is linearly interpolated /*! * Get the temperature corresponding to a specific flow. @@ -46,4 +46,4 @@ class FlowTempGraph } // namespace cura -#endif // FLOW_TEMP_GRAPH \ No newline at end of file +#endif // FLOW_TEMP_GRAPH diff --git a/src/FffGcodeWriter.cpp b/src/FffGcodeWriter.cpp index 52aa1cd876..46103204ae 100644 --- a/src/FffGcodeWriter.cpp +++ b/src/FffGcodeWriter.cpp @@ -3216,7 +3216,7 @@ bool FffGcodeWriter::processSupportInfill(const SliceDataStorage& storage, Layer PathOrderOptimizer island_order_optimizer(gcode_layer.getLastPlannedPositionOrStartingPosition()); for (const SupportInfillPart& part : support_layer.support_infill_parts) { - (part.use_fractional_config ? island_order_optimizer_initial : island_order_optimizer).addPolygon(&part); + (part.use_fractional_config_ ? island_order_optimizer_initial : island_order_optimizer).addPolygon(&part); } island_order_optimizer_initial.optimize(); island_order_optimizer.optimize(); @@ -3234,13 +3234,13 @@ bool FffGcodeWriter::processSupportInfill(const SliceDataStorage& storage, Layer for (const PathOrdering& path : ranges::views::concat(island_order_optimizer_initial.paths_, island_order_optimizer.paths_)) { const SupportInfillPart& part = *path.vertices_; - const auto& configs = part.use_fractional_config ? gcode_layer.configs_storage.support_fractional_infill_config : gcode_layer.configs_storage.support_infill_config; + const auto& configs = part.use_fractional_config_ ? gcode_layer.configs_storage.support_fractional_infill_config : gcode_layer.configs_storage.support_infill_config; // always process the wall overlap if walls are generated - const int current_support_infill_overlap = (part.inset_count_to_generate > 0) ? default_support_infill_overlap : 0; + const int current_support_infill_overlap = (part.inset_count_to_generate_ > 0) ? default_support_infill_overlap : 0; // The support infill walls were generated separately, first. Always add them, regardless of how many densities we have. - std::vector wall_toolpaths = part.wall_toolpaths; + std::vector wall_toolpaths = part.wall_toolpaths_; if (! wall_toolpaths.empty()) { @@ -3268,37 +3268,37 @@ bool FffGcodeWriter::processSupportInfill(const SliceDataStorage& storage, Layer added_something |= wall_orderer.addToLayer(); } - if ((default_support_line_distance <= 0 && support_structure != ESupportStructure::TREE) || part.infill_area_per_combine_per_density.empty()) + if ((default_support_line_distance <= 0 && support_structure != ESupportStructure::TREE) || part.infill_area_per_combine_per_density_.empty()) { continue; } - for (unsigned int combine_idx = 0; combine_idx < part.infill_area_per_combine_per_density[0].size(); ++combine_idx) + for (unsigned int combine_idx = 0; combine_idx < part.infill_area_per_combine_per_density_[0].size(); ++combine_idx) { const coord_t support_line_width = default_support_line_width * (combine_idx + 1); Polygons support_polygons; std::vector wall_toolpaths_here; Polygons support_lines; - const size_t max_density_idx = part.infill_area_per_combine_per_density.size() - 1; + const size_t max_density_idx = part.infill_area_per_combine_per_density_.size() - 1; for (size_t density_idx = max_density_idx; (density_idx + 1) > 0; --density_idx) { - if (combine_idx >= part.infill_area_per_combine_per_density[density_idx].size()) + if (combine_idx >= part.infill_area_per_combine_per_density_[density_idx].size()) { continue; } const unsigned int density_factor = 2 << density_idx; // == pow(2, density_idx + 1) int support_line_distance_here - = (part.custom_line_distance > 0 - ? part.custom_line_distance + = (part.custom_line_distance_ > 0 + ? part.custom_line_distance_ : default_support_line_distance * density_factor); // the highest density infill combines with the next to create a grid with density_factor 1 const int support_shift = support_line_distance_here / 2; - if (part.custom_line_distance == 0 && (density_idx == max_density_idx || support_pattern == EFillMethod::CROSS || support_pattern == EFillMethod::CROSS_3D)) + if (part.custom_line_distance_ == 0 && (density_idx == max_density_idx || support_pattern == EFillMethod::CROSS || support_pattern == EFillMethod::CROSS_3D)) { support_line_distance_here /= 2; } - const Polygons& area = Simplify(infill_extruder.settings_).polygon(part.infill_area_per_combine_per_density[density_idx][combine_idx]); + const Polygons& area = Simplify(infill_extruder.settings_).polygon(part.infill_area_per_combine_per_density_[density_idx][combine_idx]); constexpr size_t wall_count = 0; // Walls are generated somewhere else, so their layers aren't vertically combined. const coord_t small_area_width = 0; diff --git a/src/PathOrderPath.cpp b/src/PathOrderPath.cpp index 45039c98d4..7ee8e49d55 100644 --- a/src/PathOrderPath.cpp +++ b/src/PathOrderPath.cpp @@ -35,7 +35,7 @@ namespace cura template<> ConstPolygonRef PathOrdering::getVertexData() { - return vertices_->outline.outerPolygon(); + return vertices_->outline_.outerPolygon(); } template<> ConstPolygonRef PathOrdering::getVertexData() diff --git a/src/SkirtBrim.cpp b/src/SkirtBrim.cpp index cd2ed3e907..18da72094a 100644 --- a/src/SkirtBrim.cpp +++ b/src/SkirtBrim.cpp @@ -443,7 +443,7 @@ Polygons SkirtBrim::getFirstLayerOutline(const int extruder_nr /* = -1 */) } for (const SupportInfillPart& support_infill_part : support_layer.support_infill_parts) { - first_layer_outline.add(support_infill_part.outline); + first_layer_outline.add(support_infill_part.outline_); } first_layer_outline.add(support_layer.support_bottom); first_layer_outline.add(support_layer.support_roof); @@ -608,7 +608,7 @@ void SkirtBrim::generateSupportBrim() Polygons support_outline; for (SupportInfillPart& part : support_layer.support_infill_parts) { - support_outline.add(part.outline); + support_outline.add(part.outline_); } const Polygons brim_area = support_outline.difference(support_outline.offset(-brim_width)); support_layer.excludeAreasFromSupportInfillAreas(brim_area, AABB(brim_area)); diff --git a/src/SupportInfillPart.cpp b/src/SupportInfillPart.cpp index ae0b8cf7c1..fb504f5fb5 100644 --- a/src/SupportInfillPart.cpp +++ b/src/SupportInfillPart.cpp @@ -9,12 +9,12 @@ using namespace cura; SupportInfillPart::SupportInfillPart(const PolygonsPart& outline, coord_t support_line_width, bool use_fractional_config, int inset_count_to_generate, coord_t custom_line_distance) - : outline(outline) - , outline_boundary_box(outline) - , support_line_width(support_line_width) - , inset_count_to_generate(inset_count_to_generate) - , custom_line_distance(custom_line_distance) - , use_fractional_config(use_fractional_config) + : outline_(outline) + , outline_boundary_box_(outline) + , support_line_width_(support_line_width) + , inset_count_to_generate_(inset_count_to_generate) + , custom_line_distance_(custom_line_distance) + , use_fractional_config_(use_fractional_config) { - infill_area_per_combine_per_density.clear(); + infill_area_per_combine_per_density_.clear(); } diff --git a/src/TreeSupport.cpp b/src/TreeSupport.cpp index 958a08f9fb..fe2cc87e77 100644 --- a/src/TreeSupport.cpp +++ b/src/TreeSupport.cpp @@ -139,7 +139,7 @@ void TreeSupport::generateSupportAreas(SliceDataStorage& storage) exlude_at_layer.add(storage.support.supportLayers[layer_idx].support_roof); for (auto part : storage.support.supportLayers[layer_idx].support_infill_parts) { - exlude_at_layer.add(part.outline); + exlude_at_layer.add(part.outline_); } exclude[layer_idx] = exlude_at_layer.unionPolygons(); scripta::log("tree_support_exclude", exclude[layer_idx], SectionType::SUPPORT, layer_idx); diff --git a/src/settings/FlowTempGraph.cpp b/src/settings/FlowTempGraph.cpp index 700b9cbdf3..88fcb82cb2 100644 --- a/src/settings/FlowTempGraph.cpp +++ b/src/settings/FlowTempGraph.cpp @@ -10,32 +10,32 @@ namespace cura double FlowTempGraph::getTemp(const double flow, const Temperature material_print_temperature, const bool flow_dependent_temperature) const { - if (! flow_dependent_temperature || data.size() == 0) + if (! flow_dependent_temperature || data_.size() == 0) { return material_print_temperature; } - if (data.size() == 1) + if (data_.size() == 1) { - return data.front().temp; + return data_.front().temp_; } - if (flow < data.front().flow) + if (flow < data_.front().flow_) { spdlog::warn("Warning! Flow too low!"); - return data.front().temp; + return data_.front().temp_; } - const Datum* last_datum = &data.front(); - for (unsigned int datum_idx = 1; datum_idx < data.size(); datum_idx++) + const Datum* last_datum = &data_.front(); + for (unsigned int datum_idx = 1; datum_idx < data_.size(); datum_idx++) { - const Datum& datum = data[datum_idx]; - if (datum.flow >= flow) + const Datum& datum = data_[datum_idx]; + if (datum.flow_ >= flow) { - return last_datum->temp + Temperature((datum.temp - last_datum->temp) * (flow - last_datum->flow) / (datum.flow - last_datum->flow)); + return last_datum->temp_ + Temperature((datum.temp_ - last_datum->temp_) * (flow - last_datum->flow_) / (datum.flow_ - last_datum->flow_)); } last_datum = &datum; } spdlog::warn("Warning! Flow too high!"); - return data.back().temp; + return data_.back().temp_; } } // namespace cura diff --git a/src/settings/Settings.cpp b/src/settings/Settings.cpp index ffc89a274b..c5e5bb0286 100644 --- a/src/settings/Settings.cpp +++ b/src/settings/Settings.cpp @@ -245,7 +245,7 @@ FlowTempGraph Settings::get(const std::string& key) const { double first = std::stod(first_substring); double second = std::stod(second_substring); - result.data.emplace_back(first, second); + result.data_.emplace_back(first, second); } catch (const std::invalid_argument& e) { diff --git a/src/sliceDataStorage.cpp b/src/sliceDataStorage.cpp index 37453a303c..27f0266c69 100644 --- a/src/sliceDataStorage.cpp +++ b/src/sliceDataStorage.cpp @@ -322,7 +322,7 @@ Polygons { for (const SupportInfillPart& support_infill_part : support_layer.support_infill_parts) { - total.add(support_infill_part.outline); + total.add(support_infill_part.outline_); } total.add(support_layer.support_bottom); total.add(support_layer.support_roof); @@ -667,12 +667,12 @@ void SupportLayer::excludeAreasFromSupportInfillAreas(const Polygons& exclude_po SupportInfillPart& support_infill_part = support_infill_parts[part_idx]; // if the areas don't overlap, do nothing - if (! exclude_polygons_boundary_box.hit(support_infill_part.outline_boundary_box)) + if (! exclude_polygons_boundary_box.hit(support_infill_part.outline_boundary_box_)) { continue; } - Polygons result_polygons = support_infill_part.outline.difference(exclude_polygons); + Polygons result_polygons = support_infill_part.outline_.difference(exclude_polygons); // if no smaller parts get generated, this mean this part should be removed. if (result_polygons.empty()) @@ -692,12 +692,12 @@ void SupportLayer::excludeAreasFromSupportInfillAreas(const Polygons& exclude_po // there are one or more smaller parts. // we first replace the current part with one of the smaller parts, // the rest we add to the support_infill_parts (but after part_count_to_check) - support_infill_part.outline = smaller_support_islands[0]; + support_infill_part.outline_ = smaller_support_islands[0]; for (size_t support_island_idx = 1; support_island_idx < smaller_support_islands.size(); ++support_island_idx) { const PolygonsPart& smaller_island = smaller_support_islands[support_island_idx]; - support_infill_parts.emplace_back(smaller_island, support_infill_part.support_line_width, support_infill_part.inset_count_to_generate); + support_infill_parts.emplace_back(smaller_island, support_infill_part.support_line_width_, support_infill_part.inset_count_to_generate_); } } diff --git a/src/support.cpp b/src/support.cpp index bfbd4ab8f9..234ff27dbd 100644 --- a/src/support.cpp +++ b/src/support.cpp @@ -223,15 +223,15 @@ void AreaSupport::generateGradualSupport(SliceDataStorage& storage) } // NOTE: This both generates the walls _and_ returns the _actual_ infill area (the one _without_ walls) for use in the rest of the method. const Polygons infill_area = Infill::generateWallToolPaths( - support_infill_part.wall_toolpaths, + support_infill_part.wall_toolpaths_, original_area, - support_infill_part.inset_count_to_generate, + support_infill_part.inset_count_to_generate_, wall_width, 0, infill_extruder.settings_, layer_nr, SectionType::SUPPORT); - const AABB& this_part_boundary_box = support_infill_part.outline_boundary_box; + const AABB& this_part_boundary_box = support_infill_part.outline_boundary_box_; // calculate density areas for this island Polygons less_dense_support = infill_area; // one step less dense with each density_step @@ -253,13 +253,13 @@ void AreaSupport::generateGradualSupport(SliceDataStorage& storage) Polygons relevant_upper_polygons; for (unsigned int upper_part_idx = 0; upper_part_idx < upper_infill_parts.size(); ++upper_part_idx) { - if (support_infill_part.outline.empty()) + if (support_infill_part.outline_.empty()) { continue; } // we compute intersection based on support infill areas - const AABB& upper_part_boundary_box = upper_infill_parts[upper_part_idx].outline_boundary_box; + const AABB& upper_part_boundary_box = upper_infill_parts[upper_part_idx].outline_boundary_box_; // // Here we are comparing the **outlines** of the infill areas // @@ -278,7 +278,7 @@ void AreaSupport::generateGradualSupport(SliceDataStorage& storage) // if (upper_part_boundary_box.hit(this_part_boundary_box)) { - relevant_upper_polygons.add(upper_infill_parts[upper_part_idx].outline); + relevant_upper_polygons.add(upper_infill_parts[upper_part_idx].outline_); } } @@ -290,21 +290,21 @@ void AreaSupport::generateGradualSupport(SliceDataStorage& storage) } // add new infill_area_per_combine_per_density for the current density - support_infill_part.infill_area_per_combine_per_density.emplace_back(); - std::vector& support_area_current_density = support_infill_part.infill_area_per_combine_per_density.back(); + support_infill_part.infill_area_per_combine_per_density_.emplace_back(); + std::vector& support_area_current_density = support_infill_part.infill_area_per_combine_per_density_.back(); const Polygons more_dense_support = infill_area.difference(less_dense_support); support_area_current_density.push_back(more_dense_support); } - support_infill_part.infill_area_per_combine_per_density.emplace_back(); - std::vector& support_area_current_density = support_infill_part.infill_area_per_combine_per_density.back(); + support_infill_part.infill_area_per_combine_per_density_.emplace_back(); + std::vector& support_area_current_density = support_infill_part.infill_area_per_combine_per_density_.back(); support_area_current_density.push_back(infill_area); - assert(support_infill_part.infill_area_per_combine_per_density.size() != 0 && "support_infill_part.infill_area_per_combine_per_density should now be initialized"); + assert(support_infill_part.infill_area_per_combine_per_density_.size() != 0 && "support_infill_part.infill_area_per_combine_per_density should now be initialized"); #ifdef DEBUG - for (unsigned int part_i = 0; part_i < support_infill_part.infill_area_per_combine_per_density.size(); ++part_i) + for (unsigned int part_i = 0; part_i < support_infill_part.infill_area_per_combine_per_density_.size(); ++part_i) { - assert(support_infill_part.infill_area_per_combine_per_density[part_i].size() != 0); + assert(support_infill_part.infill_area_per_combine_per_density_[part_i].size() != 0); } #endif // DEBUG } @@ -364,13 +364,13 @@ void AreaSupport::combineSupportInfillLayers(SliceDataStorage& storage) { continue; } - for (unsigned int density_idx = 0; density_idx < part.infill_area_per_combine_per_density.size(); ++density_idx) + for (unsigned int density_idx = 0; density_idx < part.infill_area_per_combine_per_density_.size(); ++density_idx) { // go over each density of gradual infill (these density areas overlap!) - std::vector& infill_area_per_combine = part.infill_area_per_combine_per_density[density_idx]; + std::vector& infill_area_per_combine = part.infill_area_per_combine_per_density_[density_idx]; Polygons result; for (SupportInfillPart& lower_layer_part : lower_layer.support_infill_parts) { - if (! part.outline_boundary_box.hit(lower_layer_part.outline_boundary_box)) + if (! part.outline_boundary_box_.hit(lower_layer_part.outline_boundary_box_)) { continue; } @@ -389,20 +389,20 @@ void AreaSupport::combineSupportInfillLayers(SliceDataStorage& storage) // Generally: remove only from *same density* areas on layer below // If there are no same density areas, then it's ok to print them anyway // Don't remove other density areas - if (density_idx == part.infill_area_per_combine_per_density.size() - 1) + if (density_idx == part.infill_area_per_combine_per_density_.size() - 1) { // For the most dense areas on a given layer the density of that area is doubled. // This means that - if the lower layer has more densities - // all those lower density lines are included in the most dense of this layer. // We therefore compare the most dense are on this layer with all densities // of the lower layer with the same or higher density index - max_lower_density_idx = lower_layer_part.infill_area_per_combine_per_density.size() - 1; + max_lower_density_idx = lower_layer_part.infill_area_per_combine_per_density_.size() - 1; } for (unsigned int lower_density_idx = density_idx; - lower_density_idx <= max_lower_density_idx && lower_density_idx < lower_layer_part.infill_area_per_combine_per_density.size(); + lower_density_idx <= max_lower_density_idx && lower_density_idx < lower_layer_part.infill_area_per_combine_per_density_.size(); lower_density_idx++) { - std::vector& lower_infill_area_per_combine = lower_layer_part.infill_area_per_combine_per_density[lower_density_idx]; + std::vector& lower_infill_area_per_combine = lower_layer_part.infill_area_per_combine_per_density_[lower_density_idx]; lower_infill_area_per_combine[0] = lower_infill_area_per_combine[0].difference(intersection); // remove thickened area from lower (single thickness) layer } @@ -425,13 +425,13 @@ void AreaSupport::cleanup(SliceDataStorage& storage) { SupportInfillPart& part = layer.support_infill_parts[part_idx]; bool can_be_removed = true; - if (part.inset_count_to_generate > 0) + if (part.inset_count_to_generate_ > 0) { can_be_removed = false; } else { - for (const std::vector& infill_area_per_combine_this_density : part.infill_area_per_combine_per_density) + for (const std::vector& infill_area_per_combine_this_density : part.infill_area_per_combine_per_density_) { for (const Polygons& infill_area_this_combine_this_density : infill_area_per_combine_this_density) { From 39098a21b23615d8c9e85d3630394be53a9b8200 Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Tue, 21 Nov 2023 12:06:25 +0100 Subject: [PATCH 17/48] Fixed variable shadowing warnings --- include/SkeletalTrapezoidationEdge.h | 52 ++--- include/SkeletalTrapezoidationJoint.h | 36 ++-- include/utils/PolygonConnector.h | 126 +++++------ src/SkeletalTrapezoidation.cpp | 293 +++++++++++++------------- src/SkeletalTrapezoidationGraph.cpp | 34 +-- src/utils/PolygonConnector.cpp | 12 +- tests/utils/PolygonConnectorTest.cpp | 28 +-- 7 files changed, 291 insertions(+), 290 deletions(-) diff --git a/include/SkeletalTrapezoidationEdge.h b/include/SkeletalTrapezoidationEdge.h index 60f464deb5..75b0c06b73 100644 --- a/include/SkeletalTrapezoidationEdge.h +++ b/include/SkeletalTrapezoidationEdge.h @@ -29,13 +29,13 @@ class SkeletalTrapezoidationEdge */ struct TransitionMiddle { - coord_t pos; // Position along edge as measure from edge.from.p - int lower_bead_count; - coord_t feature_radius; // The feature radius at which this transition is placed + coord_t pos_; // Position along edge as measure from edge.from.p + int lower_bead_count_; + coord_t feature_radius_; // The feature radius at which this transition is placed TransitionMiddle(coord_t pos, int lower_bead_count, coord_t feature_radius) - : pos(pos) - , lower_bead_count(lower_bead_count) - , feature_radius(feature_radius) + : pos_(pos) + , lower_bead_count_(lower_bead_count) + , feature_radius_(feature_radius) { } }; @@ -45,13 +45,13 @@ class SkeletalTrapezoidationEdge */ struct TransitionEnd { - coord_t pos; // Position along edge as measure from edge.from.p, where the edge is always the half edge oriented from lower to higher R - int lower_bead_count; - bool is_lower_end; // Whether this is the ed of the transition with lower bead count + coord_t pos_; // Position along edge as measure from edge.from.p, where the edge is always the half edge oriented from lower to higher R + int lower_bead_count_; + bool is_lower_end_; // Whether this is the ed of the transition with lower bead count TransitionEnd(coord_t pos, int lower_bead_count, bool is_lower_end) - : pos(pos) - , lower_bead_count(lower_bead_count) - , is_lower_end(is_lower_end) + : pos_(pos) + , lower_bead_count_(lower_bead_count) + , is_lower_end_(is_lower_end) { } }; @@ -62,14 +62,14 @@ class SkeletalTrapezoidationEdge EXTRA_VD = 1, // introduced to voronoi diagram in order to make the gMAT TRANSITION_END = 2 // introduced to voronoi diagram in order to make the gMAT }; - EdgeType type; + EdgeType type_; SkeletalTrapezoidationEdge() : SkeletalTrapezoidationEdge(EdgeType::NORMAL) { } SkeletalTrapezoidationEdge(const EdgeType& type) - : type(type) + : type_(type) , is_central(Central::UNKNOWN) { } @@ -90,49 +90,49 @@ class SkeletalTrapezoidationEdge bool hasTransitions(bool ignore_empty = false) const { - return transitions.use_count() > 0 && (ignore_empty || ! transitions.lock()->empty()); + return transitions_.use_count() > 0 && (ignore_empty || ! transitions_.lock()->empty()); } void setTransitions(std::shared_ptr>& storage) { - transitions = storage; + transitions_ = storage; } std::shared_ptr> getTransitions() { - return transitions.lock(); + return transitions_.lock(); } bool hasTransitionEnds(bool ignore_empty = false) const { - return transition_ends.use_count() > 0 && (ignore_empty || ! transition_ends.lock()->empty()); + return transition_ends_.use_count() > 0 && (ignore_empty || ! transition_ends_.lock()->empty()); } void setTransitionEnds(std::shared_ptr>& storage) { - transition_ends = storage; + transition_ends_ = storage; } std::shared_ptr> getTransitionEnds() { - return transition_ends.lock(); + return transition_ends_.lock(); } bool hasExtrusionJunctions(bool ignore_empty = false) const { - return extrusion_junctions.use_count() > 0 && (ignore_empty || ! extrusion_junctions.lock()->empty()); + return extrusion_junctions_.use_count() > 0 && (ignore_empty || ! extrusion_junctions_.lock()->empty()); } void setExtrusionJunctions(std::shared_ptr& storage) { - extrusion_junctions = storage; + extrusion_junctions_ = storage; } std::shared_ptr getExtrusionJunctions() { - return extrusion_junctions.lock(); + return extrusion_junctions_.lock(); } Central is_central; //! whether the edge is significant; whether the source segments have a sharp angle; -1 is unknown private: - std::weak_ptr> transitions; - std::weak_ptr> transition_ends; - std::weak_ptr extrusion_junctions; + std::weak_ptr> transitions_; + std::weak_ptr> transition_ends_; + std::weak_ptr extrusion_junctions_; }; diff --git a/include/SkeletalTrapezoidationJoint.h b/include/SkeletalTrapezoidationJoint.h index e8c5ad42a7..fc27526f1f 100644 --- a/include/SkeletalTrapezoidationJoint.h +++ b/include/SkeletalTrapezoidationJoint.h @@ -19,45 +19,45 @@ class SkeletalTrapezoidationJoint public: struct BeadingPropagation { - Beading beading; - coord_t dist_to_bottom_source; - coord_t dist_from_top_source; - bool is_upward_propagated_only; + Beading beading_; + coord_t dist_to_bottom_source_; + coord_t dist_from_top_source_; + bool is_upward_propagated_only_; BeadingPropagation(const Beading& beading) - : beading(beading) - , dist_to_bottom_source(0) - , dist_from_top_source(0) - , is_upward_propagated_only(false) + : beading_(beading) + , dist_to_bottom_source_(0) + , dist_from_top_source_(0) + , is_upward_propagated_only_(false) { } }; - coord_t distance_to_boundary; - coord_t bead_count; - float transition_ratio; //! The distance near the skeleton to leave free because this joint is in the middle of a transition, as a fraction of the inner bead width of the bead + coord_t distance_to_boundary_; + coord_t bead_count_; + float transition_ratio_; //! The distance near the skeleton to leave free because this joint is in the middle of a transition, as a fraction of the inner bead width of the bead //! at the higher transition. SkeletalTrapezoidationJoint() - : distance_to_boundary(-1) - , bead_count(-1) - , transition_ratio(0) + : distance_to_boundary_(-1) + , bead_count_(-1) + , transition_ratio_(0) { } bool hasBeading() const { - return beading.use_count() > 0; + return beading_.use_count() > 0; } void setBeading(std::shared_ptr& storage) { - beading = storage; + beading_ = storage; } std::shared_ptr getBeading() { - return beading.lock(); + return beading_.lock(); } private: - std::weak_ptr beading; + std::weak_ptr beading_; }; } // namespace cura diff --git a/include/utils/PolygonConnector.h b/include/utils/PolygonConnector.h index d29961ca00..b4d050a78d 100644 --- a/include/utils/PolygonConnector.h +++ b/include/utils/PolygonConnector.h @@ -101,11 +101,11 @@ class PolygonConnector void connect(Polygons& output_polygons, std::vector& output_paths); protected: - coord_t line_width; //!< The distance between the line segments which connect two polygons. - std::vector input_polygons; //!< The polygons assembled by calls to \ref PolygonConnector::add. - std::vector input_paths; //!< The paths assembled by calls to \ref PolygonConnector::add. + coord_t line_width_; //!< The distance between the line segments which connect two polygons. + std::vector input_polygons_; //!< The polygons assembled by calls to \ref PolygonConnector::add. + std::vector input_paths_; //!< The paths assembled by calls to \ref PolygonConnector::add. - constexpr static Ratio max_gap = 0.5; //!< The maximum allowed gap between lines that get connected, in multiples of the local line width. Allows connections inside corners where the endpoints are slightly apart. + constexpr static Ratio max_gap_ = 0.5; //!< The maximum allowed gap between lines that get connected, in multiples of the local line width. Allows connections inside corners where the endpoints are slightly apart. /*! * Line segment to connect two polygons, with all the necessary information @@ -121,36 +121,36 @@ class PolygonConnector /*! * The polygon at the source of the connection. */ - Polygonal* from_poly; + Polygonal* from_poly_; /*! * The index of the line segment at the source of the connection. * * This line segment is the one after the vertex with the same index. */ - size_t from_segment; + size_t from_segment_; /*! * The precise location of the source of the connection. */ - Point from_point; + Point from_point_; /*! * The polygon at the destination of the connection. */ - Polygonal* to_poly; + Polygonal* to_poly_; /*! * The index of the line segment at the destination of the connection. * * This line segment is the one after the vertex with the same index. */ - size_t to_segment; + size_t to_segment_; /*! * The precise location of the destination of the connection. */ - Point to_point; + Point to_point_; /*! * Create a new connection. @@ -166,12 +166,12 @@ class PolygonConnector * connection. */ PolygonConnection(Polygonal* from_poly, const size_t from_segment, const Point from_point, Polygonal* to_poly, const size_t to_segment, const Point to_point) - : from_poly(from_poly) - , from_segment(from_segment) - , from_point(from_point) - , to_poly(to_poly) - , to_segment(to_segment) - , to_point(to_point) + : from_poly_(from_poly) + , from_segment_(from_segment) + , from_point_(from_point) + , to_poly_(to_poly) + , to_segment_(to_segment) + , to_point_(to_point) { } @@ -183,7 +183,7 @@ class PolygonConnector */ coord_t getDistance2() const { - return vSize2(from_point - to_point); + return vSize2(from_point_ - to_point_); } }; @@ -201,10 +201,10 @@ class PolygonConnector template struct PolygonBridge { - PolygonConnection a; //!< first connection - PolygonConnection b; //!< second connection + PolygonConnection a_; //!< first connection + PolygonConnection b_; //!< second connection PolygonBridge(const PolygonConnection& a, const PolygonConnection& b) - : a(a), b(b) + : a_(a), b_(b) {} }; @@ -240,7 +240,7 @@ class PolygonConnector std::optional> bridge = getBridge(current, to_connect); if(bridge) { - connectPolygonsAlongBridge(*bridge, *bridge->a.to_poly); //Connect the polygons, and store the result in the to_poly. + connectPolygonsAlongBridge(*bridge, *bridge->a_.to_poly_); //Connect the polygons, and store the result in the to_poly. //Don't store the current polygon. It has just been merged into the other one. } else //Can't connect this to anything. Leave it as-is. @@ -371,9 +371,9 @@ class PolygonConnector template coord_t getSpace(const PolygonConnection& connection) const { - const coord_t from_width = interpolateWidth(connection.from_point, (*connection.from_poly)[connection.from_segment], (*connection.from_poly)[(connection.from_segment + 1) % connection.from_poly->size()]); - const coord_t to_width = interpolateWidth(connection.to_point, (*connection.to_poly)[connection.to_segment], (*connection.to_poly)[(connection.to_segment + 1) % connection.to_poly->size()]); - return vSize(connection.to_point - connection.from_point) - from_width / 2 - to_width / 2; + const coord_t from_width = interpolateWidth(connection.from_point_, (*connection.from_poly_)[connection.from_segment_], (*connection.from_poly_)[(connection.from_segment_ + 1) % connection.from_poly_->size()]); + const coord_t to_width = interpolateWidth(connection.to_point_, (*connection.to_poly_)[connection.to_segment_], (*connection.to_poly_)[(connection.to_segment_ + 1) % connection.to_poly_->size()]); + return vSize(connection.to_point_ - connection.from_point_) - from_width / 2 - to_width / 2; } /*! @@ -406,7 +406,7 @@ class PolygonConnector std::optional> findConnection(Polygonal& from_poly, std::vector& to_polygons) { //Optimise for finding the best connection. - coord_t best_distance = line_width * max_gap; //Allow up to the max_gap. + coord_t best_distance = line_width_ * max_gap_; //Allow up to the max_gap. std::optional> best_connection; std::optional> best_second_connection; @@ -435,7 +435,7 @@ class PolygonConnector //Try a naive distance first. Faster to compute, but it may estimate the distance too small. coord_t naive_dist = LinearAlg2D::getDistFromLine(from_pos1, to_pos1, to_pos2); - if(naive_dist - from_width1 - smallest_to_width < line_width * max_gap) + if(naive_dist - from_width1 - smallest_to_width < line_width_ * max_gap_) { const Point closest_point = LinearAlg2D::getClosestOnLineSegment(from_pos1, to_pos1, to_pos2); if(closest_point == to_pos2) //The last endpoint of a vertex is considered to be part of the next segment. Let that one handle it. @@ -459,7 +459,7 @@ class PolygonConnector //Also try the other way around: From the line segment of the from_poly to a vertex in the to_polygons. naive_dist = LinearAlg2D::getDistFromLine(to_pos1, from_pos1, from_pos2); - if(naive_dist - smallest_from_width - to_width1 < line_width * max_gap) + if(naive_dist - smallest_from_width - to_width1 < line_width_ * max_gap_) { const Point closest_point = LinearAlg2D::getClosestOnLineSegment(to_pos1, from_pos1, from_pos2); if(closest_point == from_pos2) //The last endpoint of a vertex is considered to be part of the next segment. Let that one handle it. @@ -518,9 +518,9 @@ class PolygonConnector } //Ensure that B is always the right connection and A the left. - if(LinearAlg2D::pointIsLeftOfLine(connection->b.from_point, connection->a.from_point, connection->a.to_point) > 0) + if(LinearAlg2D::pointIsLeftOfLine(connection->b_.from_point_, connection->a_.from_point_, connection->a_.to_point_) > 0) { - std::swap(connection->a, connection->b); + std::swap(connection->a_, connection->b_); } return connection; } @@ -609,10 +609,10 @@ class PolygonConnector coord_t best_connection_length = std::numeric_limits::max(); //Find the four intersections, on both sides of the initial connection, and on both polygons. - std::optional> from_forward_intersection = walkUntilDistanceFromLine(*first.from_poly, first.from_segment, adjacent_distance, first.from_point, first.to_point, +1); - std::optional> from_backward_intersection = walkUntilDistanceFromLine(*first.from_poly, first.from_segment, adjacent_distance, first.from_point, first.to_point, -1); - std::optional> to_forward_intersection = walkUntilDistanceFromLine(*first.to_poly, first.to_segment, adjacent_distance, first.from_point, first.to_point, +1); - std::optional> to_backward_intersection = walkUntilDistanceFromLine(*first.to_poly, first.to_segment, adjacent_distance, first.from_point, first.to_point, -1); + std::optional> from_forward_intersection = walkUntilDistanceFromLine(*first.from_poly_, first.from_segment_, adjacent_distance, first.from_point_, first.to_point_, +1); + std::optional> from_backward_intersection = walkUntilDistanceFromLine(*first.from_poly_, first.from_segment_, adjacent_distance, first.from_point_, first.to_point_, -1); + std::optional> to_forward_intersection = walkUntilDistanceFromLine(*first.to_poly_, first.to_segment_, adjacent_distance, first.from_point_, first.to_point_, +1); + std::optional> to_backward_intersection = walkUntilDistanceFromLine(*first.to_poly_, first.to_segment_, adjacent_distance, first.from_point_, first.to_point_, -1); for(const std::optional>& from_intersection : {from_forward_intersection, from_backward_intersection}) { @@ -621,21 +621,21 @@ class PolygonConnector continue; } //Find the shortest of the connections in the to_poly. - const bool original_side = LinearAlg2D::pointIsLeftOfLine(first.to_point, first.from_point, from_intersection->first) > 0; + const bool original_side = LinearAlg2D::pointIsLeftOfLine(first.to_point_, first.from_point_, from_intersection->first) > 0; for(const std::optional>& to_intersection : {to_forward_intersection, to_backward_intersection}) { if(!to_intersection) { continue; } - const bool current_side = LinearAlg2D::pointIsLeftOfLine(to_intersection->first, first.from_point, from_intersection->first) > 0; + const bool current_side = LinearAlg2D::pointIsLeftOfLine(to_intersection->first, first.from_point_, from_intersection->first) > 0; if (original_side != current_side) { continue; } - PolygonConnection connection(first.from_poly, from_intersection->second, from_intersection->first, first.to_poly, to_intersection->second, to_intersection->first); + PolygonConnection connection(first.from_poly_, from_intersection->second, from_intersection->first, first.to_poly_, to_intersection->second, to_intersection->first); const coord_t connection_length = getSpace(connection); - if(connection_length < max_gap * line_width && connection_length < best_connection_length) //Connection is allowed. + if(connection_length < max_gap_ * line_width_ && connection_length < best_connection_length) //Connection is allowed. { result = connection; best_connection_length = connection_length; @@ -661,72 +661,72 @@ class PolygonConnector Polygonal ret = createEmpty(); //Create a temporary result that we'll move into the result. - const size_t from_size = bridge.b.from_poly->size(); + const size_t from_size = bridge.b_.from_poly_->size(); //Add the from-endpoint of B. - const coord_t b_from_width = interpolateWidth(bridge.b.from_point, (*bridge.b.from_poly)[bridge.b.from_segment], (*bridge.b.from_poly)[(bridge.b.from_segment + 1) % from_size]); - addVertex(ret, bridge.b.from_point, b_from_width); + const coord_t b_from_width = interpolateWidth(bridge.b_.from_point_, (*bridge.b_.from_poly_)[bridge.b_.from_segment_], (*bridge.b_.from_poly_)[(bridge.b_.from_segment_ + 1) % from_size]); + addVertex(ret, bridge.b_.from_point_, b_from_width); //Add the from-polygonal from B to A. short forwards; - if(bridge.a.from_segment == bridge.b.from_segment) //If we start and end on the same segment, iterate in the direction from A to B. + if(bridge.a_.from_segment_ == bridge.b_.from_segment_) //If we start and end on the same segment, iterate in the direction from A to B. { - const Point vertex = getPosition((*bridge.b.from_poly)[bridge.b.from_segment]); //Same vertex for A and B. - const Point next_vertex = getPosition((*bridge.b.from_poly)[(bridge.b.from_segment + 1) % from_size]); + const Point vertex = getPosition((*bridge.b_.from_poly_)[bridge.b_.from_segment_]); //Same vertex for A and B. + const Point next_vertex = getPosition((*bridge.b_.from_poly_)[(bridge.b_.from_segment_ + 1) % from_size]); const Point direction = next_vertex - vertex; //Direction we'd go into when forward iterating. - const Point a_to_b = bridge.b.from_point - bridge.a.from_point; + const Point a_to_b = bridge.b_.from_point_ - bridge.a_.from_point_; forwards = vSize2(direction - a_to_b) < vSize2(-direction - a_to_b); } else { //If not the same segment, traverse in whichever direction is the long way around. - forwards = ((bridge.b.from_segment + from_size - bridge.a.from_segment) % from_size) < ((bridge.a.from_segment + from_size - bridge.b.from_segment) % from_size); + forwards = ((bridge.b_.from_segment_ + from_size - bridge.a_.from_segment_) % from_size) < ((bridge.a_.from_segment_ + from_size - bridge.b_.from_segment_) % from_size); } - size_t first_segment = forwards ? (bridge.b.from_segment + 1) % from_size : (bridge.b.from_segment + from_size) % from_size; - size_t last_segment = forwards ? bridge.a.from_segment : bridge.a.from_segment; + size_t first_segment = forwards ? (bridge.b_.from_segment_ + 1) % from_size : (bridge.b_.from_segment_ + from_size) % from_size; + size_t last_segment = forwards ? bridge.a_.from_segment_ : bridge.a_.from_segment_; if(first_segment == last_segment) last_segment = (last_segment + from_size - 2 * forwards + 1) % from_size; size_t i = first_segment; do //Since we might start and end on the same segment, do a do_while loop to iterate at least once. { - addVertex(ret, (*bridge.b.from_poly)[i]); + addVertex(ret, (*bridge.b_.from_poly_)[i]); i = (i + 2 * forwards - 1 + from_size) % from_size; } while(i != (last_segment + from_size + 2 * forwards - 1) % from_size); //Add the from-endpoint of A. - const coord_t a_from_width = interpolateWidth(bridge.a.from_point, (*bridge.b.from_poly)[bridge.a.from_segment], (*bridge.b.from_poly)[(bridge.a.from_segment + 1) % from_size]); - addVertex(ret, bridge.a.from_point, a_from_width); + const coord_t a_from_width = interpolateWidth(bridge.a_.from_point_, (*bridge.b_.from_poly_)[bridge.a_.from_segment_], (*bridge.b_.from_poly_)[(bridge.a_.from_segment_ + 1) % from_size]); + addVertex(ret, bridge.a_.from_point_, a_from_width); - const size_t to_size = bridge.b.to_poly->size(); + const size_t to_size = bridge.b_.to_poly_->size(); //Add the to-endpoint of A. - const coord_t a_to_width = interpolateWidth(bridge.a.to_point, (*bridge.a.to_poly)[bridge.a.to_segment], (*bridge.a.to_poly)[(bridge.a.to_segment + 1) % to_size]); - addVertex(ret, bridge.a.to_point, a_to_width); + const coord_t a_to_width = interpolateWidth(bridge.a_.to_point_, (*bridge.a_.to_poly_)[bridge.a_.to_segment_], (*bridge.a_.to_poly_)[(bridge.a_.to_segment_ + 1) % to_size]); + addVertex(ret, bridge.a_.to_point_, a_to_width); //Add the to_polygonal from A to B. - if(bridge.a.to_segment == bridge.b.to_segment) + if(bridge.a_.to_segment_ == bridge.b_.to_segment_) { - const Point vertex = getPosition((*bridge.b.to_poly)[bridge.b.to_segment]); //Same vertex for A and B. - const Point next_vertex = getPosition((*bridge.b.to_poly)[(bridge.b.to_segment + 1) % to_size]); + const Point vertex = getPosition((*bridge.b_.to_poly_)[bridge.b_.to_segment_]); //Same vertex for A and B. + const Point next_vertex = getPosition((*bridge.b_.to_poly_)[(bridge.b_.to_segment_ + 1) % to_size]); const Point direction = next_vertex - vertex; - const Point a_to_b = bridge.b.to_point - bridge.a.to_point; + const Point a_to_b = bridge.b_.to_point_ - bridge.a_.to_point_; forwards = vSize2(direction - a_to_b) > vSize2(-direction - a_to_b); } else { - forwards = ((bridge.a.to_segment + to_size - bridge.b.to_segment) % to_size) < ((bridge.b.to_segment + to_size - bridge.a.to_segment) % to_size); + forwards = ((bridge.a_.to_segment_ + to_size - bridge.b_.to_segment_) % to_size) < ((bridge.b_.to_segment_ + to_size - bridge.a_.to_segment_) % to_size); } - first_segment = forwards ? (bridge.a.to_segment + 1) % to_size : bridge.a.to_segment; - size_t end_segment = forwards ? (bridge.b.to_segment + 1) % to_size : bridge.b.to_segment; + first_segment = forwards ? (bridge.a_.to_segment_ + 1) % to_size : bridge.a_.to_segment_; + size_t end_segment = forwards ? (bridge.b_.to_segment_ + 1) % to_size : bridge.b_.to_segment_; i = first_segment; do { - addVertex(ret, (*bridge.b.to_poly)[i]); + addVertex(ret, (*bridge.b_.to_poly_)[i]); i = (i + 2 * forwards - 1 + to_size) % to_size; } while(i != end_segment); //Add the to-endpoint of B. - const coord_t b_to_width = interpolateWidth(bridge.b.to_point, (*bridge.b.to_poly)[bridge.b.to_segment], (*bridge.b.to_poly)[(bridge.b.to_segment + 1) % to_size]); - addVertex(ret, bridge.b.to_point, b_to_width); + const coord_t b_to_width = interpolateWidth(bridge.b_.to_point_, (*bridge.b_.to_poly_)[bridge.b_.to_segment_], (*bridge.b_.to_poly_)[(bridge.b_.to_segment_ + 1) % to_size]); + addVertex(ret, bridge.b_.to_point_, b_to_width); if(getPosition(ret.back()) != getPosition(ret.front())) { diff --git a/src/SkeletalTrapezoidation.cpp b/src/SkeletalTrapezoidation.cpp index 4f2eb2151d..dd4b69ccbd 100644 --- a/src/SkeletalTrapezoidation.cpp +++ b/src/SkeletalTrapezoidation.cpp @@ -3,21 +3,21 @@ #include "SkeletalTrapezoidation.h" -#include "BoostInterface.hpp" -#include "settings/types/Ratio.h" -#include "utils/VoronoiUtils.h" -#include "utils/linearAlg2D.h" -#include "utils/macros.h" - -#include -#include - #include #include #include #include #include +#include +#include + +#include "BoostInterface.hpp" +#include "settings/types/Ratio.h" +#include "utils/VoronoiUtils.h" +#include "utils/linearAlg2D.h" +#include "utils/macros.h" + #define SKELETAL_TRAPEZOIDATION_BEAD_SEARCH_MAX \ 1000 // A limit to how long it'll keep searching for adjacent beads. Increasing will re-use beadings more often (saving performance), but search longer for beading (costing // performance). @@ -458,7 +458,7 @@ void SkeletalTrapezoidation::constructFromPolygons(const Polygons& polys) points, segments); node_t* starting_node = vd_node_to_he_node[starting_vonoroi_edge->vertex0()]; - starting_node->data.distance_to_boundary = 0; + starting_node->data.distance_to_boundary_ = 0; constexpr bool is_next_to_start_or_end = true; graph.makeRib(prev_edge, start_source_point, end_source_point, is_next_to_start_or_end); @@ -473,7 +473,7 @@ void SkeletalTrapezoidation::constructFromPolygons(const Polygons& polys) } transferEdge(VoronoiUtils::p(ending_vonoroi_edge->vertex0()), end_source_point, *ending_vonoroi_edge, prev_edge, start_source_point, end_source_point, points, segments); - prev_edge->to->data.distance_to_boundary = 0; + prev_edge->to->data.distance_to_boundary_ = 0; } separatePointyQuadEndNodes(); @@ -730,11 +730,11 @@ void SkeletalTrapezoidation::updateIsCentral() { edge.data.setIsCentral(edge.twin->data.isCentral()); } - else if (edge.data.type == SkeletalTrapezoidationEdge::EdgeType::EXTRA_VD) + else if (edge.data.type_ == SkeletalTrapezoidationEdge::EdgeType::EXTRA_VD) { edge.data.setIsCentral(false); } - else if (std::max(edge.from->data.distance_to_boundary, edge.to->data.distance_to_boundary) < outer_edge_filter_length) + else if (std::max(edge.from->data.distance_to_boundary_, edge.to->data.distance_to_boundary_) < outer_edge_filter_length) { edge.data.setIsCentral(false); } @@ -743,7 +743,7 @@ void SkeletalTrapezoidation::updateIsCentral() Point a = edge.from->p; Point b = edge.to->p; Point ab = b - a; - coord_t dR = std::abs(edge.to->data.distance_to_boundary - edge.from->data.distance_to_boundary); + coord_t dR = std::abs(edge.to->data.distance_to_boundary_ - edge.from->data.distance_to_boundary_); coord_t dD = vSize(ab); edge.data.setIsCentral(dR < dD * cap); } @@ -805,7 +805,7 @@ void SkeletalTrapezoidation::updateBeadCount() { if (edge.data.isCentral()) { - edge.to->data.bead_count = beading_strategy.getOptimalBeadCount(edge.to->data.distance_to_boundary * 2); + edge.to->data.bead_count_ = beading_strategy.getOptimalBeadCount(edge.to->data.distance_to_boundary_ * 2); } } @@ -814,18 +814,18 @@ void SkeletalTrapezoidation::updateBeadCount() { if (node.isLocalMaximum()) { - if (node.data.distance_to_boundary < 0) + if (node.data.distance_to_boundary_ < 0) { spdlog::warn("Distance to boundary not yet computed for local maximum!"); - node.data.distance_to_boundary = std::numeric_limits::max(); + node.data.distance_to_boundary_ = std::numeric_limits::max(); edge_t* edge = node.incident_edge; do { - node.data.distance_to_boundary = std::min(node.data.distance_to_boundary, edge->to->data.distance_to_boundary + vSize(edge->from->p - edge->to->p)); + node.data.distance_to_boundary_ = std::min(node.data.distance_to_boundary_, edge->to->data.distance_to_boundary_ + vSize(edge->from->p - edge->to->p)); } while (edge = edge->twin->next, edge != node.incident_edge); } - coord_t bead_count = beading_strategy.getOptimalBeadCount(node.data.distance_to_boundary * 2); - node.data.bead_count = bead_count; + coord_t bead_count = beading_strategy.getOptimalBeadCount(node.data.distance_to_boundary_ * 2); + node.data.bead_count_ = bead_count; } } } @@ -838,24 +838,24 @@ void SkeletalTrapezoidation::filterNoncentralRegions() { continue; } - if (edge.to->data.bead_count < 0 && edge.to->data.distance_to_boundary != 0) + if (edge.to->data.bead_count_ < 0 && edge.to->data.distance_to_boundary_ != 0) { spdlog::warn("Encountered an uninitialized bead at the boundary!"); } - assert(edge.to->data.bead_count >= 0 || edge.to->data.distance_to_boundary == 0); + assert(edge.to->data.bead_count_ >= 0 || edge.to->data.distance_to_boundary_ == 0); constexpr coord_t max_dist = 400; - filterNoncentralRegions(&edge, edge.to->data.bead_count, 0, max_dist); + filterNoncentralRegions(&edge, edge.to->data.bead_count_, 0, max_dist); } } bool SkeletalTrapezoidation::filterNoncentralRegions(edge_t* to_edge, coord_t bead_count, coord_t traveled_dist, coord_t max_dist) { - coord_t r = to_edge->to->data.distance_to_boundary; + coord_t r = to_edge->to->data.distance_to_boundary_; edge_t* next_edge = to_edge->next; for (; next_edge && next_edge != to_edge->twin; next_edge = next_edge->twin->next) { - if (next_edge->to->data.distance_to_boundary >= r || shorterThen(next_edge->to->p - next_edge->from->p, 10)) + if (next_edge->to->data.distance_to_boundary_ >= r || shorterThen(next_edge->to->p - next_edge->from->p, 10)) { break; // Only walk upward } @@ -868,26 +868,26 @@ bool SkeletalTrapezoidation::filterNoncentralRegions(edge_t* to_edge, coord_t be const coord_t length = vSize(next_edge->to->p - next_edge->from->p); bool dissolve = false; - if (next_edge->to->data.bead_count == bead_count) + if (next_edge->to->data.bead_count_ == bead_count) { dissolve = true; } - else if (next_edge->to->data.bead_count < 0) + else if (next_edge->to->data.bead_count_ < 0) { dissolve = filterNoncentralRegions(next_edge, bead_count, traveled_dist + length, max_dist); } else // Upward bead count is different { // Dissolve if two central regions with different bead count are closer together than the max_dist (= transition distance) - dissolve = (traveled_dist + length < max_dist) && std::abs(next_edge->to->data.bead_count - bead_count) == 1; + dissolve = (traveled_dist + length < max_dist) && std::abs(next_edge->to->data.bead_count_ - bead_count) == 1; } if (dissolve) { next_edge->data.setIsCentral(true); next_edge->twin->data.setIsCentral(true); - next_edge->to->data.bead_count = beading_strategy.getOptimalBeadCount(next_edge->to->data.distance_to_boundary * 2); - next_edge->to->data.transition_ratio = 0; + next_edge->to->data.bead_count_ = beading_strategy.getOptimalBeadCount(next_edge->to->data.distance_to_boundary_ * 2); + next_edge->to->data.transition_ratio_ = 0; } return dissolve; // Dissolving only depend on the one edge going upward. There cannot be multiple edges going upward. } @@ -901,7 +901,7 @@ void SkeletalTrapezoidation::generateTransitioningRibs() for (edge_t& edge : graph.edges) { // Check if there is a transition in between nodes with different bead counts - if (edge.data.isCentral() && edge.from->data.bead_count != edge.to->data.bead_count) + if (edge.data.isCentral() && edge.from->data.bead_count_ != edge.to->data.bead_count_) { assert(edge.data.hasTransitions() || edge.twin->data.hasTransitions()); } @@ -926,17 +926,17 @@ void SkeletalTrapezoidation::generateTransitionMids(ptr_vector_tdata.distance_to_boundary; - coord_t end_R = edge.to->data.distance_to_boundary; - int start_bead_count = edge.from->data.bead_count; - int end_bead_count = edge.to->data.bead_count; + coord_t start_R = edge.from->data.distance_to_boundary_; + coord_t end_R = edge.to->data.distance_to_boundary_; + int start_bead_count = edge.from->data.bead_count_; + int end_bead_count = edge.to->data.bead_count_; if (start_R == end_R) { // No transitions occur when both end points have the same distance_to_boundary - assert(edge.from->data.bead_count == edge.to->data.bead_count); - if (edge.from->data.bead_count != edge.to->data.bead_count) + assert(edge.from->data.bead_count_ == edge.to->data.bead_count_); + if (edge.from->data.bead_count_ != edge.to->data.bead_count_) { - spdlog::warn("Bead count {} is different from {} even though distance to boundary is the same.", edge.from->data.bead_count, edge.to->data.bead_count); + spdlog::warn("Bead count {} is different from {} even though distance to boundary is the same.", edge.from->data.bead_count_, edge.to->data.bead_count_); } continue; } @@ -945,7 +945,7 @@ void SkeletalTrapezoidation::generateTransitionMids(ptr_vector_tdata.bead_count == edge.to->data.bead_count) + if (edge.from->data.bead_count_ == edge.to->data.bead_count_) { // No transitions should occur according to the enforced bead counts continue; } @@ -982,7 +982,7 @@ void SkeletalTrapezoidation::generateTransitionMids(ptr_vector_t= transitions->back().pos); + assert((! edge.data.hasTransitions(ignore_empty)) || mid_pos >= transitions->back().pos_); if (! edge.data.hasTransitions(ignore_empty)) { edge_transitions.emplace_back(std::make_shared>()); @@ -991,7 +991,7 @@ void SkeletalTrapezoidation::generateTransitionMids(ptr_vector_templace_back(mid_pos, transition_lower_bead_count, mid_R); } - assert((edge.from->data.bead_count == edge.to->data.bead_count) || edge.data.hasTransitions()); + assert((edge.from->data.bead_count_ == edge.to->data.bead_count_) || edge.data.hasTransitions()); } } @@ -1006,8 +1006,8 @@ void SkeletalTrapezoidation::filterTransitionMids() auto& transitions = *edge.data.getTransitions(); // This is how stuff should be stored in transitions - assert(transitions.front().lower_bead_count <= transitions.back().lower_bead_count); - assert(edge.from->data.distance_to_boundary <= edge.to->data.distance_to_boundary); + assert(transitions.front().lower_bead_count_ <= transitions.back().lower_bead_count_); + assert(edge.from->data.distance_to_boundary_ <= edge.to->data.distance_to_boundary_); const Point a = edge.from->p; const Point b = edge.to->p; @@ -1015,18 +1015,19 @@ void SkeletalTrapezoidation::filterTransitionMids() coord_t ab_size = vSize(ab); bool going_up = true; - std::list to_be_dissolved_back = dissolveNearbyTransitions(&edge, transitions.back(), ab_size - transitions.back().pos, transition_filter_dist, going_up); + std::list to_be_dissolved_back + = dissolveNearbyTransitions(&edge, transitions.back(), ab_size - transitions.back().pos_, transition_filter_dist, going_up); bool should_dissolve_back = ! to_be_dissolved_back.empty(); for (TransitionMidRef& ref : to_be_dissolved_back) { - dissolveBeadCountRegion(&edge, transitions.back().lower_bead_count + 1, transitions.back().lower_bead_count); + dissolveBeadCountRegion(&edge, transitions.back().lower_bead_count_ + 1, transitions.back().lower_bead_count_); ref.edge->data.getTransitions()->erase(ref.transition_it); } { - coord_t trans_bead_count = transitions.back().lower_bead_count; + coord_t trans_bead_count = transitions.back().lower_bead_count_; coord_t upper_transition_half_length = (1.0 - beading_strategy.getTransitionAnchorPos(trans_bead_count)) * beading_strategy.getTransitioningLength(trans_bead_count); - should_dissolve_back |= filterEndOfCentralTransition(&edge, ab_size - transitions.back().pos, upper_transition_half_length, trans_bead_count); + should_dissolve_back |= filterEndOfCentralTransition(&edge, ab_size - transitions.back().pos_, upper_transition_half_length, trans_bead_count); } if (should_dissolve_back) @@ -1039,18 +1040,18 @@ void SkeletalTrapezoidation::filterTransitionMids() } going_up = false; - std::list to_be_dissolved_front = dissolveNearbyTransitions(edge.twin, transitions.front(), transitions.front().pos, transition_filter_dist, going_up); + std::list to_be_dissolved_front = dissolveNearbyTransitions(edge.twin, transitions.front(), transitions.front().pos_, transition_filter_dist, going_up); bool should_dissolve_front = ! to_be_dissolved_front.empty(); for (TransitionMidRef& ref : to_be_dissolved_front) { - dissolveBeadCountRegion(edge.twin, transitions.front().lower_bead_count, transitions.front().lower_bead_count + 1); + dissolveBeadCountRegion(edge.twin, transitions.front().lower_bead_count_, transitions.front().lower_bead_count_ + 1); ref.edge->data.getTransitions()->erase(ref.transition_it); } { - coord_t trans_bead_count = transitions.front().lower_bead_count; + coord_t trans_bead_count = transitions.front().lower_bead_count_; coord_t lower_transition_half_length = beading_strategy.getTransitionAnchorPos(trans_bead_count) * beading_strategy.getTransitioningLength(trans_bead_count); - should_dissolve_front |= filterEndOfCentralTransition(edge.twin, transitions.front().pos, lower_transition_half_length, trans_bead_count + 1); + should_dissolve_front |= filterEndOfCentralTransition(edge.twin, transitions.front().pos_, lower_transition_half_length, trans_bead_count + 1); } if (should_dissolve_front) @@ -1088,9 +1089,9 @@ std::list edge_t* aligned_edge = is_aligned ? edge : edge->twin; bool seen_transition_on_this_edge = false; - const coord_t origin_radius = origin_transition.feature_radius; - const coord_t radius_here = edge->from->data.distance_to_boundary; - const bool dissolve_result_is_odd = bool(origin_transition.lower_bead_count % 2) == going_up; + const coord_t origin_radius = origin_transition.feature_radius_; + const coord_t radius_here = edge->from->data.distance_to_boundary_; + const bool dissolve_result_is_odd = bool(origin_transition.lower_bead_count_ % 2) == going_up; const coord_t width_deviation = std::abs(origin_radius - radius_here) * 2; // times by two because the deviation happens at both sides of the significant edge const coord_t line_width_deviation = dissolve_result_is_odd ? width_deviation @@ -1106,13 +1107,13 @@ std::list for (auto transition_it = transitions.begin(); transition_it != transitions.end(); ++transition_it) { // Note: this is not necessarily iterating in the traveling direction! // Check whether we should dissolve - coord_t pos = is_aligned ? transition_it->pos : ab_size - transition_it->pos; - if (traveled_dist + pos < max_dist && transition_it->lower_bead_count == origin_transition.lower_bead_count) // Only dissolve local optima + coord_t pos = is_aligned ? transition_it->pos_ : ab_size - transition_it->pos_; + if (traveled_dist + pos < max_dist && transition_it->lower_bead_count_ == origin_transition.lower_bead_count_) // Only dissolve local optima { - if (traveled_dist + pos < beading_strategy.getTransitioningLength(transition_it->lower_bead_count)) + if (traveled_dist + pos < beading_strategy.getTransitioningLength(transition_it->lower_bead_count_)) { // Consecutive transitions both in/decreasing in bead count should never be closer together than the transition distance - assert(going_up != is_aligned || transition_it->lower_bead_count == 0); + assert(going_up != is_aligned || transition_it->lower_bead_count_ == 0); } to_be_dissolved.emplace_back(aligned_edge, transition_it); seen_transition_on_this_edge = true; @@ -1145,12 +1146,12 @@ std::list void SkeletalTrapezoidation::dissolveBeadCountRegion(edge_t* edge_to_start, coord_t from_bead_count, coord_t to_bead_count) { assert(from_bead_count != to_bead_count); - if (edge_to_start->to->data.bead_count != from_bead_count) + if (edge_to_start->to->data.bead_count_ != from_bead_count) { return; } - edge_to_start->to->data.bead_count = to_bead_count; + edge_to_start->to->data.bead_count_ = to_bead_count; for (edge_t* edge = edge_to_start->next; edge && edge != edge_to_start->twin; edge = edge->twin->next) { if (! edge->data.isCentral()) @@ -1186,7 +1187,7 @@ bool SkeletalTrapezoidation::filterEndOfCentralTransition(edge_t* edge_to_start, if (should_dissolve) { - edge_to_start->to->data.bead_count = replacing_bead_count; + edge_to_start->to->data.bead_count_ = replacing_bead_count; } return should_dissolve; } @@ -1201,12 +1202,12 @@ void SkeletalTrapezoidation::generateAllTransitionEnds(ptr_vector_tdata.distance_to_boundary <= edge.to->data.distance_to_boundary); + assert(edge.from->data.distance_to_boundary_ <= edge.to->data.distance_to_boundary_); for (TransitionMiddle& transition_middle : transition_positions) { - assert(transition_positions.front().pos <= transition_middle.pos); - assert(transition_middle.pos <= transition_positions.back().pos); - generateTransitionEnds(edge, transition_middle.pos, transition_middle.lower_bead_count, edge_transition_ends); + assert(transition_positions.front().pos_ <= transition_middle.pos_); + assert(transition_middle.pos_ <= transition_positions.back().pos_); + generateTransitionEnds(edge, transition_middle.pos_, transition_middle.lower_bead_count_, edge_transition_ends); } } } @@ -1317,8 +1318,8 @@ bool SkeletalTrapezoidation::generateTransitionEnd( } if (! going_up || (has_recursed && ! is_only_going_down)) { - edge.to->data.transition_ratio = rest; - edge.to->data.bead_count = lower_bead_count; + edge.to->data.transition_ratio_ = rest; + edge.to->data.bead_count_ = lower_bead_count; } return is_only_going_down; } @@ -1350,7 +1351,7 @@ bool SkeletalTrapezoidation::generateTransitionEnd( // Add a transition to it (on the correct side). assert(ab_size == vSize(edge.twin->from->p - edge.twin->to->p)); assert(pos <= ab_size); - if (transitions->empty() || pos < transitions->front().pos) + if (transitions->empty() || pos < transitions->front().pos_) { // Preorder so that sorting later on is faster transitions->emplace_front(pos, lower_bead_count, is_lower_end); } @@ -1367,13 +1368,13 @@ bool SkeletalTrapezoidation::isGoingDown(edge_t* outgoing, coord_t traveled_dist { // NOTE: the logic below is not fully thought through. // TODO: take transition mids into account - if (outgoing->to->data.distance_to_boundary == 0) + if (outgoing->to->data.distance_to_boundary_ == 0) { return true; } - bool is_upward = outgoing->to->data.distance_to_boundary >= outgoing->from->data.distance_to_boundary; + bool is_upward = outgoing->to->data.distance_to_boundary_ >= outgoing->from->data.distance_to_boundary_; edge_t* upward_edge = is_upward ? outgoing : outgoing->twin; - if (outgoing->to->data.bead_count > lower_bead_count + 1) + if (outgoing->to->data.bead_count_ > lower_bead_count + 1) { assert(upward_edge->data.hasTransitions() && "If the bead count is going down there has to be a transition mid!"); if (! upward_edge->data.hasTransitions()) @@ -1387,7 +1388,7 @@ bool SkeletalTrapezoidation::isGoingDown(edge_t* outgoing, coord_t traveled_dist { auto& transition_mids = *upward_edge->data.getTransitions(); TransitionMiddle& mid = is_upward ? transition_mids.front() : transition_mids.back(); - if (mid.lower_bead_count == lower_bead_count && ((is_upward && mid.pos + traveled_dist < max_dist) || (! is_upward && length - mid.pos + traveled_dist < max_dist))) + if (mid.lower_bead_count_ == lower_bead_count && ((is_upward && mid.pos_ + traveled_dist < max_dist) || (! is_upward && length - mid.pos_ + traveled_dist < max_dist))) { return true; } @@ -1396,7 +1397,7 @@ bool SkeletalTrapezoidation::isGoingDown(edge_t* outgoing, coord_t traveled_dist { return false; } - if (outgoing->to->data.bead_count <= lower_bead_count && ! (outgoing->to->data.bead_count == lower_bead_count && outgoing->to->data.transition_ratio > 0.0)) + if (outgoing->to->data.bead_count_ <= lower_bead_count && ! (outgoing->to->data.bead_count_ == lower_bead_count && outgoing->to->data.transition_ratio_ > 0.0)) { return true; } @@ -1432,7 +1433,7 @@ void SkeletalTrapezoidation::applyTransitions(ptr_vector_t ab_size - snap_dist) && close_node->data.bead_count == new_node_bead_count) + if ((end_pos < snap_dist || end_pos > ab_size - snap_dist) && close_node->data.bead_count_ == new_node_bead_count) { assert(end_pos <= ab_size); - close_node->data.transition_ratio = 0; + close_node->data.transition_ratio_ = 0; continue; } Point mid = a + normal(ab, end_pos); assert(last_edge_replacing_input->data.isCentral()); - assert(last_edge_replacing_input->data.type != SkeletalTrapezoidationEdge::EdgeType::EXTRA_VD); + assert(last_edge_replacing_input->data.type_ != SkeletalTrapezoidationEdge::EdgeType::EXTRA_VD); last_edge_replacing_input = graph.insertNode(last_edge_replacing_input, mid, new_node_bead_count); - assert(last_edge_replacing_input->data.type != SkeletalTrapezoidationEdge::EdgeType::EXTRA_VD); + assert(last_edge_replacing_input->data.type_ != SkeletalTrapezoidationEdge::EdgeType::EXTRA_VD); assert(last_edge_replacing_input->data.isCentral()); } } @@ -1512,12 +1513,12 @@ void SkeletalTrapezoidation::generateExtraRibs() for (auto& edge : graph.edges) { if (! edge.data.isCentral() || shorterThen(edge.to->p - edge.from->p, discretization_step_size) - || edge.from->data.distance_to_boundary >= edge.to->data.distance_to_boundary) + || edge.from->data.distance_to_boundary_ >= edge.to->data.distance_to_boundary_) { continue; } - std::vector rib_thicknesses = beading_strategy.getNonlinearThicknesses(edge.from->data.bead_count); + std::vector rib_thicknesses = beading_strategy.getNonlinearThicknesses(edge.from->data.bead_count_); if (rib_thicknesses.empty()) { @@ -1531,8 +1532,8 @@ void SkeletalTrapezoidation::generateExtraRibs() Point b = to->p; Point ab = b - a; coord_t ab_size = vSize(ab); - coord_t a_R = edge.from->data.distance_to_boundary; - coord_t b_R = edge.to->data.distance_to_boundary; + coord_t a_R = edge.from->data.distance_to_boundary_; + coord_t b_R = edge.to->data.distance_to_boundary_; edge_t* last_edge_replacing_input = &edge; for (coord_t rib_thickness : rib_thicknesses) @@ -1546,23 +1547,23 @@ void SkeletalTrapezoidation::generateExtraRibs() break; } - coord_t new_node_bead_count = std::min(edge.from->data.bead_count, edge.to->data.bead_count); + coord_t new_node_bead_count = std::min(edge.from->data.bead_count_, edge.to->data.bead_count_); coord_t end_pos = ab_size * (rib_thickness / 2 - a_R) / (b_R - a_R); assert(end_pos > 0); assert(end_pos < ab_size); node_t* close_node = (end_pos < ab_size / 2) ? from : to; - if ((end_pos < snap_dist || end_pos > ab_size - snap_dist) && close_node->data.bead_count == new_node_bead_count) + if ((end_pos < snap_dist || end_pos > ab_size - snap_dist) && close_node->data.bead_count_ == new_node_bead_count) { assert(end_pos <= ab_size); - close_node->data.transition_ratio = 0; + close_node->data.transition_ratio_ = 0; continue; } Point mid = a + normal(ab, end_pos); assert(last_edge_replacing_input->data.isCentral()); - assert(last_edge_replacing_input->data.type != SkeletalTrapezoidationEdge::EdgeType::EXTRA_VD); + assert(last_edge_replacing_input->data.type_ != SkeletalTrapezoidationEdge::EdgeType::EXTRA_VD); last_edge_replacing_input = graph.insertNode(last_edge_replacing_input, mid, new_node_bead_count); - assert(last_edge_replacing_input->data.type != SkeletalTrapezoidationEdge::EdgeType::EXTRA_VD); + assert(last_edge_replacing_input->data.type_ != SkeletalTrapezoidationEdge::EdgeType::EXTRA_VD); assert(last_edge_replacing_input->data.isCentral()); } } @@ -1570,7 +1571,7 @@ void SkeletalTrapezoidation::generateExtraRibs() // // ^^^^^^^^^^^^^^^^^^^^^ -// TRANSTISIONING +// TRANSITIONING // ===================== // TOOLPATH GENERATION // vvvvvvvvvvvvvvvvvvvvv @@ -1592,20 +1593,20 @@ void SkeletalTrapezoidation::generateSegments() upward_quad_mids.end(), [this](edge_t* a, edge_t* b) { - if (a->to->data.distance_to_boundary == b->to->data.distance_to_boundary) + if (a->to->data.distance_to_boundary_ == b->to->data.distance_to_boundary_) { // PathOrdering between two 'upward' edges of the same distance is important when one of the edges is flat and connected to the other - if (a->from->data.distance_to_boundary == a->to->data.distance_to_boundary && b->from->data.distance_to_boundary == b->to->data.distance_to_boundary) + if (a->from->data.distance_to_boundary_ == a->to->data.distance_to_boundary_ && b->from->data.distance_to_boundary_ == b->to->data.distance_to_boundary_) { coord_t max = std::numeric_limits::max(); coord_t a_dist_from_up = std::min(a->distToGoUp().value_or(max), a->twin->distToGoUp().value_or(max)) - vSize(a->to->p - a->from->p); coord_t b_dist_from_up = std::min(b->distToGoUp().value_or(max), b->twin->distToGoUp().value_or(max)) - vSize(b->to->p - b->from->p); return a_dist_from_up < b_dist_from_up; } - else if (a->from->data.distance_to_boundary == a->to->data.distance_to_boundary) + else if (a->from->data.distance_to_boundary_ == a->to->data.distance_to_boundary_) { return true; // Edge a might be 'above' edge b } - else if (b->from->data.distance_to_boundary == b->to->data.distance_to_boundary) + else if (b->from->data.distance_to_boundary_ == b->to->data.distance_to_boundary_) { return false; // Edge b might be 'above' edge a } @@ -1614,36 +1615,36 @@ void SkeletalTrapezoidation::generateSegments() // PathOrdering is not important } } - return a->to->data.distance_to_boundary > b->to->data.distance_to_boundary; + return a->to->data.distance_to_boundary_ > b->to->data.distance_to_boundary_; }); ptr_vector_t node_beadings; { // Store beading for (node_t& node : graph.nodes) { - if (node.data.bead_count <= 0) + if (node.data.bead_count_ <= 0) { continue; } - if (node.data.transition_ratio == 0) + if (node.data.transition_ratio_ == 0) { - node_beadings.emplace_back(new BeadingPropagation(beading_strategy.compute(node.data.distance_to_boundary * 2, node.data.bead_count))); + node_beadings.emplace_back(new BeadingPropagation(beading_strategy.compute(node.data.distance_to_boundary_ * 2, node.data.bead_count_))); node.data.setBeading(node_beadings.back()); - assert(node_beadings.back()->beading.total_thickness == node.data.distance_to_boundary * 2); - if (node_beadings.back()->beading.total_thickness != node.data.distance_to_boundary * 2) + assert(node_beadings.back()->beading_.total_thickness == node.data.distance_to_boundary_ * 2); + if (node_beadings.back()->beading_.total_thickness != node.data.distance_to_boundary_ * 2) { spdlog::warn("If transitioning to an endpoint (ratio 0), the node should be exactly in the middle."); } } else { - Beading low_count_beading = beading_strategy.compute(node.data.distance_to_boundary * 2, node.data.bead_count); - Beading high_count_beading = beading_strategy.compute(node.data.distance_to_boundary * 2, node.data.bead_count + 1); - Beading merged = interpolate(low_count_beading, 1.0 - node.data.transition_ratio, high_count_beading); + Beading low_count_beading = beading_strategy.compute(node.data.distance_to_boundary_ * 2, node.data.bead_count_); + Beading high_count_beading = beading_strategy.compute(node.data.distance_to_boundary_ * 2, node.data.bead_count_ + 1); + Beading merged = interpolate(low_count_beading, 1.0 - node.data.transition_ratio_, high_count_beading); node_beadings.emplace_back(new BeadingPropagation(merged)); node.data.setBeading(node_beadings.back()); - assert(merged.total_thickness == node.data.distance_to_boundary * 2); - if (merged.total_thickness != node.data.distance_to_boundary * 2) + assert(merged.total_thickness == node.data.distance_to_boundary_ * 2); + if (merged.total_thickness != node.data.distance_to_boundary_ * 2) { spdlog::warn("If merging two beads, the new bead must be exactly in the middle."); } @@ -1666,19 +1667,19 @@ void SkeletalTrapezoidation::generateSegments() SkeletalTrapezoidation::edge_t* SkeletalTrapezoidation::getQuadMaxRedgeTo(edge_t* quad_start_edge) { assert(quad_start_edge->prev == nullptr); - assert(quad_start_edge->from->data.distance_to_boundary == 0); + assert(quad_start_edge->from->data.distance_to_boundary_ == 0); coord_t max_R = -1; edge_t* ret = nullptr; for (edge_t* edge = quad_start_edge; edge; edge = edge->next) { - coord_t r = edge->to->data.distance_to_boundary; + coord_t r = edge->to->data.distance_to_boundary_; if (r > max_R) { max_R = r; ret = edge; } } - if (! ret->next && ret->to->data.distance_to_boundary - 5 < ret->from->data.distance_to_boundary) + if (! ret->next && ret->to->data.distance_to_boundary_ - 5 < ret->from->data.distance_to_boundary_) { ret = ret->prev; } @@ -1692,7 +1693,7 @@ void SkeletalTrapezoidation::propagateBeadingsUpward(std::vector& upwar for (auto upward_quad_mids_it = upward_quad_mids.rbegin(); upward_quad_mids_it != upward_quad_mids.rend(); ++upward_quad_mids_it) { edge_t* upward_edge = *upward_quad_mids_it; - if (upward_edge->to->data.bead_count >= 0) + if (upward_edge->to->data.bead_count_ >= 0) { // Don't override local beading continue; } @@ -1706,16 +1707,16 @@ void SkeletalTrapezoidation::propagateBeadingsUpward(std::vector& upwar continue; } assert( - (upward_edge->from->data.distance_to_boundary != upward_edge->to->data.distance_to_boundary + (upward_edge->from->data.distance_to_boundary_ != upward_edge->to->data.distance_to_boundary_ || shorterThen(upward_edge->to->p - upward_edge->from->p, central_filter_dist)) && "zero difference R edges should always be central"); coord_t length = vSize(upward_edge->to->p - upward_edge->from->p); BeadingPropagation upper_beading = lower_beading; - upper_beading.dist_to_bottom_source += length; - upper_beading.is_upward_propagated_only = true; + upper_beading.dist_to_bottom_source_ += length; + upper_beading.is_upward_propagated_only_ = true; node_beadings.emplace_back(new BeadingPropagation(upper_beading)); upward_edge->to->data.setBeading(node_beadings.back()); - assert(upper_beading.beading.total_thickness <= upward_edge->to->data.distance_to_boundary * 2); + assert(upper_beading.beading_.total_thickness <= upward_edge->to->data.distance_to_boundary_ * 2); } } @@ -1727,7 +1728,7 @@ void SkeletalTrapezoidation::propagateBeadingsDownward(std::vector& upw if (! upward_quad_mid->data.isCentral()) { // for equidistant edge: propagate from known beading to node with unknown beading - if (upward_quad_mid->from->data.distance_to_boundary == upward_quad_mid->to->data.distance_to_boundary && upward_quad_mid->from->data.hasBeading() + if (upward_quad_mid->from->data.distance_to_boundary_ == upward_quad_mid->to->data.distance_to_boundary_ && upward_quad_mid->from->data.hasBeading() && ! upward_quad_mid->to->data.hasBeading()) { propagateBeadingsDownward(upward_quad_mid->twin, node_beadings); @@ -1744,21 +1745,21 @@ void SkeletalTrapezoidation::propagateBeadingsDownward(edge_t* edge_to_peak, ptr { coord_t length = vSize(edge_to_peak->to->p - edge_to_peak->from->p); BeadingPropagation& top_beading = *getOrCreateBeading(edge_to_peak->to, node_beadings); - assert(top_beading.beading.total_thickness >= edge_to_peak->to->data.distance_to_boundary * 2); - if (top_beading.beading.total_thickness < edge_to_peak->to->data.distance_to_boundary * 2) + assert(top_beading.beading_.total_thickness >= edge_to_peak->to->data.distance_to_boundary_ * 2); + if (top_beading.beading_.total_thickness < edge_to_peak->to->data.distance_to_boundary_ * 2) { spdlog::warn("Top bead is beyond the center of the total width."); } - assert(! top_beading.is_upward_propagated_only); + assert(! top_beading.is_upward_propagated_only_); if (! edge_to_peak->from->data.hasBeading()) { // Set new beading if there is no beading associated with the node yet BeadingPropagation propagated_beading = top_beading; - propagated_beading.dist_from_top_source += length; + propagated_beading.dist_from_top_source_ += length; node_beadings.emplace_back(new BeadingPropagation(propagated_beading)); edge_to_peak->from->data.setBeading(node_beadings.back()); - assert(propagated_beading.beading.total_thickness >= edge_to_peak->from->data.distance_to_boundary * 2); - if (propagated_beading.beading.total_thickness < edge_to_peak->from->data.distance_to_boundary * 2) + assert(propagated_beading.beading_.total_thickness >= edge_to_peak->from->data.distance_to_boundary_ * 2); + if (propagated_beading.beading_.total_thickness < edge_to_peak->from->data.distance_to_boundary_ * 2) { spdlog::warn("Propagated bead is beyond the center of the total width."); } @@ -1766,21 +1767,21 @@ void SkeletalTrapezoidation::propagateBeadingsDownward(edge_t* edge_to_peak, ptr else { BeadingPropagation& bottom_beading = *edge_to_peak->from->data.getBeading(); - coord_t total_dist = top_beading.dist_from_top_source + length + bottom_beading.dist_to_bottom_source; - Ratio ratio_of_top = static_cast(bottom_beading.dist_to_bottom_source) / std::min(total_dist, beading_propagation_transition_dist); + coord_t total_dist = top_beading.dist_from_top_source_ + length + bottom_beading.dist_to_bottom_source_; + Ratio ratio_of_top = static_cast(bottom_beading.dist_to_bottom_source_) / std::min(total_dist, beading_propagation_transition_dist); ratio_of_top = std::max(0.0_r, ratio_of_top); if (ratio_of_top >= 1.0) { bottom_beading = top_beading; - bottom_beading.dist_from_top_source += length; + bottom_beading.dist_from_top_source_ += length; } else { - Beading merged_beading = interpolate(top_beading.beading, ratio_of_top, bottom_beading.beading, edge_to_peak->from->data.distance_to_boundary); + Beading merged_beading = interpolate(top_beading.beading_, ratio_of_top, bottom_beading.beading_, edge_to_peak->from->data.distance_to_boundary_); bottom_beading = BeadingPropagation(merged_beading); - bottom_beading.is_upward_propagated_only = false; - assert(merged_beading.total_thickness >= edge_to_peak->from->data.distance_to_boundary * 2); - if (merged_beading.total_thickness < edge_to_peak->from->data.distance_to_boundary * 2) + bottom_beading.is_upward_propagated_only_ = false; + assert(merged_beading.total_thickness >= edge_to_peak->from->data.distance_to_boundary_ * 2); + if (merged_beading.total_thickness < edge_to_peak->from->data.distance_to_boundary_ * 2) { spdlog::warn("Merged bead is beyond the center of the total width."); } @@ -1859,26 +1860,26 @@ void SkeletalTrapezoidation::generateJunctions(ptr_vector_t& for (edge_t& edge_ : graph.edges) { edge_t* edge = &edge_; - if (edge->from->data.distance_to_boundary > edge->to->data.distance_to_boundary) + if (edge->from->data.distance_to_boundary_ > edge->to->data.distance_to_boundary_) { // Only consider the upward half-edges continue; } - coord_t start_R = edge->to->data.distance_to_boundary; // higher R - coord_t end_R = edge->from->data.distance_to_boundary; // lower R + coord_t start_R = edge->to->data.distance_to_boundary_; // higher R + coord_t end_R = edge->from->data.distance_to_boundary_; // lower R - if ((edge->from->data.bead_count == edge->to->data.bead_count && edge->from->data.bead_count >= 0) || end_R >= start_R) + if ((edge->from->data.bead_count_ == edge->to->data.bead_count_ && edge->from->data.bead_count_ >= 0) || end_R >= start_R) { // No beads to generate continue; } - Beading* beading = &getOrCreateBeading(edge->to, node_beadings)->beading; + Beading* beading = &getOrCreateBeading(edge->to, node_beadings)->beading_; edge_junctions.emplace_back(std::make_shared()); edge_.data.setExtrusionJunctions(edge_junctions.back()); // initialization LineJunctions& ret = *edge_junctions.back(); - assert(beading->total_thickness >= edge->to->data.distance_to_boundary * 2); - if (beading->total_thickness < edge->to->data.distance_to_boundary * 2) + assert(beading->total_thickness >= edge->to->data.distance_to_boundary_ * 2); + if (beading->total_thickness < edge->to->data.distance_to_boundary_ * 2) { spdlog::warn("Generated junction is beyond the center of total width."); } @@ -1929,7 +1930,7 @@ std::shared_ptr SkeletalTrapezo { if (! node->data.hasBeading()) { - if (node->data.bead_count == -1) + if (node->data.bead_count_ == -1) { // This bug is due to too small central edges constexpr coord_t nearby_dist = 100; // TODO auto nearest_beading = getNearestBeading(node, nearby_dist); @@ -1948,8 +1949,8 @@ std::shared_ptr SkeletalTrapezo { has_central_edge = true; } - assert(edge->to->data.distance_to_boundary >= 0); - dist = std::min(dist, edge->to->data.distance_to_boundary + vSize(edge->to->p - edge->from->p)); + assert(edge->to->data.distance_to_boundary_ >= 0); + dist = std::min(dist, edge->to->data.distance_to_boundary_ + vSize(edge->to->p - edge->from->p)); first = false; } if (! has_central_edge) @@ -1957,10 +1958,10 @@ std::shared_ptr SkeletalTrapezo spdlog::error("Unknown beading for non-central node!"); } assert(dist != std::numeric_limits::max()); - node->data.bead_count = beading_strategy.getOptimalBeadCount(dist * 2); + node->data.bead_count_ = beading_strategy.getOptimalBeadCount(dist * 2); } - assert(node->data.bead_count != -1); - node_beadings.emplace_back(new BeadingPropagation(beading_strategy.compute(node->data.distance_to_boundary * 2, node->data.bead_count))); + assert(node->data.bead_count_ != -1); + node_beadings.emplace_back(new BeadingPropagation(beading_strategy.compute(node->data.distance_to_boundary_ * 2, node->data.bead_count_))); node->data.setBeading(node_beadings.back()); } assert(node->data.hasBeading()); @@ -2155,12 +2156,12 @@ void SkeletalTrapezoidation::connectJunctions(ptr_vector_t& edge_ { spdlog::warn("Connecting two perimeters with different indices! Perimeter {} and {}", from.perimeter_index, to.perimeter_index); } - const bool from_is_odd = quad_start->to->data.bead_count > 0 && quad_start->to->data.bead_count % 2 == 1 // quad contains single bead segment - && quad_start->to->data.transition_ratio == 0 // We're not in a transition + const bool from_is_odd = quad_start->to->data.bead_count_ > 0 && quad_start->to->data.bead_count_ % 2 == 1 // quad contains single bead segment + && quad_start->to->data.transition_ratio_ == 0 // We're not in a transition && junction_rev_idx == segment_count - 1 // Is single bead segment && shorterThen(from.p - quad_start->to->p, 5); - const bool to_is_odd = quad_end->from->data.bead_count > 0 && quad_end->from->data.bead_count % 2 == 1 // quad contains single bead segment - && quad_end->from->data.transition_ratio == 0 // We're not in a transition + const bool to_is_odd = quad_end->from->data.bead_count_ > 0 && quad_end->from->data.bead_count_ % 2 == 1 // quad contains single bead segment + && quad_end->from->data.transition_ratio_ == 0 // We're not in a transition && junction_rev_idx == segment_count - 1 // Is single bead segment && shorterThen(to.p - quad_end->from->p, 5); const bool is_odd_segment = from_is_odd && to_is_odd; @@ -2192,7 +2193,7 @@ void SkeletalTrapezoidation::generateLocalMaximaSingleBeads() { continue; } - Beading& beading = node.data.getBeading()->beading; + Beading& beading = node.data.getBeading()->beading_; if (beading.bead_widths.size() % 2 == 1 && node.isLocalMaximum(true) && ! node.isCentral()) { const size_t inset_index = beading.bead_widths.size() / 2; diff --git a/src/SkeletalTrapezoidationGraph.cpp b/src/SkeletalTrapezoidationGraph.cpp index 4657b8ee97..0ac596ea2c 100644 --- a/src/SkeletalTrapezoidationGraph.cpp +++ b/src/SkeletalTrapezoidationGraph.cpp @@ -3,12 +3,12 @@ #include "SkeletalTrapezoidationGraph.h" -#include "utils/linearAlg2D.h" -#include "utils/macros.h" +#include #include -#include +#include "utils/linearAlg2D.h" +#include "utils/macros.h" namespace cura { @@ -20,11 +20,11 @@ STHalfEdge::STHalfEdge(SkeletalTrapezoidationEdge data) bool STHalfEdge::canGoUp(bool strict) const { - if (to->data.distance_to_boundary > from->data.distance_to_boundary) + if (to->data.distance_to_boundary_ > from->data.distance_to_boundary_) { return true; } - if (to->data.distance_to_boundary < from->data.distance_to_boundary || strict) + if (to->data.distance_to_boundary_ < from->data.distance_to_boundary_ || strict) { return false; } @@ -48,11 +48,11 @@ bool STHalfEdge::canGoUp(bool strict) const bool STHalfEdge::isUpward() const { - if (to->data.distance_to_boundary > from->data.distance_to_boundary) + if (to->data.distance_to_boundary_ > from->data.distance_to_boundary_) { return true; } - if (to->data.distance_to_boundary < from->data.distance_to_boundary) + if (to->data.distance_to_boundary_ < from->data.distance_to_boundary_) { return false; } @@ -79,11 +79,11 @@ bool STHalfEdge::isUpward() const std::optional STHalfEdge::distToGoUp() const { - if (to->data.distance_to_boundary > from->data.distance_to_boundary) + if (to->data.distance_to_boundary_ > from->data.distance_to_boundary_) { return 0; } - if (to->data.distance_to_boundary < from->data.distance_to_boundary) + if (to->data.distance_to_boundary_ < from->data.distance_to_boundary_) { return std::optional(); } @@ -173,7 +173,7 @@ bool STHalfEdgeNode::isCentral() const bool STHalfEdgeNode::isLocalMaximum(bool strict) const { - if (data.distance_to_boundary == 0) + if (data.distance_to_boundary_ == 0) { return false; } @@ -333,12 +333,12 @@ void SkeletalTrapezoidationGraph::makeRib(edge_t*& prev_edge, Point start_source { Point p = LinearAlg2D::getClosestOnLine(prev_edge->to->p, start_source_point, end_source_point); coord_t dist = vSize(prev_edge->to->p - p); - prev_edge->to->data.distance_to_boundary = dist; + prev_edge->to->data.distance_to_boundary_ = dist; assert(dist >= 0); nodes.emplace_front(SkeletalTrapezoidationJoint(), p); node_t* node = &nodes.front(); - node->data.distance_to_boundary = 0; + node->data.distance_to_boundary_ = 0; edges.emplace_front(SkeletalTrapezoidationEdge(SkeletalTrapezoidationEdge::EdgeType::EXTRA_VD)); edge_t* forth_edge = &edges.front(); @@ -371,12 +371,12 @@ std::pair 0); - mid_node->data.distance_to_boundary = dist; - mid_node->data.transition_ratio = 0; // Both transition end should have rest = 0, because at the ends a whole number of beads fits without rest + mid_node->data.distance_to_boundary_ = dist; + mid_node->data.transition_ratio_ = 0; // Both transition end should have rest = 0, because at the ends a whole number of beads fits without rest nodes.emplace_back(SkeletalTrapezoidationJoint(), px); node_t* source_node = &nodes.back(); - source_node->data.distance_to_boundary = 0; + source_node->data.distance_to_boundary_ = 0; edge_t* first = &edge; edges.emplace_back(SkeletalTrapezoidationEdge()); @@ -433,7 +433,7 @@ std::pairtwin = nullptr; // we don't know these yet! second->twin = nullptr; - assert(second->prev->from->data.distance_to_boundary == 0); + assert(second->prev->from->data.distance_to_boundary_ == 0); return std::make_pair(first, second); } @@ -460,7 +460,7 @@ SkeletalTrapezoidationGraph::edge_t* SkeletalTrapezoidationGraph::insertNode(edg last_edge_replacing_input->twin = first_edge_replacing_twin; first_edge_replacing_twin->twin = last_edge_replacing_input; - mid_node->data.bead_count = mide_node_bead_count; + mid_node->data.bead_count_ = mide_node_bead_count; return last_edge_replacing_input; } diff --git a/src/utils/PolygonConnector.cpp b/src/utils/PolygonConnector.cpp index 85d4284a10..b984010dc9 100644 --- a/src/utils/PolygonConnector.cpp +++ b/src/utils/PolygonConnector.cpp @@ -10,14 +10,14 @@ namespace cura { PolygonConnector::PolygonConnector(const coord_t line_width) -: line_width(line_width) +: line_width_(line_width) {} void PolygonConnector::add(const Polygons& input) { for (ConstPolygonRef poly : input) { - input_polygons.push_back(poly); + input_polygons_.push_back(poly); } } @@ -27,20 +27,20 @@ void PolygonConnector::add(const std::vector& input) { for(const ExtrusionLine& line : lines) { - input_paths.push_back(line); + input_paths_.push_back(line); } } } void PolygonConnector::connect(Polygons& output_polygons, std::vector& output_paths) { - std::vector result_polygons = connectGroup(input_polygons); + std::vector result_polygons = connectGroup(input_polygons_); for(Polygon& polygon : result_polygons) { output_polygons.add(polygon); } - std::vector result_paths = connectGroup(input_paths); + std::vector result_paths = connectGroup(input_paths_); output_paths.push_back(result_paths); } @@ -56,7 +56,7 @@ Point PolygonConnector::getPosition(const ExtrusionJunction& junction) const coord_t PolygonConnector::getWidth(const Point&) const { - return line_width; + return line_width_; } coord_t PolygonConnector::getWidth(const ExtrusionJunction& junction) const diff --git a/tests/utils/PolygonConnectorTest.cpp b/tests/utils/PolygonConnectorTest.cpp index 8286e85fd2..dc7c7b832e 100644 --- a/tests/utils/PolygonConnectorTest.cpp +++ b/tests/utils/PolygonConnectorTest.cpp @@ -68,11 +68,11 @@ TEST_F(PolygonConnectorTest, getBridgeNestedSquares) ASSERT_NE(bridge, std::nullopt) << "The two polygons are nested simply, so they are definitely positioned closely enough to bridge. They are also wide enough."; - EXPECT_EQ(vSize(bridge->a.from_point - bridge->a.to_point), 100) << "The polygons are 100 units spaced out concentrically, so this is the shortest possible bridge."; - EXPECT_EQ(vSize(bridge->b.from_point - bridge->b.to_point), 100) << "The second bridge should also be equally short in this case."; - EXPECT_EQ(LinearAlg2D::getDist2BetweenLineSegments(bridge->a.from_point, bridge->a.to_point, bridge->b.from_point, bridge->b.to_point), 100 * 100) << "The bridges should be spaced 1 line width (100 units) apart."; - EXPECT_LT(LinearAlg2D::pointIsLeftOfLine(bridge->b.from_point, bridge->a.from_point, bridge->a.to_point), 0) << "Connection B should be to the right of connection A."; - EXPECT_LT(LinearAlg2D::pointIsLeftOfLine(bridge->b.to_point, bridge->a.from_point, bridge->a.to_point), 0) << "Connection B should be to the right of connection A."; + EXPECT_EQ(vSize(bridge->a_.from_point_ - bridge->a_.to_point_), 100) << "The polygons are 100 units spaced out concentrically, so this is the shortest possible bridge."; + EXPECT_EQ(vSize(bridge->b_.from_point_ - bridge->b_.to_point_), 100) << "The second bridge should also be equally short in this case."; + EXPECT_EQ(LinearAlg2D::getDist2BetweenLineSegments(bridge->a_.from_point_, bridge->a_.to_point_, bridge->b_.from_point_, bridge->b_.to_point_), 100 * 100) << "The bridges should be spaced 1 line width (100 units) apart."; + EXPECT_LT(LinearAlg2D::pointIsLeftOfLine(bridge->b_.from_point_, bridge->a_.from_point_, bridge->a_.to_point_), 0) << "Connection B should be to the right of connection A."; + EXPECT_LT(LinearAlg2D::pointIsLeftOfLine(bridge->b_.to_point_, bridge->a_.from_point_, bridge->a_.to_point_), 0) << "Connection B should be to the right of connection A."; } /*! @@ -88,11 +88,11 @@ TEST_F(PolygonConnectorTest, getBridgeAdjacentSquares) ASSERT_NE(bridge, std::nullopt) << "The two polygons are adjacent, spaced closely enough to bridge and with enough room."; - EXPECT_EQ(vSize(bridge->a.from_point - bridge->a.to_point), 100) << "The polygons are 100 units spaced apart, so this is the shortest possible bridge."; - EXPECT_EQ(vSize(bridge->b.from_point - bridge->b.to_point), 100) << "The second bridge should also be equally short in this case."; - EXPECT_EQ(LinearAlg2D::getDist2BetweenLineSegments(bridge->a.from_point, bridge->a.to_point, bridge->b.from_point, bridge->b.to_point), 100 * 100) << "The bridges should be spaced 1 line width (100 units) apart."; - EXPECT_LT(LinearAlg2D::pointIsLeftOfLine(bridge->b.from_point, bridge->a.from_point, bridge->a.to_point), 0) << "Connection B should be to the right of connection A."; - EXPECT_LT(LinearAlg2D::pointIsLeftOfLine(bridge->b.to_point, bridge->a.from_point, bridge->a.to_point), 0) << "Connection B should be to the right of connection A."; + EXPECT_EQ(vSize(bridge->a_.from_point_ - bridge->a_.to_point_), 100) << "The polygons are 100 units spaced apart, so this is the shortest possible bridge."; + EXPECT_EQ(vSize(bridge->b_.from_point_ - bridge->b_.to_point_), 100) << "The second bridge should also be equally short in this case."; + EXPECT_EQ(LinearAlg2D::getDist2BetweenLineSegments(bridge->a_.from_point_, bridge->a_.to_point_, bridge->b_.from_point_, bridge->b_.to_point_), 100 * 100) << "The bridges should be spaced 1 line width (100 units) apart."; + EXPECT_LT(LinearAlg2D::pointIsLeftOfLine(bridge->b_.from_point_, bridge->a_.from_point_, bridge->a_.to_point_), 0) << "Connection B should be to the right of connection A."; + EXPECT_LT(LinearAlg2D::pointIsLeftOfLine(bridge->b_.to_point_, bridge->a_.from_point_, bridge->a_.to_point_), 0) << "Connection B should be to the right of connection A."; } /*! @@ -113,10 +113,10 @@ TEST_F(PolygonConnectorTest, getBridgeClosest) ASSERT_NE(bridge, std::nullopt) << "The two polygons are adjacent and spaced closely enough to bridge along their entire side, even with the slant."; - EXPECT_EQ(bridge->b.from_point, Point(1000, 200)) << "The closest connection is [1000,200] -> [1100,200]. There is no space to the right of that, so bridge B should be there."; - EXPECT_EQ(bridge->b.to_point, Point(1100, 200)) << "The closest connection is [1000,200] -> [1100,200]. There is no space to the right of that, so bridge B should be there."; - EXPECT_GT(LinearAlg2D::pointIsLeftOfLine(bridge->a.from_point, bridge->b.from_point, bridge->b.to_point), 0) << "Connection A should be to the left of connection B."; - EXPECT_GT(LinearAlg2D::pointIsLeftOfLine(bridge->a.to_point, bridge->b.from_point, bridge->b.to_point), 0) << "Connection A should be to the left of connection B."; + EXPECT_EQ(bridge->b_.from_point_, Point(1000, 200)) << "The closest connection is [1000,200] -> [1100,200]. There is no space to the right of that, so bridge B should be there."; + EXPECT_EQ(bridge->b_.to_point_, Point(1100, 200)) << "The closest connection is [1000,200] -> [1100,200]. There is no space to the right of that, so bridge B should be there."; + EXPECT_GT(LinearAlg2D::pointIsLeftOfLine(bridge->a_.from_point_, bridge->b_.from_point_, bridge->b_.to_point_), 0) << "Connection A should be to the left of connection B."; + EXPECT_GT(LinearAlg2D::pointIsLeftOfLine(bridge->a_.to_point_, bridge->b_.from_point_, bridge->b_.to_point_), 0) << "Connection A should be to the left of connection B."; } /*! From 6720d7a8ec0ef1f2a35999c020fb4bf364ed07af Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Tue, 21 Nov 2023 12:10:21 +0100 Subject: [PATCH 18/48] Fixed variable shadowing warnings --- include/SkeletalTrapezoidation.h | 8 ++++---- src/SkeletalTrapezoidation.cpp | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/include/SkeletalTrapezoidation.h b/include/SkeletalTrapezoidation.h index 2b920465c4..87b5155099 100644 --- a/include/SkeletalTrapezoidation.h +++ b/include/SkeletalTrapezoidation.h @@ -136,11 +136,11 @@ class SkeletalTrapezoidation */ struct TransitionMidRef { - edge_t* edge; - std::list::iterator transition_it; + edge_t* edge_; + std::list::iterator transition_it_; TransitionMidRef(edge_t* edge, std::list::iterator transition_it) - : edge(edge) - , transition_it(transition_it) + : edge_(edge) + , transition_it_(transition_it) {} }; diff --git a/src/SkeletalTrapezoidation.cpp b/src/SkeletalTrapezoidation.cpp index dd4b69ccbd..7fd2ffdc48 100644 --- a/src/SkeletalTrapezoidation.cpp +++ b/src/SkeletalTrapezoidation.cpp @@ -1021,7 +1021,7 @@ void SkeletalTrapezoidation::filterTransitionMids() for (TransitionMidRef& ref : to_be_dissolved_back) { dissolveBeadCountRegion(&edge, transitions.back().lower_bead_count_ + 1, transitions.back().lower_bead_count_); - ref.edge->data.getTransitions()->erase(ref.transition_it); + ref.edge_->data.getTransitions()->erase(ref.transition_it_); } { @@ -1045,7 +1045,7 @@ void SkeletalTrapezoidation::filterTransitionMids() for (TransitionMidRef& ref : to_be_dissolved_front) { dissolveBeadCountRegion(edge.twin, transitions.front().lower_bead_count_, transitions.front().lower_bead_count_ + 1); - ref.edge->data.getTransitions()->erase(ref.transition_it); + ref.edge_->data.getTransitions()->erase(ref.transition_it_); } { From bdbdd178d1362f7fdf57a082ca80ef8cc79d75e9 Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Tue, 21 Nov 2023 12:14:35 +0100 Subject: [PATCH 19/48] Removed last occurences of M_PI --- .../BeadingStrategy/BeadingStrategyFactory.h | 8 ++--- include/PathOrderOptimizer.h | 4 +-- include/settings/types/Angle.h | 4 +-- include/utils/ExtrusionSegment.h | 23 ++++++------ include/utils/IntPoint.h | 6 ++-- include/utils/polygonUtils.h | 2 +- .../BeadingStrategyFactory.cpp | 36 +++++++++++-------- 7 files changed, 43 insertions(+), 40 deletions(-) diff --git a/include/BeadingStrategy/BeadingStrategyFactory.h b/include/BeadingStrategy/BeadingStrategyFactory.h index 55cfe6d2ac..2789fa4657 100644 --- a/include/BeadingStrategy/BeadingStrategyFactory.h +++ b/include/BeadingStrategy/BeadingStrategyFactory.h @@ -13,12 +13,11 @@ namespace cura class BeadingStrategyFactory { public: - static BeadingStrategyPtr makeStrategy - ( + static BeadingStrategyPtr makeStrategy( const coord_t preferred_bead_width_outer = MM2INT(0.5), const coord_t preferred_bead_width_inner = MM2INT(0.5), const coord_t preferred_transition_length = MM2INT(0.4), - const float transitioning_angle = M_PI / 4.0, + const double transitioning_angle = std::numbers::pi / 4.0, const bool print_thin_walls = false, const coord_t min_bead_width = 0, const coord_t min_feature_size = 0, @@ -27,8 +26,7 @@ class BeadingStrategyFactory const coord_t max_bead_count = 0, const coord_t outer_wall_offset = 0, const int inward_distributed_center_wall_count = 2, - const Ratio minimum_variable_line_ratio = 0.5 - ); + const Ratio minimum_variable_line_ratio = 0.5); }; } // namespace cura diff --git a/include/PathOrderOptimizer.h b/include/PathOrderOptimizer.h index 2206ece605..ee2ab5102e 100644 --- a/include/PathOrderOptimizer.h +++ b/include/PathOrderOptimizer.h @@ -804,9 +804,9 @@ class PathOrderOptimizer const Point next = findNeighbourPoint(path, i, bounded_distance, segments_sizes); const Point previous = findNeighbourPoint(path, i, -bounded_distance, segments_sizes); - float angle = LinearAlg2D::getAngleLeft(previous, here, next) - M_PI; + float angle = LinearAlg2D::getAngleLeft(previous, here, next) - std::numbers::pi_v; - return angle / M_PI; + return angle / std::numbers::pi_v; } /*! diff --git a/include/settings/types/Angle.h b/include/settings/types/Angle.h index 4b4ed3de5e..f6a7665b00 100644 --- a/include/settings/types/Angle.h +++ b/include/settings/types/Angle.h @@ -6,9 +6,9 @@ #include //For fmod. -#include "../../utils/math.h" //For M_PI. +#include "../../utils/math.h" //For PI. -#define TAU (2.0 * M_PI) +#define TAU (2.0 * std::numbers::pi) namespace cura { diff --git a/include/utils/ExtrusionSegment.h b/include/utils/ExtrusionSegment.h index 11d0d4fb57..8c97b04215 100644 --- a/include/utils/ExtrusionSegment.h +++ b/include/utils/ExtrusionSegment.h @@ -1,5 +1,5 @@ -//Copyright (c) 2020 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2020 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef UTILS_EXTRUSION_SEGMENT_H @@ -7,10 +7,10 @@ #include +#include "ExtrusionJunction.h" #include "IntPoint.h" #include "polygon.h" #include "polygonUtils.h" -#include "ExtrusionJunction.h" namespace cura { @@ -23,7 +23,7 @@ namespace cura */ class ExtrusionSegment { - static constexpr float a_step = 15 / 180.0 * M_PI; //!< In the calculation of the area covered by this line, the angle between line segments of the round endcaps. + static constexpr float a_step = 15 / 180.0 * std::numbers::pi; //!< In the calculation of the area covered by this line, the angle between line segments of the round endcaps. public: ExtrusionJunction from; ExtrusionJunction to; @@ -43,17 +43,18 @@ class ExtrusionSegment bool is_reduced; ExtrusionSegment(ExtrusionJunction from, ExtrusionJunction to, bool is_odd, bool is_reduced) - : from(from) - , to(to) - , is_odd(is_odd) - , is_reduced(is_reduced) - {} + : from(from) + , to(to) + , is_odd(is_odd) + , is_reduced(is_reduced) + { + } /*! * Converts this segment to an outline of the area that the segment covers. * \return The area that would be covered by this extrusion segment. */ - Polygons toPolygons(); + Polygons toPolygons(); /*! * Converts this segment to an outline of the area that the segment covers. @@ -80,7 +81,5 @@ class ExtrusionSegment }; - - } // namespace cura #endif // UTILS_EXTRUSION_SEGMENT_H diff --git a/include/utils/IntPoint.h b/include/utils/IntPoint.h index 7649241e82..1e4f5cabee 100644 --- a/include/utils/IntPoint.h +++ b/include/utils/IntPoint.h @@ -18,7 +18,7 @@ Integer points are used to avoid floating point rounding errors, and because Cli #include #include -#include "../utils/math.h" // for M_PI. Use relative path to avoid pulling +#include "../utils/math.h" // for PI. Use relative path to avoid pulling #include "Point3.h" //For applying Point3Matrices. #ifdef __GNUC__ @@ -185,7 +185,7 @@ INLINE coord_t cross(const Point& p0, const Point& p1) INLINE int angle(const Point& p) { - double angle = std::atan2(p.X, p.Y) / M_PI * 180.0; + double angle = std::atan2(p.X, p.Y) / std::numbers::pi * 180.0; if (angle < 0.0) angle += 360.0; return static_cast(std::lrint(angle)); @@ -233,7 +233,7 @@ class PointMatrix PointMatrix(double rotation) { - rotation = rotation / 180 * M_PI; + rotation = rotation / 180 * std::numbers::pi; matrix[0] = cos(rotation); matrix[1] = -sin(rotation); matrix[2] = -matrix[1]; diff --git a/include/utils/polygonUtils.h b/include/utils/polygonUtils.h index 24d8936561..9e2017d1b2 100644 --- a/include/utils/polygonUtils.h +++ b/include/utils/polygonUtils.h @@ -671,7 +671,7 @@ class PolygonUtils * \param a_step The angle between segments of the circle. * \return A new Polygon containing the circle. */ - static Polygon makeCircle(const Point mid, const coord_t radius, const AngleRadians a_step = M_PI / 8); + static Polygon makeCircle(const Point mid, const coord_t radius, const AngleRadians a_step = std::numbers::pi / 8); /*! * Connect all polygons to their holes using zero widths hole channels, so that the polygons and their outlines are connected together diff --git a/src/BeadingStrategy/BeadingStrategyFactory.cpp b/src/BeadingStrategy/BeadingStrategyFactory.cpp index f9682eb2ef..c929bd5d9f 100644 --- a/src/BeadingStrategy/BeadingStrategyFactory.cpp +++ b/src/BeadingStrategy/BeadingStrategyFactory.cpp @@ -16,24 +16,30 @@ namespace cura { -BeadingStrategyPtr BeadingStrategyFactory::makeStrategy(const coord_t preferred_bead_width_outer, - const coord_t preferred_bead_width_inner, - const coord_t preferred_transition_length, - const float transitioning_angle, - const bool print_thin_walls, - const coord_t min_bead_width, - const coord_t min_feature_size, - const Ratio wall_split_middle_threshold, - const Ratio wall_add_middle_threshold, - const coord_t max_bead_count, - const coord_t outer_wall_offset, - const int inward_distributed_center_wall_count, - const Ratio minimum_variable_line_ratio) +BeadingStrategyPtr BeadingStrategyFactory::makeStrategy( + const coord_t preferred_bead_width_outer, + const coord_t preferred_bead_width_inner, + const coord_t preferred_transition_length, + const double transitioning_angle, + const bool print_thin_walls, + const coord_t min_bead_width, + const coord_t min_feature_size, + const Ratio wall_split_middle_threshold, + const Ratio wall_add_middle_threshold, + const coord_t max_bead_count, + const coord_t outer_wall_offset, + const int inward_distributed_center_wall_count, + const Ratio minimum_variable_line_ratio) { using std::make_unique; using std::move; - BeadingStrategyPtr ret = - make_unique(preferred_bead_width_inner, preferred_transition_length, transitioning_angle, wall_split_middle_threshold, wall_add_middle_threshold, inward_distributed_center_wall_count); + BeadingStrategyPtr ret = make_unique( + preferred_bead_width_inner, + preferred_transition_length, + transitioning_angle, + wall_split_middle_threshold, + wall_add_middle_threshold, + inward_distributed_center_wall_count); spdlog::debug("Applying the Redistribute meta-strategy with outer-wall width = {}, inner-wall width = {}", preferred_bead_width_outer, preferred_bead_width_inner); ret = make_unique(preferred_bead_width_outer, minimum_variable_line_ratio, move(ret)); From bfe91cb226f8235fd8d0bd2929fcdfcb178e7299 Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Tue, 21 Nov 2023 14:36:51 +0100 Subject: [PATCH 20/48] Use double instead of float, unless explicitely necessary --- include/BeadingStrategy/BeadingStrategy.h | 4 +- .../DistributedBeadingStrategy.h | 16 +- .../BeadingStrategy/LimitedBeadingStrategy.h | 2 +- .../RedistributeBeadingStrategy.h | 148 +++++++++--------- .../BeadingStrategy/WideningBeadingStrategy.h | 6 +- include/LayerPlan.h | 12 +- include/PathOrderOptimizer.h | 24 +-- include/SkeletalTrapezoidationJoint.h | 8 +- include/communication/ArcusCommunication.h | 6 +- include/communication/CommandLine.h | 8 +- include/communication/Communication.h | 2 +- include/infill.h | 2 +- include/infill/DensityProvider.h | 12 +- include/infill/ImageBasedDensityProvider.h | 9 +- include/infill/SierpinskiFill.h | 22 +-- include/infill/UniformDensityProvider.h | 19 +-- include/mesh.h | 39 +++-- include/utils/ExtrusionSegment.h | 19 +-- include/utils/FMatrix4x3.h | 4 +- include/utils/IntPoint.h | 4 +- include/utils/Point3d.h | 142 +++++++++++++++++ include/utils/Point3f.h | 45 ++++++ include/utils/SVG.h | 38 ++--- include/utils/SparseGrid.h | 133 ++++++++-------- include/utils/SparseLineGrid.h | 43 ++--- include/utils/SparsePointGrid.h | 38 ++--- include/utils/SparsePointGridInclusive.h | 56 ++++--- include/utils/ToolpathVisualizer.h | 17 +- include/utils/VoronoiUtils.h | 35 ++--- include/utils/floatpoint.h | 142 ----------------- include/utils/linearAlg2D.h | 2 +- include/utils/polygon.h | 9 +- src/BeadingStrategy/BeadingStrategy.cpp | 45 +++--- .../DistributedBeadingStrategy.cpp | 25 ++- .../LimitedBeadingStrategy.cpp | 7 +- .../RedistributeBeadingStrategy.cpp | 30 ++-- .../WideningBeadingStrategy.cpp | 14 +- src/FffGcodeWriter.cpp | 6 +- src/FffPolygonGenerator.cpp | 2 +- src/LayerPlan.cpp | 32 ++-- src/MeshGroup.cpp | 18 +-- src/SkeletalTrapezoidation.cpp | 24 +-- src/TopSurface.cpp | 2 +- src/bridge.cpp | 2 +- src/communication/ArcusCommunication.cpp | 20 +-- .../ArcusCommunicationPrivate.cpp | 18 +-- src/communication/CommandLine.cpp | 4 +- src/gcodeExport.cpp | 8 +- src/infill.cpp | 18 +-- src/infill/GyroidInfill.cpp | 48 +++--- src/infill/ImageBasedDensityProvider.cpp | 8 +- src/infill/SierpinskiFill.cpp | 70 ++++----- src/infill/SierpinskiFillProvider.cpp | 4 +- src/mesh.cpp | 14 +- src/pathPlanning/LinePolygonsCrossings.cpp | 93 ++++++----- src/progress/Progress.cpp | 2 +- src/settings/AdaptiveLayerHeights.cpp | 16 +- src/settings/PathConfigStorage.cpp | 2 +- src/skin.cpp | 12 +- src/support.cpp | 18 +-- src/timeEstimate.cpp | 8 +- src/utils/ExtrusionSegment.cpp | 56 ++++--- src/utils/FMatrix4x3.cpp | 4 +- src/utils/LinearAlg2D.cpp | 8 +- src/utils/SVG.cpp | 100 ++++++------ src/utils/ToolpathVisualizer.cpp | 60 +++---- src/utils/VoronoiUtils.cpp | 14 +- src/utils/VoxelUtils.cpp | 4 +- src/utils/polygon.cpp | 10 +- src/utils/polygonUtils.cpp | 2 +- 70 files changed, 968 insertions(+), 926 deletions(-) create mode 100644 include/utils/Point3d.h create mode 100644 include/utils/Point3f.h delete mode 100644 include/utils/floatpoint.h diff --git a/include/BeadingStrategy/BeadingStrategy.h b/include/BeadingStrategy/BeadingStrategy.h index ee2d2635e6..0b6d28a87d 100644 --- a/include/BeadingStrategy/BeadingStrategy.h +++ b/include/BeadingStrategy/BeadingStrategy.h @@ -41,7 +41,7 @@ class BeadingStrategy Ratio wall_split_middle_threshold, Ratio wall_add_middle_threshold, coord_t default_transition_length, - float transitioning_angle = std::numbers::pi_v / 3.0); + double transitioning_angle = std::numbers::pi / 3.0); BeadingStrategy(const BeadingStrategy& other); @@ -85,7 +85,7 @@ class BeadingStrategy * * Transitions are used to smooth out the jumps in integer bead count; the jumps turn into ramps which could be positioned relative to the jump location. */ - virtual float getTransitionAnchorPos(coord_t lower_bead_count) const; + virtual double getTransitionAnchorPos(coord_t lower_bead_count) const; /*! * Get the locations in a bead count region where \ref BeadingStrategy::compute exhibits a bend in the widths. diff --git a/include/BeadingStrategy/DistributedBeadingStrategy.h b/include/BeadingStrategy/DistributedBeadingStrategy.h index dde25da175..35a7bb0bde 100644 --- a/include/BeadingStrategy/DistributedBeadingStrategy.h +++ b/include/BeadingStrategy/DistributedBeadingStrategy.h @@ -18,23 +18,23 @@ namespace cura class DistributedBeadingStrategy : public BeadingStrategy { protected: - float one_over_distribution_radius_squared; // (1 / distribution_radius)^2 + double one_over_distribution_radius_squared; // (1 / distribution_radius)^2 public: /*! - * \param distribution_radius the radius (in number of beads) over which to distribute the discrepancy between the feature size and the optimal thickness - */ - DistributedBeadingStrategy - ( + * \param distribution_radius the radius (in number of beads) over which to distribute the discrepancy between the feature size and the optimal thickness + */ + DistributedBeadingStrategy( const coord_t optimal_width, const coord_t default_transition_length, const AngleRadians transitioning_angle, const Ratio wall_split_middle_threshold, const Ratio wall_add_middle_threshold, - const int distribution_radius - ); + const int distribution_radius); - virtual ~DistributedBeadingStrategy() override {} + virtual ~DistributedBeadingStrategy() override + { + } Beading compute(coord_t thickness, coord_t bead_count) const override; coord_t getOptimalBeadCount(coord_t thickness) const override; diff --git a/include/BeadingStrategy/LimitedBeadingStrategy.h b/include/BeadingStrategy/LimitedBeadingStrategy.h index e727015db6..b4ca975fd6 100644 --- a/include/BeadingStrategy/LimitedBeadingStrategy.h +++ b/include/BeadingStrategy/LimitedBeadingStrategy.h @@ -39,7 +39,7 @@ class LimitedBeadingStrategy : public BeadingStrategy coord_t getTransitioningLength(coord_t lower_bead_count) const override; - float getTransitionAnchorPos(coord_t lower_bead_count) const override; + double getTransitionAnchorPos(coord_t lower_bead_count) const override; protected: const coord_t max_bead_count; diff --git a/include/BeadingStrategy/RedistributeBeadingStrategy.h b/include/BeadingStrategy/RedistributeBeadingStrategy.h index 28e767d05a..6609eee995 100644 --- a/include/BeadingStrategy/RedistributeBeadingStrategy.h +++ b/include/BeadingStrategy/RedistributeBeadingStrategy.h @@ -1,98 +1,92 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef REDISTRIBUTE_DISTRIBUTED_BEADING_STRATEGY_H #define REDISTRIBUTE_DISTRIBUTED_BEADING_STRATEGY_H -#include "BeadingStrategy.h" - #include "../settings/types/Ratio.h" +#include "BeadingStrategy.h" namespace cura { +/*! + * A meta-beading-strategy that takes outer and inner wall widths into account. + * + * The outer wall will try to keep a constant width by only applying the beading strategy on the inner walls. This + * ensures that this outer wall doesn't react to changes happening to inner walls. It will limit print artifacts on + * the surface of the print. Although this strategy technically deviates from the original philosophy of the paper. + * It will generally results in better prints because of a smoother motion and less variation in extrusion width in + * the outer walls. + * + * If the thickness of the model is less then two times the optimal outer wall width and once the minimum inner wall + * width it will keep the minimum inner wall at a minimum constant and vary the outer wall widths symmetrical. Until + * The thickness of the model is that of at least twice the optimal outer wall width it will then use two + * symmetrical outer walls only. Until it transitions into a single outer wall. These last scenario's are always + * symmetrical in nature, disregarding the user specified strategy. + */ +class RedistributeBeadingStrategy : public BeadingStrategy +{ +public: /*! - * A meta-beading-strategy that takes outer and inner wall widths into account. - * - * The outer wall will try to keep a constant width by only applying the beading strategy on the inner walls. This - * ensures that this outer wall doesn't react to changes happening to inner walls. It will limit print artifacts on - * the surface of the print. Although this strategy technically deviates from the original philosophy of the paper. - * It will generally results in better prints because of a smoother motion and less variation in extrusion width in - * the outer walls. - * - * If the thickness of the model is less then two times the optimal outer wall width and once the minimum inner wall - * width it will keep the minimum inner wall at a minimum constant and vary the outer wall widths symmetrical. Until - * The thickness of the model is that of at least twice the optimal outer wall width it will then use two - * symmetrical outer walls only. Until it transitions into a single outer wall. These last scenario's are always - * symmetrical in nature, disregarding the user specified strategy. + * /param optimal_width_outer Outer wall width, guaranteed to be the actual (save rounding errors) at a + * bead count if the parent strategies' optimum bead width is a weighted + * average of the outer and inner walls at that bead count. + * /param minimum_variable_line_ratio Minimum factor that the variable line might deviate from the optimal width. */ - class RedistributeBeadingStrategy : public BeadingStrategy - { - public: - /*! - * /param optimal_width_outer Outer wall width, guaranteed to be the actual (save rounding errors) at a - * bead count if the parent strategies' optimum bead width is a weighted - * average of the outer and inner walls at that bead count. - * /param minimum_variable_line_ratio Minimum factor that the variable line might deviate from the optimal width. - */ - RedistributeBeadingStrategy - ( - const coord_t optimal_width_outer, - const Ratio minimum_variable_line_ratio, - BeadingStrategyPtr parent - ); + RedistributeBeadingStrategy(const coord_t optimal_width_outer, const Ratio minimum_variable_line_ratio, BeadingStrategyPtr parent); - virtual ~RedistributeBeadingStrategy() override = default; + virtual ~RedistributeBeadingStrategy() override = default; - Beading compute(coord_t thickness, coord_t bead_count) const override; + Beading compute(coord_t thickness, coord_t bead_count) const override; - coord_t getOptimalThickness(coord_t bead_count) const override; - coord_t getTransitionThickness(coord_t lower_bead_count) const override; - coord_t getOptimalBeadCount(coord_t thickness) const override; - coord_t getTransitioningLength(coord_t lower_bead_count) const override; - float getTransitionAnchorPos(coord_t lower_bead_count) const override; + coord_t getOptimalThickness(coord_t bead_count) const override; + coord_t getTransitionThickness(coord_t lower_bead_count) const override; + coord_t getOptimalBeadCount(coord_t thickness) const override; + coord_t getTransitioningLength(coord_t lower_bead_count) const override; + double getTransitionAnchorPos(coord_t lower_bead_count) const override; - virtual std::string toString() const; + virtual std::string toString() const; - protected: - /*! - * Determine the outer bead width. - * - * According to the following logic: - * - If the thickness of the model is more then twice the optimal outer bead width and the minimum inner bead - * width it will return the optimal outer bead width. - * - If the thickness is less then twice the optimal outer bead width and the minimum inner bead width, but - * more them twice the optimal outer bead with it will return the optimal bead width minus half the inner bead - * width. - * - If the thickness is less then twice the optimal outer bead width it will return half the thickness as - * outer bead width - * - * \param thickness Thickness of the total beads. - * \param optimal_width_outer User specified optimal outer bead width. - * \param minimum_width_inner Inner bead width times the minimum variable line width. - * \return The outer bead width. - */ - static coord_t getOptimalOuterBeadWidth(coord_t thickness, coord_t optimal_width_outer, coord_t minimum_width_inner); +protected: + /*! + * Determine the outer bead width. + * + * According to the following logic: + * - If the thickness of the model is more then twice the optimal outer bead width and the minimum inner bead + * width it will return the optimal outer bead width. + * - If the thickness is less then twice the optimal outer bead width and the minimum inner bead width, but + * more them twice the optimal outer bead with it will return the optimal bead width minus half the inner bead + * width. + * - If the thickness is less then twice the optimal outer bead width it will return half the thickness as + * outer bead width + * + * \param thickness Thickness of the total beads. + * \param optimal_width_outer User specified optimal outer bead width. + * \param minimum_width_inner Inner bead width times the minimum variable line width. + * \return The outer bead width. + */ + static coord_t getOptimalOuterBeadWidth(coord_t thickness, coord_t optimal_width_outer, coord_t minimum_width_inner); - /*! - * Moves the beads towards the outer edges of thickness and ensures that the outer walls are locked in location - * \param beading The beading instance. - * \param thickness The thickness of the bead. - */ - static void resetToolPathLocations(Beading& beading, coord_t thickness); + /*! + * Moves the beads towards the outer edges of thickness and ensures that the outer walls are locked in location + * \param beading The beading instance. + * \param thickness The thickness of the bead. + */ + static void resetToolPathLocations(Beading& beading, coord_t thickness); - /*! - * Filters and validates the beads, to ensure that all inner beads are at least the minimum bead width. - * - * \param beading The beading instance. - * \param minimum_width_inner Inner bead width times the minimum variable line width. - * \return true if beads are removed. - */ - static bool validateInnerBeadWidths(Beading& beading, coord_t minimum_width_inner); + /*! + * Filters and validates the beads, to ensure that all inner beads are at least the minimum bead width. + * + * \param beading The beading instance. + * \param minimum_width_inner Inner bead width times the minimum variable line width. + * \return true if beads are removed. + */ + static bool validateInnerBeadWidths(Beading& beading, coord_t minimum_width_inner); - BeadingStrategyPtr parent; - coord_t optimal_width_outer; - Ratio minimum_variable_line_ratio; - }; + BeadingStrategyPtr parent; + coord_t optimal_width_outer; + Ratio minimum_variable_line_ratio; +}; } // namespace cura #endif // INWARD_DISTRIBUTED_BEADING_STRATEGY_H diff --git a/include/BeadingStrategy/WideningBeadingStrategy.h b/include/BeadingStrategy/WideningBeadingStrategy.h index 86ea45e616..5ec9bf4cad 100644 --- a/include/BeadingStrategy/WideningBeadingStrategy.h +++ b/include/BeadingStrategy/WideningBeadingStrategy.h @@ -1,5 +1,5 @@ -//Copyright (c) 2020 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2020 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef WIDENING_BEADING_STRATEGY_H #define WIDENING_BEADING_STRATEGY_H @@ -32,7 +32,7 @@ class WideningBeadingStrategy : public BeadingStrategy virtual coord_t getTransitionThickness(coord_t lower_bead_count) const override; virtual coord_t getOptimalBeadCount(coord_t thickness) const override; virtual coord_t getTransitioningLength(coord_t lower_bead_count) const override; - virtual float getTransitionAnchorPos(coord_t lower_bead_count) const override; + virtual double getTransitionAnchorPos(coord_t lower_bead_count) const override; virtual std::vector getNonlinearThicknesses(coord_t lower_bead_count) const override; virtual std::string toString() const override; diff --git a/include/LayerPlan.h b/include/LayerPlan.h index 4ad62a6584..a4b639030a 100644 --- a/include/LayerPlan.h +++ b/include/LayerPlan.h @@ -298,7 +298,7 @@ class LayerPlan : public NoCopy /*! * Plan a prime blob at the current location. */ - void planPrime(const float& prime_blob_wipe_length = 10.0); + void planPrime(double prime_blob_wipe_length = 10.0); /*! * Add an extrusion move to a certain point, optionally with a different flow than the one in the \p config. @@ -414,9 +414,9 @@ class LayerPlan : public NoCopy const Settings& settings, const GCodePathConfig& non_bridge_config, const GCodePathConfig& bridge_config, - float flow, + double flow, const Ratio width_factor, - float& non_bridge_line_volume, + double& non_bridge_line_volume, Ratio speed_factor, double distance_to_bridge_start); @@ -442,7 +442,7 @@ class LayerPlan : public NoCopy const GCodePathConfig& non_bridge_config, const GCodePathConfig& bridge_config, coord_t wall_0_wipe_dist, - float flow_ratio, + double flow_ratio, bool always_retract); /*! @@ -471,7 +471,7 @@ class LayerPlan : public NoCopy const GCodePathConfig& non_bridge_config, const GCodePathConfig& bridge_config, coord_t wall_0_wipe_dist, - float flow_ratio, + double flow_ratio, bool always_retract, const bool is_closed, const bool is_reversed, @@ -504,7 +504,7 @@ class LayerPlan : public NoCopy const GCodePathConfig& bridge_config, const ZSeamConfig& z_seam_config = ZSeamConfig(), coord_t wall_0_wipe_dist = 0, - float flow_ratio = 1.0, + double flow_ratio = 1.0, bool always_retract = false); /*! diff --git a/include/PathOrderOptimizer.h b/include/PathOrderOptimizer.h index ee2ab5102e..8a46854aed 100644 --- a/include/PathOrderOptimizer.h +++ b/include/PathOrderOptimizer.h @@ -647,21 +647,21 @@ class PathOrderOptimizer } size_t best_i; - float best_score = std::numeric_limits::infinity(); + double best_score = std::numeric_limits::infinity(); for (const auto& [i, here] : **path.converted_ | ranges::views::drop_last(1) | ranges::views::enumerate) { // For most seam types, the shortest distance matters. Not for SHARPEST_CORNER though. // For SHARPEST_CORNER, use a fixed starting score of 0. const coord_t distance = (combing_boundary_ == nullptr) ? getDirectDistance(here, target_pos) : getCombingDistance(here, target_pos); - const float score_distance = (seam_config_.type == EZSeamType::SHARPEST_CORNER && seam_config_.corner_pref != EZSeamCornerPrefType::Z_SEAM_CORNER_PREF_NONE) - ? MM2INT(10) - : vSize2(here - target_pos); + const double score_distance = (seam_config_.type == EZSeamType::SHARPEST_CORNER && seam_config_.corner_pref != EZSeamCornerPrefType::Z_SEAM_CORNER_PREF_NONE) + ? MM2INT(10) + : vSize2(here - target_pos); - float corner_angle = cornerAngle(path, i, segments_sizes, total_length); + double corner_angle = cornerAngle(path, i, segments_sizes, total_length); // angles < 0 are concave (left turning) // angles > 0 are convex (right turning) - float corner_shift; + double corner_shift; if (seam_config_.type == EZSeamType::SHORTEST) { // the more a corner satisfies our criteria, the closer it appears to be @@ -677,7 +677,7 @@ class PathOrderOptimizer corner_shift = score_distance / 50; } - float score = score_distance; + double score = score_distance; switch (seam_config_.corner_pref) { default: @@ -696,7 +696,7 @@ class PathOrderOptimizer break; case EZSeamCornerPrefType::Z_SEAM_CORNER_PREF_WEIGHTED: // Give sharper corners some advantage, but sharper concave corners even more. { - float score_corner = std::abs(corner_angle) * corner_shift; + double score_corner = std::abs(corner_angle) * corner_shift; if (corner_angle < 0) // Concave corner. { score_corner *= 2; @@ -706,7 +706,7 @@ class PathOrderOptimizer } } - constexpr float EPSILON = 5.0; + constexpr double EPSILON = 5.0; if (std::abs(best_score - score) <= EPSILON) { // add breaker for two candidate starting location with similar score @@ -797,16 +797,16 @@ class PathOrderOptimizer * \param angle_query_distance query range (default to 1mm) * \return angle between the reference point and the two sibling points, weighed to [-1.0 ; 1.0] */ - static float cornerAngle(const OrderablePath& path, int i, const std::vector& segments_sizes, coord_t total_length, const coord_t angle_query_distance = 1000) + static double cornerAngle(const OrderablePath& path, int i, const std::vector& segments_sizes, coord_t total_length, const coord_t angle_query_distance = 1000) { const coord_t bounded_distance = std::min(angle_query_distance, total_length / 2); const Point& here = (*path.converted_)[i]; const Point next = findNeighbourPoint(path, i, bounded_distance, segments_sizes); const Point previous = findNeighbourPoint(path, i, -bounded_distance, segments_sizes); - float angle = LinearAlg2D::getAngleLeft(previous, here, next) - std::numbers::pi_v; + double angle = LinearAlg2D::getAngleLeft(previous, here, next) - std::numbers::pi; - return angle / std::numbers::pi_v; + return angle / std::numbers::pi; } /*! diff --git a/include/SkeletalTrapezoidationJoint.h b/include/SkeletalTrapezoidationJoint.h index fc27526f1f..0c596b6599 100644 --- a/include/SkeletalTrapezoidationJoint.h +++ b/include/SkeletalTrapezoidationJoint.h @@ -4,11 +4,11 @@ #ifndef SKELETAL_TRAPEZOIDATION_JOINT_H #define SKELETAL_TRAPEZOIDATION_JOINT_H +#include // smart pointers + #include "BeadingStrategy/BeadingStrategy.h" #include "utils/IntPoint.h" -#include // smart pointers - namespace cura { @@ -34,8 +34,8 @@ class SkeletalTrapezoidationJoint coord_t distance_to_boundary_; coord_t bead_count_; - float transition_ratio_; //! The distance near the skeleton to leave free because this joint is in the middle of a transition, as a fraction of the inner bead width of the bead - //! at the higher transition. + double transition_ratio_; //! The distance near the skeleton to leave free because this joint is in the middle of a transition, as a fraction of the inner bead width of the + //! bead at the higher transition. SkeletalTrapezoidationJoint() : distance_to_boundary_(-1) , bead_count_(-1) diff --git a/include/communication/ArcusCommunication.h b/include/communication/ArcusCommunication.h index 7cc7679535..37855fa368 100644 --- a/include/communication/ArcusCommunication.h +++ b/include/communication/ArcusCommunication.h @@ -8,11 +8,11 @@ #ifdef BUILD_TESTS #include #endif +#include //For unique_ptr and shared_ptr. + #include "Communication.h" //The class we're implementing. #include "Cura.pb.h" //To create Protobuf messages for Cura's front-end. -#include //For unique_ptr and shared_ptr. - // Forward declarations to speed up compilation. namespace Arcus { @@ -177,7 +177,7 @@ class ArcusCommunication : public Communication /* * \brief Communicate to Arcus what our progress is. */ - void sendProgress(const float& progress) const override; + void sendProgress(double progress) const override; /* * \brief Set which extruder is being used for the following calls to diff --git a/include/communication/CommandLine.h b/include/communication/CommandLine.h index 2948241c51..fbae3e3010 100644 --- a/include/communication/CommandLine.h +++ b/include/communication/CommandLine.h @@ -4,13 +4,13 @@ #ifndef COMMANDLINE_H #define COMMANDLINE_H -#include "Communication.h" //The class we're implementing. - #include //Loading JSON documents to get settings from them. #include //To store the command line arguments. #include #include //To store the command line arguments. +#include "Communication.h" //The class we're implementing. + namespace cura { class Settings; @@ -125,7 +125,7 @@ class CommandLine : public Communication /* * \brief Show an update of our slicing progress. */ - void sendProgress(const float& progress) const override; + void sendProgress(double progress) const override; /* * \brief Set which extruder is being used for the following calls to @@ -216,4 +216,4 @@ class CommandLine : public Communication } // namespace cura -#endif // COMMANDLINE_H \ No newline at end of file +#endif // COMMANDLINE_H diff --git a/include/communication/Communication.h b/include/communication/Communication.h index bdd68b9630..48186c133b 100644 --- a/include/communication/Communication.h +++ b/include/communication/Communication.h @@ -49,7 +49,7 @@ class Communication * \brief Indicate to the communication channel what the current progress of * slicing the current slice is. */ - virtual void sendProgress(const float& progress) const = 0; + virtual void sendProgress(double progress) const = 0; /* * \brief Indicate to the communication channel that a layer is complete and diff --git a/include/infill.h b/include/infill.h index d8d2f83768..806d5b89b5 100644 --- a/include/infill.h +++ b/include/infill.h @@ -447,7 +447,7 @@ class Infill * \param angle_shift The angle to add to the infill_angle * \param[out] result (output) The resulting lines */ - void generateHalfTetrahedralInfill(float pattern_z_shift, int angle_shift, Polygons& result); + void generateHalfTetrahedralInfill(double pattern_z_shift, int angle_shift, Polygons& result); /*! * Generate a triangular grid of infill lines diff --git a/include/infill/DensityProvider.h b/include/infill/DensityProvider.h index 12af6eb333..7174a8d1fb 100644 --- a/include/infill/DensityProvider.h +++ b/include/infill/DensityProvider.h @@ -1,6 +1,6 @@ -//Copyright (c) 2017 Tim Kuipers -//Copyright (c) 2018 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2017 Tim Kuipers +// Copyright (c) 2018 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef INFILL_DENSITY_PROVIDER_H #define INFILL_DENSITY_PROVIDER_H @@ -12,7 +12,7 @@ struct AABB3D; /*! * Parent class of function objects which return the density required for a given region. - * + * * This density requirement can be based on user input, distance to the 3d model shell, Z distance to top skin, etc. */ class DensityProvider @@ -21,10 +21,10 @@ class DensityProvider /*! * \return the approximate required density of a cube */ - virtual float operator()(const AABB3D& aabb) const = 0; + virtual double operator()(const AABB3D& aabb) const = 0; virtual ~DensityProvider() { - }; + } }; } // namespace cura diff --git a/include/infill/ImageBasedDensityProvider.h b/include/infill/ImageBasedDensityProvider.h index c27b142a45..cd5e8afb37 100644 --- a/include/infill/ImageBasedDensityProvider.h +++ b/include/infill/ImageBasedDensityProvider.h @@ -1,12 +1,11 @@ -//Copyright (c) 2017 Tim Kuipers -//Copyright (c) 2018 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2017 Tim Kuipers +// Copyright (c) 2018 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef INFILL_IMAGE_BASED_DENSITY_PROVIDER_H #define INFILL_IMAGE_BASED_DENSITY_PROVIDER_H #include "../utils/AABB.h" - #include "DensityProvider.h" namespace cura @@ -21,7 +20,7 @@ class ImageBasedDensityProvider : public DensityProvider virtual ~ImageBasedDensityProvider(); - virtual float operator()(const AABB3D& aabb) const; + virtual double operator()(const AABB3D& aabb) const; protected: Point3 image_size; //!< dimensions of the image. Third dimension is the amount of channels. diff --git a/include/infill/SierpinskiFill.h b/include/infill/SierpinskiFill.h index f5603bd509..1c8569cb0a 100644 --- a/include/infill/SierpinskiFill.h +++ b/include/infill/SierpinskiFill.h @@ -257,12 +257,12 @@ class SierpinskiFill const bool straight_corner_is_left_; //!< Whether the \ref straight_corner is left of the curve, rather than right. I.e. whether triangle ABC is counter-clockwise const int depth_; //!< The recursion depth at which this triangle is generated. Root is zero. - float area_; //!< The area of the triangle in mm^2 - float requested_length_; //!< The polyline length corresponding to the average density requested by the volumetric density specification. - float realized_length_; //!< The polyline length of the Cross Fractal line segment which would cross this triangle. - float total_child_realized_length_; //!< The total of the \ref realized_length of all children. - float error_left_; //!< Extra value modulating the \ref requested_length obtained from the triangle on the left / obtained by giving value to the triangle to the left. - float error_right_; //!< Extra value modulating the \ref requested_length obtained from the triangle on the right / obtained by giving value to the triangle to the right. + double area_; //!< The area of the triangle in mm^2 + double requested_length_; //!< The polyline length corresponding to the average density requested by the volumetric density specification. + double realized_length_; //!< The polyline length of the Cross Fractal line segment which would cross this triangle. + double total_child_realized_length_; //!< The total of the \ref realized_length of all children. + double error_left_; //!< Extra value modulating the \ref requested_length obtained from the triangle on the left / obtained by giving value to the triangle to the left. + double error_right_; //!< Extra value modulating the \ref requested_length obtained from the triangle on the right / obtained by giving value to the triangle to the right. SierpinskiTriangle(Point straight_corner, Point a, Point b, SierpinskiDirection dir, bool straight_corner_is_left, int depth) : straight_corner_(straight_corner) @@ -296,13 +296,13 @@ class SierpinskiFill //! Get the second edge of this triangle crossed by the Sierpinski and/or Cross Fractal curve. Edge getToEdge(); //! Get the total error value modulating the \ref requested_length - float getTotalError(); + double getTotalError(); //! Get the total modulated \ref requested_length - float getErroredValue(); + double getErroredValue(); //! Get the error induced by subdividing this triangle. - float getSubdivisionError(); + double getSubdivisionError(); //! Get the total error currently acting on this traingle. - float getValueError(); + double getValueError(); //! The children into which this triangle would be subdivided. Empty if this is a leaf node. std::vector children; }; @@ -447,7 +447,7 @@ class SierpinskiFill /*! * \return the requested value left over if we would subdivide all nodes in the sequence from \p begin to \p end */ - float getSubdivisionError(std::list::iterator begin, std::list::iterator end); + double getSubdivisionError(std::list::iterator begin, std::list::iterator end); /*! * Check whether all properties which should hold at any time during the algorithm hold for the current sequence. diff --git a/include/infill/UniformDensityProvider.h b/include/infill/UniformDensityProvider.h index be8c70e277..cf7fae5d03 100644 --- a/include/infill/UniformDensityProvider.h +++ b/include/infill/UniformDensityProvider.h @@ -1,5 +1,5 @@ -//Copyright (c) 2018 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2018 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef INFILL_UNIFORM_DENSITY_PROVIDER_H #define INFILL_UNIFORM_DENSITY_PROVIDER_H @@ -14,21 +14,22 @@ struct AABB3D; class UniformDensityProvider : public DensityProvider { public: - UniformDensityProvider(float density) - : density_(density) + UniformDensityProvider(double density) + : density_(density) { - }; + } virtual ~UniformDensityProvider() { - }; + } - virtual float operator()(const AABB3D&) const + virtual double operator()(const AABB3D&) const { return density_; - }; + } + protected: - float density_; + double density_; }; } // namespace cura diff --git a/include/mesh.h b/include/mesh.h index 8a48c41e28..dedb1ed311 100644 --- a/include/mesh.h +++ b/include/mesh.h @@ -1,12 +1,11 @@ -//Copyright (c) 2018 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2018 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef MESH_H #define MESH_H #include "settings/Settings.h" #include "utils/AABB3D.h" -#include "utils/floatpoint.h" #include "utils/FMatrix4x3.h" namespace cura @@ -22,7 +21,11 @@ class MeshVertex Point3 p_; //!< location of the vertex std::vector connected_faces_; //!< list of the indices of connected faces - MeshVertex(Point3 p) : p_(p) {connected_faces_.reserve(8);} //!< doesn't set connected_faces + MeshVertex(Point3 p) + : p_(p) + { + connected_faces_.reserve(8); + } //!< doesn't set connected_faces }; /*! A MeshFace is a 3 dimensional model triangle with 3 points. These points are already converted to integers @@ -49,7 +52,7 @@ In such a case the face_index stored in connected_face_index is the one connecte class MeshFace { public: - int vertex_index_[3] = {-1}; //!< counter-clockwise ordering + int vertex_index_[3] = { -1 }; //!< counter-clockwise ordering int connected_face_index_[3]; //!< same ordering as vertex_index (connected_face 0 is connected via vertex 0 and 1, etc.) }; @@ -62,10 +65,11 @@ See MeshFace for the specifics of how/when faces are connected. class Mesh { //! The vertex_hash_map stores a index reference of each vertex for the hash of that location. Allows for quick retrieval of points with the same location. - std::unordered_map > vertex_hash_map_; + std::unordered_map> vertex_hash_map_; AABB3D aabb_; + public: - std::vector vertices_;//!< list of all vertices in the mesh + std::vector vertices_; //!< list of all vertices in the mesh std::vector faces_; //!< list of all faces in the mesh Settings settings_; std::string mesh_name_; @@ -81,15 +85,18 @@ class Mesh Point3 max() const; //!< max (in x,y and z) vertex of the bounding box AABB3D getAABB() const; //!< Get the axis aligned bounding box void expandXY(int64_t offset); //!< Register applied horizontal expansion in the AABB - + /*! * Offset the whole mesh (all vertices and the bounding box). * \param offset The offset byu which to offset the whole mesh. */ void translate(Point3 offset) { - if (offset == Point3(0,0,0)) { return; } - for(MeshVertex& v : vertices_) + if (offset == Point3(0, 0, 0)) + { + return; + } + for (MeshVertex& v : vertices_) v.p_ += offset; aabb_.translate(offset); } @@ -115,6 +122,7 @@ class Mesh * \return True if an interface of the mesh could be interlocking with another mesh */ bool canInterlock() const; + private: mutable bool has_disconnected_faces; //!< Whether it has been logged that this mesh contains disconnected faces mutable bool has_overlapping_faces; //!< Whether it has been logged that this mesh contains overlapping faces @@ -122,18 +130,17 @@ class Mesh /*! * Get the index of the face connected to the face with index \p notFaceIdx, via vertices \p idx0 and \p idx1. - * + * * In case multiple faces connect with the same edge, return the next counter-clockwise face when viewing from \p idx1 to \p idx0. - * + * * \param idx0 the first vertex index * \param idx1 the second vertex index * \param notFaceIdx the index of a face which shouldn't be returned * \param notFaceVertexIdx should be the third vertex of face \p notFaceIdx. * \return the face index of a face sharing the edge from \p idx0 to \p idx1 - */ + */ int getFaceIdxWithPoints(int idx0, int idx1, int notFaceIdx, int notFaceVertexIdx) const; }; -}//namespace cura -#endif//MESH_H - +} // namespace cura +#endif // MESH_H diff --git a/include/utils/ExtrusionSegment.h b/include/utils/ExtrusionSegment.h index 8c97b04215..318c2e25cf 100644 --- a/include/utils/ExtrusionSegment.h +++ b/include/utils/ExtrusionSegment.h @@ -23,15 +23,16 @@ namespace cura */ class ExtrusionSegment { - static constexpr float a_step = 15 / 180.0 * std::numbers::pi; //!< In the calculation of the area covered by this line, the angle between line segments of the round endcaps. + static constexpr double a_step = 15 / 180.0 * std::numbers::pi; //!< In the calculation of the area covered by this line, the angle between line segments of the round endcaps. + public: - ExtrusionJunction from; - ExtrusionJunction to; + ExtrusionJunction from_; + ExtrusionJunction to_; /*! * Whether this is a polyline segment rather than a polygonal segment. */ - bool is_odd; + bool is_odd_; /*! * In the \ref toPolygons function, should the endcap at the to-location be @@ -40,13 +41,13 @@ class ExtrusionSegment * If the segment is reduced, a circle is removed from the to-location * because it will be included in the next extrusion move's covered area. */ - bool is_reduced; + bool is_reduced_; ExtrusionSegment(ExtrusionJunction from, ExtrusionJunction to, bool is_odd, bool is_reduced) - : from(from) - , to(to) - , is_odd(is_odd) - , is_reduced(is_reduced) + : from_(from) + , to_(to) + , is_odd_(is_odd) + , is_reduced_(is_reduced) { } diff --git a/include/utils/FMatrix4x3.h b/include/utils/FMatrix4x3.h index 64d44138ca..fff6838beb 100644 --- a/include/utils/FMatrix4x3.h +++ b/include/utils/FMatrix4x3.h @@ -9,7 +9,7 @@ namespace cura { -class FPoint3; +class Point3d; class Point3; /*! @@ -51,7 +51,7 @@ class FMatrix4x3 * \param p The coordinate to transform. * \return A transformed coordinate. */ - Point3 apply(const FPoint3& p) const; + Point3 apply(const Point3d& p) const; /*! * Apply this transformation to a coordinate. diff --git a/include/utils/IntPoint.h b/include/utils/IntPoint.h index 1e4f5cabee..6b35405074 100644 --- a/include/utils/IntPoint.h +++ b/include/utils/IntPoint.h @@ -116,9 +116,9 @@ INLINE coord_t vSize2(const Point& p0) { return p0.X * p0.X + p0.Y * p0.Y; } -INLINE float vSize2f(const Point& p0) +INLINE double vSize2f(const Point& p0) { - return static_cast(p0.X) * static_cast(p0.X) + static_cast(p0.Y) * static_cast(p0.Y); + return static_cast(p0.X) * static_cast(p0.X) + static_cast(p0.Y) * static_cast(p0.Y); } INLINE bool shorterThen(const Point& p0, const coord_t len) diff --git a/include/utils/Point3d.h b/include/utils/Point3d.h new file mode 100644 index 0000000000..713926cc40 --- /dev/null +++ b/include/utils/Point3d.h @@ -0,0 +1,142 @@ +// Copyright (c) 2020 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. + +#ifndef POINT3D_H +#define POINT3D_H + +#include +#include + +#include "IntPoint.h" + + +namespace cura +{ + +/* +Double-precision 3D points are used for geometry computation. +They represent millimeters in 3D space. +*/ +class Point3d +{ +public: + double x, y, z; + + Point3d() + { + } + + Point3d(double _x, double _y, double _z) + : x(_x) + , y(_y) + , z(_z) + { + } + + Point3d(const Point3& p) + : x(static_cast(p.x_) * .001) + , y(static_cast(p.y_) * .001) + , z(static_cast(p.z_) * .001) + { + } + + Point3d operator+(const Point3d& p) const + { + return Point3d(x + p.x, y + p.y, z + p.z); + } + Point3d operator-(const Point3d& p) const + { + return Point3d(x - p.x, y - p.y, z - p.z); + } + Point3d operator*(const double f) const + { + return Point3d(x * f, y * f, z * f); + } + Point3d operator/(const double f) const + { + return Point3d(x / f, y / f, z / f); + } + + Point3d& operator+=(const Point3d& p) + { + x += p.x; + y += p.y; + z += p.z; + return *this; + } + Point3d& operator-=(const Point3d& p) + { + x -= p.x; + y -= p.y; + z -= p.z; + return *this; + } + Point3d& operator*=(const double f) + { + x *= f; + y *= f; + z *= f; + return *this; + } + + bool operator==(Point3d& p) const + { + return x == p.x && y == p.y && z == p.z; + } + bool operator!=(Point3d& p) const + { + return x != p.x || y != p.y || z != p.z; + } + + double max() const + { + if (x > y && x > z) + return x; + if (y > z) + return y; + return z; + } + + bool testLength(double len) const + { + return vSize2() <= len * len; + } + + double vSize2() const + { + return x * x + y * y + z * z; + } + + double vSize() const + { + return sqrt(vSize2()); + } + + inline Point3d normalized() const + { + return (*this) / vSize(); + } + + Point3d cross(const Point3d& p) const + { + return Point3d(y * p.z - z * p.y, z * p.x - x * p.z, x * p.y - y * p.x); + } + + static Point3d cross(const Point3& a, const Point3& b) + { + return Point3d(a).cross(Point3d(b)); + } + + Point3 toPoint3() + { + return Point3(MM2INT(x), MM2INT(y), MM2INT(z)); + } +}; + +inline double operator*(Point3d lhs, const Point3d& rhs) +{ + return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z; +} + +} // namespace cura +#endif // POINT3D_H diff --git a/include/utils/Point3f.h b/include/utils/Point3f.h new file mode 100644 index 0000000000..dd93519199 --- /dev/null +++ b/include/utils/Point3f.h @@ -0,0 +1,45 @@ +// Copyright (c) 2020 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. + +#ifndef POINT3F_H +#define POINT3F_H + +#include +#include + +#include "IntPoint.h" +#include "Point3d.h" + + +namespace cura +{ + +/* +Floating point 3D points are used during model loading as 3D vectors. +They represent millimeters in 3D space. +This class should not be used for geometric computation. Use Point3d for this purpose. +*/ +class Point3f +{ +public: + float x, y, z; + + Point3f() + { + } + + Point3f(double _x, double _y, double _z) + : x(_x) + , y(_y) + , z(_z) + { + } + + Point3d toPoint3d() const + { + return Point3d(static_cast(x), static_cast(y), static_cast(z)); + } +}; + +} // namespace cura +#endif // POINT3F_H diff --git a/include/utils/SVG.h b/include/utils/SVG.h index 8257e7e959..400a02010a 100644 --- a/include/utils/SVG.h +++ b/include/utils/SVG.h @@ -14,7 +14,7 @@ namespace cura { -class FPoint3; +class Point3d; class SVG : NoCopy { @@ -92,19 +92,19 @@ class SVG : NoCopy /*! * transform a point in real space to canvas space with more precision */ - FPoint3 transformF(const Point& p) const; + Point3d transformF(const Point& p) const; void writeComment(const std::string& comment) const; - void writeAreas(const Polygons& polygons, const ColorObject color = Color::GRAY, const ColorObject outline_color = Color::BLACK, const float stroke_width = 1.0f) const; + void writeAreas(const Polygons& polygons, const ColorObject color = Color::GRAY, const ColorObject outline_color = Color::BLACK, const double stroke_width = 1.0) const; - void writeAreas(ConstPolygonRef polygon, const ColorObject color = Color::GRAY, const ColorObject outline_color = Color::BLACK, const float stroke_width = 1.0f) const; + void writeAreas(ConstPolygonRef polygon, const ColorObject color = Color::GRAY, const ColorObject outline_color = Color::BLACK, const double stroke_width = 1.0) const; - void writePoint(const Point& p, const bool write_coords = false, const float size = 5.0f, const ColorObject color = Color::BLACK) const; + void writePoint(const Point& p, const bool write_coords = false, const double size = 5.0, const ColorObject color = Color::BLACK) const; - void writePoints(ConstPolygonRef poly, const bool write_coords = false, const float size = 5.0f, const ColorObject color = Color::BLACK) const; + void writePoints(ConstPolygonRef poly, const bool write_coords = false, const double size = 5.0, const ColorObject color = Color::BLACK) const; - void writePoints(const Polygons& polygons, const bool write_coords = false, const float size = 5.0f, const ColorObject color = Color::BLACK) const; + void writePoints(const Polygons& polygons, const bool write_coords = false, const double size = 5.0, const ColorObject color = Color::BLACK) const; /*! * \brief Draws a polyline on the canvas. @@ -119,11 +119,11 @@ class SVG : NoCopy */ void writeLines(const std::vector& polyline, const ColorObject color = Color::BLACK) const; - void writeLine(const Point& a, const Point& b, const ColorObject color = Color::BLACK, const float stroke_width = 1.0f) const; + void writeLine(const Point& a, const Point& b, const ColorObject color = Color::BLACK, const double stroke_width = 1.0) const; - void writeArrow(const Point& a, const Point& b, const ColorObject color = Color::BLACK, const float stroke_width = 1.0f, const float head_size = 5.0f) const; + void writeArrow(const Point& a, const Point& b, const ColorObject color = Color::BLACK, const double stroke_width = 1.0, const double head_size = 5.0) const; - void writeLineRGB(const Point& from, const Point& to, const int r = 0, const int g = 0, const int b = 0, const float stroke_width = 1.0f) const; + void writeLineRGB(const Point& from, const Point& to, const int r = 0, const int g = 0, const int b = 0, const double stroke_width = 1.0) const; /*! * \brief Draws a dashed line on the canvas from point A to point B. @@ -139,15 +139,15 @@ class SVG : NoCopy template void printf(const char* txt, Args&&... args) const; - void writeText(const Point& p, const std::string& txt, const ColorObject color = Color::BLACK, const float font_size = 10.0f) const; + void writeText(const Point& p, const std::string& txt, const ColorObject color = Color::BLACK, const double font_size = 10.0) const; - void writePolygons(const Polygons& polys, const ColorObject color = Color::BLACK, const float stroke_width = 1.0f) const; + void writePolygons(const Polygons& polys, const ColorObject color = Color::BLACK, const double stroke_width = 1.0) const; - void writePolygon(ConstPolygonRef poly, const ColorObject color = Color::BLACK, const float stroke_width = 1.0f) const; + void writePolygon(ConstPolygonRef poly, const ColorObject color = Color::BLACK, const double stroke_width = 1.0) const; - void writePolylines(const Polygons& polys, const ColorObject color = Color::BLACK, const float stroke_width = 1.0f) const; + void writePolylines(const Polygons& polys, const ColorObject color = Color::BLACK, const double stroke_width = 1.0) const; - void writePolyline(ConstPolygonRef poly, const ColorObject color = Color::BLACK, const float stroke_width = 1.0f) const; + void writePolyline(ConstPolygonRef poly, const ColorObject color = Color::BLACK, const double stroke_width = 1.0) const; /*! * Draw variable-width paths into the image. @@ -158,7 +158,7 @@ class SVG : NoCopy * \param color The color to draw the paths with. * \param width_factor A multiplicative factor on the line widths. */ - void writePaths(const std::vector& paths, const ColorObject color = Color::BLACK, const float width_factor = 1.0f) const; + void writePaths(const std::vector& paths, const ColorObject color = Color::BLACK, const double width_factor = 1.0) const; /*! * Draw variable-width lines into the image. @@ -169,7 +169,7 @@ class SVG : NoCopy * \param color The color to draw the lines with. * \param width_factor A multiplicative factor on the line widths. */ - void writeLines(const VariableWidthLines& lines, const ColorObject color = Color::BLACK, const float width_factor = 1.0f) const; + void writeLines(const VariableWidthLines& lines, const ColorObject color = Color::BLACK, const double width_factor = 1.0) const; /*! * Draw a variable-width line into the image. @@ -180,7 +180,7 @@ class SVG : NoCopy * \param color The color to draw the line with. * \param width_factor A multiplicative factor on the line width. */ - void writeLine(const ExtrusionLine& line, const ColorObject color = Color::BLACK, const float width_factor = 1.0f) const; + void writeLine(const ExtrusionLine& line, const ColorObject color = Color::BLACK, const double width_factor = 1.0) const; /*! * Draws a grid across the image and writes down coordinates. @@ -191,7 +191,7 @@ class SVG : NoCopy * \param stroke_width The width of the grid lines. * \param font_size The size of the font to write the coordinates with. */ - void writeCoordinateGrid(const coord_t grid_size = MM2INT(1), const Color color = Color::BLACK, const float stroke_width = 0.1f, const float font_size = 10) const; + void writeCoordinateGrid(const coord_t grid_size = MM2INT(1), const Color color = Color::BLACK, const double stroke_width = 0.1, const double font_size = 10.0) const; }; template diff --git a/include/utils/SparseGrid.h b/include/utils/SparseGrid.h index 5b6d10f63f..f31631c206 100644 --- a/include/utils/SparseGrid.h +++ b/include/utils/SparseGrid.h @@ -1,22 +1,23 @@ -//Copyright (c) 2016 Scott Lenser -//Copyright (c) 2018 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2016 Scott Lenser +// Copyright (c) 2018 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef UTILS_SPARSE_GRID_H #define UTILS_SPARSE_GRID_H #include +#include #include #include -#include #include "IntPoint.h" #include "SquareGrid.h" -namespace cura { +namespace cura +{ /*! \brief Sparse grid which can locate spatially nearby elements efficiently. - * + * * \note This is an abstract template class which doesn't have any functions to insert elements. * \see SparsePointGrid * @@ -31,7 +32,7 @@ class SparseGrid : public SquareGrid using GridPoint = SquareGrid::GridPoint; using grid_coord_t = SquareGrid::grid_coord_t; using GridMap = std::unordered_multimap; - + using iterator = typename GridMap::iterator; using const_iterator = typename GridMap::const_iterator; @@ -42,13 +43,13 @@ class SparseGrid : public SquareGrid * \param[in] elem_reserve Number of elements to research space for. * \param[in] max_load_factor Maximum average load factor before rehashing. */ - SparseGrid(coord_t cell_size, size_t elem_reserve=0U, float max_load_factor=1.0f); - + SparseGrid(coord_t cell_size, size_t elem_reserve = 0U, double max_load_factor = 1.0); + iterator begin() { return m_grid.begin(); } - + iterator end() { return m_grid.end(); @@ -58,12 +59,12 @@ class SparseGrid : public SquareGrid { return m_grid.begin(); } - + const_iterator end() const { return m_grid.end(); } - + /*! \brief Returns all data within radius of query_pt. * * Finds all elements with location within radius of \p query_pt. May @@ -79,7 +80,7 @@ class SparseGrid : public SquareGrid * \param[in] radius The search radius. * \return Vector of elements found */ - std::vector getNearby(const Point &query_pt, coord_t radius) const; + std::vector getNearby(const Point& query_pt, coord_t radius) const; static const std::function no_precondition; @@ -93,8 +94,7 @@ class SparseGrid : public SquareGrid * to be considered for output * \return True if and only if an object has been found within the radius. */ - bool getNearest(const Point &query_pt, coord_t radius, Elem &elem_nearest, - const std::function precondition = no_precondition) const; + bool getNearest(const Point& query_pt, coord_t radius, Elem& elem_nearest, const std::function precondition = no_precondition) const; /*! \brief Process elements from cells that might contain sought after points. * @@ -109,8 +109,7 @@ class SparseGrid : public SquareGrid * called for each element in the cell. Processing stops if function returns false. * \return Whether we need to continue processing after this function */ - bool processNearby(const Point &query_pt, coord_t radius, - const std::function& process_func) const; + bool processNearby(const Point& query_pt, coord_t radius, const std::function& process_func) const; /*! \brief Process elements from cells that might contain sought after points along a line. * @@ -122,8 +121,7 @@ class SparseGrid : public SquareGrid * called for each element in the cells. Processing stops if function returns false. * \return Whether we need to continue processing after this function */ - bool processLine(const std::pair query_line, - const std::function& process_elem_func) const; + bool processLine(const std::pair query_line, const std::function& process_elem_func) const; protected: /*! \brief Process elements from the cell indicated by \p grid_pt. @@ -133,38 +131,35 @@ class SparseGrid : public SquareGrid * called for each element in the cell. Processing stops if function returns false. * \return Whether we need to continue processing a next cell. */ - bool processFromCell(const GridPoint &grid_pt, - const std::function& process_func) const; + bool processFromCell(const GridPoint& grid_pt, const std::function& process_func) const; /*! \brief Map from grid locations (GridPoint) to elements (Elem). */ GridMap m_grid; }; - #define SGI_TEMPLATE template #define SGI_THIS SparseGrid SGI_TEMPLATE -SGI_THIS::SparseGrid(coord_t cell_size, size_t elem_reserve, float max_load_factor) -: SquareGrid(cell_size) +SGI_THIS::SparseGrid(coord_t cell_size, size_t elem_reserve, double max_load_factor) + : SquareGrid(cell_size) { // Must be before the reserve call. m_grid.max_load_factor(max_load_factor); - if (elem_reserve != 0U) { + if (elem_reserve != 0U) + { m_grid.reserve(elem_reserve); } } SGI_TEMPLATE -bool SGI_THIS::processFromCell( - const GridPoint &grid_pt, - const std::function& process_func) const +bool SGI_THIS::processFromCell(const GridPoint& grid_pt, const std::function& process_func) const { auto grid_range = m_grid.equal_range(grid_pt); for (auto iter = grid_range.first; iter != grid_range.second; ++iter) { - if (!process_func(iter->second)) + if (! process_func(iter->second)) { return false; } @@ -173,72 +168,66 @@ bool SGI_THIS::processFromCell( } SGI_TEMPLATE -bool SGI_THIS::processNearby(const Point &query_pt, coord_t radius, - const std::function& process_func) const +bool SGI_THIS::processNearby(const Point& query_pt, coord_t radius, const std::function& process_func) const { - return SquareGrid::processNearby(query_pt, radius, - [&process_func, this](const GridPoint& grid_pt) - { - return processFromCell(grid_pt, process_func); - }); + return SquareGrid::processNearby( + query_pt, + radius, + [&process_func, this](const GridPoint& grid_pt) + { + return processFromCell(grid_pt, process_func); + }); } SGI_TEMPLATE -bool SGI_THIS::processLine(const std::pair query_line, - const std::function& process_elem_func) const +bool SGI_THIS::processLine(const std::pair query_line, const std::function& process_elem_func) const { - const std::function process_cell_func = [&process_elem_func, this](GridPoint grid_loc) - { - return processFromCell(grid_loc, process_elem_func); - }; + const std::function process_cell_func = [&process_elem_func, this](GridPoint grid_loc) + { + return processFromCell(grid_loc, process_elem_func); + }; return processLineCells(query_line, process_cell_func); } SGI_TEMPLATE -std::vector -SGI_THIS::getNearby(const Point &query_pt, coord_t radius) const +std::vector SGI_THIS::getNearby(const Point& query_pt, coord_t radius) const { std::vector ret; - const std::function process_func = [&ret](const Elem &elem) - { - ret.push_back(elem); - return true; - }; + const std::function process_func = [&ret](const Elem& elem) + { + ret.push_back(elem); + return true; + }; processNearby(query_pt, radius, process_func); return ret; } SGI_TEMPLATE -const std::function - SGI_THIS::no_precondition = - [](const typename SGI_THIS::Elem &) - { - return true; - }; +const std::function SGI_THIS::no_precondition = [](const typename SGI_THIS::Elem&) +{ + return true; +}; SGI_TEMPLATE -bool SGI_THIS::getNearest( - const Point &query_pt, coord_t radius, Elem &elem_nearest, - const std::function precondition) const +bool SGI_THIS::getNearest(const Point& query_pt, coord_t radius, Elem& elem_nearest, const std::function precondition) const { bool found = false; int64_t best_dist2 = static_cast(radius) * radius; - const std::function process_func = - [&query_pt, &elem_nearest, &found, &best_dist2, &precondition](const Elem &elem) + const std::function process_func = [&query_pt, &elem_nearest, &found, &best_dist2, &precondition](const Elem& elem) + { + if (! precondition(elem)) { - if (!precondition(elem)) - { - return true; - } - int64_t dist2 = vSize2(elem.point - query_pt); - if (dist2 < best_dist2) - { - found = true; - elem_nearest = elem; - best_dist2 = dist2; - } return true; - }; + } + int64_t dist2 = vSize2(elem.point - query_pt); + if (dist2 < best_dist2) + { + found = true; + elem_nearest = elem; + best_dist2 = dist2; + } + return true; + }; processNearby(query_pt, radius, process_func); return found; } diff --git a/include/utils/SparseLineGrid.h b/include/utils/SparseLineGrid.h index 385b129df5..d851664aea 100644 --- a/include/utils/SparseLineGrid.h +++ b/include/utils/SparseLineGrid.h @@ -1,20 +1,21 @@ -//Copyright (c) 2018 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2018 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef UTILS_SPARSE_LINE_GRID_H #define UTILS_SPARSE_LINE_GRID_H #include +#include #include #include -#include #include "IntPoint.h" -#include "SparseGrid.h" #include "SVG.h" // debug +#include "SparseGrid.h" -namespace cura { +namespace cura +{ /*! \brief Sparse grid which can locate spatially nearby elements efficiently. * @@ -36,17 +37,18 @@ class SparseLineGrid : public SparseGrid * \param[in] elem_reserve Number of elements to research space for. * \param[in] max_load_factor Maximum average load factor before rehashing. */ - SparseLineGrid(coord_t cell_size, size_t elem_reserve = 0U, float max_load_factor = 1.0f); + SparseLineGrid(coord_t cell_size, size_t elem_reserve = 0U, double max_load_factor = 1.0); /*! \brief Inserts elem into the sparse grid. * * \param[in] elem The element to be inserted. */ - void insert(const Elem &elem); + void insert(const Elem& elem); void debugHTML(std::string filename); static void debugTest(); + protected: using GridPoint = typename SparseGrid::GridPoint; using grid_coord_t = typename SparseGrid::grid_coord_t; @@ -56,31 +58,30 @@ class SparseLineGrid : public SparseGrid }; - #define SGI_TEMPLATE template #define SGI_THIS SparseLineGrid SGI_TEMPLATE -SGI_THIS::SparseLineGrid(coord_t cell_size, size_t elem_reserve, float max_load_factor) - : SparseGrid(cell_size, elem_reserve, max_load_factor) +SGI_THIS::SparseLineGrid(coord_t cell_size, size_t elem_reserve, double max_load_factor) + : SparseGrid(cell_size, elem_reserve, max_load_factor) { } SGI_TEMPLATE -void SGI_THIS::insert(const Elem &elem) +void SGI_THIS::insert(const Elem& elem) { const std::pair line = m_locator(elem); using GridMap = std::unordered_multimap; // below is a workaround for the fact that lambda functions cannot access private or protected members // first we define a lambda which works on any GridMap and then we bind it to the actual protected GridMap of the parent class - std::function process_cell_func_ = [&elem, this](GridMap* m_grid, const GridPoint grid_loc) - { - m_grid->emplace(grid_loc, elem); - return true; - }; - using namespace std::placeholders; // for _1, _2, _3... + std::function process_cell_func_ = [&elem, this](GridMap* m_grid, const GridPoint grid_loc) + { + m_grid->emplace(grid_loc, elem); + return true; + }; + using namespace std::placeholders; // for _1, _2, _3... GridMap* m_grid = &(this->m_grid); - std::function process_cell_func(std::bind(process_cell_func_, m_grid, _1)); + std::function process_cell_func(std::bind(process_cell_func_, m_grid, _1)); SparseGrid::processLineCells(line, process_cell_func); } @@ -89,13 +90,13 @@ SGI_TEMPLATE void SGI_THIS::debugHTML(std::string filename) { AABB aabb; - for (std::pair cell: SparseGrid::m_grid) + for (std::pair cell : SparseGrid::m_grid) { aabb.include(SparseGrid::toLowerCorner(cell.first)); aabb.include(SparseGrid::toLowerCorner(cell.first + GridPoint(SparseGrid::nonzero_sign(cell.first.X), SparseGrid::nonzero_sign(cell.first.Y)))); } SVG svg(filename.c_str(), aabb); - for (std::pair cell: SparseGrid::m_grid) + for (std::pair cell : SparseGrid::m_grid) { // doesn't draw cells at x = 0 or y = 0 correctly (should be double size) Point lb = SparseGrid::toLowerCorner(cell.first); @@ -112,7 +113,7 @@ void SGI_THIS::debugHTML(std::string filename) lb.Y = -SparseGrid::cell_size_; rb.Y = -SparseGrid::cell_size_; } -// svg.writePoint(lb, true, 1); + // svg.writePoint(lb, true, 1); svg.writeLine(lb, lt, SVG::Color::GRAY); svg.writeLine(lt, rt, SVG::Color::GRAY); svg.writeLine(rt, rb, SVG::Color::GRAY); diff --git a/include/utils/SparsePointGrid.h b/include/utils/SparsePointGrid.h index a61f94051e..214fc1fdc1 100644 --- a/include/utils/SparsePointGrid.h +++ b/include/utils/SparsePointGrid.h @@ -1,6 +1,6 @@ -//Copyright (c) 2016 Scott Lenser -//Copyright (c) 2020 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2016 Scott Lenser +// Copyright (c) 2020 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef UTILS_SPARSE_POINT_GRID_H #define UTILS_SPARSE_POINT_GRID_H @@ -12,7 +12,8 @@ #include "IntPoint.h" #include "SparseGrid.h" -namespace cura { +namespace cura +{ /*! \brief Sparse grid which can locate spatially nearby elements efficiently. * @@ -34,13 +35,13 @@ class SparsePointGrid : public SparseGrid * \param[in] elem_reserve Number of elements to research space for. * \param[in] max_load_factor Maximum average load factor before rehashing. */ - SparsePointGrid(coord_t cell_size, size_t elem_reserve=0U, float max_load_factor=1.0f); + SparsePointGrid(coord_t cell_size, size_t elem_reserve = 0U, double max_load_factor = 1.0); /*! \brief Inserts elem into the sparse grid. * * \param[in] elem The element to be inserted. */ - void insert(const Elem &elem); + void insert(const Elem& elem); /*! * Get just any element that's within a certain radius of a point. @@ -60,38 +61,37 @@ class SparsePointGrid : public SparseGrid }; - #define SGI_TEMPLATE template #define SGI_THIS SparsePointGrid SGI_TEMPLATE -SGI_THIS::SparsePointGrid(coord_t cell_size, size_t elem_reserve, float max_load_factor) - : SparseGrid(cell_size, elem_reserve, max_load_factor) +SGI_THIS::SparsePointGrid(coord_t cell_size, size_t elem_reserve, double max_load_factor) + : SparseGrid(cell_size, elem_reserve, max_load_factor) { } SGI_TEMPLATE -void SGI_THIS::insert(const Elem &elem) +void SGI_THIS::insert(const Elem& elem) { Point loc = m_locator(elem); GridPoint grid_loc = SparseGrid::toGridPoint(loc); - SparseGrid::m_grid.emplace(grid_loc,elem); + SparseGrid::m_grid.emplace(grid_loc, elem); } SGI_TEMPLATE const ElemT* SGI_THIS::getAnyNearby(const Point& query_pt, coord_t radius) { const ElemT* ret = nullptr; - const std::function& process_func = [&ret, query_pt, radius, this](const ElemT& maybe_nearby) + const std::function& process_func = [&ret, query_pt, radius, this](const ElemT& maybe_nearby) + { + if (shorterThen(m_locator(maybe_nearby) - query_pt, radius)) { - if (shorterThen(m_locator(maybe_nearby) - query_pt, radius)) - { - ret = &maybe_nearby; - return false; - } - return true; - }; + ret = &maybe_nearby; + return false; + } + return true; + }; SparseGrid::processNearby(query_pt, radius, process_func); return ret; diff --git a/include/utils/SparsePointGridInclusive.h b/include/utils/SparsePointGridInclusive.h index b7496c65fc..7e4cdce82e 100644 --- a/include/utils/SparsePointGridInclusive.h +++ b/include/utils/SparsePointGridInclusive.h @@ -1,6 +1,6 @@ -//Copyright (c) 2016 Scott Lenser -//Copyright (c) 2018 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2016 Scott Lenser +// Copyright (c) 2018 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef UTILS_SPARSE_POINT_GRID_INCLUSIVE_H #define UTILS_SPARSE_POINT_GRID_INCLUSIVE_H @@ -12,10 +12,12 @@ #include "IntPoint.h" #include "SparsePointGrid.h" -namespace cura { +namespace cura +{ -namespace SparsePointGridInclusiveImpl { +namespace SparsePointGridInclusiveImpl +{ template struct SparsePointGridInclusiveElem @@ -24,9 +26,9 @@ struct SparsePointGridInclusiveElem { } - SparsePointGridInclusiveElem(const Point &point_, const Val &val_) : - point(point_), - val(val_) + SparsePointGridInclusiveElem(const Point& point_, const Val& val_) + : point(point_) + , val(val_) { } @@ -37,25 +39,23 @@ struct SparsePointGridInclusiveElem template struct Locatoror { - Point operator()(const SparsePointGridInclusiveElem &elem) + Point operator()(const SparsePointGridInclusiveElem& elem) { return elem.point; } }; -} // namespace SparseGridImpl +} // namespace SparsePointGridInclusiveImpl /*! \brief Sparse grid which can locate spatially nearby values efficiently. * * \tparam Val The value type to store. */ template -class SparsePointGridInclusive : public SparsePointGrid, - SparsePointGridInclusiveImpl::Locatoror > +class SparsePointGridInclusive : public SparsePointGrid, SparsePointGridInclusiveImpl::Locatoror> { public: - using Base = SparsePointGrid, - SparsePointGridInclusiveImpl::Locatoror >; + using Base = SparsePointGrid, SparsePointGridInclusiveImpl::Locatoror>; /*! \brief Constructs a sparse grid with the specified cell size. * @@ -64,7 +64,7 @@ class SparsePointGridInclusive : public SparsePointGrid getNearbyVals(const Point &query_pt, coord_t radius) const; - + std::vector getNearbyVals(const Point& query_pt, coord_t radius) const; }; #define SG_TEMPLATE template #define SG_THIS SparsePointGridInclusive SG_TEMPLATE -SG_THIS::SparsePointGridInclusive(coord_t cell_size, size_t elem_reserve, float max_load_factor) : - Base(cell_size,elem_reserve,max_load_factor) +SG_THIS::SparsePointGridInclusive(coord_t cell_size, size_t elem_reserve, double max_load_factor) + : Base(cell_size, elem_reserve, max_load_factor) { } SG_TEMPLATE -void SG_THIS::insert(const Point &point, const Val &val) +void SG_THIS::insert(const Point& point, const Val& val) { - typename SG_THIS::Elem elem(point,val); + typename SG_THIS::Elem elem(point, val); Base::insert(elem); } SG_TEMPLATE -std::vector -SG_THIS::getNearbyVals(const Point &query_pt, coord_t radius) const +std::vector SG_THIS::getNearbyVals(const Point& query_pt, coord_t radius) const { std::vector ret; - std::function&)> process_func = [&ret](const typename SG_THIS::Elem &elem) - { - ret.push_back(elem.val); - return true; - }; + std::function&)> process_func = [&ret](const typename SG_THIS::Elem& elem) + { + ret.push_back(elem.val); + return true; + }; this->processNearby(query_pt, radius, process_func); return ret; } diff --git a/include/utils/ToolpathVisualizer.h b/include/utils/ToolpathVisualizer.h index ffd98ecc85..d3ad54ac7a 100644 --- a/include/utils/ToolpathVisualizer.h +++ b/include/utils/ToolpathVisualizer.h @@ -1,14 +1,14 @@ -//Copyright (c) 2019 Ultimaker B.V. +// Copyright (c) 2019 Ultimaker B.V. #ifndef TOOLPATH_VISUALIZER_H #define TOOLPATH_VISUALIZER_H -#include "polygon.h" -#include "SVG.h" #include "ExtrusionSegment.h" +#include "SVG.h" +#include "polygon.h" namespace cura { - using namespace cura; +using namespace cura; /*! * Get statistics of the resulting toolpaths @@ -17,21 +17,20 @@ class ToolpathVisualizer { public: ToolpathVisualizer(SVG& svg) - : svg(svg) + : svg_(svg) { } + void outline(const Polygons& input); void toolpaths(const std::vector& all_segments, bool rounded_visualization = true); void underfill(const Polygons& underfills); void overfill(const Polygons& overfills, const Polygons& double_overfills = Polygons()); void width_legend(const Polygons& input, coord_t nozzle_size, coord_t max_dev, coord_t min_w, bool rounded_visualization); void widths(const std::vector& all_segments, coord_t nozzle_size, coord_t max_dev, coord_t min_w, bool rounded_visualization, bool exaggerate_widths = false); + private: - SVG& svg; + SVG& svg_; }; - - - } // namespace cura #endif // TOOLPATH_VISUALIZER_H diff --git a/include/utils/VoronoiUtils.h b/include/utils/VoronoiUtils.h index 33145c77ba..4c0c196cc4 100644 --- a/include/utils/VoronoiUtils.h +++ b/include/utils/VoronoiUtils.h @@ -1,5 +1,5 @@ -//Copyright (c) 2020 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2020 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef UTILS_VORONOI_UTILS_H @@ -7,14 +7,13 @@ #include - #include -#include "SVG.h" #include "PolygonsSegmentIndex.h" +#include "SVG.h" -namespace cura +namespace cura { /*! @@ -31,46 +30,43 @@ class VoronoiUtils static PolygonsPointIndex getSourcePointIndex(const vd_t::cell_type& cell, const std::vector& points, const std::vector& segments); static Point p(const vd_t::vertex_type* node); - + static bool isSourcePoint(Point p, const vd_t::cell_type& cell, const std::vector& points, const std::vector& segments, coord_t snap_dist = 10); - + static coord_t getDistance(Point p, const vd_t::cell_type& cell, const std::vector& points, const std::vector& segments); - + /*! * Discretize a parabola based on (approximate) step size. * The \p approximate_step_size is measured parallel to the \p source_segment, not along the parabola. */ - static std::vector discretizeParabola(const Point& source_point, const Segment& source_segment, Point start, Point end, coord_t approximate_step_size, float transitioning_angle); + static std::vector + discretizeParabola(const Point& source_point, const Segment& source_segment, Point start, Point end, coord_t approximate_step_size, double transitioning_angle); protected: /*! * Discretize parabola based on max absolute deviation from the parabola. - * + * * adapted from boost::polygon::voronoi_visual_utils.cpp - * + * * Discretize parabolic Voronoi edge. * Parabolic Voronoi edges are always formed by one point and one segment * from the initial input set. - * + * * Args: * point: input point. * segment: input segment. * max_dist: maximum discretization distance. * discretization: point discretization of the given Voronoi edge. - * + * * Template arguments: * InCT: coordinate type of the input geometries (usually integer). * Point: point type, should model point concept. * Segment: segment type, should model segment concept. - * + * * Important: * discretization should contain both edge endpoints initially. */ - static void discretize( - const Point& point, - const Segment& segment, - const coord_t max_dist, - std::vector* discretization); + static void discretize(const Point& point, const Segment& segment, const coord_t max_dist, std::vector* discretization); /*! * adapted from boost::polygon::voronoi_visual_utils.cpp @@ -89,7 +85,6 @@ class VoronoiUtils * the point lies between the start-point and endpoint of the segment. */ static double getPointProjection(const Point& point, const Segment& segment); - }; } // namespace cura diff --git a/include/utils/floatpoint.h b/include/utils/floatpoint.h deleted file mode 100644 index df9a2d2ad0..0000000000 --- a/include/utils/floatpoint.h +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright (c) 2020 Ultimaker B.V. -// CuraEngine is released under the terms of the AGPLv3 or higher. - -#ifndef FLOAT_POINT_H -#define FLOAT_POINT_H - -#include -#include - -#include "IntPoint.h" - - -namespace cura -{ - -/* -Floating point 3D points are used during model loading as 3D vectors. -They represent millimeters in 3D space. -*/ -class FPoint3 -{ -public: - float x, y, z; - - FPoint3() - { - } - - FPoint3(float _x, float _y, float _z) - : x(_x) - , y(_y) - , z(_z) - { - } - - FPoint3(const Point3& p) - : x(static_cast(p.x_) * .001f) - , y(static_cast(p.y_) * .001f) - , z(static_cast(p.z_) * .001f) - { - } - - FPoint3 operator+(const FPoint3& p) const - { - return FPoint3(x + p.x, y + p.y, z + p.z); - } - FPoint3 operator-(const FPoint3& p) const - { - return FPoint3(x - p.x, y - p.y, z - p.z); - } - FPoint3 operator*(const float f) const - { - return FPoint3(x * f, y * f, z * f); - } - FPoint3 operator/(const float f) const - { - return FPoint3(x / f, y / f, z / f); - } - - FPoint3& operator+=(const FPoint3& p) - { - x += p.x; - y += p.y; - z += p.z; - return *this; - } - FPoint3& operator-=(const FPoint3& p) - { - x -= p.x; - y -= p.y; - z -= p.z; - return *this; - } - FPoint3& operator*=(const float f) - { - x *= f; - y *= f; - z *= f; - return *this; - } - - bool operator==(FPoint3& p) const - { - return x == p.x && y == p.y && z == p.z; - } - bool operator!=(FPoint3& p) const - { - return x != p.x || y != p.y || z != p.z; - } - - float max() const - { - if (x > y && x > z) - return x; - if (y > z) - return y; - return z; - } - - bool testLength(float len) const - { - return vSize2() <= len * len; - } - - float vSize2() const - { - return x * x + y * y + z * z; - } - - float vSize() const - { - return sqrt(vSize2()); - } - - inline FPoint3 normalized() const - { - return (*this) / vSize(); - } - - FPoint3 cross(const FPoint3& p) const - { - return FPoint3(y * p.z - z * p.y, z * p.x - x * p.z, x * p.y - y * p.x); - } - - static FPoint3 cross(const Point3& a, const Point3& b) - { - return FPoint3(a).cross(FPoint3(b)); - } - - Point3 toPoint3() - { - return Point3(MM2INT(x), MM2INT(y), MM2INT(z)); - } -}; - -inline float operator*(FPoint3 lhs, const FPoint3& rhs) -{ - return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z; -} - -} // namespace cura -#endif // INT_POINT_H diff --git a/include/utils/linearAlg2D.h b/include/utils/linearAlg2D.h index 13dd873497..dce7acf95c 100644 --- a/include/utils/linearAlg2D.h +++ b/include/utils/linearAlg2D.h @@ -325,7 +325,7 @@ class LinearAlg2D * \param c end of second line segment * \return the angle in radians between 0 and 2 * pi of the corner in \p b */ - static float getAngleLeft(const Point& a, const Point& b, const Point& c); + static double getAngleLeft(const Point& a, const Point& b, const Point& c); /*! * Returns the determinant of the 2D matrix defined by the the vectors ab and ap as rows. diff --git a/include/utils/polygon.h b/include/utils/polygon.h index b32b59e51f..7036e256d5 100644 --- a/include/utils/polygon.h +++ b/include/utils/polygon.h @@ -8,7 +8,6 @@ #include // std::reverse, fill_n array #include #include // fabs -#include #include #include // int64_t.min #include @@ -268,10 +267,10 @@ class ConstPolygonRef Point closestPointTo(Point p) const { Point ret = p; - float bestDist = FLT_MAX; - for (unsigned int n = 0; n < path->size(); n++) + double bestDist = std::numeric_limits::max(); + for (size_t n = 0; n < path->size(); n++) { - float dist = vSize2f(p - (*path)[n]); + double dist = vSize2f(p - (*path)[n]); if (dist < bestDist) { ret = (*path)[n]; @@ -400,7 +399,7 @@ class ConstPolygonRef const Point v12, const Point v02, const int64_t shortcut_length, - float cos_angle); + double cos_angle); /*! * Smooth out a complex corner where the shortcut bypasses more than two line segments diff --git a/src/BeadingStrategy/BeadingStrategy.cpp b/src/BeadingStrategy/BeadingStrategy.cpp index 03c6adb3a1..17cc6a5e1f 100644 --- a/src/BeadingStrategy/BeadingStrategy.cpp +++ b/src/BeadingStrategy/BeadingStrategy.cpp @@ -1,38 +1,37 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. - -#include +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #include "BeadingStrategy/BeadingStrategy.h" +#include + namespace cura { -BeadingStrategy::BeadingStrategy -( +BeadingStrategy::BeadingStrategy( coord_t optimal_width, Ratio wall_split_middle_threshold, Ratio wall_add_middle_threshold, coord_t default_transition_length, - float transitioning_angle -) : - optimal_width(optimal_width), - wall_split_middle_threshold(wall_split_middle_threshold), - wall_add_middle_threshold(wall_add_middle_threshold), - default_transition_length(default_transition_length), - transitioning_angle(transitioning_angle) + double transitioning_angle) + : optimal_width(optimal_width) + , wall_split_middle_threshold(wall_split_middle_threshold) + , wall_add_middle_threshold(wall_add_middle_threshold) + , default_transition_length(default_transition_length) + , transitioning_angle(transitioning_angle) { name = "Unknown"; } -BeadingStrategy::BeadingStrategy(const BeadingStrategy& other) : - optimal_width(other.optimal_width), - wall_split_middle_threshold(other.wall_split_middle_threshold), - wall_add_middle_threshold(other.wall_add_middle_threshold), - default_transition_length(other.default_transition_length), - transitioning_angle(other.transitioning_angle), - name(other.name) -{} +BeadingStrategy::BeadingStrategy(const BeadingStrategy& other) + : optimal_width(other.optimal_width) + , wall_split_middle_threshold(other.wall_split_middle_threshold) + , wall_add_middle_threshold(other.wall_add_middle_threshold) + , default_transition_length(other.default_transition_length) + , transitioning_angle(other.transitioning_angle) + , name(other.name) +{ +} coord_t BeadingStrategy::getTransitioningLength(coord_t lower_bead_count) const { @@ -43,12 +42,12 @@ coord_t BeadingStrategy::getTransitioningLength(coord_t lower_bead_count) const return default_transition_length; } -float BeadingStrategy::getTransitionAnchorPos(coord_t lower_bead_count) const +double BeadingStrategy::getTransitionAnchorPos(coord_t lower_bead_count) const { coord_t lower_optimum = getOptimalThickness(lower_bead_count); coord_t transition_point = getTransitionThickness(lower_bead_count); coord_t upper_optimum = getOptimalThickness(lower_bead_count + 1); - return 1.0 - float(transition_point - lower_optimum) / float(upper_optimum - lower_optimum); + return 1.0 - static_cast(transition_point - lower_optimum) / static_cast(upper_optimum - lower_optimum); } std::vector BeadingStrategy::getNonlinearThicknesses(coord_t lower_bead_count) const diff --git a/src/BeadingStrategy/DistributedBeadingStrategy.cpp b/src/BeadingStrategy/DistributedBeadingStrategy.cpp index 8874d07b7a..7480d94e6e 100644 --- a/src/BeadingStrategy/DistributedBeadingStrategy.cpp +++ b/src/BeadingStrategy/DistributedBeadingStrategy.cpp @@ -1,23 +1,22 @@ // Copyright (c) 2022 Ultimaker B.V. // CuraEngine is released under the terms of the AGPLv3 or higher. -#include #include "BeadingStrategy/DistributedBeadingStrategy.h" +#include + namespace cura { -DistributedBeadingStrategy::DistributedBeadingStrategy -( +DistributedBeadingStrategy::DistributedBeadingStrategy( const coord_t optimal_width, const coord_t default_transition_length, const AngleRadians transitioning_angle, const Ratio wall_split_middle_threshold, const Ratio wall_add_middle_threshold, - const int distribution_radius -) : - BeadingStrategy(optimal_width, wall_split_middle_threshold, wall_add_middle_threshold, default_transition_length, transitioning_angle) + const int distribution_radius) + : BeadingStrategy(optimal_width, wall_split_middle_threshold, wall_add_middle_threshold, default_transition_length, transitioning_angle) { - if(distribution_radius >= 2) + if (distribution_radius >= 2) { one_over_distribution_radius_squared = 1.0f / (distribution_radius - 1) * 1.0f / (distribution_radius - 1); } @@ -36,25 +35,25 @@ DistributedBeadingStrategy::Beading DistributedBeadingStrategy::compute(coord_t if (bead_count > 2) { const coord_t to_be_divided = thickness - bead_count * optimal_width; - const float middle = static_cast(bead_count - 1) / 2; + const double middle = static_cast(bead_count - 1) / 2; const auto getWeight = [middle, this](coord_t bead_idx) { - const float dev_from_middle = bead_idx - middle; - return std::max(0.0f, 1.0f - one_over_distribution_radius_squared * dev_from_middle * dev_from_middle); + const double dev_from_middle = bead_idx - middle; + return std::max(0.0, 1.0 - one_over_distribution_radius_squared * dev_from_middle * dev_from_middle); }; - std::vector weights; + std::vector weights; weights.resize(bead_count); for (coord_t bead_idx = 0; bead_idx < bead_count; bead_idx++) { weights[bead_idx] = getWeight(bead_idx); } - const float total_weight = std::accumulate(weights.cbegin(), weights.cend(), 0.f); + const double total_weight = std::accumulate(weights.cbegin(), weights.cend(), 0.0); for (coord_t bead_idx = 0; bead_idx < bead_count; bead_idx++) { - const float weight_fraction = weights[bead_idx] / total_weight; + const double weight_fraction = weights[bead_idx] / total_weight; const coord_t splitup_left_over_weight = to_be_divided * weight_fraction; const coord_t width = optimal_width + splitup_left_over_weight; if (bead_idx == 0) diff --git a/src/BeadingStrategy/LimitedBeadingStrategy.cpp b/src/BeadingStrategy/LimitedBeadingStrategy.cpp index d5a2a2b72b..8b612ce419 100644 --- a/src/BeadingStrategy/LimitedBeadingStrategy.cpp +++ b/src/BeadingStrategy/LimitedBeadingStrategy.cpp @@ -20,12 +20,15 @@ coord_t LimitedBeadingStrategy::getTransitioningLength(coord_t lower_bead_count) return parent->getTransitioningLength(lower_bead_count); } -float LimitedBeadingStrategy::getTransitionAnchorPos(coord_t lower_bead_count) const +double LimitedBeadingStrategy::getTransitionAnchorPos(coord_t lower_bead_count) const { return parent->getTransitionAnchorPos(lower_bead_count); } -LimitedBeadingStrategy::LimitedBeadingStrategy(const coord_t max_bead_count, BeadingStrategyPtr parent) : BeadingStrategy(*parent), max_bead_count(max_bead_count), parent(std::move(parent)) +LimitedBeadingStrategy::LimitedBeadingStrategy(const coord_t max_bead_count, BeadingStrategyPtr parent) + : BeadingStrategy(*parent) + , max_bead_count(max_bead_count) + , parent(std::move(parent)) { if (max_bead_count % 2 == 1) { diff --git a/src/BeadingStrategy/RedistributeBeadingStrategy.cpp b/src/BeadingStrategy/RedistributeBeadingStrategy.cpp index 54ad5b99d9..c2109bed83 100644 --- a/src/BeadingStrategy/RedistributeBeadingStrategy.cpp +++ b/src/BeadingStrategy/RedistributeBeadingStrategy.cpp @@ -1,5 +1,5 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #include "BeadingStrategy/RedistributeBeadingStrategy.h" @@ -9,16 +9,11 @@ namespace cura { -RedistributeBeadingStrategy::RedistributeBeadingStrategy -( - const coord_t optimal_width_outer, - const Ratio minimum_variable_line_ratio, - BeadingStrategyPtr parent -) : - BeadingStrategy(*parent), - parent(std::move(parent)), - optimal_width_outer(optimal_width_outer), - minimum_variable_line_ratio(minimum_variable_line_ratio) +RedistributeBeadingStrategy::RedistributeBeadingStrategy(const coord_t optimal_width_outer, const Ratio minimum_variable_line_ratio, BeadingStrategyPtr parent) + : BeadingStrategy(*parent) + , parent(std::move(parent)) + , optimal_width_outer(optimal_width_outer) + , minimum_variable_line_ratio(minimum_variable_line_ratio) { name = "RedistributeBeadingStrategy"; } @@ -34,9 +29,12 @@ coord_t RedistributeBeadingStrategy::getTransitionThickness(coord_t lower_bead_c { switch (lower_bead_count) { - case 0: return minimum_variable_line_ratio * optimal_width_outer; - case 1: return (1.0 + parent->getSplitMiddleThreshold()) * optimal_width_outer; - default: return parent->getTransitionThickness(lower_bead_count - 2) + 2 * optimal_width_outer; + case 0: + return minimum_variable_line_ratio * optimal_width_outer; + case 1: + return (1.0 + parent->getSplitMiddleThreshold()) * optimal_width_outer; + default: + return parent->getTransitionThickness(lower_bead_count - 2) + 2 * optimal_width_outer; } } @@ -58,7 +56,7 @@ coord_t RedistributeBeadingStrategy::getTransitioningLength(coord_t lower_bead_c return parent->getTransitioningLength(lower_bead_count); } -float RedistributeBeadingStrategy::getTransitionAnchorPos(coord_t lower_bead_count) const +double RedistributeBeadingStrategy::getTransitionAnchorPos(coord_t lower_bead_count) const { return parent->getTransitionAnchorPos(lower_bead_count); } diff --git a/src/BeadingStrategy/WideningBeadingStrategy.cpp b/src/BeadingStrategy/WideningBeadingStrategy.cpp index 893c88d67a..368eaaed87 100644 --- a/src/BeadingStrategy/WideningBeadingStrategy.cpp +++ b/src/BeadingStrategy/WideningBeadingStrategy.cpp @@ -1,5 +1,5 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #include "BeadingStrategy/WideningBeadingStrategy.h" @@ -61,18 +61,20 @@ coord_t WideningBeadingStrategy::getTransitionThickness(coord_t lower_bead_count coord_t WideningBeadingStrategy::getOptimalBeadCount(coord_t thickness) const { - if (thickness < min_input_width) return 0; + if (thickness < min_input_width) + return 0; coord_t ret = parent->getOptimalBeadCount(thickness); - if (thickness >= min_input_width && ret < 1) return 1; + if (thickness >= min_input_width && ret < 1) + return 1; return ret; } -coord_t WideningBeadingStrategy::getTransitioningLength(coord_t lower_bead_count) const +coord_t WideningBeadingStrategy::getTransitioningLength(coord_t lower_bead_count) const { return parent->getTransitioningLength(lower_bead_count); } -float WideningBeadingStrategy::getTransitionAnchorPos(coord_t lower_bead_count) const +double WideningBeadingStrategy::getTransitionAnchorPos(coord_t lower_bead_count) const { return parent->getTransitionAnchorPos(lower_bead_count); } diff --git a/src/FffGcodeWriter.cpp b/src/FffGcodeWriter.cpp index 46103204ae..91fb9ffbbe 100644 --- a/src/FffGcodeWriter.cpp +++ b/src/FffGcodeWriter.cpp @@ -236,7 +236,7 @@ unsigned int FffGcodeWriter::findSpiralizedLayerSeamVertexIndex(const SliceDataS Point last_wall_seam_vertex_vector = last_wall_seam_vertex + last_wall_seam_vertex_inward_normal; // now test the vertex following the candidate seam vertex and if it lies to the left of the vector, it's good to use - float a = LinearAlg2D::getAngleLeft(last_wall_seam_vertex_vector, last_wall_seam_vertex, wall[(seam_vertex_idx + 1) % n_points]); + double a = LinearAlg2D::getAngleLeft(last_wall_seam_vertex_vector, last_wall_seam_vertex, wall[(seam_vertex_idx + 1) % n_points]); if (a <= 0 || a >= std::numbers::pi) { @@ -2764,7 +2764,7 @@ void FffGcodeWriter::processTopBottom( // helper function that detects skin regions that have no support and modifies their print settings (config, line angle, density, etc.) - auto handle_bridge_skin = [&](const int bridge_layer, const GCodePathConfig* config, const float density) // bridge_layer = 1, 2 or 3 + auto handle_bridge_skin = [&](const int bridge_layer, const GCodePathConfig* config, const double density) // bridge_layer = 1, 2 or 3 { if (support_layer_nr >= (bridge_layer - 1)) { @@ -3055,7 +3055,7 @@ void FffGcodeWriter::processSkinPrintFeature( } constexpr bool enable_travel_optimization = false; - constexpr float flow = 1.0; + constexpr double flow = 1.0; if (pattern == EFillMethod::GRID || pattern == EFillMethod::LINES || pattern == EFillMethod::TRIANGLES || pattern == EFillMethod::CUBIC || pattern == EFillMethod::TETRAHEDRAL || pattern == EFillMethod::QUARTER_CUBIC || pattern == EFillMethod::CUBICSUBDIV || pattern == EFillMethod::LIGHTNING) { diff --git a/src/FffPolygonGenerator.cpp b/src/FffPolygonGenerator.cpp index dd9aedc002..4335a1b49d 100644 --- a/src/FffPolygonGenerator.cpp +++ b/src/FffPolygonGenerator.cpp @@ -965,7 +965,7 @@ void FffPolygonGenerator::processOozeShield(SliceDataStorage& storage) } } - const float largest_printed_area = 1.0; // TODO: make var a parameter, and perhaps even a setting? + const double largest_printed_area = 1.0; // TODO: make var a parameter, and perhaps even a setting? for (LayerIndex layer_nr = 0; layer_nr <= storage.max_print_height_second_to_last_extruder; layer_nr++) { storage.oozeShield[layer_nr].removeSmallAreas(largest_printed_area); diff --git a/src/LayerPlan.cpp b/src/LayerPlan.cpp index ae37348fc4..6641a321b5 100644 --- a/src/LayerPlan.cpp +++ b/src/LayerPlan.cpp @@ -498,7 +498,7 @@ GCodePath& LayerPlan::addTravel_simple(const Point& p, GCodePath* path) return *path; } -void LayerPlan::planPrime(const float& prime_blob_wipe_length) +void LayerPlan::planPrime(double prime_blob_wipe_length) { forceNewPathStart(); GCodePath& prime_travel = addTravel_simple(getLastPlannedPositionOrStartingPosition() + Point(0, MM2INT(prime_blob_wipe_length))); @@ -623,7 +623,7 @@ void LayerPlan::addPolygonsByOptimizer( } } -static constexpr float max_non_bridge_line_volume = MM2INT(100); // limit to accumulated "volume" of non-bridge lines which is proportional to distance x extrusion rate +static constexpr double max_non_bridge_line_volume = MM2INT(100); // limit to accumulated "volume" of non-bridge lines which is proportional to distance x extrusion rate void LayerPlan::addWallLine( const Point& p0, @@ -631,9 +631,9 @@ void LayerPlan::addWallLine( const Settings& settings, const GCodePathConfig& non_bridge_config, const GCodePathConfig& bridge_config, - float flow, + double flow, const Ratio width_factor, - float& non_bridge_line_volume, + double& non_bridge_line_volume, Ratio speed_factor, double distance_to_bridge_start) { @@ -667,7 +667,7 @@ void LayerPlan::addWallLine( // flow required for the next line segment - when accelerating after a bridge segment, the flow is increased in inverse proportion to the speed_factor // so the slower the feedrate, the greater the flow - the idea is to get the extruder back to normal pressure as quickly as possible - const float segment_flow = (speed_factor > 1) ? flow * (1 / speed_factor) : flow; + const double segment_flow = (speed_factor > 1) ? flow * (1 / speed_factor) : flow; // if a bridge is present in this wall, this particular segment may need to be partially or wholely coasted if (distance_to_bridge_start > 0) @@ -775,10 +775,10 @@ void LayerPlan::addWallLine( { // find the bridge line segment that's nearest to the current point int nearest = 0; - float smallest_dist2 = vSize2f(cur_point - line_polys[0][0]); + double smallest_dist2 = vSize2f(cur_point - line_polys[0][0]); for (unsigned i = 1; i < line_polys.size(); ++i) { - float dist2 = vSize2f(cur_point - line_polys[i][0]); + double dist2 = vSize2f(cur_point - line_polys[i][0]); if (dist2 < smallest_dist2) { nearest = i; @@ -852,7 +852,7 @@ void LayerPlan::addWall( const GCodePathConfig& non_bridge_config, const GCodePathConfig& bridge_config, coord_t wall_0_wipe_dist, - float flow_ratio, + double flow_ratio, bool always_retract) { // TODO: Deprecated in favor of ExtrusionJunction version below. @@ -888,7 +888,7 @@ void LayerPlan::addWall( const GCodePathConfig& non_bridge_config, const GCodePathConfig& bridge_config, coord_t wall_0_wipe_dist, - float flow_ratio, + double flow_ratio, bool always_retract, const bool is_closed, const bool is_reversed, @@ -904,7 +904,7 @@ void LayerPlan::addWall( start_idx = locateFirstSupportedVertex(wall, start_idx); } - float non_bridge_line_volume = max_non_bridge_line_volume; // assume extruder is fully pressurised before first non-bridge line is output + double non_bridge_line_volume = max_non_bridge_line_volume; // assume extruder is fully pressurised before first non-bridge line is output double speed_factor = 1.0; // start first line at normal speed coord_t distance_to_bridge_start = 0; // will be updated before each line is processed @@ -943,10 +943,10 @@ void LayerPlan::addWall( { // find the bridge line segment that's nearest to p0 int nearest = 0; - float smallest_dist2 = vSize2f(p0.p - line_polys[0][0]); + double smallest_dist2 = vSize2f(p0.p - line_polys[0][0]); for (unsigned i = 1; i < line_polys.size(); ++i) { - float dist2 = vSize2f(p0.p - line_polys[i][0]); + double dist2 = vSize2f(p0.p - line_polys[i][0]); if (dist2 < smallest_dist2) { nearest = i; @@ -1054,7 +1054,7 @@ void LayerPlan::addWall( for (size_t piece = 0; piece < pieces; ++piece) { - const float average_progress = (float(piece) + 0.5) / pieces; // How far along this line to sample the line width in the middle of this piece. + const double average_progress = (double(piece) + 0.5) / pieces; // How far along this line to sample the line width in the middle of this piece. const coord_t line_width = p0.w + average_progress * delta_line_width; const Point destination = p0.p + normal(line_vector, piece_length * (piece + 1)); if (is_small_feature) @@ -1154,7 +1154,7 @@ void LayerPlan::addWalls( const GCodePathConfig& bridge_config, const ZSeamConfig& z_seam_config, coord_t wall_0_wipe_dist, - float flow_ratio, + double flow_ratio, bool always_retract) { // TODO: Deprecated in favor of ExtrusionJunction version below. @@ -2123,7 +2123,7 @@ void LayerPlan::writeGCode(GCodeExport& gcode) else { // SPIRALIZE // If we need to spiralize then raise the head slowly by 1 layer as this path progresses. - float totalLength = 0.0; + double totalLength = 0.0; Point p0 = gcode.getPositionXY(); for (unsigned int _path_idx = path_idx; _path_idx < paths.size() && ! paths[_path_idx].isTravelPath(); _path_idx++) { @@ -2136,7 +2136,7 @@ void LayerPlan::writeGCode(GCodeExport& gcode) } } - float length = 0.0; + double length = 0.0; p0 = gcode.getPositionXY(); for (; path_idx < paths.size() && paths[path_idx].spiralize; path_idx++) { // handle all consecutive spiralized paths > CHANGES path_idx! diff --git a/src/MeshGroup.cpp b/src/MeshGroup.cpp index b70e04c45e..75a4dccf33 100644 --- a/src/MeshGroup.cpp +++ b/src/MeshGroup.cpp @@ -14,7 +14,7 @@ #include "settings/types/Ratio.h" //For the shrinkage percentage and scale factor. #include "utils/FMatrix4x3.h" //To transform the input meshes for shrinkage compensation and to align in command line mode. -#include "utils/floatpoint.h" //To accept incoming meshes with floating point vertices. +#include "utils/Point3f.h" //To accept incoming meshes with floating point vertices. #include "utils/gettime.h" #include "utils/section_type.h" #include "utils/string.h" @@ -140,7 +140,7 @@ bool loadMeshSTL_ascii(Mesh* mesh, const char* filename, const FMatrix4x3& matri { FILE* f = fopen(filename, "rt"); char buffer[1024]; - FPoint3 vertex; + Point3f vertex; int n = 0; Point3 v0(0, 0, 0), v1(0, 0, 0), v2(0, 0, 0); while (fgets_(buffer, sizeof(buffer), f)) @@ -151,13 +151,13 @@ bool loadMeshSTL_ascii(Mesh* mesh, const char* filename, const FMatrix4x3& matri switch (n) { case 1: - v0 = matrix.apply(vertex); + v0 = matrix.apply(vertex.toPoint3d()); break; case 2: - v1 = matrix.apply(vertex); + v1 = matrix.apply(vertex.toPoint3d()); break; case 3: - v2 = matrix.apply(vertex); + v2 = matrix.apply(vertex.toPoint3d()); mesh->addFace(v0, v1, v2); n = 0; break; @@ -203,7 +203,7 @@ bool loadMeshSTL_binary(Mesh* mesh, const char* filename, const FMatrix4x3& matr // Every Face is 50 Bytes: Normal(3*float), Vertices(9*float), 2 Bytes Spacer mesh->faces_.reserve(face_count); mesh->vertices_.reserve(face_count); - for (unsigned int i = 0; i < face_count; i++) + for (size_t i = 0; i < face_count; i++) { if (fread(buffer, 50, 1, f) != 1) { @@ -212,9 +212,9 @@ bool loadMeshSTL_binary(Mesh* mesh, const char* filename, const FMatrix4x3& matr } float* v = ((float*)buffer) + 3; - Point3 v0 = matrix.apply(FPoint3(v[0], v[1], v[2])); - Point3 v1 = matrix.apply(FPoint3(v[3], v[4], v[5])); - Point3 v2 = matrix.apply(FPoint3(v[6], v[7], v[8])); + Point3 v0 = matrix.apply(Point3f(v[0], v[1], v[2]).toPoint3d()); + Point3 v1 = matrix.apply(Point3f(v[3], v[4], v[5]).toPoint3d()); + Point3 v2 = matrix.apply(Point3f(v[6], v[7], v[8]).toPoint3d()); mesh->addFace(v0, v1, v2); } fclose(f); diff --git a/src/SkeletalTrapezoidation.cpp b/src/SkeletalTrapezoidation.cpp index 7fd2ffdc48..346e1eb46f 100644 --- a/src/SkeletalTrapezoidation.cpp +++ b/src/SkeletalTrapezoidation.cpp @@ -207,7 +207,7 @@ std::vector SkeletalTrapezoidation::discretize(const vd_t::edge_type& vd_ coord_t end_x = projected_x(end); // Part of the edge will be bound to the markings on the endpoints of the edge. Calculate how far that is. - float bound = 0.5 / tan((std::numbers::pi - transitioning_angle) * 0.5); + double bound = 0.5 / tan((std::numbers::pi - transitioning_angle) * 0.5); coord_t marking_start_x = -d * bound; coord_t marking_end_x = d * bound; Point marking_start = middle + x_axis_dir * marking_start_x / x_axis_length; @@ -717,7 +717,7 @@ void SkeletalTrapezoidation::updateIsCentral() coord_t outer_edge_filter_length = beading_strategy.getTransitionThickness(0) / 2; - float cap = sin(beading_strategy.getTransitioningAngle() * 0.5); // = cos(bisector_angle / 2) + double cap = sin(beading_strategy.getTransitioningAngle() * 0.5); // = cos(bisector_angle / 2) for (edge_t& edge : graph.edges) { assert(edge.twin); @@ -1220,12 +1220,12 @@ void SkeletalTrapezoidation::generateTransitionEnds(edge_t& edge, coord_t mid_po const coord_t ab_size = vSize(ab); const coord_t transition_length = beading_strategy.getTransitioningLength(lower_bead_count); - const float transition_mid_position = beading_strategy.getTransitionAnchorPos(lower_bead_count); - constexpr float inner_bead_width_ratio_after_transition = 1.0; + const double transition_mid_position = beading_strategy.getTransitionAnchorPos(lower_bead_count); + constexpr double inner_bead_width_ratio_after_transition = 1.0; constexpr Ratio start_rest{ 0.0 }; - const float mid_rest = transition_mid_position * inner_bead_width_ratio_after_transition; - constexpr float end_rest = inner_bead_width_ratio_after_transition; + const double mid_rest = transition_mid_position * inner_bead_width_ratio_after_transition; + constexpr double end_rest = inner_bead_width_ratio_after_transition; { // Lower bead count transition end const coord_t start_pos = ab_size - mid_pos; @@ -1281,7 +1281,7 @@ bool SkeletalTrapezoidation::generateTransitionEnd( if (end_pos > ab_size) { // Recurse on all further edges - float rest = end_rest - (start_rest - end_rest) * (end_pos - ab_size) / (start_pos - end_pos); + double rest = end_rest - (start_rest - end_rest) * (end_pos - ab_size) / (start_pos - end_pos); assert(rest >= 0); assert(rest <= std::max(end_rest, start_rest)); assert(rest >= std::min(end_rest, start_rest)); @@ -1768,7 +1768,7 @@ void SkeletalTrapezoidation::propagateBeadingsDownward(edge_t* edge_to_peak, ptr { BeadingPropagation& bottom_beading = *edge_to_peak->from->data.getBeading(); coord_t total_dist = top_beading.dist_from_top_source_ + length + bottom_beading.dist_to_bottom_source_; - Ratio ratio_of_top = static_cast(bottom_beading.dist_to_bottom_source_) / std::min(total_dist, beading_propagation_transition_dist); + Ratio ratio_of_top = static_cast(bottom_beading.dist_to_bottom_source_) / std::min(total_dist, beading_propagation_transition_dist); ratio_of_top = std::max(0.0_r, ratio_of_top); if (ratio_of_top >= 1.0) { @@ -1825,8 +1825,8 @@ SkeletalTrapezoidation::Beading SkeletalTrapezoidation::interpolate(const Beadin // f*(l-r) + r = s // f*(l-r) = s - r // f = (s-r) / (l-r) - float new_ratio = static_cast(switching_radius - right.toolpath_locations[next_inset_idx]) - / static_cast(left.toolpath_locations[next_inset_idx] - right.toolpath_locations[next_inset_idx]); + double new_ratio = static_cast(switching_radius - right.toolpath_locations[next_inset_idx]) + / static_cast(left.toolpath_locations[next_inset_idx] - right.toolpath_locations[next_inset_idx]); new_ratio = std::min(1.0, new_ratio + 0.1); return interpolate(left, new_ratio, right); } @@ -1837,7 +1837,7 @@ SkeletalTrapezoidation::Beading SkeletalTrapezoidation::interpolate(const Beadin SkeletalTrapezoidation::Beading SkeletalTrapezoidation::interpolate(const Beading& left, Ratio ratio_left_to_whole, const Beading& right) const { assert(ratio_left_to_whole >= 0.0 && ratio_left_to_whole <= 1.0); - float ratio_right_to_whole = 1.0 - ratio_left_to_whole; + double ratio_right_to_whole = 1.0 - ratio_left_to_whole; Beading ret = (left.total_thickness > right.total_thickness) ? left : right; for (size_t inset_idx = 0; inset_idx < std::min(left.bead_widths.size(), right.bead_widths.size()); inset_idx++) @@ -2213,7 +2213,7 @@ void SkeletalTrapezoidation::generateLocalMaximaSingleBeads() constexpr coord_t n_segments = 6; for (coord_t segment = 0; segment < n_segments; segment++) { - float a = 2.0 * std::numbers::pi / n_segments * segment; + double a = 2.0 * std::numbers::pi / n_segments * segment; line.junctions.emplace_back(node.p + Point(r * cos(a), r * sin(a)), width, inset_index); } } diff --git a/src/TopSurface.cpp b/src/TopSurface.cpp index 2e5a2a4465..ba3915748d 100644 --- a/src/TopSurface.cpp +++ b/src/TopSurface.cpp @@ -74,7 +74,7 @@ bool TopSurface::ironing(const SliceDataStorage& storage, const SliceMeshStorage if (pattern == EFillMethod::ZIG_ZAG) { // Compensate for the outline_offset decrease that takes place when using the infill generator to generate ironing with the zigzag pattern - const Ratio width_scale = (float)mesh.settings.get("layer_height") / mesh.settings.get("infill_sparse_thickness"); + const Ratio width_scale = (double)mesh.settings.get("layer_height") / mesh.settings.get("infill_sparse_thickness"); ironing_inset += width_scale * line_width / 2; // Align the edge of the ironing line with the edge of the outer wall ironing_inset -= ironing_flow * line_width / 2; diff --git a/src/bridge.cpp b/src/bridge.cpp index 75e42889e2..a5a1ab40ac 100644 --- a/src/bridge.cpp +++ b/src/bridge.cpp @@ -39,7 +39,7 @@ int bridgeAngle( { const coord_t infill_line_distance = mesh.settings.get("infill_line_distance"); const coord_t infill_line_width = mesh.settings.get("infill_line_width"); - const bool part_has_sparse_infill = (infill_line_distance == 0) || ((float)infill_line_width / infill_line_distance) <= sparse_infill_max_density; + const bool part_has_sparse_infill = (infill_line_distance == 0) || ((double)infill_line_width / infill_line_distance) <= sparse_infill_max_density; for (const SliceLayerPart& prev_layer_part : mesh.layers[layer_nr - bridge_layer].parts) { diff --git a/src/communication/ArcusCommunication.cpp b/src/communication/ArcusCommunication.cpp index 231f7e001d..7f589a1312 100644 --- a/src/communication/ArcusCommunication.cpp +++ b/src/communication/ArcusCommunication.cpp @@ -5,6 +5,13 @@ #include "communication/ArcusCommunication.h" +#include //To sleep while waiting for the connection. +#include //To map settings to their extruder numbers for limit_to_extruder. + +#include //The socket to communicate to. +#include +#include + #include "Application.h" //To get and set the current slice command. #include "ExtruderTrain.h" #include "FffProcessor.h" //To start a slice. @@ -19,13 +26,6 @@ #include "utils/channel.h" #include "utils/polygon.h" -#include //The socket to communicate to. -#include -#include - -#include //To sleep while waiting for the connection. -#include //To map settings to their extruder numbers for limit_to_extruder. - namespace cura { @@ -479,7 +479,7 @@ void ArcusCommunication::sendPrintTimeMaterialEstimates() const spdlog::debug("Done sending print time and material estimates."); } -void ArcusCommunication::sendProgress(const float& progress) const +void ArcusCommunication::sendProgress(double progress) const { const int rounded_amount = 1000 * progress; if (private_data->last_sent_progress == rounded_amount) // No need to send another tiny update step. @@ -488,7 +488,7 @@ void ArcusCommunication::sendProgress(const float& progress) const } std::shared_ptr message = std::make_shared(); - float progress_all_objects = progress / private_data->object_count; + double progress_all_objects = progress / private_data->object_count; progress_all_objects += private_data->optimized_layers.sliced_objects * (1.0 / private_data->object_count); message->set_amount(progress_all_objects); private_data->socket->sendMessage(message); @@ -573,4 +573,4 @@ void ArcusCommunication::sliceNext() } // namespace cura -#endif // ARCUS \ No newline at end of file +#endif // ARCUS diff --git a/src/communication/ArcusCommunicationPrivate.cpp b/src/communication/ArcusCommunicationPrivate.cpp index 1e18cc81b0..6de1c1d9fd 100644 --- a/src/communication/ArcusCommunicationPrivate.cpp +++ b/src/communication/ArcusCommunicationPrivate.cpp @@ -5,14 +5,14 @@ #include "communication/ArcusCommunicationPrivate.h" +#include + #include "Application.h" #include "ExtruderTrain.h" #include "Slice.h" #include "settings/types/LayerIndex.h" #include "utils/FMatrix4x3.h" //To convert vertices to integer-points. -#include "utils/floatpoint.h" //To accept vertices (which are provided in floating point). - -#include +#include "utils/Point3f.h" //To accept vertices (which are provided in floating point). namespace cura { @@ -102,7 +102,7 @@ void ArcusCommunication::Private::readMeshGroupMessage(const proto::ObjectList& FMatrix4x3 matrix; for (const cura::proto::Object& object : mesh_group_message.objects()) { - const size_t bytes_per_face = sizeof(FPoint3) * 3; // 3 vectors per face. + const size_t bytes_per_face = sizeof(Point3f) * 3; // 3 vectors per face. const size_t face_count = object.vertices().size() / bytes_per_face; if (face_count <= 0) @@ -125,12 +125,12 @@ void ArcusCommunication::Private::readMeshGroupMessage(const proto::ObjectList& for (size_t face = 0; face < face_count; face++) { const std::string data = object.vertices().substr(face * bytes_per_face, bytes_per_face); - const FPoint3* float_vertices = reinterpret_cast(data.data()); + const Point3f* float_vertices = reinterpret_cast(data.data()); Point3 verts[3]; - verts[0] = matrix.apply(float_vertices[0]); - verts[1] = matrix.apply(float_vertices[1]); - verts[2] = matrix.apply(float_vertices[2]); + verts[0] = matrix.apply(float_vertices[0].toPoint3d()); + verts[1] = matrix.apply(float_vertices[1].toPoint3d()); + verts[2] = matrix.apply(float_vertices[2].toPoint3d()); mesh.addFace(verts[0], verts[1], verts[2]); } @@ -143,4 +143,4 @@ void ArcusCommunication::Private::readMeshGroupMessage(const proto::ObjectList& } // namespace cura -#endif // ARCUS \ No newline at end of file +#endif // ARCUS diff --git a/src/communication/CommandLine.cpp b/src/communication/CommandLine.cpp index 08b8600eae..9f2e7419e1 100644 --- a/src/communication/CommandLine.cpp +++ b/src/communication/CommandLine.cpp @@ -98,7 +98,7 @@ void CommandLine::sendPrintTimeMaterialEstimates() const } } -void CommandLine::sendProgress(const float& progress) const +void CommandLine::sendProgress(double progress) const { const unsigned int rounded_amount = 100 * progress; if (last_shown_progress == rounded_amount) // No need to send another tiny update step. @@ -584,4 +584,4 @@ const std::string CommandLine::findDefinitionFile(const std::string& definition_ return std::string(""); } -} // namespace cura \ No newline at end of file +} // namespace cura diff --git a/src/gcodeExport.cpp b/src/gcodeExport.cpp index 01d57a6357..559ff91b4e 100644 --- a/src/gcodeExport.cpp +++ b/src/gcodeExport.cpp @@ -649,7 +649,7 @@ bool GCodeExport::initializeExtruderTrains(const SliceDataStorage& storage, cons const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; if (Application::getInstance().communication_->isSequential()) // If we must output the g-code sequentially, we must already place the g-code header here even if we don't know - // the exact time/material usages yet. + // the exact time/material usages yet. { std::string prefix = getFileHeader(storage.getExtrudersUsed()); writeCode(prefix.c_str()); @@ -875,9 +875,9 @@ void GCodeExport::writeMoveBFB(const int x, const int y, const int z, const Velo Point gcode_pos = getGcodePos(x, y, current_extruder); // For Bits From Bytes machines, we need to handle this completely differently. As they do not use E values but RPM values. - float fspeed = speed * 60; - float rpm = extrusion_per_mm * speed * 60; - const float mm_per_rpm = 4.0; // All BFB machines have 4mm per RPM extrusion. + double fspeed = speed * 60; + double rpm = extrusion_per_mm * speed * 60; + const double mm_per_rpm = 4.0; // All BFB machines have 4mm per RPM extrusion. rpm /= mm_per_rpm; if (rpm > 0) { diff --git a/src/infill.cpp b/src/infill.cpp index 0c7dd8b641..39e3342b50 100644 --- a/src/infill.cpp +++ b/src/infill.cpp @@ -3,6 +3,13 @@ #include "infill.h" +#include //For std::sort. +#include +#include + +#include +#include + #include "WallToolPaths.h" #include "infill/GyroidInfill.h" #include "infill/ImageBasedDensityProvider.h" @@ -21,13 +28,6 @@ #include "utils/linearAlg2D.h" #include "utils/polygonUtils.h" -#include -#include - -#include //For std::sort. -#include -#include - /*! * Function which returns the scanline_idx for a given x coordinate * @@ -460,7 +460,7 @@ void Infill::generateConcentricInfill(std::vector& toolpaths constexpr size_t inset_wall_count = 1; // 1 wall at a time. constexpr coord_t wall_0_inset = 0; // Don't apply any outer wall inset for these. That's just for the outer wall. WallToolPaths wall_toolpaths(current_inset, infill_line_width_, inset_wall_count, wall_0_inset, settings, 0, SectionType::CONCENTRIC_INFILL); // FIXME: @jellespijker pass - // the correct layer + // the correct layer const std::vector inset_paths = wall_toolpaths.getToolPaths(); toolpaths.insert(toolpaths.end(), inset_paths.begin(), inset_paths.end()); @@ -494,7 +494,7 @@ void Infill::generateQuarterCubicInfill(Polygons& result) generateHalfTetrahedralInfill(0.5, 90, result); } -void Infill::generateHalfTetrahedralInfill(float pattern_z_shift, int angle_shift, Polygons& result) +void Infill::generateHalfTetrahedralInfill(double pattern_z_shift, int angle_shift, Polygons& result) { const coord_t period = line_distance_ * 2; coord_t shift = coord_t(one_over_sqrt_2 * (z_ + pattern_z_shift * period * 2)) % period; diff --git a/src/infill/GyroidInfill.cpp b/src/infill/GyroidInfill.cpp index 861d2b95ae..dbabec6f61 100644 --- a/src/infill/GyroidInfill.cpp +++ b/src/infill/GyroidInfill.cpp @@ -1,17 +1,21 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #include "infill/GyroidInfill.h" + #include "utils/AABB.h" #include "utils/linearAlg2D.h" #include "utils/polygon.h" -namespace cura { +namespace cura +{ -GyroidInfill::GyroidInfill() { +GyroidInfill::GyroidInfill() +{ } -GyroidInfill::~GyroidInfill() { +GyroidInfill::~GyroidInfill() +{ } void GyroidInfill::generateTotalGyroidInfill(Polygons& result_lines, bool zig_zaggify, coord_t line_distance, const Polygons& in_outline, coord_t z) @@ -51,14 +55,14 @@ void GyroidInfill::generateTotalGyroidInfill(Polygons& result_lines, bool zig_za const double odd_c = sin_z * std::cos(y_rads + phase_offset); const double even_c = sin_z * std::cos(y_rads + phase_offset + std::numbers::pi); const double h = std::sqrt(a * a + b * b); - const double odd_x_rads = ((h != 0) ? std::asin(odd_c / h) + std::asin(b / h) : 0) - std::numbers::pi/2; - const double even_x_rads = ((h != 0) ? std::asin(even_c / h) + std::asin(b / h) : 0) - std::numbers::pi/2; + const double odd_x_rads = ((h != 0) ? std::asin(odd_c / h) + std::asin(b / h) : 0) - std::numbers::pi / 2; + const double even_x_rads = ((h != 0) ? std::asin(even_c / h) + std::asin(b / h) : 0) - std::numbers::pi / 2; odd_line_coords.push_back(odd_x_rads / std::numbers::pi * pitch); even_line_coords.push_back(even_x_rads / std::numbers::pi * pitch); } const unsigned num_coords = odd_line_coords.size(); unsigned num_columns = 0; - for (coord_t x = (std::floor(aabb.min.X / pitch) - 2.25) * pitch; x <= aabb.max.X + pitch/2; x += pitch/2) + for (coord_t x = (std::floor(aabb.min.X / pitch) - 2.25) * pitch; x <= aabb.max.X + pitch / 2; x += pitch / 2) { bool is_first_point = true; Point last; @@ -69,9 +73,9 @@ void GyroidInfill::generateTotalGyroidInfill(Polygons& result_lines, bool zig_za { for (unsigned i = 0; i < num_coords; ++i) { - Point current(x + ((num_columns & 1) ? odd_line_coords[i] : even_line_coords[i])/2 + pitch, y + (coord_t)(i * step)); + Point current(x + ((num_columns & 1) ? odd_line_coords[i] : even_line_coords[i]) / 2 + pitch, y + (coord_t)(i * step)); bool current_inside = in_outline.inside(current, true); - if (!is_first_point) + if (! is_first_point) { if (last_inside && current_inside) { @@ -143,14 +147,14 @@ void GyroidInfill::generateTotalGyroidInfill(Polygons& result_lines, bool zig_za const double odd_c = cos_z * std::sin(x_rads + phase_offset + std::numbers::pi); const double even_c = cos_z * std::sin(x_rads + phase_offset); const double h = std::sqrt(a * a + b * b); - const double odd_y_rads = ((h != 0) ? std::asin(odd_c / h) + std::asin(b / h) : 0) + std::numbers::pi/2; - const double even_y_rads = ((h != 0) ? std::asin(even_c / h) + std::asin(b / h) : 0) + std::numbers::pi/2; + const double odd_y_rads = ((h != 0) ? std::asin(odd_c / h) + std::asin(b / h) : 0) + std::numbers::pi / 2; + const double even_y_rads = ((h != 0) ? std::asin(even_c / h) + std::asin(b / h) : 0) + std::numbers::pi / 2; odd_line_coords.push_back(odd_y_rads / std::numbers::pi * pitch); even_line_coords.push_back(even_y_rads / std::numbers::pi * pitch); } const unsigned num_coords = odd_line_coords.size(); unsigned num_rows = 0; - for (coord_t y = (std::floor(aabb.min.Y / pitch) - 1) * pitch; y <= aabb.max.Y + pitch/2; y += pitch/2) + for (coord_t y = (std::floor(aabb.min.Y / pitch) - 1) * pitch; y <= aabb.max.Y + pitch / 2; y += pitch / 2) { bool is_first_point = true; Point last; @@ -161,9 +165,9 @@ void GyroidInfill::generateTotalGyroidInfill(Polygons& result_lines, bool zig_za { for (unsigned i = 0; i < num_coords; ++i) { - Point current(x + (coord_t)(i * step), y + ((num_rows & 1) ? odd_line_coords[i] : even_line_coords[i])/2); + Point current(x + (coord_t)(i * step), y + ((num_rows & 1) ? odd_line_coords[i] : even_line_coords[i]) / 2); bool current_inside = in_outline.inside(current, true); - if (!is_first_point) + if (! is_first_point) { if (last_inside && current_inside) { @@ -267,7 +271,7 @@ void GyroidInfill::generateTotalGyroidInfill(Polygons& result_lines, bool zig_za { // don't include chain ends that are close to the segment but are beyond the segment ends short beyond = 0; - if (LinearAlg2D::getDist2FromLineSegment(op0, chains[point_index][chain_index], op1, &beyond) < 10 && !beyond) + if (LinearAlg2D::getDist2FromLineSegment(op0, chains[point_index][chain_index], op1, &beyond) < 10 && ! beyond) { points_on_outline_point_index.push_back(point_index); points_on_outline_chain_index.push_back(chain_index); @@ -298,10 +302,10 @@ void GyroidInfill::generateTotalGyroidInfill(Polygons& result_lines, bool zig_za { // find the nearest chain end to the current point unsigned nearest_point_index = 0; - float nearest_point_dist2 = std::numeric_limits::infinity(); + double nearest_point_dist2 = std::numeric_limits::infinity(); for (unsigned pi = 0; pi < points_on_outline_chain_index.size(); ++pi) { - float dist2 = vSize2f(chains[points_on_outline_point_index[pi]][points_on_outline_chain_index[pi]] - cur_point); + double dist2 = vSize2f(chains[points_on_outline_point_index[pi]][points_on_outline_chain_index[pi]] - cur_point); if (dist2 < nearest_point_dist2) { nearest_point_dist2 = dist2; @@ -380,10 +384,8 @@ void GyroidInfill::generateTotalGyroidInfill(Polygons& result_lines, bool zig_za // we have now visited all the points in the outline, if a connector was (potentially) being drawn // check whether the first chain is already connected to the last chain and, if not, draw the // connector between - if (drawing && first_chain_chain_index != std::numeric_limits::max() - && first_chain_chain_index != connector_start_chain_index - && connected_to[0][first_chain_chain_index] != connector_start_chain_index - && connected_to[1][first_chain_chain_index] != connector_start_chain_index) + if (drawing && first_chain_chain_index != std::numeric_limits::max() && first_chain_chain_index != connector_start_chain_index + && connected_to[0][first_chain_chain_index] != connector_start_chain_index && connected_to[1][first_chain_chain_index] != connector_start_chain_index) { // output the connector line segments from the last chain to the first point in the outline connector_points.push_back(outline_poly[0]); @@ -402,4 +404,4 @@ void GyroidInfill::generateTotalGyroidInfill(Polygons& result_lines, bool zig_za result_lines = result; } -} // namespace cura \ No newline at end of file +} // namespace cura diff --git a/src/infill/ImageBasedDensityProvider.cpp b/src/infill/ImageBasedDensityProvider.cpp index 83e53e018f..4d2344e454 100644 --- a/src/infill/ImageBasedDensityProvider.cpp +++ b/src/infill/ImageBasedDensityProvider.cpp @@ -38,8 +38,8 @@ ImageBasedDensityProvider::ImageBasedDensityProvider(const std::string filename, Point middle = model_aabb.getMiddle(); Point model_aabb_size = model_aabb.max - model_aabb.min; Point image_size2 = Point(image_size.x_, image_size.y_); - float aabb_aspect_ratio = float(model_aabb_size.X) / float(model_aabb_size.Y); - float image_aspect_ratio = float(image_size.x_) / float(image_size.y_); + double aabb_aspect_ratio = double(model_aabb_size.X) / double(model_aabb_size.Y); + double image_aspect_ratio = double(image_size.x_) / double(image_size.y_); Point aabb_size; if (image_aspect_ratio < aabb_aspect_ratio) { @@ -63,7 +63,7 @@ ImageBasedDensityProvider::~ImageBasedDensityProvider() } } -float ImageBasedDensityProvider::operator()(const AABB3D& query_cube) const +double ImageBasedDensityProvider::operator()(const AABB3D& query_cube) const { AABB query_box(Point(query_cube.min.x_, query_cube.min.y_), Point(query_cube.max.x_, query_cube.max.y_)); Point img_min = (query_box.min - print_aabb.min - Point(1, 1)) * image_size.x_ / (print_aabb.max.X - print_aabb.min.X); @@ -93,7 +93,7 @@ float ImageBasedDensityProvider::operator()(const AABB3D& query_cube) const value_count++; } } - return 1.0f - ((float)total_lightness) / value_count / 255.0f; + return 1.0 - ((double)total_lightness) / value_count / 255.0; } } // namespace cura diff --git a/src/infill/SierpinskiFill.cpp b/src/infill/SierpinskiFill.cpp index 623f9ab9af..b3a15b3b46 100644 --- a/src/infill/SierpinskiFill.cpp +++ b/src/infill/SierpinskiFill.cpp @@ -22,7 +22,7 @@ namespace cura static constexpr bool diagonal = true; static constexpr bool straight = false; -static constexpr float allowed_length_error = .01; +static constexpr double allowed_length_error = 0.01; static constexpr bool deep_debug_checking = false; @@ -120,9 +120,9 @@ void SierpinskiFill::createTree(SierpinskiTriangle& sub_root) void SierpinskiFill::createTreeStatistics(SierpinskiTriangle& triangle) { Point ac = triangle.straight_corner_ - triangle.a_; - float area = 0.5 * INT2MM2(vSize2(ac)); - float short_length = .5 * vSizeMM(ac); - float long_length = .5 * vSizeMM(triangle.b_ - triangle.a_); + double area = 0.5 * INT2MM2(vSize2(ac)); + double short_length = .5 * vSizeMM(ac); + double long_length = .5 * vSizeMM(triangle.b_ - triangle.a_); triangle.area_ = area; triangle.realized_length_ = (triangle.dir_ == SierpinskiTriangle::SierpinskiDirection::AC_TO_BC) ? long_length : short_length; for (SierpinskiTriangle& child : triangle.children) @@ -141,7 +141,7 @@ void SierpinskiFill::createTreeRequestedLengths(SierpinskiTriangle& triangle) triangle_aabb.include(triangle.b_); triangle_aabb.include(triangle.straight_corner_); AABB3D triangle_aabb3d(Point3(triangle_aabb.min.X, triangle_aabb.min.Y, 0), Point3(triangle_aabb.max.X, triangle_aabb.max.Y, 1)); - float density = density_provider(triangle_aabb3d); // The density of the square around the triangle is a rough estimate of the density of the triangle. + double density = density_provider(triangle_aabb3d); // The density of the square around the triangle is a rough estimate of the density of the triangle. triangle.requested_length_ = density * triangle.area_ / INT2MM(line_width); } else @@ -231,7 +231,7 @@ bool SierpinskiFill::subdivideAll() if (node->depth_ == max_depth) // Never subdivide beyond maximum depth. continue; - float total_subdiv_error = getSubdivisionError(begin, end); + double total_subdiv_error = getSubdivisionError(begin, end); if (! node->children.empty() && total_subdiv_error >= 0 && ! is_constrained) { bool redistribute_errors = true; @@ -256,7 +256,7 @@ bool SierpinskiFill::bubbleUpConstraintErrors() SierpinskiTriangle* node = *it; SierpinskiTriangle& triangle = *node; - float unresolvable_error = triangle.getValueError(); + double unresolvable_error = triangle.getValueError(); // If constrained in one direction, resolve the error in the other direction only. // If constrained in both directions, divide the error equally over both directions. @@ -363,7 +363,7 @@ void SierpinskiFill::redistributeLeftoverErrors(std::list:: spdlog::warn("Nodes aren't balanced! er: {} next el: {}", node->error_right_, next->error_left_); assert(false); } - float exchange = node->error_right_; + double exchange = node->error_right_; if (node->error_right_ < next->error_left_) { exchange *= -1; @@ -372,7 +372,7 @@ void SierpinskiFill::redistributeLeftoverErrors(std::list:: next->error_left_ += exchange; } - float total_superfluous_error = 0; + double total_superfluous_error = 0; for (auto it = begin; it != end; ++it) { SierpinskiTriangle* node = *it; @@ -389,10 +389,10 @@ void SierpinskiFill::redistributeLeftoverErrors(std::list:: } if (begin != sequence.begin() && end != sequence.end() && first->error_left_ > allowed_length_error && last->error_right_ > allowed_length_error) { - float total_error_input = first->error_left_ + last->error_right_; + double total_error_input = first->error_left_ + last->error_right_; total_superfluous_error = std::min(total_superfluous_error, total_error_input); // total superfluous error cannot be more than the influx of error - float left_spillover = total_superfluous_error * first->error_left_ / total_error_input; - float right_spillover = total_superfluous_error * last->error_right_ / total_error_input; + double left_spillover = total_superfluous_error * first->error_left_ / total_error_input; + double right_spillover = total_superfluous_error * last->error_right_ / total_error_input; (*begin)->error_left_ -= left_spillover; prev->error_right_ += left_spillover; (*std::prev(end))->error_right_ -= right_spillover; @@ -423,7 +423,7 @@ void SierpinskiFill::balanceErrors(std::list node_error_compensation(nodes.size()); + std::vector node_error_compensation(nodes.size()); // sort children on value_error, i.e. sort on total_value std::vector order; @@ -440,13 +440,13 @@ void SierpinskiFill::balanceErrors(std::listgetValueError(); + double value_error = node->getValueError(); if (value_error < 0) { added -= value_error; @@ -462,14 +462,14 @@ void SierpinskiFill::balanceErrors(std::listgetValueError(); + double val_err = node->getValueError(); assert(val_err > -allowed_length_error); total_remaining_value_error += val_err; } @@ -489,10 +489,10 @@ void SierpinskiFill::balanceErrors(std::listgetValueError(); + double val_error = node->getValueError(); assert(val_error > -allowed_length_error); - float diff = added * val_error / total_remaining_value_error; + double diff = added * val_error / total_remaining_value_error; subtracted += diff; node_error_compensation[node_idx] = -diff; } @@ -502,7 +502,7 @@ void SierpinskiFill::balanceErrors(std::listerror_left_ -= energy; @@ -531,16 +531,16 @@ void SierpinskiFill::diffuseError() int constrained_nodes = 0; int unconstrained_nodes = 0; int subdivided_nodes = 0; - float error = 0; + double error = 0; for (std::list::iterator it = sequence.begin(); it != sequence.end(); ++it) { SierpinskiTriangle& triangle = *(*it); - float boundary = (triangle.realized_length_ + triangle.total_child_realized_length_) * .5f; + double boundary = (triangle.realized_length_ + triangle.total_child_realized_length_) * 0.5; - float nodal_value = ((use_errors_in_dithering) ? triangle.getErroredValue() : triangle.requested_length_); + double nodal_value = ((use_errors_in_dithering) ? triangle.getErroredValue() : triangle.requested_length_); - float boundary_error = nodal_value - boundary + error; + double boundary_error = nodal_value - boundary + error; std::list::iterator begin = it; std::list::iterator end = std::next(it); @@ -606,9 +606,9 @@ bool SierpinskiFill::isConstrainedForward(std::list::iterat return false; } -float SierpinskiFill::getSubdivisionError(std::list::iterator begin, std::list::iterator end) +double SierpinskiFill::getSubdivisionError(std::list::iterator begin, std::list::iterator end) { - float ret = 0; + double ret = 0; for (auto it = begin; it != end; ++it) { SierpinskiTriangle* node = *it; @@ -677,22 +677,22 @@ SierpinskiFill::Edge SierpinskiFill::SierpinskiTriangle::getToEdge() return ret; } -float SierpinskiFill::SierpinskiTriangle::getTotalError() +double SierpinskiFill::SierpinskiTriangle::getTotalError() { return error_left_ + error_right_; } -float SierpinskiFill::SierpinskiTriangle::getErroredValue() +double SierpinskiFill::SierpinskiTriangle::getErroredValue() { return requested_length_ + getTotalError(); } -float SierpinskiFill::SierpinskiTriangle::getSubdivisionError() +double SierpinskiFill::SierpinskiTriangle::getSubdivisionError() { return getErroredValue() - total_child_realized_length_; } -float SierpinskiFill::SierpinskiTriangle::getValueError() +double SierpinskiFill::SierpinskiTriangle::getValueError() { return getErroredValue() - realized_length_; } @@ -721,10 +721,10 @@ Polygon SierpinskiFill::generateCross() const ret.add(edge_middle / 2); } - float realized_length = INT2MM(ret.polygonLength()); - float requested_length = root.requested_length_; - float error = (realized_length - requested_length) / requested_length; - spdlog::debug("realized_length: {}, requested_length: {} :: {}% error", realized_length, requested_length, .01 * static_cast(10000 * error)); + double realized_length = INT2MM(ret.polygonLength()); + double requested_length = root.requested_length_; + double error = (realized_length - requested_length) / requested_length; + spdlog::debug("realized_length: {}, requested_length: {} :: {}% error", realized_length, requested_length, 0.01 * static_cast(10000 * error)); return ret; } diff --git a/src/infill/SierpinskiFillProvider.cpp b/src/infill/SierpinskiFillProvider.cpp index b659b48fe9..2668641842 100644 --- a/src/infill/SierpinskiFillProvider.cpp +++ b/src/infill/SierpinskiFillProvider.cpp @@ -20,7 +20,7 @@ constexpr bool SierpinskiFillProvider::use_dithering; SierpinskiFillProvider::SierpinskiFillProvider(const AABB3D aabb_3d, coord_t min_line_distance, const coord_t line_width) : fractal_config(getFractalConfig(aabb_3d, min_line_distance)) - , density_provider(new UniformDensityProvider((float)line_width / min_line_distance)) + , density_provider(new UniformDensityProvider((double)line_width / min_line_distance)) , fill_pattern_for_all_layers(std::in_place, *density_provider, fractal_config.aabb, fractal_config.depth, line_width, use_dithering) { } @@ -76,7 +76,7 @@ SierpinskiFillProvider::FractalConfig SierpinskiFillProvider::getFractalConfig(c aabb_size *= 2; depth += 2; } - const float half_sqrt2 = .5 * std::numbers::pi; + const double half_sqrt2 = 0.5 * std::numbers::sqrt2; if (depth > 0 && aabb_size * half_sqrt2 >= max_side_length) { aabb_size *= half_sqrt2; diff --git a/src/mesh.cpp b/src/mesh.cpp index 5e2ca66224..6bcc38f550 100644 --- a/src/mesh.cpp +++ b/src/mesh.cpp @@ -5,7 +5,7 @@ #include -#include "utils/floatpoint.h" +#include "utils/Point3d.h" namespace cura { @@ -203,12 +203,12 @@ int Mesh::getFaceIdxWithPoints(int idx0, int idx1, int notFaceIdx, int notFaceVe has_disconnected_faces = true; } - FPoint3 vn = vertices_[idx1].p_ - vertices_[idx0].p_; - FPoint3 n = vn / vn.vSize(); // the normal of the plane in which all normals of faces connected to the edge lie => the normalized normal - FPoint3 v0 = vertices_[idx1].p_ - vertices_[idx0].p_; + Point3d vn = vertices_[idx1].p_ - vertices_[idx0].p_; + Point3d n = vn / vn.vSize(); // the normal of the plane in which all normals of faces connected to the edge lie => the normalized normal + Point3d v0 = vertices_[idx1].p_ - vertices_[idx0].p_; // the normals below are abnormally directed! : these normals all point counterclockwise (viewed from idx1 to idx0) from the face, irrespective of the direction of the face. - FPoint3 n0 = FPoint3(vertices_[notFaceVertexIdx].p_ - vertices_[idx0].p_).cross(v0); + Point3d n0 = Point3d(vertices_[notFaceVertexIdx].p_ - vertices_[idx0].p_).cross(v0); if (n0.vSize() <= 0) { @@ -227,8 +227,8 @@ int Mesh::getFaceIdxWithPoints(int idx0, int idx1, int notFaceIdx, int notFaceVe break; } - FPoint3 v1 = vertices_[faces_[candidateFace].vertex_index_[candidateVertex]].p_ - vertices_[idx0].p_; - FPoint3 n1 = v0.cross(v1); + Point3d v1 = vertices_[faces_[candidateFace].vertex_index_[candidateVertex]].p_ - vertices_[idx0].p_; + Point3d n1 = v0.cross(v1); double dot = n0 * n1; double det = n * n0.cross(n1); diff --git a/src/pathPlanning/LinePolygonsCrossings.cpp b/src/pathPlanning/LinePolygonsCrossings.cpp index 85896739b2..611aaffe4c 100644 --- a/src/pathPlanning/LinePolygonsCrossings.cpp +++ b/src/pathPlanning/LinePolygonsCrossings.cpp @@ -1,5 +1,5 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #include "pathPlanning/LinePolygonsCrossings.h" @@ -8,36 +8,38 @@ #include "sliceDataStorage.h" #include "utils/SVG.h" -namespace cura { +namespace cura +{ LinePolygonsCrossings::Crossing::Crossing(const size_t poly_idx, const coord_t x, const size_t point_idx) -: poly_idx_(poly_idx) -, x_(x) -, point_idx_(point_idx) + : poly_idx_(poly_idx) + , x_(x) + , point_idx_(point_idx) { } bool LinePolygonsCrossings::calcScanlineCrossings(bool fail_on_unavoidable_obstacles) { - for(unsigned int poly_idx = 0; poly_idx < boundary_.size(); poly_idx++) + for (unsigned int poly_idx = 0; poly_idx < boundary_.size(); poly_idx++) { ConstPolygonRef poly = boundary_[poly_idx]; Point p0 = transformation_matrix_.apply(poly[poly.size() - 1]); - for(unsigned int point_idx = 0; point_idx < poly.size(); point_idx++) + for (unsigned int point_idx = 0; point_idx < poly.size(); point_idx++) { Point p1 = transformation_matrix_.apply(poly[point_idx]); if ((p0.Y >= transformed_start_point_.Y && p1.Y <= transformed_start_point_.Y) || (p1.Y >= transformed_start_point_.Y && p0.Y <= transformed_start_point_.Y)) { // if line segment crosses the line through the transformed start and end point (aka scanline) - if (p1.Y == p0.Y) //Line segment is parallel with the scanline. That means that both endpoints lie on the scanline, so they will have intersected with the adjacent line. + if (p1.Y == p0.Y) // Line segment is parallel with the scanline. That means that both endpoints lie on the scanline, so they will have intersected with the adjacent + // line. { p0 = p1; continue; } const coord_t x = p0.X + (p1.X - p0.X) * (transformed_start_point_.Y - p0.Y) / (p1.Y - p0.Y); // intersection point between line segment and the scanline - + if (x >= transformed_start_point_.X && x <= transformed_end_point_.X) { - if (!((p1.Y == transformed_start_point_.Y && p1.Y < p0.Y) || (p0.Y == transformed_start_point_.Y && p0.Y < p1.Y))) + if (! ((p1.Y == transformed_start_point_.Y && p1.Y < p0.Y) || (p0.Y == transformed_start_point_.Y && p0.Y < p1.Y))) { // perform edge case only for line segments on and below the scanline, not for line segments on and above. // \/ will be no crossings and /\ two, but most importantly | will be one crossing. crossings_.emplace_back(poly_idx, x, point_idx); @@ -53,7 +55,13 @@ bool LinePolygonsCrossings::calcScanlineCrossings(bool fail_on_unavoidable_obsta } } // order crossings by increasing x - std::sort(crossings_.begin(), crossings_.end(), [](const Crossing& a, const Crossing& b) -> bool { return a.x_ < b.x_; }); + std::sort( + crossings_.begin(), + crossings_.end(), + [](const Crossing& a, const Crossing& b) -> bool + { + return a.x_ < b.x_; + }); return true; } @@ -66,10 +74,10 @@ bool LinePolygonsCrossings::lineSegmentCollidesWithBoundary() transformed_start_point_ = transformation_matrix_.apply(start_point_); transformed_end_point_ = transformation_matrix_.apply(end_point_); - for(ConstPolygonRef poly : boundary_) + for (ConstPolygonRef poly : boundary_) { Point p0 = transformation_matrix_.apply(poly.back()); - for(Point p1_ : poly) + for (Point p1_ : poly) { Point p1 = transformation_matrix_.apply(p1_); // when the boundary just touches the line don't disambiguate between the boundary moving on to actually cross the line @@ -77,7 +85,8 @@ bool LinePolygonsCrossings::lineSegmentCollidesWithBoundary() // // disregard overlapping line segments; probably the next or previous line segment is not overlapping, but will give a collision // when the boundary line segment fully overlaps with the line segment this edge case is not viewed as a collision - if (p1.Y != p0.Y && ((p0.Y >= transformed_start_point_.Y && p1.Y <= transformed_start_point_.Y) || (p1.Y >= transformed_start_point_.Y && p0.Y <= transformed_start_point_.Y))) + if (p1.Y != p0.Y + && ((p0.Y >= transformed_start_point_.Y && p1.Y <= transformed_start_point_.Y) || (p1.Y >= transformed_start_point_.Y && p0.Y <= transformed_start_point_.Y))) { int64_t x = p0.X + (p1.X - p0.X) * (transformed_start_point_.Y - p0.Y) / (p1.Y - p0.Y); @@ -89,23 +98,23 @@ bool LinePolygonsCrossings::lineSegmentCollidesWithBoundary() p0 = p1; } } - + return false; } bool LinePolygonsCrossings::generateCombingPath(CombPath& combPath, int64_t max_comb_distance_ignored, bool fail_on_unavoidable_obstacles) { - if (shorterThen(end_point_ - start_point_, max_comb_distance_ignored) || !lineSegmentCollidesWithBoundary()) + if (shorterThen(end_point_ - start_point_, max_comb_distance_ignored) || ! lineSegmentCollidesWithBoundary()) { - //We're not crossing any boundaries. So skip the comb generation. - combPath.push_back(start_point_); + // We're not crossing any boundaries. So skip the comb generation. + combPath.push_back(start_point_); combPath.push_back(end_point_); return true; } bool success = calcScanlineCrossings(fail_on_unavoidable_obstacles); - if (!success) + if (! success) { return false; } @@ -113,7 +122,7 @@ bool LinePolygonsCrossings::generateCombingPath(CombPath& combPath, int64_t max_ CombPath basicPath; generateBasicCombingPath(basicPath); optimizePath(basicPath, combPath); -// combPath = basicPath; // uncomment to disable comb path optimization + // combPath = basicPath; // uncomment to disable comb path optimization return true; } @@ -150,9 +159,7 @@ void LinePolygonsCrossings::generateBasicCombingPath(const Crossing& min, const std::vector fwd_points; Point prev = combPath.back(); coord_t fwd_len = 0; - for (unsigned int point_idx = min.point_idx_ - ; point_idx != max.point_idx_ - ; point_idx = (point_idx < poly.size() - 1) ? (point_idx + 1) : (0)) + for (unsigned int point_idx = min.point_idx_; point_idx != max.point_idx_; point_idx = (point_idx < poly.size() - 1) ? (point_idx + 1) : (0)) { const Point p = PolygonUtils::getBoundaryPointWithOffset(poly, point_idx, dist_to_move_boundary_point_outside_); fwd_points.push_back(p); @@ -171,11 +178,9 @@ void LinePolygonsCrossings::generateBasicCombingPath(const Crossing& min, const std::vector rev_points; prev = combPath.back(); coord_t rev_len = 0; - unsigned int min_idx = (min.point_idx_ == 0)? poly.size() - 1 : min.point_idx_ - 1; - unsigned int max_idx = (max.point_idx_ == 0)? poly.size() - 1 : max.point_idx_ - 1; - for (unsigned int point_idx = min_idx - ; point_idx != max_idx - ; point_idx = (point_idx > 0) ? (point_idx - 1) : (poly.size() - 1)) + unsigned int min_idx = (min.point_idx_ == 0) ? poly.size() - 1 : min.point_idx_ - 1; + unsigned int max_idx = (max.point_idx_ == 0) ? poly.size() - 1 : max.point_idx_ - 1; + for (unsigned int point_idx = min_idx; point_idx != max_idx; point_idx = (point_idx > 0) ? (point_idx - 1) : (poly.size() - 1)) { const Point p = PolygonUtils::getBoundaryPointWithOffset(poly, point_idx, dist_to_move_boundary_point_outside_); rev_points.push_back(p); @@ -201,12 +206,12 @@ void LinePolygonsCrossings::generateBasicCombingPath(const Crossing& min, const combPath.push_back(last); } -bool LinePolygonsCrossings::optimizePath(CombPath& comb_path, CombPath& optimized_comb_path) +bool LinePolygonsCrossings::optimizePath(CombPath& comb_path, CombPath& optimized_comb_path) { optimized_comb_path.push_back(start_point_); - for(unsigned int point_idx = 1; point_idx 0; n >>= 1) { - if (optimized_comb_path.size() > n && !PolygonUtils::polygonCollidesWithLineSegment(optimized_comb_path[optimized_comb_path.size() - n - 1], comb_path[point_idx - 1], loc_to_line_grid_)) + if (optimized_comb_path.size() > n + && ! PolygonUtils::polygonCollidesWithLineSegment(optimized_comb_path[optimized_comb_path.size() - n - 1], comb_path[point_idx - 1], loc_to_line_grid_)) { // we can remove n points from the path without it clashing with the combing boundary for (unsigned i = 0; i < n; ++i) @@ -250,11 +256,11 @@ bool LinePolygonsCrossings::optimizePath(CombPath& comb_path, CombPath& optimize // Point p = optimized_comb_path.back(); - for (float frac : { 0.9, 0.9, 0.7, 0.5 }) + for (double frac : { 0.9, 0.9, 0.7, 0.5 }) { // slide p towards the second point in the comb path p = comb_path[1] + (p - comb_path[1]) * frac; - if (!PolygonUtils::polygonCollidesWithLineSegment(start_point_, p, loc_to_line_grid_)) + if (! PolygonUtils::polygonCollidesWithLineSegment(start_point_, p, loc_to_line_grid_)) { // using the new corner doesn't cause a conflict optimized_comb_path.back() = p; @@ -267,10 +273,10 @@ bool LinePolygonsCrossings::optimizePath(CombPath& comb_path, CombPath& optimize } } } - else + else { // : dont add the newest point - + // TODO: add the below extra optimization? (+/- 7% extra computation time, +/- 2% faster print for Dual_extrusion_support_generation.stl) while (optimized_comb_path.size() > 1) { @@ -278,7 +284,7 @@ bool LinePolygonsCrossings::optimizePath(CombPath& comb_path, CombPath& optimize { break; } - else + else { optimized_comb_path.pop_back(); } @@ -290,18 +296,19 @@ bool LinePolygonsCrossings::optimizePath(CombPath& comb_path, CombPath& optimize { const unsigned n = optimized_comb_path.size(); // the penultimate corner may be deleted if the resulting path doesn't conflict with the boundary - if (!PolygonUtils::polygonCollidesWithLineSegment(optimized_comb_path[n - 2], comb_path.back(), loc_to_line_grid_)) + if (! PolygonUtils::polygonCollidesWithLineSegment(optimized_comb_path[n - 2], comb_path.back(), loc_to_line_grid_)) { optimized_comb_path.pop_back(); } - else { + else + { // that wasn't possible so try and move the penultimate corner without conficting with the boundary // in exactly the same way as we did at the start of the path - for (float frac : { 0.9, 0.9, 0.7, 0.5 }) + for (double frac : { 0.9, 0.9, 0.7, 0.5 }) { // make a new point between the penultimate corner and the corner before that Point p = optimized_comb_path[n - 2] + (optimized_comb_path[n - 1] - optimized_comb_path[n - 2]) * frac; - if (!PolygonUtils::polygonCollidesWithLineSegment(p, comb_path.back(), loc_to_line_grid_)) + if (! PolygonUtils::polygonCollidesWithLineSegment(p, comb_path.back(), loc_to_line_grid_)) { // using the new corner doesn't cause a conflict optimized_comb_path[n - 1] = p; @@ -319,4 +326,4 @@ bool LinePolygonsCrossings::optimizePath(CombPath& comb_path, CombPath& optimize return true; } -}//namespace cura +} // namespace cura diff --git a/src/progress/Progress.cpp b/src/progress/Progress.cpp index a32b50ea94..318657643c 100644 --- a/src/progress/Progress.cpp +++ b/src/progress/Progress.cpp @@ -40,7 +40,7 @@ void Progress::init() void Progress::messageProgress(Progress::Stage stage, int progress_in_stage, int progress_in_stage_max) { double percentage = calcOverallProgress(stage, static_cast(progress_in_stage / static_cast(progress_in_stage_max))); - Application::getInstance().communication_->sendProgress(static_cast(percentage)); + Application::getInstance().communication_->sendProgress(percentage); } void Progress::messageProgressStage(Progress::Stage stage, TimeKeeper* time_keeper) diff --git a/src/settings/AdaptiveLayerHeights.cpp b/src/settings/AdaptiveLayerHeights.cpp index 09d2bf5682..89b34bc64c 100644 --- a/src/settings/AdaptiveLayerHeights.cpp +++ b/src/settings/AdaptiveLayerHeights.cpp @@ -11,7 +11,7 @@ #include "Slice.h" #include "settings/EnumSettings.h" #include "settings/types/Angle.h" -#include "utils/floatpoint.h" +#include "utils/Point3d.h" namespace cura { @@ -201,20 +201,20 @@ void AdaptiveLayerHeights::calculateMeshTriangleSlopes() const MeshVertex& v1 = mesh.vertices_[face.vertex_index_[1]]; const MeshVertex& v2 = mesh.vertices_[face.vertex_index_[2]]; - const FPoint3 p0 = v0.p_; - const FPoint3 p1 = v1.p_; - const FPoint3 p2 = v2.p_; + const Point3d p0 = v0.p_; + const Point3d p1 = v1.p_; + const Point3d p2 = v2.p_; - float min_z = p0.z; + double min_z = p0.z; min_z = std::min(min_z, p1.z); min_z = std::min(min_z, p2.z); - float max_z = p0.z; + double max_z = p0.z; max_z = std::max(max_z, p1.z); max_z = std::max(max_z, p2.z); // calculate the angle of this triangle in the z direction - const FPoint3 n = (p1 - p0).cross(p2 - p0); - const FPoint3 normal = n.normalized(); + const Point3d n = (p1 - p0).cross(p2 - p0); + const Point3d normal = n.normalized(); AngleRadians z_angle = std::acos(std::abs(normal.z)); // prevent flat surfaces from influencing the algorithm diff --git a/src/settings/PathConfigStorage.cpp b/src/settings/PathConfigStorage.cpp index 48ca20d6d2..c0edd6d0e8 100644 --- a/src/settings/PathConfigStorage.cpp +++ b/src/settings/PathConfigStorage.cpp @@ -130,7 +130,7 @@ PathConfigStorage::PathConfigStorage(const SliceDataStorage& storage, const Laye } support_infill_config.reserve(MAX_INFILL_COMBINE); - const float support_infill_line_width_factor + const double support_infill_line_width_factor = (mesh_group_settings.get("adhesion_type") == EPlatformAdhesion::RAFT) ? 1.0_r : line_width_factor_per_extruder[support_infill_extruder_nr]; for (int combine_idx = 0; combine_idx < MAX_INFILL_COMBINE; combine_idx++) { diff --git a/src/skin.cpp b/src/skin.cpp index 3b01559d4e..19e54f2072 100644 --- a/src/skin.cpp +++ b/src/skin.cpp @@ -3,6 +3,8 @@ #include "skin.h" +#include // std::ceil + #include "Application.h" //To get settings. #include "ExtruderTrain.h" #include "Slice.h" @@ -15,8 +17,6 @@ #include "utils/math.h" #include "utils/polygonUtils.h" -#include // std::ceil - #define MIN_AREA_SIZE (0.4 * 0.4) namespace cura @@ -444,7 +444,7 @@ void SkinInfillAreaComputation::generateInfillSupport(SliceMeshStorage& mesh) void SkinInfillAreaComputation::generateGradualInfill(SliceMeshStorage& mesh) { // no early-out for this function; it needs to initialize the [infill_area_per_combine_per_density] - float layer_skip_count = 8; // skip every so many layers as to ignore small gaps in the model making computation more easy + double layer_skip_count = 8; // skip every so many layers as to ignore small gaps in the model making computation more easy if (! mesh.settings.get("skin_no_small_gaps_heuristic")) { layer_skip_count = 1; @@ -454,8 +454,8 @@ void SkinInfillAreaComputation::generateGradualInfill(SliceMeshStorage& mesh) = round_divide(gradual_infill_step_height, mesh.settings.get("layer_height")); // The difference in layer count between consecutive density infill areas // make gradual_infill_step_height divisible by layer_skip_count - float n_skip_steps_per_gradual_step - = std::max(1.0f, std::ceil(gradual_infill_step_layer_count / layer_skip_count)); // only decrease layer_skip_count to make it a divisor of gradual_infill_step_layer_count + double n_skip_steps_per_gradual_step + = std::max(1.0, std::ceil(gradual_infill_step_layer_count / layer_skip_count)); // only decrease layer_skip_count to make it a divisor of gradual_infill_step_layer_count layer_skip_count = gradual_infill_step_layer_count / n_skip_steps_per_gradual_step; const size_t max_infill_steps = mesh.settings.get("gradual_infill_steps"); @@ -496,7 +496,7 @@ void SkinInfillAreaComputation::generateGradualInfill(SliceMeshStorage& mesh) LayerIndex min_layer = layer_idx + infill_step * gradual_infill_step_layer_count + static_cast(layer_skip_count); LayerIndex max_layer = layer_idx + (infill_step + 1) * gradual_infill_step_layer_count; - for (float upper_layer_idx = min_layer; upper_layer_idx <= max_layer; upper_layer_idx += layer_skip_count) + for (double upper_layer_idx = min_layer; upper_layer_idx <= max_layer; upper_layer_idx += layer_skip_count) { if (upper_layer_idx >= mesh.layers.size()) { diff --git a/src/support.cpp b/src/support.cpp index 234ff27dbd..4fcc69630e 100644 --- a/src/support.cpp +++ b/src/support.cpp @@ -240,7 +240,7 @@ void AreaSupport::generateGradualSupport(SliceDataStorage& storage) LayerIndex min_layer{ layer_nr + density_step * gradual_support_step_layer_count + static_cast(layer_skip_count) }; LayerIndex max_layer{ layer_nr + (density_step + 1) * gradual_support_step_layer_count }; - for (float upper_layer_idx = min_layer; upper_layer_idx <= max_layer; upper_layer_idx += layer_skip_count) + for (double upper_layer_idx = min_layer; upper_layer_idx <= max_layer; upper_layer_idx += layer_skip_count) { if (static_cast(upper_layer_idx) >= total_layer_count) { @@ -1753,9 +1753,9 @@ void AreaSupport::generateSupportBottom(SliceDataStorage& storage, const SliceMe const coord_t bottom_outline_offset = mesh_group_settings.get("support_bottom_extruder_nr").settings_.get("support_bottom_offset"); const size_t scan_count = std::max(size_t(1), (bottom_layer_count - 1) / skip_layer_count); // How many measurements to take to generate bottom areas. - const float z_skip = std::max( - 1.0f, - float(bottom_layer_count - 1) / float(scan_count)); // How many layers to skip between measurements. Using float for better spread, but this is later rounded. + const double z_skip = std::max( + 1.0, + double(bottom_layer_count - 1) / double(scan_count)); // How many layers to skip between measurements. Using float for better spread, but this is later rounded. const double minimum_bottom_area = mesh.settings.get("minimum_bottom_area"); std::vector& support_layers = storage.support.supportLayers; @@ -1763,7 +1763,7 @@ void AreaSupport::generateSupportBottom(SliceDataStorage& storage, const SliceMe { const unsigned int bottom_layer_idx_below = std::max(0, int(layer_idx) - int(bottom_layer_count) - int(z_distance_bottom)); Polygons mesh_outlines; - for (float layer_idx_below = bottom_layer_idx_below; std::round(layer_idx_below) < (int)(layer_idx - z_distance_bottom); layer_idx_below += z_skip) + for (double layer_idx_below = bottom_layer_idx_below; std::round(layer_idx_below) < (int)(layer_idx - z_distance_bottom); layer_idx_below += z_skip) { mesh_outlines.add(mesh.layers[std::round(layer_idx_below)].getOutlines()); } @@ -1790,9 +1790,9 @@ void AreaSupport::generateSupportRoof(SliceDataStorage& storage, const SliceMesh const coord_t roof_outline_offset = mesh_group_settings.get("support_roof_extruder_nr").settings_.get("support_roof_offset"); const size_t scan_count = std::max(size_t(1), (roof_layer_count - 1) / skip_layer_count); // How many measurements to take to generate roof areas. - const float z_skip = std::max( - 1.0f, - float(roof_layer_count - 1) / float(scan_count)); // How many layers to skip between measurements. Using float for better spread, but this is later rounded. + const double z_skip = std::max( + 1.0, + double(roof_layer_count - 1) / double(scan_count)); // How many layers to skip between measurements. Using float for better spread, but this is later rounded. const double minimum_roof_area = mesh.settings.get("minimum_roof_area"); std::vector& support_layers = storage.support.supportLayers; @@ -1802,7 +1802,7 @@ void AreaSupport::generateSupportRoof(SliceDataStorage& storage, const SliceMesh std::min(LayerIndex{ support_layers.size() - 1 }, LayerIndex{ layer_idx + roof_layer_count + z_distance_top }) }; // Maximum layer of the model that generates support roof. Polygons mesh_outlines; - for (float layer_idx_above = top_layer_idx_above; layer_idx_above > layer_idx + z_distance_top; layer_idx_above -= z_skip) + for (double layer_idx_above = top_layer_idx_above; layer_idx_above > layer_idx + z_distance_top; layer_idx_above -= z_skip) { mesh_outlines.add(mesh.layers[std::round(layer_idx_above)].getOutlines()); } diff --git a/src/timeEstimate.cpp b/src/timeEstimate.cpp index 3e2345a92f..dcab876932 100644 --- a/src/timeEstimate.cpp +++ b/src/timeEstimate.cpp @@ -3,14 +3,14 @@ #include "timeEstimate.h" -#include "settings/Settings.h" -#include "utils/math.h" - #include #include #include #include +#include "settings/Settings.h" +#include "utils/math.h" + namespace cura { @@ -68,7 +68,7 @@ static inline Velocity maxAllowableSpeed(const Acceleration& acceleration, const } // Calculates the distance (not time) it takes to accelerate from initial_rate to target_rate using the given acceleration: -static inline float estimateAccelerationDistance(const Velocity& initial_rate, const Velocity& target_rate, const Acceleration& acceleration) +static inline double estimateAccelerationDistance(const Velocity& initial_rate, const Velocity& target_rate, const Acceleration& acceleration) { if (acceleration == 0) { diff --git a/src/utils/ExtrusionSegment.cpp b/src/utils/ExtrusionSegment.cpp index 872bae3000..6c152c5612 100644 --- a/src/utils/ExtrusionSegment.cpp +++ b/src/utils/ExtrusionSegment.cpp @@ -12,13 +12,13 @@ namespace cura Polygons ExtrusionSegment::toPolygons() { - return toPolygons(is_reduced); + return toPolygons(is_reduced_); } Polygons ExtrusionSegment::toPolygons(bool reduced) { Polygons ret; - const Point vec = to.p - from.p; + const Point vec = to_.p - from_.p; const coord_t vec_length = vSize(vec); if (vec_length <= 0) // Don't even output the endcaps. @@ -27,10 +27,10 @@ Polygons ExtrusionSegment::toPolygons(bool reduced) } PolygonRef poly = ret.newPoly(); - const float delta_r = 0.5f * std::abs(from.w - to.w); - const float vec_length_fixed = std::max(delta_r, static_cast(vec_length)); + const double delta_r = 0.5 * std::abs(from_.w - to_.w); + const double vec_length_fixed = std::max(delta_r, static_cast(vec_length)); float alpha = std::acos(delta_r / vec_length_fixed); // Angle between the slope along the edge of the polygon (due to varying line width) and the centerline. - if (to.w > from.w) + if (to_.w > from_.w) { alpha = std::numbers::pi - alpha; } @@ -41,7 +41,7 @@ Polygons ExtrusionSegment::toPolygons(bool reduced) RUN_ONCE(spdlog::warn("Line joint slope is out of bounds (should be between -pi and +pi): {}", alpha)); } - float dir = std::atan(vec.Y / static_cast(vec.X)); + double dir = std::atan(vec.Y / static_cast(vec.X)); if (vec.X < 0) { dir += std::numbers::pi; @@ -49,34 +49,38 @@ Polygons ExtrusionSegment::toPolygons(bool reduced) // Draw the endcap on the "from" vertex's end. { - poly.emplace_back(from.p + Point(from.w / 2 * cos(alpha + dir), from.w / 2 * sin(alpha + dir))); + poly.emplace_back(from_.p + Point(from_.w / 2 * cos(alpha + dir), from_.w / 2 * sin(alpha + dir))); - float start_a = 2 * std::numbers::pi; + double start_a = 2 * std::numbers::pi; while (start_a > alpha + dir) { start_a -= a_step; } start_a += a_step; - float end_a = -2 * std::numbers::pi; + double end_a = -2 * std::numbers::pi; while (end_a < 2 * std::numbers::pi - alpha + dir) { end_a += a_step; } // Draw the endcap. - for (float a = start_a; a <= end_a; a += a_step) + for (double a = start_a; a <= end_a; a += a_step) { - poly.emplace_back(from.p + Point(from.w / 2 * cos(a), from.w / 2 * sin(a))); + poly.emplace_back(from_.p + Point(from_.w / 2 * cos(a), from_.w / 2 * sin(a))); } - poly.emplace_back(from.p + Point(from.w / 2 * cos(2 * std::numbers::pi - alpha + dir), from.w / 2 * sin(2 * std::numbers::pi - alpha + dir))); + poly.emplace_back(from_.p + Point(from_.w / 2 * cos(2 * std::numbers::pi - alpha + dir), from_.w / 2 * sin(2 * std::numbers::pi - alpha + dir))); } // Draw the endcap on the "to" vertex's end. { - poly.emplace_back(to.p + Point(to.w / 2 * cos(2 * std::numbers::pi - alpha + dir), to.w / 2 * sin(2 * std::numbers::pi - alpha + dir))); // Also draws the main diagonal from the "from" vertex to the "to" vertex! + poly.emplace_back( + to_.p + + Point( + to_.w / 2 * cos(2 * std::numbers::pi - alpha + dir), + to_.w / 2 * sin(2 * std::numbers::pi - alpha + dir))); // Also draws the main diagonal from the "from" vertex to the "to" vertex! - float start_a = 2 * std::numbers::pi; + double start_a = 2 * std::numbers::pi; while (start_a > alpha + dir) { start_a -= a_step; @@ -88,7 +92,7 @@ Polygons ExtrusionSegment::toPolygons(bool reduced) start_a += a_step; } - float end_a = -2 * std::numbers::pi; + double end_a = -2 * std::numbers::pi; while (end_a < 2 * std::numbers::pi - alpha + dir) end_a += a_step; if (reduced) @@ -103,20 +107,20 @@ Polygons ExtrusionSegment::toPolygons(bool reduced) // Draw the endcap. if (reduced) { - for (float a = end_a; a >= start_a; a -= a_step) // Go in the opposite direction. + for (double a = end_a; a >= start_a; a -= a_step) // Go in the opposite direction. { - poly.emplace_back(to.p + Point(to.w / 2 * cos(a), to.w / 2 * sin(a))); + poly.emplace_back(to_.p + Point(to_.w / 2 * cos(a), to_.w / 2 * sin(a))); } } else { - for (float a = end_a; a <= start_a; a += a_step) + for (double a = end_a; a <= start_a; a += a_step) { - poly.emplace_back(to.p + Point(to.w / 2 * cos(a), to.w / 2 * sin(a))); + poly.emplace_back(to_.p + Point(to_.w / 2 * cos(a), to_.w / 2 * sin(a))); } } - poly.emplace_back(to.p + Point(to.w / 2 * cos(alpha + dir), to.w / 2 * sin(alpha + dir))); + poly.emplace_back(to_.p + Point(to_.w / 2 * cos(alpha + dir), to_.w / 2 * sin(alpha + dir))); // The other main diagonal from the "to" vertex to the "from" vertex is implicit in the closing of the polygon. } @@ -134,19 +138,19 @@ Polygons ExtrusionSegment::toPolygons(bool reduced) std::vector ExtrusionSegment::discretize(coord_t step_size) { - Point a = from.p; - Point b = to.p; + Point a = from_.p; + Point b = to_.p; Point ab = b - a; coord_t ab_length = vSize(ab); coord_t step_count = std::max(static_cast(1), (ab_length + step_size / 2) / step_size); std::vector discretized; for (coord_t step = 0; step < step_count; step++) { - ExtrusionJunction mid(a + ab * (step + 1) / step_count, from.w + (to.w - from.w) * (step + 1) / step_count, from.perimeter_index); - discretized.emplace_back(from, mid, is_odd, true); - from = mid; + ExtrusionJunction mid(a + ab * (step + 1) / step_count, from_.w + (to_.w - from_.w) * (step + 1) / step_count, from_.perimeter_index); + discretized.emplace_back(from_, mid, is_odd_, true); + from_ = mid; } - discretized.back().is_reduced = is_reduced; + discretized.back().is_reduced_ = is_reduced_; return discretized; } diff --git a/src/utils/FMatrix4x3.cpp b/src/utils/FMatrix4x3.cpp index a52621b680..0aa49bc434 100644 --- a/src/utils/FMatrix4x3.cpp +++ b/src/utils/FMatrix4x3.cpp @@ -5,7 +5,7 @@ #include "settings/types/Ratio.h" //Scale factor. #include "utils/IntPoint.h" //Conversion directly into integer-based coordinates. -#include "utils/floatpoint.h" //This matrix gets applied to floating point coordinates. +#include "utils/Point3d.h" //This matrix gets applied to floating point coordinates. namespace cura { @@ -46,7 +46,7 @@ FMatrix4x3::FMatrix4x3() m[3][2] = 0.0; } -Point3 FMatrix4x3::apply(const FPoint3& p) const +Point3 FMatrix4x3::apply(const Point3d& p) const { return Point3( MM2INT(p.x * m[0][0] + p.y * m[1][0] + p.z * m[2][0] + m[3][0]), diff --git a/src/utils/LinearAlg2D.cpp b/src/utils/LinearAlg2D.cpp index a917c073e2..98a9b896fa 100644 --- a/src/utils/LinearAlg2D.cpp +++ b/src/utils/LinearAlg2D.cpp @@ -3,16 +3,16 @@ #include "utils/linearAlg2D.h" -#include "utils/IntPoint.h" // dot - #include // swap #include #include // atan2 +#include "utils/IntPoint.h" // dot + namespace cura { -float LinearAlg2D::getAngleLeft(const Point& a, const Point& b, const Point& c) +double LinearAlg2D::getAngleLeft(const Point& a, const Point& b, const Point& c) { const Point ba = a - b; const Point bc = c - b; @@ -29,7 +29,7 @@ float LinearAlg2D::getAngleLeft(const Point& a, const Point& b, const Point& c) return std::numbers::pi; // straight bit } } - const float angle = -atan2(det, dott); // from -pi to pi + const double angle = -atan2(det, dott); // from -pi to pi if (angle >= 0) { return angle; diff --git a/src/utils/SVG.cpp b/src/utils/SVG.cpp index c0a3170d76..e495a566aa 100644 --- a/src/utils/SVG.cpp +++ b/src/utils/SVG.cpp @@ -8,7 +8,7 @@ #include #include "utils/ExtrusionLine.h" -#include "utils/floatpoint.h" +#include "utils/Point3d.h" #include "utils/polygon.h" namespace cura @@ -145,9 +145,9 @@ Point SVG::transform(const Point& p) const return Point(std::llrint(static_cast(p.X - aabb_.min.X) * scale_), std::llrint(static_cast(p.Y - aabb_.min.Y) * scale_)); } -FPoint3 SVG::transformF(const Point& p) const +Point3d SVG::transformF(const Point& p) const { - return FPoint3(static_cast(static_cast(p.X - aabb_.min.X) * scale_), static_cast(static_cast(p.Y - aabb_.min.Y) * scale_), 0.0f); + return Point3d(static_cast(p.X - aabb_.min.X) * scale_, static_cast(p.Y - aabb_.min.Y) * scale_, 0.0); } void SVG::writeComment(const std::string& comment) const @@ -155,7 +155,7 @@ void SVG::writeComment(const std::string& comment) const fprintf(out_, "\n", comment.c_str()); } -void SVG::writeAreas(const Polygons& polygons, const ColorObject color, const ColorObject outline_color, const float stroke_width) const +void SVG::writeAreas(const Polygons& polygons, const ColorObject color, const ColorObject outline_color, const double stroke_width) const { std::vector parts = polygons.splitIntoParts(); for (auto part_it = parts.rbegin(); part_it != parts.rend(); ++part_it) @@ -166,7 +166,7 @@ void SVG::writeAreas(const Polygons& polygons, const ColorObject color, const Co fprintf(out_, "(fp.x), static_cast(fp.y)); } if (j == 0) @@ -177,7 +177,7 @@ void SVG::writeAreas(const Polygons& polygons, const ColorObject color, const Co } } -void SVG::writeAreas(ConstPolygonRef polygon, const ColorObject color, const ColorObject outline_color, const float stroke_width) const +void SVG::writeAreas(ConstPolygonRef polygon, const ColorObject color, const ColorObject outline_color, const double stroke_width) const { fprintf( out_, @@ -187,15 +187,15 @@ void SVG::writeAreas(ConstPolygonRef polygon, const ColorObject color, const Col static_cast(stroke_width)); // The beginning of the polygon tag. for (const Point& point : polygon) // Add every point to the list of points. { - FPoint3 transformed = transformF(point); + Point3d transformed = transformF(point); fprintf(out_, "%f,%f ", static_cast(transformed.x), static_cast(transformed.y)); } fprintf(out_, "\" />\n"); // The end of the polygon tag. } -void SVG::writePoint(const Point& p, const bool write_coords, const float size, const ColorObject color) const +void SVG::writePoint(const Point& p, const bool write_coords, const double size, const ColorObject color) const { - FPoint3 pf = transformF(p); + Point3d pf = transformF(p); fprintf( out_, "\n", @@ -210,7 +210,7 @@ void SVG::writePoint(const Point& p, const bool write_coords, const float size, } } -void SVG::writePoints(ConstPolygonRef poly, const bool write_coords, const float size, const ColorObject color) const +void SVG::writePoints(ConstPolygonRef poly, const bool write_coords, const double size, const ColorObject color) const { for (const Point& p : poly) { @@ -218,7 +218,7 @@ void SVG::writePoints(ConstPolygonRef poly, const bool write_coords, const float } } -void SVG::writePoints(const Polygons& polygons, const bool write_coords, const float size, const ColorObject color) const +void SVG::writePoints(const Polygons& polygons, const bool write_coords, const double size, const ColorObject color) const { for (const ConstPolygonRef poly : polygons) { @@ -233,7 +233,7 @@ void SVG::writeLines(const std::vector& polyline, const ColorObject color return; } - FPoint3 transformed = transformF(polyline[0]); // Element 0 must exist due to the check above. + Point3d transformed = transformF(polyline[0]); // Element 0 must exist due to the check above. fprintf( out_, "& polyline, const ColorObject color fprintf(out_, "\" />\n"); // Write the end of the tag. } -void SVG::writeLine(const Point& a, const Point& b, const ColorObject color, const float stroke_width) const +void SVG::writeLine(const Point& a, const Point& b, const ColorObject color, const double stroke_width) const { - FPoint3 fa = transformF(a); - FPoint3 fb = transformF(b); + Point3d fa = transformF(a); + Point3d fb = transformF(b); fprintf( out_, "\n", @@ -263,17 +263,17 @@ void SVG::writeLine(const Point& a, const Point& b, const ColorObject color, con static_cast(stroke_width)); } -void SVG::writeArrow(const Point& a, const Point& b, const ColorObject color, const float stroke_width, const float head_size) const +void SVG::writeArrow(const Point& a, const Point& b, const ColorObject color, const double stroke_width, const double head_size) const { - FPoint3 fa = transformF(a); - FPoint3 fb = transformF(b); - FPoint3 ab = fb - fa; - FPoint3 normal = FPoint3(ab.y, -ab.x, 0.0).normalized(); - FPoint3 direction = ab.normalized(); - - FPoint3 tip = fb + normal * head_size - direction * head_size; - FPoint3 b_base = fb + normal * stroke_width - direction * stroke_width * 2.41f; - FPoint3 a_base = fa + normal * stroke_width; + Point3d fa = transformF(a); + Point3d fb = transformF(b); + Point3d ab = fb - fa; + Point3d normal = Point3d(ab.y, -ab.x, 0.0).normalized(); + Point3d direction = ab.normalized(); + + Point3d tip = fb + normal * head_size - direction * head_size; + Point3d b_base = fb + normal * stroke_width - direction * stroke_width * 2.41f; + Point3d a_base = fa + normal * stroke_width; fprintf( out_, "", @@ -290,10 +290,10 @@ void SVG::writeArrow(const Point& a, const Point& b, const ColorObject color, co static_cast(a_base.y)); } -void SVG::writeLineRGB(const Point& from, const Point& to, const int r, const int g, const int b, const float stroke_width) const +void SVG::writeLineRGB(const Point& from, const Point& to, const int r, const int g, const int b, const double stroke_width) const { - FPoint3 fa = transformF(from); - FPoint3 fb = transformF(to); + Point3d fa = transformF(from); + Point3d fb = transformF(to); fprintf( out_, "\n", @@ -309,8 +309,8 @@ void SVG::writeLineRGB(const Point& from, const Point& to, const int r, const in void SVG::writeDashedLine(const Point& a, const Point& b, ColorObject color) const { - FPoint3 fa = transformF(a); - FPoint3 fb = transformF(b); + Point3d fa = transformF(a); + Point3d fb = transformF(b); fprintf( out_, "\n", @@ -321,9 +321,9 @@ void SVG::writeDashedLine(const Point& a, const Point& b, ColorObject color) con toString(color).c_str()); } -void SVG::writeText(const Point& p, const std::string& txt, const ColorObject color, const float font_size) const +void SVG::writeText(const Point& p, const std::string& txt, const ColorObject color, const double font_size) const { - FPoint3 pf = transformF(p); + Point3d pf = transformF(p); fprintf( out_, "%s\n", @@ -334,7 +334,7 @@ void SVG::writeText(const Point& p, const std::string& txt, const ColorObject co txt.c_str()); } -void SVG::writePolygons(const Polygons& polys, const ColorObject color, const float stroke_width) const +void SVG::writePolygons(const Polygons& polys, const ColorObject color, const double stroke_width) const { for (ConstPolygonRef poly : polys) { @@ -342,7 +342,7 @@ void SVG::writePolygons(const Polygons& polys, const ColorObject color, const fl } } -void SVG::writePolygon(ConstPolygonRef poly, const ColorObject color, const float stroke_width) const +void SVG::writePolygon(ConstPolygonRef poly, const ColorObject color, const double stroke_width) const { if (poly.size() == 0) { @@ -377,7 +377,7 @@ void SVG::writePolygon(ConstPolygonRef poly, const ColorObject color, const floa } -void SVG::writePolylines(const Polygons& polys, const ColorObject color, const float stroke_width) const +void SVG::writePolylines(const Polygons& polys, const ColorObject color, const double stroke_width) const { for (ConstPolygonRef poly : polys) { @@ -385,7 +385,7 @@ void SVG::writePolylines(const Polygons& polys, const ColorObject color, const f } } -void SVG::writePolyline(ConstPolygonRef poly, const ColorObject color, const float stroke_width) const +void SVG::writePolyline(ConstPolygonRef poly, const ColorObject color, const double stroke_width) const { if (poly.size() == 0) { @@ -416,7 +416,7 @@ void SVG::writePolyline(ConstPolygonRef poly, const ColorObject color, const flo } } -void SVG::writePaths(const std::vector& paths, const ColorObject color, const float width_factor) const +void SVG::writePaths(const std::vector& paths, const ColorObject color, const double width_factor) const { for (const VariableWidthLines& lines : paths) { @@ -424,7 +424,7 @@ void SVG::writePaths(const std::vector& paths, const ColorOb } } -void SVG::writeLines(const VariableWidthLines& lines, const ColorObject color, const float width_factor) const +void SVG::writeLines(const VariableWidthLines& lines, const ColorObject color, const double width_factor) const { for (const ExtrusionLine& line : lines) { @@ -432,9 +432,9 @@ void SVG::writeLines(const VariableWidthLines& lines, const ColorObject color, c } } -void SVG::writeLine(const ExtrusionLine& line, const ColorObject color, const float width_factor) const +void SVG::writeLine(const ExtrusionLine& line, const ColorObject color, const double width_factor) const { - constexpr float minimum_line_width = 10; // Always have some width, otherwise some lines become completely invisible. + constexpr double minimum_line_width = 10; // Always have some width, otherwise some lines become completely invisible. if (line.junctions.empty()) // Only draw lines that have at least 2 junctions, otherwise they are degenerate. { return; @@ -448,12 +448,12 @@ void SVG::writeLine(const ExtrusionLine& line, const ColorObject color, const fl const Point direction_vector = end_vertex.p - start_vertex.p; const Point direction_left = turn90CCW(direction_vector); const Point direction_right = -direction_left; // Opposite of left. - const FPoint3 start_left - = transformF(start_vertex.p + normal(direction_left, std::llrint(std::max(minimum_line_width, static_cast(start_vertex.w) * width_factor)))); - const FPoint3 start_right - = transformF(start_vertex.p + normal(direction_right, std::llrint(std::max(minimum_line_width, static_cast(start_vertex.w) * width_factor)))); - const FPoint3 end_left = transformF(end_vertex.p + normal(direction_left, std::llrint(std::max(minimum_line_width, static_cast(end_vertex.w) * width_factor)))); - const FPoint3 end_right = transformF(end_vertex.p + normal(direction_right, std::llrint(std::max(minimum_line_width, static_cast(end_vertex.w) * width_factor)))); + const Point3d start_left + = transformF(start_vertex.p + normal(direction_left, std::llrint(std::max(minimum_line_width, static_cast(start_vertex.w) * width_factor)))); + const Point3d start_right + = transformF(start_vertex.p + normal(direction_right, std::llrint(std::max(minimum_line_width, static_cast(start_vertex.w) * width_factor)))); + const Point3d end_left = transformF(end_vertex.p + normal(direction_left, std::llrint(std::max(minimum_line_width, static_cast(end_vertex.w) * width_factor)))); + const Point3d end_right = transformF(end_vertex.p + normal(direction_right, std::llrint(std::max(minimum_line_width, static_cast(end_vertex.w) * width_factor)))); fprintf( out_, @@ -472,9 +472,9 @@ void SVG::writeLine(const ExtrusionLine& line, const ColorObject color, const fl } } -void SVG::writeCoordinateGrid(const coord_t grid_size, const Color color, const float stroke_width, const float font_size) const +void SVG::writeCoordinateGrid(const coord_t grid_size, const Color color, const double stroke_width, const double font_size) const { - constexpr float dist_from_edge = 0.05f; // As fraction of image width or height. + constexpr double dist_from_edge = 0.05; // As fraction of image width or height. const coord_t min_x = aabb_.min.X - (aabb_.min.X % grid_size); const coord_t min_y = aabb_.min.Y - (aabb_.min.Y % grid_size); @@ -483,14 +483,14 @@ void SVG::writeCoordinateGrid(const coord_t grid_size, const Color color, const writeLine(Point(x, aabb_.min.Y), Point(x, aabb_.max.Y), color, stroke_width); std::stringstream ss; ss << INT2MM(x); - writeText(Point(x, std::llrint(static_cast(aabb_.min.Y) + static_cast(aabb_.max.Y - aabb_.min.Y) * dist_from_edge)), ss.str(), color, font_size); + writeText(Point(x, std::llrint(static_cast(aabb_.min.Y) + static_cast(aabb_.max.Y - aabb_.min.Y) * dist_from_edge)), ss.str(), color, font_size); } for (coord_t y = min_y; y < aabb_.max.Y; y += grid_size) { writeLine(Point(aabb_.min.X, y), Point(aabb_.max.Y, y), color, stroke_width); std::stringstream ss; ss << INT2MM(y); - writeText(Point(std::llrint(static_cast(aabb_.min.X) + static_cast(aabb_.max.X - aabb_.min.X) * dist_from_edge), y), ss.str(), color, font_size); + writeText(Point(std::llrint(static_cast(aabb_.min.X) + static_cast(aabb_.max.X - aabb_.min.X) * dist_from_edge), y), ss.str(), color, font_size); } } diff --git a/src/utils/ToolpathVisualizer.cpp b/src/utils/ToolpathVisualizer.cpp index 4e470e34e5..1b5d294b89 100644 --- a/src/utils/ToolpathVisualizer.cpp +++ b/src/utils/ToolpathVisualizer.cpp @@ -10,20 +10,20 @@ namespace cura void ToolpathVisualizer::outline(const Polygons& input) { - svg.writeAreas(input, SVG::Color::GRAY, SVG::Color::NONE, 2); - svg.nextLayer(); + svg_.writeAreas(input, SVG::Color::GRAY, SVG::Color::NONE, 2); + svg_.nextLayer(); } void ToolpathVisualizer::toolpaths(const std::vector& all_segments, bool rounded_visualization) { - for (float w = .9; w > .25; w = 1.0 - (1.0 - w) * 1.2) + for (double w = .9; w > .25; w = 1.0 - (1.0 - w) * 1.2) { Polygons polys; for (size_t segment_idx = 0; segment_idx < all_segments.size(); segment_idx++) { ExtrusionSegment s = all_segments[segment_idx]; - s.from.w *= w / .9; - s.to.w *= w / .9; + s.from_.w *= w / .9; + s.to_.w *= w / .9; Polygons covered = s.toPolygons(false); polys.add(covered); } @@ -32,33 +32,33 @@ void ToolpathVisualizer::toolpaths(const std::vector& all_segm polys = polys.execute(ClipperLib::pftNonZero); polys = PolygonUtils::connect(polys); for (PolygonRef connected : polys) - svg.writeAreas(connected, clr, SVG::Color::NONE); + svg_.writeAreas(connected, clr, SVG::Color::NONE); if (! rounded_visualization) break; } - svg.nextLayer(); + svg_.nextLayer(); } void ToolpathVisualizer::underfill(const Polygons& underfills) { - svg.writeAreas(underfills, SVG::ColorObject(0, 128, 255), SVG::Color::NONE); - svg.nextLayer(); + svg_.writeAreas(underfills, SVG::ColorObject(0, 128, 255), SVG::Color::NONE); + svg_.nextLayer(); } void ToolpathVisualizer::overfill(const Polygons& overfills, const Polygons& double_overfills) { - svg.writeAreas(overfills, SVG::ColorObject(255, 128, 0), SVG::Color::NONE); - svg.nextLayer(); - svg.writeAreas(double_overfills, SVG::ColorObject(255, 100, 0), SVG::Color::NONE); + svg_.writeAreas(overfills, SVG::ColorObject(255, 128, 0), SVG::Color::NONE); + svg_.nextLayer(); + svg_.writeAreas(double_overfills, SVG::ColorObject(255, 100, 0), SVG::Color::NONE); if (! double_overfills.empty()) { - svg.nextLayer(); + svg_.nextLayer(); } } void ToolpathVisualizer::width_legend(const Polygons& input, coord_t nozzle_size, coord_t max_dev, coord_t min_w, bool rounded_visualization) { - auto to_string = [](float v) + auto to_string = [](double v) { std::ostringstream ss; ss << v; @@ -71,17 +71,17 @@ void ToolpathVisualizer::width_legend(const Polygons& input, coord_t nozzle_size legend_btm.p += (legend_mid.p - legend_btm.p) / 4; legend_top.p += (legend_mid.p - legend_top.p) / 4; ExtrusionSegment legend_segment(legend_btm, legend_top, true, false); - svg.writeAreas(legend_segment.toPolygons(false), SVG::ColorObject(200, 200, 200), SVG::Color::NONE); // real outline + svg_.writeAreas(legend_segment.toPolygons(false), SVG::ColorObject(200, 200, 200), SVG::Color::NONE); // real outline std::vector all_segments_plus; all_segments_plus.emplace_back(legend_segment); // colored Point legend_text_offset(nozzle_size, 0); - svg.writeText(legend_top.p + legend_text_offset, to_string(INT2MM(legend_top.w))); - svg.writeText(legend_btm.p + legend_text_offset, to_string(INT2MM(legend_btm.w))); - svg.writeText(legend_mid.p + legend_text_offset, to_string(INT2MM(legend_mid.w))); - svg.writeLine(legend_top.p, legend_top.p + legend_text_offset); - svg.writeLine(legend_btm.p, legend_btm.p + legend_text_offset); - svg.writeLine(legend_mid.p, legend_mid.p + legend_text_offset); + svg_.writeText(legend_top.p + legend_text_offset, to_string(INT2MM(legend_top.w))); + svg_.writeText(legend_btm.p + legend_text_offset, to_string(INT2MM(legend_btm.w))); + svg_.writeText(legend_mid.p + legend_text_offset, to_string(INT2MM(legend_mid.w))); + svg_.writeLine(legend_top.p, legend_top.p + legend_text_offset); + svg_.writeLine(legend_btm.p, legend_btm.p + legend_text_offset); + svg_.writeLine(legend_mid.p, legend_mid.p + legend_text_offset); widths(all_segments_plus, nozzle_size, max_dev, min_w, rounded_visualization); } @@ -103,7 +103,7 @@ void ToolpathVisualizer::widths( // for (PolygonRef connected : connecteds) // svg.writeAreas(connected, SVG::Color::BLACK, SVG::Color::NONE); - for (float w = .9; w > .25; w = 1.0 - (1.0 - w) * 1.2) + for (double w = 0.9; w > 0.25; w = 1.0 - (1.0 - w) * 1.2) { int brightness = rounded_visualization ? 255 - 200 * (w - .25) : 192; for (size_t segment_idx = 0; segment_idx < all_segments.size(); segment_idx++) @@ -113,9 +113,9 @@ void ToolpathVisualizer::widths( // ss.to.w *= w; for (ExtrusionSegment s : ss.discretize(MM2INT(0.1))) { - coord_t avg_w = (s.from.w + s.to.w) / 2; + coord_t avg_w = (s.from_.w + s.to_.w) / 2; Point3 clr; - float color_ratio = std::min(1.0, double(std::abs(avg_w - nozzle_size)) / max_dev); + double color_ratio = std::min(1.0, double(std::abs(avg_w - nozzle_size)) / max_dev); color_ratio = color_ratio * .5 + .5 * sqrt(color_ratio); if (avg_w > nozzle_size) { @@ -133,23 +133,23 @@ void ToolpathVisualizer::widths( // clr.y = clr.y * (255 - 92 * clr.dot(green) / green.vSize() / 255) / 255; if (exaggerate_widths) { - s.from.w = std::max(min_w, min_w + (s.from.w - (nozzle_size - max_dev)) * 5 / 4); - s.to.w = std::max(min_w, min_w + (s.to.w - (nozzle_size - max_dev)) * 5 / 4); + s.from_.w = std::max(min_w, min_w + (s.from_.w - (nozzle_size - max_dev)) * 5 / 4); + s.to_.w = std::max(min_w, min_w + (s.to_.w - (nozzle_size - max_dev)) * 5 / 4); } // else // { // s.from.w *= 0.9; // s.to.w *= 0.9; // } - s.from.w *= w / .9; - s.to.w *= w / .9; + s.from_.w *= w / .9; + s.to_.w *= w / .9; Polygons covered = s.toPolygons(); - svg.writeAreas(covered, SVG::ColorObject(clr.x_, clr.y_, clr.z_), SVG::Color::NONE); + svg_.writeAreas(covered, SVG::ColorObject(clr.x_, clr.y_, clr.z_), SVG::Color::NONE); } } if (! rounded_visualization) break; - svg.nextLayer(); + svg_.nextLayer(); } } diff --git a/src/utils/VoronoiUtils.cpp b/src/utils/VoronoiUtils.cpp index 0a134906da..fa1d5dc6e5 100644 --- a/src/utils/VoronoiUtils.cpp +++ b/src/utils/VoronoiUtils.cpp @@ -3,13 +3,13 @@ #include "utils/VoronoiUtils.h" -#include "utils/linearAlg2D.h" -#include "utils/macros.h" +#include +#include #include -#include -#include +#include "utils/linearAlg2D.h" +#include "utils/macros.h" namespace cura { @@ -117,7 +117,7 @@ const VoronoiUtils::Segment& VoronoiUtils::getSourceSegment(const vd_t::cell_typ } -std::vector VoronoiUtils::discretizeParabola(const Point& p, const Segment& segment, Point s, Point e, coord_t approximate_step_size, float transitioning_angle) +std::vector VoronoiUtils::discretizeParabola(const Point& p, const Segment& segment, Point s, Point e, coord_t approximate_step_size, double transitioning_angle) { std::vector discretized; // x is distance of point projected on the segment ab @@ -147,7 +147,7 @@ std::vector VoronoiUtils::discretizeParabola(const Point& p, const Segmen return discretized; } - const float marking_bound = atan(transitioning_angle * 0.5); + const double marking_bound = atan(transitioning_angle * 0.5); coord_t msx = -marking_bound * d; // projected marking_start coord_t mex = marking_bound * d; // projected marking_end const coord_t marking_start_end_h = msx * msx / (2 * d) + d / 2; @@ -174,7 +174,7 @@ std::vector VoronoiUtils::discretizeParabola(const Point& p, const Segmen RUN_ONCE(spdlog::warn("Failing to discretize parabola! Must add an apex or one of the endpoints.")); } - const coord_t step_count = static_cast(static_cast(std::abs(ex - sx)) / approximate_step_size + 0.5); + const coord_t step_count = static_cast(static_cast(std::abs(ex - sx)) / approximate_step_size + 0.5); discretized.emplace_back(s); for (coord_t step = 1; step < step_count; step++) diff --git a/src/utils/VoxelUtils.cpp b/src/utils/VoxelUtils.cpp index 0c006ba910..a00b0d4dfd 100644 --- a/src/utils/VoxelUtils.cpp +++ b/src/utils/VoxelUtils.cpp @@ -68,7 +68,7 @@ bool VoxelUtils::walkLine(Point3 start, Point3 end, const std::function::max(); + double percentage_along_line = std::numeric_limits::max(); for (int dim = 0; dim < 3; dim++) { if (diff[dim] == 0) @@ -76,7 +76,7 @@ bool VoxelUtils::walkLine(Point3 start, Point3 end, const std::function 0) * cell_size_[dim]; - float percentage_along_line_here = (crossing_boundary - start[dim]) / static_cast(diff[dim]); + double percentage_along_line_here = (crossing_boundary - start[dim]) / static_cast(diff[dim]); if (percentage_along_line_here < percentage_along_line) { percentage_along_line = percentage_along_line_here; diff --git a/src/utils/polygon.cpp b/src/utils/polygon.cpp index 40974e8d6e..d289a606ad 100644 --- a/src/utils/polygon.cpp +++ b/src/utils/polygon.cpp @@ -485,7 +485,7 @@ void PolygonRef::removeColinearEdges(const AngleRadians max_deviation_angle) const Point& pt = rpath[point_idx]; const Point& next = rpath[(point_idx + 1) % pathlen]; - float angle = LinearAlg2D::getAngleLeft(prev, pt, next); // [0 : 2 * pi] + double angle = LinearAlg2D::getAngleLeft(prev, pt, next); // [0 : 2 * pi] if (angle >= std::numbers::pi) { angle -= std::numbers::pi; @@ -883,7 +883,7 @@ bool ConstPolygonRef::smooth_corner_complex(const Point p1, ListPolyIt& p0_it, L const Point p0_2 = p0_2_it.p(); const Point v02_2 = p0_2 - p2_2; const int64_t v02_2_size = vSize(v02_2); - float progress + double progress = std::min(1.0, INT2MM(shortcut_length - v02_size) / INT2MM(v02_2_size - v02_size)); // account for rounding error when v02_2_size is approx equal to v02_size assert(progress >= 0.0f && progress <= 1.0f && "shortcut length must be between last length and new length"); const Point new_p0 = p0_it.p() + (p0_2 - p0_it.p()) * progress; @@ -1046,7 +1046,7 @@ void ConstPolygonRef::smooth_corner_simple( const Point v12, const Point v02, const int64_t shortcut_length, - float cos_angle) + double cos_angle) { // 1----b---->2 // ^ / @@ -1155,7 +1155,7 @@ void ConstPolygonRef::smooth_outward(const AngleDegrees min_angle, int shortcut_ // 0 int shortcut_length2 = shortcut_length * shortcut_length; - float cos_min_angle = cos(min_angle / 180 * std::numbers::pi); + double cos_min_angle = cos(min_angle / 180 * std::numbers::pi); ListPolygon poly; ListPolyIt::convertPolygonToList(*this, poly); @@ -1184,7 +1184,7 @@ void ConstPolygonRef::smooth_outward(const AngleDegrees min_angle, int shortcut_ const Point v10 = p0 - p1; const Point v12 = p2 - p1; - float cos_angle = INT2MM(INT2MM(dot(v10, v12))) / vSizeMM(v10) / vSizeMM(v12); + double cos_angle = INT2MM(INT2MM(dot(v10, v12))) / vSizeMM(v10) / vSizeMM(v12); bool is_left_angle = LinearAlg2D::pointIsLeftOfLine(p1, p0, p2) > 0; if (cos_angle > cos_min_angle && is_left_angle) { diff --git a/src/utils/polygonUtils.cpp b/src/utils/polygonUtils.cpp index 574f9061b2..a3d6b3c315 100644 --- a/src/utils/polygonUtils.cpp +++ b/src/utils/polygonUtils.cpp @@ -1418,7 +1418,7 @@ double PolygonUtils::relativeHammingDistance(const Polygons& poly_a, const Polyg Polygon PolygonUtils::makeCircle(const Point mid, const coord_t radius, const AngleRadians a_step) { Polygon circle; - for (float a = 0; a < 2 * std::numbers::pi; a += a_step) + for (double a = 0; a < 2 * std::numbers::pi; a += a_step) { circle.emplace_back(mid + Point(radius * cos(a), radius * sin(a))); } From eb461e4107d615ed9d6b687ff6644a3c9afaf41b Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Tue, 21 Nov 2023 14:44:12 +0100 Subject: [PATCH 21/48] Geometry classes naming consistency --- include/MeshGroup.h | 4 +- include/mesh.h | 4 +- include/utils/{FMatrix4x3.h => Matrix4x3D.h} | 18 +++---- include/utils/{Point3d.h => Point3D.h} | 46 ++++++++-------- include/utils/{Point3f.h => Point3F.h} | 12 ++--- include/utils/SVG.h | 4 +- src/MeshGroup.cpp | 22 ++++---- .../ArcusCommunicationPrivate.cpp | 10 ++-- src/communication/CommandLine.cpp | 4 +- src/mesh.cpp | 16 +++--- src/settings/AdaptiveLayerHeights.cpp | 12 ++--- src/settings/Settings.cpp | 6 +-- src/utils/FMatrix4x3.cpp | 18 +++---- src/utils/SVG.cpp | 54 +++++++++---------- tests/integration/SlicePhaseTest.cpp | 6 +-- tests/settings/SettingsTest.cpp | 4 +- 16 files changed, 120 insertions(+), 120 deletions(-) rename include/utils/{FMatrix4x3.h => Matrix4x3D.h} (83%) rename include/utils/{Point3d.h => Point3D.h} (63%) rename include/utils/{Point3f.h => Point3F.h} (76%) diff --git a/include/MeshGroup.h b/include/MeshGroup.h index e9bfd1b782..71ba1f6a6f 100644 --- a/include/MeshGroup.h +++ b/include/MeshGroup.h @@ -10,7 +10,7 @@ namespace cura { -class FMatrix4x3; +class Matrix4x3D; /*! * A MeshGroup is a collection with 1 or more 3D meshes. @@ -50,7 +50,7 @@ class MeshGroup : public NoCopy * \param object_parent_settings (optional) The parent settings object of the new mesh. Defaults to \p meshgroup if none is given. * \return whether the file could be loaded */ -bool loadMeshIntoMeshGroup(MeshGroup* meshgroup, const char* filename, const FMatrix4x3& transformation, Settings& object_parent_settings); +bool loadMeshIntoMeshGroup(MeshGroup* meshgroup, const char* filename, const Matrix4x3D& transformation, Settings& object_parent_settings); } //namespace cura diff --git a/include/mesh.h b/include/mesh.h index dedb1ed311..e50b1303a7 100644 --- a/include/mesh.h +++ b/include/mesh.h @@ -6,7 +6,7 @@ #include "settings/Settings.h" #include "utils/AABB3D.h" -#include "utils/FMatrix4x3.h" +#include "utils/Matrix4x3D.h" namespace cura { @@ -105,7 +105,7 @@ class Mesh * Apply an affine transformation to this mesh's 3D data. * \param transformation The transformation to apply. */ - void transform(const FMatrix4x3& transformation); + void transform(const Matrix4x3D& transformation); /*! * Gets whether this is a printable mesh (not an infill mesh, slicing mesh, diff --git a/include/utils/FMatrix4x3.h b/include/utils/Matrix4x3D.h similarity index 83% rename from include/utils/FMatrix4x3.h rename to include/utils/Matrix4x3D.h index fff6838beb..b4b9aed3cc 100644 --- a/include/utils/FMatrix4x3.h +++ b/include/utils/Matrix4x3D.h @@ -1,15 +1,15 @@ // Copyright (c) 2020 Ultimaker B.V. // CuraEngine is released under the terms of the AGPLv3 or higher. -#ifndef FMATRIX4X3_H -#define FMATRIX4X3_H +#ifndef MATRIX4X3D_H +#define MATRIX4X3D_H #include "settings/types/Ratio.h" namespace cura { -class Point3d; +class Point3D; class Point3; /*! @@ -18,7 +18,7 @@ class Point3; * This matrix behaves as if it's a 4x4 transformation matrix, but the bottom * row is always identity. */ -class FMatrix4x3 +class Matrix4x3D { public: /*! @@ -28,8 +28,8 @@ class FMatrix4x3 * is reduced, all coordinates will go towards this origin. If the scale is * increased, all coordinates will go away from this origin. */ - static FMatrix4x3 scale(const Ratio scale, const Point3 origin); - static FMatrix4x3 scale(const Ratio scale_x, const Ratio scale_y, const Ratio scale_z, const Point3 origin); + static Matrix4x3D scale(const Ratio scale, const Point3 origin); + static Matrix4x3D scale(const Ratio scale_x, const Ratio scale_y, const Ratio scale_z, const Point3 origin); /*! * The matrix data, row-endian. @@ -41,7 +41,7 @@ class FMatrix4x3 /*! * Construct an identity matrix. */ - FMatrix4x3(); + Matrix4x3D(); /*! * Apply this transformation to a coordinate. @@ -51,7 +51,7 @@ class FMatrix4x3 * \param p The coordinate to transform. * \return A transformed coordinate. */ - Point3 apply(const Point3d& p) const; + Point3 apply(const Point3D& p) const; /*! * Apply this transformation to a coordinate. @@ -62,4 +62,4 @@ class FMatrix4x3 }; } // namespace cura -#endif // FMATRIX4X3_H \ No newline at end of file +#endif // MATRIX4X3D_H diff --git a/include/utils/Point3d.h b/include/utils/Point3D.h similarity index 63% rename from include/utils/Point3d.h rename to include/utils/Point3D.h index 713926cc40..5371b16f4d 100644 --- a/include/utils/Point3d.h +++ b/include/utils/Point3D.h @@ -17,61 +17,61 @@ namespace cura Double-precision 3D points are used for geometry computation. They represent millimeters in 3D space. */ -class Point3d +class Point3D { public: double x, y, z; - Point3d() + Point3D() { } - Point3d(double _x, double _y, double _z) + Point3D(double _x, double _y, double _z) : x(_x) , y(_y) , z(_z) { } - Point3d(const Point3& p) + Point3D(const Point3& p) : x(static_cast(p.x_) * .001) , y(static_cast(p.y_) * .001) , z(static_cast(p.z_) * .001) { } - Point3d operator+(const Point3d& p) const + Point3D operator+(const Point3D& p) const { - return Point3d(x + p.x, y + p.y, z + p.z); + return Point3D(x + p.x, y + p.y, z + p.z); } - Point3d operator-(const Point3d& p) const + Point3D operator-(const Point3D& p) const { - return Point3d(x - p.x, y - p.y, z - p.z); + return Point3D(x - p.x, y - p.y, z - p.z); } - Point3d operator*(const double f) const + Point3D operator*(const double f) const { - return Point3d(x * f, y * f, z * f); + return Point3D(x * f, y * f, z * f); } - Point3d operator/(const double f) const + Point3D operator/(const double f) const { - return Point3d(x / f, y / f, z / f); + return Point3D(x / f, y / f, z / f); } - Point3d& operator+=(const Point3d& p) + Point3D& operator+=(const Point3D& p) { x += p.x; y += p.y; z += p.z; return *this; } - Point3d& operator-=(const Point3d& p) + Point3D& operator-=(const Point3D& p) { x -= p.x; y -= p.y; z -= p.z; return *this; } - Point3d& operator*=(const double f) + Point3D& operator*=(const double f) { x *= f; y *= f; @@ -79,11 +79,11 @@ class Point3d return *this; } - bool operator==(Point3d& p) const + bool operator==(Point3D& p) const { return x == p.x && y == p.y && z == p.z; } - bool operator!=(Point3d& p) const + bool operator!=(Point3D& p) const { return x != p.x || y != p.y || z != p.z; } @@ -112,19 +112,19 @@ class Point3d return sqrt(vSize2()); } - inline Point3d normalized() const + inline Point3D normalized() const { return (*this) / vSize(); } - Point3d cross(const Point3d& p) const + Point3D cross(const Point3D& p) const { - return Point3d(y * p.z - z * p.y, z * p.x - x * p.z, x * p.y - y * p.x); + return Point3D(y * p.z - z * p.y, z * p.x - x * p.z, x * p.y - y * p.x); } - static Point3d cross(const Point3& a, const Point3& b) + static Point3D cross(const Point3& a, const Point3& b) { - return Point3d(a).cross(Point3d(b)); + return Point3D(a).cross(Point3D(b)); } Point3 toPoint3() @@ -133,7 +133,7 @@ class Point3d } }; -inline double operator*(Point3d lhs, const Point3d& rhs) +inline double operator*(Point3D lhs, const Point3D& rhs) { return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z; } diff --git a/include/utils/Point3f.h b/include/utils/Point3F.h similarity index 76% rename from include/utils/Point3f.h rename to include/utils/Point3F.h index dd93519199..3d8a5b83d3 100644 --- a/include/utils/Point3f.h +++ b/include/utils/Point3F.h @@ -8,7 +8,7 @@ #include #include "IntPoint.h" -#include "Point3d.h" +#include "Point3D.h" namespace cura @@ -19,25 +19,25 @@ Floating point 3D points are used during model loading as 3D vectors. They represent millimeters in 3D space. This class should not be used for geometric computation. Use Point3d for this purpose. */ -class Point3f +class Point3F { public: float x, y, z; - Point3f() + Point3F() { } - Point3f(double _x, double _y, double _z) + Point3F(double _x, double _y, double _z) : x(_x) , y(_y) , z(_z) { } - Point3d toPoint3d() const + Point3D toPoint3d() const { - return Point3d(static_cast(x), static_cast(y), static_cast(z)); + return Point3D(static_cast(x), static_cast(y), static_cast(z)); } }; diff --git a/include/utils/SVG.h b/include/utils/SVG.h index 400a02010a..8fda644264 100644 --- a/include/utils/SVG.h +++ b/include/utils/SVG.h @@ -14,7 +14,7 @@ namespace cura { -class Point3d; +class Point3D; class SVG : NoCopy { @@ -92,7 +92,7 @@ class SVG : NoCopy /*! * transform a point in real space to canvas space with more precision */ - Point3d transformF(const Point& p) const; + Point3D transformF(const Point& p) const; void writeComment(const std::string& comment) const; diff --git a/src/MeshGroup.cpp b/src/MeshGroup.cpp index 75a4dccf33..ff93cc39c4 100644 --- a/src/MeshGroup.cpp +++ b/src/MeshGroup.cpp @@ -13,8 +13,8 @@ #include #include "settings/types/Ratio.h" //For the shrinkage percentage and scale factor. -#include "utils/FMatrix4x3.h" //To transform the input meshes for shrinkage compensation and to align in command line mode. -#include "utils/Point3f.h" //To accept incoming meshes with floating point vertices. +#include "utils/Matrix4x3D.h" //To transform the input meshes for shrinkage compensation and to align in command line mode. +#include "utils/Point3F.h" //To accept incoming meshes with floating point vertices. #include "utils/gettime.h" #include "utils/section_type.h" #include "utils/string.h" @@ -129,18 +129,18 @@ void MeshGroup::scaleFromBottom(const Ratio factor_xy, const Ratio factor_z) const Point3 center = (max() + min()) / 2; const Point3 origin(center.x_, center.y_, 0); - const FMatrix4x3 transformation = FMatrix4x3::scale(factor_xy, factor_xy, factor_z, origin); + const Matrix4x3D transformation = Matrix4x3D::scale(factor_xy, factor_xy, factor_z, origin); for (Mesh& mesh : meshes) { mesh.transform(transformation); } } -bool loadMeshSTL_ascii(Mesh* mesh, const char* filename, const FMatrix4x3& matrix) +bool loadMeshSTL_ascii(Mesh* mesh, const char* filename, const Matrix4x3D& matrix) { FILE* f = fopen(filename, "rt"); char buffer[1024]; - Point3f vertex; + Point3F vertex; int n = 0; Point3 v0(0, 0, 0), v1(0, 0, 0), v2(0, 0, 0); while (fgets_(buffer, sizeof(buffer), f)) @@ -169,7 +169,7 @@ bool loadMeshSTL_ascii(Mesh* mesh, const char* filename, const FMatrix4x3& matri return true; } -bool loadMeshSTL_binary(Mesh* mesh, const char* filename, const FMatrix4x3& matrix) +bool loadMeshSTL_binary(Mesh* mesh, const char* filename, const Matrix4x3D& matrix) { FILE* f = fopen(filename, "rb"); @@ -212,9 +212,9 @@ bool loadMeshSTL_binary(Mesh* mesh, const char* filename, const FMatrix4x3& matr } float* v = ((float*)buffer) + 3; - Point3 v0 = matrix.apply(Point3f(v[0], v[1], v[2]).toPoint3d()); - Point3 v1 = matrix.apply(Point3f(v[3], v[4], v[5]).toPoint3d()); - Point3 v2 = matrix.apply(Point3f(v[6], v[7], v[8]).toPoint3d()); + Point3 v0 = matrix.apply(Point3F(v[0], v[1], v[2]).toPoint3d()); + Point3 v1 = matrix.apply(Point3F(v[3], v[4], v[5]).toPoint3d()); + Point3 v2 = matrix.apply(Point3F(v[6], v[7], v[8]).toPoint3d()); mesh->addFace(v0, v1, v2); } fclose(f); @@ -222,7 +222,7 @@ bool loadMeshSTL_binary(Mesh* mesh, const char* filename, const FMatrix4x3& matr return true; } -bool loadMeshSTL(Mesh* mesh, const char* filename, const FMatrix4x3& matrix) +bool loadMeshSTL(Mesh* mesh, const char* filename, const Matrix4x3D& matrix) { FILE* f = fopen(filename, "rb"); if (f == nullptr) @@ -279,7 +279,7 @@ bool loadMeshSTL(Mesh* mesh, const char* filename, const FMatrix4x3& matrix) return loadMeshSTL_binary(mesh, filename, matrix); } -bool loadMeshIntoMeshGroup(MeshGroup* meshgroup, const char* filename, const FMatrix4x3& transformation, Settings& object_parent_settings) +bool loadMeshIntoMeshGroup(MeshGroup* meshgroup, const char* filename, const Matrix4x3D& transformation, Settings& object_parent_settings) { TimeKeeper load_timer; diff --git a/src/communication/ArcusCommunicationPrivate.cpp b/src/communication/ArcusCommunicationPrivate.cpp index 6de1c1d9fd..9d5f3118b2 100644 --- a/src/communication/ArcusCommunicationPrivate.cpp +++ b/src/communication/ArcusCommunicationPrivate.cpp @@ -11,8 +11,8 @@ #include "ExtruderTrain.h" #include "Slice.h" #include "settings/types/LayerIndex.h" -#include "utils/FMatrix4x3.h" //To convert vertices to integer-points. -#include "utils/Point3f.h" //To accept vertices (which are provided in floating point). +#include "utils/Matrix4x3D.h" //To convert vertices to integer-points. +#include "utils/Point3F.h" //To accept vertices (which are provided in floating point). namespace cura { @@ -99,10 +99,10 @@ void ArcusCommunication::Private::readMeshGroupMessage(const proto::ObjectList& mesh_group.settings.add(setting.name(), setting.value()); } - FMatrix4x3 matrix; + Matrix4x3D matrix; for (const cura::proto::Object& object : mesh_group_message.objects()) { - const size_t bytes_per_face = sizeof(Point3f) * 3; // 3 vectors per face. + const size_t bytes_per_face = sizeof(Point3F) * 3; // 3 vectors per face. const size_t face_count = object.vertices().size() / bytes_per_face; if (face_count <= 0) @@ -125,7 +125,7 @@ void ArcusCommunication::Private::readMeshGroupMessage(const proto::ObjectList& for (size_t face = 0; face < face_count; face++) { const std::string data = object.vertices().substr(face * bytes_per_face, bytes_per_face); - const Point3f* float_vertices = reinterpret_cast(data.data()); + const Point3F* float_vertices = reinterpret_cast(data.data()); Point3 verts[3]; verts[0] = matrix.apply(float_vertices[0].toPoint3d()); diff --git a/src/communication/CommandLine.cpp b/src/communication/CommandLine.cpp index 9f2e7419e1..de365e2bf9 100644 --- a/src/communication/CommandLine.cpp +++ b/src/communication/CommandLine.cpp @@ -7,7 +7,7 @@ #include "ExtruderTrain.h" #include "FffProcessor.h" //To start a slice and get time estimates. #include "Slice.h" -#include "utils/FMatrix4x3.h" //For the mesh_rotation_matrix setting. +#include "utils/Matrix4x3D.h" //For the mesh_rotation_matrix setting. #include @@ -257,7 +257,7 @@ void CommandLine::sliceNext() } argument = arguments[argument_index]; - const FMatrix4x3 transformation = last_settings->get("mesh_rotation_matrix"); // The transformation applied to the model when loaded. + const Matrix4x3D transformation = last_settings->get("mesh_rotation_matrix"); // The transformation applied to the model when loaded. if (! loadMeshIntoMeshGroup(&slice.scene.mesh_groups[mesh_group_index], argument.c_str(), transformation, last_extruder->settings_)) { diff --git a/src/mesh.cpp b/src/mesh.cpp index 6bcc38f550..377e72c69a 100644 --- a/src/mesh.cpp +++ b/src/mesh.cpp @@ -5,7 +5,7 @@ #include -#include "utils/Point3d.h" +#include "utils/Point3D.h" namespace cura { @@ -97,7 +97,7 @@ void Mesh::expandXY(int64_t offset) } } -void Mesh::transform(const FMatrix4x3& transformation) +void Mesh::transform(const Matrix4x3D& transformation) { for (MeshVertex& v : vertices_) { @@ -203,12 +203,12 @@ int Mesh::getFaceIdxWithPoints(int idx0, int idx1, int notFaceIdx, int notFaceVe has_disconnected_faces = true; } - Point3d vn = vertices_[idx1].p_ - vertices_[idx0].p_; - Point3d n = vn / vn.vSize(); // the normal of the plane in which all normals of faces connected to the edge lie => the normalized normal - Point3d v0 = vertices_[idx1].p_ - vertices_[idx0].p_; + Point3D vn = vertices_[idx1].p_ - vertices_[idx0].p_; + Point3D n = vn / vn.vSize(); // the normal of the plane in which all normals of faces connected to the edge lie => the normalized normal + Point3D v0 = vertices_[idx1].p_ - vertices_[idx0].p_; // the normals below are abnormally directed! : these normals all point counterclockwise (viewed from idx1 to idx0) from the face, irrespective of the direction of the face. - Point3d n0 = Point3d(vertices_[notFaceVertexIdx].p_ - vertices_[idx0].p_).cross(v0); + Point3D n0 = Point3D(vertices_[notFaceVertexIdx].p_ - vertices_[idx0].p_).cross(v0); if (n0.vSize() <= 0) { @@ -227,8 +227,8 @@ int Mesh::getFaceIdxWithPoints(int idx0, int idx1, int notFaceIdx, int notFaceVe break; } - Point3d v1 = vertices_[faces_[candidateFace].vertex_index_[candidateVertex]].p_ - vertices_[idx0].p_; - Point3d n1 = v0.cross(v1); + Point3D v1 = vertices_[faces_[candidateFace].vertex_index_[candidateVertex]].p_ - vertices_[idx0].p_; + Point3D n1 = v0.cross(v1); double dot = n0 * n1; double det = n * n0.cross(n1); diff --git a/src/settings/AdaptiveLayerHeights.cpp b/src/settings/AdaptiveLayerHeights.cpp index 89b34bc64c..82da909588 100644 --- a/src/settings/AdaptiveLayerHeights.cpp +++ b/src/settings/AdaptiveLayerHeights.cpp @@ -11,7 +11,7 @@ #include "Slice.h" #include "settings/EnumSettings.h" #include "settings/types/Angle.h" -#include "utils/Point3d.h" +#include "utils/Point3D.h" namespace cura { @@ -201,9 +201,9 @@ void AdaptiveLayerHeights::calculateMeshTriangleSlopes() const MeshVertex& v1 = mesh.vertices_[face.vertex_index_[1]]; const MeshVertex& v2 = mesh.vertices_[face.vertex_index_[2]]; - const Point3d p0 = v0.p_; - const Point3d p1 = v1.p_; - const Point3d p2 = v2.p_; + const Point3D p0 = v0.p_; + const Point3D p1 = v1.p_; + const Point3D p2 = v2.p_; double min_z = p0.z; min_z = std::min(min_z, p1.z); @@ -213,8 +213,8 @@ void AdaptiveLayerHeights::calculateMeshTriangleSlopes() max_z = std::max(max_z, p2.z); // calculate the angle of this triangle in the z direction - const Point3d n = (p1 - p0).cross(p2 - p0); - const Point3d normal = n.normalized(); + const Point3D n = (p1 - p0).cross(p2 - p0); + const Point3D normal = n.normalized(); AngleRadians z_angle = std::acos(std::abs(normal.z)); // prevent flat surfaces from influencing the algorithm diff --git a/src/settings/Settings.cpp b/src/settings/Settings.cpp index c5e5bb0286..9ec36c2446 100644 --- a/src/settings/Settings.cpp +++ b/src/settings/Settings.cpp @@ -26,7 +26,7 @@ #include "settings/types/Ratio.h" //For ratio settings and percentages. #include "settings/types/Temperature.h" //For temperature settings. #include "settings/types/Velocity.h" //For velocity settings. -#include "utils/FMatrix4x3.h" +#include "utils/Matrix4x3D.h" #include "utils/polygon.h" #include "utils/string.h" //For Escaped. #include "utils/types/string_switch.h" //For string switch. @@ -319,11 +319,11 @@ Polygons Settings::get(const std::string& key) const } template<> -FMatrix4x3 Settings::get(const std::string& key) const +Matrix4x3D Settings::get(const std::string& key) const { const std::string value_string = get(key); - FMatrix4x3 result; + Matrix4x3D result; if (value_string.empty()) { return result; // Standard matrix ([[1,0,0], [0,1,0], [0,0,1]]). diff --git a/src/utils/FMatrix4x3.cpp b/src/utils/FMatrix4x3.cpp index 0aa49bc434..74a337fa31 100644 --- a/src/utils/FMatrix4x3.cpp +++ b/src/utils/FMatrix4x3.cpp @@ -1,23 +1,23 @@ // Copyright (c) 2022 Ultimaker B.V. // CuraEngine is released under the terms of the AGPLv3 or higher. -#include "utils/FMatrix4x3.h" //The definitions we're implementing. +#include "utils/Matrix4x3D.h" //The definitions we're implementing. #include "settings/types/Ratio.h" //Scale factor. #include "utils/IntPoint.h" //Conversion directly into integer-based coordinates. -#include "utils/Point3d.h" //This matrix gets applied to floating point coordinates. +#include "utils/Point3D.h" //This matrix gets applied to floating point coordinates. namespace cura { -FMatrix4x3 FMatrix4x3::scale(const Ratio scale, const Point3 origin) +Matrix4x3D Matrix4x3D::scale(const Ratio scale, const Point3 origin) { - return FMatrix4x3::scale(scale, scale, scale, origin); + return Matrix4x3D::scale(scale, scale, scale, origin); } -FMatrix4x3 FMatrix4x3::scale(const Ratio scale_x, const Ratio scale_y, const Ratio scale_z, const Point3 origin) +Matrix4x3D Matrix4x3D::scale(const Ratio scale_x, const Ratio scale_y, const Ratio scale_z, const Point3 origin) { - FMatrix4x3 result; + Matrix4x3D result; result.m[0][0] = scale_x; // X scale. result.m[1][1] = scale_y; // Y scale. result.m[2][2] = scale_z; // Z scale. @@ -30,7 +30,7 @@ FMatrix4x3 FMatrix4x3::scale(const Ratio scale_x, const Ratio scale_y, const Rat return result; } -FMatrix4x3::FMatrix4x3() +Matrix4x3D::Matrix4x3D() { m[0][0] = 1.0; m[1][0] = 0.0; @@ -46,7 +46,7 @@ FMatrix4x3::FMatrix4x3() m[3][2] = 0.0; } -Point3 FMatrix4x3::apply(const Point3d& p) const +Point3 Matrix4x3D::apply(const Point3D& p) const { return Point3( MM2INT(p.x * m[0][0] + p.y * m[1][0] + p.z * m[2][0] + m[3][0]), @@ -54,7 +54,7 @@ Point3 FMatrix4x3::apply(const Point3d& p) const MM2INT(p.x * m[0][2] + p.y * m[1][2] + p.z * m[2][2] + m[3][2])); } -Point3 FMatrix4x3::apply(const Point3& p) const +Point3 Matrix4x3D::apply(const Point3& p) const { return Point3( m[0][0] * p.x_ + m[1][0] * p.y_ + m[2][0] * p.z_ + m[3][0], diff --git a/src/utils/SVG.cpp b/src/utils/SVG.cpp index e495a566aa..b01a250810 100644 --- a/src/utils/SVG.cpp +++ b/src/utils/SVG.cpp @@ -8,7 +8,7 @@ #include #include "utils/ExtrusionLine.h" -#include "utils/Point3d.h" +#include "utils/Point3D.h" #include "utils/polygon.h" namespace cura @@ -145,9 +145,9 @@ Point SVG::transform(const Point& p) const return Point(std::llrint(static_cast(p.X - aabb_.min.X) * scale_), std::llrint(static_cast(p.Y - aabb_.min.Y) * scale_)); } -Point3d SVG::transformF(const Point& p) const +Point3D SVG::transformF(const Point& p) const { - return Point3d(static_cast(p.X - aabb_.min.X) * scale_, static_cast(p.Y - aabb_.min.Y) * scale_, 0.0); + return Point3D(static_cast(p.X - aabb_.min.X) * scale_, static_cast(p.Y - aabb_.min.Y) * scale_, 0.0); } void SVG::writeComment(const std::string& comment) const @@ -166,7 +166,7 @@ void SVG::writeAreas(const Polygons& polygons, const ColorObject color, const Co fprintf(out_, "(fp.x), static_cast(fp.y)); } if (j == 0) @@ -187,7 +187,7 @@ void SVG::writeAreas(ConstPolygonRef polygon, const ColorObject color, const Col static_cast(stroke_width)); // The beginning of the polygon tag. for (const Point& point : polygon) // Add every point to the list of points. { - Point3d transformed = transformF(point); + Point3D transformed = transformF(point); fprintf(out_, "%f,%f ", static_cast(transformed.x), static_cast(transformed.y)); } fprintf(out_, "\" />\n"); // The end of the polygon tag. @@ -195,7 +195,7 @@ void SVG::writeAreas(ConstPolygonRef polygon, const ColorObject color, const Col void SVG::writePoint(const Point& p, const bool write_coords, const double size, const ColorObject color) const { - Point3d pf = transformF(p); + Point3D pf = transformF(p); fprintf( out_, "\n", @@ -233,7 +233,7 @@ void SVG::writeLines(const std::vector& polyline, const ColorObject color return; } - Point3d transformed = transformF(polyline[0]); // Element 0 must exist due to the check above. + Point3D transformed = transformF(polyline[0]); // Element 0 must exist due to the check above. fprintf( out_, "& polyline, const ColorObject color void SVG::writeLine(const Point& a, const Point& b, const ColorObject color, const double stroke_width) const { - Point3d fa = transformF(a); - Point3d fb = transformF(b); + Point3D fa = transformF(a); + Point3D fb = transformF(b); fprintf( out_, "\n", @@ -265,15 +265,15 @@ void SVG::writeLine(const Point& a, const Point& b, const ColorObject color, con void SVG::writeArrow(const Point& a, const Point& b, const ColorObject color, const double stroke_width, const double head_size) const { - Point3d fa = transformF(a); - Point3d fb = transformF(b); - Point3d ab = fb - fa; - Point3d normal = Point3d(ab.y, -ab.x, 0.0).normalized(); - Point3d direction = ab.normalized(); - - Point3d tip = fb + normal * head_size - direction * head_size; - Point3d b_base = fb + normal * stroke_width - direction * stroke_width * 2.41f; - Point3d a_base = fa + normal * stroke_width; + Point3D fa = transformF(a); + Point3D fb = transformF(b); + Point3D ab = fb - fa; + Point3D normal = Point3D(ab.y, -ab.x, 0.0).normalized(); + Point3D direction = ab.normalized(); + + Point3D tip = fb + normal * head_size - direction * head_size; + Point3D b_base = fb + normal * stroke_width - direction * stroke_width * 2.41f; + Point3D a_base = fa + normal * stroke_width; fprintf( out_, "", @@ -292,8 +292,8 @@ void SVG::writeArrow(const Point& a, const Point& b, const ColorObject color, co void SVG::writeLineRGB(const Point& from, const Point& to, const int r, const int g, const int b, const double stroke_width) const { - Point3d fa = transformF(from); - Point3d fb = transformF(to); + Point3D fa = transformF(from); + Point3D fb = transformF(to); fprintf( out_, "\n", @@ -309,8 +309,8 @@ void SVG::writeLineRGB(const Point& from, const Point& to, const int r, const in void SVG::writeDashedLine(const Point& a, const Point& b, ColorObject color) const { - Point3d fa = transformF(a); - Point3d fb = transformF(b); + Point3D fa = transformF(a); + Point3D fb = transformF(b); fprintf( out_, "\n", @@ -323,7 +323,7 @@ void SVG::writeDashedLine(const Point& a, const Point& b, ColorObject color) con void SVG::writeText(const Point& p, const std::string& txt, const ColorObject color, const double font_size) const { - Point3d pf = transformF(p); + Point3D pf = transformF(p); fprintf( out_, "%s\n", @@ -448,12 +448,12 @@ void SVG::writeLine(const ExtrusionLine& line, const ColorObject color, const do const Point direction_vector = end_vertex.p - start_vertex.p; const Point direction_left = turn90CCW(direction_vector); const Point direction_right = -direction_left; // Opposite of left. - const Point3d start_left + const Point3D start_left = transformF(start_vertex.p + normal(direction_left, std::llrint(std::max(minimum_line_width, static_cast(start_vertex.w) * width_factor)))); - const Point3d start_right + const Point3D start_right = transformF(start_vertex.p + normal(direction_right, std::llrint(std::max(minimum_line_width, static_cast(start_vertex.w) * width_factor)))); - const Point3d end_left = transformF(end_vertex.p + normal(direction_left, std::llrint(std::max(minimum_line_width, static_cast(end_vertex.w) * width_factor)))); - const Point3d end_right = transformF(end_vertex.p + normal(direction_right, std::llrint(std::max(minimum_line_width, static_cast(end_vertex.w) * width_factor)))); + const Point3D end_left = transformF(end_vertex.p + normal(direction_left, std::llrint(std::max(minimum_line_width, static_cast(end_vertex.w) * width_factor)))); + const Point3D end_right = transformF(end_vertex.p + normal(direction_right, std::llrint(std::max(minimum_line_width, static_cast(end_vertex.w) * width_factor)))); fprintf( out_, diff --git a/tests/integration/SlicePhaseTest.cpp b/tests/integration/SlicePhaseTest.cpp index 42508af961..c357169170 100644 --- a/tests/integration/SlicePhaseTest.cpp +++ b/tests/integration/SlicePhaseTest.cpp @@ -9,7 +9,7 @@ #include "Slice.h" // To set up a scene to slice. #include "slicer.h" // Starts the slicing phase that we want to test. #include "utils/Coord_t.h" -#include "utils/FMatrix4x3.h" // To load STL files. +#include "utils/Matrix4x3D.h" // To load STL files. #include "utils/polygon.h" // Creating polygons to compare to sliced layers. #include "utils/polygonUtils.h" // Comparing similarity of polygons. @@ -69,7 +69,7 @@ TEST_F(SlicePhaseTest, Cube) Scene& scene = Application::getInstance().current_slice_->scene; MeshGroup& mesh_group = scene.mesh_groups.back(); - const FMatrix4x3 transformation; + const Matrix4x3D transformation; // Path to cube.stl is relative to CMAKE_CURRENT_SOURCE_DIR/tests. ASSERT_TRUE(loadMeshIntoMeshGroup(&mesh_group, std::filesystem::path(__FILE__).parent_path().append("resources/cube.stl").string().c_str(), transformation, scene.settings)); EXPECT_EQ(mesh_group.meshes.size(), 1); @@ -129,7 +129,7 @@ TEST_F(SlicePhaseTest, Cylinder1000) Scene& scene = Application::getInstance().current_slice_->scene; MeshGroup& mesh_group = scene.mesh_groups.back(); - const FMatrix4x3 transformation; + const Matrix4x3D transformation; // Path to cylinder1000.stl is relative to CMAKE_CURRENT_SOURCE_DIR/tests. ASSERT_TRUE( loadMeshIntoMeshGroup(&mesh_group, std::filesystem::path(__FILE__).parent_path().append("resources/cylinder1000.stl").string().c_str(), transformation, scene.settings)); diff --git a/tests/settings/SettingsTest.cpp b/tests/settings/SettingsTest.cpp index ecc9884a00..8486ce2292 100644 --- a/tests/settings/SettingsTest.cpp +++ b/tests/settings/SettingsTest.cpp @@ -15,7 +15,7 @@ #include "settings/types/Temperature.h" #include "settings/types/Velocity.h" #include "utils/Coord_t.h" -#include "utils/FMatrix4x3.h" //Testing matrix transformation settings. +#include "utils/Matrix4x3D.h" //Testing matrix transformation settings. #include //For std::numbers::pi. #include @@ -184,7 +184,7 @@ TEST_F(SettingsTest, AddSettingFlowTempGraph) TEST_F(SettingsTest, AddSettingFMatrix3x3) { settings.add("test_setting", "[[1.0, 2.0, 3.3],[ 2 , 3.0 , 1.0],[3.0 ,1.0,2.0 ]]"); // Try various spacing and radixes. - auto float_matrix = settings.get("test_setting"); + auto float_matrix = settings.get("test_setting"); EXPECT_DOUBLE_EQ(1.0, float_matrix.m[0][0]); EXPECT_DOUBLE_EQ(2.0, float_matrix.m[1][0]); From db39edeeb820632e94800f493a1238811517134e Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Tue, 21 Nov 2023 14:47:37 +0100 Subject: [PATCH 22/48] Geometry classes variables naming consistency --- include/utils/Point3D.h | 64 ++++++++++----------- include/utils/Point3F.h | 12 ++-- src/MeshGroup.cpp | 2 +- src/settings/AdaptiveLayerHeights.cpp | 14 ++--- src/utils/FMatrix4x3.cpp | 6 +- src/utils/SVG.cpp | 82 +++++++++++++-------------- 6 files changed, 90 insertions(+), 90 deletions(-) diff --git a/include/utils/Point3D.h b/include/utils/Point3D.h index 5371b16f4d..c44f6e79e6 100644 --- a/include/utils/Point3D.h +++ b/include/utils/Point3D.h @@ -20,81 +20,81 @@ They represent millimeters in 3D space. class Point3D { public: - double x, y, z; + double x_, y_, z_; Point3D() { } - Point3D(double _x, double _y, double _z) - : x(_x) - , y(_y) - , z(_z) + Point3D(double x, double y, double z) + : x_(x) + , y_(y) + , z_(z) { } Point3D(const Point3& p) - : x(static_cast(p.x_) * .001) - , y(static_cast(p.y_) * .001) - , z(static_cast(p.z_) * .001) + : x_(static_cast(p.x_) * .001) + , y_(static_cast(p.y_) * .001) + , z_(static_cast(p.z_) * .001) { } Point3D operator+(const Point3D& p) const { - return Point3D(x + p.x, y + p.y, z + p.z); + return Point3D(x_ + p.x_, y_ + p.y_, z_ + p.z_); } Point3D operator-(const Point3D& p) const { - return Point3D(x - p.x, y - p.y, z - p.z); + return Point3D(x_ - p.x_, y_ - p.y_, z_ - p.z_); } Point3D operator*(const double f) const { - return Point3D(x * f, y * f, z * f); + return Point3D(x_ * f, y_ * f, z_ * f); } Point3D operator/(const double f) const { - return Point3D(x / f, y / f, z / f); + return Point3D(x_ / f, y_ / f, z_ / f); } Point3D& operator+=(const Point3D& p) { - x += p.x; - y += p.y; - z += p.z; + x_ += p.x_; + y_ += p.y_; + z_ += p.z_; return *this; } Point3D& operator-=(const Point3D& p) { - x -= p.x; - y -= p.y; - z -= p.z; + x_ -= p.x_; + y_ -= p.y_; + z_ -= p.z_; return *this; } Point3D& operator*=(const double f) { - x *= f; - y *= f; - z *= f; + x_ *= f; + y_ *= f; + z_ *= f; return *this; } bool operator==(Point3D& p) const { - return x == p.x && y == p.y && z == p.z; + return x_ == p.x_ && y_ == p.y_ && z_ == p.z_; } bool operator!=(Point3D& p) const { - return x != p.x || y != p.y || z != p.z; + return x_ != p.x_ || y_ != p.y_ || z_ != p.z_; } double max() const { - if (x > y && x > z) - return x; - if (y > z) - return y; - return z; + if (x_ > y_ && x_ > z_) + return x_; + if (y_ > z_) + return y_; + return z_; } bool testLength(double len) const @@ -104,7 +104,7 @@ class Point3D double vSize2() const { - return x * x + y * y + z * z; + return x_ * x_ + y_ * y_ + z_ * z_; } double vSize() const @@ -119,7 +119,7 @@ class Point3D Point3D cross(const Point3D& p) const { - return Point3D(y * p.z - z * p.y, z * p.x - x * p.z, x * p.y - y * p.x); + return Point3D(y_ * p.z_ - z_ * p.y_, z_ * p.x_ - x_ * p.z_, x_ * p.y_ - y_ * p.x_); } static Point3D cross(const Point3& a, const Point3& b) @@ -129,13 +129,13 @@ class Point3D Point3 toPoint3() { - return Point3(MM2INT(x), MM2INT(y), MM2INT(z)); + return Point3(MM2INT(x_), MM2INT(y_), MM2INT(z_)); } }; inline double operator*(Point3D lhs, const Point3D& rhs) { - return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z; + return lhs.x_ * rhs.x_ + lhs.y_ * rhs.y_ + lhs.z_ * rhs.z_; } } // namespace cura diff --git a/include/utils/Point3F.h b/include/utils/Point3F.h index 3d8a5b83d3..0772521240 100644 --- a/include/utils/Point3F.h +++ b/include/utils/Point3F.h @@ -22,22 +22,22 @@ This class should not be used for geometric computation. Use Point3d for this pu class Point3F { public: - float x, y, z; + float x_, y_, z_; Point3F() { } - Point3F(double _x, double _y, double _z) - : x(_x) - , y(_y) - , z(_z) + Point3F(float x, float y, float z) + : x_(x) + , y_(y) + , z_(z) { } Point3D toPoint3d() const { - return Point3D(static_cast(x), static_cast(y), static_cast(z)); + return Point3D(static_cast(x_), static_cast(y_), static_cast(z_)); } }; diff --git a/src/MeshGroup.cpp b/src/MeshGroup.cpp index ff93cc39c4..4940471de3 100644 --- a/src/MeshGroup.cpp +++ b/src/MeshGroup.cpp @@ -145,7 +145,7 @@ bool loadMeshSTL_ascii(Mesh* mesh, const char* filename, const Matrix4x3D& matri Point3 v0(0, 0, 0), v1(0, 0, 0), v2(0, 0, 0); while (fgets_(buffer, sizeof(buffer), f)) { - if (sscanf(buffer, " vertex %f %f %f", &vertex.x, &vertex.y, &vertex.z) == 3) + if (sscanf(buffer, " vertex %f %f %f", &vertex.x_, &vertex.y_, &vertex.z_) == 3) { n++; switch (n) diff --git a/src/settings/AdaptiveLayerHeights.cpp b/src/settings/AdaptiveLayerHeights.cpp index 82da909588..66fae223bf 100644 --- a/src/settings/AdaptiveLayerHeights.cpp +++ b/src/settings/AdaptiveLayerHeights.cpp @@ -205,17 +205,17 @@ void AdaptiveLayerHeights::calculateMeshTriangleSlopes() const Point3D p1 = v1.p_; const Point3D p2 = v2.p_; - double min_z = p0.z; - min_z = std::min(min_z, p1.z); - min_z = std::min(min_z, p2.z); - double max_z = p0.z; - max_z = std::max(max_z, p1.z); - max_z = std::max(max_z, p2.z); + double min_z = p0.z_; + min_z = std::min(min_z, p1.z_); + min_z = std::min(min_z, p2.z_); + double max_z = p0.z_; + max_z = std::max(max_z, p1.z_); + max_z = std::max(max_z, p2.z_); // calculate the angle of this triangle in the z direction const Point3D n = (p1 - p0).cross(p2 - p0); const Point3D normal = n.normalized(); - AngleRadians z_angle = std::acos(std::abs(normal.z)); + AngleRadians z_angle = std::acos(std::abs(normal.z_)); // prevent flat surfaces from influencing the algorithm if (z_angle == 0) diff --git a/src/utils/FMatrix4x3.cpp b/src/utils/FMatrix4x3.cpp index 74a337fa31..bdf5adb257 100644 --- a/src/utils/FMatrix4x3.cpp +++ b/src/utils/FMatrix4x3.cpp @@ -49,9 +49,9 @@ Matrix4x3D::Matrix4x3D() Point3 Matrix4x3D::apply(const Point3D& p) const { return Point3( - MM2INT(p.x * m[0][0] + p.y * m[1][0] + p.z * m[2][0] + m[3][0]), - MM2INT(p.x * m[0][1] + p.y * m[1][1] + p.z * m[2][1] + m[3][1]), - MM2INT(p.x * m[0][2] + p.y * m[1][2] + p.z * m[2][2] + m[3][2])); + MM2INT(p.x_ * m[0][0] + p.y_ * m[1][0] + p.z_ * m[2][0] + m[3][0]), + MM2INT(p.x_ * m[0][1] + p.y_ * m[1][1] + p.z_ * m[2][1] + m[3][1]), + MM2INT(p.x_ * m[0][2] + p.y_ * m[1][2] + p.z_ * m[2][2] + m[3][2])); } Point3 Matrix4x3D::apply(const Point3& p) const diff --git a/src/utils/SVG.cpp b/src/utils/SVG.cpp index b01a250810..317bd32fba 100644 --- a/src/utils/SVG.cpp +++ b/src/utils/SVG.cpp @@ -167,7 +167,7 @@ void SVG::writeAreas(const Polygons& polygons, const ColorObject color, const Co for (Point& p : part[j]) { Point3D fp = transformF(p); - fprintf(out_, "%f,%f ", static_cast(fp.x), static_cast(fp.y)); + fprintf(out_, "%f,%f ", static_cast(fp.x_), static_cast(fp.y_)); } if (j == 0) fprintf(out_, "\" style=\"fill:%s;stroke:%s;stroke-width:%f\" />\n", toString(color).c_str(), toString(outline_color).c_str(), static_cast(stroke_width)); @@ -188,7 +188,7 @@ void SVG::writeAreas(ConstPolygonRef polygon, const ColorObject color, const Col for (const Point& point : polygon) // Add every point to the list of points. { Point3D transformed = transformF(point); - fprintf(out_, "%f,%f ", static_cast(transformed.x), static_cast(transformed.y)); + fprintf(out_, "%f,%f ", static_cast(transformed.x_), static_cast(transformed.y_)); } fprintf(out_, "\" />\n"); // The end of the polygon tag. } @@ -199,14 +199,14 @@ void SVG::writePoint(const Point& p, const bool write_coords, const double size, fprintf( out_, "\n", - static_cast(pf.x), - static_cast(pf.y), + static_cast(pf.x_), + static_cast(pf.y_), static_cast(size), toString(color).c_str()); if (write_coords) { - fprintf(out_, "%lli,%lli\n", static_cast(pf.x), static_cast(pf.y), p.X, p.Y); + fprintf(out_, "%lli,%lli\n", static_cast(pf.x_), static_cast(pf.y_), p.X, p.Y); } } @@ -238,12 +238,12 @@ void SVG::writeLines(const std::vector& polyline, const ColorObject color out_, "(transformed.x), - static_cast(transformed.y)); // Write the start of the path tag and the first endpoint. + static_cast(transformed.x_), + static_cast(transformed.y_)); // Write the start of the path tag and the first endpoint. for (size_t point = 1; point < polyline.size(); point++) { transformed = transformF(polyline[point]); - fprintf(out_, "L%f,%f", static_cast(transformed.x), static_cast(transformed.y)); // Write a line segment to the next point. + fprintf(out_, "L%f,%f", static_cast(transformed.x_), static_cast(transformed.y_)); // Write a line segment to the next point. } fprintf(out_, "\" />\n"); // Write the end of the tag. } @@ -255,10 +255,10 @@ void SVG::writeLine(const Point& a, const Point& b, const ColorObject color, con fprintf( out_, "\n", - static_cast(fa.x), - static_cast(fa.y), - static_cast(fb.x), - static_cast(fb.y), + static_cast(fa.x_), + static_cast(fa.y_), + static_cast(fb.x_), + static_cast(fb.y_), toString(color).c_str(), static_cast(stroke_width)); } @@ -268,7 +268,7 @@ void SVG::writeArrow(const Point& a, const Point& b, const ColorObject color, co Point3D fa = transformF(a); Point3D fb = transformF(b); Point3D ab = fb - fa; - Point3D normal = Point3D(ab.y, -ab.x, 0.0).normalized(); + Point3D normal = Point3D(ab.y_, -ab.x_, 0.0).normalized(); Point3D direction = ab.normalized(); Point3D tip = fb + normal * head_size - direction * head_size; @@ -278,16 +278,16 @@ void SVG::writeArrow(const Point& a, const Point& b, const ColorObject color, co out_, "", toString(color).c_str(), - static_cast(fa.x), - static_cast(fa.y), - static_cast(fb.x), - static_cast(fb.y), - static_cast(tip.x), - static_cast(tip.y), - static_cast(b_base.x), - static_cast(b_base.y), - static_cast(a_base.x), - static_cast(a_base.y)); + static_cast(fa.x_), + static_cast(fa.y_), + static_cast(fb.x_), + static_cast(fb.y_), + static_cast(tip.x_), + static_cast(tip.y_), + static_cast(b_base.x_), + static_cast(b_base.y_), + static_cast(a_base.x_), + static_cast(a_base.y_)); } void SVG::writeLineRGB(const Point& from, const Point& to, const int r, const int g, const int b, const double stroke_width) const @@ -297,10 +297,10 @@ void SVG::writeLineRGB(const Point& from, const Point& to, const int r, const in fprintf( out_, "\n", - static_cast(fa.x), - static_cast(fa.y), - static_cast(fb.x), - static_cast(fb.y), + static_cast(fa.x_), + static_cast(fa.y_), + static_cast(fb.x_), + static_cast(fb.y_), r, g, b, @@ -314,10 +314,10 @@ void SVG::writeDashedLine(const Point& a, const Point& b, ColorObject color) con fprintf( out_, "\n", - static_cast(fa.x), - static_cast(fa.y), - static_cast(fb.x), - static_cast(fb.y), + static_cast(fa.x_), + static_cast(fa.y_), + static_cast(fb.x_), + static_cast(fb.y_), toString(color).c_str()); } @@ -327,8 +327,8 @@ void SVG::writeText(const Point& p, const std::string& txt, const ColorObject co fprintf( out_, "%s\n", - static_cast(pf.x), - static_cast(pf.y), + static_cast(pf.x_), + static_cast(pf.y_), static_cast(font_size), toString(color).c_str(), txt.c_str()); @@ -459,14 +459,14 @@ void SVG::writeLine(const ExtrusionLine& line, const ColorObject color, const do out_, "\n", toString(color).c_str(), - static_cast(start_left.x), - static_cast(start_left.y), - static_cast(start_right.x), - static_cast(start_right.y), - static_cast(end_right.x), - static_cast(end_right.y), - static_cast(end_left.x), - static_cast(end_left.y)); + static_cast(start_left.x_), + static_cast(start_left.y_), + static_cast(start_right.x_), + static_cast(start_right.y_), + static_cast(end_right.x_), + static_cast(end_right.y_), + static_cast(end_left.x_), + static_cast(end_left.y_)); start_vertex = end_vertex; // For the next line segment. } From 4763b3b13b0d566ca0643b71a837a2753ebbdf36 Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Tue, 21 Nov 2023 14:52:15 +0100 Subject: [PATCH 23/48] Fixed variable shadowing warnings --- include/SkeletalTrapezoidation.h | 182 ++++++++++++++++----------- src/SkeletalTrapezoidation.cpp | 204 +++++++++++++++---------------- 2 files changed, 210 insertions(+), 176 deletions(-) diff --git a/include/SkeletalTrapezoidation.h b/include/SkeletalTrapezoidation.h index 87b5155099..b277ffd0ce 100644 --- a/include/SkeletalTrapezoidation.h +++ b/include/SkeletalTrapezoidation.h @@ -4,39 +4,39 @@ #ifndef SKELETAL_TRAPEZOIDATION_H #define SKELETAL_TRAPEZOIDATION_H -#include - #include // smart pointers #include #include // pair -#include "utils/HalfEdgeGraph.h" -#include "utils/polygon.h" -#include "utils/PolygonsSegmentIndex.h" +#include + +#include "BeadingStrategy/BeadingStrategy.h" +#include "SkeletalTrapezoidationEdge.h" +#include "SkeletalTrapezoidationGraph.h" +#include "SkeletalTrapezoidationJoint.h" +#include "settings/types/Ratio.h" #include "utils/ExtrusionJunction.h" #include "utils/ExtrusionLine.h" +#include "utils/HalfEdgeGraph.h" +#include "utils/PolygonsSegmentIndex.h" +#include "utils/polygon.h" #include "utils/section_type.h" -#include "settings/types/Ratio.h" -#include "SkeletalTrapezoidationEdge.h" -#include "SkeletalTrapezoidationJoint.h" -#include "BeadingStrategy/BeadingStrategy.h" -#include "SkeletalTrapezoidationGraph.h" namespace cura { /*! * Main class of the dynamic beading strategies. - * + * * The input polygon region is decomposed into trapezoids and represented as a half-edge data-structure. - * + * * We determine which edges are 'central' accordinding to the transitioning_angle of the beading strategy, * and determine the bead count for these central regions and apply them outward when generating toolpaths. [oversimplified] - * + * * The method can be visually explained as generating the 3D union of cones surface on the outline polygons, - * and changing the heights along central regions of that surface so that they are flat. + * and changing the heights along central regions of that surface so that they are flat. * For more info, please consult the paper "A framework for adaptive width control of dense contour-parallel toolpaths in fused -deposition modeling" by Kuipers et al. +deposition modeling" by Kuipers et al. * This visual explanation aid explains the use of "upward", "lower" etc, * i.e. the radial distance and/or the bead count are used as heights of this visualization, there is no coordinate called 'Z'. * @@ -59,15 +59,15 @@ class SkeletalTrapezoidation template using ptr_vector_t = std::vector>; - AngleRadians transitioning_angle; //!< How pointy a region should be before we apply the method. Equals 180* - limit_bisector_angle - coord_t discretization_step_size; //!< approximate size of segments when parabolic VD edges get discretized (and vertex-vertex edges) - coord_t transition_filter_dist; //!< Filter transition mids (i.e. anchors) closer together than this - coord_t allowed_filter_deviation; //!< The allowed line width deviation induced by filtering - coord_t beading_propagation_transition_dist; //!< When there are different beadings propagated from below and from above, use this transitioning distance - static constexpr coord_t central_filter_dist = 20; //!< Filter areas marked as 'central' smaller than this - static constexpr coord_t snap_dist = 20; //!< Generic arithmatic inaccuracy. Only used to determine whether a transition really needs to insert an extra edge. - int layer_idx { }; - SectionType section_type; + AngleRadians transitioning_angle_; //!< How pointy a region should be before we apply the method. Equals 180* - limit_bisector_angle + coord_t discretization_step_size_; //!< approximate size of segments when parabolic VD edges get discretized (and vertex-vertex edges) + coord_t transition_filter_dist_; //!< Filter transition mids (i.e. anchors) closer together than this + coord_t allowed_filter_deviation_; //!< The allowed line width deviation induced by filtering + coord_t beading_propagation_transition_dist_; //!< When there are different beadings propagated from below and from above, use this transitioning distance + static constexpr coord_t central_filter_dist_ = 20; //!< Filter areas marked as 'central' smaller than this + static constexpr coord_t snap_dist_ = 20; //!< Generic arithmatic inaccuracy. Only used to determine whether a transition really needs to insert an extra edge. + int layer_idx_{}; + SectionType section_type_; /*! * The strategy to use to fill a certain shape with lines. @@ -77,11 +77,21 @@ class SkeletalTrapezoidation * how the joints are handled where we transition to different numbers of * lines. */ - const BeadingStrategy& beading_strategy; + const BeadingStrategy& beading_strategy_; public: using Segment = PolygonsSegmentIndex; + /*! + * A skeletal graph through the polygons that we need to fill with beads. + * + * The skeletal graph represents the medial axes through each part of the + * polygons, and the lines from these medial axes towards each vertex of the + * polygons. The graph can be used to see what the width is of a polygon in + * each place and where the width transitions. + */ + graph_t graph_; + /*! * Construct a new trapezoidation problem to solve. * \param polys The shapes to fill with walls. @@ -99,26 +109,16 @@ class SkeletalTrapezoidation * beadings propagated from below and from above, use this transitioning * distance. */ - SkeletalTrapezoidation(const Polygons& polys, - const BeadingStrategy& beading_strategy, - AngleRadians transitioning_angle, - coord_t discretization_step_size, - coord_t transition_filter_dist, - coord_t allowed_filter_deviation, - coord_t beading_propagation_transition_dist, - int layer_idx, - SectionType section_type - ); - - /*! - * A skeletal graph through the polygons that we need to fill with beads. - * - * The skeletal graph represents the medial axes through each part of the - * polygons, and the lines from these medial axes towards each vertex of the - * polygons. The graph can be used to see what the width is of a polygon in - * each place and where the width transitions. - */ - graph_t graph; + SkeletalTrapezoidation( + const Polygons& polys, + const BeadingStrategy& beading_strategy, + AngleRadians transitioning_angle, + coord_t discretization_step_size, + coord_t transition_filter_dist, + coord_t allowed_filter_deviation, + coord_t beading_propagation_transition_dist, + int layer_idx, + SectionType section_type); /*! * Generate the paths that the printer must extrude, to print the outlines @@ -141,35 +141,37 @@ class SkeletalTrapezoidation TransitionMidRef(edge_t* edge, std::list::iterator transition_it) : edge_(edge) , transition_it_(transition_it) - {} + { + } }; + /*! + * mapping each voronoi VD edge to the corresponding halfedge HE edge + * In case the result segment is discretized, we map the VD edge to the *last* HE edge + */ + std::unordered_map vd_edge_to_he_edge_; + std::unordered_map vd_node_to_he_node_; + /*! * Compute the skeletal trapezoidation decomposition of the input shape. - * + * * Compute the Voronoi Diagram (VD) and transfer all inside edges into our half-edge (HE) datastructure. - * + * * The algorithm is currently a bit overcomplicated, because the discretization of parabolic edges is performed at the same time as all edges are being transfered, * which means that there is no one-to-one mapping from VD edges to HE edges. * Instead we map from a VD edge to the last HE edge. * This could be cimplified by recording the edges which should be discretized and discretizing the mafterwards. - * + * * Another complication arises because the VD uses floating logic, which can result in zero-length segments after rounding to integers. * We therefore collapse edges and their whole cells afterwards. */ void constructFromPolygons(const Polygons& polys); - /*! - * mapping each voronoi VD edge to the corresponding halfedge HE edge - * In case the result segment is discretized, we map the VD edge to the *last* HE edge - */ - std::unordered_map vd_edge_to_he_edge; - std::unordered_map vd_node_to_he_node; node_t& makeNode(vd_t::vertex_type& vd_node, Point p); //!< Get the node which the VD node maps to, or create a new mapping if there wasn't any yet. /*! * (Eventual) returned 'polylines per index' result (from generateToolpaths): - * + * * Binned by inset_idx. */ std::vector* p_generated_toolpaths; @@ -178,7 +180,15 @@ class SkeletalTrapezoidation * Transfer an edge from the VD to the HE and perform discretization of parabolic edges (and vertex-vertex edges) * \p prev_edge serves as input and output. May be null as input. */ - void transferEdge(Point from, Point to, vd_t::edge_type& vd_edge, edge_t*& prev_edge, Point& start_source_point, Point& end_source_point, const std::vector& points, const std::vector& segments); + void transferEdge( + Point from, + Point to, + vd_t::edge_type& vd_edge, + edge_t*& prev_edge, + Point& start_source_point, + Point& end_source_point, + const std::vector& points, + const std::vector& segments); /*! * Discretize a Voronoi edge that represents the medial axis of a vertex- @@ -231,7 +241,14 @@ class SkeletalTrapezoidation * /return Whether the cell is inside of the polygon. If it's outside of the * polygon we should skip processing it altogether. */ - bool computePointCellRange(vd_t::cell_type& cell, Point& start_source_point, Point& end_source_point, vd_t::edge_type*& starting_vd_edge, vd_t::edge_type*& ending_vd_edge, const std::vector& points, const std::vector& segments); + bool computePointCellRange( + vd_t::cell_type& cell, + Point& start_source_point, + Point& end_source_point, + vd_t::edge_type*& starting_vd_edge, + vd_t::edge_type*& ending_vd_edge, + const std::vector& points, + const std::vector& segments); /*! * Compute the range of line segments that surround a cell of the skeletal @@ -257,7 +274,14 @@ class SkeletalTrapezoidation * /return Whether the cell is inside of the polygon. If it's outside of the * polygon we should skip processing it altogether. */ - void computeSegmentCellRange(vd_t::cell_type& cell, Point& start_source_point, Point& end_source_point, vd_t::edge_type*& starting_vd_edge, vd_t::edge_type*& ending_vd_edge, const std::vector& points, const std::vector& segments); + void computeSegmentCellRange( + vd_t::cell_type& cell, + Point& start_source_point, + Point& end_source_point, + vd_t::edge_type*& starting_vd_edge, + vd_t::edge_type*& ending_vd_edge, + const std::vector& points, + const std::vector& segments); /*! * For VD cells associated with an input polygon vertex, we need to separate the node at the end and start of the cell into two @@ -273,7 +297,7 @@ class SkeletalTrapezoidation /*! * Filter out small central areas. - * + * * Only used to get rid of small edges which get marked as central because * of rounding errors because the region is so small. */ @@ -289,9 +313,9 @@ class SkeletalTrapezoidation /*! * Unmark the outermost edges directly connected to the outline, as not * being central. - * + * * Only used to emulate some related literature. - * + * * The paper shows that this function is bad for the stability of the framework. */ void filterOuterCentral(); @@ -429,7 +453,15 @@ class SkeletalTrapezoidation * \return Whether the given edge is going downward (i.e. towards a thinner * region of the polygon). */ - bool generateTransitionEnd(edge_t& edge, coord_t start_pos, coord_t end_pos, coord_t transition_half_length, Ratio start_rest, Ratio end_rest, coord_t transition_lower_bead_count, ptr_vector_t>& edge_transition_ends); + bool generateTransitionEnd( + edge_t& edge, + coord_t start_pos, + coord_t end_pos, + coord_t transition_half_length, + Ratio start_rest, + Ratio end_rest, + coord_t transition_lower_bead_count, + ptr_vector_t>& edge_transition_ends); /*! * Determines whether an edge is going downwards or upwards in the graph. @@ -488,28 +520,30 @@ class SkeletalTrapezoidation /*! * Propagate beading information from nodes that are closer to the edge * (low radius R) to nodes that are farther from the edge (high R). - * + * * only propagate from nodes with beading info upward to nodes without beading info - * + * * Edges are sorted by their radius, so that we can do a depth-first walk * without employing a recursive algorithm. - * + * * In upward propagated beadings we store the distance traveled, so that we can merge these beadings with the downward propagated beadings in \ref propagateBeadingsDownward(.) - * - * \param upward_quad_mids all upward halfedges of the inner skeletal edges (not directly connected to the outline) sorted on their highest [distance_to_boundary]. Higher dist first. + * + * \param upward_quad_mids all upward halfedges of the inner skeletal edges (not directly connected to the outline) sorted on their highest [distance_to_boundary]. Higher dist + * first. */ void propagateBeadingsUpward(std::vector& upward_quad_mids, ptr_vector_t& node_beadings); /*! * propagate beading info from higher R nodes to lower R nodes - * + * * merge with upward propagated beadings if they are encountered - * + * * don't transfer to nodes which lie on the outline polygon - * + * * edges are sorted so that we can do a depth-first walk without employing a recursive algorithm - * - * \param upward_quad_mids all upward halfedges of the inner skeletal edges (not directly connected to the outline) sorted on their highest [distance_to_boundary]. Higher dist first. + * + * \param upward_quad_mids all upward halfedges of the inner skeletal edges (not directly connected to the outline) sorted on their highest [distance_to_boundary]. Higher dist + * first. */ void propagateBeadingsDownward(std::vector& upward_quad_mids, ptr_vector_t& node_beadings); @@ -580,7 +614,7 @@ class SkeletalTrapezoidation /*! * Add a new toolpath segment, defined between two extrusion-juntions. - * + * * \param from The junction from which to add a segment. * \param to The junction to which to add a segment. * \param is_odd Whether this segment is an odd gap filler along the middle of the skeleton. diff --git a/src/SkeletalTrapezoidation.cpp b/src/SkeletalTrapezoidation.cpp index 346e1eb46f..e56844549a 100644 --- a/src/SkeletalTrapezoidation.cpp +++ b/src/SkeletalTrapezoidation.cpp @@ -27,12 +27,12 @@ namespace cura SkeletalTrapezoidation::node_t& SkeletalTrapezoidation::makeNode(vd_t::vertex_type& vd_node, Point p) { - auto he_node_it = vd_node_to_he_node.find(&vd_node); - if (he_node_it == vd_node_to_he_node.end()) + auto he_node_it = vd_node_to_he_node_.find(&vd_node); + if (he_node_it == vd_node_to_he_node_.end()) { - graph.nodes.emplace_front(SkeletalTrapezoidationJoint(), p); - node_t& node = graph.nodes.front(); - vd_node_to_he_node.emplace(&vd_node, &node); + graph_.nodes.emplace_front(SkeletalTrapezoidationJoint(), p); + node_t& node = graph_.nodes.front(); + vd_node_to_he_node_.emplace(&vd_node, &node); return node; } else @@ -51,13 +51,13 @@ void SkeletalTrapezoidation::transferEdge( const std::vector& points, const std::vector& segments) { - auto he_edge_it = vd_edge_to_he_edge.find(vd_edge.twin()); - if (he_edge_it != vd_edge_to_he_edge.end()) + auto he_edge_it = vd_edge_to_he_edge_.find(vd_edge.twin()); + if (he_edge_it != vd_edge_to_he_edge_.end()) { // Twin segment(s) have already been made edge_t* source_twin = he_edge_it->second; assert(source_twin); - auto end_node_it = vd_node_to_he_node.find(vd_edge.vertex1()); - assert(end_node_it != vd_node_to_he_node.end()); + auto end_node_it = vd_node_to_he_node_.find(vd_edge.vertex1()); + assert(end_node_it != vd_node_to_he_node_.end()); node_t* end_node = end_node_it->second; for (edge_t* twin = source_twin;; twin = twin->prev->twin->prev) { @@ -67,8 +67,8 @@ void SkeletalTrapezoidation::transferEdge( continue; // Prevent reading unallocated memory. } assert(twin); - graph.edges.emplace_front(SkeletalTrapezoidationEdge()); - edge_t* edge = &graph.edges.front(); + graph_.edges.emplace_front(SkeletalTrapezoidationEdge()); + edge_t* edge = &graph_.edges.front(); edge->from = twin->to; edge->to = twin->from; edge->twin = twin; @@ -99,7 +99,7 @@ void SkeletalTrapezoidation::transferEdge( assert(twin->prev->twin->prev); // Prev segment along parabola constexpr bool is_not_next_to_start_or_end = false; // Only ribs at the end of a cell should be skipped - graph.makeRib(prev_edge, start_source_point, end_source_point, is_not_next_to_start_or_end); + graph_.makeRib(prev_edge, start_source_point, end_source_point, is_not_next_to_start_or_end); } assert(prev_edge); } @@ -126,16 +126,16 @@ void SkeletalTrapezoidation::transferEdge( node_t* v1; if (p1_idx < discretized.size() - 1) { - graph.nodes.emplace_front(SkeletalTrapezoidationJoint(), p1); - v1 = &graph.nodes.front(); + graph_.nodes.emplace_front(SkeletalTrapezoidationJoint(), p1); + v1 = &graph_.nodes.front(); } else { v1 = &makeNode(*vd_edge.vertex1(), to); } - graph.edges.emplace_front(SkeletalTrapezoidationEdge()); - edge_t* edge = &graph.edges.front(); + graph_.edges.emplace_front(SkeletalTrapezoidationEdge()); + edge_t* edge = &graph_.edges.front(); edge->from = v0; edge->to = v1; edge->from->incident_edge = edge; @@ -153,11 +153,11 @@ void SkeletalTrapezoidation::transferEdge( if (p1_idx < discretized.size() - 1) { // Rib for last segment gets introduced outside this function! constexpr bool is_not_next_to_start_or_end = false; // Only ribs at the end of a cell should be skipped - graph.makeRib(prev_edge, start_source_point, end_source_point, is_not_next_to_start_or_end); + graph_.makeRib(prev_edge, start_source_point, end_source_point, is_not_next_to_start_or_end); } } assert(prev_edge); - vd_edge_to_he_edge.emplace(&vd_edge, prev_edge); + vd_edge_to_he_edge_.emplace(&vd_edge, prev_edge); } } @@ -182,7 +182,7 @@ std::vector SkeletalTrapezoidation::discretize(const vd_t::edge_type& vd_ { Point p = VoronoiUtils::getSourcePoint(*(point_left ? left_cell : right_cell), points, segments); const Segment& s = VoronoiUtils::getSourceSegment(*(point_left ? right_cell : left_cell), points, segments); - return VoronoiUtils::discretizeParabola(p, s, start, end, discretization_step_size, transitioning_angle); + return VoronoiUtils::discretizeParabola(p, s, start, end, discretization_step_size_, transitioning_angle_); } else // This is a straight edge between two points. { @@ -207,7 +207,7 @@ std::vector SkeletalTrapezoidation::discretize(const vd_t::edge_type& vd_ coord_t end_x = projected_x(end); // Part of the edge will be bound to the markings on the endpoints of the edge. Calculate how far that is. - double bound = 0.5 / tan((std::numbers::pi - transitioning_angle) * 0.5); + double bound = 0.5 / tan((std::numbers::pi - transitioning_angle_) * 0.5); coord_t marking_start_x = -d * bound; coord_t marking_end_x = d * bound; Point marking_start = middle + x_axis_dir * marking_start_x / x_axis_length; @@ -234,7 +234,7 @@ std::vector SkeletalTrapezoidation::discretize(const vd_t::edge_type& vd_ // The edge's length may not be divisible by the step size, so calculate an integer step count and evenly distribute the vertices among those. Point ab = b - a; coord_t ab_size = vSize(ab); - coord_t step_count = (ab_size + discretization_step_size / 2) / discretization_step_size; + coord_t step_count = (ab_size + discretization_step_size_ / 2) / discretization_step_size_; if (step_count % 2 == 1) { step_count++; // enforce a discretization point being added in the middle @@ -382,14 +382,14 @@ SkeletalTrapezoidation::SkeletalTrapezoidation( coord_t beading_propagation_transition_dist, int layer_idx, SectionType section_type) - : transitioning_angle(transitioning_angle) - , discretization_step_size(discretization_step_size) - , transition_filter_dist(transition_filter_dist) - , allowed_filter_deviation(allowed_filter_deviation) - , beading_propagation_transition_dist(beading_propagation_transition_dist) - , beading_strategy(beading_strategy) - , layer_idx(layer_idx) - , section_type(section_type) + : transitioning_angle_(transitioning_angle) + , discretization_step_size_(discretization_step_size) + , transition_filter_dist_(transition_filter_dist) + , allowed_filter_deviation_(allowed_filter_deviation) + , beading_propagation_transition_dist_(beading_propagation_transition_dist) + , beading_strategy_(beading_strategy) + , layer_idx_(layer_idx) + , section_type_(section_type) { scripta::log("skeletal_trapezoidation_0", polys, section_type, layer_idx); constructFromPolygons(polys); @@ -397,8 +397,8 @@ SkeletalTrapezoidation::SkeletalTrapezoidation( void SkeletalTrapezoidation::constructFromPolygons(const Polygons& polys) { - vd_edge_to_he_edge.clear(); - vd_node_to_he_node.clear(); + vd_edge_to_he_edge_.clear(); + vd_node_to_he_node_.clear(); std::vector points; // Remains empty @@ -457,11 +457,11 @@ void SkeletalTrapezoidation::constructFromPolygons(const Polygons& polys) end_source_point, points, segments); - node_t* starting_node = vd_node_to_he_node[starting_vonoroi_edge->vertex0()]; + node_t* starting_node = vd_node_to_he_node_[starting_vonoroi_edge->vertex0()]; starting_node->data.distance_to_boundary_ = 0; constexpr bool is_next_to_start_or_end = true; - graph.makeRib(prev_edge, start_source_point, end_source_point, is_next_to_start_or_end); + graph_.makeRib(prev_edge, start_source_point, end_source_point, is_next_to_start_or_end); for (vd_t::edge_type* vd_edge = starting_vonoroi_edge->next(); vd_edge != ending_vonoroi_edge; vd_edge = vd_edge->next()) { assert(vd_edge->is_finite()); @@ -469,7 +469,7 @@ void SkeletalTrapezoidation::constructFromPolygons(const Polygons& polys) Point v2 = VoronoiUtils::p(vd_edge->vertex1()); transferEdge(v1, v2, *vd_edge, prev_edge, start_source_point, end_source_point, points, segments); - graph.makeRib(prev_edge, start_source_point, end_source_point, vd_edge->next() == ending_vonoroi_edge); + graph_.makeRib(prev_edge, start_source_point, end_source_point, vd_edge->next() == ending_vonoroi_edge); } transferEdge(VoronoiUtils::p(ending_vonoroi_edge->vertex0()), end_source_point, *ending_vonoroi_edge, prev_edge, start_source_point, end_source_point, points, segments); @@ -478,11 +478,11 @@ void SkeletalTrapezoidation::constructFromPolygons(const Polygons& polys) separatePointyQuadEndNodes(); - graph.collapseSmallEdges(); + graph_.collapseSmallEdges(); // Set [incident_edge] the the first possible edge that way we can iterate over all reachable edges from node.incident_edge, // without needing to iterate backward - for (edge_t& edge : graph.edges) + for (edge_t& edge : graph_.edges) { if (! edge.prev) { @@ -494,7 +494,7 @@ void SkeletalTrapezoidation::constructFromPolygons(const Polygons& polys) void SkeletalTrapezoidation::separatePointyQuadEndNodes() { std::unordered_set visited_nodes; - for (edge_t& edge : graph.edges) + for (edge_t& edge : graph_.edges) { if (edge.prev) { @@ -507,8 +507,8 @@ void SkeletalTrapezoidation::separatePointyQuadEndNodes() } else { // Needs to be duplicated - graph.nodes.emplace_back(*quad_start->from); - node_t* new_node = &graph.nodes.back(); + graph_.nodes.emplace_back(*quad_start->from); + node_t* new_node = &graph_.nodes.back(); new_node->incident_edge = quad_start; quad_start->from = new_node; quad_start->twin->to = new_node; @@ -532,7 +532,7 @@ void SkeletalTrapezoidation::generateToolpaths(std::vector& updateIsCentral(); - filterCentral(central_filter_dist); + filterCentral(central_filter_dist_); if (filter_outermost_central_edges) { @@ -542,9 +542,9 @@ void SkeletalTrapezoidation::generateToolpaths(std::vector& updateBeadCount(); scripta::log( "st_graph_0", - graph, - section_type, - layer_idx, + graph_, + section_type_, + layer_idx_, scripta::CellVDI{ "is_central", [](const auto& edge) { @@ -574,9 +574,9 @@ void SkeletalTrapezoidation::generateToolpaths(std::vector& filterNoncentralRegions(); scripta::log( "st_graph_1", - graph, - section_type, - layer_idx, + graph_, + section_type_, + layer_idx_, scripta::CellVDI{ "is_central", [](const auto& edge) { @@ -606,9 +606,9 @@ void SkeletalTrapezoidation::generateToolpaths(std::vector& generateTransitioningRibs(); scripta::log( "st_graph_2", - graph, - section_type, - layer_idx, + graph_, + section_type_, + layer_idx_, scripta::CellVDI{ "is_central", [](const auto& edge) { @@ -638,9 +638,9 @@ void SkeletalTrapezoidation::generateToolpaths(std::vector& generateExtraRibs(); scripta::log( "st_graph_3", - graph, - section_type, - layer_idx, + graph_, + section_type_, + layer_idx_, scripta::CellVDI{ "is_central", [](const auto& edge) { @@ -670,9 +670,9 @@ void SkeletalTrapezoidation::generateToolpaths(std::vector& generateSegments(); scripta::log( "st_graph_4", - graph, - section_type, - layer_idx, + graph_, + section_type_, + layer_idx_, scripta::CellVDI{ "is_central", [](const auto& edge) { @@ -715,10 +715,10 @@ void SkeletalTrapezoidation::updateIsCentral() // `^'-._ corner is obtuse. // sin a = dR / dD - coord_t outer_edge_filter_length = beading_strategy.getTransitionThickness(0) / 2; + coord_t outer_edge_filter_length = beading_strategy_.getTransitionThickness(0) / 2; - double cap = sin(beading_strategy.getTransitioningAngle() * 0.5); // = cos(bisector_angle / 2) - for (edge_t& edge : graph.edges) + double cap = sin(beading_strategy_.getTransitioningAngle() * 0.5); // = cos(bisector_angle / 2) + for (edge_t& edge : graph_.edges) { assert(edge.twin); if (! edge.twin) @@ -752,7 +752,7 @@ void SkeletalTrapezoidation::updateIsCentral() void SkeletalTrapezoidation::filterCentral(coord_t max_length) { - for (edge_t& edge : graph.edges) + for (edge_t& edge : graph_.edges) { if (isEndOfCentral(edge) && edge.to->isLocalMaximum() && ! edge.to->isLocalMaximum()) { @@ -789,7 +789,7 @@ bool SkeletalTrapezoidation::filterCentral(edge_t* starting_edge, coord_t travel void SkeletalTrapezoidation::filterOuterCentral() { - for (edge_t& edge : graph.edges) + for (edge_t& edge : graph_.edges) { if (! edge.prev) { @@ -801,16 +801,16 @@ void SkeletalTrapezoidation::filterOuterCentral() void SkeletalTrapezoidation::updateBeadCount() { - for (edge_t& edge : graph.edges) + for (edge_t& edge : graph_.edges) { if (edge.data.isCentral()) { - edge.to->data.bead_count_ = beading_strategy.getOptimalBeadCount(edge.to->data.distance_to_boundary_ * 2); + edge.to->data.bead_count_ = beading_strategy_.getOptimalBeadCount(edge.to->data.distance_to_boundary_ * 2); } } // Fix bead count at locally maximal R, also for central regions!! See TODO s in generateTransitionEnd(.) - for (node_t& node : graph.nodes) + for (node_t& node : graph_.nodes) { if (node.isLocalMaximum()) { @@ -824,7 +824,7 @@ void SkeletalTrapezoidation::updateBeadCount() node.data.distance_to_boundary_ = std::min(node.data.distance_to_boundary_, edge->to->data.distance_to_boundary_ + vSize(edge->from->p - edge->to->p)); } while (edge = edge->twin->next, edge != node.incident_edge); } - coord_t bead_count = beading_strategy.getOptimalBeadCount(node.data.distance_to_boundary_ * 2); + coord_t bead_count = beading_strategy_.getOptimalBeadCount(node.data.distance_to_boundary_ * 2); node.data.bead_count_ = bead_count; } } @@ -832,7 +832,7 @@ void SkeletalTrapezoidation::updateBeadCount() void SkeletalTrapezoidation::filterNoncentralRegions() { - for (edge_t& edge : graph.edges) + for (edge_t& edge : graph_.edges) { if (! isEndOfCentral(edge)) { @@ -886,7 +886,7 @@ bool SkeletalTrapezoidation::filterNoncentralRegions(edge_t* to_edge, coord_t be { next_edge->data.setIsCentral(true); next_edge->twin->data.setIsCentral(true); - next_edge->to->data.bead_count_ = beading_strategy.getOptimalBeadCount(next_edge->to->data.distance_to_boundary_ * 2); + next_edge->to->data.bead_count_ = beading_strategy_.getOptimalBeadCount(next_edge->to->data.distance_to_boundary_ * 2); next_edge->to->data.transition_ratio_ = 0; } return dissolve; // Dissolving only depend on the one edge going upward. There cannot be multiple edges going upward. @@ -899,7 +899,7 @@ void SkeletalTrapezoidation::generateTransitioningRibs() ptr_vector_t> edge_transitions; generateTransitionMids(edge_transitions); - for (edge_t& edge : graph.edges) + for (edge_t& edge : graph_.edges) { // Check if there is a transition in between nodes with different bead counts if (edge.data.isCentral() && edge.from->data.bead_count_ != edge.to->data.bead_count_) { @@ -919,7 +919,7 @@ void SkeletalTrapezoidation::generateTransitioningRibs() void SkeletalTrapezoidation::generateTransitionMids(ptr_vector_t>& edge_transitions) { - for (edge_t& edge : graph.edges) + for (edge_t& edge : graph_.edges) { assert(edge.data.centralIsSet()); if (! edge.data.isCentral()) @@ -950,7 +950,7 @@ void SkeletalTrapezoidation::generateTransitionMids(ptr_vector_t beading_strategy.getOptimalBeadCount(start_R * 2) || end_bead_count > beading_strategy.getOptimalBeadCount(end_R * 2)) + if (start_bead_count > beading_strategy_.getOptimalBeadCount(start_R * 2) || end_bead_count > beading_strategy_.getOptimalBeadCount(end_R * 2)) { // Wasn't the case earlier in this function because of already introduced transitions spdlog::error("transitioning segment overlap!"); } @@ -962,7 +962,7 @@ void SkeletalTrapezoidation::generateTransitionMids(ptr_vector_tp - edge.to->p); for (int transition_lower_bead_count = start_bead_count; transition_lower_bead_count < end_bead_count; transition_lower_bead_count++) { - coord_t mid_R = beading_strategy.getTransitionThickness(transition_lower_bead_count) / 2; + coord_t mid_R = beading_strategy_.getTransitionThickness(transition_lower_bead_count) / 2; if (mid_R > end_R) { spdlog::error("transition on segment lies outside of segment!"); @@ -997,7 +997,7 @@ void SkeletalTrapezoidation::generateTransitionMids(ptr_vector_t to_be_dissolved_back - = dissolveNearbyTransitions(&edge, transitions.back(), ab_size - transitions.back().pos_, transition_filter_dist, going_up); + = dissolveNearbyTransitions(&edge, transitions.back(), ab_size - transitions.back().pos_, transition_filter_dist_, going_up); bool should_dissolve_back = ! to_be_dissolved_back.empty(); for (TransitionMidRef& ref : to_be_dissolved_back) { @@ -1026,7 +1026,7 @@ void SkeletalTrapezoidation::filterTransitionMids() { coord_t trans_bead_count = transitions.back().lower_bead_count_; - coord_t upper_transition_half_length = (1.0 - beading_strategy.getTransitionAnchorPos(trans_bead_count)) * beading_strategy.getTransitioningLength(trans_bead_count); + coord_t upper_transition_half_length = (1.0 - beading_strategy_.getTransitionAnchorPos(trans_bead_count)) * beading_strategy_.getTransitioningLength(trans_bead_count); should_dissolve_back |= filterEndOfCentralTransition(&edge, ab_size - transitions.back().pos_, upper_transition_half_length, trans_bead_count); } @@ -1040,7 +1040,7 @@ void SkeletalTrapezoidation::filterTransitionMids() } going_up = false; - std::list to_be_dissolved_front = dissolveNearbyTransitions(edge.twin, transitions.front(), transitions.front().pos_, transition_filter_dist, going_up); + std::list to_be_dissolved_front = dissolveNearbyTransitions(edge.twin, transitions.front(), transitions.front().pos_, transition_filter_dist_, going_up); bool should_dissolve_front = ! to_be_dissolved_front.empty(); for (TransitionMidRef& ref : to_be_dissolved_front) { @@ -1050,7 +1050,7 @@ void SkeletalTrapezoidation::filterTransitionMids() { coord_t trans_bead_count = transitions.front().lower_bead_count_; - coord_t lower_transition_half_length = beading_strategy.getTransitionAnchorPos(trans_bead_count) * beading_strategy.getTransitioningLength(trans_bead_count); + coord_t lower_transition_half_length = beading_strategy_.getTransitionAnchorPos(trans_bead_count) * beading_strategy_.getTransitioningLength(trans_bead_count); should_dissolve_front |= filterEndOfCentralTransition(edge.twin, transitions.front().pos_, lower_transition_half_length, trans_bead_count + 1); } @@ -1096,7 +1096,7 @@ std::list const coord_t line_width_deviation = dissolve_result_is_odd ? width_deviation : width_deviation / 2; // assume the deviation will be split over either 1 or 2 lines, i.e. assume wall_distribution_count = 1 - if (line_width_deviation > allowed_filter_deviation) + if (line_width_deviation > allowed_filter_deviation_) { should_dissolve = false; } @@ -1110,7 +1110,7 @@ std::list coord_t pos = is_aligned ? transition_it->pos_ : ab_size - transition_it->pos_; if (traveled_dist + pos < max_dist && transition_it->lower_bead_count_ == origin_transition.lower_bead_count_) // Only dissolve local optima { - if (traveled_dist + pos < beading_strategy.getTransitioningLength(transition_it->lower_bead_count_)) + if (traveled_dist + pos < beading_strategy_.getTransitioningLength(transition_it->lower_bead_count_)) { // Consecutive transitions both in/decreasing in bead count should never be closer together than the transition distance assert(going_up != is_aligned || transition_it->lower_bead_count_ == 0); @@ -1194,7 +1194,7 @@ bool SkeletalTrapezoidation::filterEndOfCentralTransition(edge_t* edge_to_start, void SkeletalTrapezoidation::generateAllTransitionEnds(ptr_vector_t>& edge_transition_ends) { - for (edge_t& edge : graph.edges) + for (edge_t& edge : graph_.edges) { if (! edge.data.hasTransitions()) { @@ -1219,8 +1219,8 @@ void SkeletalTrapezoidation::generateTransitionEnds(edge_t& edge, coord_t mid_po const Point ab = b - a; const coord_t ab_size = vSize(ab); - const coord_t transition_length = beading_strategy.getTransitioningLength(lower_bead_count); - const double transition_mid_position = beading_strategy.getTransitionAnchorPos(lower_bead_count); + const coord_t transition_length = beading_strategy_.getTransitioningLength(lower_bead_count); + const double transition_mid_position = beading_strategy_.getTransitionAnchorPos(lower_bead_count); constexpr double inner_bead_width_ratio_after_transition = 1.0; constexpr Ratio start_rest{ 0.0 }; @@ -1419,7 +1419,7 @@ bool SkeletalTrapezoidation::isGoingDown(edge_t* outgoing, coord_t traveled_dist void SkeletalTrapezoidation::applyTransitions(ptr_vector_t>& edge_transition_ends) { - for (edge_t& edge : graph.edges) + for (edge_t& edge : graph_.edges) { if (edge.twin->data.hasTransitionEnds()) { @@ -1439,7 +1439,7 @@ void SkeletalTrapezoidation::applyTransitions(ptr_vector_t ab_size - snap_dist) && close_node->data.bead_count_ == new_node_bead_count) + if ((end_pos < snap_dist_ || end_pos > ab_size - snap_dist_) && close_node->data.bead_count_ == new_node_bead_count) { assert(end_pos <= ab_size); close_node->data.transition_ratio_ = 0; @@ -1478,7 +1478,7 @@ void SkeletalTrapezoidation::applyTransitions(ptr_vector_tdata.isCentral()); assert(last_edge_replacing_input->data.type_ != SkeletalTrapezoidationEdge::EdgeType::EXTRA_VD); - last_edge_replacing_input = graph.insertNode(last_edge_replacing_input, mid, new_node_bead_count); + last_edge_replacing_input = graph_.insertNode(last_edge_replacing_input, mid, new_node_bead_count); assert(last_edge_replacing_input->data.type_ != SkeletalTrapezoidationEdge::EdgeType::EXTRA_VD); assert(last_edge_replacing_input->data.isCentral()); } @@ -1510,15 +1510,15 @@ void SkeletalTrapezoidation::generateExtraRibs() { // NOTE: At one point there was a comment here and some odd code that seemed to suggest some edge(s?) at the end should perhaps not be looped over. // The code was equivalent to a full loop over all the edges though, unless there was one edge or less, in which case it would produce undefined behaviour. - for (auto& edge : graph.edges) + for (auto& edge : graph_.edges) { - if (! edge.data.isCentral() || shorterThen(edge.to->p - edge.from->p, discretization_step_size) + if (! edge.data.isCentral() || shorterThen(edge.to->p - edge.from->p, discretization_step_size_) || edge.from->data.distance_to_boundary_ >= edge.to->data.distance_to_boundary_) { continue; } - std::vector rib_thicknesses = beading_strategy.getNonlinearThicknesses(edge.from->data.bead_count_); + std::vector rib_thicknesses = beading_strategy_.getNonlinearThicknesses(edge.from->data.bead_count_); if (rib_thicknesses.empty()) { @@ -1552,7 +1552,7 @@ void SkeletalTrapezoidation::generateExtraRibs() assert(end_pos > 0); assert(end_pos < ab_size); node_t* close_node = (end_pos < ab_size / 2) ? from : to; - if ((end_pos < snap_dist || end_pos > ab_size - snap_dist) && close_node->data.bead_count_ == new_node_bead_count) + if ((end_pos < snap_dist_ || end_pos > ab_size - snap_dist_) && close_node->data.bead_count_ == new_node_bead_count) { assert(end_pos <= ab_size); close_node->data.transition_ratio_ = 0; @@ -1562,7 +1562,7 @@ void SkeletalTrapezoidation::generateExtraRibs() assert(last_edge_replacing_input->data.isCentral()); assert(last_edge_replacing_input->data.type_ != SkeletalTrapezoidationEdge::EdgeType::EXTRA_VD); - last_edge_replacing_input = graph.insertNode(last_edge_replacing_input, mid, new_node_bead_count); + last_edge_replacing_input = graph_.insertNode(last_edge_replacing_input, mid, new_node_bead_count); assert(last_edge_replacing_input->data.type_ != SkeletalTrapezoidationEdge::EdgeType::EXTRA_VD); assert(last_edge_replacing_input->data.isCentral()); } @@ -1580,7 +1580,7 @@ void SkeletalTrapezoidation::generateExtraRibs() void SkeletalTrapezoidation::generateSegments() { std::vector upward_quad_mids; - for (edge_t& edge : graph.edges) + for (edge_t& edge : graph_.edges) { if (edge.prev && edge.next && edge.isUpward()) { @@ -1620,7 +1620,7 @@ void SkeletalTrapezoidation::generateSegments() ptr_vector_t node_beadings; { // Store beading - for (node_t& node : graph.nodes) + for (node_t& node : graph_.nodes) { if (node.data.bead_count_ <= 0) { @@ -1628,7 +1628,7 @@ void SkeletalTrapezoidation::generateSegments() } if (node.data.transition_ratio_ == 0) { - node_beadings.emplace_back(new BeadingPropagation(beading_strategy.compute(node.data.distance_to_boundary_ * 2, node.data.bead_count_))); + node_beadings.emplace_back(new BeadingPropagation(beading_strategy_.compute(node.data.distance_to_boundary_ * 2, node.data.bead_count_))); node.data.setBeading(node_beadings.back()); assert(node_beadings.back()->beading_.total_thickness == node.data.distance_to_boundary_ * 2); if (node_beadings.back()->beading_.total_thickness != node.data.distance_to_boundary_ * 2) @@ -1638,8 +1638,8 @@ void SkeletalTrapezoidation::generateSegments() } else { - Beading low_count_beading = beading_strategy.compute(node.data.distance_to_boundary_ * 2, node.data.bead_count_); - Beading high_count_beading = beading_strategy.compute(node.data.distance_to_boundary_ * 2, node.data.bead_count_ + 1); + Beading low_count_beading = beading_strategy_.compute(node.data.distance_to_boundary_ * 2, node.data.bead_count_); + Beading high_count_beading = beading_strategy_.compute(node.data.distance_to_boundary_ * 2, node.data.bead_count_ + 1); Beading merged = interpolate(low_count_beading, 1.0 - node.data.transition_ratio_, high_count_beading); node_beadings.emplace_back(new BeadingPropagation(merged)); node.data.setBeading(node_beadings.back()); @@ -1708,7 +1708,7 @@ void SkeletalTrapezoidation::propagateBeadingsUpward(std::vector& upwar } assert( (upward_edge->from->data.distance_to_boundary_ != upward_edge->to->data.distance_to_boundary_ - || shorterThen(upward_edge->to->p - upward_edge->from->p, central_filter_dist)) + || shorterThen(upward_edge->to->p - upward_edge->from->p, central_filter_dist_)) && "zero difference R edges should always be central"); coord_t length = vSize(upward_edge->to->p - upward_edge->from->p); BeadingPropagation upper_beading = lower_beading; @@ -1768,7 +1768,7 @@ void SkeletalTrapezoidation::propagateBeadingsDownward(edge_t* edge_to_peak, ptr { BeadingPropagation& bottom_beading = *edge_to_peak->from->data.getBeading(); coord_t total_dist = top_beading.dist_from_top_source_ + length + bottom_beading.dist_to_bottom_source_; - Ratio ratio_of_top = static_cast(bottom_beading.dist_to_bottom_source_) / std::min(total_dist, beading_propagation_transition_dist); + Ratio ratio_of_top = static_cast(bottom_beading.dist_to_bottom_source_) / std::min(total_dist, beading_propagation_transition_dist_); ratio_of_top = std::max(0.0_r, ratio_of_top); if (ratio_of_top >= 1.0) { @@ -1857,7 +1857,7 @@ SkeletalTrapezoidation::Beading SkeletalTrapezoidation::interpolate(const Beadin void SkeletalTrapezoidation::generateJunctions(ptr_vector_t& node_beadings, ptr_vector_t& edge_junctions) { - for (edge_t& edge_ : graph.edges) + for (edge_t& edge_ : graph_.edges) { edge_t* edge = &edge_; if (edge->from->data.distance_to_boundary_ > edge->to->data.distance_to_boundary_) @@ -1958,10 +1958,10 @@ std::shared_ptr SkeletalTrapezo spdlog::error("Unknown beading for non-central node!"); } assert(dist != std::numeric_limits::max()); - node->data.bead_count_ = beading_strategy.getOptimalBeadCount(dist * 2); + node->data.bead_count_ = beading_strategy_.getOptimalBeadCount(dist * 2); } assert(node->data.bead_count_ != -1); - node_beadings.emplace_back(new BeadingPropagation(beading_strategy.compute(node->data.distance_to_boundary_ * 2, node->data.bead_count_))); + node_beadings.emplace_back(new BeadingPropagation(beading_strategy_.compute(node->data.distance_to_boundary_ * 2, node->data.bead_count_))); node->data.setBeading(node_beadings.back()); } assert(node->data.hasBeading()); @@ -2062,8 +2062,8 @@ void SkeletalTrapezoidation::addToolpathSegment(const ExtrusionJunction& from, c void SkeletalTrapezoidation::connectJunctions(ptr_vector_t& edge_junctions) { - std::unordered_set unprocessed_quad_starts(graph.edges.size() * 5 / 2); - for (edge_t& edge : graph.edges) + std::unordered_set unprocessed_quad_starts(graph_.edges.size() * 5 / 2); + for (edge_t& edge : graph_.edges) { if (! edge.prev) { @@ -2187,7 +2187,7 @@ void SkeletalTrapezoidation::generateLocalMaximaSingleBeads() { std::vector& generated_toolpaths = *p_generated_toolpaths; - for (auto& node : graph.nodes) + for (auto& node : graph_.nodes) { if (! node.data.hasBeading()) { From e52f91af42193653a58062bc730b7f8360987065 Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Tue, 21 Nov 2023 15:32:47 +0100 Subject: [PATCH 24/48] Fixed variable shadowing warnings --- include/PrimeTower.h | 28 +- include/gcodeExport.h | 131 ++-- include/progress/ProgressStageEstimator.h | 40 +- include/skin.h | 31 +- include/utils/HalfEdge.h | 22 +- include/utils/HalfEdgeNode.h | 17 +- src/FffGcodeWriter.cpp | 33 +- src/FffPolygonGenerator.cpp | 2 +- src/PrimeTower.cpp | 91 ++- src/SkeletalTrapezoidation.cpp | 633 ++++++++--------- src/SkeletalTrapezoidationGraph.cpp | 270 ++++---- src/SkirtBrim.cpp | 4 +- src/TreeModelVolumes.cpp | 2 +- src/gcodeExport.cpp | 802 +++++++++++----------- src/infill.cpp | 28 +- src/progress/ProgressStageEstimator.cpp | 32 +- src/raft.cpp | 2 +- src/skin.cpp | 122 ++-- src/sliceDataStorage.cpp | 4 +- tests/GCodeExportTest.cpp | 78 +-- 20 files changed, 1193 insertions(+), 1179 deletions(-) diff --git a/include/PrimeTower.h b/include/PrimeTower.h index a493cfb3be..9761c12e0f 100644 --- a/include/PrimeTower.h +++ b/include/PrimeTower.h @@ -29,26 +29,26 @@ class PrimeTower using MovesByExtruder = std::vector; using MovesByLayer = std::vector; - size_t extruder_count; //!< Number of extruders + size_t extruder_count_; //!< Number of extruders - bool wipe_from_middle; //!< Whether to wipe on the inside of the hollow prime tower - Point middle; //!< The middle of the prime tower + bool wipe_from_middle_; //!< Whether to wipe on the inside of the hollow prime tower + Point middle_; //!< The middle of the prime tower - Point post_wipe_point; //!< Location to post-wipe the unused nozzle off on + Point post_wipe_point_; //!< Location to post-wipe the unused nozzle off on - std::vector prime_tower_start_locations; //!< The differernt locations where to pre-wipe the active nozzle - const unsigned int number_of_prime_tower_start_locations = 21; //!< The required size of \ref PrimeTower::wipe_locations + std::vector prime_tower_start_locations_; //!< The differernt locations where to pre-wipe the active nozzle + const unsigned int number_of_prime_tower_start_locations_ = 21; //!< The required size of \ref PrimeTower::wipe_locations - MovesByExtruder prime_moves; //!< For each extruder, the moves to be processed for actual priming. - MovesByLayer base_extra_moves; //!< For each layer and each extruder, the extra moves to be processed for better adhesion/strength + MovesByExtruder prime_moves_; //!< For each extruder, the moves to be processed for actual priming. + MovesByLayer base_extra_moves_; //!< For each layer and each extruder, the extra moves to be processed for better adhesion/strength - Polygons outer_poly; //!< The outline of the outermost prime tower. - std::vector outer_poly_base; //!< The outline of the layers having extra width for the base + Polygons outer_poly_; //!< The outline of the outermost prime tower. + std::vector outer_poly_base_; //!< The outline of the layers having extra width for the base public: - bool enabled; //!< Whether the prime tower is enabled. - bool would_have_actual_tower; //!< Whether there is an actual tower. - bool multiple_extruders_on_first_layer; //!< Whether multiple extruders are allowed on the first layer of the prime tower (e.g. when a raft is there) + bool enabled_; //!< Whether the prime tower is enabled. + bool would_have_actual_tower_; //!< Whether there is an actual tower. + bool multiple_extruders_on_first_layer_; //!< Whether multiple extruders are allowed on the first layer of the prime tower (e.g. when a raft is there) /* * In which order, from outside to inside, will we be printing the prime @@ -57,7 +57,7 @@ class PrimeTower * This is the spatial order from outside to inside. This is NOT the actual * order in time in which they are printed. */ - std::vector extruder_order; + std::vector extruder_order_; /*! * \brief Creates a prime tower instance that will determine where and how diff --git a/include/gcodeExport.h b/include/gcodeExport.h index b16512569b..f05cac2a81 100644 --- a/include/gcodeExport.h +++ b/include/gcodeExport.h @@ -67,76 +67,76 @@ class GCodeExport : public NoCopy private: struct ExtruderTrainAttributes { - bool is_primed; //!< Whether this extruder has currently already been primed in this print + bool is_primed_; //!< Whether this extruder has currently already been primed in this print - bool is_used; //!< Whether this extruder train is actually used during the printing of all meshgroups - char extruderCharacter; + bool is_used_; //!< Whether this extruder train is actually used during the printing of all meshgroups + char extruder_character_; - double filament_area; //!< in mm^2 for non-volumetric, cylindrical filament + double filament_area_; //!< in mm^2 for non-volumetric, cylindrical filament - double totalFilament; //!< total filament used per extruder in mm^3 - Temperature currentTemperature; - bool waited_for_temperature; //!< Whether the most recent temperature command has been a heat-and-wait command (M109) or not (M104). - Temperature initial_temp; //!< Temperature this nozzle needs to be at the start of the print. + double total_filament_; //!< total filament used per extruder in mm^3 + Temperature current_temperature_; + bool waited_for_temperature_; //!< Whether the most recent temperature command has been a heat-and-wait command (M109) or not (M104). + Temperature initial_temp_; //!< Temperature this nozzle needs to be at the start of the print. - double retraction_e_amount_current; //!< The current retracted amount (in mm or mm^3), or zero(i.e. false) if it is not currently retracted (positive values mean retracted + double retraction_e_amount_current_; //!< The current retracted amount (in mm or mm^3), or zero(i.e. false) if it is not currently retracted (positive values mean retracted //!< amount, so negative impact on E values) - double retraction_e_amount_at_e_start; //!< The ExtruderTrainAttributes::retraction_amount_current value at E0, i.e. the offset (in mm or mm^3) from E0 to the situation + double retraction_e_amount_at_e_start_; //!< The ExtruderTrainAttributes::retraction_amount_current value at E0, i.e. the offset (in mm or mm^3) from E0 to the situation //!< where the filament is at the tip of the nozzle. - double prime_volume; //!< Amount of material (in mm^3) to be primed after an unretration (due to oozing and/or coasting) - Velocity last_retraction_prime_speed; //!< The last prime speed (in mm/s) of the to-be-primed amount + double prime_volume_; //!< Amount of material (in mm^3) to be primed after an unretration (due to oozing and/or coasting) + Velocity last_retraction_prime_speed_; //!< The last prime speed (in mm/s) of the to-be-primed amount - double last_e_value_after_wipe; //!< The current material amount extruded since last wipe + double last_e_value_after_wipe_; //!< The current material amount extruded since last wipe - unsigned fan_number; // nozzle print cooling fan number - Point nozzle_offset; //!< Cache of setting machine_nozzle_offset_[xy] - bool machine_firmware_retract; //!< Cache of setting machine_firmware_retract + unsigned fan_number_; // nozzle print cooling fan number + Point nozzle_offset_; //!< Cache of setting machine_nozzle_offset_[xy] + bool machine_firmware_retract_; //!< Cache of setting machine_firmware_retract - std::deque extruded_volume_at_previous_n_retractions; // in mm^3 + std::deque extruded_volume_at_previous_n_retractions_; // in mm^3 ExtruderTrainAttributes() - : is_primed(false) - , is_used(false) - , extruderCharacter(0) - , filament_area(0) - , totalFilament(0) - , currentTemperature(0) - , waited_for_temperature(false) - , initial_temp(0) - , retraction_e_amount_current(0.0) - , retraction_e_amount_at_e_start(0.0) - , prime_volume(0.0) - , last_retraction_prime_speed(0.0) - , fan_number(0) + : is_primed_(false) + , is_used_(false) + , extruder_character_(0) + , filament_area_(0) + , total_filament_(0) + , current_temperature_(0) + , waited_for_temperature_(false) + , initial_temp_(0) + , retraction_e_amount_current_(0.0) + , retraction_e_amount_at_e_start_(0.0) + , prime_volume_(0.0) + , last_retraction_prime_speed_(0.0) + , fan_number_(0) { } }; - ExtruderTrainAttributes extruder_attr[MAX_EXTRUDERS]; - bool use_extruder_offset_to_offset_coords; - std::string machine_name; + ExtruderTrainAttributes extruder_attr_[MAX_EXTRUDERS]; + bool use_extruder_offset_to_offset_coords_; + std::string machine_name_; std::string slice_uuid_; //!< The UUID of the current slice. - std::ostream* output_stream; - std::string new_line; + std::ostream* output_stream_; + std::string new_line_; - double current_e_value; //!< The last E value written to gcode (in mm or mm^3) + double current_e_value_; //!< The last E value written to gcode (in mm or mm^3) // flow-rate compensation - double current_e_offset; //!< Offset to compensate for flow rate (mm or mm^3) - double max_extrusion_offset; //!< 0 to turn it off, normally 4 - double extrusion_offset_factor; //!< default 1 - - Point3 currentPosition; //!< The last build plate coordinates written to gcode (which might be different from actually written gcode coordinates when the extruder offset is - //!< encoded in the gcode) - Velocity currentSpeed; //!< The current speed (F values / 60) in mm/s - Acceleration current_print_acceleration; //!< The current acceleration (in mm/s^2) used for print moves (and also for travel moves if the gcode flavor doesn't have separate - //!< travel acceleration) + double current_e_offset_; //!< Offset to compensate for flow rate (mm or mm^3) + double max_extrusion_offset_; //!< 0 to turn it off, normally 4 + double extrusion_offset_factor_; //!< default 1 + + Point3 current_position_; //!< The last build plate coordinates written to gcode (which might be different from actually written gcode coordinates when the extruder offset is + //!< encoded in the gcode) + Velocity current_speed_; //!< The current speed (F values / 60) in mm/s + Acceleration current_print_acceleration_; //!< The current acceleration (in mm/s^2) used for print moves (and also for travel moves if the gcode flavor doesn't have separate + //!< travel acceleration) Acceleration - current_travel_acceleration; //!< The current acceleration (in mm/s^2) used for travel moves for those gcode flavors that have separate print and travel accelerations - Velocity current_jerk; //!< The current jerk in the XY direction (in mm/s^3) + current_travel_acceleration_; //!< The current acceleration (in mm/s^2) used for travel moves for those gcode flavors that have separate print and travel accelerations + Velocity current_jerk_; //!< The current jerk in the XY direction (in mm/s^3) - AABB3D total_bounding_box; //!< The bounding box of all g-code. + AABB3D total_bounding_box_; //!< The bounding box of all g-code. /*! * The z position to be used on the next xy move, if the head wasn't in the correct z position yet. @@ -145,28 +145,29 @@ class GCodeExport : public NoCopy * * \note After GCodeExport::writeExtrusion(Point, double, double) has been called currentPosition.z coincides with this value */ - coord_t current_layer_z; - coord_t is_z_hopped; //!< The amount by which the print head is currently z hopped, or zero if it is not z hopped. (A z hop is used during travel moves to avoid collision with - //!< other layer parts) + coord_t current_layer_z_; + coord_t is_z_hopped_; //!< The amount by which the print head is currently z hopped, or zero if it is not z hopped. (A z hop is used during travel moves to avoid collision with + //!< other layer parts) - size_t current_extruder; - double current_fan_speed; - unsigned fan_number; // current print cooling fan number - EGCodeFlavor flavor; + size_t current_extruder_; + double current_fan_speed_; + unsigned fan_number_; // current print cooling fan number + EGCodeFlavor flavor_; - std::vector total_print_times; //!< The total estimated print time in seconds for each feature - TimeEstimateCalculator estimateCalculator; + std::vector total_print_times_; //!< The total estimated print time in seconds for each feature + TimeEstimateCalculator estimate_calculator_; - LayerIndex layer_nr; //!< for sending travel data + LayerIndex layer_nr_; //!< for sending travel data - bool is_volumetric; - bool relative_extrusion; //!< whether to use relative extrusion distances rather than absolute - bool always_write_active_tool; //!< whether to write the active tool after sending commands to inactive tool + bool is_volumetric_; + bool relative_extrusion_; //!< whether to use relative extrusion distances rather than absolute + bool always_write_active_tool_; //!< whether to write the active tool after sending commands to inactive tool + + Temperature initial_bed_temp_; //!< bed temperature at the beginning of the print. + Temperature bed_temperature_; //!< Current build plate temperature. + Temperature build_volume_temperature_; //!< build volume temperature + bool machine_heated_build_volume_; //!< does the machine have the ability to control/stabilize build-volume-temperature - Temperature initial_bed_temp; //!< bed temperature at the beginning of the print. - Temperature bed_temperature; //!< Current build plate temperature. - Temperature build_volume_temperature; //!< build volume temperature - bool machine_heated_build_volume; //!< does the machine have the ability to control/stabilize build-volume-temperature protected: /*! * Convert an E value to a value in mm (if it wasn't already in mm) for the current extruder. diff --git a/include/progress/ProgressStageEstimator.h b/include/progress/ProgressStageEstimator.h index f6a9f14376..a60bd5e32f 100644 --- a/include/progress/ProgressStageEstimator.h +++ b/include/progress/ProgressStageEstimator.h @@ -1,5 +1,5 @@ -//Copyright (c) 2020 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2020 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef PROGRESS_PROGRESS_STAGE_ESTIMATOR_H #define PROGRESS_PROGRESS_STAGE_ESTIMATOR_H @@ -18,39 +18,39 @@ class ProgressStageEstimator : public ProgressEstimator { struct ProgressStage { - double relative_estimated_time; - ProgressEstimator* stage; + double relative_estimated_time_; + ProgressEstimator* stage_; + ProgressStage(double relative_estimated_time) - : relative_estimated_time(relative_estimated_time) - , stage(nullptr) + : relative_estimated_time_(relative_estimated_time) + , stage_(nullptr) { } - }; - + protected: - std::vector stages; - double total_estimated_time; - + std::vector stages_; + double total_estimated_time_; + private: - double accumulated_estimate; - int current_stage_idx; - + double accumulated_estimate_; + int current_stage_idx_; + public: ProgressStageEstimator(std::vector& relative_time_estimates); - + double progress(int current_step); - + /*! - * + * * \warning This class is responsible for deleting the \p stage - * + * */ void nextStage(ProgressEstimator* stage); - + ~ProgressStageEstimator(); }; } // namespace cura -#endif // PROGRESS_PROGRESS_STAGE_ESTIMATOR_H \ No newline at end of file +#endif // PROGRESS_PROGRESS_STAGE_ESTIMATOR_H diff --git a/include/skin.h b/include/skin.h index de96d6e1c3..e0367cbf0c 100644 --- a/include/skin.h +++ b/include/skin.h @@ -161,21 +161,22 @@ class SkinInfillAreaComputation Polygons generateFilledAreaBelow(SliceLayerPart& part, size_t flooring_layer_count); protected: - LayerIndex layer_nr; //!< The index of the layer for which to generate the skins and infill. - SliceMeshStorage& mesh; //!< The storage where the layer outline information (input) is stored and where the skin insets and fill areas (output) are stored. - size_t bottom_layer_count; //!< The number of layers of bottom skin - size_t initial_bottom_layer_count; //!< Whether to make bottom skin for the initial layer - size_t top_layer_count; //!< The number of layers of top skin - size_t wall_line_count; //!< The number of walls, i.e. the number of the wall from which to offset. - coord_t skin_line_width; //!< The line width of the skin. - size_t skin_inset_count; //!< The number of perimeters to surround the skin - bool no_small_gaps_heuristic; //!< A heuristic which assumes there will be no small gaps between bottom and top skin with a z size smaller than the skin size itself - bool process_infill; //!< Whether to process infill, i.e. whether there's a positive infill density or there are infill meshes modifying this mesh. - - coord_t top_skin_preshrink; //!< The top skin removal width, to remove thin strips of skin along nearly-vertical walls. - coord_t bottom_skin_preshrink; //!< The bottom skin removal width, to remove thin strips of skin along nearly-vertical walls. - coord_t top_skin_expand_distance; //!< The distance by which the top skins should be larger than the original top skins. - coord_t bottom_skin_expand_distance; //!< The distance by which the bottom skins should be larger than the original bottom skins. + LayerIndex layer_nr_; //!< The index of the layer for which to generate the skins and infill. + SliceMeshStorage& mesh_; //!< The storage where the layer outline information (input) is stored and where the skin insets and fill areas (output) are stored. + size_t bottom_layer_count_; //!< The number of layers of bottom skin + size_t initial_bottom_layer_count_; //!< Whether to make bottom skin for the initial layer + size_t top_layer_count_; //!< The number of layers of top skin + size_t wall_line_count_; //!< The number of walls, i.e. the number of the wall from which to offset. + coord_t skin_line_width_; //!< The line width of the skin. + size_t skin_inset_count_; //!< The number of perimeters to surround the skin + bool no_small_gaps_heuristic_; //!< A heuristic which assumes there will be no small gaps between bottom and top skin with a z size smaller than the skin size itself + bool process_infill_; //!< Whether to process infill, i.e. whether there's a positive infill density or there are infill meshes modifying this mesh. + + coord_t top_skin_preshrink_; //!< The top skin removal width, to remove thin strips of skin along nearly-vertical walls. + coord_t bottom_skin_preshrink_; //!< The bottom skin removal width, to remove thin strips of skin along nearly-vertical walls. + coord_t top_skin_expand_distance_; //!< The distance by which the top skins should be larger than the original top skins. + coord_t bottom_skin_expand_distance_; //!< The distance by which the bottom skins should be larger than the original bottom skins. + private: static coord_t getSkinLineWidth(const SliceMeshStorage& mesh, const LayerIndex& layer_nr); //!< Compute the skin line width, which might be different for the first layer. diff --git a/include/utils/HalfEdge.h b/include/utils/HalfEdge.h index 63ef040ead..34df6f2a48 100644 --- a/include/utils/HalfEdge.h +++ b/include/utils/HalfEdge.h @@ -18,16 +18,20 @@ class HalfEdge { using edge_t = derived_edge_t; using node_t = derived_node_t; + public: - edge_data_t data; - edge_t* twin = nullptr; - edge_t* next = nullptr; - edge_t* prev = nullptr; - node_t* from = nullptr; - node_t* to = nullptr; + edge_data_t data_; + edge_t* twin_ = nullptr; + edge_t* next_ = nullptr; + edge_t* prev_ = nullptr; + node_t* from_ = nullptr; + node_t* to_ = nullptr; + HalfEdge(edge_data_t data) - : data(data) - {} + : data_(data) + { + } + bool operator==(const edge_t& other) { return this == &other; @@ -35,7 +39,5 @@ class HalfEdge }; - - } // namespace cura #endif // UTILS_HALF_EDGE_H diff --git a/include/utils/HalfEdgeNode.h b/include/utils/HalfEdgeNode.h index b22a7fa804..3da47ba7fe 100644 --- a/include/utils/HalfEdgeNode.h +++ b/include/utils/HalfEdgeNode.h @@ -16,14 +16,17 @@ class HalfEdgeNode { using edge_t = derived_edge_t; using node_t = derived_node_t; + public: - node_data_t data; - Point p; - edge_t* incident_edge = nullptr; + node_data_t data_; + Point p_; + edge_t* incident_edge_ = nullptr; + HalfEdgeNode(node_data_t data, Point p) - : data(data) - , p(p) - {} + : data_(data) + , p_(p) + { + } bool operator==(const node_t& other) { @@ -32,7 +35,5 @@ class HalfEdgeNode }; - - } // namespace cura #endif // UTILS_HALF_EDGE_NODE_H diff --git a/src/FffGcodeWriter.cpp b/src/FffGcodeWriter.cpp index 91fb9ffbbe..119ddfbd31 100644 --- a/src/FffGcodeWriter.cpp +++ b/src/FffGcodeWriter.cpp @@ -558,7 +558,7 @@ void FffGcodeWriter::processRaft(const SliceDataStorage& storage) const size_t base_extruder_nr = mesh_group_settings.get("raft_base_extruder_nr").extruder_nr_; const size_t interface_extruder_nr = mesh_group_settings.get("raft_interface_extruder_nr").extruder_nr_; const size_t surface_extruder_nr = mesh_group_settings.get("raft_surface_extruder_nr").extruder_nr_; - const size_t prime_tower_extruder_nr = storage.primeTower.extruder_order.front(); + const size_t prime_tower_extruder_nr = storage.primeTower.extruder_order_.front(); coord_t z = 0; const LayerIndex initial_raft_layer_nr = -Raft::getTotalExtraLayers(); @@ -631,7 +631,7 @@ void FffGcodeWriter::processRaft(const SliceDataStorage& storage) std::vector raft_outline_paths; raft_outline_paths.emplace_back(ParameterizedRaftPath{ line_spacing, storage.raftOutline }); - if (storage.primeTower.enabled) + if (storage.primeTower.enabled_) { const Polygons& raft_outline_prime_tower = storage.primeTower.getOuterPoly(layer_nr); if (line_spacing_prime_tower == line_spacing) @@ -718,7 +718,7 @@ void FffGcodeWriter::processRaft(const SliceDataStorage& storage) for (LayerIndex raft_interface_layer = 1; static_cast(raft_interface_layer) <= num_interface_layers; ++raft_interface_layer) { // raft interface layer - bool prime_tower_added_on_this_layer = ! storage.primeTower.enabled; + bool prime_tower_added_on_this_layer = ! storage.primeTower.enabled_; const LayerIndex layer_nr = initial_raft_layer_nr + raft_interface_layer; z += interface_layer_height; @@ -779,7 +779,7 @@ void FffGcodeWriter::processRaft(const SliceDataStorage& storage) constexpr int zag_skip_count = 0; constexpr coord_t pocket_size = 0; - if (storage.primeTower.enabled) + if (storage.primeTower.enabled_) { // Interface layer excludes prime tower base raft_outline_path = raft_outline_path.difference(storage.primeTower.getOuterPoly(layer_nr)); @@ -836,7 +836,7 @@ void FffGcodeWriter::processRaft(const SliceDataStorage& storage) for (LayerIndex raft_surface_layer = 1; static_cast(raft_surface_layer) <= num_surface_layers; raft_surface_layer++) { // raft surface layers - bool prime_tower_added_on_this_layer = ! storage.primeTower.enabled; + bool prime_tower_added_on_this_layer = ! storage.primeTower.enabled_; const LayerIndex layer_nr = initial_raft_layer_nr + 1 + num_interface_layers + raft_surface_layer - 1; // +1: 1 base layer z += surface_layer_height; @@ -899,7 +899,7 @@ void FffGcodeWriter::processRaft(const SliceDataStorage& storage) constexpr size_t zag_skip_count = 0; constexpr coord_t pocket_size = 0; - if (storage.primeTower.enabled) + if (storage.primeTower.enabled_) { // Surface layers exclude prime tower base raft_outline_path = raft_outline_path.difference(storage.primeTower.getOuterPoly(layer_nr)); @@ -1413,7 +1413,7 @@ std::vector FffGcodeWriter::getUsedExtrudersOnLayerExcludingStartingExtr // The outermost prime tower extruder is always used if there is a prime tower, apart on layers with negative index (e.g. for the raft) if (mesh_group_settings.get("prime_tower_enable") && /*layer_nr >= 0 &&*/ layer_nr <= storage.max_print_height_second_to_last_extruder) { - extruder_is_used_on_this_layer[storage.primeTower.extruder_order[0]] = true; + extruder_is_used_on_this_layer[storage.primeTower.extruder_order_[0]] = true; } // check if we are on the first layer @@ -2484,13 +2484,13 @@ bool FffGcodeWriter::processInsets( const size_t roofing_layer_count = std::min(mesh.settings.get("roofing_layer_count"), mesh.settings.get("top_layers")); const bool no_small_gaps_heuristic = mesh.settings.get("skin_no_small_gaps_heuristic"); const int layer_nr = gcode_layer.getLayerNr(); - auto filled_area_above = getOutlineOnLayer(part, layer_nr + roofing_layer_count); + auto filled_area_above_res = getOutlineOnLayer(part, layer_nr + roofing_layer_count); if (! no_small_gaps_heuristic) { for (int layer_nr_above = layer_nr + 1; layer_nr_above < layer_nr + roofing_layer_count; layer_nr_above++) { Polygons outlines_above = getOutlineOnLayer(part, layer_nr_above); - filled_area_above = filled_area_above.intersection(outlines_above); + filled_area_above_res = filled_area_above_res.intersection(outlines_above); } } if (layer_nr > 0) @@ -2506,11 +2506,11 @@ bool FffGcodeWriter::processInsets( if (! air_below.empty()) { // add the polygons that have air below to the no air above polygons - filled_area_above = filled_area_above.unionPolygons(air_below); + filled_area_above_res = filled_area_above_res.unionPolygons(air_below); } } - return filled_area_above; + return filled_area_above_res; }(); if (filled_area_above.empty()) @@ -3047,17 +3047,18 @@ void FffGcodeWriter::processSkinPrintFeature( else { std::optional near_start_location; - const EFillMethod pattern + const EFillMethod actual_pattern = (gcode_layer.getLayerNr() == 0) ? mesh.settings.get("top_bottom_pattern_0") : mesh.settings.get("top_bottom_pattern"); - if (pattern == EFillMethod::LINES || pattern == EFillMethod::ZIG_ZAG) + if (actual_pattern == EFillMethod::LINES || actual_pattern == EFillMethod::ZIG_ZAG) { // update near_start_location to a location which tries to avoid seams in skin near_start_location = getSeamAvoidingLocation(area, skin_angle, gcode_layer.getLastPlannedPositionOrStartingPosition()); } constexpr bool enable_travel_optimization = false; constexpr double flow = 1.0; - if (pattern == EFillMethod::GRID || pattern == EFillMethod::LINES || pattern == EFillMethod::TRIANGLES || pattern == EFillMethod::CUBIC - || pattern == EFillMethod::TETRAHEDRAL || pattern == EFillMethod::QUARTER_CUBIC || pattern == EFillMethod::CUBICSUBDIV || pattern == EFillMethod::LIGHTNING) + if (actual_pattern == EFillMethod::GRID || actual_pattern == EFillMethod::LINES || actual_pattern == EFillMethod::TRIANGLES || actual_pattern == EFillMethod::CUBIC + || actual_pattern == EFillMethod::TETRAHEDRAL || actual_pattern == EFillMethod::QUARTER_CUBIC || actual_pattern == EFillMethod::CUBICSUBDIV + || actual_pattern == EFillMethod::LIGHTNING) { gcode_layer.addLinesByOptimizer( skin_lines, @@ -3071,7 +3072,7 @@ void FffGcodeWriter::processSkinPrintFeature( } else { - SpaceFillType space_fill_type = (pattern == EFillMethod::ZIG_ZAG) ? SpaceFillType::PolyLines : SpaceFillType::Lines; + SpaceFillType space_fill_type = (actual_pattern == EFillMethod::ZIG_ZAG) ? SpaceFillType::PolyLines : SpaceFillType::Lines; constexpr coord_t wipe_dist = 0; gcode_layer.addLinesByOptimizer(skin_lines, config, space_fill_type, enable_travel_optimization, wipe_dist, flow, near_start_location, fan_speed); } diff --git a/src/FffPolygonGenerator.cpp b/src/FffPolygonGenerator.cpp index 4335a1b49d..cb4d60f6d4 100644 --- a/src/FffPolygonGenerator.cpp +++ b/src/FffPolygonGenerator.cpp @@ -425,7 +425,7 @@ void FffPolygonGenerator::slices2polygons(SliceDataStorage& storage, TimeKeeper& // This catches a special case in which the models are in the air, and then // the adhesion mustn't be calculated. - if (! isEmptyLayer(storage, 0) || storage.primeTower.enabled) + if (! isEmptyLayer(storage, 0) || storage.primeTower.enabled_) { spdlog::debug("Processing platform adhesion"); processPlatformAdhesion(storage); diff --git a/src/PrimeTower.cpp b/src/PrimeTower.cpp index 41bf694f43..bfcaed4bdb 100644 --- a/src/PrimeTower.cpp +++ b/src/PrimeTower.cpp @@ -24,7 +24,7 @@ namespace cura { PrimeTower::PrimeTower() - : wipe_from_middle(false) + : wipe_from_middle_(false) { const Scene& scene = Application::getInstance().current_slice_->scene; @@ -39,25 +39,25 @@ PrimeTower::PrimeTower() // used (sacrifying for this purpose the usual single-extruder first layer, that would be better for prime-tower // adhesion). - multiple_extruders_on_first_layer = scene.current_mesh_group->settings.get("machine_extruders_share_nozzle") - && ((adhesion_type != EPlatformAdhesion::SKIRT) && (adhesion_type != EPlatformAdhesion::BRIM)); + multiple_extruders_on_first_layer_ = scene.current_mesh_group->settings.get("machine_extruders_share_nozzle") + && ((adhesion_type != EPlatformAdhesion::SKIRT) && (adhesion_type != EPlatformAdhesion::BRIM)); } - enabled = scene.current_mesh_group->settings.get("prime_tower_enable") && scene.current_mesh_group->settings.get("prime_tower_min_volume") > 10 - && scene.current_mesh_group->settings.get("prime_tower_size") > 10; - would_have_actual_tower = enabled; // Assume so for now. + enabled_ = scene.current_mesh_group->settings.get("prime_tower_enable") && scene.current_mesh_group->settings.get("prime_tower_min_volume") > 10 + && scene.current_mesh_group->settings.get("prime_tower_size") > 10; + would_have_actual_tower_ = enabled_; // Assume so for now. - extruder_count = scene.extruders.size(); - extruder_order.resize(extruder_count); - for (unsigned int extruder_nr = 0; extruder_nr < extruder_count; extruder_nr++) + extruder_count_ = scene.extruders.size(); + extruder_order_.resize(extruder_count_); + for (unsigned int extruder_nr = 0; extruder_nr < extruder_count_; extruder_nr++) { - extruder_order[extruder_nr] = extruder_nr; // Start with default order, then sort. + extruder_order_[extruder_nr] = extruder_nr; // Start with default order, then sort. } // Sort from high adhesion to low adhesion. const Scene* scene_pointer = &scene; // Communicate to lambda via pointer to prevent copy. std::stable_sort( - extruder_order.begin(), - extruder_order.end(), + extruder_order_.begin(), + extruder_order_.end(), [scene_pointer](const unsigned int& extruder_nr_a, const unsigned int& extruder_nr_b) -> bool { const Ratio adhesion_a = scene_pointer->extruders[extruder_nr_a].settings_.get("material_adhesion_tendency"); @@ -76,13 +76,13 @@ void PrimeTower::checkUsed(const SliceDataStorage& storage) } if (used_extruder_count <= 1) { - enabled = false; + enabled_ = false; } } void PrimeTower::generateGroundpoly() { - if (! enabled) + if (! enabled_) { return; } @@ -94,18 +94,18 @@ void PrimeTower::generateGroundpoly() const coord_t x = mesh_group_settings.get("prime_tower_position_x"); const coord_t y = mesh_group_settings.get("prime_tower_position_y"); const coord_t tower_radius = tower_size / 2; - outer_poly.add(PolygonUtils::makeCircle(Point(x - tower_radius, y + tower_radius), tower_radius, TAU / CIRCLE_RESOLUTION)); - middle = Point(x - tower_size / 2, y + tower_size / 2); + outer_poly_.add(PolygonUtils::makeCircle(Point(x - tower_radius, y + tower_radius), tower_radius, TAU / CIRCLE_RESOLUTION)); + middle_ = Point(x - tower_size / 2, y + tower_size / 2); - post_wipe_point = Point(x - tower_size / 2, y + tower_size / 2); + post_wipe_point_ = Point(x - tower_size / 2, y + tower_size / 2); } void PrimeTower::generatePaths(const SliceDataStorage& storage) { const int raft_total_extra_layers = Raft::getTotalExtraLayers(); - would_have_actual_tower = storage.max_print_height_second_to_last_extruder - >= -raft_total_extra_layers; // Maybe it turns out that we don't need a prime tower after all because there are no layer switches. - if (would_have_actual_tower && enabled) + would_have_actual_tower_ = storage.max_print_height_second_to_last_extruder + >= -raft_total_extra_layers; // Maybe it turns out that we don't need a prime tower after all because there are no layer switches. + if (would_have_actual_tower_ && enabled_) { generatePaths_denseInfill(); generateStartLocations(); @@ -122,27 +122,26 @@ void PrimeTower::generatePaths_denseInfill() const bool has_raft = mesh_group_settings.get("adhesion_type") == EPlatformAdhesion::RAFT; const coord_t base_height = std::max(scene.settings.get("prime_tower_base_height"), has_raft ? layer_height : 0); const double base_curve_magnitude = mesh_group_settings.get("prime_tower_base_curve_magnitude"); - const coord_t line_width = scene.extruders[extruder_order.front()].settings_.get("prime_tower_line_width"); - prime_moves.resize(extruder_count); - base_extra_moves.resize(extruder_count); + prime_moves_.resize(extruder_count_); + base_extra_moves_.resize(extruder_count_); coord_t cumulative_inset = 0; // Each tower shape is going to be printed inside the other. This is the inset we're doing for each extruder. - for (size_t extruder_nr : extruder_order) + for (size_t extruder_nr : extruder_order_) { const coord_t line_width = scene.extruders[extruder_nr].settings_.get("prime_tower_line_width"); const coord_t required_volume = MM3_2INT(scene.extruders[extruder_nr].settings_.get("prime_tower_min_volume")); const Ratio flow = scene.extruders[extruder_nr].settings_.get("prime_tower_flow"); coord_t current_volume = 0; - Polygons& pattern = prime_moves[extruder_nr]; + Polygons& prime_moves = prime_moves_[extruder_nr]; // Create the walls of the prime tower. unsigned int wall_nr = 0; for (; current_volume < required_volume; wall_nr++) { // Create a new polygon with an offset from the outer polygon. - Polygons polygons = outer_poly.offset(-cumulative_inset - wall_nr * line_width - line_width / 2); - pattern.add(polygons); + Polygons polygons = outer_poly_.offset(-cumulative_inset - wall_nr * line_width - line_width / 2); + prime_moves.add(polygons); current_volume += polygons.polygonLength() * line_width * layer_height * flow; if (polygons.empty()) // Don't continue. We won't ever reach the required volume because it doesn't fit. { @@ -151,7 +150,7 @@ void PrimeTower::generatePaths_denseInfill() } // The most outside extruder is used for the base - if (extruder_nr == extruder_order.front() && (base_enabled || has_raft) && base_extra_radius > 0 && base_height > 0) + if (extruder_nr == extruder_order_.front() && (base_enabled || has_raft) && base_extra_radius > 0 && base_height > 0) { for (coord_t z = 0; z < base_height; z += layer_height) { @@ -163,21 +162,21 @@ void PrimeTower::generatePaths_denseInfill() break; } extra_radius = line_width * extra_rings; - outer_poly_base.push_back(outer_poly.offset(extra_radius)); + outer_poly_base_.push_back(outer_poly_.offset(extra_radius)); - base_extra_moves[extruder_nr].push_back(PolygonUtils::generateOutset(outer_poly, extra_rings, line_width)); + base_extra_moves_[extruder_nr].push_back(PolygonUtils::generateOutset(outer_poly_, extra_rings, line_width)); } } cumulative_inset += wall_nr * line_width; // Only the most inside extruder needs to fill the inside of the prime tower - if (extruder_nr == extruder_order.back()) + if (extruder_nr == extruder_order_.back()) { - Polygons pattern = PolygonUtils::generateInset(outer_poly, line_width, cumulative_inset); - if (! pattern.empty()) + Polygons base_extra_moves = PolygonUtils::generateInset(outer_poly_, line_width, cumulative_inset); + if (! base_extra_moves.empty()) { - base_extra_moves[extruder_nr].push_back(pattern); + base_extra_moves_[extruder_nr].push_back(base_extra_moves); } } } @@ -187,15 +186,15 @@ void PrimeTower::generateStartLocations() { // Evenly spread out a number of dots along the prime tower's outline. This is done for the complete outline, // so use the same start and end segments for this. - PolygonsPointIndex segment_start = PolygonsPointIndex(&outer_poly, 0, 0); + PolygonsPointIndex segment_start = PolygonsPointIndex(&outer_poly_, 0, 0); PolygonsPointIndex segment_end = segment_start; - PolygonUtils::spreadDots(segment_start, segment_end, number_of_prime_tower_start_locations, prime_tower_start_locations); + PolygonUtils::spreadDots(segment_start, segment_end, number_of_prime_tower_start_locations_, prime_tower_start_locations_); } void PrimeTower::addToGcode(const SliceDataStorage& storage, LayerPlan& gcode_layer, const size_t prev_extruder, const size_t new_extruder) const { - if (! (enabled && would_have_actual_tower)) + if (! (enabled_ && would_have_actual_tower_)) { return; } @@ -234,7 +233,7 @@ void PrimeTower::addToGcode(const SliceDataStorage& storage, LayerPlan& gcode_la const Point previous_nozzle_offset = Point(previous_settings.get("machine_nozzle_offset_x"), previous_settings.get("machine_nozzle_offset_y")); const Settings& new_settings = Application::getInstance().current_slice_->scene.extruders[new_extruder].settings_; const Point new_nozzle_offset = Point(new_settings.get("machine_nozzle_offset_x"), new_settings.get("machine_nozzle_offset_y")); - gcode_layer.addTravel(post_wipe_point - previous_nozzle_offset + new_nozzle_offset); + gcode_layer.addTravel(post_wipe_point_ - previous_nozzle_offset + new_nozzle_offset); } gcode_layer.setPrimeTowerIsPlanned(new_extruder); @@ -250,11 +249,11 @@ void PrimeTower::addToGcode_denseInfill(LayerPlan& gcode_layer, const size_t ext { // Actual prime pattern const GCodePathConfig& config = gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr]; - const Polygons& pattern = prime_moves[extruder_nr]; + const Polygons& pattern = prime_moves_[extruder_nr]; gcode_layer.addPolygonsByOptimizer(pattern, config); } - const std::vector& pattern_extra_brim = base_extra_moves[extruder_nr]; + const std::vector& pattern_extra_brim = base_extra_moves_[extruder_nr]; if (absolute_layer_number < pattern_extra_brim.size()) { // Extra rings for stronger base @@ -279,13 +278,13 @@ void PrimeTower::subtractFromSupport(SliceDataStorage& storage) const Polygons& PrimeTower::getOuterPoly(const LayerIndex& layer_nr) const { const LayerIndex absolute_layer_nr = layer_nr + Raft::getTotalExtraLayers(); - if (absolute_layer_nr < outer_poly_base.size()) + if (absolute_layer_nr < outer_poly_base_.size()) { - return outer_poly_base[absolute_layer_nr]; + return outer_poly_base_[absolute_layer_nr]; } else { - return outer_poly; + return outer_poly_; } } @@ -296,10 +295,10 @@ const Polygons& PrimeTower::getGroundPoly() const void PrimeTower::gotoStartLocation(LayerPlan& gcode_layer, const int extruder_nr) const { - int current_start_location_idx = ((((extruder_nr + 1) * gcode_layer.getLayerNr()) % number_of_prime_tower_start_locations) + number_of_prime_tower_start_locations) - % number_of_prime_tower_start_locations; + int current_start_location_idx = ((((extruder_nr + 1) * gcode_layer.getLayerNr()) % number_of_prime_tower_start_locations_) + number_of_prime_tower_start_locations_) + % number_of_prime_tower_start_locations_; - const ClosestPolygonPoint wipe_location = prime_tower_start_locations[current_start_location_idx]; + const ClosestPolygonPoint wipe_location = prime_tower_start_locations_[current_start_location_idx]; const ExtruderTrain& train = Application::getInstance().current_slice_->scene.extruders[extruder_nr]; const coord_t inward_dist = train.settings_.get("machine_nozzle_size") * 3 / 2; diff --git a/src/SkeletalTrapezoidation.cpp b/src/SkeletalTrapezoidation.cpp index e56844549a..94adbffe11 100644 --- a/src/SkeletalTrapezoidation.cpp +++ b/src/SkeletalTrapezoidation.cpp @@ -59,7 +59,7 @@ void SkeletalTrapezoidation::transferEdge( auto end_node_it = vd_node_to_he_node_.find(vd_edge.vertex1()); assert(end_node_it != vd_node_to_he_node_.end()); node_t* end_node = end_node_it->second; - for (edge_t* twin = source_twin;; twin = twin->prev->twin->prev) + for (edge_t* twin = source_twin;; twin = twin->prev_->twin_->prev_) { if (! twin) { @@ -69,34 +69,34 @@ void SkeletalTrapezoidation::transferEdge( assert(twin); graph_.edges.emplace_front(SkeletalTrapezoidationEdge()); edge_t* edge = &graph_.edges.front(); - edge->from = twin->to; - edge->to = twin->from; - edge->twin = twin; - twin->twin = edge; - edge->from->incident_edge = edge; + edge->from_ = twin->to_; + edge->to_ = twin->from_; + edge->twin_ = twin; + twin->twin_ = edge; + edge->from_->incident_edge_ = edge; if (prev_edge) { - edge->prev = prev_edge; - prev_edge->next = edge; + edge->prev_ = prev_edge; + prev_edge->next_ = edge; } prev_edge = edge; - if (prev_edge->to == end_node) + if (prev_edge->to_ == end_node) { return; } - if (! twin->prev || ! twin->prev->twin || ! twin->prev->twin->prev) + if (! twin->prev_ || ! twin->prev_->twin_ || ! twin->prev_->twin_->prev_) { spdlog::error("Discretized segment behaves oddly!"); return; } - assert(twin->prev); // Forth rib - assert(twin->prev->twin); // Back rib - assert(twin->prev->twin->prev); // Prev segment along parabola + assert(twin->prev_); // Forth rib + assert(twin->prev_->twin_); // Back rib + assert(twin->prev_->twin_->prev_); // Prev segment along parabola constexpr bool is_not_next_to_start_or_end = false; // Only ribs at the end of a cell should be skipped graph_.makeRib(prev_edge, start_source_point, end_source_point, is_not_next_to_start_or_end); @@ -112,13 +112,13 @@ void SkeletalTrapezoidation::transferEdge( spdlog::warn("Discretized Voronoi edge is degenerate."); } - assert(! prev_edge || prev_edge->to); - if (prev_edge && ! prev_edge->to) + assert(! prev_edge || prev_edge->to_); + if (prev_edge && ! prev_edge->to_) { spdlog::warn("Previous edge doesn't go anywhere."); } node_t* v0 - = (prev_edge) ? prev_edge->to : &makeNode(*vd_edge.vertex0(), from); // TODO: investigate whether boost:voronoi can produce multiple verts and violates consistency + = (prev_edge) ? prev_edge->to_ : &makeNode(*vd_edge.vertex0(), from); // TODO: investigate whether boost:voronoi can produce multiple verts and violates consistency Point p0 = discretized.front(); for (size_t p1_idx = 1; p1_idx < discretized.size(); p1_idx++) { @@ -136,14 +136,14 @@ void SkeletalTrapezoidation::transferEdge( graph_.edges.emplace_front(SkeletalTrapezoidationEdge()); edge_t* edge = &graph_.edges.front(); - edge->from = v0; - edge->to = v1; - edge->from->incident_edge = edge; + edge->from_ = v0; + edge->to_ = v1; + edge->from_->incident_edge_ = edge; if (prev_edge) { - edge->prev = prev_edge; - prev_edge->next = edge; + edge->prev_ = prev_edge; + prev_edge->next_ = edge; } prev_edge = edge; @@ -458,7 +458,7 @@ void SkeletalTrapezoidation::constructFromPolygons(const Polygons& polys) points, segments); node_t* starting_node = vd_node_to_he_node_[starting_vonoroi_edge->vertex0()]; - starting_node->data.distance_to_boundary_ = 0; + starting_node->data_.distance_to_boundary_ = 0; constexpr bool is_next_to_start_or_end = true; graph_.makeRib(prev_edge, start_source_point, end_source_point, is_next_to_start_or_end); @@ -473,7 +473,7 @@ void SkeletalTrapezoidation::constructFromPolygons(const Polygons& polys) } transferEdge(VoronoiUtils::p(ending_vonoroi_edge->vertex0()), end_source_point, *ending_vonoroi_edge, prev_edge, start_source_point, end_source_point, points, segments); - prev_edge->to->data.distance_to_boundary_ = 0; + prev_edge->to_->data_.distance_to_boundary_ = 0; } separatePointyQuadEndNodes(); @@ -484,9 +484,9 @@ void SkeletalTrapezoidation::constructFromPolygons(const Polygons& polys) // without needing to iterate backward for (edge_t& edge : graph_.edges) { - if (! edge.prev) + if (! edge.prev_) { - edge.from->incident_edge = &edge; + edge.from_->incident_edge_ = &edge; } } } @@ -496,22 +496,22 @@ void SkeletalTrapezoidation::separatePointyQuadEndNodes() std::unordered_set visited_nodes; for (edge_t& edge : graph_.edges) { - if (edge.prev) + if (edge.prev_) { continue; } edge_t* quad_start = &edge; - if (visited_nodes.find(quad_start->from) == visited_nodes.end()) + if (visited_nodes.find(quad_start->from_) == visited_nodes.end()) { - visited_nodes.emplace(quad_start->from); + visited_nodes.emplace(quad_start->from_); } else { // Needs to be duplicated - graph_.nodes.emplace_back(*quad_start->from); + graph_.nodes.emplace_back(*quad_start->from_); node_t* new_node = &graph_.nodes.back(); - new_node->incident_edge = quad_start; - quad_start->from = new_node; - quad_start->twin->to = new_node; + new_node->incident_edge_ = quad_start; + quad_start->from_ = new_node; + quad_start->twin_->to_ = new_node; } } } @@ -720,32 +720,32 @@ void SkeletalTrapezoidation::updateIsCentral() double cap = sin(beading_strategy_.getTransitioningAngle() * 0.5); // = cos(bisector_angle / 2) for (edge_t& edge : graph_.edges) { - assert(edge.twin); - if (! edge.twin) + assert(edge.twin_); + if (! edge.twin_) { spdlog::warn("Encountered a Voronoi edge without twin!"); continue; } - if (edge.twin->data.centralIsSet()) + if (edge.twin_->data_.centralIsSet()) { - edge.data.setIsCentral(edge.twin->data.isCentral()); + edge.data_.setIsCentral(edge.twin_->data_.isCentral()); } - else if (edge.data.type_ == SkeletalTrapezoidationEdge::EdgeType::EXTRA_VD) + else if (edge.data_.type_ == SkeletalTrapezoidationEdge::EdgeType::EXTRA_VD) { - edge.data.setIsCentral(false); + edge.data_.setIsCentral(false); } - else if (std::max(edge.from->data.distance_to_boundary_, edge.to->data.distance_to_boundary_) < outer_edge_filter_length) + else if (std::max(edge.from_->data_.distance_to_boundary_, edge.to_->data_.distance_to_boundary_) < outer_edge_filter_length) { - edge.data.setIsCentral(false); + edge.data_.setIsCentral(false); } else { - Point a = edge.from->p; - Point b = edge.to->p; + Point a = edge.from_->p_; + Point b = edge.to_->p_; Point ab = b - a; - coord_t dR = std::abs(edge.to->data.distance_to_boundary_ - edge.from->data.distance_to_boundary_); + coord_t dR = std::abs(edge.to_->data_.distance_to_boundary_ - edge.from_->data_.distance_to_boundary_); coord_t dD = vSize(ab); - edge.data.setIsCentral(dR < dD * cap); + edge.data_.setIsCentral(dR < dD * cap); } } } @@ -754,35 +754,35 @@ void SkeletalTrapezoidation::filterCentral(coord_t max_length) { for (edge_t& edge : graph_.edges) { - if (isEndOfCentral(edge) && edge.to->isLocalMaximum() && ! edge.to->isLocalMaximum()) + if (isEndOfCentral(edge) && edge.to_->isLocalMaximum() && ! edge.to_->isLocalMaximum()) { - filterCentral(edge.twin, 0, max_length); + filterCentral(edge.twin_, 0, max_length); } } } bool SkeletalTrapezoidation::filterCentral(edge_t* starting_edge, coord_t traveled_dist, coord_t max_length) { - coord_t length = vSize(starting_edge->from->p - starting_edge->to->p); + coord_t length = vSize(starting_edge->from_->p_ - starting_edge->to_->p_); if (traveled_dist + length > max_length) { return false; } bool should_dissolve = true; // Should we unmark this as central and propagate that? - for (edge_t* next_edge = starting_edge->next; next_edge && next_edge != starting_edge->twin; next_edge = next_edge->twin->next) + for (edge_t* next_edge = starting_edge->next_; next_edge && next_edge != starting_edge->twin_; next_edge = next_edge->twin_->next_) { - if (next_edge->data.isCentral()) + if (next_edge->data_.isCentral()) { should_dissolve &= filterCentral(next_edge, traveled_dist + length, max_length); } } - should_dissolve &= ! starting_edge->to->isLocalMaximum(); // Don't filter central regions with a local maximum! + should_dissolve &= ! starting_edge->to_->isLocalMaximum(); // Don't filter central regions with a local maximum! if (should_dissolve) { - starting_edge->data.setIsCentral(false); - starting_edge->twin->data.setIsCentral(false); + starting_edge->data_.setIsCentral(false); + starting_edge->twin_->data_.setIsCentral(false); } return should_dissolve; } @@ -791,10 +791,10 @@ void SkeletalTrapezoidation::filterOuterCentral() { for (edge_t& edge : graph_.edges) { - if (! edge.prev) + if (! edge.prev_) { - edge.data.setIsCentral(false); - edge.twin->data.setIsCentral(false); + edge.data_.setIsCentral(false); + edge.twin_->data_.setIsCentral(false); } } } @@ -803,9 +803,9 @@ void SkeletalTrapezoidation::updateBeadCount() { for (edge_t& edge : graph_.edges) { - if (edge.data.isCentral()) + if (edge.data_.isCentral()) { - edge.to->data.bead_count_ = beading_strategy_.getOptimalBeadCount(edge.to->data.distance_to_boundary_ * 2); + edge.to_->data_.bead_count_ = beading_strategy_.getOptimalBeadCount(edge.to_->data_.distance_to_boundary_ * 2); } } @@ -814,18 +814,18 @@ void SkeletalTrapezoidation::updateBeadCount() { if (node.isLocalMaximum()) { - if (node.data.distance_to_boundary_ < 0) + if (node.data_.distance_to_boundary_ < 0) { spdlog::warn("Distance to boundary not yet computed for local maximum!"); - node.data.distance_to_boundary_ = std::numeric_limits::max(); - edge_t* edge = node.incident_edge; + node.data_.distance_to_boundary_ = std::numeric_limits::max(); + edge_t* edge = node.incident_edge_; do { - node.data.distance_to_boundary_ = std::min(node.data.distance_to_boundary_, edge->to->data.distance_to_boundary_ + vSize(edge->from->p - edge->to->p)); - } while (edge = edge->twin->next, edge != node.incident_edge); + node.data_.distance_to_boundary_ = std::min(node.data_.distance_to_boundary_, edge->to_->data_.distance_to_boundary_ + vSize(edge->from_->p_ - edge->to_->p_)); + } while (edge = edge->twin_->next_, edge != node.incident_edge_); } - coord_t bead_count = beading_strategy_.getOptimalBeadCount(node.data.distance_to_boundary_ * 2); - node.data.bead_count_ = bead_count; + coord_t bead_count = beading_strategy_.getOptimalBeadCount(node.data_.distance_to_boundary_ * 2); + node.data_.bead_count_ = bead_count; } } } @@ -838,56 +838,56 @@ void SkeletalTrapezoidation::filterNoncentralRegions() { continue; } - if (edge.to->data.bead_count_ < 0 && edge.to->data.distance_to_boundary_ != 0) + if (edge.to_->data_.bead_count_ < 0 && edge.to_->data_.distance_to_boundary_ != 0) { spdlog::warn("Encountered an uninitialized bead at the boundary!"); } - assert(edge.to->data.bead_count_ >= 0 || edge.to->data.distance_to_boundary_ == 0); + assert(edge.to_->data_.bead_count_ >= 0 || edge.to_->data_.distance_to_boundary_ == 0); constexpr coord_t max_dist = 400; - filterNoncentralRegions(&edge, edge.to->data.bead_count_, 0, max_dist); + filterNoncentralRegions(&edge, edge.to_->data_.bead_count_, 0, max_dist); } } bool SkeletalTrapezoidation::filterNoncentralRegions(edge_t* to_edge, coord_t bead_count, coord_t traveled_dist, coord_t max_dist) { - coord_t r = to_edge->to->data.distance_to_boundary_; + coord_t r = to_edge->to_->data_.distance_to_boundary_; - edge_t* next_edge = to_edge->next; - for (; next_edge && next_edge != to_edge->twin; next_edge = next_edge->twin->next) + edge_t* next_edge = to_edge->next_; + for (; next_edge && next_edge != to_edge->twin_; next_edge = next_edge->twin_->next_) { - if (next_edge->to->data.distance_to_boundary_ >= r || shorterThen(next_edge->to->p - next_edge->from->p, 10)) + if (next_edge->to_->data_.distance_to_boundary_ >= r || shorterThen(next_edge->to_->p_ - next_edge->from_->p_, 10)) { break; // Only walk upward } } - if (next_edge == to_edge->twin || ! next_edge) + if (next_edge == to_edge->twin_ || ! next_edge) { return false; } - const coord_t length = vSize(next_edge->to->p - next_edge->from->p); + const coord_t length = vSize(next_edge->to_->p_ - next_edge->from_->p_); bool dissolve = false; - if (next_edge->to->data.bead_count_ == bead_count) + if (next_edge->to_->data_.bead_count_ == bead_count) { dissolve = true; } - else if (next_edge->to->data.bead_count_ < 0) + else if (next_edge->to_->data_.bead_count_ < 0) { dissolve = filterNoncentralRegions(next_edge, bead_count, traveled_dist + length, max_dist); } else // Upward bead count is different { // Dissolve if two central regions with different bead count are closer together than the max_dist (= transition distance) - dissolve = (traveled_dist + length < max_dist) && std::abs(next_edge->to->data.bead_count_ - bead_count) == 1; + dissolve = (traveled_dist + length < max_dist) && std::abs(next_edge->to_->data_.bead_count_ - bead_count) == 1; } if (dissolve) { - next_edge->data.setIsCentral(true); - next_edge->twin->data.setIsCentral(true); - next_edge->to->data.bead_count_ = beading_strategy_.getOptimalBeadCount(next_edge->to->data.distance_to_boundary_ * 2); - next_edge->to->data.transition_ratio_ = 0; + next_edge->data_.setIsCentral(true); + next_edge->twin_->data_.setIsCentral(true); + next_edge->to_->data_.bead_count_ = beading_strategy_.getOptimalBeadCount(next_edge->to_->data_.distance_to_boundary_ * 2); + next_edge->to_->data_.transition_ratio_ = 0; } return dissolve; // Dissolving only depend on the one edge going upward. There cannot be multiple edges going upward. } @@ -901,9 +901,9 @@ void SkeletalTrapezoidation::generateTransitioningRibs() for (edge_t& edge : graph_.edges) { // Check if there is a transition in between nodes with different bead counts - if (edge.data.isCentral() && edge.from->data.bead_count_ != edge.to->data.bead_count_) + if (edge.data_.isCentral() && edge.from_->data_.bead_count_ != edge.to_->data_.bead_count_) { - assert(edge.data.hasTransitions() || edge.twin->data.hasTransitions()); + assert(edge.data_.hasTransitions() || edge.twin_->data_.hasTransitions()); } } @@ -921,22 +921,22 @@ void SkeletalTrapezoidation::generateTransitionMids(ptr_vector_tdata.distance_to_boundary_; - coord_t end_R = edge.to->data.distance_to_boundary_; - int start_bead_count = edge.from->data.bead_count_; - int end_bead_count = edge.to->data.bead_count_; + coord_t start_R = edge.from_->data_.distance_to_boundary_; + coord_t end_R = edge.to_->data_.distance_to_boundary_; + int start_bead_count = edge.from_->data_.bead_count_; + int end_bead_count = edge.to_->data_.bead_count_; if (start_R == end_R) { // No transitions occur when both end points have the same distance_to_boundary - assert(edge.from->data.bead_count_ == edge.to->data.bead_count_); - if (edge.from->data.bead_count_ != edge.to->data.bead_count_) + assert(edge.from_->data_.bead_count_ == edge.to_->data_.bead_count_); + if (edge.from_->data_.bead_count_ != edge.to_->data_.bead_count_) { - spdlog::warn("Bead count {} is different from {} even though distance to boundary is the same.", edge.from->data.bead_count_, edge.to->data.bead_count_); + spdlog::warn("Bead count {} is different from {} even though distance to boundary is the same.", edge.from_->data_.bead_count_, edge.to_->data_.bead_count_); } continue; } @@ -945,7 +945,7 @@ void SkeletalTrapezoidation::generateTransitionMids(ptr_vector_tdata.bead_count_ == edge.to->data.bead_count_) + if (edge.from_->data_.bead_count_ == edge.to_->data_.bead_count_) { // No transitions should occur according to the enforced bead counts continue; } @@ -959,7 +959,7 @@ void SkeletalTrapezoidation::generateTransitionMids(ptr_vector_tp - edge.to->p); + coord_t edge_size = vSize(edge.from_->p_ - edge.to_->p_); for (int transition_lower_bead_count = start_bead_count; transition_lower_bead_count < end_bead_count; transition_lower_bead_count++) { coord_t mid_R = beading_strategy_.getTransitionThickness(transition_lower_bead_count) / 2; @@ -980,18 +980,18 @@ void SkeletalTrapezoidation::generateTransitionMids(ptr_vector_t= transitions->back().pos_); - if (! edge.data.hasTransitions(ignore_empty)) + assert((! edge.data_.hasTransitions(ignore_empty)) || mid_pos >= transitions->back().pos_); + if (! edge.data_.hasTransitions(ignore_empty)) { edge_transitions.emplace_back(std::make_shared>()); - edge.data.setTransitions(edge_transitions.back()); // initialization - transitions = edge.data.getTransitions(); + edge.data_.setTransitions(edge_transitions.back()); // initialization + transitions = edge.data_.getTransitions(); } transitions->emplace_back(mid_pos, transition_lower_bead_count, mid_R); } - assert((edge.from->data.bead_count_ == edge.to->data.bead_count_) || edge.data.hasTransitions()); + assert((edge.from_->data_.bead_count_ == edge.to_->data_.bead_count_) || edge.data_.hasTransitions()); } } @@ -999,18 +999,18 @@ void SkeletalTrapezoidation::filterTransitionMids() { for (edge_t& edge : graph_.edges) { - if (! edge.data.hasTransitions()) + if (! edge.data_.hasTransitions()) { continue; } - auto& transitions = *edge.data.getTransitions(); + auto& transitions = *edge.data_.getTransitions(); // This is how stuff should be stored in transitions assert(transitions.front().lower_bead_count_ <= transitions.back().lower_bead_count_); - assert(edge.from->data.distance_to_boundary_ <= edge.to->data.distance_to_boundary_); + assert(edge.from_->data_.distance_to_boundary_ <= edge.to_->data_.distance_to_boundary_); - const Point a = edge.from->p; - const Point b = edge.to->p; + const Point a = edge.from_->p_; + const Point b = edge.to_->p_; Point ab = b - a; coord_t ab_size = vSize(ab); @@ -1021,7 +1021,7 @@ void SkeletalTrapezoidation::filterTransitionMids() for (TransitionMidRef& ref : to_be_dissolved_back) { dissolveBeadCountRegion(&edge, transitions.back().lower_bead_count_ + 1, transitions.back().lower_bead_count_); - ref.edge_->data.getTransitions()->erase(ref.transition_it_); + ref.edge_->data_.getTransitions()->erase(ref.transition_it_); } { @@ -1040,18 +1040,18 @@ void SkeletalTrapezoidation::filterTransitionMids() } going_up = false; - std::list to_be_dissolved_front = dissolveNearbyTransitions(edge.twin, transitions.front(), transitions.front().pos_, transition_filter_dist_, going_up); + std::list to_be_dissolved_front = dissolveNearbyTransitions(edge.twin_, transitions.front(), transitions.front().pos_, transition_filter_dist_, going_up); bool should_dissolve_front = ! to_be_dissolved_front.empty(); for (TransitionMidRef& ref : to_be_dissolved_front) { - dissolveBeadCountRegion(edge.twin, transitions.front().lower_bead_count_, transitions.front().lower_bead_count_ + 1); - ref.edge_->data.getTransitions()->erase(ref.transition_it_); + dissolveBeadCountRegion(edge.twin_, transitions.front().lower_bead_count_, transitions.front().lower_bead_count_ + 1); + ref.edge_->data_.getTransitions()->erase(ref.transition_it_); } { coord_t trans_bead_count = transitions.front().lower_bead_count_; coord_t lower_transition_half_length = beading_strategy_.getTransitionAnchorPos(trans_bead_count) * beading_strategy_.getTransitioningLength(trans_bead_count); - should_dissolve_front |= filterEndOfCentralTransition(edge.twin, transitions.front().pos_, lower_transition_half_length, trans_bead_count + 1); + should_dissolve_front |= filterEndOfCentralTransition(edge.twin_, transitions.front().pos_, lower_transition_half_length, trans_bead_count + 1); } if (should_dissolve_front) @@ -1074,23 +1074,23 @@ std::list return to_be_dissolved; } bool should_dissolve = true; - for (edge_t* edge = edge_to_start->next; edge && edge != edge_to_start->twin; edge = edge->twin->next) + for (edge_t* edge = edge_to_start->next_; edge && edge != edge_to_start->twin_; edge = edge->twin_->next_) { - if (! edge->data.isCentral()) + if (! edge->data_.isCentral()) { continue; } - Point a = edge->from->p; - Point b = edge->to->p; + Point a = edge->from_->p_; + Point b = edge->to_->p_; Point ab = b - a; coord_t ab_size = vSize(ab); bool is_aligned = edge->isUpward(); - edge_t* aligned_edge = is_aligned ? edge : edge->twin; + edge_t* aligned_edge = is_aligned ? edge : edge->twin_; bool seen_transition_on_this_edge = false; const coord_t origin_radius = origin_transition.feature_radius_; - const coord_t radius_here = edge->from->data.distance_to_boundary_; + const coord_t radius_here = edge->from_->data_.distance_to_boundary_; const bool dissolve_result_is_odd = bool(origin_transition.lower_bead_count_ % 2) == going_up; const coord_t width_deviation = std::abs(origin_radius - radius_here) * 2; // times by two because the deviation happens at both sides of the significant edge const coord_t line_width_deviation = dissolve_result_is_odd @@ -1101,9 +1101,9 @@ std::list should_dissolve = false; } - if (should_dissolve && aligned_edge->data.hasTransitions()) + if (should_dissolve && aligned_edge->data_.hasTransitions()) { - auto& transitions = *aligned_edge->data.getTransitions(); + auto& transitions = *aligned_edge->data_.getTransitions(); for (auto transition_it = transitions.begin(); transition_it != transitions.end(); ++transition_it) { // Note: this is not necessarily iterating in the traveling direction! // Check whether we should dissolve @@ -1146,15 +1146,15 @@ std::list void SkeletalTrapezoidation::dissolveBeadCountRegion(edge_t* edge_to_start, coord_t from_bead_count, coord_t to_bead_count) { assert(from_bead_count != to_bead_count); - if (edge_to_start->to->data.bead_count_ != from_bead_count) + if (edge_to_start->to_->data_.bead_count_ != from_bead_count) { return; } - edge_to_start->to->data.bead_count_ = to_bead_count; - for (edge_t* edge = edge_to_start->next; edge && edge != edge_to_start->twin; edge = edge->twin->next) + edge_to_start->to_->data_.bead_count_ = to_bead_count; + for (edge_t* edge = edge_to_start->next_; edge && edge != edge_to_start->twin_; edge = edge->twin_->next_) { - if (! edge->data.isCentral()) + if (! edge->data_.isCentral()) { continue; } @@ -1171,11 +1171,11 @@ bool SkeletalTrapezoidation::filterEndOfCentralTransition(edge_t* edge_to_start, bool is_end_of_central = true; bool should_dissolve = false; - for (edge_t* next_edge = edge_to_start->next; next_edge && next_edge != edge_to_start->twin; next_edge = next_edge->twin->next) + for (edge_t* next_edge = edge_to_start->next_; next_edge && next_edge != edge_to_start->twin_; next_edge = next_edge->twin_->next_) { - if (next_edge->data.isCentral()) + if (next_edge->data_.isCentral()) { - coord_t length = vSize(next_edge->to->p - next_edge->from->p); + coord_t length = vSize(next_edge->to_->p_ - next_edge->from_->p_); should_dissolve |= filterEndOfCentralTransition(next_edge, traveled_dist + length, max_dist, replacing_bead_count); is_end_of_central = false; } @@ -1187,7 +1187,7 @@ bool SkeletalTrapezoidation::filterEndOfCentralTransition(edge_t* edge_to_start, if (should_dissolve) { - edge_to_start->to->data.bead_count_ = replacing_bead_count; + edge_to_start->to_->data_.bead_count_ = replacing_bead_count; } return should_dissolve; } @@ -1196,13 +1196,13 @@ void SkeletalTrapezoidation::generateAllTransitionEnds(ptr_vector_tdata.distance_to_boundary_ <= edge.to->data.distance_to_boundary_); + assert(edge.from_->data_.distance_to_boundary_ <= edge.to_->data_.distance_to_boundary_); for (TransitionMiddle& transition_middle : transition_positions) { assert(transition_positions.front().pos_ <= transition_middle.pos_); @@ -1214,8 +1214,8 @@ void SkeletalTrapezoidation::generateAllTransitionEnds(ptr_vector_t>& edge_transition_ends) { - const Point a = edge.from->p; - const Point b = edge.to->p; + const Point a = edge.from_->p_; + const Point b = edge.to_->p_; const Point ab = b - a; const coord_t ab_size = vSize(ab); @@ -1231,7 +1231,7 @@ void SkeletalTrapezoidation::generateTransitionEnds(edge_t& edge, coord_t mid_po const coord_t start_pos = ab_size - mid_pos; const coord_t transition_half_length = transition_mid_position * transition_length; const coord_t end_pos = start_pos + transition_half_length; - generateTransitionEnd(*edge.twin, start_pos, end_pos, transition_half_length, mid_rest, start_rest, lower_bead_count, edge_transition_ends); + generateTransitionEnd(*edge.twin_, start_pos, end_pos, transition_half_length, mid_rest, start_rest, lower_bead_count, edge_transition_ends); } { // Upper bead count transition end @@ -1259,8 +1259,8 @@ bool SkeletalTrapezoidation::generateTransitionEnd( coord_t lower_bead_count, ptr_vector_t>& edge_transition_ends) { - Point a = edge.from->p; - Point b = edge.to->p; + Point a = edge.from_->p_; + Point b = edge.to_->p_; Point ab = b - a; coord_t ab_size = vSize(ab); // TODO: prevent recalculation of these values @@ -1272,8 +1272,8 @@ bool SkeletalTrapezoidation::generateTransitionEnd( bool going_up = end_rest > start_rest; - assert(edge.data.isCentral()); - if (! edge.data.isCentral()) + assert(edge.data_.isCentral()); + if (! edge.data_.isCentral()) { spdlog::warn("This function shouldn't generate ends in or beyond non-central regions."); return false; @@ -1287,19 +1287,19 @@ bool SkeletalTrapezoidation::generateTransitionEnd( assert(rest >= std::min(end_rest, start_rest)); coord_t central_edge_count = 0; - for (edge_t* outgoing = edge.next; outgoing && outgoing != edge.twin; outgoing = outgoing->twin->next) + for (edge_t* outgoing = edge.next_; outgoing && outgoing != edge.twin_; outgoing = outgoing->twin_->next_) { - if (! outgoing->data.isCentral()) + if (! outgoing->data_.isCentral()) continue; central_edge_count++; } bool is_only_going_down = true; bool has_recursed = false; - for (edge_t* outgoing = edge.next; outgoing && outgoing != edge.twin;) + for (edge_t* outgoing = edge.next_; outgoing && outgoing != edge.twin_;) { - edge_t* next = outgoing->twin->next; // Before we change the outgoing edge itself - if (! outgoing->data.isCentral()) + edge_t* next = outgoing->twin_->next_; // Before we change the outgoing edge itself + if (! outgoing->data_.isCentral()) { outgoing = next; continue; // Don't put transition ends in non-central regions @@ -1318,8 +1318,8 @@ bool SkeletalTrapezoidation::generateTransitionEnd( } if (! going_up || (has_recursed && ! is_only_going_down)) { - edge.to->data.transition_ratio_ = rest; - edge.to->data.bead_count_ = lower_bead_count; + edge.to_->data_.transition_ratio_ = rest; + edge.to_->data_.bead_count_ = lower_bead_count; } return is_only_going_down; } @@ -1336,20 +1336,20 @@ bool SkeletalTrapezoidation::generateTransitionEnd( } else { - upward_edge = edge.twin; + upward_edge = edge.twin_; pos = ab_size - end_pos; } - if (! upward_edge->data.hasTransitionEnds()) + if (! upward_edge->data_.hasTransitionEnds()) { // This edge doesn't have a data structure yet for the transition ends. Make one. edge_transition_ends.emplace_back(std::make_shared>()); - upward_edge->data.setTransitionEnds(edge_transition_ends.back()); + upward_edge->data_.setTransitionEnds(edge_transition_ends.back()); } - auto transitions = upward_edge->data.getTransitionEnds(); + auto transitions = upward_edge->data_.getTransitionEnds(); // Add a transition to it (on the correct side). - assert(ab_size == vSize(edge.twin->from->p - edge.twin->to->p)); + assert(ab_size == vSize(edge.twin_->from_->p_ - edge.twin_->to_->p_)); assert(pos <= ab_size); if (transitions->empty() || pos < transitions->front().pos_) { // Preorder so that sorting later on is faster @@ -1368,25 +1368,25 @@ bool SkeletalTrapezoidation::isGoingDown(edge_t* outgoing, coord_t traveled_dist { // NOTE: the logic below is not fully thought through. // TODO: take transition mids into account - if (outgoing->to->data.distance_to_boundary_ == 0) + if (outgoing->to_->data_.distance_to_boundary_ == 0) { return true; } - bool is_upward = outgoing->to->data.distance_to_boundary_ >= outgoing->from->data.distance_to_boundary_; - edge_t* upward_edge = is_upward ? outgoing : outgoing->twin; - if (outgoing->to->data.bead_count_ > lower_bead_count + 1) + bool is_upward = outgoing->to_->data_.distance_to_boundary_ >= outgoing->from_->data_.distance_to_boundary_; + edge_t* upward_edge = is_upward ? outgoing : outgoing->twin_; + if (outgoing->to_->data_.bead_count_ > lower_bead_count + 1) { - assert(upward_edge->data.hasTransitions() && "If the bead count is going down there has to be a transition mid!"); - if (! upward_edge->data.hasTransitions()) + assert(upward_edge->data_.hasTransitions() && "If the bead count is going down there has to be a transition mid!"); + if (! upward_edge->data_.hasTransitions()) { spdlog::warn("If the bead count is going down there has to be a transition mid!"); } return false; } - coord_t length = vSize(outgoing->to->p - outgoing->from->p); - if (upward_edge->data.hasTransitions()) + coord_t length = vSize(outgoing->to_->p_ - outgoing->from_->p_); + if (upward_edge->data_.hasTransitions()) { - auto& transition_mids = *upward_edge->data.getTransitions(); + auto& transition_mids = *upward_edge->data_.getTransitions(); TransitionMiddle& mid = is_upward ? transition_mids.front() : transition_mids.back(); if (mid.lower_bead_count_ == lower_bead_count && ((is_upward && mid.pos_ + traveled_dist < max_dist) || (! is_upward && length - mid.pos_ + traveled_dist < max_dist))) { @@ -1397,16 +1397,16 @@ bool SkeletalTrapezoidation::isGoingDown(edge_t* outgoing, coord_t traveled_dist { return false; } - if (outgoing->to->data.bead_count_ <= lower_bead_count && ! (outgoing->to->data.bead_count_ == lower_bead_count && outgoing->to->data.transition_ratio_ > 0.0)) + if (outgoing->to_->data_.bead_count_ <= lower_bead_count && ! (outgoing->to_->data_.bead_count_ == lower_bead_count && outgoing->to_->data_.transition_ratio_ > 0.0)) { return true; } bool is_only_going_down = true; bool has_recursed = false; - for (edge_t* next = outgoing->next; next && next != outgoing->twin; next = next->twin->next) + for (edge_t* next = outgoing->next_; next && next != outgoing->twin_; next = next->twin_->next_) { - if (! next->data.isCentral()) + if (! next->data_.isCentral()) { continue; } @@ -1421,16 +1421,16 @@ void SkeletalTrapezoidation::applyTransitions(ptr_vector_tdata.hasTransitionEnds()) + if (edge.twin_->data_.hasTransitionEnds()) { - coord_t length = vSize(edge.from->p - edge.to->p); - auto& twin_transition_ends = *edge.twin->data.getTransitionEnds(); - if (! edge.data.hasTransitionEnds()) + coord_t length = vSize(edge.from_->p_ - edge.to_->p_); + auto& twin_transition_ends = *edge.twin_->data_.getTransitionEnds(); + if (! edge.data_.hasTransitionEnds()) { edge_transition_ends.emplace_back(std::make_shared>()); - edge.data.setTransitionEnds(edge_transition_ends.back()); + edge.data_.setTransitionEnds(edge_transition_ends.back()); } - auto& transition_ends = *edge.data.getTransitionEnds(); + auto& transition_ends = *edge.data_.getTransitionEnds(); for (TransitionEnd& end : twin_transition_ends) { transition_ends.emplace_back(length - end.pos_, end.lower_bead_count_, end.is_lower_end_); @@ -1441,24 +1441,24 @@ void SkeletalTrapezoidation::applyTransitions(ptr_vector_tp; - Point b = to->p; + node_t* from = edge.from_; + node_t* to = edge.to_; + Point a = from->p_; + Point b = to->p_; Point ab = b - a; coord_t ab_size = vSize(ab); @@ -1468,40 +1468,40 @@ void SkeletalTrapezoidation::applyTransitions(ptr_vector_t ab_size - snap_dist_) && close_node->data.bead_count_ == new_node_bead_count) + if ((end_pos < snap_dist_ || end_pos > ab_size - snap_dist_) && close_node->data_.bead_count_ == new_node_bead_count) { assert(end_pos <= ab_size); - close_node->data.transition_ratio_ = 0; + close_node->data_.transition_ratio_ = 0; continue; } Point mid = a + normal(ab, end_pos); - assert(last_edge_replacing_input->data.isCentral()); - assert(last_edge_replacing_input->data.type_ != SkeletalTrapezoidationEdge::EdgeType::EXTRA_VD); + assert(last_edge_replacing_input->data_.isCentral()); + assert(last_edge_replacing_input->data_.type_ != SkeletalTrapezoidationEdge::EdgeType::EXTRA_VD); last_edge_replacing_input = graph_.insertNode(last_edge_replacing_input, mid, new_node_bead_count); - assert(last_edge_replacing_input->data.type_ != SkeletalTrapezoidationEdge::EdgeType::EXTRA_VD); - assert(last_edge_replacing_input->data.isCentral()); + assert(last_edge_replacing_input->data_.type_ != SkeletalTrapezoidationEdge::EdgeType::EXTRA_VD); + assert(last_edge_replacing_input->data_.isCentral()); } } } bool SkeletalTrapezoidation::isEndOfCentral(const edge_t& edge_to) const { - if (! edge_to.data.isCentral()) + if (! edge_to.data_.isCentral()) { return false; } - if (! edge_to.next) + if (! edge_to.next_) { return true; } - for (const edge_t* edge = edge_to.next; edge && edge != edge_to.twin; edge = edge->twin->next) + for (const edge_t* edge = edge_to.next_; edge && edge != edge_to.twin_; edge = edge->twin_->next_) { - if (edge->data.isCentral()) + if (edge->data_.isCentral()) { return false; } - assert(edge->twin); + assert(edge->twin_); } return true; } @@ -1512,13 +1512,13 @@ void SkeletalTrapezoidation::generateExtraRibs() // The code was equivalent to a full loop over all the edges though, unless there was one edge or less, in which case it would produce undefined behaviour. for (auto& edge : graph_.edges) { - if (! edge.data.isCentral() || shorterThen(edge.to->p - edge.from->p, discretization_step_size_) - || edge.from->data.distance_to_boundary_ >= edge.to->data.distance_to_boundary_) + if (! edge.data_.isCentral() || shorterThen(edge.to_->p_ - edge.from_->p_, discretization_step_size_) + || edge.from_->data_.distance_to_boundary_ >= edge.to_->data_.distance_to_boundary_) { continue; } - std::vector rib_thicknesses = beading_strategy_.getNonlinearThicknesses(edge.from->data.bead_count_); + std::vector rib_thicknesses = beading_strategy_.getNonlinearThicknesses(edge.from_->data_.bead_count_); if (rib_thicknesses.empty()) { @@ -1526,14 +1526,14 @@ void SkeletalTrapezoidation::generateExtraRibs() } // Preload some variables before [edge] gets changed - node_t* from = edge.from; - node_t* to = edge.to; - Point a = from->p; - Point b = to->p; + node_t* from = edge.from_; + node_t* to = edge.to_; + Point a = from->p_; + Point b = to->p_; Point ab = b - a; coord_t ab_size = vSize(ab); - coord_t a_R = edge.from->data.distance_to_boundary_; - coord_t b_R = edge.to->data.distance_to_boundary_; + coord_t a_R = edge.from_->data_.distance_to_boundary_; + coord_t b_R = edge.to_->data_.distance_to_boundary_; edge_t* last_edge_replacing_input = &edge; for (coord_t rib_thickness : rib_thicknesses) @@ -1547,24 +1547,24 @@ void SkeletalTrapezoidation::generateExtraRibs() break; } - coord_t new_node_bead_count = std::min(edge.from->data.bead_count_, edge.to->data.bead_count_); + coord_t new_node_bead_count = std::min(edge.from_->data_.bead_count_, edge.to_->data_.bead_count_); coord_t end_pos = ab_size * (rib_thickness / 2 - a_R) / (b_R - a_R); assert(end_pos > 0); assert(end_pos < ab_size); node_t* close_node = (end_pos < ab_size / 2) ? from : to; - if ((end_pos < snap_dist_ || end_pos > ab_size - snap_dist_) && close_node->data.bead_count_ == new_node_bead_count) + if ((end_pos < snap_dist_ || end_pos > ab_size - snap_dist_) && close_node->data_.bead_count_ == new_node_bead_count) { assert(end_pos <= ab_size); - close_node->data.transition_ratio_ = 0; + close_node->data_.transition_ratio_ = 0; continue; } Point mid = a + normal(ab, end_pos); - assert(last_edge_replacing_input->data.isCentral()); - assert(last_edge_replacing_input->data.type_ != SkeletalTrapezoidationEdge::EdgeType::EXTRA_VD); + assert(last_edge_replacing_input->data_.isCentral()); + assert(last_edge_replacing_input->data_.type_ != SkeletalTrapezoidationEdge::EdgeType::EXTRA_VD); last_edge_replacing_input = graph_.insertNode(last_edge_replacing_input, mid, new_node_bead_count); - assert(last_edge_replacing_input->data.type_ != SkeletalTrapezoidationEdge::EdgeType::EXTRA_VD); - assert(last_edge_replacing_input->data.isCentral()); + assert(last_edge_replacing_input->data_.type_ != SkeletalTrapezoidationEdge::EdgeType::EXTRA_VD); + assert(last_edge_replacing_input->data_.isCentral()); } } } @@ -1582,7 +1582,7 @@ void SkeletalTrapezoidation::generateSegments() std::vector upward_quad_mids; for (edge_t& edge : graph_.edges) { - if (edge.prev && edge.next && edge.isUpward()) + if (edge.prev_ && edge.next_ && edge.isUpward()) { upward_quad_mids.emplace_back(&edge); } @@ -1593,20 +1593,20 @@ void SkeletalTrapezoidation::generateSegments() upward_quad_mids.end(), [this](edge_t* a, edge_t* b) { - if (a->to->data.distance_to_boundary_ == b->to->data.distance_to_boundary_) + if (a->to_->data_.distance_to_boundary_ == b->to_->data_.distance_to_boundary_) { // PathOrdering between two 'upward' edges of the same distance is important when one of the edges is flat and connected to the other - if (a->from->data.distance_to_boundary_ == a->to->data.distance_to_boundary_ && b->from->data.distance_to_boundary_ == b->to->data.distance_to_boundary_) + if (a->from_->data_.distance_to_boundary_ == a->to_->data_.distance_to_boundary_ && b->from_->data_.distance_to_boundary_ == b->to_->data_.distance_to_boundary_) { coord_t max = std::numeric_limits::max(); - coord_t a_dist_from_up = std::min(a->distToGoUp().value_or(max), a->twin->distToGoUp().value_or(max)) - vSize(a->to->p - a->from->p); - coord_t b_dist_from_up = std::min(b->distToGoUp().value_or(max), b->twin->distToGoUp().value_or(max)) - vSize(b->to->p - b->from->p); + coord_t a_dist_from_up = std::min(a->distToGoUp().value_or(max), a->twin_->distToGoUp().value_or(max)) - vSize(a->to_->p_ - a->from_->p_); + coord_t b_dist_from_up = std::min(b->distToGoUp().value_or(max), b->twin_->distToGoUp().value_or(max)) - vSize(b->to_->p_ - b->from_->p_); return a_dist_from_up < b_dist_from_up; } - else if (a->from->data.distance_to_boundary_ == a->to->data.distance_to_boundary_) + else if (a->from_->data_.distance_to_boundary_ == a->to_->data_.distance_to_boundary_) { return true; // Edge a might be 'above' edge b } - else if (b->from->data.distance_to_boundary_ == b->to->data.distance_to_boundary_) + else if (b->from_->data_.distance_to_boundary_ == b->to_->data_.distance_to_boundary_) { return false; // Edge b might be 'above' edge a } @@ -1615,36 +1615,36 @@ void SkeletalTrapezoidation::generateSegments() // PathOrdering is not important } } - return a->to->data.distance_to_boundary_ > b->to->data.distance_to_boundary_; + return a->to_->data_.distance_to_boundary_ > b->to_->data_.distance_to_boundary_; }); ptr_vector_t node_beadings; { // Store beading for (node_t& node : graph_.nodes) { - if (node.data.bead_count_ <= 0) + if (node.data_.bead_count_ <= 0) { continue; } - if (node.data.transition_ratio_ == 0) + if (node.data_.transition_ratio_ == 0) { - node_beadings.emplace_back(new BeadingPropagation(beading_strategy_.compute(node.data.distance_to_boundary_ * 2, node.data.bead_count_))); - node.data.setBeading(node_beadings.back()); - assert(node_beadings.back()->beading_.total_thickness == node.data.distance_to_boundary_ * 2); - if (node_beadings.back()->beading_.total_thickness != node.data.distance_to_boundary_ * 2) + node_beadings.emplace_back(new BeadingPropagation(beading_strategy_.compute(node.data_.distance_to_boundary_ * 2, node.data_.bead_count_))); + node.data_.setBeading(node_beadings.back()); + assert(node_beadings.back()->beading_.total_thickness == node.data_.distance_to_boundary_ * 2); + if (node_beadings.back()->beading_.total_thickness != node.data_.distance_to_boundary_ * 2) { spdlog::warn("If transitioning to an endpoint (ratio 0), the node should be exactly in the middle."); } } else { - Beading low_count_beading = beading_strategy_.compute(node.data.distance_to_boundary_ * 2, node.data.bead_count_); - Beading high_count_beading = beading_strategy_.compute(node.data.distance_to_boundary_ * 2, node.data.bead_count_ + 1); - Beading merged = interpolate(low_count_beading, 1.0 - node.data.transition_ratio_, high_count_beading); + Beading low_count_beading = beading_strategy_.compute(node.data_.distance_to_boundary_ * 2, node.data_.bead_count_); + Beading high_count_beading = beading_strategy_.compute(node.data_.distance_to_boundary_ * 2, node.data_.bead_count_ + 1); + Beading merged = interpolate(low_count_beading, 1.0 - node.data_.transition_ratio_, high_count_beading); node_beadings.emplace_back(new BeadingPropagation(merged)); - node.data.setBeading(node_beadings.back()); - assert(merged.total_thickness == node.data.distance_to_boundary_ * 2); - if (merged.total_thickness != node.data.distance_to_boundary_ * 2) + node.data_.setBeading(node_beadings.back()); + assert(merged.total_thickness == node.data_.distance_to_boundary_ * 2); + if (merged.total_thickness != node.data_.distance_to_boundary_ * 2) { spdlog::warn("If merging two beads, the new bead must be exactly in the middle."); } @@ -1666,25 +1666,25 @@ void SkeletalTrapezoidation::generateSegments() SkeletalTrapezoidation::edge_t* SkeletalTrapezoidation::getQuadMaxRedgeTo(edge_t* quad_start_edge) { - assert(quad_start_edge->prev == nullptr); - assert(quad_start_edge->from->data.distance_to_boundary_ == 0); + assert(quad_start_edge->prev_ == nullptr); + assert(quad_start_edge->from_->data_.distance_to_boundary_ == 0); coord_t max_R = -1; edge_t* ret = nullptr; - for (edge_t* edge = quad_start_edge; edge; edge = edge->next) + for (edge_t* edge = quad_start_edge; edge; edge = edge->next_) { - coord_t r = edge->to->data.distance_to_boundary_; + coord_t r = edge->to_->data_.distance_to_boundary_; if (r > max_R) { max_R = r; ret = edge; } } - if (! ret->next && ret->to->data.distance_to_boundary_ - 5 < ret->from->data.distance_to_boundary_) + if (! ret->next_ && ret->to_->data_.distance_to_boundary_ - 5 < ret->from_->data_.distance_to_boundary_) { - ret = ret->prev; + ret = ret->prev_; } assert(ret); - assert(ret->next); + assert(ret->next_); return ret; } @@ -1693,30 +1693,30 @@ void SkeletalTrapezoidation::propagateBeadingsUpward(std::vector& upwar for (auto upward_quad_mids_it = upward_quad_mids.rbegin(); upward_quad_mids_it != upward_quad_mids.rend(); ++upward_quad_mids_it) { edge_t* upward_edge = *upward_quad_mids_it; - if (upward_edge->to->data.bead_count_ >= 0) + if (upward_edge->to_->data_.bead_count_ >= 0) { // Don't override local beading continue; } - if (! upward_edge->from->data.hasBeading()) + if (! upward_edge->from_->data_.hasBeading()) { // Only propagate if we have something to propagate continue; } - BeadingPropagation& lower_beading = *upward_edge->from->data.getBeading(); - if (upward_edge->to->data.hasBeading()) + BeadingPropagation& lower_beading = *upward_edge->from_->data_.getBeading(); + if (upward_edge->to_->data_.hasBeading()) { // Only propagate to places where there is place continue; } assert( - (upward_edge->from->data.distance_to_boundary_ != upward_edge->to->data.distance_to_boundary_ - || shorterThen(upward_edge->to->p - upward_edge->from->p, central_filter_dist_)) + (upward_edge->from_->data_.distance_to_boundary_ != upward_edge->to_->data_.distance_to_boundary_ + || shorterThen(upward_edge->to_->p_ - upward_edge->from_->p_, central_filter_dist_)) && "zero difference R edges should always be central"); - coord_t length = vSize(upward_edge->to->p - upward_edge->from->p); + coord_t length = vSize(upward_edge->to_->p_ - upward_edge->from_->p_); BeadingPropagation upper_beading = lower_beading; upper_beading.dist_to_bottom_source_ += length; upper_beading.is_upward_propagated_only_ = true; node_beadings.emplace_back(new BeadingPropagation(upper_beading)); - upward_edge->to->data.setBeading(node_beadings.back()); - assert(upper_beading.beading_.total_thickness <= upward_edge->to->data.distance_to_boundary_ * 2); + upward_edge->to_->data_.setBeading(node_beadings.back()); + assert(upper_beading.beading_.total_thickness <= upward_edge->to_->data_.distance_to_boundary_ * 2); } } @@ -1725,13 +1725,13 @@ void SkeletalTrapezoidation::propagateBeadingsDownward(std::vector& upw for (edge_t* upward_quad_mid : upward_quad_mids) { // Transfer beading information to lower nodes - if (! upward_quad_mid->data.isCentral()) + if (! upward_quad_mid->data_.isCentral()) { // for equidistant edge: propagate from known beading to node with unknown beading - if (upward_quad_mid->from->data.distance_to_boundary_ == upward_quad_mid->to->data.distance_to_boundary_ && upward_quad_mid->from->data.hasBeading() - && ! upward_quad_mid->to->data.hasBeading()) + if (upward_quad_mid->from_->data_.distance_to_boundary_ == upward_quad_mid->to_->data_.distance_to_boundary_ && upward_quad_mid->from_->data_.hasBeading() + && ! upward_quad_mid->to_->data_.hasBeading()) { - propagateBeadingsDownward(upward_quad_mid->twin, node_beadings); + propagateBeadingsDownward(upward_quad_mid->twin_, node_beadings); } else { @@ -1743,30 +1743,30 @@ void SkeletalTrapezoidation::propagateBeadingsDownward(std::vector& upw void SkeletalTrapezoidation::propagateBeadingsDownward(edge_t* edge_to_peak, ptr_vector_t& node_beadings) { - coord_t length = vSize(edge_to_peak->to->p - edge_to_peak->from->p); - BeadingPropagation& top_beading = *getOrCreateBeading(edge_to_peak->to, node_beadings); - assert(top_beading.beading_.total_thickness >= edge_to_peak->to->data.distance_to_boundary_ * 2); - if (top_beading.beading_.total_thickness < edge_to_peak->to->data.distance_to_boundary_ * 2) + coord_t length = vSize(edge_to_peak->to_->p_ - edge_to_peak->from_->p_); + BeadingPropagation& top_beading = *getOrCreateBeading(edge_to_peak->to_, node_beadings); + assert(top_beading.beading_.total_thickness >= edge_to_peak->to_->data_.distance_to_boundary_ * 2); + if (top_beading.beading_.total_thickness < edge_to_peak->to_->data_.distance_to_boundary_ * 2) { spdlog::warn("Top bead is beyond the center of the total width."); } assert(! top_beading.is_upward_propagated_only_); - if (! edge_to_peak->from->data.hasBeading()) + if (! edge_to_peak->from_->data_.hasBeading()) { // Set new beading if there is no beading associated with the node yet BeadingPropagation propagated_beading = top_beading; propagated_beading.dist_from_top_source_ += length; node_beadings.emplace_back(new BeadingPropagation(propagated_beading)); - edge_to_peak->from->data.setBeading(node_beadings.back()); - assert(propagated_beading.beading_.total_thickness >= edge_to_peak->from->data.distance_to_boundary_ * 2); - if (propagated_beading.beading_.total_thickness < edge_to_peak->from->data.distance_to_boundary_ * 2) + edge_to_peak->from_->data_.setBeading(node_beadings.back()); + assert(propagated_beading.beading_.total_thickness >= edge_to_peak->from_->data_.distance_to_boundary_ * 2); + if (propagated_beading.beading_.total_thickness < edge_to_peak->from_->data_.distance_to_boundary_ * 2) { spdlog::warn("Propagated bead is beyond the center of the total width."); } } else { - BeadingPropagation& bottom_beading = *edge_to_peak->from->data.getBeading(); + BeadingPropagation& bottom_beading = *edge_to_peak->from_->data_.getBeading(); coord_t total_dist = top_beading.dist_from_top_source_ + length + bottom_beading.dist_to_bottom_source_; Ratio ratio_of_top = static_cast(bottom_beading.dist_to_bottom_source_) / std::min(total_dist, beading_propagation_transition_dist_); ratio_of_top = std::max(0.0_r, ratio_of_top); @@ -1777,11 +1777,11 @@ void SkeletalTrapezoidation::propagateBeadingsDownward(edge_t* edge_to_peak, ptr } else { - Beading merged_beading = interpolate(top_beading.beading_, ratio_of_top, bottom_beading.beading_, edge_to_peak->from->data.distance_to_boundary_); + Beading merged_beading = interpolate(top_beading.beading_, ratio_of_top, bottom_beading.beading_, edge_to_peak->from_->data_.distance_to_boundary_); bottom_beading = BeadingPropagation(merged_beading); bottom_beading.is_upward_propagated_only_ = false; - assert(merged_beading.total_thickness >= edge_to_peak->from->data.distance_to_boundary_ * 2); - if (merged_beading.total_thickness < edge_to_peak->from->data.distance_to_boundary_ * 2) + assert(merged_beading.total_thickness >= edge_to_peak->from_->data_.distance_to_boundary_ * 2); + if (merged_beading.total_thickness < edge_to_peak->from_->data_.distance_to_boundary_ * 2) { spdlog::warn("Merged bead is beyond the center of the total width."); } @@ -1860,32 +1860,32 @@ void SkeletalTrapezoidation::generateJunctions(ptr_vector_t& for (edge_t& edge_ : graph_.edges) { edge_t* edge = &edge_; - if (edge->from->data.distance_to_boundary_ > edge->to->data.distance_to_boundary_) + if (edge->from_->data_.distance_to_boundary_ > edge->to_->data_.distance_to_boundary_) { // Only consider the upward half-edges continue; } - coord_t start_R = edge->to->data.distance_to_boundary_; // higher R - coord_t end_R = edge->from->data.distance_to_boundary_; // lower R + coord_t start_R = edge->to_->data_.distance_to_boundary_; // higher R + coord_t end_R = edge->from_->data_.distance_to_boundary_; // lower R - if ((edge->from->data.bead_count_ == edge->to->data.bead_count_ && edge->from->data.bead_count_ >= 0) || end_R >= start_R) + if ((edge->from_->data_.bead_count_ == edge->to_->data_.bead_count_ && edge->from_->data_.bead_count_ >= 0) || end_R >= start_R) { // No beads to generate continue; } - Beading* beading = &getOrCreateBeading(edge->to, node_beadings)->beading_; + Beading* beading = &getOrCreateBeading(edge->to_, node_beadings)->beading_; edge_junctions.emplace_back(std::make_shared()); - edge_.data.setExtrusionJunctions(edge_junctions.back()); // initialization + edge_.data_.setExtrusionJunctions(edge_junctions.back()); // initialization LineJunctions& ret = *edge_junctions.back(); - assert(beading->total_thickness >= edge->to->data.distance_to_boundary_ * 2); - if (beading->total_thickness < edge->to->data.distance_to_boundary_ * 2) + assert(beading->total_thickness >= edge->to_->data_.distance_to_boundary_ * 2); + if (beading->total_thickness < edge->to_->data_.distance_to_boundary_ * 2) { spdlog::warn("Generated junction is beyond the center of total width."); } - Point a = edge->to->p; - Point b = edge->from->p; + Point a = edge->to_->p_; + Point b = edge->from_->p_; Point ab = b - a; const size_t num_junctions = beading->toolpath_locations.size(); @@ -1928,9 +1928,9 @@ void SkeletalTrapezoidation::generateJunctions(ptr_vector_t& std::shared_ptr SkeletalTrapezoidation::getOrCreateBeading(node_t* node, ptr_vector_t& node_beadings) { - if (! node->data.hasBeading()) + if (! node->data_.hasBeading()) { - if (node->data.bead_count_ == -1) + if (node->data_.bead_count_ == -1) { // This bug is due to too small central edges constexpr coord_t nearby_dist = 100; // TODO auto nearest_beading = getNearestBeading(node, nearby_dist); @@ -1943,14 +1943,14 @@ std::shared_ptr SkeletalTrapezo bool has_central_edge = false; bool first = true; coord_t dist = std::numeric_limits::max(); - for (edge_t* edge = node->incident_edge; edge && (first || edge != node->incident_edge); edge = edge->twin->next) + for (edge_t* edge = node->incident_edge_; edge && (first || edge != node->incident_edge_); edge = edge->twin_->next_) { - if (edge->data.isCentral()) + if (edge->data_.isCentral()) { has_central_edge = true; } - assert(edge->to->data.distance_to_boundary_ >= 0); - dist = std::min(dist, edge->to->data.distance_to_boundary_ + vSize(edge->to->p - edge->from->p)); + assert(edge->to_->data_.distance_to_boundary_ >= 0); + dist = std::min(dist, edge->to_->data_.distance_to_boundary_ + vSize(edge->to_->p_ - edge->from_->p_)); first = false; } if (! has_central_edge) @@ -1958,38 +1958,39 @@ std::shared_ptr SkeletalTrapezo spdlog::error("Unknown beading for non-central node!"); } assert(dist != std::numeric_limits::max()); - node->data.bead_count_ = beading_strategy_.getOptimalBeadCount(dist * 2); + node->data_.bead_count_ = beading_strategy_.getOptimalBeadCount(dist * 2); } - assert(node->data.bead_count_ != -1); - node_beadings.emplace_back(new BeadingPropagation(beading_strategy_.compute(node->data.distance_to_boundary_ * 2, node->data.bead_count_))); - node->data.setBeading(node_beadings.back()); + assert(node->data_.bead_count_ != -1); + node_beadings.emplace_back(new BeadingPropagation(beading_strategy_.compute(node->data_.distance_to_boundary_ * 2, node->data_.bead_count_))); + node->data_.setBeading(node_beadings.back()); } - assert(node->data.hasBeading()); - return node->data.getBeading(); + assert(node->data_.hasBeading()); + return node->data_.getBeading(); } std::shared_ptr SkeletalTrapezoidation::getNearestBeading(node_t* node, coord_t max_dist) { struct DistEdge { - edge_t* edge_to; - coord_t dist; + edge_t* edge_to_; + coord_t dist_; + DistEdge(edge_t* edge_to, coord_t dist) - : edge_to(edge_to) - , dist(dist) + : edge_to_(edge_to) + , dist_(dist) { } }; auto compare = [](const DistEdge& l, const DistEdge& r) -> bool { - return l.dist > r.dist; + return l.dist_ > r.dist_; }; std::priority_queue, decltype(compare)> further_edges(compare); bool first = true; - for (edge_t* outgoing = node->incident_edge; outgoing && (first || outgoing != node->incident_edge); outgoing = outgoing->twin->next) + for (edge_t* outgoing = node->incident_edge_; outgoing && (first || outgoing != node->incident_edge_); outgoing = outgoing->twin_->next_) { - further_edges.emplace(outgoing, vSize(outgoing->to->p - outgoing->from->p)); + further_edges.emplace(outgoing, vSize(outgoing->to_->p_ - outgoing->from_->p_)); first = false; } @@ -1999,17 +2000,17 @@ std::shared_ptr SkeletalTrapezo return nullptr; DistEdge here = further_edges.top(); further_edges.pop(); - if (here.dist > max_dist) + if (here.dist_ > max_dist) return nullptr; - if (here.edge_to->to->data.hasBeading()) + if (here.edge_to_->to_->data_.hasBeading()) { - return here.edge_to->to->data.getBeading(); + return here.edge_to_->to_->data_.getBeading(); } else { // recurse - for (edge_t* further_edge = here.edge_to->next; further_edge && further_edge != here.edge_to->twin; further_edge = further_edge->twin->next) + for (edge_t* further_edge = here.edge_to_->next_; further_edge && further_edge != here.edge_to_->twin_; further_edge = further_edge->twin_->next_) { - further_edges.emplace(further_edge, here.dist + vSize(further_edge->to->p - further_edge->from->p)); + further_edges.emplace(further_edge, here.dist_ + vSize(further_edge->to_->p_ - further_edge->from_->p_)); } } } @@ -2065,7 +2066,7 @@ void SkeletalTrapezoidation::connectJunctions(ptr_vector_t& edge_ std::unordered_set unprocessed_quad_starts(graph_.edges.size() * 5 / 2); for (edge_t& edge : graph_.edges) { - if (! edge.prev) + if (! edge.prev_) { unprocessed_quad_starts.insert(&edge); } @@ -2081,58 +2082,58 @@ void SkeletalTrapezoidation::connectJunctions(ptr_vector_t& edge_ do { edge_t* quad_end = quad_start; - while (quad_end->next) + while (quad_end->next_) { - quad_end = quad_end->next; + quad_end = quad_end->next_; } edge_t* edge_to_peak = getQuadMaxRedgeTo(quad_start); // walk down on both sides and connect junctions - edge_t* edge_from_peak = edge_to_peak->next; + edge_t* edge_from_peak = edge_to_peak->next_; assert(edge_from_peak); unprocessed_quad_starts.erase(quad_start); - if (! edge_to_peak->data.hasExtrusionJunctions()) + if (! edge_to_peak->data_.hasExtrusionJunctions()) { edge_junctions.emplace_back(std::make_shared()); - edge_to_peak->data.setExtrusionJunctions(edge_junctions.back()); + edge_to_peak->data_.setExtrusionJunctions(edge_junctions.back()); } // The junctions on the edge(s) from the start of the quad to the node with highest R - LineJunctions from_junctions = *edge_to_peak->data.getExtrusionJunctions(); - if (! edge_from_peak->twin->data.hasExtrusionJunctions()) + LineJunctions from_junctions = *edge_to_peak->data_.getExtrusionJunctions(); + if (! edge_from_peak->twin_->data_.hasExtrusionJunctions()) { edge_junctions.emplace_back(std::make_shared()); - edge_from_peak->twin->data.setExtrusionJunctions(edge_junctions.back()); + edge_from_peak->twin_->data_.setExtrusionJunctions(edge_junctions.back()); } // The junctions on the edge(s) from the end of the quad to the node with highest R - LineJunctions to_junctions = *edge_from_peak->twin->data.getExtrusionJunctions(); - if (edge_to_peak->prev) + LineJunctions to_junctions = *edge_from_peak->twin_->data_.getExtrusionJunctions(); + if (edge_to_peak->prev_) { - LineJunctions from_prev_junctions = *edge_to_peak->prev->data.getExtrusionJunctions(); + LineJunctions from_prev_junctions = *edge_to_peak->prev_->data_.getExtrusionJunctions(); while (! from_junctions.empty() && ! from_prev_junctions.empty() && from_junctions.back().perimeter_index <= from_prev_junctions.front().perimeter_index) { from_junctions.pop_back(); } from_junctions.reserve(from_junctions.size() + from_prev_junctions.size()); from_junctions.insert(from_junctions.end(), from_prev_junctions.begin(), from_prev_junctions.end()); - assert(! edge_to_peak->prev->prev); - if (edge_to_peak->prev->prev) + assert(! edge_to_peak->prev_->prev_); + if (edge_to_peak->prev_->prev_) { spdlog::warn("The edge we're about to connect is already connected."); } } - if (edge_from_peak->next) + if (edge_from_peak->next_) { - LineJunctions to_next_junctions = *edge_from_peak->next->twin->data.getExtrusionJunctions(); + LineJunctions to_next_junctions = *edge_from_peak->next_->twin_->data_.getExtrusionJunctions(); while (! to_junctions.empty() && ! to_next_junctions.empty() && to_junctions.back().perimeter_index <= to_next_junctions.front().perimeter_index) { to_junctions.pop_back(); } to_junctions.reserve(to_junctions.size() + to_next_junctions.size()); to_junctions.insert(to_junctions.end(), to_next_junctions.begin(), to_next_junctions.end()); - assert(! edge_from_peak->next->next); - if (edge_from_peak->next->next) + assert(! edge_from_peak->next_->next_); + if (edge_from_peak->next_->next_) { spdlog::warn("The edge we're about to connect is already connected!"); } @@ -2156,25 +2157,25 @@ void SkeletalTrapezoidation::connectJunctions(ptr_vector_t& edge_ { spdlog::warn("Connecting two perimeters with different indices! Perimeter {} and {}", from.perimeter_index, to.perimeter_index); } - const bool from_is_odd = quad_start->to->data.bead_count_ > 0 && quad_start->to->data.bead_count_ % 2 == 1 // quad contains single bead segment - && quad_start->to->data.transition_ratio_ == 0 // We're not in a transition + const bool from_is_odd = quad_start->to_->data_.bead_count_ > 0 && quad_start->to_->data_.bead_count_ % 2 == 1 // quad contains single bead segment + && quad_start->to_->data_.transition_ratio_ == 0 // We're not in a transition && junction_rev_idx == segment_count - 1 // Is single bead segment - && shorterThen(from.p - quad_start->to->p, 5); - const bool to_is_odd = quad_end->from->data.bead_count_ > 0 && quad_end->from->data.bead_count_ % 2 == 1 // quad contains single bead segment - && quad_end->from->data.transition_ratio_ == 0 // We're not in a transition + && shorterThen(from.p - quad_start->to_->p_, 5); + const bool to_is_odd = quad_end->from_->data_.bead_count_ > 0 && quad_end->from_->data_.bead_count_ % 2 == 1 // quad contains single bead segment + && quad_end->from_->data_.transition_ratio_ == 0 // We're not in a transition && junction_rev_idx == segment_count - 1 // Is single bead segment - && shorterThen(to.p - quad_end->from->p, 5); + && shorterThen(to.p - quad_end->from_->p_, 5); const bool is_odd_segment = from_is_odd && to_is_odd; - if (is_odd_segment && passed_odd_edges.count(quad_start->next->twin) > 0) // Only generate toolpath for odd segments once + if (is_odd_segment && passed_odd_edges.count(quad_start->next_->twin_) > 0) // Only generate toolpath for odd segments once { continue; // Prevent duplication of single bead segments } - bool from_is_3way = from_is_odd && quad_start->to->isMultiIntersection(); - bool to_is_3way = to_is_odd && quad_end->from->isMultiIntersection(); + bool from_is_3way = from_is_odd && quad_start->to_->isMultiIntersection(); + bool to_is_3way = to_is_odd && quad_end->from_->isMultiIntersection(); - passed_odd_edges.emplace(quad_start->next); + passed_odd_edges.emplace(quad_start->next_); addToolpathSegment(from, to, is_odd_segment, new_domain_start, from_is_3way, to_is_3way); } @@ -2189,11 +2190,11 @@ void SkeletalTrapezoidation::generateLocalMaximaSingleBeads() for (auto& node : graph_.nodes) { - if (! node.data.hasBeading()) + if (! node.data_.hasBeading()) { continue; } - Beading& beading = node.data.getBeading()->beading_; + Beading& beading = node.data_.getBeading()->beading_; if (beading.bead_widths.size() % 2 == 1 && node.isLocalMaximum(true) && ! node.isCentral()) { const size_t inset_index = beading.bead_widths.size() / 2; @@ -2214,7 +2215,7 @@ void SkeletalTrapezoidation::generateLocalMaximaSingleBeads() for (coord_t segment = 0; segment < n_segments; segment++) { double a = 2.0 * std::numbers::pi / n_segments * segment; - line.junctions.emplace_back(node.p + Point(r * cos(a), r * sin(a)), width, inset_index); + line.junctions.emplace_back(node.p_ + Point(r * cos(a), r * sin(a)), width, inset_index); } } } diff --git a/src/SkeletalTrapezoidationGraph.cpp b/src/SkeletalTrapezoidationGraph.cpp index 0ac596ea2c..35dec4cd61 100644 --- a/src/SkeletalTrapezoidationGraph.cpp +++ b/src/SkeletalTrapezoidationGraph.cpp @@ -20,27 +20,27 @@ STHalfEdge::STHalfEdge(SkeletalTrapezoidationEdge data) bool STHalfEdge::canGoUp(bool strict) const { - if (to->data.distance_to_boundary_ > from->data.distance_to_boundary_) + if (to_->data_.distance_to_boundary_ > from_->data_.distance_to_boundary_) { return true; } - if (to->data.distance_to_boundary_ < from->data.distance_to_boundary_ || strict) + if (to_->data_.distance_to_boundary_ < from_->data_.distance_to_boundary_ || strict) { return false; } // Edge is between equidistqant verts; recurse! - for (edge_t* outgoing = next; outgoing != twin; outgoing = outgoing->twin->next) + for (edge_t* outgoing = next_; outgoing != twin_; outgoing = outgoing->twin_->next_) { if (outgoing->canGoUp()) { return true; } - assert(outgoing->twin); - if (! outgoing->twin) + assert(outgoing->twin_); + if (! outgoing->twin_) return false; - assert(outgoing->twin->next); - if (! outgoing->twin->next) + assert(outgoing->twin_->next_); + if (! outgoing->twin_->next_) return true; // This point is on the boundary?! Should never occur } return false; @@ -48,18 +48,18 @@ bool STHalfEdge::canGoUp(bool strict) const bool STHalfEdge::isUpward() const { - if (to->data.distance_to_boundary_ > from->data.distance_to_boundary_) + if (to_->data_.distance_to_boundary_ > from_->data_.distance_to_boundary_) { return true; } - if (to->data.distance_to_boundary_ < from->data.distance_to_boundary_) + if (to_->data_.distance_to_boundary_ < from_->data_.distance_to_boundary_) { return false; } // Equidistant edge case: std::optional forward_up_dist = this->distToGoUp(); - std::optional backward_up_dist = twin->distToGoUp(); + std::optional backward_up_dist = twin_->distToGoUp(); if (forward_up_dist && backward_up_dist) { return forward_up_dist < backward_up_dist; @@ -74,23 +74,23 @@ bool STHalfEdge::isUpward() const { return false; } - return to->p < from->p; // Arbitrary ordering, which returns the opposite for the twin edge + return to_->p_ < from_->p_; // Arbitrary ordering, which returns the opposite for the twin edge } std::optional STHalfEdge::distToGoUp() const { - if (to->data.distance_to_boundary_ > from->data.distance_to_boundary_) + if (to_->data_.distance_to_boundary_ > from_->data_.distance_to_boundary_) { return 0; } - if (to->data.distance_to_boundary_ < from->data.distance_to_boundary_) + if (to_->data_.distance_to_boundary_ < from_->data_.distance_to_boundary_) { return std::optional(); } // Edge is between equidistqant verts; recurse! std::optional ret; - for (edge_t* outgoing = next; outgoing != twin; outgoing = outgoing->twin->next) + for (edge_t* outgoing = next_; outgoing != twin_; outgoing = outgoing->twin_->next_) { std::optional dist_to_up = outgoing->distToGoUp(); if (dist_to_up) @@ -104,16 +104,16 @@ std::optional STHalfEdge::distToGoUp() const ret = dist_to_up; } } - assert(outgoing->twin); - if (! outgoing->twin) + assert(outgoing->twin_); + if (! outgoing->twin_) return std::optional(); - assert(outgoing->twin->next); - if (! outgoing->twin->next) + assert(outgoing->twin_->next_); + if (! outgoing->twin_->next_) return 0; // This point is on the boundary?! Should never occur } if (ret) { - ret = *ret + cura::vSize(to->p - from->p); + ret = *ret + cura::vSize(to_->p_ - from_->p_); } return ret; } @@ -121,15 +121,15 @@ std::optional STHalfEdge::distToGoUp() const STHalfEdge* STHalfEdge::getNextUnconnected() { edge_t* result = static_cast(this); - while (result->next) + while (result->next_) { - result = result->next; + result = result->next_; if (result == this) { return nullptr; } } - return result->twin; + return result->twin_; } STHalfEdgeNode::STHalfEdgeNode(SkeletalTrapezoidationJoint data, Point p) @@ -140,60 +140,60 @@ STHalfEdgeNode::STHalfEdgeNode(SkeletalTrapezoidationJoint data, Point p) bool STHalfEdgeNode::isMultiIntersection() { int odd_path_count = 0; - edge_t* outgoing = this->incident_edge; + edge_t* outgoing = incident_edge_; do { if (! outgoing) { // This is a node on the outside return false; } - if (outgoing->data.isCentral()) + if (outgoing->data_.isCentral()) { odd_path_count++; } - } while (outgoing = outgoing->twin->next, outgoing != this->incident_edge); + } while (outgoing = outgoing->twin_->next_, outgoing != incident_edge_); return odd_path_count > 2; } bool STHalfEdgeNode::isCentral() const { - edge_t* edge = incident_edge; + edge_t* edge = incident_edge_; do { - if (edge->data.isCentral()) + if (edge->data_.isCentral()) { return true; } - assert(edge->twin); - if (! edge->twin) + assert(edge->twin_); + if (! edge->twin_) return false; - } while (edge = edge->twin->next, edge != incident_edge); + } while (edge = edge->twin_->next_, edge != incident_edge_); return false; } bool STHalfEdgeNode::isLocalMaximum(bool strict) const { - if (data.distance_to_boundary_ == 0) + if (data_.distance_to_boundary_ == 0) { return false; } - edge_t* edge = incident_edge; + edge_t* edge = incident_edge_; do { if (edge->canGoUp(strict)) { return false; } - assert(edge->twin); - if (! edge->twin) + assert(edge->twin_); + if (! edge->twin_) return false; - if (! edge->twin->next) + if (! edge->twin_->next_) { // This point is on the boundary return false; } - } while (edge = edge->twin->next, edge != incident_edge); + } while (edge = edge->twin_->next_, edge != incident_edge_); return true; } @@ -227,12 +227,12 @@ void SkeletalTrapezoidationGraph::collapseSmallEdges(coord_t snap_dist) auto should_collapse = [snap_dist](node_t* a, node_t* b) { - return shorterThen(a->p - b->p, snap_dist); + return shorterThen(a->p_ - b->p_, snap_dist); }; for (auto edge_it = edges.begin(); edge_it != edges.end();) { - if (edge_it->prev) + if (edge_it->prev_) { edge_it++; continue; @@ -240,24 +240,24 @@ void SkeletalTrapezoidationGraph::collapseSmallEdges(coord_t snap_dist) edge_t* quad_start = &*edge_it; edge_t* quad_end = quad_start; - while (quad_end->next) - quad_end = quad_end->next; - edge_t* quad_mid = (quad_start->next == quad_end) ? nullptr : quad_start->next; + while (quad_end->next_) + quad_end = quad_end->next_; + edge_t* quad_mid = (quad_start->next_ == quad_end) ? nullptr : quad_start->next_; bool edge_it_is_updated = false; - if (quad_mid && should_collapse(quad_mid->from, quad_mid->to)) + if (quad_mid && should_collapse(quad_mid->from_, quad_mid->to_)) { - assert(quad_mid->twin); - if (! quad_mid->twin) + assert(quad_mid->twin_); + if (! quad_mid->twin_) { RUN_ONCE(spdlog::warn("Encountered quad edge without a twin.")); continue; // Prevent accessing unallocated memory. } int count = 0; - for (edge_t* edge_from_3 = quad_end; edge_from_3 && edge_from_3 != quad_mid->twin; edge_from_3 = edge_from_3->twin->next) + for (edge_t* edge_from_3 = quad_end; edge_from_3 && edge_from_3 != quad_mid->twin_; edge_from_3 = edge_from_3->twin_->next_) { - edge_from_3->from = quad_mid->from; - edge_from_3->twin->to = quad_mid->from; + edge_from_3->from_ = quad_mid->from_; + edge_from_3->twin_->to_ = quad_mid->from_; if (++count > 1000) { break; @@ -269,52 +269,52 @@ void SkeletalTrapezoidationGraph::collapseSmallEdges(coord_t snap_dist) // | | // | | // o o - if (quad_mid->from->incident_edge == quad_mid) + if (quad_mid->from_->incident_edge_ == quad_mid) { - if (quad_mid->twin->next) + if (quad_mid->twin_->next_) { - quad_mid->from->incident_edge = quad_mid->twin->next; + quad_mid->from_->incident_edge_ = quad_mid->twin_->next_; } else { - quad_mid->from->incident_edge = quad_mid->prev->twin; + quad_mid->from_->incident_edge_ = quad_mid->prev_->twin_; } } - nodes.erase(node_locator[quad_mid->to]); + nodes.erase(node_locator[quad_mid->to_]); - quad_mid->prev->next = quad_mid->next; - quad_mid->next->prev = quad_mid->prev; - quad_mid->twin->next->prev = quad_mid->twin->prev; - quad_mid->twin->prev->next = quad_mid->twin->next; + quad_mid->prev_->next_ = quad_mid->next_; + quad_mid->next_->prev_ = quad_mid->prev_; + quad_mid->twin_->next_->prev_ = quad_mid->twin_->prev_; + quad_mid->twin_->prev_->next_ = quad_mid->twin_->next_; - safelyRemoveEdge(quad_mid->twin, edge_it, edge_it_is_updated); + safelyRemoveEdge(quad_mid->twin_, edge_it, edge_it_is_updated); safelyRemoveEdge(quad_mid, edge_it, edge_it_is_updated); } // o-o // | | > collapse sides // o o - if (should_collapse(quad_start->from, quad_end->to) && should_collapse(quad_start->to, quad_end->from)) + if (should_collapse(quad_start->from_, quad_end->to_) && should_collapse(quad_start->to_, quad_end->from_)) { // Collapse start and end edges and remove whole cell - quad_start->twin->to = quad_end->to; - quad_end->to->incident_edge = quad_end->twin; - if (quad_end->from->incident_edge == quad_end) + quad_start->twin_->to_ = quad_end->to_; + quad_end->to_->incident_edge_ = quad_end->twin_; + if (quad_end->from_->incident_edge_ == quad_end) { - if (quad_end->twin->next) + if (quad_end->twin_->next_) { - quad_end->from->incident_edge = quad_end->twin->next; + quad_end->from_->incident_edge_ = quad_end->twin_->next_; } else { - quad_end->from->incident_edge = quad_end->prev->twin; + quad_end->from_->incident_edge_ = quad_end->prev_->twin_; } } - nodes.erase(node_locator[quad_start->from]); + nodes.erase(node_locator[quad_start->from_]); - quad_start->twin->twin = quad_end->twin; - quad_end->twin->twin = quad_start->twin; + quad_start->twin_->twin_ = quad_end->twin_; + quad_end->twin_->twin_ = quad_start->twin_; safelyRemoveEdge(quad_start, edge_it, edge_it_is_updated); safelyRemoveEdge(quad_end, edge_it, edge_it_is_updated); } @@ -331,52 +331,52 @@ void SkeletalTrapezoidationGraph::collapseSmallEdges(coord_t snap_dist) void SkeletalTrapezoidationGraph::makeRib(edge_t*& prev_edge, Point start_source_point, Point end_source_point, bool is_next_to_start_or_end) { - Point p = LinearAlg2D::getClosestOnLine(prev_edge->to->p, start_source_point, end_source_point); - coord_t dist = vSize(prev_edge->to->p - p); - prev_edge->to->data.distance_to_boundary_ = dist; + Point p = LinearAlg2D::getClosestOnLine(prev_edge->to_->p_, start_source_point, end_source_point); + coord_t dist = vSize(prev_edge->to_->p_ - p); + prev_edge->to_->data_.distance_to_boundary_ = dist; assert(dist >= 0); nodes.emplace_front(SkeletalTrapezoidationJoint(), p); node_t* node = &nodes.front(); - node->data.distance_to_boundary_ = 0; + node->data_.distance_to_boundary_ = 0; edges.emplace_front(SkeletalTrapezoidationEdge(SkeletalTrapezoidationEdge::EdgeType::EXTRA_VD)); edge_t* forth_edge = &edges.front(); edges.emplace_front(SkeletalTrapezoidationEdge(SkeletalTrapezoidationEdge::EdgeType::EXTRA_VD)); edge_t* back_edge = &edges.front(); - prev_edge->next = forth_edge; - forth_edge->prev = prev_edge; - forth_edge->from = prev_edge->to; - forth_edge->to = node; - forth_edge->twin = back_edge; - back_edge->twin = forth_edge; - back_edge->from = node; - back_edge->to = prev_edge->to; - node->incident_edge = back_edge; + prev_edge->next_ = forth_edge; + forth_edge->prev_ = prev_edge; + forth_edge->from_ = prev_edge->to_; + forth_edge->to_ = node; + forth_edge->twin_ = back_edge; + back_edge->twin_ = forth_edge; + back_edge->from_ = node; + back_edge->to_ = prev_edge->to_; + node->incident_edge_ = back_edge; prev_edge = back_edge; } std::pair SkeletalTrapezoidationGraph::insertRib(edge_t& edge, node_t* mid_node) { - edge_t* edge_before = edge.prev; - edge_t* edge_after = edge.next; - node_t* node_before = edge.from; - node_t* node_after = edge.to; + edge_t* edge_before = edge.prev_; + edge_t* edge_after = edge.next_; + node_t* node_before = edge.from_; + node_t* node_after = edge.to_; - Point p = mid_node->p; + Point p = mid_node->p_; std::pair source_segment = getSource(edge); Point px = LinearAlg2D::getClosestOnLineSegment(p, source_segment.first, source_segment.second); coord_t dist = vSize(p - px); assert(dist > 0); - mid_node->data.distance_to_boundary_ = dist; - mid_node->data.transition_ratio_ = 0; // Both transition end should have rest = 0, because at the ends a whole number of beads fits without rest + mid_node->data_.distance_to_boundary_ = dist; + mid_node->data_.transition_ratio_ = 0; // Both transition end should have rest = 0, because at the ends a whole number of beads fits without rest nodes.emplace_back(SkeletalTrapezoidationJoint(), px); node_t* source_node = &nodes.back(); - source_node->data.distance_to_boundary_ = 0; + source_node->data_.distance_to_boundary_ = 0; edge_t* first = &edge; edges.emplace_back(SkeletalTrapezoidationEdge()); @@ -388,52 +388,52 @@ std::pairnext = first; + edge_before->next_ = first; } - first->next = outward_edge; - outward_edge->next = nullptr; - inward_edge->next = second; - second->next = edge_after; + first->next_ = outward_edge; + outward_edge->next_ = nullptr; + inward_edge->next_ = second; + second->next_ = edge_after; if (edge_after) { - edge_after->prev = second; + edge_after->prev_ = second; } - second->prev = inward_edge; - inward_edge->prev = nullptr; - outward_edge->prev = first; - first->prev = edge_before; - - first->to = mid_node; - outward_edge->to = source_node; - inward_edge->to = mid_node; - second->to = node_after; - - first->from = node_before; - outward_edge->from = mid_node; - inward_edge->from = source_node; - second->from = mid_node; - - node_before->incident_edge = first; - mid_node->incident_edge = outward_edge; - source_node->incident_edge = inward_edge; + second->prev_ = inward_edge; + inward_edge->prev_ = nullptr; + outward_edge->prev_ = first; + first->prev_ = edge_before; + + first->to_ = mid_node; + outward_edge->to_ = source_node; + inward_edge->to_ = mid_node; + second->to_ = node_after; + + first->from_ = node_before; + outward_edge->from_ = mid_node; + inward_edge->from_ = source_node; + second->from_ = mid_node; + + node_before->incident_edge_ = first; + mid_node->incident_edge_ = outward_edge; + source_node->incident_edge_ = inward_edge; if (edge_after) { - node_after->incident_edge = edge_after; + node_after->incident_edge_ = edge_after; } - first->data.setIsCentral(true); - outward_edge->data.setIsCentral(false); // TODO verify this is always the case. - inward_edge->data.setIsCentral(false); - second->data.setIsCentral(true); + first->data_.setIsCentral(true); + outward_edge->data_.setIsCentral(false); // TODO verify this is always the case. + inward_edge->data_.setIsCentral(false); + second->data_.setIsCentral(true); - outward_edge->twin = inward_edge; - inward_edge->twin = outward_edge; + outward_edge->twin_ = inward_edge; + inward_edge->twin_ = outward_edge; - first->twin = nullptr; // we don't know these yet! - second->twin = nullptr; + first->twin_ = nullptr; // we don't know these yet! + second->twin_ = nullptr; - assert(second->prev->from->data.distance_to_boundary_ == 0); + assert(second->prev_->from_->data_.distance_to_boundary_ == 0); return std::make_pair(first, second); } @@ -445,9 +445,9 @@ SkeletalTrapezoidationGraph::edge_t* SkeletalTrapezoidationGraph::insertNode(edg nodes.emplace_back(SkeletalTrapezoidationJoint(), mid); node_t* mid_node = &nodes.back(); - edge_t* twin = last_edge_replacing_input->twin; - last_edge_replacing_input->twin = nullptr; - twin->twin = nullptr; + edge_t* twin = last_edge_replacing_input->twin_; + last_edge_replacing_input->twin_ = nullptr; + twin->twin_ = nullptr; std::pair left_pair = insertRib(*last_edge_replacing_input, mid_node); std::pair right_pair = insertRib(*twin, mid_node); edge_t* first_edge_replacing_input = left_pair.first; @@ -455,12 +455,12 @@ SkeletalTrapezoidationGraph::edge_t* SkeletalTrapezoidationGraph::insertNode(edg edge_t* first_edge_replacing_twin = right_pair.first; edge_t* last_edge_replacing_twin = right_pair.second; - first_edge_replacing_input->twin = last_edge_replacing_twin; - last_edge_replacing_twin->twin = first_edge_replacing_input; - last_edge_replacing_input->twin = first_edge_replacing_twin; - first_edge_replacing_twin->twin = last_edge_replacing_input; + first_edge_replacing_input->twin_ = last_edge_replacing_twin; + last_edge_replacing_twin->twin_ = first_edge_replacing_input; + last_edge_replacing_input->twin_ = first_edge_replacing_twin; + first_edge_replacing_twin->twin_ = last_edge_replacing_input; - mid_node->data.bead_count_ = mide_node_bead_count; + mid_node->data_.bead_count_ = mide_node_bead_count; return last_edge_replacing_input; } @@ -468,18 +468,18 @@ SkeletalTrapezoidationGraph::edge_t* SkeletalTrapezoidationGraph::insertNode(edg std::pair SkeletalTrapezoidationGraph::getSource(const edge_t& edge) { const edge_t* from_edge = &edge; - while (from_edge->prev) + while (from_edge->prev_) { - from_edge = from_edge->prev; + from_edge = from_edge->prev_; } const edge_t* to_edge = &edge; - while (to_edge->next) + while (to_edge->next_) { - to_edge = to_edge->next; + to_edge = to_edge->next_; } - return std::make_pair(from_edge->from->p, to_edge->to->p); + return std::make_pair(from_edge->from_->p_, to_edge->to_->p_); } } // namespace cura diff --git a/src/SkirtBrim.cpp b/src/SkirtBrim.cpp index 18da72094a..4567a92d6c 100644 --- a/src/SkirtBrim.cpp +++ b/src/SkirtBrim.cpp @@ -118,7 +118,7 @@ void SkirtBrim::generate() constexpr LayerIndex layer_nr = 0; constexpr bool include_support = true; const bool include_prime_tower = adhesion_type_ == EPlatformAdhesion::SKIRT; - const bool has_prime_tower = storage_.primeTower.enabled; + const bool has_prime_tower = storage_.primeTower.enabled_; Polygons covered_area = storage_.getLayerOutlines(layer_nr, include_support, include_prime_tower, /*external_polys_only*/ false); std::vector allowed_areas_per_extruder(extruder_count_); @@ -350,7 +350,7 @@ Polygons SkirtBrim::getFirstLayerOutline(const int extruder_nr /* = -1 */) const int primary_line_count = line_count_[reference_extruder_nr]; const bool external_only = adhesion_type_ == EPlatformAdhesion::SKIRT || external_polys_only_[reference_extruder_nr]; // Whether to include holes or not. Skirt doesn't have any holes. - const bool has_prime_tower = storage_.primeTower.enabled; + const bool has_prime_tower = storage_.primeTower.enabled_; const LayerIndex layer_nr = 0; if (adhesion_type_ == EPlatformAdhesion::SKIRT) { diff --git a/src/TreeModelVolumes.cpp b/src/TreeModelVolumes.cpp index 4604967baf..750020cc1d 100644 --- a/src/TreeModelVolumes.cpp +++ b/src/TreeModelVolumes.cpp @@ -148,7 +148,7 @@ TreeModelVolumes::TreeModelVolumes( anti_overhang_[layer_idx].add(storage.support.supportLayers[layer_idx].anti_overhang); } - if (storage.primeTower.enabled) + if (storage.primeTower.enabled_) { anti_overhang_[layer_idx].add(storage.primeTower.getGroundPoly()); } diff --git a/src/gcodeExport.cpp b/src/gcodeExport.cpp index 559ff91b4e..5e4e1db16e 100644 --- a/src/gcodeExport.cpp +++ b/src/gcodeExport.cpp @@ -37,38 +37,38 @@ std::string transliterate(const std::string& text) } GCodeExport::GCodeExport() - : output_stream(&std::cout) - , currentPosition(0, 0, MM2INT(20)) - , layer_nr(0) - , relative_extrusion(false) + : output_stream_(&std::cout) + , current_position_(0, 0, MM2INT(20)) + , layer_nr_(0) + , relative_extrusion_(false) { - *output_stream << std::fixed; + *output_stream_ << std::fixed; - current_e_value = 0; - current_extruder = 0; - current_fan_speed = -1; + current_e_value_ = 0; + current_extruder_ = 0; + current_fan_speed_ = -1; - total_print_times = std::vector(static_cast(PrintFeatureType::NumPrintFeatureTypes), 0.0); + total_print_times_ = std::vector(static_cast(PrintFeatureType::NumPrintFeatureTypes), 0.0); - currentSpeed = 1.0; - current_print_acceleration = -1.0; - current_travel_acceleration = -1.0; - current_jerk = -1.0; + current_speed_ = 1.0; + current_print_acceleration_ = -1.0; + current_travel_acceleration_ = -1.0; + current_jerk_ = -1.0; - is_z_hopped = 0; + is_z_hopped_ = 0; setFlavor(EGCodeFlavor::MARLIN); - initial_bed_temp = 0; - bed_temperature = 0; - build_volume_temperature = 0; - machine_heated_build_volume = false; + initial_bed_temp_ = 0; + bed_temperature_ = 0; + build_volume_temperature_ = 0; + machine_heated_build_volume_ = false; - fan_number = 0; - use_extruder_offset_to_offset_coords = false; - machine_name = ""; - relative_extrusion = false; - new_line = "\n"; + fan_number_ = 0; + use_extruder_offset_to_offset_coords_ = false; + machine_name_ = ""; + relative_extrusion_ = false; + new_line_ = "\n"; - total_bounding_box = AABB3D(); + total_bounding_box_ = AABB3D(); } GCodeExport::~GCodeExport() @@ -77,12 +77,12 @@ GCodeExport::~GCodeExport() void GCodeExport::preSetup(const size_t start_extruder) { - current_extruder = start_extruder; + current_extruder_ = start_extruder; const Scene& scene = Application::getInstance().current_slice_->scene; std::vector::iterator mesh_group = scene.current_mesh_group; setFlavor(mesh_group->settings.get("machine_gcode_flavor")); - use_extruder_offset_to_offset_coords = mesh_group->settings.get("machine_use_extruder_offset_to_offset_coords"); + use_extruder_offset_to_offset_coords_ = mesh_group->settings.get("machine_use_extruder_offset_to_offset_coords"); const size_t extruder_count = Application::getInstance().current_slice_->scene.extruders.size(); for (size_t extruder_nr = 0; extruder_nr < extruder_count; extruder_nr++) @@ -90,45 +90,45 @@ void GCodeExport::preSetup(const size_t start_extruder) const ExtruderTrain& train = scene.extruders[extruder_nr]; setFilamentDiameter(extruder_nr, train.settings_.get("material_diameter")); - extruder_attr[extruder_nr].last_retraction_prime_speed + extruder_attr_[extruder_nr].last_retraction_prime_speed_ = train.settings_.get("retraction_prime_speed"); // the alternative would be switch_extruder_prime_speed, but dual extrusion might not even be configured... - extruder_attr[extruder_nr].fan_number = train.settings_.get("machine_extruder_cooling_fan_number"); + extruder_attr_[extruder_nr].fan_number_ = train.settings_.get("machine_extruder_cooling_fan_number"); // Cache some settings that we use frequently. const Settings& extruder_settings = Application::getInstance().current_slice_->scene.extruders[extruder_nr].settings_; - if (use_extruder_offset_to_offset_coords) + if (use_extruder_offset_to_offset_coords_) { - extruder_attr[extruder_nr].nozzle_offset = Point(extruder_settings.get("machine_nozzle_offset_x"), extruder_settings.get("machine_nozzle_offset_y")); + extruder_attr_[extruder_nr].nozzle_offset_ = Point(extruder_settings.get("machine_nozzle_offset_x"), extruder_settings.get("machine_nozzle_offset_y")); } else { - extruder_attr[extruder_nr].nozzle_offset = Point(0, 0); + extruder_attr_[extruder_nr].nozzle_offset_ = Point(0, 0); } - extruder_attr[extruder_nr].machine_firmware_retract = extruder_settings.get("machine_firmware_retract"); + extruder_attr_[extruder_nr].machine_firmware_retract_ = extruder_settings.get("machine_firmware_retract"); } - machine_name = mesh_group->settings.get("machine_name"); + machine_name_ = mesh_group->settings.get("machine_name"); - relative_extrusion = mesh_group->settings.get("relative_extrusion"); - always_write_active_tool = mesh_group->settings.get("machine_always_write_active_tool"); + relative_extrusion_ = mesh_group->settings.get("relative_extrusion"); + always_write_active_tool_ = mesh_group->settings.get("machine_always_write_active_tool"); - if (flavor == EGCodeFlavor::BFB) + if (flavor_ == EGCodeFlavor::BFB) { - new_line = "\r\n"; + new_line_ = "\r\n"; } else { - new_line = "\n"; + new_line_ = "\n"; } - estimateCalculator.setFirmwareDefaults(mesh_group->settings); + estimate_calculator_.setFirmwareDefaults(mesh_group->settings); if (mesh_group == scene.mesh_groups.begin()) { if (! scene.current_mesh_group->settings.get("material_bed_temp_prepend")) { // Current bed temperature is the one of the first layer (has already been set in header) - bed_temperature = scene.current_mesh_group->settings.get("material_bed_temperature_layer_0"); + bed_temperature_ = scene.current_mesh_group->settings.get("material_bed_temperature_layer_0"); } else { @@ -138,7 +138,7 @@ void GCodeExport::preSetup(const size_t start_extruder) else { // Current bed temperature is the one of the previous group - bed_temperature = (scene.current_mesh_group - 1)->settings.get("material_bed_temperature"); + bed_temperature_ = (scene.current_mesh_group - 1)->settings.get("material_bed_temperature"); } } @@ -156,17 +156,17 @@ void GCodeExport::setInitialAndBuildVolumeTemps(const unsigned int start_extrude setInitialTemp(extruder_nr, temp); } - initial_bed_temp = scene.current_mesh_group->settings.get("material_bed_temperature_layer_0"); - machine_heated_build_volume = scene.current_mesh_group->settings.get("machine_heated_build_volume"); - build_volume_temperature = machine_heated_build_volume ? scene.current_mesh_group->settings.get("build_volume_temperature") : Temperature(0); + initial_bed_temp_ = scene.current_mesh_group->settings.get("material_bed_temperature_layer_0"); + machine_heated_build_volume_ = scene.current_mesh_group->settings.get("machine_heated_build_volume"); + build_volume_temperature_ = machine_heated_build_volume_ ? scene.current_mesh_group->settings.get("build_volume_temperature") : Temperature(0); } void GCodeExport::setInitialTemp(int extruder_nr, double temp) { - extruder_attr[extruder_nr].initial_temp = temp; - if (flavor == EGCodeFlavor::GRIFFIN || flavor == EGCodeFlavor::ULTIGCODE) + extruder_attr_[extruder_nr].initial_temp_ = temp; + if (flavor_ == EGCodeFlavor::GRIFFIN || flavor_ == EGCodeFlavor::ULTIGCODE) { - extruder_attr[extruder_nr].currentTemperature = temp; + extruder_attr_[extruder_nr].current_temperature_ = temp; } } @@ -205,16 +205,16 @@ std::string GCodeExport::getFileHeader( std::ostringstream prefix; const size_t extruder_count = Application::getInstance().current_slice_->scene.extruders.size(); - switch (flavor) + switch (flavor_) { case EGCodeFlavor::GRIFFIN: - prefix << ";START_OF_HEADER" << new_line; - prefix << ";HEADER_VERSION:0.1" << new_line; - prefix << ";FLAVOR:" << flavorToString(flavor) << new_line; - prefix << ";GENERATOR.NAME:Cura_SteamEngine" << new_line; - prefix << ";GENERATOR.VERSION:" << CURA_ENGINE_VERSION << new_line; - prefix << ";GENERATOR.BUILD_DATE:" << Date::getDate().toStringDashed() << new_line; - prefix << ";TARGET_MACHINE.NAME:" << transliterate(machine_name) << new_line; + prefix << ";START_OF_HEADER" << new_line_; + prefix << ";HEADER_VERSION:0.1" << new_line_; + prefix << ";FLAVOR:" << flavorToString(flavor_) << new_line_; + prefix << ";GENERATOR.NAME:Cura_SteamEngine" << new_line_; + prefix << ";GENERATOR.VERSION:" << CURA_ENGINE_VERSION << new_line_; + prefix << ";GENERATOR.BUILD_DATE:" << Date::getDate().toStringDashed() << new_line_; + prefix << ";TARGET_MACHINE.NAME:" << transliterate(machine_name_) << new_line_; for (size_t extr_nr = 0; extr_nr < extruder_count; extr_nr++) { @@ -222,59 +222,59 @@ std::string GCodeExport::getFileHeader( { continue; } - prefix << ";EXTRUDER_TRAIN." << extr_nr << ".INITIAL_TEMPERATURE:" << extruder_attr[extr_nr].initial_temp << new_line; + prefix << ";EXTRUDER_TRAIN." << extr_nr << ".INITIAL_TEMPERATURE:" << extruder_attr_[extr_nr].initial_temp_ << new_line_; if (filament_used.size() == extruder_count) { - prefix << ";EXTRUDER_TRAIN." << extr_nr << ".MATERIAL.VOLUME_USED:" << static_cast(filament_used[extr_nr]) << new_line; + prefix << ";EXTRUDER_TRAIN." << extr_nr << ".MATERIAL.VOLUME_USED:" << static_cast(filament_used[extr_nr]) << new_line_; } if (mat_ids.size() == extruder_count && mat_ids[extr_nr] != "") { - prefix << ";EXTRUDER_TRAIN." << extr_nr << ".MATERIAL.GUID:" << mat_ids[extr_nr] << new_line; + prefix << ";EXTRUDER_TRAIN." << extr_nr << ".MATERIAL.GUID:" << mat_ids[extr_nr] << new_line_; } const Settings& extruder_settings = Application::getInstance().current_slice_->scene.extruders[extr_nr].settings_; - prefix << ";EXTRUDER_TRAIN." << extr_nr << ".NOZZLE.DIAMETER:" << extruder_settings.get("machine_nozzle_size") << new_line; - prefix << ";EXTRUDER_TRAIN." << extr_nr << ".NOZZLE.NAME:" << extruder_settings.get("machine_nozzle_id") << new_line; + prefix << ";EXTRUDER_TRAIN." << extr_nr << ".NOZZLE.DIAMETER:" << extruder_settings.get("machine_nozzle_size") << new_line_; + prefix << ";EXTRUDER_TRAIN." << extr_nr << ".NOZZLE.NAME:" << extruder_settings.get("machine_nozzle_id") << new_line_; } - prefix << ";BUILD_PLATE.INITIAL_TEMPERATURE:" << initial_bed_temp << new_line; + prefix << ";BUILD_PLATE.INITIAL_TEMPERATURE:" << initial_bed_temp_ << new_line_; - if (machine_heated_build_volume) + if (machine_heated_build_volume_) { - prefix << ";BUILD_VOLUME.TEMPERATURE:" << build_volume_temperature << new_line; + prefix << ";BUILD_VOLUME.TEMPERATURE:" << build_volume_temperature_ << new_line_; } if (print_time) { - prefix << ";PRINT.TIME:" << static_cast(*print_time) << new_line; + prefix << ";PRINT.TIME:" << static_cast(*print_time) << new_line_; } - prefix << ";PRINT.GROUPS:" << Application::getInstance().current_slice_->scene.mesh_groups.size() << new_line; + prefix << ";PRINT.GROUPS:" << Application::getInstance().current_slice_->scene.mesh_groups.size() << new_line_; - if (total_bounding_box.min.x_ > total_bounding_box.max.x_) // We haven't encountered any movement (yet). This probably means we're command-line slicing. + if (total_bounding_box_.min.x_ > total_bounding_box_.max.x_) // We haven't encountered any movement (yet). This probably means we're command-line slicing. { // Put some small default in there. - total_bounding_box.min = Point3(0, 0, 0); - total_bounding_box.max = Point3(10, 10, 10); + total_bounding_box_.min = Point3(0, 0, 0); + total_bounding_box_.max = Point3(10, 10, 10); } - prefix << ";PRINT.SIZE.MIN.X:" << INT2MM(total_bounding_box.min.x_) << new_line; - prefix << ";PRINT.SIZE.MIN.Y:" << INT2MM(total_bounding_box.min.y_) << new_line; - prefix << ";PRINT.SIZE.MIN.Z:" << INT2MM(total_bounding_box.min.z_) << new_line; - prefix << ";PRINT.SIZE.MAX.X:" << INT2MM(total_bounding_box.max.x_) << new_line; - prefix << ";PRINT.SIZE.MAX.Y:" << INT2MM(total_bounding_box.max.y_) << new_line; - prefix << ";PRINT.SIZE.MAX.Z:" << INT2MM(total_bounding_box.max.z_) << new_line; - prefix << ";SLICE_UUID:" << slice_uuid_ << new_line; - prefix << ";END_OF_HEADER" << new_line; + prefix << ";PRINT.SIZE.MIN.X:" << INT2MM(total_bounding_box_.min.x_) << new_line_; + prefix << ";PRINT.SIZE.MIN.Y:" << INT2MM(total_bounding_box_.min.y_) << new_line_; + prefix << ";PRINT.SIZE.MIN.Z:" << INT2MM(total_bounding_box_.min.z_) << new_line_; + prefix << ";PRINT.SIZE.MAX.X:" << INT2MM(total_bounding_box_.max.x_) << new_line_; + prefix << ";PRINT.SIZE.MAX.Y:" << INT2MM(total_bounding_box_.max.y_) << new_line_; + prefix << ";PRINT.SIZE.MAX.Z:" << INT2MM(total_bounding_box_.max.z_) << new_line_; + prefix << ";SLICE_UUID:" << slice_uuid_ << new_line_; + prefix << ";END_OF_HEADER" << new_line_; break; default: - prefix << ";FLAVOR:" << flavorToString(flavor) << new_line; - prefix << ";TIME:" << ((print_time) ? static_cast(*print_time) : 6666) << new_line; - if (flavor == EGCodeFlavor::ULTIGCODE) + prefix << ";FLAVOR:" << flavorToString(flavor_) << new_line_; + prefix << ";TIME:" << ((print_time) ? static_cast(*print_time) : 6666) << new_line_; + if (flavor_ == EGCodeFlavor::ULTIGCODE) { - prefix << ";MATERIAL:" << ((filament_used.size() >= 1) ? static_cast(filament_used[0]) : 6666) << new_line; - prefix << ";MATERIAL2:" << ((filament_used.size() >= 2) ? static_cast(filament_used[1]) : 0) << new_line; + prefix << ";MATERIAL:" << ((filament_used.size() >= 1) ? static_cast(filament_used[0]) : 6666) << new_line_; + prefix << ";MATERIAL2:" << ((filament_used.size() >= 2) ? static_cast(filament_used[1]) : 0) << new_line_; - prefix << ";NOZZLE_DIAMETER:" << Application::getInstance().current_slice_->scene.extruders[0].settings_.get("machine_nozzle_size") << new_line; + prefix << ";NOZZLE_DIAMETER:" << Application::getInstance().current_slice_->scene.extruders[0].settings_.get("machine_nozzle_size") << new_line_; } - else if (flavor == EGCodeFlavor::REPRAP || flavor == EGCodeFlavor::MARLIN || flavor == EGCodeFlavor::MARLIN_VOLUMATRIC) + else if (flavor_ == EGCodeFlavor::REPRAP || flavor_ == EGCodeFlavor::MARLIN || flavor_ == EGCodeFlavor::MARLIN_VOLUMATRIC) { prefix << ";Filament used: "; if (filament_used.size() > 0) @@ -285,9 +285,9 @@ std::string GCodeExport::getFileHeader( { prefix << ", "; } - if (flavor != EGCodeFlavor::MARLIN_VOLUMATRIC) + if (flavor_ != EGCodeFlavor::MARLIN_VOLUMATRIC) { - prefix << filament_used[i] / (1000 * extruder_attr[i].filament_area) << "m"; + prefix << filament_used[i] / (1000 * extruder_attr_[i].filament_area_) << "m"; } else // Use volumetric filament used. { @@ -299,144 +299,144 @@ std::string GCodeExport::getFileHeader( { prefix << "0m"; } - prefix << new_line; - prefix << ";Layer height: " << Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("layer_height") << new_line; + prefix << new_line_; + prefix << ";Layer height: " << Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("layer_height") << new_line_; } - prefix << ";MINX:" << INT2MM(total_bounding_box.min.x_) << new_line; - prefix << ";MINY:" << INT2MM(total_bounding_box.min.y_) << new_line; - prefix << ";MINZ:" << INT2MM(total_bounding_box.min.z_) << new_line; - prefix << ";MAXX:" << INT2MM(total_bounding_box.max.x_) << new_line; - prefix << ";MAXY:" << INT2MM(total_bounding_box.max.y_) << new_line; - prefix << ";MAXZ:" << INT2MM(total_bounding_box.max.z_) << new_line; - prefix << ";TARGET_MACHINE.NAME:" << transliterate(machine_name) << new_line; + prefix << ";MINX:" << INT2MM(total_bounding_box_.min.x_) << new_line_; + prefix << ";MINY:" << INT2MM(total_bounding_box_.min.y_) << new_line_; + prefix << ";MINZ:" << INT2MM(total_bounding_box_.min.z_) << new_line_; + prefix << ";MAXX:" << INT2MM(total_bounding_box_.max.x_) << new_line_; + prefix << ";MAXY:" << INT2MM(total_bounding_box_.max.y_) << new_line_; + prefix << ";MAXZ:" << INT2MM(total_bounding_box_.max.z_) << new_line_; + prefix << ";TARGET_MACHINE.NAME:" << transliterate(machine_name_) << new_line_; } return prefix.str(); } -void GCodeExport::setLayerNr(const LayerIndex& layer_nr_) +void GCodeExport::setLayerNr(const LayerIndex& layer_nr) { - layer_nr = layer_nr_; + layer_nr_ = layer_nr; } void GCodeExport::setOutputStream(std::ostream* stream) { - output_stream = stream; - *output_stream << std::fixed; + output_stream_ = stream; + *output_stream_ << std::fixed; } bool GCodeExport::getExtruderIsUsed(const int extruder_nr) const { assert(extruder_nr >= 0); assert(extruder_nr < MAX_EXTRUDERS); - return extruder_attr[extruder_nr].is_used; + return extruder_attr_[extruder_nr].is_used_; } Point GCodeExport::getGcodePos(const coord_t x, const coord_t y, const int extruder_train) const { - return Point(x, y) - extruder_attr[extruder_train].nozzle_offset; + return Point(x, y) - extruder_attr_[extruder_train].nozzle_offset_; } void GCodeExport::setFlavor(EGCodeFlavor flavor) { - this->flavor = flavor; + this->flavor_ = flavor; if (flavor == EGCodeFlavor::MACH3) { for (int n = 0; n < MAX_EXTRUDERS; n++) { - extruder_attr[n].extruderCharacter = 'A' + n; + extruder_attr_[n].extruder_character_ = 'A' + n; } } else { for (int n = 0; n < MAX_EXTRUDERS; n++) { - extruder_attr[n].extruderCharacter = 'E'; + extruder_attr_[n].extruder_character_ = 'E'; } } if (flavor == EGCodeFlavor::ULTIGCODE || flavor == EGCodeFlavor::MARLIN_VOLUMATRIC) { - is_volumetric = true; + is_volumetric_ = true; } else { - is_volumetric = false; + is_volumetric_ = false; } } EGCodeFlavor GCodeExport::getFlavor() const { - return flavor; + return flavor_; } void GCodeExport::setZ(int z) { - current_layer_z = z; + current_layer_z_ = z; } void GCodeExport::addExtraPrimeAmount(double extra_prime_volume) { - extruder_attr[current_extruder].prime_volume += extra_prime_volume; + extruder_attr_[current_extruder_].prime_volume_ += extra_prime_volume; } void GCodeExport::setFlowRateExtrusionSettings(double max_extrusion_offset, double extrusion_offset_factor) { - this->max_extrusion_offset = max_extrusion_offset; - this->extrusion_offset_factor = extrusion_offset_factor; + this->max_extrusion_offset_ = max_extrusion_offset; + this->extrusion_offset_factor_ = extrusion_offset_factor; } Point3 GCodeExport::getPosition() const { - return currentPosition; + return current_position_; } Point GCodeExport::getPositionXY() const { - return Point(currentPosition.x_, currentPosition.y_); + return Point(current_position_.x_, current_position_.y_); } int GCodeExport::getPositionZ() const { - return currentPosition.z_; + return current_position_.z_; } int GCodeExport::getExtruderNr() const { - return current_extruder; + return current_extruder_; } void GCodeExport::setFilamentDiameter(const size_t extruder, const coord_t diameter) { const double r = INT2MM(diameter) / 2.0; const double area = std::numbers::pi * r * r; - extruder_attr[extruder].filament_area = area; + extruder_attr_[extruder].filament_area_ = area; } double GCodeExport::getCurrentExtrudedVolume() const { - double extrusion_amount = current_e_value; - if (! extruder_attr[current_extruder].machine_firmware_retract) + double extrusion_amount = current_e_value_; + if (! extruder_attr_[current_extruder_].machine_firmware_retract_) { // no E values are changed to perform a retraction extrusion_amount - -= extruder_attr[current_extruder].retraction_e_amount_at_e_start; // subtract the increment in E which was used for the first unretraction instead of extrusion + -= extruder_attr_[current_extruder_].retraction_e_amount_at_e_start_; // subtract the increment in E which was used for the first unretraction instead of extrusion extrusion_amount - += extruder_attr[current_extruder].retraction_e_amount_current; // add the decrement in E which the filament is behind on extrusion due to the last retraction + += extruder_attr_[current_extruder_].retraction_e_amount_current_; // add the decrement in E which the filament is behind on extrusion due to the last retraction } - if (is_volumetric) + if (is_volumetric_) { return extrusion_amount; } else { - return extrusion_amount * extruder_attr[current_extruder].filament_area; + return extrusion_amount * extruder_attr_[current_extruder_].filament_area_; } } double GCodeExport::eToMm(double e) { - if (is_volumetric) + if (is_volumetric_) { - return e / extruder_attr[current_extruder].filament_area; + return e / extruder_attr_[current_extruder_].filament_area_; } else { @@ -446,21 +446,21 @@ double GCodeExport::eToMm(double e) double GCodeExport::mm3ToE(double mm3) { - if (is_volumetric) + if (is_volumetric_) { return mm3; } else { - return mm3 / extruder_attr[current_extruder].filament_area; + return mm3 / extruder_attr_[current_extruder_].filament_area_; } } double GCodeExport::mmToE(double mm) { - if (is_volumetric) + if (is_volumetric_) { - return mm * extruder_attr[current_extruder].filament_area; + return mm * extruder_attr_[current_extruder_].filament_area_; } else { @@ -470,26 +470,26 @@ double GCodeExport::mmToE(double mm) double GCodeExport::eToMm3(double e, size_t extruder) { - if (is_volumetric) + if (is_volumetric_) { return e; } else { - return e * extruder_attr[extruder].filament_area; + return e * extruder_attr_[extruder].filament_area_; } } double GCodeExport::getTotalFilamentUsed(size_t extruder_nr) { - if (extruder_nr == current_extruder) - return extruder_attr[extruder_nr].totalFilament + getCurrentExtrudedVolume(); - return extruder_attr[extruder_nr].totalFilament; + if (extruder_nr == current_extruder_) + return extruder_attr_[extruder_nr].total_filament_ + getCurrentExtrudedVolume(); + return extruder_attr_[extruder_nr].total_filament_; } std::vector GCodeExport::getTotalPrintTimePerFeature() { - return total_print_times; + return total_print_times_; } double GCodeExport::getSumTotalPrintTimes() @@ -504,28 +504,28 @@ double GCodeExport::getSumTotalPrintTimes() void GCodeExport::resetTotalPrintTimeAndFilament() { - for (size_t i = 0; i < total_print_times.size(); i++) + for (size_t i = 0; i < total_print_times_.size(); i++) { - total_print_times[i] = 0.0; + total_print_times_[i] = 0.0; } for (unsigned int e = 0; e < MAX_EXTRUDERS; e++) { - extruder_attr[e].totalFilament = 0.0; - extruder_attr[e].currentTemperature = 0; - extruder_attr[e].waited_for_temperature = false; + extruder_attr_[e].total_filament_ = 0.0; + extruder_attr_[e].current_temperature_ = 0; + extruder_attr_[e].waited_for_temperature_ = false; } - current_e_value = 0.0; - estimateCalculator.reset(); + current_e_value_ = 0.0; + estimate_calculator_.reset(); } void GCodeExport::updateTotalPrintTime() { - std::vector estimates = estimateCalculator.calculate(); + std::vector estimates = estimate_calculator_.calculate(); for (size_t i = 0; i < estimates.size(); i++) { - total_print_times[i] += estimates[i]; + total_print_times_[i] += estimates[i]; } - estimateCalculator.reset(); + estimate_calculator_.reset(); writeTimeComment(getSumTotalPrintTimes()); } @@ -533,24 +533,24 @@ void GCodeExport::writeComment(const std::string& unsanitized_comment) { const std::string comment = transliterate(unsanitized_comment); - *output_stream << ";"; + *output_stream_ << ";"; for (unsigned int i = 0; i < comment.length(); i++) { if (comment[i] == '\n') { - *output_stream << new_line << ";"; + *output_stream_ << new_line_ << ";"; } else { - *output_stream << comment[i]; + *output_stream_ << comment[i]; } } - *output_stream << new_line; + *output_stream_ << new_line_; } void GCodeExport::writeTimeComment(const Duration time) { - *output_stream << ";TIME_ELAPSED:" << time << new_line; + *output_stream_ << ";TIME_ELAPSED:" << time << new_line_; } void GCodeExport::writeTypeComment(const PrintFeatureType& type) @@ -558,31 +558,31 @@ void GCodeExport::writeTypeComment(const PrintFeatureType& type) switch (type) { case PrintFeatureType::OuterWall: - *output_stream << ";TYPE:WALL-OUTER" << new_line; + *output_stream_ << ";TYPE:WALL-OUTER" << new_line_; break; case PrintFeatureType::InnerWall: - *output_stream << ";TYPE:WALL-INNER" << new_line; + *output_stream_ << ";TYPE:WALL-INNER" << new_line_; break; case PrintFeatureType::Skin: - *output_stream << ";TYPE:SKIN" << new_line; + *output_stream_ << ";TYPE:SKIN" << new_line_; break; case PrintFeatureType::Support: - *output_stream << ";TYPE:SUPPORT" << new_line; + *output_stream_ << ";TYPE:SUPPORT" << new_line_; break; case PrintFeatureType::SkirtBrim: - *output_stream << ";TYPE:SKIRT" << new_line; + *output_stream_ << ";TYPE:SKIRT" << new_line_; break; case PrintFeatureType::Infill: - *output_stream << ";TYPE:FILL" << new_line; + *output_stream_ << ";TYPE:FILL" << new_line_; break; case PrintFeatureType::SupportInfill: - *output_stream << ";TYPE:SUPPORT" << new_line; + *output_stream_ << ";TYPE:SUPPORT" << new_line_; break; case PrintFeatureType::SupportInterface: - *output_stream << ";TYPE:SUPPORT-INTERFACE" << new_line; + *output_stream_ << ";TYPE:SUPPORT-INTERFACE" << new_line_; break; case PrintFeatureType::PrimeTower: - *output_stream << ";TYPE:PRIME-TOWER" << new_line; + *output_stream_ << ";TYPE:PRIME-TOWER" << new_line_; break; case PrintFeatureType::MoveCombing: case PrintFeatureType::MoveRetraction: @@ -596,17 +596,17 @@ void GCodeExport::writeTypeComment(const PrintFeatureType& type) void GCodeExport::writeLayerComment(const LayerIndex layer_nr) { - *output_stream << ";LAYER:" << layer_nr << new_line; + *output_stream_ << ";LAYER:" << layer_nr << new_line_; } void GCodeExport::writeLayerCountComment(const size_t layer_count) { - *output_stream << ";LAYER_COUNT:" << layer_count << new_line; + *output_stream_ << ";LAYER_COUNT:" << layer_count << new_line_; } void GCodeExport::writeLine(const char* line) { - *output_stream << line << new_line; + *output_stream_ << line << new_line_; } void GCodeExport::resetExtrusionMode() @@ -619,28 +619,28 @@ void GCodeExport::writeExtrusionMode(bool set_relative_extrusion_mode) { if (set_relative_extrusion_mode) { - *output_stream << "M83 ;relative extrusion mode" << new_line; + *output_stream_ << "M83 ;relative extrusion mode" << new_line_; } else { - *output_stream << "M82 ;absolute extrusion mode" << new_line; + *output_stream_ << "M82 ;absolute extrusion mode" << new_line_; } } void GCodeExport::resetExtrusionValue() { - if (! relative_extrusion) + if (! relative_extrusion_) { - *output_stream << "G92 " << extruder_attr[current_extruder].extruderCharacter << "0" << new_line; + *output_stream_ << "G92 " << extruder_attr_[current_extruder_].extruder_character_ << "0" << new_line_; } double current_extruded_volume = getCurrentExtrudedVolume(); - extruder_attr[current_extruder].totalFilament += current_extruded_volume; - for (double& extruded_volume_at_retraction : extruder_attr[current_extruder].extruded_volume_at_previous_n_retractions) + extruder_attr_[current_extruder_].total_filament_ += current_extruded_volume; + for (double& extruded_volume_at_retraction : extruder_attr_[current_extruder_].extruded_volume_at_previous_n_retractions_) { // update the extruded_volume_at_previous_n_retractions only of the current extruder, since other extruders don't extrude the current volume extruded_volume_at_retraction -= current_extruded_volume; } - current_e_value = 0.0; - extruder_attr[current_extruder].retraction_e_amount_at_e_start = extruder_attr[current_extruder].retraction_e_amount_current; + current_e_value_ = 0.0; + extruder_attr_[current_extruder_].retraction_e_amount_at_e_start_ = extruder_attr_[current_extruder_].retraction_e_amount_current_; } bool GCodeExport::initializeExtruderTrains(const SliceDataStorage& storage, const size_t start_extruder_nr) @@ -822,32 +822,32 @@ bool GCodeExport::needPrimeBlob() const void GCodeExport::writeDelay(const Duration& time_amount) { - *output_stream << "G4 P" << int(time_amount * 1000) << new_line; - estimateCalculator.addTime(time_amount); + *output_stream_ << "G4 P" << int(time_amount * 1000) << new_line_; + estimate_calculator_.addTime(time_amount); } void GCodeExport::writeTravel(const Point& p, const Velocity& speed) { - writeTravel(Point3(p.X, p.Y, current_layer_z), speed); + writeTravel(Point3(p.X, p.Y, current_layer_z_), speed); } void GCodeExport::writeExtrusion(const Point& p, const Velocity& speed, double extrusion_mm3_per_mm, PrintFeatureType feature, bool update_extrusion_offset) { - writeExtrusion(Point3(p.X, p.Y, current_layer_z), speed, extrusion_mm3_per_mm, feature, update_extrusion_offset); + writeExtrusion(Point3(p.X, p.Y, current_layer_z_), speed, extrusion_mm3_per_mm, feature, update_extrusion_offset); } void GCodeExport::writeTravel(const Point3& p, const Velocity& speed) { - if (flavor == EGCodeFlavor::BFB) + if (flavor_ == EGCodeFlavor::BFB) { - writeMoveBFB(p.x_, p.y_, p.z_ + is_z_hopped, speed, 0.0, PrintFeatureType::MoveCombing); + writeMoveBFB(p.x_, p.y_, p.z_ + is_z_hopped_, speed, 0.0, PrintFeatureType::MoveCombing); return; } - writeTravel(p.x_, p.y_, p.z_ + is_z_hopped, speed); + writeTravel(p.x_, p.y_, p.z_ + is_z_hopped_, speed); } void GCodeExport::writeExtrusion(const Point3& p, const Velocity& speed, double extrusion_mm3_per_mm, PrintFeatureType feature, bool update_extrusion_offset) { - if (flavor == EGCodeFlavor::BFB) + if (flavor_ == EGCodeFlavor::BFB) { writeMoveBFB(p.x_, p.y_, p.z_, speed, extrusion_mm3_per_mm, feature); return; @@ -872,7 +872,7 @@ void GCodeExport::writeMoveBFB(const int x, const int y, const int z, const Velo double extrusion_per_mm = mm3ToE(extrusion_mm3_per_mm); - Point gcode_pos = getGcodePos(x, y, current_extruder); + Point gcode_pos = getGcodePos(x, y, current_extruder_); // For Bits From Bytes machines, we need to handle this completely differently. As they do not use E values but RPM values. double fspeed = speed * 60; @@ -881,18 +881,18 @@ void GCodeExport::writeMoveBFB(const int x, const int y, const int z, const Velo rpm /= mm_per_rpm; if (rpm > 0) { - if (extruder_attr[current_extruder].retraction_e_amount_current) + if (extruder_attr_[current_extruder_].retraction_e_amount_current_) { - if (currentSpeed != double(rpm)) + if (current_speed_ != double(rpm)) { // fprintf(f, "; %f e-per-mm %d mm-width %d mm/s\n", extrusion_per_mm, lineWidth, speed); // fprintf(f, "M108 S%0.1f\r\n", rpm); - *output_stream << "M108 S" << PrecisionedDouble{ 1, rpm } << new_line; - currentSpeed = double(rpm); + *output_stream_ << "M108 S" << PrecisionedDouble{ 1, rpm } << new_line_; + current_speed_ = double(rpm); } // Add M101 or M201 to enable the proper extruder. - *output_stream << "M" << int((current_extruder + 1) * 100 + 1) << new_line; - extruder_attr[current_extruder].retraction_e_amount_current = 0.0; + *output_stream_ << "M" << int((current_extruder_ + 1) * 100 + 1) << new_line_; + extruder_attr_[current_extruder_].retraction_e_amount_current_ = 0.0; } // Fix the speed by the actual RPM we are asking, because of rounding errors we cannot get all RPM values, but we have a lot more resolution in the feedrate value. // (Trick copied from KISSlicer, thanks Jonathan) @@ -901,49 +901,49 @@ void GCodeExport::writeMoveBFB(const int x, const int y, const int z, const Velo // Increase the extrusion amount to calculate the amount of filament used. Point3 diff = Point3(x, y, z) - getPosition(); - current_e_value += extrusion_per_mm * diff.vSizeMM(); + current_e_value_ += extrusion_per_mm * diff.vSizeMM(); } else { // If we are not extruding, check if we still need to disable the extruder. This causes a retraction due to auto-retraction. - if (! extruder_attr[current_extruder].retraction_e_amount_current) + if (! extruder_attr_[current_extruder_].retraction_e_amount_current_) { - *output_stream << "M103" << new_line; - extruder_attr[current_extruder].retraction_e_amount_current + *output_stream_ << "M103" << new_line_; + extruder_attr_[current_extruder_].retraction_e_amount_current_ = 1.0; // 1.0 used as stub; BFB doesn't use the actual retraction amount; it performs retraction on the firmware automatically } } - *output_stream << "G1 X" << MMtoStream{ gcode_pos.X } << " Y" << MMtoStream{ gcode_pos.Y } << " Z" << MMtoStream{ z }; - *output_stream << " F" << PrecisionedDouble{ 1, fspeed } << new_line; + *output_stream_ << "G1 X" << MMtoStream{ gcode_pos.X } << " Y" << MMtoStream{ gcode_pos.Y } << " Z" << MMtoStream{ z }; + *output_stream_ << " F" << PrecisionedDouble{ 1, fspeed } << new_line_; - currentPosition = Point3(x, y, z); - estimateCalculator.plan( - TimeEstimateCalculator::Position(INT2MM(currentPosition.x_), INT2MM(currentPosition.y_), INT2MM(currentPosition.z_), eToMm(current_e_value)), + current_position_ = Point3(x, y, z); + estimate_calculator_.plan( + TimeEstimateCalculator::Position(INT2MM(current_position_.x_), INT2MM(current_position_.y_), INT2MM(current_position_.z_), eToMm(current_e_value_)), speed, feature); } void GCodeExport::writeTravel(const coord_t x, const coord_t y, const coord_t z, const Velocity& speed) { - if (currentPosition.x_ == x && currentPosition.y_ == y && currentPosition.z_ == z) + if (current_position_.x_ == x && current_position_.y_ == y && current_position_.z_ == z) { return; } #ifdef ASSERT_INSANE_OUTPUT assert(speed < 1000 && speed > 1); // normal F values occurring in UM2 gcode (this code should not be compiled for release) - assert(currentPosition != no_point3); + assert(current_position_ != no_point3); assert(Point3(x, y, z) != no_point3); - assert((Point3(x, y, z) - currentPosition).vSize() < MM2INT(1000)); // no crazy positions (this code should not be compiled for release) + assert((Point3(x, y, z) - current_position_).vSize() < MM2INT(1000)); // no crazy positions (this code should not be compiled for release) #endif // ASSERT_INSANE_OUTPUT - const PrintFeatureType travel_move_type = extruder_attr[current_extruder].retraction_e_amount_current ? PrintFeatureType::MoveRetraction : PrintFeatureType::MoveCombing; - const int display_width = extruder_attr[current_extruder].retraction_e_amount_current ? MM2INT(0.2) : MM2INT(0.1); + const PrintFeatureType travel_move_type = extruder_attr_[current_extruder_].retraction_e_amount_current_ ? PrintFeatureType::MoveRetraction : PrintFeatureType::MoveCombing; + const int display_width = extruder_attr_[current_extruder_].retraction_e_amount_current_ ? MM2INT(0.2) : MM2INT(0.1); const double layer_height = Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("layer_height"); Application::getInstance().communication_->sendLineTo(travel_move_type, Point(x, y), display_width, layer_height, speed); - *output_stream << "G0"; - writeFXYZE(speed, x, y, z, current_e_value, travel_move_type); + *output_stream_ << "G0"; + writeFXYZE(speed, x, y, z, current_e_value_, travel_move_type); } void GCodeExport::writeExtrusion( @@ -955,16 +955,16 @@ void GCodeExport::writeExtrusion( const PrintFeatureType& feature, const bool update_extrusion_offset) { - if (currentPosition.x_ == x && currentPosition.y_ == y && currentPosition.z_ == z) + if (current_position_.x_ == x && current_position_.y_ == y && current_position_.z_ == z) { return; } #ifdef ASSERT_INSANE_OUTPUT assert(speed < 1000 && speed > 1); // normal F values occurring in UM2 gcode (this code should not be compiled for release) - assert(currentPosition != no_point3); + assert(current_position_ != no_point3); assert(Point3(x, y, z) != no_point3); - assert((Point3(x, y, z) - currentPosition).vSize() < MM2INT(1000)); // no crazy positions (this code should not be compiled for release) + assert((Point3(x, y, z) - current_position_).vSize() < MM2INT(1000)); // no crazy positions (this code should not be compiled for release) assert(extrusion_mm3_per_mm >= 0.0); #endif // ASSERT_INSANE_OUTPUT #ifdef DEBUG @@ -990,12 +990,12 @@ void GCodeExport::writeExtrusion( const double extrusion_per_mm = mm3ToE(extrusion_mm3_per_mm); - if (is_z_hopped > 0) + if (is_z_hopped_ > 0) { writeZhopEnd(); } - const Point3 diff = Point3(x, y, z) - currentPosition; + const Point3 diff = Point3(x, y, z) - current_position_; const double diff_length = diff.vSizeMM(); writeUnretractionAndPrime(); @@ -1004,134 +1004,134 @@ void GCodeExport::writeExtrusion( double extrusion_offset = 0; if (diff_length) { - extrusion_offset = speed * extrusion_mm3_per_mm * extrusion_offset_factor; - if (extrusion_offset > max_extrusion_offset) + extrusion_offset = speed * extrusion_mm3_per_mm * extrusion_offset_factor_; + if (extrusion_offset > max_extrusion_offset_) { - extrusion_offset = max_extrusion_offset; + extrusion_offset = max_extrusion_offset_; } } // write new value of extrusion_offset, which will be remembered. - if (update_extrusion_offset && (extrusion_offset != current_e_offset)) + if (update_extrusion_offset && (extrusion_offset != current_e_offset_)) { - current_e_offset = extrusion_offset; - *output_stream << ";FLOW_RATE_COMPENSATED_OFFSET = " << current_e_offset << new_line; + current_e_offset_ = extrusion_offset; + *output_stream_ << ";FLOW_RATE_COMPENSATED_OFFSET = " << current_e_offset_ << new_line_; } - extruder_attr[current_extruder].last_e_value_after_wipe += extrusion_per_mm * diff_length; - const double new_e_value = current_e_value + extrusion_per_mm * diff_length; + extruder_attr_[current_extruder_].last_e_value_after_wipe_ += extrusion_per_mm * diff_length; + const double new_e_value = current_e_value_ + extrusion_per_mm * diff_length; - *output_stream << "G1"; + *output_stream_ << "G1"; writeFXYZE(speed, x, y, z, new_e_value, feature); } void GCodeExport::writeFXYZE(const Velocity& speed, const coord_t x, const coord_t y, const coord_t z, const double e, const PrintFeatureType& feature) { - if (currentSpeed != speed) + if (current_speed_ != speed) { - *output_stream << " F" << PrecisionedDouble{ 1, speed * 60 }; - currentSpeed = speed; + *output_stream_ << " F" << PrecisionedDouble{ 1, speed * 60 }; + current_speed_ = speed; } - Point gcode_pos = getGcodePos(x, y, current_extruder); - total_bounding_box.include(Point3(gcode_pos.X, gcode_pos.Y, z)); + Point gcode_pos = getGcodePos(x, y, current_extruder_); + total_bounding_box_.include(Point3(gcode_pos.X, gcode_pos.Y, z)); - *output_stream << " X" << MMtoStream{ gcode_pos.X } << " Y" << MMtoStream{ gcode_pos.Y }; - if (z != currentPosition.z_) + *output_stream_ << " X" << MMtoStream{ gcode_pos.X } << " Y" << MMtoStream{ gcode_pos.Y }; + if (z != current_position_.z_) { - *output_stream << " Z" << MMtoStream{ z }; + *output_stream_ << " Z" << MMtoStream{ z }; } - if (e + current_e_offset != current_e_value) + if (e + current_e_offset_ != current_e_value_) { - const double output_e = (relative_extrusion) ? e + current_e_offset - current_e_value : e + current_e_offset; - *output_stream << " " << extruder_attr[current_extruder].extruderCharacter << PrecisionedDouble{ 5, output_e }; + const double output_e = (relative_extrusion_) ? e + current_e_offset_ - current_e_value_ : e + current_e_offset_; + *output_stream_ << " " << extruder_attr_[current_extruder_].extruder_character_ << PrecisionedDouble{ 5, output_e }; } - *output_stream << new_line; + *output_stream_ << new_line_; - currentPosition = Point3(x, y, z); - current_e_value = e; - estimateCalculator.plan(TimeEstimateCalculator::Position(INT2MM(x), INT2MM(y), INT2MM(z), eToMm(e)), speed, feature); + current_position_ = Point3(x, y, z); + current_e_value_ = e; + estimate_calculator_.plan(TimeEstimateCalculator::Position(INT2MM(x), INT2MM(y), INT2MM(z), eToMm(e)), speed, feature); } void GCodeExport::writeUnretractionAndPrime() { - const double prime_volume = extruder_attr[current_extruder].prime_volume; + const double prime_volume = extruder_attr_[current_extruder_].prime_volume_; const double prime_volume_e = mm3ToE(prime_volume); - current_e_value += prime_volume_e; - if (extruder_attr[current_extruder].retraction_e_amount_current) + current_e_value_ += prime_volume_e; + if (extruder_attr_[current_extruder_].retraction_e_amount_current_) { - if (extruder_attr[current_extruder].machine_firmware_retract) + if (extruder_attr_[current_extruder_].machine_firmware_retract_) { // note that BFB is handled differently - *output_stream << "G11" << new_line; + *output_stream_ << "G11" << new_line_; // Assume default UM2 retraction settings. if (prime_volume != 0) { - const double output_e = (relative_extrusion) ? prime_volume_e : current_e_value; - *output_stream << "G1 F" << PrecisionedDouble{ 1, extruder_attr[current_extruder].last_retraction_prime_speed * 60 } << " " - << extruder_attr[current_extruder].extruderCharacter << PrecisionedDouble{ 5, output_e } << new_line; - currentSpeed = extruder_attr[current_extruder].last_retraction_prime_speed; + const double output_e = (relative_extrusion_) ? prime_volume_e : current_e_value_; + *output_stream_ << "G1 F" << PrecisionedDouble{ 1, extruder_attr_[current_extruder_].last_retraction_prime_speed_ * 60 } << " " + << extruder_attr_[current_extruder_].extruder_character_ << PrecisionedDouble{ 5, output_e } << new_line_; + current_speed_ = extruder_attr_[current_extruder_].last_retraction_prime_speed_; } - estimateCalculator.plan( - TimeEstimateCalculator::Position(INT2MM(currentPosition.x_), INT2MM(currentPosition.y_), INT2MM(currentPosition.z_), eToMm(current_e_value)), + estimate_calculator_.plan( + TimeEstimateCalculator::Position(INT2MM(current_position_.x_), INT2MM(current_position_.y_), INT2MM(current_position_.z_), eToMm(current_e_value_)), 25.0, PrintFeatureType::MoveRetraction); } else { - current_e_value += extruder_attr[current_extruder].retraction_e_amount_current; - const double output_e = (relative_extrusion) ? extruder_attr[current_extruder].retraction_e_amount_current + prime_volume_e : current_e_value; - *output_stream << "G1 F" << PrecisionedDouble{ 1, extruder_attr[current_extruder].last_retraction_prime_speed * 60 } << " " - << extruder_attr[current_extruder].extruderCharacter << PrecisionedDouble{ 5, output_e } << new_line; - currentSpeed = extruder_attr[current_extruder].last_retraction_prime_speed; - estimateCalculator.plan( - TimeEstimateCalculator::Position(INT2MM(currentPosition.x_), INT2MM(currentPosition.y_), INT2MM(currentPosition.z_), eToMm(current_e_value)), - currentSpeed, + current_e_value_ += extruder_attr_[current_extruder_].retraction_e_amount_current_; + const double output_e = (relative_extrusion_) ? extruder_attr_[current_extruder_].retraction_e_amount_current_ + prime_volume_e : current_e_value_; + *output_stream_ << "G1 F" << PrecisionedDouble{ 1, extruder_attr_[current_extruder_].last_retraction_prime_speed_ * 60 } << " " + << extruder_attr_[current_extruder_].extruder_character_ << PrecisionedDouble{ 5, output_e } << new_line_; + current_speed_ = extruder_attr_[current_extruder_].last_retraction_prime_speed_; + estimate_calculator_.plan( + TimeEstimateCalculator::Position(INT2MM(current_position_.x_), INT2MM(current_position_.y_), INT2MM(current_position_.z_), eToMm(current_e_value_)), + current_speed_, PrintFeatureType::MoveRetraction); } } else if (prime_volume != 0.0) { - const double output_e = (relative_extrusion) ? prime_volume_e : current_e_value; - *output_stream << "G1 F" << PrecisionedDouble{ 1, extruder_attr[current_extruder].last_retraction_prime_speed * 60 } << " " - << extruder_attr[current_extruder].extruderCharacter; - *output_stream << PrecisionedDouble{ 5, output_e } << new_line; - currentSpeed = extruder_attr[current_extruder].last_retraction_prime_speed; - estimateCalculator.plan( - TimeEstimateCalculator::Position(INT2MM(currentPosition.x_), INT2MM(currentPosition.y_), INT2MM(currentPosition.z_), eToMm(current_e_value)), - currentSpeed, + const double output_e = (relative_extrusion_) ? prime_volume_e : current_e_value_; + *output_stream_ << "G1 F" << PrecisionedDouble{ 1, extruder_attr_[current_extruder_].last_retraction_prime_speed_ * 60 } << " " + << extruder_attr_[current_extruder_].extruder_character_; + *output_stream_ << PrecisionedDouble{ 5, output_e } << new_line_; + current_speed_ = extruder_attr_[current_extruder_].last_retraction_prime_speed_; + estimate_calculator_.plan( + TimeEstimateCalculator::Position(INT2MM(current_position_.x_), INT2MM(current_position_.y_), INT2MM(current_position_.z_), eToMm(current_e_value_)), + current_speed_, PrintFeatureType::NoneType); } - extruder_attr[current_extruder].prime_volume = 0.0; + extruder_attr_[current_extruder_].prime_volume_ = 0.0; - if (getCurrentExtrudedVolume() > 10000.0 && flavor != EGCodeFlavor::BFB - && flavor != EGCodeFlavor::MAKERBOT) // According to https://github.com/Ultimaker/CuraEngine/issues/14 having more then 21m of extrusion causes inaccuracies. So reset it - // every 10m, just to be sure. + if (getCurrentExtrudedVolume() > 10000.0 && flavor_ != EGCodeFlavor::BFB + && flavor_ != EGCodeFlavor::MAKERBOT) // According to https://github.com/Ultimaker/CuraEngine/issues/14 having more then 21m of extrusion causes inaccuracies. So reset it + // every 10m, just to be sure. { resetExtrusionValue(); } - if (extruder_attr[current_extruder].retraction_e_amount_current) + if (extruder_attr_[current_extruder_].retraction_e_amount_current_) { - extruder_attr[current_extruder].retraction_e_amount_current = 0.0; + extruder_attr_[current_extruder_].retraction_e_amount_current_ = 0.0; } } void GCodeExport::writeRetraction(const RetractionConfig& config, bool force, bool extruder_switch) { - ExtruderTrainAttributes& extr_attr = extruder_attr[current_extruder]; + ExtruderTrainAttributes& extr_attr = extruder_attr_[current_extruder_]; - if (flavor == EGCodeFlavor::BFB) // BitsFromBytes does automatic retraction. + if (flavor_ == EGCodeFlavor::BFB) // BitsFromBytes does automatic retraction. { if (extruder_switch) { - if (! extr_attr.retraction_e_amount_current) + if (! extr_attr.retraction_e_amount_current_) { - *output_stream << "M103" << new_line; + *output_stream_ << "M103" << new_line_; } - extr_attr.retraction_e_amount_current = 1.0; // 1.0 is a stub; BFB doesn't use the actual retracted amount; retraction is performed by firmware + extr_attr.retraction_e_amount_current_ = 1.0; // 1.0 is a stub; BFB doesn't use the actual retracted amount; retraction is performed by firmware } return; } - double old_retraction_e_amount = extr_attr.retraction_e_amount_current; + double old_retraction_e_amount = extr_attr.retraction_e_amount_current_; double new_retraction_e_amount = mmToE(config.distance); double retraction_diff_e_amount = old_retraction_e_amount - new_retraction_e_amount; if (std::abs(retraction_diff_e_amount) < 0.000001) @@ -1141,7 +1141,7 @@ void GCodeExport::writeRetraction(const RetractionConfig& config, bool force, bo { // handle retraction limitation double current_extruded_volume = getCurrentExtrudedVolume(); - std::deque& extruded_volume_at_previous_n_retractions = extr_attr.extruded_volume_at_previous_n_retractions; + std::deque& extruded_volume_at_previous_n_retractions = extr_attr.extruded_volume_at_previous_n_retractions_; while (extruded_volume_at_previous_n_retractions.size() > config.retraction_count_max && ! extruded_volume_at_previous_n_retractions.empty()) { // extruder switch could have introduced data which falls outside the retraction window @@ -1153,7 +1153,7 @@ void GCodeExport::writeRetraction(const RetractionConfig& config, bool force, bo return; } if (! force && extruded_volume_at_previous_n_retractions.size() == config.retraction_count_max - && current_extruded_volume < extruded_volume_at_previous_n_retractions.back() + config.retraction_extrusion_window * extr_attr.filament_area) + && current_extruded_volume < extruded_volume_at_previous_n_retractions.back() + config.retraction_extrusion_window * extr_attr.filament_area_) { return; } @@ -1164,40 +1164,44 @@ void GCodeExport::writeRetraction(const RetractionConfig& config, bool force, bo } } - if (extruder_attr[current_extruder].machine_firmware_retract) + if (extruder_attr_[current_extruder_].machine_firmware_retract_) { - if (extruder_switch && extr_attr.retraction_e_amount_current) + if (extruder_switch && extr_attr.retraction_e_amount_current_) { return; } - *output_stream << "G10"; - if (extruder_switch && flavor == EGCodeFlavor::REPETIER) + *output_stream_ << "G10"; + if (extruder_switch && flavor_ == EGCodeFlavor::REPETIER) { - *output_stream << " S1"; + *output_stream_ << " S1"; } - *output_stream << new_line; + *output_stream_ << new_line_; // Assume default UM2 retraction settings. - estimateCalculator.plan( - TimeEstimateCalculator::Position(INT2MM(currentPosition.x_), INT2MM(currentPosition.y_), INT2MM(currentPosition.z_), eToMm(current_e_value + retraction_diff_e_amount)), + estimate_calculator_.plan( + TimeEstimateCalculator::Position( + INT2MM(current_position_.x_), + INT2MM(current_position_.y_), + INT2MM(current_position_.z_), + eToMm(current_e_value_ + retraction_diff_e_amount)), 25.0, PrintFeatureType::MoveRetraction); // TODO: hardcoded values! } else { - double speed = ((retraction_diff_e_amount < 0.0) ? config.speed : extr_attr.last_retraction_prime_speed); - current_e_value += retraction_diff_e_amount; - const double output_e = (relative_extrusion) ? retraction_diff_e_amount : current_e_value; - *output_stream << "G1 F" << PrecisionedDouble{ 1, speed * 60 } << " " << extr_attr.extruderCharacter << PrecisionedDouble{ 5, output_e } << new_line; - currentSpeed = speed; - estimateCalculator.plan( - TimeEstimateCalculator::Position(INT2MM(currentPosition.x_), INT2MM(currentPosition.y_), INT2MM(currentPosition.z_), eToMm(current_e_value)), - currentSpeed, + double speed = ((retraction_diff_e_amount < 0.0) ? config.speed : extr_attr.last_retraction_prime_speed_); + current_e_value_ += retraction_diff_e_amount; + const double output_e = (relative_extrusion_) ? retraction_diff_e_amount : current_e_value_; + *output_stream_ << "G1 F" << PrecisionedDouble{ 1, speed * 60 } << " " << extr_attr.extruder_character_ << PrecisionedDouble{ 5, output_e } << new_line_; + current_speed_ = speed; + estimate_calculator_.plan( + TimeEstimateCalculator::Position(INT2MM(current_position_.x_), INT2MM(current_position_.y_), INT2MM(current_position_.z_), eToMm(current_e_value_)), + current_speed_, PrintFeatureType::MoveRetraction); - extr_attr.last_retraction_prime_speed = config.primeSpeed; + extr_attr.last_retraction_prime_speed_ = config.primeSpeed; } - extr_attr.retraction_e_amount_current = new_retraction_e_amount; // suppose that for UM2 the retraction amount in the firmware is equal to the provided amount - extr_attr.prime_volume += config.prime_volume; + extr_attr.retraction_e_amount_current_ = new_retraction_e_amount; // suppose that for UM2 the retraction amount in the firmware is equal to the provided amount + extr_attr.prime_volume_ += config.prime_volume; } void GCodeExport::writeZhopStart(const coord_t hop_height, Velocity speed /*= 0*/) @@ -1206,50 +1210,50 @@ void GCodeExport::writeZhopStart(const coord_t hop_height, Velocity speed /*= 0* { if (speed == 0) { - const ExtruderTrain& extruder = Application::getInstance().current_slice_->scene.extruders[current_extruder]; + const ExtruderTrain& extruder = Application::getInstance().current_slice_->scene.extruders[current_extruder_]; speed = extruder.settings_.get("speed_z_hop"); } - is_z_hopped = hop_height; - currentSpeed = speed; - *output_stream << "G1 F" << PrecisionedDouble{ 1, speed * 60 } << " Z" << MMtoStream{ current_layer_z + is_z_hopped } << new_line; - total_bounding_box.includeZ(current_layer_z + is_z_hopped); + is_z_hopped_ = hop_height; + current_speed_ = speed; + *output_stream_ << "G1 F" << PrecisionedDouble{ 1, speed * 60 } << " Z" << MMtoStream{ current_layer_z_ + is_z_hopped_ } << new_line_; + total_bounding_box_.includeZ(current_layer_z_ + is_z_hopped_); assert(speed > 0.0 && "Z hop speed should be positive."); } } void GCodeExport::writeZhopEnd(Velocity speed /*= 0*/) { - if (is_z_hopped) + if (is_z_hopped_) { if (speed == 0) { - const ExtruderTrain& extruder = Application::getInstance().current_slice_->scene.extruders[current_extruder]; + const ExtruderTrain& extruder = Application::getInstance().current_slice_->scene.extruders[current_extruder_]; speed = extruder.settings_.get("speed_z_hop"); } - is_z_hopped = 0; - currentPosition.z_ = current_layer_z; - currentSpeed = speed; - *output_stream << "G1 F" << PrecisionedDouble{ 1, speed * 60 } << " Z" << MMtoStream{ current_layer_z } << new_line; + is_z_hopped_ = 0; + current_position_.z_ = current_layer_z_; + current_speed_ = speed; + *output_stream_ << "G1 F" << PrecisionedDouble{ 1, speed * 60 } << " Z" << MMtoStream{ current_layer_z_ } << new_line_; assert(speed > 0.0 && "Z hop speed should be positive."); } } void GCodeExport::startExtruder(const size_t new_extruder) { - extruder_attr[new_extruder].is_used = true; - if (new_extruder != current_extruder) // wouldn't be the case on the very first extruder start if it's extruder 0 + extruder_attr_[new_extruder].is_used_ = true; + if (new_extruder != current_extruder_) // wouldn't be the case on the very first extruder start if it's extruder 0 { - if (flavor == EGCodeFlavor::MAKERBOT) + if (flavor_ == EGCodeFlavor::MAKERBOT) { - *output_stream << "M135 T" << new_extruder << new_line; + *output_stream_ << "M135 T" << new_extruder << new_line_; } else { - *output_stream << "T" << new_extruder << new_line; + *output_stream_ << "T" << new_extruder << new_line_; } } - current_extruder = new_extruder; + current_extruder_ = new_extruder; assert(getCurrentExtrudedVolume() == 0.0 && "Just after an extruder switch we haven't extruded anything yet!"); resetExtrusionValue(); // zero the E value on the new extruder, just to be sure @@ -1258,14 +1262,14 @@ void GCodeExport::startExtruder(const size_t new_extruder) if (! start_code.empty()) { - if (relative_extrusion) + if (relative_extrusion_) { writeExtrusionMode(false); // ensure absolute extrusion mode is set before the start gcode } writeCode(start_code.c_str()); - if (relative_extrusion) + if (relative_extrusion_) { writeExtrusionMode(true); // restore relative extrusion mode } @@ -1275,19 +1279,19 @@ void GCodeExport::startExtruder(const size_t new_extruder) Application::getInstance().communication_->sendCurrentPosition(getPositionXY()); // Change the Z position so it gets re-written again. We do not know if the switch code modified the Z position. - currentPosition.z_ += 1; + current_position_.z_ += 1; setExtruderFanNumber(new_extruder); } void GCodeExport::switchExtruder(size_t new_extruder, const RetractionConfig& retraction_config_old_extruder, coord_t perform_z_hop /*= 0*/) { - if (current_extruder == new_extruder) + if (current_extruder_ == new_extruder) { return; } - const Settings& old_extruder_settings = Application::getInstance().current_slice_->scene.extruders[current_extruder].settings_; + const Settings& old_extruder_settings = Application::getInstance().current_slice_->scene.extruders[current_extruder_].settings_; if (old_extruder_settings.get("retraction_enable")) { constexpr bool force = true; @@ -1306,14 +1310,14 @@ void GCodeExport::switchExtruder(size_t new_extruder, const RetractionConfig& re if (! end_code.empty()) { - if (relative_extrusion) + if (relative_extrusion_) { writeExtrusionMode(false); // ensure absolute extrusion mode is set before the end gcode } writeCode(end_code.c_str()); - if (relative_extrusion) + if (relative_extrusion_) { writeExtrusionMode(true); // restore relative extrusion mode } @@ -1324,23 +1328,23 @@ void GCodeExport::switchExtruder(size_t new_extruder, const RetractionConfig& re void GCodeExport::writeCode(const char* str) { - *output_stream << str << new_line; + *output_stream_ << str << new_line_; } void GCodeExport::resetExtruderToPrimed(const size_t extruder, const double initial_retraction) { - extruder_attr[extruder].is_primed = true; + extruder_attr_[extruder].is_primed_ = true; - extruder_attr[extruder].retraction_e_amount_current = initial_retraction; + extruder_attr_[extruder].retraction_e_amount_current_ = initial_retraction; } void GCodeExport::writePrimeTrain(const Velocity& travel_speed) { - if (extruder_attr[current_extruder].is_primed) + if (extruder_attr_[current_extruder_].is_primed_) { // extruder is already primed once! return; } - const Settings& extruder_settings = Application::getInstance().current_slice_->scene.extruders[current_extruder].settings_; + const Settings& extruder_settings = Application::getInstance().current_slice_->scene.extruders[current_extruder_].settings_; if (extruder_settings.get("prime_blob_enable")) { // only move to prime position if we do a blob/poop // ideally the prime position would be respected whether we do a blob or not, @@ -1353,12 +1357,12 @@ void GCodeExport::writePrimeTrain(const Velocity& travel_speed) if (! extruder_settings.get("extruder_prime_pos_abs")) { // currentPosition.z can be already z hopped - prime_pos += Point3(currentPosition.x_, currentPosition.y_, current_layer_z); + prime_pos += Point3(current_position_.x_, current_position_.y_, current_layer_z_); } writeTravel(prime_pos, travel_speed); } - if (flavor == EGCodeFlavor::GRIFFIN) + if (flavor_ == EGCodeFlavor::GRIFFIN) { bool should_correct_z = false; @@ -1368,7 +1372,7 @@ void GCodeExport::writePrimeTrain(const Velocity& travel_speed) command += " S1"; // use S1 to disable prime blob should_correct_z = true; } - *output_stream << command << new_line; + *output_stream_ << command << new_line_; // There was an issue with the S1 strategy parameter, where it would only change the material-position, // as opposed to 'be a prime-blob maneuvre without actually printing the prime blob', as we assumed here. @@ -1378,7 +1382,7 @@ void GCodeExport::writePrimeTrain(const Velocity& travel_speed) { // Can't output via 'writeTravel', since if this is needed, the value saved for 'current height' will not be correct. // For similar reasons, this isn't written to the front-end via command-socket. - *output_stream << "G0 Z" << MMtoStream{ getPositionZ() } << new_line; + *output_stream_ << "G0 Z" << MMtoStream{ getPositionZ() } << new_line_; } } else @@ -1386,56 +1390,56 @@ void GCodeExport::writePrimeTrain(const Velocity& travel_speed) // there is no prime gcode for other firmware versions... } - extruder_attr[current_extruder].is_primed = true; + extruder_attr_[current_extruder_].is_primed_ = true; } void GCodeExport::setExtruderFanNumber(int extruder) { - if (extruder_attr[extruder].fan_number != fan_number) + if (extruder_attr_[extruder].fan_number_ != fan_number_) { - fan_number = extruder_attr[extruder].fan_number; - current_fan_speed = -1; // ensure fan speed gcode gets output for this fan + fan_number_ = extruder_attr_[extruder].fan_number_; + current_fan_speed_ = -1; // ensure fan speed gcode gets output for this fan } } void GCodeExport::writeFanCommand(double speed) { - if (std::abs(current_fan_speed - speed) < 0.1) + if (std::abs(current_fan_speed_ - speed) < 0.1) { return; } - if (flavor == EGCodeFlavor::MAKERBOT) + if (flavor_ == EGCodeFlavor::MAKERBOT) { if (speed >= 50) { - *output_stream << "M126 T0" << new_line; // Makerbot cannot PWM the fan speed... + *output_stream_ << "M126 T0" << new_line_; // Makerbot cannot PWM the fan speed... } else { - *output_stream << "M127 T0" << new_line; + *output_stream_ << "M127 T0" << new_line_; } } else if (speed > 0) { const bool should_scale_zero_to_one = Application::getInstance().current_slice_->scene.settings.get("machine_scale_fan_speed_zero_to_one"); - *output_stream << "M106 S" << PrecisionedDouble{ (should_scale_zero_to_one ? 2u : 1u), (should_scale_zero_to_one ? speed : speed * 255) / 100 }; - if (fan_number) + *output_stream_ << "M106 S" << PrecisionedDouble{ (should_scale_zero_to_one ? 2u : 1u), (should_scale_zero_to_one ? speed : speed * 255) / 100 }; + if (fan_number_) { - *output_stream << " P" << fan_number; + *output_stream_ << " P" << fan_number_; } - *output_stream << new_line; + *output_stream_ << new_line_; } else { - *output_stream << "M107"; - if (fan_number) + *output_stream_ << "M107"; + if (fan_number_) { - *output_stream << " P" << fan_number; + *output_stream_ << " P" << fan_number_; } - *output_stream << new_line; + *output_stream_ << new_line_; } - current_fan_speed = speed; + current_fan_speed_ = speed; } void GCodeExport::writeTemperatureCommand(const size_t extruder, const Temperature& temperature, const bool wait) @@ -1450,7 +1454,7 @@ void GCodeExport::writeTemperatureCommand(const size_t extruder, const Temperatu if (extruder_train.settings_.get("machine_extruders_share_heater")) { // extruders share a single heater - if (extruder != current_extruder) + if (extruder != current_extruder_) { // ignore all changes to the non-current extruder return; @@ -1465,101 +1469,101 @@ void GCodeExport::writeTemperatureCommand(const size_t extruder, const Temperatu { // only reset the other extruders' waited_for_temperature state when the new temperature // is greater than the old temperature - if (wait || temperature > extruder_attr[extruder_nr].currentTemperature) + if (wait || temperature > extruder_attr_[extruder_nr].current_temperature_) { - extruder_attr[extruder_nr].waited_for_temperature = wait; + extruder_attr_[extruder_nr].waited_for_temperature_ = wait; } - extruder_attr[extruder_nr].currentTemperature = temperature; + extruder_attr_[extruder_nr].current_temperature_ = temperature; } } } - if ((! wait || extruder_attr[extruder].waited_for_temperature) && extruder_attr[extruder].currentTemperature == temperature) + if ((! wait || extruder_attr_[extruder].waited_for_temperature_) && extruder_attr_[extruder].current_temperature_ == temperature) { return; } - if (wait && flavor != EGCodeFlavor::MAKERBOT) + if (wait && flavor_ != EGCodeFlavor::MAKERBOT) { - if (flavor == EGCodeFlavor::MARLIN) + if (flavor_ == EGCodeFlavor::MARLIN) { - *output_stream << "M105" << new_line; // get temperatures from the last update, the M109 will not let get the target temperature + *output_stream_ << "M105" << new_line_; // get temperatures from the last update, the M109 will not let get the target temperature } - *output_stream << "M109"; - extruder_attr[extruder].waited_for_temperature = true; + *output_stream_ << "M109"; + extruder_attr_[extruder].waited_for_temperature_ = true; } else { - *output_stream << "M104"; - extruder_attr[extruder].waited_for_temperature = false; + *output_stream_ << "M104"; + extruder_attr_[extruder].waited_for_temperature_ = false; } - if (extruder != current_extruder) + if (extruder != current_extruder_) { - *output_stream << " T" << extruder; + *output_stream_ << " T" << extruder; } #ifdef ASSERT_INSANE_OUTPUT assert(temperature >= 0); #endif // ASSERT_INSANE_OUTPUT - *output_stream << " S" << PrecisionedDouble{ 1, temperature } << new_line; - if (extruder != current_extruder && always_write_active_tool) + *output_stream_ << " S" << PrecisionedDouble{ 1, temperature } << new_line_; + if (extruder != current_extruder_ && always_write_active_tool_) { // Some firmwares (ie Smoothieware) change tools every time a "T" command is read - even on a M104 line, so we need to switch back to the active tool. - *output_stream << "T" << current_extruder << new_line; + *output_stream_ << "T" << current_extruder_ << new_line_; } - if (wait && flavor == EGCodeFlavor::MAKERBOT) + if (wait && flavor_ == EGCodeFlavor::MAKERBOT) { // Makerbot doesn't use M109 for heat-and-wait. Instead, use M104 and then wait using M116. - *output_stream << "M116" << new_line; + *output_stream_ << "M116" << new_line_; } - extruder_attr[extruder].currentTemperature = temperature; + extruder_attr_[extruder].current_temperature_ = temperature; } void GCodeExport::writeBedTemperatureCommand(const Temperature& temperature, const bool wait) { - if (flavor == EGCodeFlavor::ULTIGCODE) + if (flavor_ == EGCodeFlavor::ULTIGCODE) { // The UM2 family doesn't support temperature commands (they are fixed in the firmware) return; } - if (bed_temperature != temperature) // Not already at the desired temperature. + if (bed_temperature_ != temperature) // Not already at the desired temperature. { if (wait) { - if (flavor == EGCodeFlavor::MARLIN) + if (flavor_ == EGCodeFlavor::MARLIN) { - *output_stream << "M140 S"; // set the temperature, it will be used as target temperature from M105 - *output_stream << PrecisionedDouble{ 1, temperature } << new_line; - *output_stream << "M105" << new_line; + *output_stream_ << "M140 S"; // set the temperature, it will be used as target temperature from M105 + *output_stream_ << PrecisionedDouble{ 1, temperature } << new_line_; + *output_stream_ << "M105" << new_line_; } - *output_stream << "M190 S"; + *output_stream_ << "M190 S"; } else { - *output_stream << "M140 S"; + *output_stream_ << "M140 S"; } - *output_stream << PrecisionedDouble{ 1, temperature } << new_line; + *output_stream_ << PrecisionedDouble{ 1, temperature } << new_line_; - bed_temperature = temperature; + bed_temperature_ = temperature; } } void GCodeExport::writeBuildVolumeTemperatureCommand(const Temperature& temperature, const bool wait) { - if (flavor == EGCodeFlavor::ULTIGCODE || flavor == EGCodeFlavor::GRIFFIN) + if (flavor_ == EGCodeFlavor::ULTIGCODE || flavor_ == EGCodeFlavor::GRIFFIN) { // Ultimaker printers don't support build volume temperature commands. return; } if (wait) { - *output_stream << "M191 S"; + *output_stream_ << "M191 S"; } else { - *output_stream << "M141 S"; + *output_stream_ << "M141 S"; } - *output_stream << PrecisionedDouble{ 1, temperature } << new_line; + *output_stream_ << PrecisionedDouble{ 1, temperature } << new_line_; } void GCodeExport::writePrintAcceleration(const Acceleration& acceleration) @@ -1567,27 +1571,27 @@ void GCodeExport::writePrintAcceleration(const Acceleration& acceleration) switch (getFlavor()) { case EGCodeFlavor::REPETIER: - if (current_print_acceleration != acceleration) + if (current_print_acceleration_ != acceleration) { - *output_stream << "M201 X" << PrecisionedDouble{ 0, acceleration } << " Y" << PrecisionedDouble{ 0, acceleration } << new_line; + *output_stream_ << "M201 X" << PrecisionedDouble{ 0, acceleration } << " Y" << PrecisionedDouble{ 0, acceleration } << new_line_; } break; case EGCodeFlavor::REPRAP: - if (current_print_acceleration != acceleration) + if (current_print_acceleration_ != acceleration) { - *output_stream << "M204 P" << PrecisionedDouble{ 0, acceleration } << new_line; + *output_stream_ << "M204 P" << PrecisionedDouble{ 0, acceleration } << new_line_; } break; default: // MARLIN, etc. only have one acceleration for both print and travel - if (current_print_acceleration != acceleration) + if (current_print_acceleration_ != acceleration) { - *output_stream << "M204 S" << PrecisionedDouble{ 0, acceleration } << new_line; + *output_stream_ << "M204 S" << PrecisionedDouble{ 0, acceleration } << new_line_; } break; } - current_print_acceleration = acceleration; - estimateCalculator.setAcceleration(acceleration); + current_print_acceleration_ = acceleration; + estimate_calculator_.setAcceleration(acceleration); } void GCodeExport::writeTravelAcceleration(const Acceleration& acceleration) @@ -1595,15 +1599,15 @@ void GCodeExport::writeTravelAcceleration(const Acceleration& acceleration) switch (getFlavor()) { case EGCodeFlavor::REPETIER: - if (current_travel_acceleration != acceleration) + if (current_travel_acceleration_ != acceleration) { - *output_stream << "M202 X" << PrecisionedDouble{ 0, acceleration } << " Y" << PrecisionedDouble{ 0, acceleration } << new_line; + *output_stream_ << "M202 X" << PrecisionedDouble{ 0, acceleration } << " Y" << PrecisionedDouble{ 0, acceleration } << new_line_; } break; case EGCodeFlavor::REPRAP: - if (current_travel_acceleration != acceleration) + if (current_travel_acceleration_ != acceleration) { - *output_stream << "M204 T" << PrecisionedDouble{ 0, acceleration } << new_line; + *output_stream_ << "M204 T" << PrecisionedDouble{ 0, acceleration } << new_line_; } break; default: @@ -1611,28 +1615,28 @@ void GCodeExport::writeTravelAcceleration(const Acceleration& acceleration) writePrintAcceleration(acceleration); break; } - current_travel_acceleration = acceleration; - estimateCalculator.setAcceleration(acceleration); + current_travel_acceleration_ = acceleration; + estimate_calculator_.setAcceleration(acceleration); } void GCodeExport::writeJerk(const Velocity& jerk) { - if (current_jerk != jerk) + if (current_jerk_ != jerk) { switch (getFlavor()) { case EGCodeFlavor::REPETIER: - *output_stream << "M207 X" << PrecisionedDouble{ 2, jerk } << new_line; + *output_stream_ << "M207 X" << PrecisionedDouble{ 2, jerk } << new_line_; break; case EGCodeFlavor::REPRAP: - *output_stream << "M566 X" << PrecisionedDouble{ 2, jerk * 60 } << " Y" << PrecisionedDouble{ 2, jerk * 60 } << new_line; + *output_stream_ << "M566 X" << PrecisionedDouble{ 2, jerk * 60 } << " Y" << PrecisionedDouble{ 2, jerk * 60 } << new_line_; break; default: - *output_stream << "M205 X" << PrecisionedDouble{ 2, jerk } << " Y" << PrecisionedDouble{ 2, jerk } << new_line; + *output_stream_ << "M205 X" << PrecisionedDouble{ 2, jerk } << " Y" << PrecisionedDouble{ 2, jerk } << new_line_; break; } - current_jerk = jerk; - estimateCalculator.setMaxXyJerk(jerk); + current_jerk_ = jerk; + estimate_calculator_.setMaxXyJerk(jerk); } } @@ -1648,22 +1652,22 @@ void GCodeExport::finalize(const char* endCode) for (int n = 1; n < MAX_EXTRUDERS; n++) if (getTotalFilamentUsed(n) > 0) spdlog::info("Filament {}: {}", n + 1, int(getTotalFilamentUsed(n))); - output_stream->flush(); + output_stream_->flush(); } double GCodeExport::getExtrudedVolumeAfterLastWipe(size_t extruder) { - return eToMm3(extruder_attr[extruder].last_e_value_after_wipe, extruder); + return eToMm3(extruder_attr_[extruder].last_e_value_after_wipe_, extruder); } void GCodeExport::ResetLastEValueAfterWipe(size_t extruder) { - extruder_attr[extruder].last_e_value_after_wipe = 0; + extruder_attr_[extruder].last_e_value_after_wipe_ = 0; } void GCodeExport::insertWipeScript(const WipeScriptConfig& wipe_config) { - const Point3 prev_position = currentPosition; + const Point3 prev_position = current_position_; writeComment("WIPE_SCRIPT_BEGIN"); if (wipe_config.retraction_enable) @@ -1676,11 +1680,11 @@ void GCodeExport::insertWipeScript(const WipeScriptConfig& wipe_config) writeZhopStart(wipe_config.hop_amount, wipe_config.hop_speed); } - writeTravel(Point(wipe_config.brush_pos_x, currentPosition.y_), wipe_config.move_speed); + writeTravel(Point(wipe_config.brush_pos_x, current_position_.y_), wipe_config.move_speed); for (size_t i = 0; i < wipe_config.repeat_count; ++i) { - coord_t x = currentPosition.x_ + (i % 2 ? -wipe_config.move_distance : wipe_config.move_distance); - writeTravel(Point(x, currentPosition.y_), wipe_config.move_speed); + coord_t x = current_position_.x_ + (i % 2 ? -wipe_config.move_distance : wipe_config.move_distance); + writeTravel(Point(x, current_position_.y_), wipe_config.move_speed); } writeTravel(prev_position, wipe_config.move_speed); diff --git a/src/infill.cpp b/src/infill.cpp index 39e3342b50..6c7f5e80dc 100644 --- a/src/infill.cpp +++ b/src/infill.cpp @@ -675,16 +675,20 @@ void Infill::generateLinearBasedInfill( // Then we can later join two crossings together to form lines and still know what polygon line segments that infill line connected to. struct Crossing { + Point coordinate_; + size_t polygon_index_; + size_t vertex_index_; + Crossing(Point coordinate, size_t polygon_index, size_t vertex_index) - : coordinate(coordinate) - , polygon_index(polygon_index) - , vertex_index(vertex_index){}; - Point coordinate; - size_t polygon_index; - size_t vertex_index; + : coordinate_(coordinate) + , polygon_index_(polygon_index) + , vertex_index_(vertex_index) + { + } + bool operator<(const Crossing& other) const // Crossings will be ordered by their Y coordinate so that they get ordered along the scanline. { - return coordinate.Y < other.coordinate.Y; + return coordinate_.Y < other.coordinate_.Y; } }; std::vector> crossings_per_scanline; // For each scanline, a list of crossings. @@ -768,17 +772,17 @@ void Infill::generateLinearBasedInfill( const Crossing& first = crossings[crossing_index]; const Crossing& second = crossings[crossing_index + 1]; // Avoid creating zero length crossing lines - const Point unrotated_first = rotation_matrix.unapply(first.coordinate); - const Point unrotated_second = rotation_matrix.unapply(second.coordinate); + const Point unrotated_first = rotation_matrix.unapply(first.coordinate_); + const Point unrotated_second = rotation_matrix.unapply(second.coordinate_); if (unrotated_first == unrotated_second) { continue; } InfillLineSegment* new_segment - = new InfillLineSegment(unrotated_first, first.vertex_index, first.polygon_index, unrotated_second, second.vertex_index, second.polygon_index); + = new InfillLineSegment(unrotated_first, first.vertex_index_, first.polygon_index_, unrotated_second, second.vertex_index_, second.polygon_index_); // Put the same line segment in the data structure twice: Once for each of the polygon line segment that it crosses. - crossings_on_line_[first.polygon_index][first.vertex_index].push_back(new_segment); - crossings_on_line_[second.polygon_index][second.vertex_index].push_back(new_segment); + crossings_on_line_[first.polygon_index_][first.vertex_index_].push_back(new_segment); + crossings_on_line_[second.polygon_index_][second.vertex_index_].push_back(new_segment); } } } diff --git a/src/progress/ProgressStageEstimator.cpp b/src/progress/ProgressStageEstimator.cpp index 667103a046..e587141a0b 100644 --- a/src/progress/ProgressStageEstimator.cpp +++ b/src/progress/ProgressStageEstimator.cpp @@ -9,45 +9,45 @@ namespace cura ProgressStageEstimator::ProgressStageEstimator(std::vector< double >& relative_time_estimates) -: total_estimated_time(0) -, accumulated_estimate(0) -, current_stage_idx(-1) +: total_estimated_time_(0) +, accumulated_estimate_(0) +, current_stage_idx_(-1) { - stages.reserve(relative_time_estimates.size()); + stages_.reserve(relative_time_estimates.size()); for (double relative_estimated_time : relative_time_estimates) { - stages.emplace_back(relative_estimated_time); - total_estimated_time += relative_estimated_time; + stages_.emplace_back(relative_estimated_time); + total_estimated_time_ += relative_estimated_time; } } ProgressStageEstimator::~ProgressStageEstimator() { - for (ProgressStage& stage : stages) + for (ProgressStage& stage : stages_) { - delete stage.stage; + delete stage.stage_; } } double ProgressStageEstimator::progress(int current_step) { - ProgressStage& current_stage = stages[current_stage_idx]; - return (accumulated_estimate + current_stage.stage->progress(current_step) * current_stage.relative_estimated_time) / total_estimated_time; + ProgressStage& current_stage = stages_[current_stage_idx_]; + return (accumulated_estimate_ + current_stage.stage_->progress(current_step) * current_stage.relative_estimated_time_) / total_estimated_time_; } void ProgressStageEstimator::nextStage(ProgressEstimator* stage) { - if (current_stage_idx >= int(stages.size()) - 1) + if (current_stage_idx_ >= int(stages_.size()) - 1) { return; } - if (current_stage_idx >= 0) + if (current_stage_idx_ >= 0) { - ProgressStage& current_stage = stages[current_stage_idx]; - accumulated_estimate += current_stage.relative_estimated_time; + ProgressStage& current_stage = stages_[current_stage_idx_]; + accumulated_estimate_ += current_stage.relative_estimated_time_; } - current_stage_idx++; - stages[current_stage_idx].stage = stage; + current_stage_idx_++; + stages_[current_stage_idx_].stage_ = stage; } diff --git a/src/raft.cpp b/src/raft.cpp index 74325690d0..0bdc72bbfe 100644 --- a/src/raft.cpp +++ b/src/raft.cpp @@ -51,7 +51,7 @@ void Raft::generate(SliceDataStorage& storage) storage.raftOutline = storage.raftOutline.offset(smoothing, ClipperLib::jtRound).offset(-smoothing, ClipperLib::jtRound); // remove small holes and smooth inward corners } - if (storage.primeTower.enabled && ! storage.primeTower.would_have_actual_tower) + if (storage.primeTower.enabled_ && ! storage.primeTower.would_have_actual_tower_) { // Find out if the prime-tower part of the raft still needs to be printed, even if there is no actual tower. // This will only happen if the different raft layers are printed by different extruders. diff --git a/src/skin.cpp b/src/skin.cpp index 19e54f2072..9f1d865dcd 100644 --- a/src/skin.cpp +++ b/src/skin.cpp @@ -34,18 +34,18 @@ coord_t SkinInfillAreaComputation::getSkinLineWidth(const SliceMeshStorage& mesh } SkinInfillAreaComputation::SkinInfillAreaComputation(const LayerIndex& layer_nr, SliceMeshStorage& mesh, bool process_infill) - : layer_nr(layer_nr) - , mesh(mesh) - , bottom_layer_count(mesh.settings.get("bottom_layers")) - , initial_bottom_layer_count(mesh.settings.get("initial_bottom_layers")) - , top_layer_count(mesh.settings.get("top_layers")) - , skin_line_width(getSkinLineWidth(mesh, layer_nr)) - , no_small_gaps_heuristic(mesh.settings.get("skin_no_small_gaps_heuristic")) - , process_infill(process_infill) - , top_skin_preshrink(mesh.settings.get("top_skin_preshrink")) - , bottom_skin_preshrink(mesh.settings.get("bottom_skin_preshrink")) - , top_skin_expand_distance(mesh.settings.get("top_skin_expand_distance")) - , bottom_skin_expand_distance(mesh.settings.get("bottom_skin_expand_distance")) + : layer_nr_(layer_nr) + , mesh_(mesh) + , bottom_layer_count_(mesh.settings.get("bottom_layers")) + , initial_bottom_layer_count_(mesh.settings.get("initial_bottom_layers")) + , top_layer_count_(mesh.settings.get("top_layers")) + , skin_line_width_(getSkinLineWidth(mesh, layer_nr)) + , no_small_gaps_heuristic_(mesh.settings.get("skin_no_small_gaps_heuristic")) + , process_infill_(process_infill) + , top_skin_preshrink_(mesh.settings.get("top_skin_preshrink")) + , bottom_skin_preshrink_(mesh.settings.get("bottom_skin_preshrink")) + , top_skin_expand_distance_(mesh.settings.get("top_skin_expand_distance")) + , bottom_skin_expand_distance_(mesh.settings.get("bottom_skin_expand_distance")) { } @@ -58,11 +58,11 @@ SkinInfillAreaComputation::SkinInfillAreaComputation(const LayerIndex& layer_nr, Polygons SkinInfillAreaComputation::getOutlineOnLayer(const SliceLayerPart& part_here, const LayerIndex layer2_nr) { Polygons result; - if (layer2_nr >= static_cast(mesh.layers.size())) + if (layer2_nr >= static_cast(mesh_.layers.size())) { return result; } - const SliceLayer& layer2 = mesh.layers[layer2_nr]; + const SliceLayer& layer2 = mesh_.layers[layer2_nr]; for (const SliceLayerPart& part2 : layer2.parts) { if (part_here.boundaryBox.hit(part2.boundaryBox)) @@ -86,7 +86,7 @@ void SkinInfillAreaComputation::generateSkinsAndInfill() { generateSkinAndInfillAreas(); - SliceLayer* layer = &mesh.layers[layer_nr]; + SliceLayer* layer = &mesh_.layers[layer_nr_]; for (SliceLayerPart& part : layer->parts) { @@ -104,9 +104,9 @@ void SkinInfillAreaComputation::generateSkinsAndInfill() */ void SkinInfillAreaComputation::generateSkinAndInfillAreas() { - SliceLayer& layer = mesh.layers[layer_nr]; + SliceLayer& layer = mesh_.layers[layer_nr_]; - if (! process_infill && bottom_layer_count == 0 && top_layer_count == 0) + if (! process_infill_ && bottom_layer_count_ == 0 && top_layer_count_ == 0) { return; } @@ -127,12 +127,12 @@ void SkinInfillAreaComputation::generateSkinAndInfillAreas(SliceLayerPart& part) { // Make a copy of the outline which we later intersect and union with the resized skins to ensure the resized skin isn't too large or removed completely. Polygons top_skin; - if (top_layer_count > 0) + if (top_layer_count_ > 0) { top_skin = Polygons(part.inner_area); } Polygons bottom_skin; - if (bottom_layer_count > 0 || layer_nr < LayerIndex(initial_bottom_layer_count)) + if (bottom_layer_count_ > 0 || layer_nr_ < LayerIndex(initial_bottom_layer_count_)) { bottom_skin = Polygons(part.inner_area); } @@ -148,7 +148,7 @@ void SkinInfillAreaComputation::generateSkinAndInfillAreas(SliceLayerPart& part) skin.removeSmallAreas(MIN_AREA_SIZE); // Create infill area irrespective if the infill is to be generated or not(would be used for bridging). part.infill_area = part.inner_area.difference(skin); - if (process_infill) + if (process_infill_) { // process infill when infill density > 0 // or when other infill meshes want to modify this infill generateInfill(part); @@ -169,24 +169,24 @@ void SkinInfillAreaComputation::generateSkinAndInfillAreas(SliceLayerPart& part) */ void SkinInfillAreaComputation::calculateBottomSkin(const SliceLayerPart& part, Polygons& downskin) { - if (bottom_layer_count == 0 && initial_bottom_layer_count == 0) + if (bottom_layer_count_ == 0 && initial_bottom_layer_count_ == 0) { return; // downskin remains empty } - if (layer_nr < LayerIndex(initial_bottom_layer_count)) + if (layer_nr_ < LayerIndex(initial_bottom_layer_count_)) { return; // don't subtract anything form the downskin } - LayerIndex bottom_check_start_layer_idx{ std::max(LayerIndex{ 0 }, LayerIndex{ layer_nr - bottom_layer_count }) }; + LayerIndex bottom_check_start_layer_idx{ std::max(LayerIndex{ 0 }, LayerIndex{ layer_nr_ - bottom_layer_count_ }) }; Polygons not_air = getOutlineOnLayer(part, bottom_check_start_layer_idx); - if (! no_small_gaps_heuristic) + if (! no_small_gaps_heuristic_) { - for (int downskin_layer_nr = bottom_check_start_layer_idx + 1; downskin_layer_nr < layer_nr; downskin_layer_nr++) + for (int downskin_layer_nr = bottom_check_start_layer_idx + 1; downskin_layer_nr < layer_nr_; downskin_layer_nr++) { not_air = not_air.intersection(getOutlineOnLayer(part, downskin_layer_nr)); } } - const double min_infill_area = mesh.settings.get("min_infill_area"); + const double min_infill_area = mesh_.settings.get("min_infill_area"); if (min_infill_area > 0.0) { not_air.removeSmallAreas(min_infill_area); @@ -196,23 +196,23 @@ void SkinInfillAreaComputation::calculateBottomSkin(const SliceLayerPart& part, void SkinInfillAreaComputation::calculateTopSkin(const SliceLayerPart& part, Polygons& upskin) { - if (layer_nr > LayerIndex(mesh.layers.size()) - top_layer_count || top_layer_count <= 0) + if (layer_nr_ > LayerIndex(mesh_.layers.size()) - top_layer_count_ || top_layer_count_ <= 0) { // If we're in the very top layers (less than top_layer_count from the top of the mesh) everything will be top skin anyway, so no need to generate infill. Just take the // original inner contour. If top_layer_count is 0, no need to calculate anything either. return; } - Polygons not_air = getOutlineOnLayer(part, layer_nr + top_layer_count); - if (! no_small_gaps_heuristic) + Polygons not_air = getOutlineOnLayer(part, layer_nr_ + top_layer_count_); + if (! no_small_gaps_heuristic_) { - for (int upskin_layer_nr = layer_nr + 1; upskin_layer_nr < layer_nr + top_layer_count; upskin_layer_nr++) + for (int upskin_layer_nr = layer_nr_ + 1; upskin_layer_nr < layer_nr_ + top_layer_count_; upskin_layer_nr++) { not_air = not_air.intersection(getOutlineOnLayer(part, upskin_layer_nr)); } } - const double min_infill_area = mesh.settings.get("min_infill_area"); + const double min_infill_area = mesh_.settings.get("min_infill_area"); if (min_infill_area > 0.0) { not_air.removeSmallAreas(min_infill_area); @@ -229,39 +229,39 @@ void SkinInfillAreaComputation::calculateTopSkin(const SliceLayerPart& part, Pol */ void SkinInfillAreaComputation::applySkinExpansion(const Polygons& original_outline, Polygons& upskin, Polygons& downskin) { - const coord_t min_width = mesh.settings.get("min_skin_width_for_expansion") / 2; + const coord_t min_width = mesh_.settings.get("min_skin_width_for_expansion") / 2; // Expand some areas of the skin for Skin Expand Distance. if (min_width > 0) { // This performs an opening operation by first insetting by the minimum width, then offsetting with the same width. // The expansion is only applied to that opened shape. - if (bottom_skin_expand_distance != 0) + if (bottom_skin_expand_distance_ != 0) { - const Polygons expanded = downskin.offset(-min_width).offset(min_width + bottom_skin_expand_distance); + const Polygons expanded = downskin.offset(-min_width).offset(min_width + bottom_skin_expand_distance_); // And then re-joined with the original part that was not offset, to retain parts smaller than min_width. downskin = downskin.unionPolygons(expanded); } - if (top_skin_expand_distance != 0) + if (top_skin_expand_distance_ != 0) { - const Polygons expanded = upskin.offset(-min_width).offset(min_width + top_skin_expand_distance); + const Polygons expanded = upskin.offset(-min_width).offset(min_width + top_skin_expand_distance_); upskin = upskin.unionPolygons(expanded); } } else // No need to pay attention to minimum width. Just expand. { - if (bottom_skin_expand_distance != 0) + if (bottom_skin_expand_distance_ != 0) { - downskin = downskin.offset(bottom_skin_expand_distance); + downskin = downskin.offset(bottom_skin_expand_distance_); } - if (top_skin_expand_distance != 0) + if (top_skin_expand_distance_ != 0) { - upskin = upskin.offset(top_skin_expand_distance); + upskin = upskin.offset(top_skin_expand_distance_); } } - bool should_bottom_be_clipped = bottom_skin_expand_distance > 0; - bool should_top_be_clipped = top_skin_expand_distance > 0; + bool should_bottom_be_clipped = bottom_skin_expand_distance_ > 0; + bool should_top_be_clipped = top_skin_expand_distance_ > 0; // Set miter limit for morphological open in order to fill in // "narrow point" features of polygons due to offsetting artifacts. @@ -278,16 +278,16 @@ void SkinInfillAreaComputation::applySkinExpansion(const Polygons& original_outl // as the final polygon is limited (intersected) with the original polygon. constexpr double MITER_LIMIT = 10000000.0; // Remove thin pieces of support for Skin Removal Width. - if (bottom_skin_preshrink > 0 || (min_width == 0 && bottom_skin_expand_distance != 0)) + if (bottom_skin_preshrink_ > 0 || (min_width == 0 && bottom_skin_expand_distance_ != 0)) { - downskin = downskin.offset(-bottom_skin_preshrink / 2, ClipperLib::jtMiter, MITER_LIMIT) - .offset(bottom_skin_preshrink / 2, ClipperLib::jtMiter, MITER_LIMIT) + downskin = downskin.offset(-bottom_skin_preshrink_ / 2, ClipperLib::jtMiter, MITER_LIMIT) + .offset(bottom_skin_preshrink_ / 2, ClipperLib::jtMiter, MITER_LIMIT) .intersection(downskin); should_bottom_be_clipped = true; // Rounding errors can lead to propagation of errors. This could mean that skin goes beyond the original outline } - if (top_skin_preshrink > 0 || (min_width == 0 && top_skin_expand_distance != 0)) + if (top_skin_preshrink_ > 0 || (min_width == 0 && top_skin_expand_distance_ != 0)) { - upskin = upskin.offset(-top_skin_preshrink / 2, ClipperLib::jtMiter, MITER_LIMIT).offset(top_skin_preshrink / 2, ClipperLib::jtMiter, MITER_LIMIT); + upskin = upskin.offset(-top_skin_preshrink_ / 2, ClipperLib::jtMiter, MITER_LIMIT).offset(top_skin_preshrink_ / 2, ClipperLib::jtMiter, MITER_LIMIT); should_top_be_clipped = true; // Rounding errors can lead to propagation of errors. This could mean that skin goes beyond the original outline } @@ -323,8 +323,8 @@ void SkinInfillAreaComputation::generateRoofingFillAndSkinFill(SliceLayerPart& p { for (SkinPart& skin_part : part.skin_parts) { - const size_t roofing_layer_count = std::min(mesh.settings.get("roofing_layer_count"), mesh.settings.get("top_layers")); - const coord_t skin_overlap = mesh.settings.get("skin_overlap_mm"); + const size_t roofing_layer_count = std::min(mesh_.settings.get("roofing_layer_count"), mesh_.settings.get("top_layers")); + const coord_t skin_overlap = mesh_.settings.get("skin_overlap_mm"); Polygons filled_area_above = generateFilledAreaAbove(part, roofing_layer_count); @@ -346,16 +346,16 @@ void SkinInfillAreaComputation::generateRoofingFillAndSkinFill(SliceLayerPart& p */ Polygons SkinInfillAreaComputation::generateFilledAreaAbove(SliceLayerPart& part, size_t roofing_layer_count) { - Polygons filled_area_above = getOutlineOnLayer(part, layer_nr + roofing_layer_count); - if (! no_small_gaps_heuristic) + Polygons filled_area_above = getOutlineOnLayer(part, layer_nr_ + roofing_layer_count); + if (! no_small_gaps_heuristic_) { - for (int layer_nr_above = layer_nr + 1; layer_nr_above < layer_nr + roofing_layer_count; layer_nr_above++) + for (int layer_nr_above = layer_nr_ + 1; layer_nr_above < layer_nr_ + roofing_layer_count; layer_nr_above++) { Polygons outlines_above = getOutlineOnLayer(part, layer_nr_above); filled_area_above = filled_area_above.intersection(outlines_above); } } - if (layer_nr > 0) + if (layer_nr_ > 0) { // if the skin has air below it then cutting it into regions could cause a region // to be wholely or partly above air and it may not be printable so restrict @@ -363,7 +363,7 @@ Polygons SkinInfillAreaComputation::generateFilledAreaAbove(SliceLayerPart& part // has air below (fixes https://github.com/Ultimaker/Cura/issues/2656) // set air_below to the skin area for the current layer that has air below it - Polygons air_below = getOutlineOnLayer(part, layer_nr).difference(getOutlineOnLayer(part, layer_nr - 1)); + Polygons air_below = getOutlineOnLayer(part, layer_nr_).difference(getOutlineOnLayer(part, layer_nr_ - 1)); if (! air_below.empty()) { @@ -382,18 +382,18 @@ Polygons SkinInfillAreaComputation::generateFilledAreaAbove(SliceLayerPart& part */ Polygons SkinInfillAreaComputation::generateFilledAreaBelow(SliceLayerPart& part, size_t flooring_layer_count) { - if (layer_nr < flooring_layer_count) + if (layer_nr_ < flooring_layer_count) { return {}; } constexpr size_t min_wall_line_count = 2; - const int lowest_flooring_layer = layer_nr - flooring_layer_count; + const int lowest_flooring_layer = layer_nr_ - flooring_layer_count; Polygons filled_area_below = getOutlineOnLayer(part, lowest_flooring_layer); - if (! no_small_gaps_heuristic) + if (! no_small_gaps_heuristic_) { const int next_lowest_flooring_layer = lowest_flooring_layer + 1; - for (int layer_nr_below = next_lowest_flooring_layer; layer_nr_below < layer_nr; layer_nr_below++) + for (int layer_nr_below = next_lowest_flooring_layer; layer_nr_below < layer_nr_; layer_nr_below++) { Polygons outlines_below = getOutlineOnLayer(part, layer_nr_below); filled_area_below = filled_area_below.intersection(outlines_below); @@ -459,8 +459,8 @@ void SkinInfillAreaComputation::generateGradualInfill(SliceMeshStorage& mesh) layer_skip_count = gradual_infill_step_layer_count / n_skip_steps_per_gradual_step; const size_t max_infill_steps = mesh.settings.get("gradual_infill_steps"); - const LayerIndex min_layer = mesh.settings.get("initial_bottom_layers"); - const LayerIndex max_layer = mesh.layers.size() - 1 - mesh.settings.get("top_layers"); + const LayerIndex mesh_min_layer = mesh.settings.get("initial_bottom_layers"); + const LayerIndex mesh_max_layer = mesh.layers.size() - 1 - mesh.settings.get("top_layers"); const auto infill_wall_count = mesh.settings.get("infill_wall_line_count"); const auto infill_wall_width = mesh.settings.get("infill_line_width"); @@ -483,7 +483,7 @@ void SkinInfillAreaComputation::generateGradualInfill(SliceMeshStorage& mesh) layer_idx, SectionType::SKIN); - if (infill_area.empty() || layer_idx < min_layer || layer_idx > max_layer) + if (infill_area.empty() || layer_idx < mesh_min_layer || layer_idx > mesh_max_layer) { // initialize infill_area_per_combine_per_density empty part.infill_area_per_combine_per_density.emplace_back(); // create a new infill_area_per_combine part.infill_area_per_combine_per_density.back().emplace_back(); // put empty infill area in the newly constructed infill_area_per_combine diff --git a/src/sliceDataStorage.cpp b/src/sliceDataStorage.cpp index 27f0266c69..ddce31175b 100644 --- a/src/sliceDataStorage.cpp +++ b/src/sliceDataStorage.cpp @@ -328,10 +328,10 @@ Polygons total.add(support_layer.support_roof); } } - int prime_tower_outer_extruder_nr = primeTower.extruder_order[0]; + int prime_tower_outer_extruder_nr = primeTower.extruder_order_[0]; if (include_prime_tower && (extruder_nr == -1 || extruder_nr == prime_tower_outer_extruder_nr)) { - if (primeTower.enabled) + if (primeTower.enabled_) { total.add(primeTower.getOuterPoly(layer_nr)); } diff --git a/tests/GCodeExportTest.cpp b/tests/GCodeExportTest.cpp index e85b6fb2da..4a80f409ca 100644 --- a/tests/GCodeExportTest.cpp +++ b/tests/GCodeExportTest.cpp @@ -43,31 +43,31 @@ class GCodeExportTest : public testing::Test void SetUp() override { output << std::fixed; - gcode.output_stream = &output; + gcode.output_stream_ = &output; // Since GCodeExport doesn't support copying, we have to reset everything in-place. - gcode.currentPosition = Point3(0, 0, MM2INT(20)); - gcode.layer_nr = 0; - gcode.current_e_value = 0; - gcode.current_e_offset = 0; - gcode.current_extruder = 0; - gcode.current_fan_speed = -1; - gcode.total_print_times = std::vector(static_cast(PrintFeatureType::NumPrintFeatureTypes), 0.0); - gcode.currentSpeed = 1.0; - gcode.current_print_acceleration = -1.0; - gcode.current_travel_acceleration = -1.0; - gcode.current_jerk = -1.0; - gcode.is_z_hopped = 0; + gcode.current_position_ = Point3(0, 0, MM2INT(20)); + gcode.layer_nr_ = 0; + gcode.current_e_value_ = 0; + gcode.current_e_offset_ = 0; + gcode.current_extruder_ = 0; + gcode.current_fan_speed_ = -1; + gcode.total_print_times_ = std::vector(static_cast(PrintFeatureType::NumPrintFeatureTypes), 0.0); + gcode.current_speed_ = 1.0; + gcode.current_print_acceleration_ = -1.0; + gcode.current_travel_acceleration_ = -1.0; + gcode.current_jerk_ = -1.0; + gcode.is_z_hopped_ = 0; gcode.setFlavor(EGCodeFlavor::MARLIN); - gcode.bed_temperature = 0; - gcode.initial_bed_temp = 0; - gcode.fan_number = 0; - gcode.total_bounding_box = AABB3D(); - gcode.current_layer_z = 0; - gcode.relative_extrusion = false; + gcode.bed_temperature_ = 0; + gcode.initial_bed_temp_ = 0; + gcode.fan_number_ = 0; + gcode.total_bounding_box_ = AABB3D(); + gcode.current_layer_z_ = 0; + gcode.relative_extrusion_ = false; - gcode.new_line = "\n"; // Not BFB flavour by default. - gcode.machine_name = "Your favourite 3D printer"; + gcode.new_line_ = "\n"; // Not BFB flavour by default. + gcode.machine_name_ = "Your favourite 3D printer"; // Set up a scene so that we may request settings. Application::getInstance().current_slice_ = new Slice(1); @@ -204,28 +204,28 @@ class GriffinHeaderTest : public testing::TestWithParam void SetUp() override { output << std::fixed; - gcode.output_stream = &output; + gcode.output_stream_ = &output; // Since GCodeExport doesn't support copying, we have to reset everything in-place. - gcode.currentPosition = Point3(0, 0, MM2INT(20)); - gcode.layer_nr = 0; - gcode.current_e_value = 0; - gcode.current_extruder = 0; - gcode.current_fan_speed = -1; - gcode.total_print_times = std::vector(static_cast(PrintFeatureType::NumPrintFeatureTypes), 0.0); - gcode.currentSpeed = 1.0; - gcode.current_print_acceleration = -1.0; - gcode.current_travel_acceleration = -1.0; - gcode.current_jerk = -1.0; - gcode.is_z_hopped = 0; + gcode.current_position_ = Point3(0, 0, MM2INT(20)); + gcode.layer_nr_ = 0; + gcode.current_e_value_ = 0; + gcode.current_extruder_ = 0; + gcode.current_fan_speed_ = -1; + gcode.total_print_times_ = std::vector(static_cast(PrintFeatureType::NumPrintFeatureTypes), 0.0); + gcode.current_speed_ = 1.0; + gcode.current_print_acceleration_ = -1.0; + gcode.current_travel_acceleration_ = -1.0; + gcode.current_jerk_ = -1.0; + gcode.is_z_hopped_ = 0; gcode.setFlavor(EGCodeFlavor::MARLIN); - gcode.initial_bed_temp = 0; - gcode.bed_temperature = 0; - gcode.fan_number = 0; - gcode.total_bounding_box = AABB3D(); + gcode.initial_bed_temp_ = 0; + gcode.bed_temperature_ = 0; + gcode.fan_number_ = 0; + gcode.total_bounding_box_ = AABB3D(); - gcode.new_line = "\n"; // Not BFB flavour by default. - gcode.machine_name = "Your favourite 3D printer"; + gcode.new_line_ = "\n"; // Not BFB flavour by default. + gcode.machine_name_ = "Your favourite 3D printer"; // Set up a scene so that we may request settings. Application::getInstance().current_slice_ = new Slice(0); From 4bcc29c1a44e2e5c9ac7c282e146e0a62593724c Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Tue, 21 Nov 2023 16:26:51 +0100 Subject: [PATCH 25/48] Fixed shadowed variables warnings --- include/BeadingStrategy/BeadingStrategy.h | 12 +- .../DistributedBeadingStrategy.h | 2 +- .../BeadingStrategy/LimitedBeadingStrategy.h | 4 +- .../OuterWallInsetBeadingStrategy.h | 4 +- .../RedistributeBeadingStrategy.h | 6 +- .../BeadingStrategy/WideningBeadingStrategy.h | 6 +- include/ExtruderPlan.h | 2 +- include/LayerPlan.h | 64 +-- include/PathOrder.h | 18 +- include/PathOrderMonotonic.h | 354 ++++++++-------- include/TreeModelVolumes.h | 30 +- include/WallToolPaths.h | 32 +- include/WallsComputation.h | 4 +- include/infill/LightningDistanceField.h | 41 +- src/BeadingStrategy/BeadingStrategy.cpp | 42 +- .../DistributedBeadingStrategy.cpp | 18 +- .../LimitedBeadingStrategy.cpp | 72 ++-- .../OuterWallInsetBeadingStrategy.cpp | 20 +- .../RedistributeBeadingStrategy.cpp | 40 +- .../WideningBeadingStrategy.cpp | 36 +- src/FffGcodeWriter.cpp | 60 +-- src/LayerPlan.cpp | 377 +++++++++--------- src/LayerPlanBuffer.cpp | 28 +- src/PrimeTower.cpp | 4 +- src/TopSurface.cpp | 6 +- src/TreeModelVolumes.cpp | 188 ++++----- src/WallToolPaths.cpp | 196 ++++----- src/WallsComputation.cpp | 40 +- src/infill/LightningDistanceField.cpp | 48 +-- src/support.cpp | 16 +- tests/LayerPlanTest.cpp | 22 +- tests/PathOrderMonotonicTest.cpp | 4 +- 32 files changed, 915 insertions(+), 881 deletions(-) diff --git a/include/BeadingStrategy/BeadingStrategy.h b/include/BeadingStrategy/BeadingStrategy.h index 0b6d28a87d..ab628788cd 100644 --- a/include/BeadingStrategy/BeadingStrategy.h +++ b/include/BeadingStrategy/BeadingStrategy.h @@ -104,21 +104,21 @@ class BeadingStrategy AngleRadians getTransitioningAngle() const; protected: - std::string name; + std::string name_; - coord_t optimal_width; //! Optimal bead width, nominal width off the walls in 'ideal' circumstances. + coord_t optimal_width_; //! Optimal bead width, nominal width off the walls in 'ideal' circumstances. - Ratio wall_split_middle_threshold; //! Threshold when a middle wall should be split into two, as a ratio of the optimal wall width. + Ratio wall_split_middle_threshold_; //! Threshold when a middle wall should be split into two, as a ratio of the optimal wall width. - Ratio wall_add_middle_threshold; //! Threshold when a new middle wall should be added between an even number of walls, as a ratio of the optimal wall width. + Ratio wall_add_middle_threshold_; //! Threshold when a new middle wall should be added between an even number of walls, as a ratio of the optimal wall width. - coord_t default_transition_length; //! The length of the region to smoothly transfer between bead counts + coord_t default_transition_length_; //! The length of the region to smoothly transfer between bead counts /*! * The maximum angle between outline segments smaller than which we are going to add transitions * Equals 180 - the "limit bisector angle" from the paper */ - AngleRadians transitioning_angle; + AngleRadians transitioning_angle_; }; using BeadingStrategyPtr = std::unique_ptr; diff --git a/include/BeadingStrategy/DistributedBeadingStrategy.h b/include/BeadingStrategy/DistributedBeadingStrategy.h index 35a7bb0bde..bddb1e8140 100644 --- a/include/BeadingStrategy/DistributedBeadingStrategy.h +++ b/include/BeadingStrategy/DistributedBeadingStrategy.h @@ -18,7 +18,7 @@ namespace cura class DistributedBeadingStrategy : public BeadingStrategy { protected: - double one_over_distribution_radius_squared; // (1 / distribution_radius)^2 + double one_over_distribution_radius_squared_; // (1 / distribution_radius)^2 public: /*! diff --git a/include/BeadingStrategy/LimitedBeadingStrategy.h b/include/BeadingStrategy/LimitedBeadingStrategy.h index b4ca975fd6..42d34f86a4 100644 --- a/include/BeadingStrategy/LimitedBeadingStrategy.h +++ b/include/BeadingStrategy/LimitedBeadingStrategy.h @@ -42,8 +42,8 @@ class LimitedBeadingStrategy : public BeadingStrategy double getTransitionAnchorPos(coord_t lower_bead_count) const override; protected: - const coord_t max_bead_count; - const BeadingStrategyPtr parent; + const coord_t max_bead_count_; + const BeadingStrategyPtr parent_; }; diff --git a/include/BeadingStrategy/OuterWallInsetBeadingStrategy.h b/include/BeadingStrategy/OuterWallInsetBeadingStrategy.h index f1ea71af7d..87fb2b8258 100644 --- a/include/BeadingStrategy/OuterWallInsetBeadingStrategy.h +++ b/include/BeadingStrategy/OuterWallInsetBeadingStrategy.h @@ -28,8 +28,8 @@ namespace cura virtual std::string toString() const; private: - BeadingStrategyPtr parent; - coord_t outer_wall_offset; + BeadingStrategyPtr parent_; + coord_t outer_wall_offset_; }; } // namespace cura #endif // OUTER_WALL_INSET_BEADING_STRATEGY_H diff --git a/include/BeadingStrategy/RedistributeBeadingStrategy.h b/include/BeadingStrategy/RedistributeBeadingStrategy.h index 6609eee995..2f8304bf39 100644 --- a/include/BeadingStrategy/RedistributeBeadingStrategy.h +++ b/include/BeadingStrategy/RedistributeBeadingStrategy.h @@ -83,9 +83,9 @@ class RedistributeBeadingStrategy : public BeadingStrategy */ static bool validateInnerBeadWidths(Beading& beading, coord_t minimum_width_inner); - BeadingStrategyPtr parent; - coord_t optimal_width_outer; - Ratio minimum_variable_line_ratio; + BeadingStrategyPtr parent_; + coord_t optimal_width_outer_; + Ratio minimum_variable_line_ratio_; }; } // namespace cura diff --git a/include/BeadingStrategy/WideningBeadingStrategy.h b/include/BeadingStrategy/WideningBeadingStrategy.h index 5ec9bf4cad..bda69f345d 100644 --- a/include/BeadingStrategy/WideningBeadingStrategy.h +++ b/include/BeadingStrategy/WideningBeadingStrategy.h @@ -37,9 +37,9 @@ class WideningBeadingStrategy : public BeadingStrategy virtual std::string toString() const override; protected: - BeadingStrategyPtr parent; - const coord_t min_input_width; - const coord_t min_output_width; + BeadingStrategyPtr parent_; + const coord_t min_input_width_; + const coord_t min_output_width_; }; } // namespace cura diff --git a/include/ExtruderPlan.h b/include/ExtruderPlan.h index 5f42adfc09..ab0fef772e 100644 --- a/include/ExtruderPlan.h +++ b/include/ExtruderPlan.h @@ -44,7 +44,7 @@ class ExtruderPlan FRIEND_TEST(ExtruderPlanTest, BackPressureCompensationEmptyPlan); #endif public: - size_t extruder_nr_{ 0 }; //!< The extruder used for this paths in the current plan. + size_t extruder_nr_; //!< The extruder used for this paths in the current plan. ExtruderPlan() noexcept = default; diff --git a/include/LayerPlan.h b/include/LayerPlan.h index a4b639030a..aff1b0304a 100644 --- a/include/LayerPlan.h +++ b/include/LayerPlan.h @@ -54,49 +54,49 @@ class LayerPlan : public NoCopy #endif public: - const PathConfigStorage configs_storage; //!< The line configs for this layer for each feature type - coord_t z; - coord_t final_travel_z; - bool mode_skip_agressive_merge; //!< Whether to give every new path the 'skip_agressive_merge_hint' property (see GCodePath); default is false. + const PathConfigStorage configs_storage_; //!< The line configs for this layer for each feature type + coord_t z_; + coord_t final_travel_z_; + bool mode_skip_agressive_merge_; //!< Whether to give every new path the 'skip_agressive_merge_hint' property (see GCodePath); default is false. private: - const SliceDataStorage& storage; //!< The polygon data obtained from FffPolygonProcessor - const LayerIndex layer_nr; //!< The layer number of this layer plan - const bool is_initial_layer; //!< Whether this is the first layer (which might be raft) - const bool is_raft_layer; //!< Whether this is a layer which is part of the raft - coord_t layer_thickness; + const SliceDataStorage& storage_; //!< The polygon data obtained from FffPolygonProcessor + const LayerIndex layer_nr_; //!< The layer number of this layer plan + const bool is_initial_layer_; //!< Whether this is the first layer (which might be raft) + const bool is_raft_layer_; //!< Whether this is a layer which is part of the raft + coord_t layer_thickness_; - std::vector layer_start_pos_per_extruder; //!< The starting position of a layer for each extruder - std::vector has_prime_tower_planned_per_extruder; //!< For each extruder, whether the prime tower is planned yet or not. - std::optional last_planned_position; //!< The last planned XY position of the print head (if known) + std::vector layer_start_pos_per_extruder_; //!< The starting position of a layer for each extruder + std::vector has_prime_tower_planned_per_extruder_; //!< For each extruder, whether the prime tower is planned yet or not. + std::optional last_planned_position_; //!< The last planned XY position of the print head (if known) - std::shared_ptr current_mesh; //!< The mesh of the last planned move. + std::shared_ptr current_mesh_; //!< The mesh of the last planned move. /*! * Whether the skirt or brim polygons have been processed into planned paths * for each extruder train. */ - bool skirt_brim_is_processed[MAX_EXTRUDERS]; + bool skirt_brim_is_processed_[MAX_EXTRUDERS]; - std::vector extruder_plans; //!< should always contain at least one ExtruderPlan + std::vector extruder_plans_; //!< should always contain at least one ExtruderPlan - size_t last_extruder_previous_layer; //!< The last id of the extruder with which was printed in the previous layer - ExtruderTrain* last_planned_extruder; //!< The extruder for which a move has most recently been planned. + size_t last_extruder_previous_layer_; //!< The last id of the extruder with which was printed in the previous layer + ExtruderTrain* last_planned_extruder_; //!< The extruder for which a move has most recently been planned. - std::optional first_travel_destination; //!< The destination of the first (travel) move (if this layer is not empty) - bool first_travel_destination_is_inside; //!< Whether the destination of the first planned travel move is inside a layer part - std::optional> first_extrusion_acc_jerk; //!< The acceleration and jerk rates of the first extruded move (if this layer is not empty). - std::optional> next_layer_acc_jerk; //!< If there is a next layer, the first acceleration and jerk it starts with. - bool was_inside; //!< Whether the last planned (extrusion) move was inside a layer part - bool is_inside; //!< Whether the destination of the next planned travel move is inside a layer part - Polygons comb_boundary_minimum; //!< The minimum boundary within which to comb, or to move into when performing a retraction. - Polygons comb_boundary_preferred; //!< The boundary preferably within which to comb, or to move into when performing a retraction. - Comb* comb; - coord_t comb_move_inside_distance; //!< Whenever using the minimum boundary for combing it tries to move the coordinates inside by this distance after calculating the combing. - Polygons bridge_wall_mask; //!< The regions of a layer part that are not supported, used for bridging - Polygons overhang_mask; //!< The regions of a layer part where the walls overhang + std::optional first_travel_destination_; //!< The destination of the first (travel) move (if this layer is not empty) + bool first_travel_destination_is_inside_; //!< Whether the destination of the first planned travel move is inside a layer part + std::optional> first_extrusion_acc_jerk_; //!< The acceleration and jerk rates of the first extruded move (if this layer is not empty). + std::optional> next_layer_acc_jerk_; //!< If there is a next layer, the first acceleration and jerk it starts with. + bool was_inside_; //!< Whether the last planned (extrusion) move was inside a layer part + bool is_inside_; //!< Whether the destination of the next planned travel move is inside a layer part + Polygons comb_boundary_minimum_; //!< The minimum boundary within which to comb, or to move into when performing a retraction. + Polygons comb_boundary_preferred_; //!< The boundary preferably within which to comb, or to move into when performing a retraction. + Comb* comb_; + coord_t comb_move_inside_distance_; //!< Whenever using the minimum boundary for combing it tries to move the coordinates inside by this distance after calculating the combing. + Polygons bridge_wall_mask_; //!< The regions of a layer part that are not supported, used for bridging + Polygons overhang_mask_; //!< The regions of a layer part where the walls overhang - const std::vector fan_speed_layer_time_settings_per_extruder; + const std::vector fan_speed_layer_time_settings_per_extruder_; enum CombBoundary { @@ -619,12 +619,12 @@ class LayerPlan : public NoCopy template unsigned locateFirstSupportedVertex(const T& wall, const unsigned start_idx) const { - if (bridge_wall_mask.empty() && overhang_mask.empty()) + if (bridge_wall_mask_.empty() && overhang_mask_.empty()) { return start_idx; } - Polygons air_below(bridge_wall_mask.unionPolygons(overhang_mask)); + Polygons air_below(bridge_wall_mask_.unionPolygons(overhang_mask_)); unsigned curr_idx = start_idx; diff --git a/include/PathOrder.h b/include/PathOrder.h index 9b909a6605..bb87aa0a44 100644 --- a/include/PathOrder.h +++ b/include/PathOrder.h @@ -37,18 +37,18 @@ class PathOrder * pointer to the vertex data, whether to close the loop or not, the * direction in which to print the path and where to start the path. */ - std::vector> paths; + std::vector> paths_; /*! * The location where the nozzle is assumed to start from before printing * these parts. */ - Point start_point; + Point start_point_; /*! * Seam settings. */ - ZSeamConfig seam_config; + ZSeamConfig seam_config_; /*! * Add a new polygon to be planned. @@ -59,7 +59,7 @@ class PathOrder void addPolygon(const PathType& polygon) { constexpr bool is_closed = true; - paths.emplace_back(polygon, is_closed); + paths_.emplace_back(polygon, is_closed); } /*! @@ -71,7 +71,7 @@ class PathOrder void addPolyline(const PathType& polyline) { constexpr bool is_closed = false; - paths.emplace_back(polyline, is_closed); + paths_.emplace_back(polyline, is_closed); } /*! @@ -96,7 +96,7 @@ class PathOrder * pretend they are the same point. * This is used for detecting loops and chaining lines together. */ - constexpr static coord_t coincident_point_distance = 10; + constexpr static coord_t coincident_point_distance_ = 10; /*! @@ -108,7 +108,7 @@ class PathOrder */ void detectLoops() { - for(PathOrdering& path : paths) + for(PathOrdering& path : paths_) { if(path.is_closed_) //Already a polygon. No need to detect loops. { @@ -118,7 +118,7 @@ class PathOrder { continue; } - if(vSize2(path.converted_->back() - path.converted_->front()) < coincident_point_distance * coincident_point_distance) + if(vSize2(path.converted_->back() - path.converted_->front()) < coincident_point_distance_ * coincident_point_distance_) { //Endpoints are really close to one another. Consider it a closed loop. path.is_closed_ = true; @@ -129,4 +129,4 @@ class PathOrder } -#endif //PATHORDER_H \ No newline at end of file +#endif //PATHORDER_H diff --git a/include/PathOrderMonotonic.h b/include/PathOrderMonotonic.h index fa35bb513a..267fcc7261 100644 --- a/include/PathOrderMonotonic.h +++ b/include/PathOrderMonotonic.h @@ -1,12 +1,12 @@ -//Copyright (c) 2021 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2021 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef PATHORDERMONOTONIC_H #define PATHORDERMONOTONIC_H #include //For std::sin() and std::cos(). -#include //To track starting points of monotonic sequences. #include //To track monotonic sequences. +#include //To track starting points of monotonic sequences. #include "PathOrder.h" #include "PathOrdering.h" @@ -42,38 +42,38 @@ class PathOrderMonotonic : public PathOrder { public: using Path = PathOrdering; - using PathOrder::coincident_point_distance; + using PathOrder::coincident_point_distance_; PathOrderMonotonic(const AngleRadians monotonic_direction, const coord_t max_adjacent_distance, const Point start_point) - //The monotonic vector needs to rotate clockwise instead of counter-clockwise, the same as how the infill patterns are generated. - : monotonic_vector(-std::cos(monotonic_direction) * monotonic_vector_resolution, std::sin(monotonic_direction) * monotonic_vector_resolution) - , max_adjacent_distance(max_adjacent_distance) + // The monotonic vector needs to rotate clockwise instead of counter-clockwise, the same as how the infill patterns are generated. + : monotonic_vector_(-std::cos(monotonic_direction) * monotonic_vector_resolution_, std::sin(monotonic_direction) * monotonic_vector_resolution_) + , max_adjacent_distance_(max_adjacent_distance) { - this->start_point = start_point; + this->start_point_ = start_point; } void optimize() { - if(this->paths.empty()) + if (this->paths_.empty()) { return; } - //Get the vertex data and store it in the paths. - for(Path& path : this->paths) + // Get the vertex data and store it in the paths. + for (Path& path : this->paths_) { path.converted_ = path.getVertexData(); } - std::vector reordered; //To store the result in. At the end, we'll std::swap with the real paths. - reordered.reserve(this->paths.size()); + std::vector reordered; // To store the result in. At the end, we'll std::swap with the real paths. + reordered.reserve(this->paths_.size()); - //First print all the looping polygons, if there are any. - std::vector polylines; //Also find all polylines and store them in a vector that we can sort in-place without making copies all the time. - this->detectLoops(); //Always filter out loops. We don't specifically want to print those in monotonic order. - for(Path& path : this->paths) + // First print all the looping polygons, if there are any. + std::vector polylines; // Also find all polylines and store them in a vector that we can sort in-place without making copies all the time. + this->detectLoops(); // Always filter out loops. We don't specifically want to print those in monotonic order. + for (Path& path : this->paths_) { - if(path.is_closed_ || path.vertices_->size() <= 1) + if (path.is_closed_ || path.vertices_->size() <= 1) { reordered.push_back(path); } @@ -85,101 +85,107 @@ class PathOrderMonotonic : public PathOrder } } - //Sort the polylines by their projection on the monotonic vector. This helps find adjacent lines quickly. - std::sort(polylines.begin(), polylines.end(), [this](Path* a, Path* b) { - const coord_t a_start_projection = dot(a->converted_->front(), monotonic_vector); - const coord_t a_end_projection = dot(a->converted_->back(), monotonic_vector); - const coord_t a_projection = std::min(a_start_projection, a_end_projection); //The projection of a path is the endpoint furthest back of the two endpoints. - - const coord_t b_start_projection = dot(b->converted_->front(), monotonic_vector); - const coord_t b_end_projection = dot(b->converted_->back(), monotonic_vector); - const coord_t b_projection = std::min(b_start_projection, b_end_projection); - - return a_projection < b_projection; - }); - //Create a bucket grid to be able to find adjacent lines quickly. - SparsePointGridInclusive line_bucket_grid(MM2INT(2)); //Grid size of 2mm. - for(Path* polyline : polylines) + // Sort the polylines by their projection on the monotonic vector. This helps find adjacent lines quickly. + std::sort( + polylines.begin(), + polylines.end(), + [this](Path* a, Path* b) + { + const coord_t a_start_projection = dot(a->converted_->front(), monotonic_vector_); + const coord_t a_end_projection = dot(a->converted_->back(), monotonic_vector_); + const coord_t a_projection = std::min(a_start_projection, a_end_projection); // The projection of a path is the endpoint furthest back of the two endpoints. + + const coord_t b_start_projection = dot(b->converted_->front(), monotonic_vector_); + const coord_t b_end_projection = dot(b->converted_->back(), monotonic_vector_); + const coord_t b_projection = std::min(b_start_projection, b_end_projection); + + return a_projection < b_projection; + }); + // Create a bucket grid to be able to find adjacent lines quickly. + SparsePointGridInclusive line_bucket_grid(MM2INT(2)); // Grid size of 2mm. + for (Path* polyline : polylines) { - if(! polyline->converted_->empty()) + if (! polyline->converted_->empty()) { line_bucket_grid.insert(polyline->converted_->front(), polyline); line_bucket_grid.insert(polyline->converted_->back(), polyline); } } - //Create sequences of line segments that get printed together in a monotonic direction. - //There are several constraints we impose here: - // - Strings of incident polylines are printed in sequence. That is, if their endpoints are incident. - // - The endpoint of the string that is earlier in the monotonic direction will get printed first. - // - The start_vertex of this line will already be set to indicate where to start from. - // - If a line overlaps with another line in the perpendicular direction, and is within max_adjacent_distance (~1 line width) in the monotonic direction, it must be printed in monotonic order. - // - The earlier line is marked as being in sequence with the later line. - // - The later line is no longer a starting point, unless there are multiple adjacent lines before it. - //The ``starting_lines`` set indicates possible locations to start from. Each starting line represents one "sequence", which is either a set of adjacent line segments or a string of polylines. - //The ``connections`` map indicates, starting from each starting segment, the sequence of line segments to print in order. - //Note that for performance reasons, the ``connections`` map will sometimes link the end of one segment to the start of the next segment. This link should be ignored. - const Point perpendicular = turn90CCW(monotonic_vector); //To project on to detect adjacent lines. - - std::unordered_set connected_lines; //Lines that are reachable from one of the starting lines through its connections. - std::unordered_set starting_lines; //Starting points of a linearly connected segment. - std::unordered_map connections; //For each polyline, which polyline it overlaps with, closest in the projected order. - - for(auto polyline_it = polylines.begin(); polyline_it != polylines.end(); polyline_it++) + // Create sequences of line segments that get printed together in a monotonic direction. + // There are several constraints we impose here: + // - Strings of incident polylines are printed in sequence. That is, if their endpoints are incident. + // - The endpoint of the string that is earlier in the monotonic direction will get printed first. + // - The start_vertex of this line will already be set to indicate where to start from. + // - If a line overlaps with another line in the perpendicular direction, and is within max_adjacent_distance (~1 line width) in the monotonic direction, it must be + // printed in monotonic order. + // - The earlier line is marked as being in sequence with the later line. + // - The later line is no longer a starting point, unless there are multiple adjacent lines before it. + // The ``starting_lines`` set indicates possible locations to start from. Each starting line represents one "sequence", which is either a set of adjacent line segments or a + // string of polylines. The ``connections`` map indicates, starting from each starting segment, the sequence of line segments to print in order. Note that for performance + // reasons, the ``connections`` map will sometimes link the end of one segment to the start of the next segment. This link should be ignored. + const Point perpendicular = turn90CCW(monotonic_vector_); // To project on to detect adjacent lines. + + std::unordered_set connected_lines; // Lines that are reachable from one of the starting lines through its connections. + std::unordered_set starting_lines; // Starting points of a linearly connected segment. + std::unordered_map connections; // For each polyline, which polyline it overlaps with, closest in the projected order. + + for (auto polyline_it = polylines.begin(); polyline_it != polylines.end(); polyline_it++) { - if(connections.contains(*polyline_it)) //Already connected this one through a polyline. + if (connections.contains(*polyline_it)) // Already connected this one through a polyline. { continue; } - //First find out if this polyline is part of a string of polylines. - std::deque polystring = findPolylineString(*polyline_it, line_bucket_grid, monotonic_vector); + // First find out if this polyline is part of a string of polylines. + std::deque polystring = findPolylineString(*polyline_it, line_bucket_grid, monotonic_vector_); - //If we're part of a string of polylines, connect up the whole string and mark all of them as being connected. - if(polystring.size() > 1) + // If we're part of a string of polylines, connect up the whole string and mark all of them as being connected. + if (polystring.size() > 1) { starting_lines.insert(polystring[0]); - for(size_t i = 0; i < polystring.size() - 1; ++i) //Iterate over every pair of adjacent polylines in the string (so skip the last one)! + for (size_t i = 0; i < polystring.size() - 1; ++i) // Iterate over every pair of adjacent polylines in the string (so skip the last one)! { connections[polystring[i]] = polystring[i + 1]; connected_lines.insert(polystring[i + 1]); - //Even though we chain polylines, we still want to find lines that they overlap with. - //The strings of polylines may still have weird shapes which interweave with other strings of polylines or loose lines. - //So when a polyline string comes into contact with other lines, we still want to guarantee their order. - //So here we will look for which lines they come into contact with, and thus mark those as possible starting points, so that they function as a new junction. + // Even though we chain polylines, we still want to find lines that they overlap with. + // The strings of polylines may still have weird shapes which interweave with other strings of polylines or loose lines. + // So when a polyline string comes into contact with other lines, we still want to guarantee their order. + // So here we will look for which lines they come into contact with, and thus mark those as possible starting points, so that they function as a new junction. const std::vector overlapping_lines = getOverlappingLines(std::find(polylines.begin(), polylines.end(), polystring[i]), perpendicular, polylines); - for(Path* overlapping_line : overlapping_lines) + for (Path* overlapping_line : overlapping_lines) { - if(std::find(polystring.begin(), polystring.end(), overlapping_line) == polystring.end()) //Mark all overlapping lines not part of the string as possible starting points. + if (std::find(polystring.begin(), polystring.end(), overlapping_line) + == polystring.end()) // Mark all overlapping lines not part of the string as possible starting points. { starting_lines.insert(overlapping_line); - starting_lines.insert(polystring[i + 1]); //Also be able to re-start from this point in the string. + starting_lines.insert(polystring[i + 1]); // Also be able to re-start from this point in the string. } } } } - else //Not a string of polylines, but simply adjacent line segments. + else // Not a string of polylines, but simply adjacent line segments. { - if(! connected_lines.contains(*polyline_it)) //Nothing connects to this line yet. + if (! connected_lines.contains(*polyline_it)) // Nothing connects to this line yet. { - starting_lines.insert(*polyline_it); //This is a starting point then. + starting_lines.insert(*polyline_it); // This is a starting point then. } const std::vector overlapping_lines = getOverlappingLines(polyline_it, perpendicular, polylines); - if(overlapping_lines.size() == 1) //If we're not a string of polylines, but adjacent to only one other polyline, create a sequence of polylines. + if (overlapping_lines.size() == 1) // If we're not a string of polylines, but adjacent to only one other polyline, create a sequence of polylines. { connections[*polyline_it] = overlapping_lines[0]; - if(connected_lines.contains(overlapping_lines[0])) //This line was already connected to. + if (connected_lines.contains(overlapping_lines[0])) // This line was already connected to. { - starting_lines.insert(overlapping_lines[0]); //Multiple lines connect to it, so we must be able to start there. + starting_lines.insert(overlapping_lines[0]); // Multiple lines connect to it, so we must be able to start there. } else { connected_lines.insert(overlapping_lines[0]); } } - else //Either 0 (the for loop terminates immediately) or multiple overlapping lines. For multiple lines we need to mark all of them a starting position. + else // Either 0 (the for loop terminates immediately) or multiple overlapping lines. For multiple lines we need to mark all of them a starting position. { - for(Path* overlapping_line : overlapping_lines) + for (Path* overlapping_line : overlapping_lines) { starting_lines.insert(overlapping_line); } @@ -187,48 +193,57 @@ class PathOrderMonotonic : public PathOrder } } - //Order the starting points of each segments monotonically. This is the order in which to print each segment. + // Order the starting points of each segments monotonically. This is the order in which to print each segment. std::vector starting_lines_monotonic; starting_lines_monotonic.resize(starting_lines.size()); - std::partial_sort_copy(starting_lines.begin(), starting_lines.end(), starting_lines_monotonic.begin(), starting_lines_monotonic.end(), [this](Path* a, Path* b) { - const coord_t a_start_projection = dot(a->converted_->front(), monotonic_vector); - const coord_t a_end_projection = dot(a->converted_->back(), monotonic_vector); - const coord_t a_projection_min = std::min(a_start_projection, a_end_projection); //The projection of a path is the endpoint furthest back of the two endpoints. - const coord_t a_projection_max = std::max(a_start_projection, a_end_projection); //But in case of ties, the other endpoint counts too. Important for polylines where multiple endpoints have the same position! - - const coord_t b_start_projection = dot(b->converted_->front(), monotonic_vector); - const coord_t b_end_projection = dot(b->converted_->back(), monotonic_vector); - const coord_t b_projection_min = std::min(b_start_projection, b_end_projection); - const coord_t b_projection_max = std::max(b_start_projection, b_end_projection); - - return a_projection_min < b_projection_min || (a_projection_min == b_projection_min && a_projection_max < b_projection_max); - }); - - //Now that we have the segments of overlapping lines, and know in which order to print the segments, print segments in monotonic order. - Point current_pos = this->start_point; - for(Path* line : starting_lines_monotonic) + std::partial_sort_copy( + starting_lines.begin(), + starting_lines.end(), + starting_lines_monotonic.begin(), + starting_lines_monotonic.end(), + [this](Path* a, Path* b) + { + const coord_t a_start_projection = dot(a->converted_->front(), monotonic_vector_); + const coord_t a_end_projection = dot(a->converted_->back(), monotonic_vector_); + const coord_t a_projection_min = std::min(a_start_projection, a_end_projection); // The projection of a path is the endpoint furthest back of the two endpoints. + const coord_t a_projection_max = std::max( + a_start_projection, + a_end_projection); // But in case of ties, the other endpoint counts too. Important for polylines where multiple endpoints have the same position! + + const coord_t b_start_projection = dot(b->converted_->front(), monotonic_vector_); + const coord_t b_end_projection = dot(b->converted_->back(), monotonic_vector_); + const coord_t b_projection_min = std::min(b_start_projection, b_end_projection); + const coord_t b_projection_max = std::max(b_start_projection, b_end_projection); + + return a_projection_min < b_projection_min || (a_projection_min == b_projection_min && a_projection_max < b_projection_max); + }); + + // Now that we have the segments of overlapping lines, and know in which order to print the segments, print segments in monotonic order. + Point current_pos = this->start_point_; + for (Path* line : starting_lines_monotonic) { optimizeClosestStartPoint(*line, current_pos); - reordered.push_back(*line); //Plan the start of the sequence to be printed next! + reordered.push_back(*line); // Plan the start of the sequence to be printed next! auto connection = connections.find(line); std::unordered_map checked_connections; // Which connections have already been iterated over auto checked_connection = checked_connections.find(line); - while(connection != connections.end() //Stop if the sequence ends - && starting_lines.find(connection->second) == starting_lines.end() // or if we hit another starting point. - && (checked_connection == checked_connections.end() || checked_connection->second != connection->second)) // or if we have already checked the connection (to avoid falling into a cyclical connection) + while (connection != connections.end() // Stop if the sequence ends + && starting_lines.find(connection->second) == starting_lines.end() // or if we hit another starting point. + && (checked_connection == checked_connections.end() + || checked_connection->second != connection->second)) // or if we have already checked the connection (to avoid falling into a cyclical connection) { - checked_connections.insert({connection->first, connection->second}); + checked_connections.insert({ connection->first, connection->second }); line = connection->second; optimizeClosestStartPoint(*line, current_pos); - reordered.push_back(*line); //Plan this line in, to be printed next! + reordered.push_back(*line); // Plan this line in, to be printed next! connection = connections.find(line); checked_connection = checked_connections.find(line); } } - std::swap(reordered, this->paths); //Store the resulting list in the main paths. + std::swap(reordered, this->paths_); // Store the resulting list in the main paths. } protected: @@ -239,7 +254,7 @@ class PathOrderMonotonic : public PathOrder * The resulting ordering will cause clusters of paths to be sorted * according to their projection on this vector. */ - Point monotonic_vector; + Point monotonic_vector_; /*! * Maximum distance at which lines are considered to be adjacent. @@ -247,7 +262,7 @@ class PathOrderMonotonic : public PathOrder * The monotonicity constraint is only held for lines that are closer than * this distance together. */ - coord_t max_adjacent_distance; + coord_t max_adjacent_distance_; /*! * For a given path, make sure that it is configured correctly to start @@ -266,11 +281,11 @@ class PathOrderMonotonic : public PathOrder */ void optimizeClosestStartPoint(Path& path, Point& current_pos) { - if(path.start_vertex_ == path.converted_->size()) + if (path.start_vertex_ == path.converted_->size()) { const coord_t dist_start = vSize2(current_pos - path.converted_->front()); const coord_t dist_end = vSize2(current_pos - path.converted_->back()); - if(dist_start < dist_end) + if (dist_start < dist_end) { path.start_vertex_ = 0; path.backwards_ = false; @@ -281,7 +296,7 @@ class PathOrderMonotonic : public PathOrder path.backwards_ = true; } } - current_pos = (*path.converted_)[path.converted_->size() - 1 - path.start_vertex_]; //Opposite of the start vertex. + current_pos = (*path.converted_)[path.converted_->size() - 1 - path.start_vertex_]; // Opposite of the start vertex. } /*! @@ -298,69 +313,85 @@ class PathOrderMonotonic : public PathOrder std::deque findPolylineString(Path* polyline, const SparsePointGridInclusive& line_bucket_grid, const Point monotonic_vector) { std::deque result; - if(polyline->converted_->empty()) + if (polyline->converted_->empty()) { return result; } - //Find the two endpoints of the polyline string, on either side. + // Find the two endpoints of the polyline string, on either side. result.push_back(polyline); polyline->start_vertex_ = 0; Point first_endpoint = polyline->converted_->front(); Point last_endpoint = polyline->converted_->back(); - std::vector> lines_before = line_bucket_grid.getNearby(first_endpoint, coincident_point_distance); - auto close_line_before = std::find_if(lines_before.begin(), lines_before.end(), [first_endpoint](SparsePointGridInclusiveImpl::SparsePointGridInclusiveElem found_path) { - return canConnectToPolyline(first_endpoint, found_path); - }); - std::vector> lines_after = line_bucket_grid.getNearby(last_endpoint, coincident_point_distance); - auto close_line_after = std::find_if(lines_after.begin(), lines_after.end(), [last_endpoint](SparsePointGridInclusiveImpl::SparsePointGridInclusiveElem found_path) { - return canConnectToPolyline(last_endpoint, found_path); - }); - - while(close_line_before != lines_before.end()) + std::vector> lines_before = line_bucket_grid.getNearby(first_endpoint, coincident_point_distance_); + auto close_line_before = std::find_if( + lines_before.begin(), + lines_before.end(), + [first_endpoint](SparsePointGridInclusiveImpl::SparsePointGridInclusiveElem found_path) + { + return canConnectToPolyline(first_endpoint, found_path); + }); + std::vector> lines_after = line_bucket_grid.getNearby(last_endpoint, coincident_point_distance_); + auto close_line_after = std::find_if( + lines_after.begin(), + lines_after.end(), + [last_endpoint](SparsePointGridInclusiveImpl::SparsePointGridInclusiveElem found_path) + { + return canConnectToPolyline(last_endpoint, found_path); + }); + + while (close_line_before != lines_before.end()) { Path* first = close_line_before->val; - result.push_front(first); //Store this one in the sequence. It's a good one. - size_t farthest_vertex = getFarthestEndpoint(first, close_line_before->point); //Get to the opposite side. + result.push_front(first); // Store this one in the sequence. It's a good one. + size_t farthest_vertex = getFarthestEndpoint(first, close_line_before->point); // Get to the opposite side. first->start_vertex_ = farthest_vertex; first->backwards_ = farthest_vertex != 0; first_endpoint = (*first->converted_)[farthest_vertex]; - lines_before = line_bucket_grid.getNearby(first_endpoint, coincident_point_distance); - close_line_before = std::find_if(lines_before.begin(), lines_before.end(), [first_endpoint](SparsePointGridInclusiveImpl::SparsePointGridInclusiveElem found_path) { - return canConnectToPolyline(first_endpoint, found_path); - }); + lines_before = line_bucket_grid.getNearby(first_endpoint, coincident_point_distance_); + close_line_before = std::find_if( + lines_before.begin(), + lines_before.end(), + [first_endpoint](SparsePointGridInclusiveImpl::SparsePointGridInclusiveElem found_path) + { + return canConnectToPolyline(first_endpoint, found_path); + }); } - while(close_line_after != lines_after.end()) + while (close_line_after != lines_after.end()) { Path* last = close_line_after->val; result.push_back(last); - size_t farthest_vertex = getFarthestEndpoint(last, close_line_after->point); //Get to the opposite side. + size_t farthest_vertex = getFarthestEndpoint(last, close_line_after->point); // Get to the opposite side. last->start_vertex_ = (farthest_vertex == 0) ? last->converted_->size() - 1 : 0; last->backwards_ = farthest_vertex != 0; last_endpoint = (*last->converted_)[farthest_vertex]; - lines_after = line_bucket_grid.getNearby(last_endpoint, coincident_point_distance); - close_line_after = std::find_if(lines_after.begin(), lines_after.end(), [last_endpoint](SparsePointGridInclusiveImpl::SparsePointGridInclusiveElem found_path) { - return canConnectToPolyline(last_endpoint, found_path); - }); + lines_after = line_bucket_grid.getNearby(last_endpoint, coincident_point_distance_); + close_line_after = std::find_if( + lines_after.begin(), + lines_after.end(), + [last_endpoint](SparsePointGridInclusiveImpl::SparsePointGridInclusiveElem found_path) + { + return canConnectToPolyline(last_endpoint, found_path); + }); } - //Figure out which of the two endpoints to start with: The one monotonically earliest. + // Figure out which of the two endpoints to start with: The one monotonically earliest. const coord_t first_projection = dot(first_endpoint, monotonic_vector); const coord_t last_projection = dot(last_endpoint, monotonic_vector); - //If the last endpoint should be printed first (unlikely due to monotonic start, but possible), flip the whole polyline! - if(last_projection < first_projection) + // If the last endpoint should be printed first (unlikely due to monotonic start, but possible), flip the whole polyline! + if (last_projection < first_projection) { std::reverse(result.begin(), result.end()); - for(Path* path : result) //Also reverse their start_vertex. + for (Path* path : result) // Also reverse their start_vertex. { path->start_vertex_ = (path->start_vertex_ == 0) ? path->converted_->size() - 1 : 0; - path->backwards_ = !path->backwards_; + path->backwards_ = ! path->backwards_; } } - if(result.size() == 1) + if (result.size() == 1) { - result[0]->start_vertex_ = result[0]->converted_->size(); //Reset start vertex as "unknown" again if it's not a string of polylines. + result[0]->start_vertex_ = result[0]->converted_->size(); // Reset start vertex as "unknown" again if it's not a string of polylines. } return result; } @@ -376,7 +407,7 @@ class PathOrderMonotonic : public PathOrder { const coord_t front_dist = vSize2(polyline->converted_->front() - point); const coord_t back_dist = vSize2(polyline->converted_->back() - point); - if(front_dist < back_dist) + if (front_dist < back_dist) { return polyline->converted_->size() - 1; } @@ -398,50 +429,49 @@ class PathOrderMonotonic : public PathOrder */ std::vector getOverlappingLines(const typename std::vector::iterator polyline_it, const Point perpendicular, const std::vector& polylines) { - const coord_t max_adjacent_projected_distance = max_adjacent_distance * monotonic_vector_resolution; - //How far this extends in the monotonic direction, to make sure we only go up to max_adjacent_distance in that direction. - const coord_t start_monotonic = dot((*polyline_it)->converted_->front(), monotonic_vector); - const coord_t end_monotonic = dot((*polyline_it)->converted_->back(), monotonic_vector); + const coord_t max_adjacent_projected_distance = max_adjacent_distance_ * monotonic_vector_resolution_; + // How far this extends in the monotonic direction, to make sure we only go up to max_adjacent_distance in that direction. + const coord_t start_monotonic = dot((*polyline_it)->converted_->front(), monotonic_vector_); + const coord_t end_monotonic = dot((*polyline_it)->converted_->back(), monotonic_vector_); const coord_t my_farthest_monotonic = std::max(start_monotonic, end_monotonic); - const coord_t my_closest_monotonic = std::min(start_monotonic, end_monotonic); + const coord_t my_closest_monotonic = std::min(start_monotonic, end_monotonic); const coord_t my_farthest_monotonic_padded = my_farthest_monotonic + max_adjacent_projected_distance; - const coord_t my_closest_monotonic_padded = my_closest_monotonic - max_adjacent_projected_distance; - //How far this line reaches in the perpendicular direction -- the range at which the line overlaps other lines. + const coord_t my_closest_monotonic_padded = my_closest_monotonic - max_adjacent_projected_distance; + // How far this line reaches in the perpendicular direction -- the range at which the line overlaps other lines. const coord_t my_start = dot((*polyline_it)->converted_->front(), perpendicular); - const coord_t my_end = dot((*polyline_it)->converted_->back(), perpendicular); + const coord_t my_end = dot((*polyline_it)->converted_->back(), perpendicular); const coord_t my_farthest = std::max(my_start, my_end); - const coord_t my_closest = std::min(my_start, my_end); + const coord_t my_closest = std::min(my_start, my_end); const coord_t my_farthest_padded = my_farthest + max_adjacent_projected_distance; - const coord_t my_closest_padded = my_closest - max_adjacent_projected_distance; + const coord_t my_closest_padded = my_closest - max_adjacent_projected_distance; std::vector overlapping_lines; - for(auto overlapping_line = polyline_it + 1; overlapping_line != polylines.end(); overlapping_line++) + for (auto overlapping_line = polyline_it + 1; overlapping_line != polylines.end(); overlapping_line++) { - //Don't go beyond the maximum adjacent distance. - const coord_t start_their_projection = dot((*overlapping_line)->converted_->front(), monotonic_vector); - const coord_t end_their_projection = dot((*overlapping_line)->converted_->back(), monotonic_vector); + // Don't go beyond the maximum adjacent distance. + const coord_t start_their_projection = dot((*overlapping_line)->converted_->front(), monotonic_vector_); + const coord_t end_their_projection = dot((*overlapping_line)->converted_->back(), monotonic_vector_); const coord_t their_farthest_projection = std::max(start_their_projection, end_their_projection); const coord_t their_closest_projection = std::min(start_their_projection, end_their_projection); // Multiply by the length of the vector since we need to compare actual distances here. - if(their_closest_projection > my_farthest_monotonic_padded || my_closest_monotonic_padded > their_farthest_projection) + if (their_closest_projection > my_farthest_monotonic_padded || my_closest_monotonic_padded > their_farthest_projection) { - break; //Too far. This line and all subsequent lines are not adjacent anymore, even though they might be side-by-side. + break; // Too far. This line and all subsequent lines are not adjacent anymore, even though they might be side-by-side. } - //Does this one overlap? + // Does this one overlap? const coord_t their_start = dot((*overlapping_line)->converted_->front(), perpendicular); const coord_t their_end = dot((*overlapping_line)->converted_->back(), perpendicular); const coord_t their_farthest = std::max(their_start, their_end); - const coord_t their_closest = std::min(their_start, their_end); + const coord_t their_closest = std::min(their_start, their_end); /*There are 5 possible cases of overlapping: - We are behind them, partially overlapping. my_start is between their_start and their_end. - We are in front of them, partially overlapping. my_end is between their_start and their_end. - We are a smaller line, they completely overlap us. Both my_start and my_end are between their_start and their_end. (Caught with the first 2 conditions already.) - We are a bigger line, and completely overlap them. Both their_start and their_end are between my_start and my_end. - Lines are exactly equal. Start and end are the same. (Caught with the previous condition too.)*/ - if( (my_closest_padded >= their_closest && my_closest_padded <= their_farthest) - || (my_farthest_padded >= their_closest && my_farthest_padded <= their_farthest) - || (their_closest >= my_closest_padded && their_farthest <= my_farthest_padded)) + if ((my_closest_padded >= their_closest && my_closest_padded <= their_farthest) || (my_farthest_padded >= their_closest && my_farthest_padded <= their_farthest) + || (their_closest >= my_closest_padded && their_farthest <= my_farthest_padded)) { overlapping_lines.push_back(*overlapping_line); } @@ -459,9 +489,9 @@ class PathOrderMonotonic : public PathOrder * ``coord_t`` data type, but not so long as to cause integer overflows if * the quadratic is multiplied by a projection length. */ - constexpr static coord_t monotonic_vector_resolution = 1000; + constexpr static coord_t monotonic_vector_resolution_ = 1000; - private: +private: /*! * Predicate to check if a nearby path is okay for polylines to connect * with. @@ -476,11 +506,11 @@ class PathOrderMonotonic : public PathOrder */ static bool canConnectToPolyline(const Point nearby_endpoint, SparsePointGridInclusiveImpl::SparsePointGridInclusiveElem found_path) { - return found_path.val->start_vertex_ == found_path.val->converted_->size() //Don't find any line already in the string. - && vSize2(found_path.point - nearby_endpoint) < coincident_point_distance * coincident_point_distance; //And only find close lines. + return found_path.val->start_vertex_ == found_path.val->converted_->size() // Don't find any line already in the string. + && vSize2(found_path.point - nearby_endpoint) < coincident_point_distance_ * coincident_point_distance_; // And only find close lines. } }; -} +} // namespace cura -#endif //PATHORDERMONOTONIC_H \ No newline at end of file +#endif // PATHORDERMONOTONIC_H diff --git a/include/TreeModelVolumes.h b/include/TreeModelVolumes.h index 4454dc3b6a..8418a9d2c4 100644 --- a/include/TreeModelVolumes.h +++ b/include/TreeModelVolumes.h @@ -372,59 +372,59 @@ class TreeModelVolumes /*! * \brief Whether the precalculate was called, meaning every required value should be cached. */ - bool precalculated = false; + bool precalculated_ = false; /*! * \brief Whether the precalculate was called and finished, meaning every required value should be cached. */ - bool precalculationFinished = false; + bool precalculation_finished_ = false; /*! * \brief The index to access the outline corresponding with the currently processing mesh */ - size_t current_outline_idx; + size_t current_outline_idx_; /*! * \brief The minimum required clearance between the model and the tree branches */ - coord_t current_min_xy_dist; + coord_t current_min_xy_dist_; /*! * \brief The difference between the minimum required clearance between the model and the tree branches and the regular one. */ - coord_t current_min_xy_dist_delta; + coord_t current_min_xy_dist_delta_; /*! * \brief The top most layer where there is no anti_overhang on any layer below */ - LayerIndex max_layer_idx_without_blocker; + LayerIndex max_layer_idx_without_blocker_; /*! * \brief Does at least one mesh allow support to rest on a model. */ - bool support_rests_on_model; + bool support_rests_on_model_; /*! * \brief The progress of the precalculate function for communicating it to the progress bar. */ - coord_t precalculation_progress = 0; + coord_t precalculation_progress_ = 0; /*! * \brief The progress multiplier of all values added progress bar. * Required for the progress bar the behave as expected when areas have to be calculated multiple times */ - double progress_multiplier; + double progress_multiplier_; /*! * \brief The progress offset added to all values communicated to the progress bar. * Required for the progress bar the behave as expected when areas have to be calculated multiple times */ - double progress_offset; + double progress_offset_; /*! * \brief Increase radius in the resulting drawn branches, even if the avoidance does not allow it. Will be cut later to still fit. */ - coord_t increase_until_radius; + coord_t increase_until_radius_; /*! * \brief Polygons representing the limits of the printable area of the @@ -455,12 +455,12 @@ class TreeModelVolumes /*! * \brief Smallest radius a branch can have. This is the radius of a SupportElement with DTT=0. */ - coord_t radius_0; + coord_t radius_0_; /*! * \brief Does the main model require regular avoidance, or only avoidance to model. */ - RestPreference support_rest_preference; + RestPreference support_rest_preference_; /*! * \brief Caches for the collision, avoidance and areas on the model where support can be placed safely @@ -517,9 +517,9 @@ class TreeModelVolumes mutable std::unordered_map wall_restrictions_cache_min_; std::unique_ptr critical_wall_restrictions_cache_min_ = std::make_unique(); - std::unique_ptr critical_progress = std::make_unique(); + std::unique_ptr critical_progress_ = std::make_unique(); - Simplify simplifier = Simplify(0, 0, 0); // a simplifier to simplify polygons. Will be properly initialised in the constructor. + Simplify simplifier_ = Simplify(0, 0, 0); // a simplifier to simplify polygons. Will be properly initialised in the constructor. }; } diff --git a/include/WallToolPaths.h b/include/WallToolPaths.h index 810357a7a6..22e1f13a3d 100644 --- a/include/WallToolPaths.h +++ b/include/WallToolPaths.h @@ -107,22 +107,22 @@ class WallToolPaths static void simplifyToolPaths(std::vector& toolpaths, const Settings& settings); private: - const Polygons& outline; // toolpaths; // toolpaths_; // unsupported_points; + std::list unsupported_points_; /*! * Links the unsupported points to a grid point, so that we can quickly look * up the cell belonging to a certain position in the grid. */ - std::unordered_map::iterator> unsupported_points_grid; + std::unordered_map::iterator> unsupported_points_grid_; }; -} +} // namespace cura -#endif //LIGHTNING_DISTANCE_FIELD_H \ No newline at end of file +#endif // LIGHTNING_DISTANCE_FIELD_H diff --git a/src/BeadingStrategy/BeadingStrategy.cpp b/src/BeadingStrategy/BeadingStrategy.cpp index 17cc6a5e1f..5b3f81583f 100644 --- a/src/BeadingStrategy/BeadingStrategy.cpp +++ b/src/BeadingStrategy/BeadingStrategy.cpp @@ -14,22 +14,22 @@ BeadingStrategy::BeadingStrategy( Ratio wall_add_middle_threshold, coord_t default_transition_length, double transitioning_angle) - : optimal_width(optimal_width) - , wall_split_middle_threshold(wall_split_middle_threshold) - , wall_add_middle_threshold(wall_add_middle_threshold) - , default_transition_length(default_transition_length) - , transitioning_angle(transitioning_angle) + : optimal_width_(optimal_width) + , wall_split_middle_threshold_(wall_split_middle_threshold) + , wall_add_middle_threshold_(wall_add_middle_threshold) + , default_transition_length_(default_transition_length) + , transitioning_angle_(transitioning_angle) { - name = "Unknown"; + name_ = "Unknown"; } BeadingStrategy::BeadingStrategy(const BeadingStrategy& other) - : optimal_width(other.optimal_width) - , wall_split_middle_threshold(other.wall_split_middle_threshold) - , wall_add_middle_threshold(other.wall_add_middle_threshold) - , default_transition_length(other.default_transition_length) - , transitioning_angle(other.transitioning_angle) - , name(other.name) + : optimal_width_(other.optimal_width_) + , wall_split_middle_threshold_(other.wall_split_middle_threshold_) + , wall_add_middle_threshold_(other.wall_add_middle_threshold_) + , default_transition_length_(other.default_transition_length_) + , transitioning_angle_(other.transitioning_angle_) + , name_(other.name_) { } @@ -39,7 +39,7 @@ coord_t BeadingStrategy::getTransitioningLength(coord_t lower_bead_count) const { return 10; } - return default_transition_length; + return default_transition_length_; } double BeadingStrategy::getTransitionAnchorPos(coord_t lower_bead_count) const @@ -57,44 +57,44 @@ std::vector BeadingStrategy::getNonlinearThicknesses(coord_t lower_bead std::string BeadingStrategy::toString() const { - return name; + return name_; } coord_t BeadingStrategy::getDefaultTransitionLength() const { - return default_transition_length; + return default_transition_length_; } coord_t BeadingStrategy::getOptimalWidth() const { - return optimal_width; + return optimal_width_; } Ratio BeadingStrategy::getSplitMiddleThreshold() const { - return wall_split_middle_threshold; + return wall_split_middle_threshold_; } Ratio BeadingStrategy::getAddMiddleThreshold() const { - return wall_add_middle_threshold; + return wall_add_middle_threshold_; } AngleRadians BeadingStrategy::getTransitioningAngle() const { - return transitioning_angle; + return transitioning_angle_; } coord_t BeadingStrategy::getOptimalThickness(coord_t bead_count) const { - return optimal_width * bead_count; + return optimal_width_ * bead_count; } coord_t BeadingStrategy::getTransitionThickness(coord_t lower_bead_count) const { const coord_t lower_ideal_width = getOptimalThickness(lower_bead_count); const coord_t higher_ideal_width = getOptimalThickness(lower_bead_count + 1); - const Ratio threshold = lower_bead_count % 2 == 1 ? wall_split_middle_threshold : wall_add_middle_threshold; + const Ratio threshold = lower_bead_count % 2 == 1 ? wall_split_middle_threshold_ : wall_add_middle_threshold_; return lower_ideal_width + threshold * (higher_ideal_width - lower_ideal_width); } diff --git a/src/BeadingStrategy/DistributedBeadingStrategy.cpp b/src/BeadingStrategy/DistributedBeadingStrategy.cpp index 7480d94e6e..84dd612c9b 100644 --- a/src/BeadingStrategy/DistributedBeadingStrategy.cpp +++ b/src/BeadingStrategy/DistributedBeadingStrategy.cpp @@ -18,13 +18,13 @@ DistributedBeadingStrategy::DistributedBeadingStrategy( { if (distribution_radius >= 2) { - one_over_distribution_radius_squared = 1.0f / (distribution_radius - 1) * 1.0f / (distribution_radius - 1); + one_over_distribution_radius_squared_ = 1.0f / (distribution_radius - 1) * 1.0f / (distribution_radius - 1); } else { - one_over_distribution_radius_squared = 1.0f / 1 * 1.0f / 1; + one_over_distribution_radius_squared_ = 1.0f / 1 * 1.0f / 1; } - name = "DistributedBeadingStrategy"; + name_ = "DistributedBeadingStrategy"; } DistributedBeadingStrategy::Beading DistributedBeadingStrategy::compute(coord_t thickness, coord_t bead_count) const @@ -34,13 +34,13 @@ DistributedBeadingStrategy::Beading DistributedBeadingStrategy::compute(coord_t ret.total_thickness = thickness; if (bead_count > 2) { - const coord_t to_be_divided = thickness - bead_count * optimal_width; + const coord_t to_be_divided = thickness - bead_count * optimal_width_; const double middle = static_cast(bead_count - 1) / 2; const auto getWeight = [middle, this](coord_t bead_idx) { const double dev_from_middle = bead_idx - middle; - return std::max(0.0, 1.0 - one_over_distribution_radius_squared * dev_from_middle * dev_from_middle); + return std::max(0.0, 1.0 - one_over_distribution_radius_squared_ * dev_from_middle * dev_from_middle); }; std::vector weights; @@ -55,7 +55,7 @@ DistributedBeadingStrategy::Beading DistributedBeadingStrategy::compute(coord_t { const double weight_fraction = weights[bead_idx] / total_weight; const coord_t splitup_left_over_weight = to_be_divided * weight_fraction; - const coord_t width = optimal_width + splitup_left_over_weight; + const coord_t width = optimal_width_ + splitup_left_over_weight; if (bead_idx == 0) { ret.toolpath_locations.emplace_back(width / 2); @@ -94,9 +94,9 @@ DistributedBeadingStrategy::Beading DistributedBeadingStrategy::compute(coord_t coord_t DistributedBeadingStrategy::getOptimalBeadCount(coord_t thickness) const { - const coord_t naive_count = thickness / optimal_width; // How many lines we can fit in for sure. - const coord_t remainder = thickness - naive_count * optimal_width; // Space left after fitting that many lines. - const coord_t minimum_line_width = optimal_width * (naive_count % 2 == 1 ? wall_split_middle_threshold : wall_add_middle_threshold); + const coord_t naive_count = thickness / optimal_width_; // How many lines we can fit in for sure. + const coord_t remainder = thickness - naive_count * optimal_width_; // Space left after fitting that many lines. + const coord_t minimum_line_width = optimal_width_ * (naive_count % 2 == 1 ? wall_split_middle_threshold_ : wall_add_middle_threshold_); return naive_count + (remainder >= minimum_line_width); // If there's enough space, fit an extra one. } diff --git a/src/BeadingStrategy/LimitedBeadingStrategy.cpp b/src/BeadingStrategy/LimitedBeadingStrategy.cpp index 8b612ce419..8327cd55b7 100644 --- a/src/BeadingStrategy/LimitedBeadingStrategy.cpp +++ b/src/BeadingStrategy/LimitedBeadingStrategy.cpp @@ -12,23 +12,23 @@ namespace cura std::string LimitedBeadingStrategy::toString() const { - return std::string("LimitedBeadingStrategy+") + parent->toString(); + return std::string("LimitedBeadingStrategy+") + parent_->toString(); } coord_t LimitedBeadingStrategy::getTransitioningLength(coord_t lower_bead_count) const { - return parent->getTransitioningLength(lower_bead_count); + return parent_->getTransitioningLength(lower_bead_count); } double LimitedBeadingStrategy::getTransitionAnchorPos(coord_t lower_bead_count) const { - return parent->getTransitionAnchorPos(lower_bead_count); + return parent_->getTransitionAnchorPos(lower_bead_count); } LimitedBeadingStrategy::LimitedBeadingStrategy(const coord_t max_bead_count, BeadingStrategyPtr parent) : BeadingStrategy(*parent) - , max_bead_count(max_bead_count) - , parent(std::move(parent)) + , max_bead_count_(max_bead_count) + , parent_(std::move(parent)) { if (max_bead_count % 2 == 1) { @@ -38,28 +38,28 @@ LimitedBeadingStrategy::LimitedBeadingStrategy(const coord_t max_bead_count, Bea LimitedBeadingStrategy::Beading LimitedBeadingStrategy::compute(coord_t thickness, coord_t bead_count) const { - if (bead_count <= max_bead_count) + if (bead_count <= max_bead_count_) { - Beading ret = parent->compute(thickness, bead_count); + Beading ret = parent_->compute(thickness, bead_count); bead_count = ret.toolpath_locations.size(); - if (bead_count % 2 == 0 && bead_count == max_bead_count) + if (bead_count % 2 == 0 && bead_count == max_bead_count_) { - const coord_t innermost_toolpath_location = ret.toolpath_locations[max_bead_count / 2 - 1]; - const coord_t innermost_toolpath_width = ret.bead_widths[max_bead_count / 2 - 1]; - ret.toolpath_locations.insert(ret.toolpath_locations.begin() + max_bead_count / 2, innermost_toolpath_location + innermost_toolpath_width / 2); - ret.bead_widths.insert(ret.bead_widths.begin() + max_bead_count / 2, 0); + const coord_t innermost_toolpath_location = ret.toolpath_locations[max_bead_count_ / 2 - 1]; + const coord_t innermost_toolpath_width = ret.bead_widths[max_bead_count_ / 2 - 1]; + ret.toolpath_locations.insert(ret.toolpath_locations.begin() + max_bead_count_ / 2, innermost_toolpath_location + innermost_toolpath_width / 2); + ret.bead_widths.insert(ret.bead_widths.begin() + max_bead_count_ / 2, 0); } return ret; } - assert(bead_count == max_bead_count + 1); - if (bead_count != max_bead_count + 1) + assert(bead_count == max_bead_count_ + 1); + if (bead_count != max_bead_count_ + 1) { - RUN_ONCE(spdlog::warn("Too many beads! {} != {}", bead_count, max_bead_count + 1)); + RUN_ONCE(spdlog::warn("Too many beads! {} != {}", bead_count, max_bead_count_ + 1)); } - coord_t optimal_thickness = parent->getOptimalThickness(max_bead_count); - Beading ret = parent->compute(optimal_thickness, max_bead_count); + coord_t optimal_thickness = parent_->getOptimalThickness(max_bead_count_); + Beading ret = parent_->compute(optimal_thickness, max_bead_count_); bead_count = ret.toolpath_locations.size(); ret.left_over += thickness - ret.total_thickness; ret.total_thickness = thickness; @@ -77,13 +77,13 @@ LimitedBeadingStrategy::Beading LimitedBeadingStrategy::compute(coord_t thicknes // Create a "fake" inner wall with 0 width to indicate the edge of the walled area. // This wall can then be used by other structures to e.g. fill the infill area adjacent to the variable-width walls. - coord_t innermost_toolpath_location = ret.toolpath_locations[max_bead_count / 2 - 1]; - coord_t innermost_toolpath_width = ret.bead_widths[max_bead_count / 2 - 1]; - ret.toolpath_locations.insert(ret.toolpath_locations.begin() + max_bead_count / 2, innermost_toolpath_location + innermost_toolpath_width / 2); - ret.bead_widths.insert(ret.bead_widths.begin() + max_bead_count / 2, 0); + coord_t innermost_toolpath_location = ret.toolpath_locations[max_bead_count_ / 2 - 1]; + coord_t innermost_toolpath_width = ret.bead_widths[max_bead_count_ / 2 - 1]; + ret.toolpath_locations.insert(ret.toolpath_locations.begin() + max_bead_count_ / 2, innermost_toolpath_location + innermost_toolpath_width / 2); + ret.bead_widths.insert(ret.bead_widths.begin() + max_bead_count_ / 2, 0); // Symmetry on both sides. Symmetry is guaranteed since this code is stopped early if the bead_count <= max_bead_count, and never reaches this point then. - const size_t opposite_bead = bead_count - (max_bead_count / 2 - 1); + const size_t opposite_bead = bead_count - (max_bead_count_ / 2 - 1); innermost_toolpath_location = ret.toolpath_locations[opposite_bead]; innermost_toolpath_width = ret.bead_widths[opposite_bead]; ret.toolpath_locations.insert(ret.toolpath_locations.begin() + opposite_bead, innermost_toolpath_location - innermost_toolpath_width / 2); @@ -94,42 +94,42 @@ LimitedBeadingStrategy::Beading LimitedBeadingStrategy::compute(coord_t thicknes coord_t LimitedBeadingStrategy::getOptimalThickness(coord_t bead_count) const { - if (bead_count <= max_bead_count) + if (bead_count <= max_bead_count_) { - return parent->getOptimalThickness(bead_count); + return parent_->getOptimalThickness(bead_count); } return 10000000; // 10 meter } coord_t LimitedBeadingStrategy::getTransitionThickness(coord_t lower_bead_count) const { - if (lower_bead_count < max_bead_count) + if (lower_bead_count < max_bead_count_) { - return parent->getTransitionThickness(lower_bead_count); + return parent_->getTransitionThickness(lower_bead_count); } - if (lower_bead_count == max_bead_count) + if (lower_bead_count == max_bead_count_) { - return parent->getOptimalThickness(lower_bead_count + 1) - 10; + return parent_->getOptimalThickness(lower_bead_count + 1) - 10; } return 9000000; // 9 meter } coord_t LimitedBeadingStrategy::getOptimalBeadCount(coord_t thickness) const { - coord_t parent_bead_count = parent->getOptimalBeadCount(thickness); - if (parent_bead_count <= max_bead_count) + coord_t parent_bead_count = parent_->getOptimalBeadCount(thickness); + if (parent_bead_count <= max_bead_count_) { - return parent->getOptimalBeadCount(thickness); + return parent_->getOptimalBeadCount(thickness); } - else if (parent_bead_count == max_bead_count + 1) + else if (parent_bead_count == max_bead_count_ + 1) { - if (thickness < parent->getOptimalThickness(max_bead_count + 1) - 10) - return max_bead_count; + if (thickness < parent_->getOptimalThickness(max_bead_count_ + 1) - 10) + return max_bead_count_; else - return max_bead_count + 1; + return max_bead_count_ + 1; } else - return max_bead_count + 1; + return max_bead_count_ + 1; } } // namespace cura diff --git a/src/BeadingStrategy/OuterWallInsetBeadingStrategy.cpp b/src/BeadingStrategy/OuterWallInsetBeadingStrategy.cpp index bae2cf6649..c7d81cd798 100644 --- a/src/BeadingStrategy/OuterWallInsetBeadingStrategy.cpp +++ b/src/BeadingStrategy/OuterWallInsetBeadingStrategy.cpp @@ -9,41 +9,41 @@ namespace cura { OuterWallInsetBeadingStrategy::OuterWallInsetBeadingStrategy(coord_t outer_wall_offset, BeadingStrategyPtr parent) : BeadingStrategy(*parent), - parent(std::move(parent)), - outer_wall_offset(outer_wall_offset) + parent_(std::move(parent)), + outer_wall_offset_(outer_wall_offset) { - name = "OuterWallOfsetBeadingStrategy"; + name_ = "OuterWallOfsetBeadingStrategy"; } coord_t OuterWallInsetBeadingStrategy::getOptimalThickness(coord_t bead_count) const { - return parent->getOptimalThickness(bead_count); + return parent_->getOptimalThickness(bead_count); } coord_t OuterWallInsetBeadingStrategy::getTransitionThickness(coord_t lower_bead_count) const { - return parent->getTransitionThickness(lower_bead_count); + return parent_->getTransitionThickness(lower_bead_count); } coord_t OuterWallInsetBeadingStrategy::getOptimalBeadCount(coord_t thickness) const { - return parent->getOptimalBeadCount(thickness); + return parent_->getOptimalBeadCount(thickness); } coord_t OuterWallInsetBeadingStrategy::getTransitioningLength(coord_t lower_bead_count) const { - return parent->getTransitioningLength(lower_bead_count); + return parent_->getTransitioningLength(lower_bead_count); } std::string OuterWallInsetBeadingStrategy::toString() const { - return std::string("OuterWallOfsetBeadingStrategy+") + parent->toString(); + return std::string("OuterWallOfsetBeadingStrategy+") + parent_->toString(); } BeadingStrategy::Beading OuterWallInsetBeadingStrategy::compute(coord_t thickness, coord_t bead_count) const { - Beading ret = parent->compute(thickness, bead_count); + Beading ret = parent_->compute(thickness, bead_count); // Actual count and thickness as represented by extant walls. Don't count any potential zero-width 'signaling' walls. bead_count = std::count_if(ret.bead_widths.begin(), ret.bead_widths.end(), [](const coord_t width) { return width > 0; }); @@ -55,7 +55,7 @@ BeadingStrategy::Beading OuterWallInsetBeadingStrategy::compute(coord_t thicknes } // Actually move the outer wall inside. Ensure that the outer wall never goes beyond the middle line. - ret.toolpath_locations[0] = std::min(ret.toolpath_locations[0] + outer_wall_offset, thickness / 2); + ret.toolpath_locations[0] = std::min(ret.toolpath_locations[0] + outer_wall_offset_, thickness / 2); return ret; } diff --git a/src/BeadingStrategy/RedistributeBeadingStrategy.cpp b/src/BeadingStrategy/RedistributeBeadingStrategy.cpp index c2109bed83..ebceddf6e7 100644 --- a/src/BeadingStrategy/RedistributeBeadingStrategy.cpp +++ b/src/BeadingStrategy/RedistributeBeadingStrategy.cpp @@ -11,18 +11,18 @@ namespace cura RedistributeBeadingStrategy::RedistributeBeadingStrategy(const coord_t optimal_width_outer, const Ratio minimum_variable_line_ratio, BeadingStrategyPtr parent) : BeadingStrategy(*parent) - , parent(std::move(parent)) - , optimal_width_outer(optimal_width_outer) - , minimum_variable_line_ratio(minimum_variable_line_ratio) + , parent_(std::move(parent)) + , optimal_width_outer_(optimal_width_outer) + , minimum_variable_line_ratio_(minimum_variable_line_ratio) { - name = "RedistributeBeadingStrategy"; + name_ = "RedistributeBeadingStrategy"; } coord_t RedistributeBeadingStrategy::getOptimalThickness(coord_t bead_count) const { const coord_t inner_bead_count = std::max(static_cast(0), bead_count - 2); const coord_t outer_bead_count = bead_count - inner_bead_count; - return parent->getOptimalThickness(inner_bead_count) + optimal_width_outer * outer_bead_count; + return parent_->getOptimalThickness(inner_bead_count) + optimal_width_outer_ * outer_bead_count; } coord_t RedistributeBeadingStrategy::getTransitionThickness(coord_t lower_bead_count) const @@ -30,40 +30,40 @@ coord_t RedistributeBeadingStrategy::getTransitionThickness(coord_t lower_bead_c switch (lower_bead_count) { case 0: - return minimum_variable_line_ratio * optimal_width_outer; + return minimum_variable_line_ratio_ * optimal_width_outer_; case 1: - return (1.0 + parent->getSplitMiddleThreshold()) * optimal_width_outer; + return (1.0 + parent_->getSplitMiddleThreshold()) * optimal_width_outer_; default: - return parent->getTransitionThickness(lower_bead_count - 2) + 2 * optimal_width_outer; + return parent_->getTransitionThickness(lower_bead_count - 2) + 2 * optimal_width_outer_; } } coord_t RedistributeBeadingStrategy::getOptimalBeadCount(coord_t thickness) const { - if (thickness < minimum_variable_line_ratio * optimal_width_outer) + if (thickness < minimum_variable_line_ratio_ * optimal_width_outer_) { return 0; } - if (thickness <= 2 * optimal_width_outer) + if (thickness <= 2 * optimal_width_outer_) { - return thickness > (1.0 + parent->getSplitMiddleThreshold()) * optimal_width_outer ? 2 : 1; + return thickness > (1.0 + parent_->getSplitMiddleThreshold()) * optimal_width_outer_ ? 2 : 1; } - return parent->getOptimalBeadCount(thickness - 2 * optimal_width_outer) + 2; + return parent_->getOptimalBeadCount(thickness - 2 * optimal_width_outer_) + 2; } coord_t RedistributeBeadingStrategy::getTransitioningLength(coord_t lower_bead_count) const { - return parent->getTransitioningLength(lower_bead_count); + return parent_->getTransitioningLength(lower_bead_count); } double RedistributeBeadingStrategy::getTransitionAnchorPos(coord_t lower_bead_count) const { - return parent->getTransitionAnchorPos(lower_bead_count); + return parent_->getTransitionAnchorPos(lower_bead_count); } std::string RedistributeBeadingStrategy::toString() const { - return toString() + parent->toString(); + return toString() + parent_->toString(); } BeadingStrategy::Beading RedistributeBeadingStrategy::compute(coord_t thickness, coord_t bead_count) const @@ -71,7 +71,7 @@ BeadingStrategy::Beading RedistributeBeadingStrategy::compute(coord_t thickness, Beading ret; // Take care of all situations in which no lines are actually produced: - if (bead_count == 0 || thickness < minimum_variable_line_ratio * optimal_width_outer) + if (bead_count == 0 || thickness < minimum_variable_line_ratio_ * optimal_width_outer_) { ret.left_over = thickness; ret.total_thickness = thickness; @@ -80,18 +80,18 @@ BeadingStrategy::Beading RedistributeBeadingStrategy::compute(coord_t thickness, // Compute the beadings of the inner walls, if any: const coord_t inner_bead_count = bead_count - 2; - const coord_t inner_thickness = thickness - 2 * optimal_width_outer; + const coord_t inner_thickness = thickness - 2 * optimal_width_outer_; if (inner_bead_count > 0 && inner_thickness > 0) { - ret = parent->compute(inner_thickness, inner_bead_count); + ret = parent_->compute(inner_thickness, inner_bead_count); for (auto& toolpath_location : ret.toolpath_locations) { - toolpath_location += optimal_width_outer; + toolpath_location += optimal_width_outer_; } } // Insert the outer wall(s) around the previously computed inner wall(s), which may be empty: - const coord_t actual_outer_thickness = bead_count > 2 ? std::min(thickness / 2, optimal_width_outer) : thickness / bead_count; + const coord_t actual_outer_thickness = bead_count > 2 ? std::min(thickness / 2, optimal_width_outer_) : thickness / bead_count; ret.bead_widths.insert(ret.bead_widths.begin(), actual_outer_thickness); ret.toolpath_locations.insert(ret.toolpath_locations.begin(), actual_outer_thickness / 2); if (bead_count > 1) diff --git a/src/BeadingStrategy/WideningBeadingStrategy.cpp b/src/BeadingStrategy/WideningBeadingStrategy.cpp index 368eaaed87..fbabea586e 100644 --- a/src/BeadingStrategy/WideningBeadingStrategy.cpp +++ b/src/BeadingStrategy/WideningBeadingStrategy.cpp @@ -8,26 +8,26 @@ namespace cura WideningBeadingStrategy::WideningBeadingStrategy(BeadingStrategyPtr parent, const coord_t min_input_width, const coord_t min_output_width) : BeadingStrategy(*parent) - , parent(std::move(parent)) - , min_input_width(min_input_width) - , min_output_width(min_output_width) + , parent_(std::move(parent)) + , min_input_width_(min_input_width) + , min_output_width_(min_output_width) { } std::string WideningBeadingStrategy::toString() const { - return std::string("Widening+") + parent->toString(); + return std::string("Widening+") + parent_->toString(); } WideningBeadingStrategy::Beading WideningBeadingStrategy::compute(coord_t thickness, coord_t bead_count) const { - if (thickness < optimal_width) + if (thickness < optimal_width_) { Beading ret; ret.total_thickness = thickness; - if (thickness >= min_input_width) + if (thickness >= min_input_width_) { - ret.bead_widths.emplace_back(std::max(thickness, min_output_width)); + ret.bead_widths.emplace_back(std::max(thickness, min_output_width_)); ret.toolpath_locations.emplace_back(thickness / 2); } else @@ -38,52 +38,52 @@ WideningBeadingStrategy::Beading WideningBeadingStrategy::compute(coord_t thickn } else { - return parent->compute(thickness, bead_count); + return parent_->compute(thickness, bead_count); } } coord_t WideningBeadingStrategy::getOptimalThickness(coord_t bead_count) const { - return parent->getOptimalThickness(bead_count); + return parent_->getOptimalThickness(bead_count); } coord_t WideningBeadingStrategy::getTransitionThickness(coord_t lower_bead_count) const { if (lower_bead_count == 0) { - return min_input_width; + return min_input_width_; } else { - return parent->getTransitionThickness(lower_bead_count); + return parent_->getTransitionThickness(lower_bead_count); } } coord_t WideningBeadingStrategy::getOptimalBeadCount(coord_t thickness) const { - if (thickness < min_input_width) + if (thickness < min_input_width_) return 0; - coord_t ret = parent->getOptimalBeadCount(thickness); - if (thickness >= min_input_width && ret < 1) + coord_t ret = parent_->getOptimalBeadCount(thickness); + if (thickness >= min_input_width_ && ret < 1) return 1; return ret; } coord_t WideningBeadingStrategy::getTransitioningLength(coord_t lower_bead_count) const { - return parent->getTransitioningLength(lower_bead_count); + return parent_->getTransitioningLength(lower_bead_count); } double WideningBeadingStrategy::getTransitionAnchorPos(coord_t lower_bead_count) const { - return parent->getTransitionAnchorPos(lower_bead_count); + return parent_->getTransitionAnchorPos(lower_bead_count); } std::vector WideningBeadingStrategy::getNonlinearThicknesses(coord_t lower_bead_count) const { std::vector ret; - ret.emplace_back(min_output_width); - std::vector pret = parent->getNonlinearThicknesses(lower_bead_count); + ret.emplace_back(min_output_width_); + std::vector pret = parent_->getNonlinearThicknesses(lower_bead_count); ret.insert(ret.end(), pret.begin(), pret.end()); return ret; } diff --git a/src/FffGcodeWriter.cpp b/src/FffGcodeWriter.cpp index 119ddfbd31..3e2831f857 100644 --- a/src/FffGcodeWriter.cpp +++ b/src/FffGcodeWriter.cpp @@ -654,7 +654,7 @@ void FffGcodeWriter::processRaft(const SliceDataStorage& storage) zig_zaggify_infill, connect_polygons, raft_outline_path.outline, - gcode_layer.configs_storage.raft_base_config.getLineWidth(), + gcode_layer.configs_storage_.raft_base_config.getLineWidth(), raft_outline_path.line_spacing, fill_overlap, infill_multiplier, @@ -677,7 +677,7 @@ void FffGcodeWriter::processRaft(const SliceDataStorage& storage) infill_comp.generate(raft_paths, raft_polygons, raftLines, base_settings, layer_nr, SectionType::ADHESION); if (! raft_paths.empty()) { - const GCodePathConfig& config = gcode_layer.configs_storage.raft_base_config; + const GCodePathConfig& config = gcode_layer.configs_storage_.raft_base_config; const ZSeamConfig z_seam_config(EZSeamType::SHORTEST, gcode_layer.getLastPlannedPositionOrStartingPosition(), EZSeamCornerPrefType::Z_SEAM_CORNER_PREF_NONE, false); InsetOrderOptimizer wall_orderer( *this, @@ -698,7 +698,7 @@ void FffGcodeWriter::processRaft(const SliceDataStorage& storage) raft_paths); wall_orderer.addToLayer(); } - gcode_layer.addLinesByOptimizer(raftLines, gcode_layer.configs_storage.raft_base_config, SpaceFillType::Lines); + gcode_layer.addLinesByOptimizer(raftLines, gcode_layer.configs_storage_.raft_base_config, SpaceFillType::Lines); raft_polygons.clear(); raftLines.clear(); @@ -759,11 +759,11 @@ void FffGcodeWriter::processRaft(const SliceDataStorage& storage) Application::getInstance().communication_->sendLayerComplete(layer_nr, z, interface_layer_height); Polygons raft_outline_path; - const coord_t small_offset = gcode_layer.configs_storage.raft_interface_config.getLineWidth() + const coord_t small_offset = gcode_layer.configs_storage_.raft_interface_config.getLineWidth() / 2; // Do this manually because of micron-movement created in corners when insetting a polygon that was offset with round joint type. raft_outline_path = storage.raftOutline.offset(-small_offset); raft_outline_path = Simplify(interface_settings).polygon(raft_outline_path); // Remove those micron-movements. - const coord_t infill_outline_width = gcode_layer.configs_storage.raft_interface_config.getLineWidth(); + const coord_t infill_outline_width = gcode_layer.configs_storage_.raft_interface_config.getLineWidth(); Polygons raft_lines; AngleDegrees fill_angle = (num_surface_layers + num_interface_layers - raft_interface_layer) % 2 ? 45 : 135; // 90 degrees rotated from the first top layer. constexpr bool zig_zaggify_infill = true; @@ -811,7 +811,7 @@ void FffGcodeWriter::processRaft(const SliceDataStorage& storage) pocket_size); std::vector raft_paths; // Should remain empty, since we have no walls. infill_comp.generate(raft_paths, raft_polygons, raft_lines, interface_settings, layer_nr, SectionType::ADHESION); - gcode_layer.addLinesByOptimizer(raft_lines, gcode_layer.configs_storage.raft_interface_config, SpaceFillType::Lines, false, 0, 1.0, last_planned_position); + gcode_layer.addLinesByOptimizer(raft_lines, gcode_layer.configs_storage_.raft_interface_config, SpaceFillType::Lines, false, 0, 1.0, last_planned_position); raft_polygons.clear(); raft_lines.clear(); @@ -878,11 +878,11 @@ void FffGcodeWriter::processRaft(const SliceDataStorage& storage) Application::getInstance().communication_->sendLayerComplete(layer_nr, z, surface_layer_height); Polygons raft_outline_path; - const coord_t small_offset = gcode_layer.configs_storage.raft_interface_config.getLineWidth() + const coord_t small_offset = gcode_layer.configs_storage_.raft_interface_config.getLineWidth() / 2; // Do this manually because of micron-movement created in corners when insetting a polygon that was offset with round joint type. raft_outline_path = storage.raftOutline.offset(-small_offset); raft_outline_path = Simplify(interface_settings).polygon(raft_outline_path); // Remove those micron-movements. - const coord_t infill_outline_width = gcode_layer.configs_storage.raft_interface_config.getLineWidth(); + const coord_t infill_outline_width = gcode_layer.configs_storage_.raft_interface_config.getLineWidth(); Polygons raft_lines; AngleDegrees fill_angle = (num_surface_layers - raft_surface_layer) % 2 ? 45 : 135; // Alternate between -45 and +45 degrees, ending up 90 degrees rotated from the default skin angle. @@ -931,7 +931,7 @@ void FffGcodeWriter::processRaft(const SliceDataStorage& storage) pocket_size); std::vector raft_paths; // Should remain empty, since we have no walls. infill_comp.generate(raft_paths, raft_polygons, raft_lines, surface_settings, layer_nr, SectionType::ADHESION); - gcode_layer.addLinesByOptimizer(raft_lines, gcode_layer.configs_storage.raft_surface_config, SpaceFillType::Lines, false, 0, 1.0, last_planned_position); + gcode_layer.addLinesByOptimizer(raft_lines, gcode_layer.configs_storage_.raft_surface_config, SpaceFillType::Lines, false, 0, 1.0, last_planned_position); raft_polygons.clear(); raft_lines.clear(); @@ -1086,7 +1086,7 @@ FffGcodeWriter::ProcessLayerResult FffGcodeWriter::processLayer(const SliceDataS for (size_t mesh_idx : mesh_order) { const std::shared_ptr& mesh = storage.meshes[mesh_idx]; - const MeshPathConfigs& mesh_config = gcode_layer.configs_storage.mesh_configs[mesh_idx]; + const MeshPathConfigs& mesh_config = gcode_layer.configs_storage_.mesh_configs[mesh_idx]; if (mesh->settings.get("magic_mesh_surface_mode") == ESurfaceMode::SURFACE && extruder_nr == mesh->settings.get("wall_0_extruder_nr").extruder_nr_ // mesh surface mode should always only be printed with the outer wall extruder! @@ -1285,7 +1285,7 @@ void FffGcodeWriter::processSkirtBrim(const SliceDataStorage& storage, LayerPlan gcode_layer.addLinesByOptimizer( layer_nr == 0 ? all_brim_lines : inner_brim_line, - gcode_layer.configs_storage.skirt_brim_config_per_extruder[extruder_nr], + gcode_layer.configs_storage_.skirt_brim_config_per_extruder[extruder_nr], SpaceFillType::PolyLines, enable_travel_optimization, wipe_dist, @@ -1308,7 +1308,7 @@ void FffGcodeWriter::processSkirtBrim(const SliceDataStorage& storage, LayerPlan support_brim_lines.toPolylines(); gcode_layer.addLinesByOptimizer( support_brim_lines, - gcode_layer.configs_storage.skirt_brim_config_per_extruder[extruder_nr], + gcode_layer.configs_storage_.skirt_brim_config_per_extruder[extruder_nr], SpaceFillType::PolyLines, enable_travel_optimization, wipe_dist, @@ -1329,7 +1329,7 @@ void FffGcodeWriter::processOozeShield(const SliceDataStorage& storage, LayerPla } if (storage.oozeShield.size() > 0 && layer_nr < storage.oozeShield.size()) { - gcode_layer.addPolygonsByOptimizer(storage.oozeShield[layer_nr], gcode_layer.configs_storage.skirt_brim_config_per_extruder[0]); + gcode_layer.addPolygonsByOptimizer(storage.oozeShield[layer_nr], gcode_layer.configs_storage_.skirt_brim_config_per_extruder[0]); } } @@ -1362,7 +1362,7 @@ void FffGcodeWriter::processDraftShield(const SliceDataStorage& storage, LayerPl } } - gcode_layer.addPolygonsByOptimizer(storage.draft_protection_shield, gcode_layer.configs_storage.skirt_brim_config_per_extruder[0]); + gcode_layer.addPolygonsByOptimizer(storage.draft_protection_shield, gcode_layer.configs_storage_.skirt_brim_config_per_extruder[0]); } void FffGcodeWriter::calculateExtruderOrderPerLayer(const SliceDataStorage& storage) @@ -1711,7 +1711,7 @@ bool FffGcodeWriter::processMultiLayerInfill( infill_overlap, infill_multiplier, infill_angle, - gcode_layer.z, + gcode_layer.z_, infill_shift, max_resolution, max_deviation, @@ -1917,7 +1917,7 @@ bool FffGcodeWriter::processSingleLayerInfill( overlap, infill_multiplier, infill_angle, - gcode_layer.z, + gcode_layer.z_, infill_shift, max_resolution, max_deviation, @@ -1982,7 +1982,7 @@ bool FffGcodeWriter::processSingleLayerInfill( overlap, infill_multiplier, infill_angle, - gcode_layer.z, + gcode_layer.z_, infill_shift, max_resolution, max_deviation, @@ -2660,12 +2660,12 @@ bool FffGcodeWriter::processSkinPart( { bool added_something = false; - gcode_layer.mode_skip_agressive_merge = true; + gcode_layer.mode_skip_agressive_merge_ = true; processRoofing(storage, gcode_layer, mesh, extruder_nr, mesh_config, skin_part, added_something); processTopBottom(storage, gcode_layer, mesh, extruder_nr, mesh_config, skin_part, added_something); - gcode_layer.mode_skip_agressive_merge = false; + gcode_layer.mode_skip_agressive_merge_ = false; return added_something; } @@ -2942,7 +2942,7 @@ void FffGcodeWriter::processSkinPrintFeature( skin_overlap, infill_multiplier, skin_angle, - gcode_layer.z, + gcode_layer.z_, extra_infill_shift, max_resolution, max_deviation, @@ -3125,7 +3125,7 @@ bool FffGcodeWriter::addSupportToGCode(const SliceDataStorage& storage, LayerPla if (extruder_nr == support_roof_extruder_nr) { - support_added |= addSupportRoofsToGCode(storage, support_layer.support_fractional_roof, gcode_layer.configs_storage.support_fractional_roof_config, gcode_layer); + support_added |= addSupportRoofsToGCode(storage, support_layer.support_fractional_roof, gcode_layer.configs_storage_.support_fractional_roof_config, gcode_layer); } if (extruder_nr == support_infill_extruder_nr) { @@ -3136,7 +3136,7 @@ bool FffGcodeWriter::addSupportToGCode(const SliceDataStorage& storage, LayerPla support_added |= addSupportRoofsToGCode( storage, support_layer.support_roof.difference(support_layer.support_fractional_roof), - gcode_layer.configs_storage.support_roof_config, + gcode_layer.configs_storage_.support_roof_config, gcode_layer); } if (extruder_nr == support_bottom_extruder_nr) @@ -3235,7 +3235,7 @@ bool FffGcodeWriter::processSupportInfill(const SliceDataStorage& storage, Layer for (const PathOrdering& path : ranges::views::concat(island_order_optimizer_initial.paths_, island_order_optimizer.paths_)) { const SupportInfillPart& part = *path.vertices_; - const auto& configs = part.use_fractional_config_ ? gcode_layer.configs_storage.support_fractional_infill_config : gcode_layer.configs_storage.support_infill_config; + const auto& configs = part.use_fractional_config_ ? gcode_layer.configs_storage_.support_fractional_infill_config : gcode_layer.configs_storage_.support_infill_config; // always process the wall overlap if walls are generated const int current_support_infill_overlap = (part.inset_count_to_generate_ > 0) ? default_support_infill_overlap : 0; @@ -3315,7 +3315,7 @@ bool FffGcodeWriter::processSupportInfill(const SliceDataStorage& storage, Layer current_support_infill_overlap - (density_idx == max_density_idx ? 0 : wall_line_count * support_line_width), infill_multiplier, support_infill_angle, - gcode_layer.z + configs[combine_idx].z_offset, + gcode_layer.z_ + configs[combine_idx].z_offset, support_shift, max_resolution, max_deviation, @@ -3521,7 +3521,7 @@ bool FffGcodeWriter::addSupportRoofsToGCode( support_roof_overlap, infill_multiplier, fill_angle, - gcode_layer.z + current_roof_config.z_offset, + gcode_layer.z_ + current_roof_config.z_offset, extra_infill_shift, max_resolution, max_deviation, @@ -3631,12 +3631,12 @@ bool FffGcodeWriter::addSupportBottomsToGCode(const SliceDataStorage& storage, L zig_zaggify_infill, connect_polygons, support_layer.support_bottom, - gcode_layer.configs_storage.support_bottom_config.getLineWidth(), + gcode_layer.configs_storage_.support_bottom_config.getLineWidth(), support_bottom_line_distance, support_bottom_overlap, infill_multiplier, fill_angle, - gcode_layer.z, + gcode_layer.z_, extra_infill_shift, max_resolution, max_deviation, @@ -3663,11 +3663,11 @@ bool FffGcodeWriter::addSupportBottomsToGCode(const SliceDataStorage& storage, L { constexpr bool force_comb_retract = false; gcode_layer.addTravel(bottom_polygons[0][0], force_comb_retract); - gcode_layer.addPolygonsByOptimizer(bottom_polygons, gcode_layer.configs_storage.support_bottom_config); + gcode_layer.addPolygonsByOptimizer(bottom_polygons, gcode_layer.configs_storage_.support_bottom_config); } if (! bottom_paths.empty()) { - const GCodePathConfig& config = gcode_layer.configs_storage.support_bottom_config; + const GCodePathConfig& config = gcode_layer.configs_storage_.support_bottom_config; constexpr bool retract_before_outer_wall = false; constexpr coord_t wipe_dist = 0; const ZSeamConfig z_seam_config(EZSeamType::SHORTEST, gcode_layer.getLastPlannedPositionOrStartingPosition(), EZSeamCornerPrefType::Z_SEAM_CORNER_PREF_NONE, false); @@ -3693,7 +3693,7 @@ bool FffGcodeWriter::addSupportBottomsToGCode(const SliceDataStorage& storage, L } gcode_layer.addLinesByOptimizer( bottom_lines, - gcode_layer.configs_storage.support_bottom_config, + gcode_layer.configs_storage_.support_bottom_config, (pattern == EFillMethod::ZIG_ZAG) ? SpaceFillType::PolyLines : SpaceFillType::Lines); return true; } diff --git a/src/LayerPlan.cpp b/src/LayerPlan.cpp index 6641a321b5..5e8b6a1b2d 100644 --- a/src/LayerPlan.cpp +++ b/src/LayerPlan.cpp @@ -45,16 +45,16 @@ GCodePath* LayerPlan::getLatestPathWithConfig( const bool spiralize, const Ratio speed_factor) { - std::vector& paths = extruder_plans.back().paths_; + std::vector& paths = extruder_plans_.back().paths_; if (paths.size() > 0 && paths.back().config == config && ! paths.back().done && paths.back().flow == flow && paths.back().width_factor == width_factor && paths.back().speed_factor == speed_factor && paths.back().z_offset == z_offset - && paths.back().mesh == current_mesh) // spiralize can only change when a travel path is in between + && paths.back().mesh == current_mesh_) // spiralize can only change when a travel path is in between { return &paths.back(); } paths.emplace_back(GCodePath{ .z_offset = z_offset, .config = config, - .mesh = current_mesh, + .mesh = current_mesh_, .space_fill_type = space_fill_type, .flow = flow, .width_factor = width_factor, @@ -62,18 +62,18 @@ GCodePath* LayerPlan::getLatestPathWithConfig( .speed_factor = speed_factor }); GCodePath* ret = &paths.back(); - ret->skip_agressive_merge_hint = mode_skip_agressive_merge; + ret->skip_agressive_merge_hint = mode_skip_agressive_merge_; return ret; } const Polygons* LayerPlan::getCombBoundaryInside() const { - return &comb_boundary_preferred; + return &comb_boundary_preferred_; } void LayerPlan::forceNewPathStart() { - std::vector& paths = extruder_plans.back().paths_; + std::vector& paths = extruder_plans_.back().paths_; if (paths.size() > 0) paths[paths.size() - 1].done = true; } @@ -88,84 +88,84 @@ LayerPlan::LayerPlan( coord_t comb_boundary_offset, coord_t comb_move_inside_distance, coord_t travel_avoid_distance) - : configs_storage(storage, layer_nr, layer_thickness) - , z(z) - , final_travel_z(z) - , mode_skip_agressive_merge(false) - , storage(storage) - , layer_nr(layer_nr) - , is_initial_layer(layer_nr == 0 - static_cast(Raft::getTotalExtraLayers())) - , is_raft_layer(layer_nr < 0 - static_cast(Raft::getFillerLayerCount())) - , layer_thickness(layer_thickness) - , has_prime_tower_planned_per_extruder(Application::getInstance().current_slice_->scene.extruders.size(), false) - , current_mesh(nullptr) - , last_extruder_previous_layer(start_extruder) - , last_planned_extruder(&Application::getInstance().current_slice_->scene.extruders[start_extruder]) - , first_travel_destination_is_inside(false) + : configs_storage_(storage, layer_nr, layer_thickness) + , z_(z) + , final_travel_z_(z) + , mode_skip_agressive_merge_(false) + , storage_(storage) + , layer_nr_(layer_nr) + , is_initial_layer_(layer_nr == 0 - static_cast(Raft::getTotalExtraLayers())) + , is_raft_layer_(layer_nr < 0 - static_cast(Raft::getFillerLayerCount())) + , layer_thickness_(layer_thickness) + , has_prime_tower_planned_per_extruder_(Application::getInstance().current_slice_->scene.extruders.size(), false) + , current_mesh_(nullptr) + , last_extruder_previous_layer_(start_extruder) + , last_planned_extruder_(&Application::getInstance().current_slice_->scene.extruders[start_extruder]) + , first_travel_destination_is_inside_(false) , // set properly when addTravel is called for the first time (otherwise not set properly) - comb_boundary_minimum(computeCombBoundary(CombBoundary::MINIMUM)) - , comb_boundary_preferred(computeCombBoundary(CombBoundary::PREFERRED)) - , comb_move_inside_distance(comb_move_inside_distance) - , fan_speed_layer_time_settings_per_extruder(fan_speed_layer_time_settings_per_extruder) + comb_boundary_minimum_(computeCombBoundary(CombBoundary::MINIMUM)) + , comb_boundary_preferred_(computeCombBoundary(CombBoundary::PREFERRED)) + , comb_move_inside_distance_(comb_move_inside_distance) + , fan_speed_layer_time_settings_per_extruder_(fan_speed_layer_time_settings_per_extruder) { size_t current_extruder = start_extruder; - was_inside = true; // not used, because the first travel move is bogus - is_inside = false; // assumes the next move will not be to inside a layer part (overwritten just before going into a layer part) + was_inside_ = true; // not used, because the first travel move is bogus + is_inside_ = false; // assumes the next move will not be to inside a layer part (overwritten just before going into a layer part) if (Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("retraction_combing") != CombingMode::OFF) { - comb = new Comb(storage, layer_nr, comb_boundary_minimum, comb_boundary_preferred, comb_boundary_offset, travel_avoid_distance, comb_move_inside_distance); + comb_ = new Comb(storage, layer_nr, comb_boundary_minimum_, comb_boundary_preferred_, comb_boundary_offset, travel_avoid_distance, comb_move_inside_distance); } else { - comb = nullptr; + comb_ = nullptr; } for (const ExtruderTrain& extruder : Application::getInstance().current_slice_->scene.extruders) { - layer_start_pos_per_extruder.emplace_back(extruder.settings_.get("layer_start_x"), extruder.settings_.get("layer_start_y")); + layer_start_pos_per_extruder_.emplace_back(extruder.settings_.get("layer_start_x"), extruder.settings_.get("layer_start_y")); } - extruder_plans.reserve(Application::getInstance().current_slice_->scene.extruders.size()); - extruder_plans.emplace_back( + extruder_plans_.reserve(Application::getInstance().current_slice_->scene.extruders.size()); + extruder_plans_.emplace_back( current_extruder, layer_nr, - is_initial_layer, - is_raft_layer, + is_initial_layer_, + is_raft_layer_, layer_thickness, fan_speed_layer_time_settings_per_extruder[current_extruder], storage.retraction_wipe_config_per_extruder[current_extruder].retraction_config); for (size_t extruder_nr = 0; extruder_nr < Application::getInstance().current_slice_->scene.extruders.size(); extruder_nr++) { // Skirt and brim. - skirt_brim_is_processed[extruder_nr] = false; + skirt_brim_is_processed_[extruder_nr] = false; } } LayerPlan::~LayerPlan() { - if (comb) - delete comb; + if (comb_) + delete comb_; } ExtruderTrain* LayerPlan::getLastPlannedExtruderTrain() { - return last_planned_extruder; + return last_planned_extruder_; } Polygons LayerPlan::computeCombBoundary(const CombBoundary boundary_type) { Polygons comb_boundary; const CombingMode mesh_combing_mode = Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("retraction_combing"); - if (mesh_combing_mode != CombingMode::OFF && (layer_nr >= 0 || mesh_combing_mode != CombingMode::NO_SKIN)) + if (mesh_combing_mode != CombingMode::OFF && (layer_nr_ >= 0 || mesh_combing_mode != CombingMode::NO_SKIN)) { - if (layer_nr < 0) + if (layer_nr_ < 0) { - comb_boundary = storage.raftOutline.offset(MM2INT(0.1)); + comb_boundary = storage_.raftOutline.offset(MM2INT(0.1)); } else { - for (const std::shared_ptr& mesh_ptr : storage.meshes) + for (const std::shared_ptr& mesh_ptr : storage_.meshes) { const auto& mesh = *mesh_ptr; - const SliceLayer& layer = mesh.layers[static_cast(layer_nr)]; + const SliceLayer& layer = mesh.layers[static_cast(layer_nr_)]; // don't process infill_mesh or anti_overhang_mesh if (mesh.settings.get("infill_mesh") || mesh.settings.get("anti_overhang_mesh")) { @@ -200,9 +200,9 @@ Polygons LayerPlan::computeCombBoundary(const CombBoundary boundary_type) else if (combing_mode == CombingMode::NO_OUTER_SURFACES) { Polygons top_and_bottom_most_fill; - for (const SliceLayerPart& part : layer.parts) + for (const SliceLayerPart& outer_surface_part : layer.parts) { - for (const SkinPart& skin_part : part.skin_parts) + for (const SkinPart& skin_part : outer_surface_part.skin_parts) { top_and_bottom_most_fill.add(skin_part.top_most_surface_fill); top_and_bottom_most_fill.add(skin_part.bottom_most_surface_fill); @@ -223,7 +223,7 @@ Polygons LayerPlan::computeCombBoundary(const CombBoundary boundary_type) void LayerPlan::setIsInside(bool _is_inside) { - is_inside = _is_inside; + is_inside_ = _is_inside; } bool LayerPlan::setExtruder(const size_t extruder_nr) @@ -246,25 +246,25 @@ bool LayerPlan::setExtruder(const size_t extruder_nr) const Point extruder_offset(extruder->settings_.get("machine_nozzle_offset_x"), extruder->settings_.get("machine_nozzle_offset_y")); end_pos += extruder_offset; // absolute end pos is given as a head position } - if (end_pos_absolute || last_planned_position) + if (end_pos_absolute || last_planned_position_) { addTravel(end_pos); // + extruder_offset cause it } } - if (extruder_plans.back().paths_.empty() && extruder_plans.back().inserts_.empty()) + if (extruder_plans_.back().paths_.empty() && extruder_plans_.back().inserts_.empty()) { // first extruder plan in a layer might be empty, cause it is made with the last extruder planned in the previous layer - extruder_plans.back().extruder_nr_ = extruder_nr; + extruder_plans_.back().extruder_nr_ = extruder_nr; } - extruder_plans.emplace_back( + extruder_plans_.emplace_back( extruder_nr, - layer_nr, - is_initial_layer, - is_raft_layer, - layer_thickness, - fan_speed_layer_time_settings_per_extruder[extruder_nr], - storage.retraction_wipe_config_per_extruder[extruder_nr].retraction_config); - assert(extruder_plans.size() <= Application::getInstance().current_slice_->scene.extruders.size() && "Never use the same extruder twice on one layer!"); - last_planned_extruder = &Application::getInstance().current_slice_->scene.extruders[extruder_nr]; + layer_nr_, + is_initial_layer_, + is_raft_layer_, + layer_thickness_, + fan_speed_layer_time_settings_per_extruder_[extruder_nr], + storage_.retraction_wipe_config_per_extruder[extruder_nr].retraction_config); + assert(extruder_plans_.size() <= Application::getInstance().current_slice_->scene.extruders.size() && "Never use the same extruder twice on one layer!"); + last_planned_extruder_ = &Application::getInstance().current_slice_->scene.extruders[extruder_nr]; { // handle starting pos of the new extruder ExtruderTrain* extruder = getLastPlannedExtruderTrain(); @@ -279,16 +279,16 @@ bool LayerPlan::setExtruder(const size_t extruder_nr) Point extruder_offset(extruder->settings_.get("machine_nozzle_offset_x"), extruder->settings_.get("machine_nozzle_offset_y")); start_pos += extruder_offset; // absolute start pos is given as a head position } - if (start_pos_absolute || last_planned_position) + if (start_pos_absolute || last_planned_position_) { - last_planned_position = start_pos; + last_planned_position_ = start_pos; } } return true; } void LayerPlan::setMesh(const std::shared_ptr& mesh) { - current_mesh = mesh; + current_mesh_ = mesh; } void LayerPlan::moveInsideCombBoundary(const coord_t distance, const std::optional& part) @@ -296,11 +296,11 @@ void LayerPlan::moveInsideCombBoundary(const coord_t distance, const std::option constexpr coord_t max_dist2 = MM2INT(2.0) * MM2INT(2.0); // if we are further than this distance, we conclude we are not inside even though we thought we were. // this function is to be used to move from the boundary of a part to inside the part Point p = getLastPlannedPositionOrStartingPosition(); // copy, since we are going to move p - if (PolygonUtils::moveInside(comb_boundary_preferred, p, distance, max_dist2) != NO_INDEX) + if (PolygonUtils::moveInside(comb_boundary_preferred_, p, distance, max_dist2) != NO_INDEX) { // Move inside again, so we move out of tight 90deg corners - PolygonUtils::moveInside(comb_boundary_preferred, p, distance, max_dist2); - if (comb_boundary_preferred.inside(p) && (part == std::nullopt || part->outline.inside(p))) + PolygonUtils::moveInside(comb_boundary_preferred_, p, distance, max_dist2); + if (comb_boundary_preferred_.inside(p) && (part == std::nullopt || part->outline.inside(p))) { addTravel_simple(p); // Make sure the that any retraction happens after this move, not before it by starting a new move path. @@ -311,67 +311,68 @@ void LayerPlan::moveInsideCombBoundary(const coord_t distance, const std::option bool LayerPlan::getPrimeTowerIsPlanned(unsigned int extruder_nr) const { - return has_prime_tower_planned_per_extruder[extruder_nr]; + return has_prime_tower_planned_per_extruder_[extruder_nr]; } void LayerPlan::setPrimeTowerIsPlanned(unsigned int extruder_nr) { - has_prime_tower_planned_per_extruder[extruder_nr] = true; + has_prime_tower_planned_per_extruder_[extruder_nr] = true; } std::optional> LayerPlan::getFirstTravelDestinationState() const { std::optional> ret; - if (first_travel_destination) + if (first_travel_destination_) { - ret = std::make_pair(*first_travel_destination, first_travel_destination_is_inside); + ret = std::make_pair(*first_travel_destination_, first_travel_destination_is_inside_); } return ret; } GCodePath& LayerPlan::addTravel(const Point& p, const bool force_retract, const coord_t z_offset) { - const GCodePathConfig& travel_config = configs_storage.travel_config_per_extruder[getExtruder()]; + const GCodePathConfig& travel_config = configs_storage_.travel_config_per_extruder[getExtruder()]; const RetractionConfig& retraction_config - = current_mesh ? current_mesh->retraction_wipe_config.retraction_config : storage.retraction_wipe_config_per_extruder[getExtruder()].retraction_config; + = current_mesh_ ? current_mesh_->retraction_wipe_config.retraction_config : storage_.retraction_wipe_config_per_extruder[getExtruder()].retraction_config; GCodePath* path = getLatestPathWithConfig(travel_config, SpaceFillType::None, z_offset); bool combed = false; const ExtruderTrain* extruder = getLastPlannedExtruderTrain(); - const Settings& mesh_or_extruder_settings = current_mesh ? current_mesh->settings : extruder->settings_; + const Settings& mesh_or_extruder_settings = current_mesh_ ? current_mesh_->settings : extruder->settings_; - const bool is_first_travel_of_extruder_after_switch = extruder_plans.back().paths_.size() == 1 && (extruder_plans.size() > 1 || last_extruder_previous_layer != getExtruder()); + const bool is_first_travel_of_extruder_after_switch + = extruder_plans_.back().paths_.size() == 1 && (extruder_plans_.size() > 1 || last_extruder_previous_layer_ != getExtruder()); bool bypass_combing = is_first_travel_of_extruder_after_switch && mesh_or_extruder_settings.get("retraction_hop_after_extruder_switch"); - const bool is_first_travel_of_layer = ! static_cast(last_planned_position); + const bool is_first_travel_of_layer = ! static_cast(last_planned_position_); const bool retraction_enable = mesh_or_extruder_settings.get("retraction_enable"); if (is_first_travel_of_layer) { bypass_combing = true; // first travel move is bogus; it is added after this and the previous layer have been planned in LayerPlanBuffer::addConnectingTravelMove - first_travel_destination = p; - first_travel_destination_is_inside = is_inside; - if (layer_nr == 0 && retraction_enable && mesh_or_extruder_settings.get("retraction_hop_enabled")) + first_travel_destination_ = p; + first_travel_destination_is_inside_ = is_inside_; + if (layer_nr_ == 0 && retraction_enable && mesh_or_extruder_settings.get("retraction_hop_enabled")) { path->retract = true; path->perform_z_hop = true; } forceNewPathStart(); // force a new travel path after this first bogus move } - else if (force_retract && last_planned_position && ! shorterThen(*last_planned_position - p, retraction_config.retraction_min_travel_distance)) + else if (force_retract && last_planned_position_ && ! shorterThen(*last_planned_position_ - p, retraction_config.retraction_min_travel_distance)) { // path is not shorter than min travel distance, force a retraction path->retract = true; - if (comb == nullptr) + if (comb_ == nullptr) { path->perform_z_hop = mesh_or_extruder_settings.get("retraction_hop_enabled"); } } - if (comb != nullptr && ! bypass_combing) + if (comb_ != nullptr && ! bypass_combing) { CombPaths combPaths; @@ -382,15 +383,15 @@ GCodePath& LayerPlan::addTravel(const Point& p, const bool force_retract, const bool unretract_before_last_travel_move = false; // Decided when calculating the combing const bool perform_z_hops = mesh_or_extruder_settings.get("retraction_hop_enabled"); const bool perform_z_hops_only_when_collides = mesh_or_extruder_settings.get("retraction_hop_only_when_collides"); - combed = comb->calc( + combed = comb_->calc( perform_z_hops, perform_z_hops_only_when_collides, *extruder, - *last_planned_position, + *last_planned_position_, p, combPaths, - was_inside, - is_inside, + was_inside_, + is_inside_, max_distance_ignored, unretract_before_last_travel_move); if (combed) @@ -417,7 +418,7 @@ GCodePath& LayerPlan::addTravel(const Point& p, const bool force_retract, const const coord_t maximum_travel_resolution = mesh_or_extruder_settings.get("meshfix_maximum_travel_resolution"); coord_t distance = 0; - Point last_point((last_planned_position) ? *last_planned_position : Point(0, 0)); + Point last_point((last_planned_position_) ? *last_planned_position_ : Point(0, 0)); for (CombPath& combPath : combPaths) { // add all comb paths (don't do anything special for paths which are moving through air) if (combPath.empty()) @@ -449,21 +450,21 @@ GCodePath& LayerPlan::addTravel(const Point& p, const bool force_retract, const // CURA-6675: // Retraction Minimal Travel Distance should work for all travel moves. If the travel move is shorter than the // Retraction Minimal Travel Distance, retraction should be disabled. - if (! is_first_travel_of_layer && last_planned_position && shorterThen(*last_planned_position - p, retraction_config.retraction_min_travel_distance)) + if (! is_first_travel_of_layer && last_planned_position_ && shorterThen(*last_planned_position_ - p, retraction_config.retraction_min_travel_distance)) { path->retract = false; path->perform_z_hop = false; } // no combing? retract only when path is not shorter than minimum travel distance - if (! combed && ! is_first_travel_of_layer && last_planned_position && ! shorterThen(*last_planned_position - p, retraction_config.retraction_min_travel_distance)) + if (! combed && ! is_first_travel_of_layer && last_planned_position_ && ! shorterThen(*last_planned_position_ - p, retraction_config.retraction_min_travel_distance)) { - if (was_inside) // when the previous location was from printing something which is considered inside (not support or prime tower etc) + if (was_inside_) // when the previous location was from printing something which is considered inside (not support or prime tower etc) { // then move inside the printed part, so that we don't ooze on the outer wall while retraction, but on the inside of the print. assert(extruder != nullptr); coord_t innermost_wall_line_width = mesh_or_extruder_settings.get((mesh_or_extruder_settings.get("wall_line_count") > 1) ? "wall_line_width_x" : "wall_line_width_0"); - if (layer_nr == 0) + if (layer_nr_ == 0) { innermost_wall_line_width *= mesh_or_extruder_settings.get("initial_layer_line_width_factor"); } @@ -477,24 +478,24 @@ GCodePath& LayerPlan::addTravel(const Point& p, const bool force_retract, const forceNewPathStart(); GCodePath& ret = addTravel_simple(p, path); - was_inside = is_inside; + was_inside_ = is_inside_; return ret; } GCodePath& LayerPlan::addTravel_simple(const Point& p, GCodePath* path) { - bool is_first_travel_of_layer = ! static_cast(last_planned_position); + bool is_first_travel_of_layer = ! static_cast(last_planned_position_); if (is_first_travel_of_layer) { // spiralize calls addTravel_simple directly as the first travel move in a layer - first_travel_destination = p; - first_travel_destination_is_inside = is_inside; + first_travel_destination_ = p; + first_travel_destination_is_inside_ = is_inside_; } if (path == nullptr) { - path = getLatestPathWithConfig(configs_storage.travel_config_per_extruder[getExtruder()], SpaceFillType::None); + path = getLatestPathWithConfig(configs_storage_.travel_config_per_extruder[getExtruder()], SpaceFillType::None); } path->points.push_back(p); - last_planned_position = p; + last_planned_position_ = p; return *path; } @@ -521,11 +522,11 @@ void LayerPlan::addExtrusionMove( GCodePath* path = getLatestPathWithConfig(config, space_fill_type, config.z_offset, flow, width_factor, spiralize, speed_factor); path->points.push_back(p); path->setFanSpeed(fan_speed); - if (! static_cast(first_extrusion_acc_jerk)) + if (! static_cast(first_extrusion_acc_jerk_)) { - first_extrusion_acc_jerk = std::make_pair(path->config.getAcceleration(), path->config.getJerk()); + first_extrusion_acc_jerk_ = std::make_pair(path->config.getAcceleration(), path->config.getJerk()); } - last_planned_position = p; + last_planned_position_ = p; } void LayerPlan::addPolygon( @@ -550,8 +551,7 @@ void LayerPlan::addPolygon( } if (polygon.size() > 2) { - const Point& p1 = polygon[start_idx]; - addExtrusionMove(p1, config, SpaceFillType::Polygons, flow_ratio, width_ratio, spiralize); + addExtrusionMove(polygon[start_idx], config, SpaceFillType::Polygons, flow_ratio, width_ratio, spiralize); if (wall_0_wipe_dist > 0) { // apply outer wall wipe @@ -702,8 +702,8 @@ void LayerPlan::addWallLine( speed_factor); } // then coast to start of bridge segment - constexpr Ratio flow = 0.0_r; // Coasting has no flow rate. - addExtrusionMove(segment_end, non_bridge_config, SpaceFillType::Polygons, flow, width_factor, spiralize, speed_factor); + constexpr Ratio no_flow = 0.0_r; // Coasting has no flow rate. + addExtrusionMove(segment_end, non_bridge_config, SpaceFillType::Polygons, no_flow, width_factor, spiralize, speed_factor); } else { @@ -715,7 +715,7 @@ void LayerPlan::addWallLine( segment_flow, width_factor, spiralize, - (overhang_mask.empty() || (! overhang_mask.inside(p0, true) && ! overhang_mask.inside(p1, true))) ? speed_factor : overhang_speed_factor); + (overhang_mask_.empty() || (! overhang_mask_.inside(p0, true) && ! overhang_mask_.inside(p1, true))) ? speed_factor : overhang_speed_factor); } distance_to_bridge_start -= len; @@ -730,7 +730,7 @@ void LayerPlan::addWallLine( segment_flow, width_factor, spiralize, - (overhang_mask.empty() || (! overhang_mask.inside(p0, true) && ! overhang_mask.inside(p1, true))) ? speed_factor : overhang_speed_factor); + (overhang_mask_.empty() || (! overhang_mask_.inside(p0, true) && ! overhang_mask_.inside(p1, true))) ? speed_factor : overhang_speed_factor); } non_bridge_line_volume += vSize(cur_point - segment_end) * segment_flow * width_factor * speed_factor * non_bridge_config.getSpeed(); cur_point = segment_end; @@ -743,7 +743,7 @@ void LayerPlan::addWallLine( } }; - if (bridge_wall_mask.empty()) + if (bridge_wall_mask_.empty()) { // no bridges required addExtrusionMove( @@ -753,12 +753,12 @@ void LayerPlan::addWallLine( flow, width_factor, spiralize, - (overhang_mask.empty() || (! overhang_mask.inside(p0, true) && ! overhang_mask.inside(p1, true))) ? 1.0_r : overhang_speed_factor); + (overhang_mask_.empty() || (! overhang_mask_.inside(p0, true) && ! overhang_mask_.inside(p1, true))) ? 1.0_r : overhang_speed_factor); } else { // bridges may be required - if (PolygonUtils::polygonCollidesWithLineSegment(bridge_wall_mask, p0, p1)) + if (PolygonUtils::polygonCollidesWithLineSegment(bridge_wall_mask_, p0, p1)) { // the line crosses the boundary between supported and non-supported regions so one or more bridges are required @@ -767,7 +767,7 @@ void LayerPlan::addWallLine( Polygons line_polys; line_polys.addLine(p0, p1); constexpr bool restitch = false; // only a single line doesn't need stitching - line_polys = bridge_wall_mask.intersectionPolyLines(line_polys, restitch); + line_polys = bridge_wall_mask_.intersectionPolyLines(line_polys, restitch); // line_polys now contains the wall lines that need to be printed using bridge_config @@ -831,7 +831,7 @@ void LayerPlan::addWallLine( // if we haven't yet reached p1, fill the gap with non_bridge_config line addNonBridgeLine(p1); } - else if (bridge_wall_mask.inside(p0, true) && vSize(p0 - p1) >= min_bridge_line_len) + else if (bridge_wall_mask_.inside(p0, true) && vSize(p0 - p1) >= min_bridge_line_len) { // both p0 and p1 must be above air (the result will be ugly!) addExtrusionMove(p1, bridge_config, SpaceFillType::Polygons, flow, width_factor); @@ -920,7 +920,7 @@ void LayerPlan::addWall( { distance_to_bridge_start = 0; - if (! bridge_wall_mask.empty()) + if (! bridge_wall_mask_.empty()) { // there is air below the part so iterate through the lines that have not yet been output accumulating the total distance to the first bridge segment for (unsigned point_idx = current_index; point_idx < wall.size(); ++point_idx) @@ -928,7 +928,7 @@ void LayerPlan::addWall( const ExtrusionJunction& p0 = wall[point_idx]; const ExtrusionJunction& p1 = wall[(point_idx + 1) % wall.size()]; - if (PolygonUtils::polygonCollidesWithLineSegment(bridge_wall_mask, p0.p, p1.p)) + if (PolygonUtils::polygonCollidesWithLineSegment(bridge_wall_mask_, p0.p, p1.p)) { // the line crosses the boundary between supported and non-supported regions so it will contain one or more bridge segments @@ -937,7 +937,7 @@ void LayerPlan::addWall( Polygons line_polys; line_polys.addLine(p0.p, p1.p); constexpr bool restitch = false; // only a single line doesn't need stitching - line_polys = bridge_wall_mask.intersectionPolyLines(line_polys, restitch); + line_polys = bridge_wall_mask_.intersectionPolyLines(line_polys, restitch); while (line_polys.size() > 0) { @@ -982,7 +982,7 @@ void LayerPlan::addWall( line_polys.remove(nearest); } } - else if (! bridge_wall_mask.inside(p0.p, true)) + else if (! bridge_wall_mask_.inside(p0.p, true)) { // none of the line is over air distance_to_bridge_start += vSize(p1.p - p0.p); @@ -997,9 +997,9 @@ void LayerPlan::addWall( bool first_line = true; const coord_t small_feature_max_length = settings.get("small_feature_max_length"); - const bool is_small_feature = (small_feature_max_length > 0) && (layer_nr == 0 || wall.inset_idx == 0) && cura::shorterThan(wall, small_feature_max_length); - Ratio small_feature_speed_factor = settings.get((layer_nr == 0) ? "small_feature_speed_factor_0" : "small_feature_speed_factor"); - const Velocity min_speed = fan_speed_layer_time_settings_per_extruder[getLastPlannedExtruderTrain()->extruder_nr_].cool_min_speed; + const bool is_small_feature = (small_feature_max_length > 0) && (layer_nr_ == 0 || wall.inset_idx == 0) && cura::shorterThan(wall, small_feature_max_length); + Ratio small_feature_speed_factor = settings.get((layer_nr_ == 0) ? "small_feature_speed_factor_0" : "small_feature_speed_factor"); + const Velocity min_speed = fan_speed_layer_time_settings_per_extruder_[getLastPlannedExtruderTrain()->extruder_nr_].cool_min_speed; small_feature_speed_factor = std::max((double)small_feature_speed_factor, (double)(min_speed / non_bridge_config.getSpeed())); const coord_t max_area_deviation = std::max(settings.get("meshfix_maximum_extrusion_area_deviation"), 1); // Square micrometres! const coord_t max_resolution = std::max(settings.get("meshfix_maximum_resolution"), coord_t(1)); @@ -1012,7 +1012,7 @@ void LayerPlan::addWall( { const ExtrusionJunction& p1 = wall[(wall.size() + start_idx + point_idx * direction) % wall.size()]; - if (! bridge_wall_mask.empty()) + if (! bridge_wall_mask_.empty()) { computeDistanceToBridgeStart((wall.size() + start_idx + point_idx * direction - 1) % wall.size()); } @@ -1091,7 +1091,7 @@ void LayerPlan::addWall( if (wall.size() >= 2) { - if (! bridge_wall_mask.empty()) + if (! bridge_wall_mask_.empty()) { computeDistanceToBridgeStart((start_idx + wall.size() - 1) % wall.size()); } @@ -1184,14 +1184,14 @@ void LayerPlan::addLinesByOptimizer( const std::unordered_multimap& order_requirements) { Polygons boundary; - if (enable_travel_optimization && ! comb_boundary_minimum.empty()) + if (enable_travel_optimization && ! comb_boundary_minimum_.empty()) { // use the combing boundary inflated so that all infill lines are inside the boundary int dist = 0; - if (layer_nr >= 0) + if (layer_nr_ >= 0) { // determine how much the skin/infill lines overlap the combing boundary - for (const std::shared_ptr& mesh : storage.meshes) + for (const std::shared_ptr& mesh : storage_.meshes) { const coord_t overlap = std::max(mesh->settings.get("skin_overlap_mm"), mesh->settings.get("infill_overlap_mm")); if (overlap > dist) @@ -1201,7 +1201,7 @@ void LayerPlan::addLinesByOptimizer( } dist += 100; // ensure boundary is slightly outside all skin/infill lines } - boundary.add(comb_boundary_minimum.offset(dist)); + boundary.add(comb_boundary_minimum_.offset(dist)); // simplify boundary to cut down processing time boundary = Simplify(MM2INT(0.1), MM2INT(0.1), 0).polygon(boundary); } @@ -1377,7 +1377,7 @@ void LayerPlan::addLinesMonotonic( order.optimize(); // Read out and process the monotonically ordered lines. - addLinesInGivenOrder(order.paths, config, space_fill_type, wipe_dist, flow_ratio, fan_speed); + addLinesInGivenOrder(order.paths_, config, space_fill_type, wipe_dist, flow_ratio, fan_speed); // Add all lines in the excluded areas the 'normal' way. addLinesByOptimizer(left_over, config, space_fill_type, true, wipe_dist, flow_ratio, getLastPlannedPositionOrStartingPosition(), fan_speed); @@ -1454,7 +1454,7 @@ void LayerPlan::spiralizeWallSlice( // normal slow down for quick layers mechanism can kick in and speed this layer up (because it is longer) but we prefer // the layer to be printed at a similar speed to the previous layer to avoid abrupt changes in extrusion rate so we slow it down - const FanSpeedLayerTimeSettings& layer_time_settings = extruder_plans.back().fan_speed_layer_time_settings_; + const FanSpeedLayerTimeSettings& layer_time_settings = extruder_plans_.back().fan_speed_layer_time_settings_; const double min_time = layer_time_settings.cool_min_layer_time; const double normal_layer_time = total_length / config.getSpeed(); @@ -1556,7 +1556,6 @@ void ExtruderPlan::forceMinimalLayerTime(double minTime, double time_other_extr_ { const double minExtrudeTime = minTime - (totalTime - extrudeTime); - double factor = 0.0; double target_speed = 0.0; std::function slow_down_func{ [&target_speed](const GCodePath& path) { @@ -1592,11 +1591,11 @@ void ExtruderPlan::forceMinimalLayerTime(double minTime, double time_other_extr_ { // Slowing down to the slowest_speed is sufficient to respect the minimum layer time. // Linear interpolate between extrudeTime and total_extrude_time_at_slowest_speed - factor = (1 / total_extrude_time_at_slowest_speed - 1 / minExtrudeTime) / (1 / total_extrude_time_at_slowest_speed - 1 / extrudeTime); + const double factor = (1 / total_extrude_time_at_slowest_speed - 1 / minExtrudeTime) / (1 / total_extrude_time_at_slowest_speed - 1 / extrudeTime); slow_down_func = [&slowest_path_speed = slowest_path_speed_, &factor](const GCodePath& path) { - const double target_speed = slowest_path_speed * (1.0 - factor) + (path.config.getSpeed() * path.speed_factor) * factor; - return std::min(target_speed / (path.config.getSpeed() * path.speed_factor), 1.0); + const double actual_target_speed = slowest_path_speed * (1.0 - factor) + (path.config.getSpeed() * path.speed_factor) * factor; + return std::min(actual_target_speed / (path.config.getSpeed() * path.speed_factor), 1.0); }; // Update stored naive time estimates @@ -1773,7 +1772,7 @@ void LayerPlan::processFanSpeedAndMinimalLayerTime(Point starting_position) { // the minimum layer time behaviour is only applied to the last extruder. const size_t last_extruder_nr = ranges::max_element( - extruder_plans, + extruder_plans_, [](const ExtruderPlan& a, const ExtruderPlan& b) { return a.extruder_nr_ < b.extruder_nr_; @@ -1784,10 +1783,10 @@ void LayerPlan::processFanSpeedAndMinimalLayerTime(Point starting_position) double other_extr_plan_time = 0.0; Duration maximum_cool_min_layer_time; - for (unsigned int extr_plan_idx = 0; extr_plan_idx < extruder_plans.size(); extr_plan_idx++) + for (unsigned int extr_plan_idx = 0; extr_plan_idx < extruder_plans_.size(); extr_plan_idx++) { { - ExtruderPlan& extruder_plan = extruder_plans[extr_plan_idx]; + ExtruderPlan& extruder_plan = extruder_plans_[extr_plan_idx]; // Precalculate the time estimates. Don't call this function twice, since it is works cumulative. extruder_plan.computeNaiveTimeEstimates(starting_position); @@ -1813,7 +1812,7 @@ void LayerPlan::processFanSpeedAndMinimalLayerTime(Point starting_position) } // apply minimum layer time behaviour - ExtruderPlan& last_extruder_plan = extruder_plans[last_extruder_idx]; + ExtruderPlan& last_extruder_plan = extruder_plans_[last_extruder_idx]; last_extruder_plan.forceMinimalLayerTime(maximum_cool_min_layer_time, other_extr_plan_time); last_extruder_plan.processFanSpeedForMinimalLayerTime(starting_position_last_extruder, maximum_cool_min_layer_time, other_extr_plan_time); } @@ -1822,11 +1821,11 @@ void LayerPlan::processFanSpeedAndMinimalLayerTime(Point starting_position) void LayerPlan::writeGCode(GCodeExport& gcode) { Communication* communication = Application::getInstance().communication_; - communication->setLayerForSend(layer_nr); + communication->setLayerForSend(layer_nr_); communication->sendCurrentPosition(gcode.getPositionXY()); - gcode.setLayerNr(layer_nr); + gcode.setLayerNr(layer_nr_); - gcode.writeLayerComment(layer_nr); + gcode.writeLayerComment(layer_nr_); // flow-rate compensation const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; @@ -1835,13 +1834,13 @@ void LayerPlan::writeGCode(GCodeExport& gcode) mesh_group_settings.get("flow_rate_extrusion_offset_factor")); // Offset is in mm. static LayerIndex layer_1{ 1 - static_cast(Raft::getTotalExtraLayers()) }; - if (layer_nr == layer_1 && mesh_group_settings.get("machine_heated_bed")) + if (layer_nr_ == layer_1 && mesh_group_settings.get("machine_heated_bed")) { constexpr bool wait = false; gcode.writeBedTemperatureCommand(mesh_group_settings.get("material_bed_temperature"), wait); } - gcode.setZ(z); + gcode.setZ(z_); std::optional last_extrusion_config = std::nullopt; // used to check whether we need to insert a TYPE comment in the gcode. @@ -1852,12 +1851,12 @@ void LayerPlan::writeGCode(GCodeExport& gcode) const bool jerk_travel_enabled = mesh_group_settings.get("jerk_travel_enabled"); std::shared_ptr current_mesh; - for (size_t extruder_plan_idx = 0; extruder_plan_idx < extruder_plans.size(); extruder_plan_idx++) + for (size_t extruder_plan_idx = 0; extruder_plan_idx < extruder_plans_.size(); extruder_plan_idx++) { - ExtruderPlan& extruder_plan = extruder_plans[extruder_plan_idx]; + ExtruderPlan& extruder_plan = extruder_plans_[extruder_plan_idx]; const RetractionAndWipeConfig* retraction_config - = current_mesh ? ¤t_mesh->retraction_wipe_config : &storage.retraction_wipe_config_per_extruder[extruder_plan.extruder_nr_]; + = current_mesh ? ¤t_mesh->retraction_wipe_config : &storage_.retraction_wipe_config_per_extruder[extruder_plan.extruder_nr_]; coord_t z_hop_height = retraction_config->retraction_config.zHop; if (extruder_nr != extruder_plan.extruder_nr_) @@ -1867,7 +1866,7 @@ void LayerPlan::writeGCode(GCodeExport& gcode) gcode.ResetLastEValueAfterWipe(prev_extruder); - const RetractionAndWipeConfig& prev_retraction_config = storage.retraction_wipe_config_per_extruder[prev_extruder]; + const RetractionAndWipeConfig& prev_retraction_config = storage_.retraction_wipe_config_per_extruder[prev_extruder]; if (prev_retraction_config.retraction_hop_after_extruder_switch) { z_hop_height = prev_retraction_config.extruder_switch_retraction_config.zHop; @@ -1887,8 +1886,8 @@ void LayerPlan::writeGCode(GCodeExport& gcode) { // turn off previous extruder constexpr bool wait = false; Temperature prev_extruder_temp = *extruder_plan.prev_extruder_standby_temp_; - const LayerIndex prev_layer_nr = (extruder_plan_idx == 0) ? layer_nr - 1 : layer_nr; - if (prev_layer_nr == storage.max_print_height_per_extruder[prev_extruder]) + const LayerIndex prev_layer_nr = (extruder_plan_idx == 0) ? layer_nr_ - 1 : layer_nr_; + if (prev_layer_nr == storage_.max_print_height_per_extruder[prev_extruder]) { prev_extruder_temp = 0; // TODO ? should there be a setting for extruder_off_temperature ? } @@ -1905,13 +1904,13 @@ void LayerPlan::writeGCode(GCodeExport& gcode) } else if (extruder_plan_idx == 0) { - const WipeScriptConfig& wipe_config = storage.retraction_wipe_config_per_extruder[extruder_plan.extruder_nr_].wipe_config; + const WipeScriptConfig& wipe_config = storage_.retraction_wipe_config_per_extruder[extruder_plan.extruder_nr_].wipe_config; if (wipe_config.clean_between_layers && gcode.getExtrudedVolumeAfterLastWipe(extruder_nr) > wipe_config.max_extrusion_mm3) { gcode.insertWipeScript(wipe_config); gcode.ResetLastEValueAfterWipe(extruder_nr); } - else if (layer_nr != 0 && Application::getInstance().current_slice_->scene.extruders[extruder_nr].settings_.get("retract_at_layer_change")) + else if (layer_nr_ != 0 && Application::getInstance().current_slice_->scene.extruders[extruder_nr].settings_.get("retract_at_layer_change")) { // only do the retract if the paths are not spiralized if (! mesh_group_settings.get("magic_spiralize")) @@ -1950,12 +1949,12 @@ void LayerPlan::writeGCode(GCodeExport& gcode) gcode.writeRetraction(retraction_config->retraction_config); } - if (z > 0) + if (z_ > 0) { - gcode.setZ(z + path.z_offset); + gcode.setZ(z_ + path.z_offset); } - if (! path.retract && path.config.isTravelPath() && path.points.size() == 1 && path.points[0] == gcode.getPositionXY() && (z + path.z_offset) == gcode.getPositionZ()) + if (! path.retract && path.config.isTravelPath() && path.points.size() == 1 && path.points[0] == gcode.getPositionXY() && (z_ + path.z_offset) == gcode.getPositionZ()) { // ignore travel moves to the current location to avoid needless change of acceleration/jerk continue; @@ -1984,9 +1983,9 @@ void LayerPlan::writeGCode(GCodeExport& gcode) // Use the acceleration of the first non-travel move *after* the travel. if (next_extrusion_idx >= paths.size()) // Only travel moves for the remainder of the layer. { - if (static_cast(next_layer_acc_jerk)) + if (static_cast(next_layer_acc_jerk_)) { - gcode.writeTravelAcceleration(next_layer_acc_jerk->first); + gcode.writeTravelAcceleration(next_layer_acc_jerk_->first); } // If the next layer has no extruded move, just keep the old acceleration. Should be very rare to have an empty layer. } else @@ -2011,9 +2010,9 @@ void LayerPlan::writeGCode(GCodeExport& gcode) // Use the jerk of the first non-travel move *after* the travel. if (next_extrusion_idx >= paths.size()) // Only travel moves for the remainder of the layer. { - if (static_cast(next_layer_acc_jerk)) + if (static_cast(next_layer_acc_jerk_)) { - gcode.writeJerk(next_layer_acc_jerk->second); + gcode.writeJerk(next_layer_acc_jerk_->second); } // If the next layer has no extruded move, just keep the old jerk. Should be very rare to have an empty layer. } else @@ -2069,21 +2068,21 @@ void LayerPlan::writeGCode(GCodeExport& gcode) } if (path.config.isTravelPath()) { // early comp for travel paths, which are handled more simply - if (! path.perform_z_hop && final_travel_z != z && extruder_plan_idx == (extruder_plans.size() - 1) && path_idx == (paths.size() - 1)) + if (! path.perform_z_hop && final_travel_z_ != z_ && extruder_plan_idx == (extruder_plans_.size() - 1) && path_idx == (paths.size() - 1)) { // Before the final travel, move up to the next layer height, on the current spot, with a sensible speed. Point3 current_position = gcode.getPosition(); - current_position.z_ = final_travel_z; + current_position.z_ = final_travel_z_; gcode.writeTravel(current_position, extruder.settings_.get("speed_z_hop")); // Prevent the final travel(s) from resetting to the 'previous' layer height. - gcode.setZ(final_travel_z); + gcode.setZ(final_travel_z_); } for (size_t point_idx = 0; point_idx + 1 < path.points.size(); point_idx++) { gcode.writeTravel(path.points[point_idx], speed); } - if (path.unretract_before_last_travel_move && final_travel_z == z) + if (path.unretract_before_last_travel_move && final_travel_z_ == z_) { // We need to unretract before the last travel move of the path if the next path is an outer wall. gcode.writeUnretractionAndPrime(); @@ -2102,7 +2101,7 @@ void LayerPlan::writeGCode(GCodeExport& gcode) bool coasting = extruder.settings_.get("coasting_enable"); if (coasting) { - coasting = writePathWithCoasting(gcode, extruder_plan_idx, path_idx, layer_thickness, insertTempOnTime); + coasting = writePathWithCoasting(gcode, extruder_plan_idx, path_idx, layer_thickness_, insertTempOnTime); } if (! coasting) // not same as 'else', cause we might have changed [coasting] in the line above... { // normal path to gcode algorithm @@ -2140,18 +2139,23 @@ void LayerPlan::writeGCode(GCodeExport& gcode) p0 = gcode.getPositionXY(); for (; path_idx < paths.size() && paths[path_idx].spiralize; path_idx++) { // handle all consecutive spiralized paths > CHANGES path_idx! - GCodePath& path = paths[path_idx]; + GCodePath& spiral_path = paths[path_idx]; - for (unsigned int point_idx = 0; point_idx < path.points.size(); point_idx++) + for (unsigned int point_idx = 0; point_idx < spiral_path.points.size(); point_idx++) { - const Point p1 = path.points[point_idx]; + const Point p1 = spiral_path.points[point_idx]; length += vSizeMM(p0 - p1); p0 = p1; - gcode.setZ(std::round(z + layer_thickness * length / totalLength)); - - const double extrude_speed = speed * path.speed_back_pressure_factor; - communication->sendLineTo(path.config.type, path.points[point_idx], path.getLineWidthForLayerView(), path.config.getLayerThickness(), extrude_speed); - gcode.writeExtrusion(path.points[point_idx], extrude_speed, path.getExtrusionMM3perMM(), path.config.type, update_extrusion_offset); + gcode.setZ(std::round(z_ + layer_thickness_ * length / totalLength)); + + const double extrude_speed = speed * spiral_path.speed_back_pressure_factor; + communication->sendLineTo( + spiral_path.config.type, + spiral_path.points[point_idx], + spiral_path.getLineWidthForLayerView(), + spiral_path.config.getLayerThickness(), + extrude_speed); + gcode.writeExtrusion(spiral_path.points[point_idx], extrude_speed, spiral_path.getExtrusionMM3perMM(), spiral_path.config.type, update_extrusion_offset); } // for layer display only - the loop finished at the seam vertex but as we started from // the location of the previous layer's seam vertex the loop may have a gap if this layer's @@ -2162,7 +2166,8 @@ void LayerPlan::writeGCode(GCodeExport& gcode) // vertex would not be shifted (as it's the last vertex in the sequence). The smoother the model, // the less the vertices are shifted and the less obvious is the ridge. If the layer display // really displayed a spiral rather than slices of a spiral, this would not be required. - communication->sendLineTo(path.config.type, path.points[0], path.getLineWidthForLayerView(), path.config.getLayerThickness(), speed); + communication + ->sendLineTo(spiral_path.config.type, spiral_path.points[0], spiral_path.getLineWidthForLayerView(), spiral_path.config.getLayerThickness(), speed); } path_idx--; // the last path_idx didnt spiralize, so it's not part of the current spiralize path } @@ -2172,9 +2177,9 @@ void LayerPlan::writeGCode(GCodeExport& gcode) { gcode.writeComment("Small layer, adding delay"); const RetractionAndWipeConfig& retraction_config - = current_mesh ? current_mesh->retraction_wipe_config : storage.retraction_wipe_config_per_extruder[gcode.getExtruderNr()]; + = current_mesh ? current_mesh->retraction_wipe_config : storage_.retraction_wipe_config_per_extruder[gcode.getExtruderNr()]; gcode.writeRetraction(retraction_config.retraction_config); - if (extruder_plan_idx == extruder_plans.size() - 1 || ! extruder.settings_.get("machine_extruder_end_pos_abs")) + if (extruder_plan_idx == extruder_plans_.size() - 1 || ! extruder.settings_.get("machine_extruder_end_pos_abs")) { // only do the z-hop if it's the last extruder plan; otherwise it's already at the switching bay area // or do it anyway when we switch extruder in-place gcode.writeZhopStart(MM2INT(3.0)); @@ -2187,7 +2192,7 @@ void LayerPlan::writeGCode(GCodeExport& gcode) "extruder_plan_2", extruder_plan.paths_, SectionType::NA, - layer_nr, + layer_nr_, scripta::CellVDI{ "flow", &GCodePath::flow }, scripta::CellVDI{ "width_factor", &GCodePath::width_factor }, scripta::CellVDI{ "spiralize", &GCodePath::spiralize }, @@ -2202,13 +2207,13 @@ void LayerPlan::writeGCode(GCodeExport& gcode) scripta::CellVDI{ "extrusion_mm3_per_mm", &GCodePath::getExtrusionMM3perMM }); } // extruder plans /\ . - communication->sendLayerComplete(layer_nr, z, layer_thickness); + communication->sendLayerComplete(layer_nr_, z_, layer_thickness_); gcode.updateTotalPrintTime(); } void LayerPlan::overrideFanSpeeds(double speed) { - for (ExtruderPlan& extruder_plan : extruder_plans) + for (ExtruderPlan& extruder_plan : extruder_plans_) { extruder_plan.setFanSpeed(speed); } @@ -2217,7 +2222,7 @@ void LayerPlan::overrideFanSpeeds(double speed) bool LayerPlan::makeRetractSwitchRetract(unsigned int extruder_plan_idx, unsigned int path_idx) { - std::vector& paths = extruder_plans[extruder_plan_idx].paths_; + std::vector& paths = extruder_plans_[extruder_plan_idx].paths_; for (unsigned int path_idx2 = path_idx + 1; path_idx2 < paths.size(); path_idx2++) { if (paths[path_idx2].getExtrusionMM3perMM() > 0) @@ -2226,12 +2231,12 @@ bool LayerPlan::makeRetractSwitchRetract(unsigned int extruder_plan_idx, unsigne } } - if (extruder_plans.size() <= extruder_plan_idx + 1) + if (extruder_plans_.size() <= extruder_plan_idx + 1) { return false; // TODO: check first extruder of the next layer! (generally only on the last layer of the second extruder) } - if (extruder_plans[extruder_plan_idx + 1].extruder_nr_ != extruder_plans[extruder_plan_idx].extruder_nr_) + if (extruder_plans_[extruder_plan_idx + 1].extruder_nr_ != extruder_plans_[extruder_plan_idx].extruder_nr_) { return true; } @@ -2248,7 +2253,7 @@ bool LayerPlan::writePathWithCoasting( const coord_t layer_thickness, const std::function insertTempOnTime) { - ExtruderPlan& extruder_plan = extruder_plans[extruder_plan_idx]; + ExtruderPlan& extruder_plan = extruder_plans_[extruder_plan_idx]; const ExtruderTrain& extruder = Application::getInstance().current_slice_->scene.extruders[extruder_plan.extruder_nr_]; const double coasting_volume = extruder.settings_.get("coasting_volume"); if (coasting_volume <= 0) @@ -2373,13 +2378,13 @@ bool LayerPlan::writePathWithCoasting( void LayerPlan::applyModifyPlugin() { - for (auto& extruder_plan : extruder_plans) + for (auto& extruder_plan : extruder_plans_) { scripta::log( "extruder_plan_0", extruder_plan.paths_, SectionType::NA, - layer_nr, + layer_nr_, scripta::CellVDI{ "flow", &GCodePath::flow }, scripta::CellVDI{ "width_factor", &GCodePath::width_factor }, scripta::CellVDI{ "spiralize", &GCodePath::spiralize }, @@ -2393,13 +2398,13 @@ void LayerPlan::applyModifyPlugin() scripta::CellVDI{ "is_travel_path", &GCodePath::isTravelPath }, scripta::CellVDI{ "extrusion_mm3_per_mm", &GCodePath::getExtrusionMM3perMM }); - extruder_plan.paths_ = slots::instance().modify(extruder_plan.paths_, extruder_plan.extruder_nr_, layer_nr); + extruder_plan.paths_ = slots::instance().modify(extruder_plan.paths_, extruder_plan.extruder_nr_, layer_nr_); scripta::log( "extruder_plan_1", extruder_plan.paths_, SectionType::NA, - layer_nr, + layer_nr_, scripta::CellVDI{ "flow", &GCodePath::flow }, scripta::CellVDI{ "width_factor", &GCodePath::width_factor }, scripta::CellVDI{ "spiralize", &GCodePath::spiralize }, @@ -2417,7 +2422,7 @@ void LayerPlan::applyModifyPlugin() void LayerPlan::applyBackPressureCompensation() { - for (auto& extruder_plan : extruder_plans) + for (auto& extruder_plan : extruder_plans_) { const Ratio back_pressure_compensation = Application::getInstance().current_slice_->scene.extruders[extruder_plan.extruder_nr_].settings_.get("speed_equalize_flow_width_factor"); @@ -2430,42 +2435,42 @@ void LayerPlan::applyBackPressureCompensation() LayerIndex LayerPlan::getLayerNr() const { - return layer_nr; + return layer_nr_; } Point LayerPlan::getLastPlannedPositionOrStartingPosition() const { - return last_planned_position.value_or(layer_start_pos_per_extruder[getExtruder()]); + return last_planned_position_.value_or(layer_start_pos_per_extruder_[getExtruder()]); } bool LayerPlan::getIsInsideMesh() const { - return was_inside; + return was_inside_; } bool LayerPlan::getSkirtBrimIsPlanned(unsigned int extruder_nr) const { - return skirt_brim_is_processed[extruder_nr]; + return skirt_brim_is_processed_[extruder_nr]; } void LayerPlan::setSkirtBrimIsPlanned(unsigned int extruder_nr) { - skirt_brim_is_processed[extruder_nr] = true; + skirt_brim_is_processed_[extruder_nr] = true; } size_t LayerPlan::getExtruder() const { - return extruder_plans.back().extruder_nr_; + return extruder_plans_.back().extruder_nr_; } void LayerPlan::setBridgeWallMask(const Polygons& polys) { - bridge_wall_mask = polys; + bridge_wall_mask_ = polys; } void LayerPlan::setOverhangMask(const Polygons& polys) { - overhang_mask = polys; + overhang_mask_ = polys; } } // namespace cura diff --git a/src/LayerPlanBuffer.cpp b/src/LayerPlanBuffer.cpp index 699f6ee54d..c2c85d9b8c 100644 --- a/src/LayerPlanBuffer.cpp +++ b/src/LayerPlanBuffer.cpp @@ -63,7 +63,8 @@ LayerPlan* LayerPlanBuffer::processBuffer() void LayerPlanBuffer::flush() { - Application::getInstance().communication_->flushGCode(); // If there was still g-code in a layer, flush that as a separate layer. Don't want to group them together accidentally. + Application::getInstance() + .communication_->flushGCode(); // If there was still g-code in a layer, flush that as a separate layer. Don't want to group them together accidentally. if (buffer_.size() > 0) { insertTempCommands(); // insert preheat commands of the very last layer @@ -83,26 +84,26 @@ void LayerPlanBuffer::addConnectingTravelMove(LayerPlan* prev_layer, const Layer if (! new_layer_destination_state) { - spdlog::warn("Layer {} is empty (or it has empty extruder plans). Temperature control and cross layer travel moves might suffer!", newest_layer->layer_nr); + spdlog::warn("Layer {} is empty (or it has empty extruder plans). Temperature control and cross layer travel moves might suffer!", newest_layer->layer_nr_); return; } Point first_location_new_layer = new_layer_destination_state->first; - assert(newest_layer->extruder_plans.front().paths_[0].points.size() == 1); - assert(newest_layer->extruder_plans.front().paths_[0].points[0] == first_location_new_layer); + assert(newest_layer->extruder_plans_.front().paths_[0].points.size() == 1); + assert(newest_layer->extruder_plans_.front().paths_[0].points[0] == first_location_new_layer); // if the last planned position in the previous layer isn't the same as the first location of the new layer, travel to the new location - if (! prev_layer->last_planned_position || *prev_layer->last_planned_position != first_location_new_layer) + if (! prev_layer->last_planned_position_ || *prev_layer->last_planned_position_ != first_location_new_layer) { const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; - const Settings& extruder_settings = Application::getInstance().current_slice_->scene.extruders[prev_layer->extruder_plans.back().extruder_nr_].settings_; + const Settings& extruder_settings = Application::getInstance().current_slice_->scene.extruders[prev_layer->extruder_plans_.back().extruder_nr_].settings_; prev_layer->setIsInside(new_layer_destination_state->second); const bool force_retract = extruder_settings.get("retract_at_layer_change") || (mesh_group_settings.get("travel_retract_before_outer_wall") && (mesh_group_settings.get("inset_direction") == InsetDirection::OUTSIDE_IN || mesh_group_settings.get("wall_line_count") == 1)); // Moving towards an outer wall. - prev_layer->final_travel_z = newest_layer->z; + prev_layer->final_travel_z_ = newest_layer->z_; GCodePath& path = prev_layer->addTravel(first_location_new_layer, force_retract); if (force_retract && ! path.retract) { @@ -114,7 +115,7 @@ void LayerPlanBuffer::addConnectingTravelMove(LayerPlan* prev_layer, const Layer } // If not using travel-specific jerk and acceleration, the layer plan needs to know the jerk/acc of the first extrusion move of the next layer. - prev_layer->next_layer_acc_jerk = newest_layer->first_extrusion_acc_jerk; + prev_layer->next_layer_acc_jerk_ = newest_layer->first_extrusion_acc_jerk_; } void LayerPlanBuffer::processFanSpeedLayerTime() @@ -492,7 +493,7 @@ void LayerPlanBuffer::insertFinalPrintTempCommand(std::vector& ex void LayerPlanBuffer::insertTempCommands() { - if (buffer_.back()->extruder_plans.size() == 0 || (buffer_.back()->extruder_plans.size() == 1 && buffer_.back()->extruder_plans[0].paths_.size() == 0)) + if (buffer_.back()->extruder_plans_.size() == 0 || (buffer_.back()->extruder_plans_.size() == 1 && buffer_.back()->extruder_plans_[0].paths_.size() == 0)) { // disregard empty layer buffer_.pop_back(); return; @@ -502,7 +503,7 @@ void LayerPlanBuffer::insertTempCommands() extruder_plans.reserve(buffer_.size() * 2); for (LayerPlan* layer_plan : buffer_) { - for (ExtruderPlan& extr_plan : layer_plan->extruder_plans) + for (ExtruderPlan& extr_plan : layer_plan->extruder_plans_) { extruder_plans.push_back(&extr_plan); } @@ -511,10 +512,10 @@ void LayerPlanBuffer::insertTempCommands() // insert commands for all extruder plans on this layer Scene& scene = Application::getInstance().current_slice_->scene; LayerPlan& layer_plan = *buffer_.back(); - for (size_t extruder_plan_idx = 0; extruder_plan_idx < layer_plan.extruder_plans.size(); extruder_plan_idx++) + for (size_t extruder_plan_idx = 0; extruder_plan_idx < layer_plan.extruder_plans_.size(); extruder_plan_idx++) { - const size_t overall_extruder_plan_idx = extruder_plans.size() - layer_plan.extruder_plans.size() + extruder_plan_idx; - ExtruderPlan& extruder_plan = layer_plan.extruder_plans[extruder_plan_idx]; + const size_t overall_extruder_plan_idx = extruder_plans.size() - layer_plan.extruder_plans_.size() + extruder_plan_idx; + ExtruderPlan& extruder_plan = layer_plan.extruder_plans_[extruder_plan_idx]; size_t extruder = extruder_plan.extruder_nr_; const Settings& extruder_settings = Application::getInstance().current_slice_->scene.extruders[extruder].settings_; Duration time = extruder_plan.estimates_.getTotalUnretractedTime(); @@ -557,7 +558,6 @@ void LayerPlanBuffer::insertTempCommands() if (buffer_.size() == 1 && extruder_plan_idx == 0) { // the very first extruder plan of the current meshgroup - size_t extruder = extruder_plan.extruder_nr_; for (size_t extruder_idx = 0; extruder_idx < scene.extruders.size(); extruder_idx++) { // set temperature of the first nozzle, turn other nozzles down const Settings& other_extruder_settings = Application::getInstance().current_slice_->scene.extruders[extruder_idx].settings_; diff --git a/src/PrimeTower.cpp b/src/PrimeTower.cpp index bfcaed4bdb..761103ee1c 100644 --- a/src/PrimeTower.cpp +++ b/src/PrimeTower.cpp @@ -248,7 +248,7 @@ void PrimeTower::addToGcode_denseInfill(LayerPlan& gcode_layer, const size_t ext if (! adhesion_raft || absolute_layer_number > 0) { // Actual prime pattern - const GCodePathConfig& config = gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr]; + const GCodePathConfig& config = gcode_layer.configs_storage_.prime_tower_config_per_extruder[extruder_nr]; const Polygons& pattern = prime_moves_[extruder_nr]; gcode_layer.addPolygonsByOptimizer(pattern, config); } @@ -257,7 +257,7 @@ void PrimeTower::addToGcode_denseInfill(LayerPlan& gcode_layer, const size_t ext if (absolute_layer_number < pattern_extra_brim.size()) { // Extra rings for stronger base - const GCodePathConfig& config = gcode_layer.configs_storage.prime_tower_config_per_extruder[extruder_nr]; + const GCodePathConfig& config = gcode_layer.configs_storage_.prime_tower_config_per_extruder[extruder_nr]; const Polygons& pattern = pattern_extra_brim[absolute_layer_number]; gcode_layer.addPolygonsByOptimizer(pattern, config); } diff --git a/src/TopSurface.cpp b/src/TopSurface.cpp index ba3915748d..b27abb3a54 100644 --- a/src/TopSurface.cpp +++ b/src/TopSurface.cpp @@ -98,7 +98,7 @@ bool TopSurface::ironing(const SliceDataStorage& storage, const SliceMeshStorage infill_overlap, infill_multiplier, direction, - layer.z - 10, + layer.z_ - 10, shift, max_resolution, max_deviation, @@ -116,7 +116,7 @@ bool TopSurface::ironing(const SliceDataStorage& storage, const SliceMeshStorage return false; // Nothing to do. } - layer.mode_skip_agressive_merge = true; + layer.mode_skip_agressive_merge_ = true; bool added = false; if (! ironing_polygons.empty()) @@ -187,7 +187,7 @@ bool TopSurface::ironing(const SliceDataStorage& storage, const SliceMeshStorage added = true; } - layer.mode_skip_agressive_merge = false; + layer.mode_skip_agressive_merge_ = false; return added; } diff --git a/src/TreeModelVolumes.cpp b/src/TreeModelVolumes.cpp index 750020cc1d..948ef86ec0 100644 --- a/src/TreeModelVolumes.cpp +++ b/src/TreeModelVolumes.cpp @@ -32,8 +32,8 @@ TreeModelVolumes::TreeModelVolumes( max_move_slow_{ std::max(max_move_slow - 2, coord_t(0)) } , // -2 to avoid rounding errors min_offset_per_step_{ min_offset_per_step } - , progress_multiplier{ progress_multiplier } - , progress_offset{ progress_offset } + , progress_multiplier_{ progress_multiplier } + , progress_offset_{ progress_offset } , machine_border_{ calculateMachineBorderCollision(storage.getMachineBorder()) } , machine_area_{ storage.getMachineBorder() } { @@ -48,7 +48,7 @@ TreeModelVolumes::TreeModelVolumes( coord_t min_maximum_deviation = std::numeric_limits::max(); coord_t min_maximum_area_deviation = std::numeric_limits::max(); - support_rests_on_model = false; + support_rests_on_model_ = false; for (auto [mesh_idx, mesh_ptr] : storage.meshes | ranges::views::enumerate) { auto& mesh = *mesh_ptr; @@ -70,33 +70,33 @@ TreeModelVolumes::TreeModelVolumes( for (const auto data_pair : layer_outlines_) { - support_rests_on_model |= data_pair.first.get("support_type") == ESupportType::EVERYWHERE; + support_rests_on_model_ |= data_pair.first.get("support_type") == ESupportType::EVERYWHERE; min_maximum_deviation = std::min(min_maximum_deviation, data_pair.first.get("meshfix_maximum_deviation")); min_maximum_resolution = std::min(min_maximum_resolution, data_pair.first.get("meshfix_maximum_resolution")); min_maximum_area_deviation = std::min(min_maximum_area_deviation, data_pair.first.get("meshfix_maximum_extrusion_area_deviation")); } // Figure out the rest of the setting(-like variable)s relevant to the class a whole. - current_outline_idx = mesh_to_layeroutline_idx[current_mesh_idx]; - const TreeSupportSettings config(layer_outlines_[current_outline_idx].first); + current_outline_idx_ = mesh_to_layeroutline_idx[current_mesh_idx]; + const TreeSupportSettings config(layer_outlines_[current_outline_idx_].first); if (config.support_overrides == SupportDistPriority::Z_OVERRIDES_XY) { - current_min_xy_dist = config.xy_min_distance; + current_min_xy_dist_ = config.xy_min_distance; if (TreeSupportSettings::has_to_rely_on_min_xy_dist_only) { - current_min_xy_dist = std::max(current_min_xy_dist, coord_t(FUDGE_LENGTH * 2)); + current_min_xy_dist_ = std::max(current_min_xy_dist_, coord_t(FUDGE_LENGTH * 2)); } - current_min_xy_dist_delta = std::max(config.xy_distance - current_min_xy_dist, coord_t(0)); + current_min_xy_dist_delta_ = std::max(config.xy_distance - current_min_xy_dist_, coord_t(0)); } else { - current_min_xy_dist = config.xy_distance; - current_min_xy_dist_delta = 0; + current_min_xy_dist_ = config.xy_distance; + current_min_xy_dist_delta_ = 0; } - increase_until_radius = config.increase_radius_until_radius; + increase_until_radius_ = config.increase_radius_until_radius; // Retrieve all layer outlines. Done in this way because normally we don't do this per mesh, but for the whole buildplate. // (So we can handle some settings on a per-mesh basis.) @@ -155,35 +155,35 @@ TreeModelVolumes::TreeModelVolumes( anti_overhang_[layer_idx] = anti_overhang_[layer_idx].unionPolygons(); }); - for (max_layer_idx_without_blocker = 0; max_layer_idx_without_blocker + 1 < anti_overhang_.size(); max_layer_idx_without_blocker++) + for (max_layer_idx_without_blocker_ = 0; max_layer_idx_without_blocker_ + 1 < anti_overhang_.size(); max_layer_idx_without_blocker_++) { - if (! anti_overhang_[max_layer_idx_without_blocker + 1].empty()) + if (! anti_overhang_[max_layer_idx_without_blocker_ + 1].empty()) { break; } } // Cache some handy settings in the object itself. - radius_0 = config.getRadius(0); - support_rest_preference = config.support_rest_preference; - simplifier = Simplify(min_maximum_resolution, min_maximum_deviation, min_maximum_area_deviation); + radius_0_ = config.getRadius(0); + support_rest_preference_ = config.support_rest_preference; + simplifier_ = Simplify(min_maximum_resolution, min_maximum_deviation, min_maximum_area_deviation); } void TreeModelVolumes::precalculate(coord_t max_layer) { const auto t_start = std::chrono::high_resolution_clock::now(); - precalculated = true; + precalculated_ = true; // Get the config corresponding to one mesh that is in the current group. Which one has to be irrelevant. // Not the prettiest way to do this, but it ensures some calculations that may be a bit more complex like initial layer diameter are only done in once. - const TreeSupportSettings config(layer_outlines_[current_outline_idx].first); + const TreeSupportSettings config(layer_outlines_[current_outline_idx_].first); // Calculate which radius each layer in the tip may have. std::unordered_set possible_tip_radiis; for (const auto dtt : ranges::views::iota(0UL, config.tip_layers + 1)) { possible_tip_radiis.emplace(ceilRadius(config.getRadius(dtt))); - possible_tip_radiis.emplace(ceilRadius(config.getRadius(dtt) + current_min_xy_dist_delta)); + possible_tip_radiis.emplace(ceilRadius(config.getRadius(dtt) + current_min_xy_dist_delta_)); } // It theoretically may happen in the tip, that the radius can change so much in-between 2 layers, that a ceil step is skipped (as in there is a radius r so that // ceilRadius(radius(dtt)) relevant_collision_radiis; @@ -256,7 +256,7 @@ void TreeModelVolumes::precalculate(coord_t max_layer) for (RadiusLayerPair key : relevant_avoidance_radiis) { spdlog::debug("Calculating avoidance of radius {} up to layer {}", key.first, key.second); - if (key.first < increase_until_radius + current_min_xy_dist_delta) + if (key.first < increase_until_radius_ + current_min_xy_dist_delta_) { relevant_hole_collision_radiis.emplace_back(key); } @@ -269,7 +269,7 @@ void TreeModelVolumes::precalculate(coord_t max_layer) auto t_acc = std::chrono::high_resolution_clock::now(); - if (max_layer_idx_without_blocker < max_layer && support_rests_on_model) + if (max_layer_idx_without_blocker_ < max_layer && support_rests_on_model_) { calculateAccumulatedPlaceable0(max_layer); t_acc = std::chrono::high_resolution_clock::now(); @@ -280,23 +280,23 @@ void TreeModelVolumes::precalculate(coord_t max_layer) std::future placeable_waiter; std::future avoidance_waiter; - if (support_rests_on_model) + if (support_rests_on_model_) { calculatePlaceables(relevant_avoidance_radiis_to_model); } - if (support_rest_preference == RestPreference::BUILDPLATE) + if (support_rest_preference_ == RestPreference::BUILDPLATE) { calculateAvoidance(relevant_avoidance_radiis); } calculateWallRestrictions(relevant_avoidance_radiis); - if (support_rests_on_model) + if (support_rests_on_model_) { // FIXME: When nowait (parellel-for) is implemented, ensure here the following is calculated: calculatePlaceables. calculateAvoidanceToModel(relevant_avoidance_radiis_to_model); // FIXME: When nowait (parellel-for) is implemented, ensure here the following is calculated: calculateAvoidanceToModel. } - if (support_rest_preference == RestPreference::BUILDPLATE) + if (support_rest_preference_ == RestPreference::BUILDPLATE) { // FIXME: When nowait (parellel-for) is implemented, ensure here the following is calculated: calculateAvoidance. } @@ -305,14 +305,14 @@ void TreeModelVolumes::precalculate(coord_t max_layer) const auto t_avo = std::chrono::high_resolution_clock::now(); auto t_colAvo = std::chrono::high_resolution_clock::now(); - if (max_layer_idx_without_blocker < max_layer && support_rests_on_model) + if (max_layer_idx_without_blocker_ < max_layer && support_rests_on_model_) { // FIXME: When nowait (parellel-for) is implemented, ensure here the following is calculated: calculateAccumulatedPlaceable0. calculateCollisionAvoidance(relevant_avoidance_radiis); t_colAvo = std::chrono::high_resolution_clock::now(); } - precalculationFinished = true; + precalculation_finished_ = true; const auto dur_col = 0.001 * std::chrono::duration_cast(t_coll - t_start).count(); const auto dur_acc = 0.001 * std::chrono::duration_cast(t_acc - t_coll).count(); const auto dur_avo = 0.001 * std::chrono::duration_cast(t_avo - t_acc).count(); @@ -334,7 +334,7 @@ const Polygons& TreeModelVolumes::getCollision(coord_t radius, LayerIndex layer_ std::optional> result; if (! min_xy_dist) { - radius += current_min_xy_dist_delta; + radius += current_min_xy_dist_delta_; } // special case as if a radius 0 is requested it could be to ensure correct xy distance. As such it is beneficial if the collision is as close to the configured values as @@ -353,7 +353,7 @@ const Polygons& TreeModelVolumes::getCollision(coord_t radius, LayerIndex layer_ { return result.value().get(); } - if (precalculated) + if (precalculated_) { spdlog::warn("Had to calculate collision at radius {} and layer {}, but precalculate was called. Performance may suffer!", key.first, key.second); } @@ -367,9 +367,9 @@ const Polygons& TreeModelVolumes::getCollisionHolefree(coord_t radius, LayerInde std::optional> result; if (! min_xy_dist) { - radius += current_min_xy_dist_delta; + radius += current_min_xy_dist_delta_; } - if (radius >= increase_until_radius + current_min_xy_dist_delta) + if (radius >= increase_until_radius_ + current_min_xy_dist_delta_) { return getCollision(orig_radius, layer_idx, min_xy_dist); } @@ -383,7 +383,7 @@ const Polygons& TreeModelVolumes::getCollisionHolefree(coord_t radius, LayerInde { return result.value().get(); } - if (precalculated) + if (precalculated_) { spdlog::warn("Had to calculate collision holefree at radius {} and layer {}, but precalculate was called. Performance may suffer!", key.first, key.second); } @@ -415,10 +415,10 @@ const Polygons& TreeModelVolumes::getAvoidance(coord_t radius, LayerIndex layer_ std::optional> result; - radius += (min_xy_dist ? 0 : current_min_xy_dist_delta); + radius += (min_xy_dist ? 0 : current_min_xy_dist_delta_); radius = ceilRadius(radius); - if (radius >= increase_until_radius + current_min_xy_dist_delta && type == AvoidanceType::FAST_SAFE) // no holes anymore by definition at this request + if (radius >= increase_until_radius_ + current_min_xy_dist_delta_ && type == AvoidanceType::FAST_SAFE) // no holes anymore by definition at this request { type = AvoidanceType::FAST; } @@ -442,7 +442,7 @@ const Polygons& TreeModelVolumes::getAvoidance(coord_t radius, LayerIndex layer_ mutex_ptr = to_model ? critical_avoidance_cache_holefree_to_model_.get() : critical_avoidance_cache_holefree_.get(); break; case AvoidanceType::COLLISION: - if (layer_idx <= max_layer_idx_without_blocker) + if (layer_idx <= max_layer_idx_without_blocker_) { return getCollision(radius, layer_idx, true); } @@ -465,7 +465,7 @@ const Polygons& TreeModelVolumes::getAvoidance(coord_t radius, LayerIndex layer_ { return result.value().get(); } - if (precalculated) + if (precalculated_) { spdlog::warn( "Had to calculate Avoidance (to model-bool: {}) at radius {} and layer {} and type {}, but precalculate was called. Performance may suffer!", @@ -504,7 +504,7 @@ const Polygons& TreeModelVolumes::getPlaceableAreas(coord_t radius, LayerIndex l { return result.value().get(); } - if (precalculated) + if (precalculated_) { spdlog::warn("Had to calculate Placeable Areas at radius {} and layer {}, but precalculate was called. Performance may suffer!", radius, layer_idx); } @@ -528,7 +528,7 @@ const Polygons& TreeModelVolumes::getWallRestriction(coord_t radius, LayerIndex } const coord_t orig_radius = radius; - min_xy_dist = min_xy_dist && current_min_xy_dist_delta > 0; + min_xy_dist = min_xy_dist && current_min_xy_dist_delta_ > 0; std::optional> result; @@ -544,7 +544,7 @@ const Polygons& TreeModelVolumes::getWallRestriction(coord_t radius, LayerIndex { return result.value().get(); } - if (precalculated) + if (precalculated_) { spdlog::warn("Had to calculate Wall restrictions at radius {} and layer {}, but precalculate was called. Performance may suffer!", key.first, key.second); } @@ -555,12 +555,12 @@ const Polygons& TreeModelVolumes::getWallRestriction(coord_t radius, LayerIndex coord_t TreeModelVolumes::ceilRadius(coord_t radius, bool min_xy_dist) const { - return ceilRadius(radius + (min_xy_dist ? 0 : current_min_xy_dist_delta)); + return ceilRadius(radius + (min_xy_dist ? 0 : current_min_xy_dist_delta_)); } coord_t TreeModelVolumes::getRadiusNextCeil(coord_t radius, bool min_xy_dist) const { - return ceilRadius(radius, min_xy_dist) - (min_xy_dist ? 0 : current_min_xy_dist_delta); + return ceilRadius(radius, min_xy_dist) - (min_xy_dist ? 0 : current_min_xy_dist_delta_); } bool TreeModelVolumes::checkSettingsEquality(const Settings& me, const Settings& other) const @@ -634,7 +634,7 @@ void TreeModelVolumes::calculateCollision(const std::deque& key const coord_t z_distance_top_layers = round_up_divide(layer_outlines_[outline_idx].first.get("support_top_distance"), layer_height); const LayerIndex max_anti_overhang_layer = anti_overhang_.size() - 1; const LayerIndex max_required_layer = keys[i].second + std::max(coord_t(1), z_distance_top_layers); - const coord_t xy_distance = outline_idx == current_outline_idx ? current_min_xy_dist : layer_outlines_[outline_idx].first.get("support_xy_distance"); + const coord_t xy_distance = outline_idx == current_outline_idx_ ? current_min_xy_dist_ : layer_outlines_[outline_idx].first.get("support_xy_distance"); // Technically this causes collision for the normal xy_distance to be larger by current_min_xy_dist_delta for all not currently processing meshes as this delta will // be added at request time. Avoiding this would require saving each collision for each outline_idx separately, // and later for each avoidance... But avoidance calculation has to be for the whole scene and can NOT be done for each outline_idx separately and combined later. @@ -673,7 +673,7 @@ void TreeModelVolumes::calculateCollision(const std::deque& key } // Placeable areas also have to be calculated when a collision has to be calculated if called outside of precalculate to prevent an infinite loop when they are // invalidly requested... - if ((support_rests_on_this_model || precalculationFinished || ! precalculated) && radius == 0 && layer_idx < coord_t(1 + keys[i].second)) + if ((support_rests_on_this_model || precalculation_finished_ || ! precalculated_) && radius == 0 && layer_idx < coord_t(1 + keys[i].second)) { data[key] = data[key].unionPolygons(); Polygons above = data[RadiusLayerPair(radius, layer_idx + 1)]; @@ -731,26 +731,26 @@ void TreeModelVolumes::calculateCollision(const std::deque& key for (auto pair : data) { - pair.second = simplifier.polygon(pair.second); + pair.second = simplifier_.polygon(pair.second); data_outer[pair.first] = data_outer[pair.first].unionPolygons(pair.second); } if (radius == 0) { for (auto pair : data_placeable) { - pair.second = simplifier.polygon(pair.second); + pair.second = simplifier_.polygon(pair.second); data_placeable_outer[pair.first] = data_placeable_outer[pair.first].unionPolygons(pair.second); } } } { - std::lock_guard critical_section(*critical_progress); + std::lock_guard critical_section(*critical_progress_); - if (precalculated && precalculation_progress < TREE_PROGRESS_PRECALC_COLL) + if (precalculated_ && precalculation_progress_ < TREE_PROGRESS_PRECALC_COLL) { - precalculation_progress += TREE_PROGRESS_PRECALC_COLL / keys.size(); - Progress::messageProgress(Progress::Stage::SUPPORT, precalculation_progress * progress_multiplier + progress_offset, TREE_PROGRESS_TOTAL); + precalculation_progress_ += TREE_PROGRESS_PRECALC_COLL / keys.size(); + Progress::messageProgress(Progress::Stage::SUPPORT, precalculation_progress_ * progress_multiplier_ + progress_offset_, TREE_PROGRESS_TOTAL); } } @@ -786,10 +786,10 @@ void TreeModelVolumes::calculateCollisionHolefree(const std::deque critical_section(*critical_accumulated_placeables_cache_radius_0_); - accumulated_placeable_0 = simplifier.polygon(accumulated_placeable_0); + accumulated_placeable_0 = simplifier_.polygon(accumulated_placeable_0); data[layer] = std::pair(layer, accumulated_placeable_0); } cura::parallel_for( @@ -837,7 +837,7 @@ void TreeModelVolumes::calculateAccumulatedPlaceable0(const LayerIndex max_layer data.size(), [&](const coord_t layer_idx) { - data[layer_idx].second = data[layer_idx].second.offset(-(current_min_xy_dist + current_min_xy_dist_delta)); + data[layer_idx].second = data[layer_idx].second.offset(-(current_min_xy_dist_ + current_min_xy_dist_delta_)); }); { std::lock_guard critical_section(*critical_accumulated_placeables_cache_radius_0_); @@ -855,11 +855,11 @@ void TreeModelVolumes::calculateCollisionAvoidance(const std::deque critical_section(*critical_avoidance_cache_collision_); - start_layer = 1 + std::max(getMaxCalculatedLayer(radius, avoidance_cache_collision_), max_layer_idx_without_blocker); + start_layer = 1 + std::max(getMaxCalculatedLayer(radius, avoidance_cache_collision_), max_layer_idx_without_blocker_); } if (start_layer > max_required_layer) @@ -877,10 +877,10 @@ void TreeModelVolumes::calculateCollisionAvoidance(const std::deque& key const LayerIndex max_required_layer = keys[key_idx].second; // do not calculate not needed safe avoidances - if (holefree && radius >= increase_until_radius + current_min_xy_dist_delta) + if (holefree && radius >= increase_until_radius_ + current_min_xy_dist_delta_) { return; } const coord_t offset_speed = slow ? max_move_slow_ : max_move_; - const coord_t max_step_move = std::max(1.9 * radius, current_min_xy_dist * 1.9); + const coord_t max_step_move = std::max(1.9 * radius, current_min_xy_dist_ * 1.9); RadiusLayerPair key(radius, 0); Polygons latest_avoidance; LayerIndex start_layer; @@ -966,7 +966,7 @@ void TreeModelVolumes::calculateAvoidance(const std::deque& key { key.second = layer; Polygons col; - if ((slow && radius < increase_until_radius + current_min_xy_dist_delta) || holefree) + if ((slow && radius < increase_until_radius_ + current_min_xy_dist_delta_) || holefree) { col = getCollisionHolefree(radius, layer, true); } @@ -976,7 +976,7 @@ void TreeModelVolumes::calculateAvoidance(const std::deque& key } latest_avoidance = safeOffset(latest_avoidance, -offset_speed, ClipperLib::jtRound, -max_step_move, col); - Polygons next_latest_avoidance = simplifier.polygon(latest_avoidance); + Polygons next_latest_avoidance = simplifier_.polygon(latest_avoidance); latest_avoidance = next_latest_avoidance.unionPolygons(latest_avoidance); // ^^^ Ensure the simplification only causes the avoidance to become larger. // If the deviation of the simplification causes the avoidance to become smaller than it should be it can cause issues, if it is larger the worst case is that the @@ -986,12 +986,12 @@ void TreeModelVolumes::calculateAvoidance(const std::deque& key } { - std::lock_guard critical_section(*critical_progress); + std::lock_guard critical_section(*critical_progress_); - if (precalculated && precalculation_progress < TREE_PROGRESS_PRECALC_COLL + TREE_PROGRESS_PRECALC_AVO) + if (precalculated_ && precalculation_progress_ < TREE_PROGRESS_PRECALC_COLL + TREE_PROGRESS_PRECALC_AVO) { - precalculation_progress += support_rests_on_model ? 0.4 : 1 * TREE_PROGRESS_PRECALC_AVO / (keys.size() * 3); - Progress::messageProgress(Progress::Stage::SUPPORT, precalculation_progress * progress_multiplier + progress_offset, TREE_PROGRESS_TOTAL); + precalculation_progress_ += support_rests_on_model_ ? 0.4 : 1 * TREE_PROGRESS_PRECALC_AVO / (keys.size() * 3); + Progress::messageProgress(Progress::Stage::SUPPORT, precalculation_progress_ * progress_multiplier_ + progress_offset_, TREE_PROGRESS_TOTAL); } } @@ -1037,18 +1037,18 @@ void TreeModelVolumes::calculatePlaceables(const std::deque& ke { key.second = layer; Polygons placeable = getPlaceableAreas(0, layer); - placeable = simplifier.polygon(placeable); // it is faster to do this here in each thread than once in calculateCollision. - placeable = placeable.offset(-(radius + (current_min_xy_dist + current_min_xy_dist_delta))).unionPolygons(); + placeable = simplifier_.polygon(placeable); // it is faster to do this here in each thread than once in calculateCollision. + placeable = placeable.offset(-(radius + (current_min_xy_dist_ + current_min_xy_dist_delta_))).unionPolygons(); data[layer] = std::pair(key, placeable); } { - std::lock_guard critical_section(*critical_progress); + std::lock_guard critical_section(*critical_progress_); - if (precalculated && precalculation_progress < TREE_PROGRESS_PRECALC_COLL + TREE_PROGRESS_PRECALC_AVO) + if (precalculated_ && precalculation_progress_ < TREE_PROGRESS_PRECALC_COLL + TREE_PROGRESS_PRECALC_AVO) { - precalculation_progress += 0.2 * TREE_PROGRESS_PRECALC_AVO / (keys.size()); - Progress::messageProgress(Progress::Stage::SUPPORT, precalculation_progress * progress_multiplier + progress_offset, TREE_PROGRESS_TOTAL); + precalculation_progress_ += 0.2 * TREE_PROGRESS_PRECALC_AVO / (keys.size()); + Progress::messageProgress(Progress::Stage::SUPPORT, precalculation_progress_ * progress_multiplier_ + progress_offset_, TREE_PROGRESS_TOTAL); } } @@ -1080,13 +1080,13 @@ void TreeModelVolumes::calculateAvoidanceToModel(const std::deque= increase_until_radius + current_min_xy_dist_delta) + if (holefree && radius >= increase_until_radius_ + current_min_xy_dist_delta_) { return; } getPlaceableAreas(radius, max_required_layer); // ensuring Placeableareas are calculated const coord_t offset_speed = slow ? max_move_slow_ : max_move_; - const coord_t max_step_move = std::max(1.9 * radius, current_min_xy_dist * 1.9); + const coord_t max_step_move = std::max(1.9 * radius, current_min_xy_dist_ * 1.9); Polygons latest_avoidance; std::vector> data(max_required_layer + 1, std::pair(RadiusLayerPair(radius, -1), Polygons())); RadiusLayerPair key(radius, 0); @@ -1115,7 +1115,7 @@ void TreeModelVolumes::calculateAvoidanceToModel(const std::deque critical_section(*critical_progress); + std::lock_guard critical_section(*critical_progress_); - if (precalculated && precalculation_progress < TREE_PROGRESS_PRECALC_COLL + TREE_PROGRESS_PRECALC_AVO) + if (precalculated_ && precalculation_progress_ < TREE_PROGRESS_PRECALC_COLL + TREE_PROGRESS_PRECALC_AVO) { - precalculation_progress += 0.4 * TREE_PROGRESS_PRECALC_AVO / (keys.size() * 3); - Progress::messageProgress(Progress::Stage::SUPPORT, precalculation_progress * progress_multiplier + progress_offset, TREE_PROGRESS_TOTAL); + precalculation_progress_ += 0.4 * TREE_PROGRESS_PRECALC_AVO / (keys.size() * 3); + Progress::messageProgress(Progress::Stage::SUPPORT, precalculation_progress_ * progress_multiplier_ + progress_offset_, TREE_PROGRESS_TOTAL); } } @@ -1218,12 +1218,12 @@ void TreeModelVolumes::calculateWallRestrictions(const std::deque 0) + if (current_min_xy_dist_delta_ > 0) { - Polygons wall_restriction_min = simplifier.polygon(getCollision(0, layer_idx, true).intersection(getCollision(radius, layer_idx_below, true))); + Polygons wall_restriction_min = simplifier_.polygon(getCollision(0, layer_idx, true).intersection(getCollision(radius, layer_idx_below, true))); data_min.emplace(key, wall_restriction_min); } } @@ -1246,14 +1246,14 @@ coord_t TreeModelVolumes::ceilRadius(coord_t radius) const { return 0; } - if (radius <= radius_0) + if (radius <= radius_0_) { - return radius_0; + return radius_0_; } coord_t exponential_result = SUPPORT_TREE_EXPONENTIAL_THRESHOLD * SUPPORT_TREE_EXPONENTIAL_FACTOR; - const coord_t stepsize = (exponential_result - radius_0) / (SUPPORT_TREE_PRE_EXPONENTIAL_STEPS + 1); - coord_t result = radius_0; + const coord_t stepsize = (exponential_result - radius_0_) / (SUPPORT_TREE_PRE_EXPONENTIAL_STEPS + 1); + coord_t result = radius_0_; for (const auto step : ranges::views::iota(0UL, SUPPORT_TREE_PRE_EXPONENTIAL_STEPS)) { result += stepsize; diff --git a/src/WallToolPaths.cpp b/src/WallToolPaths.cpp index c46d4afbf5..edf90d751a 100644 --- a/src/WallToolPaths.cpp +++ b/src/WallToolPaths.cpp @@ -30,19 +30,19 @@ WallToolPaths::WallToolPaths( const Settings& settings, const int layer_idx, SectionType section_type) - : outline(outline) - , bead_width_0(nominal_bead_width) - , bead_width_x(nominal_bead_width) - , inset_count(inset_count) - , wall_0_inset(wall_0_inset) - , print_thin_walls(settings.get("fill_outline_gaps")) - , min_feature_size(settings.get("min_feature_size")) - , min_bead_width(settings.get("min_bead_width")) - , small_area_length(INT2MM(static_cast(nominal_bead_width) / 2)) - , toolpaths_generated(false) - , settings(settings) - , layer_idx(layer_idx) - , section_type(section_type) + : outline_(outline) + , bead_width_0_(nominal_bead_width) + , bead_width_x_(nominal_bead_width) + , inset_count_(inset_count) + , wall_0_inset_(wall_0_inset) + , print_thin_walls_(settings.get("fill_outline_gaps")) + , min_feature_size_(settings.get("min_feature_size")) + , min_bead_width_(settings.get("min_bead_width")) + , small_area_length_(INT2MM(static_cast(nominal_bead_width) / 2)) + , toolpaths_generated_(false) + , settings_(settings) + , layer_idx_(layer_idx) + , section_type_(section_type) { } @@ -55,46 +55,46 @@ WallToolPaths::WallToolPaths( const Settings& settings, const int layer_idx, SectionType section_type) - : outline(outline) - , bead_width_0(bead_width_0) - , bead_width_x(bead_width_x) - , inset_count(inset_count) - , wall_0_inset(wall_0_inset) - , print_thin_walls(settings.get("fill_outline_gaps")) - , min_feature_size(settings.get("min_feature_size")) - , min_bead_width(settings.get("min_bead_width")) - , small_area_length(INT2MM(static_cast(bead_width_0) / 2)) - , toolpaths_generated(false) - , settings(settings) - , layer_idx(layer_idx) - , section_type(section_type) + : outline_(outline) + , bead_width_0_(bead_width_0) + , bead_width_x_(bead_width_x) + , inset_count_(inset_count) + , wall_0_inset_(wall_0_inset) + , print_thin_walls_(settings.get("fill_outline_gaps")) + , min_feature_size_(settings.get("min_feature_size")) + , min_bead_width_(settings.get("min_bead_width")) + , small_area_length_(INT2MM(static_cast(bead_width_0) / 2)) + , toolpaths_generated_(false) + , settings_(settings) + , layer_idx_(layer_idx) + , section_type_(section_type) { } const std::vector& WallToolPaths::generate() { - const coord_t allowed_distance = settings.get("meshfix_maximum_deviation"); + const coord_t allowed_distance = settings_.get("meshfix_maximum_deviation"); // Sometimes small slivers of polygons mess up the prepared_outline. By performing an open-close operation // with half the minimum printable feature size or minimum line width, these slivers are removed, while still // keeping enough information to not degrade the print quality; // These features can't be printed anyhow. See PR CuraEngine#1811 for some screenshots const coord_t open_close_distance - = settings.get("fill_outline_gaps") ? settings.get("min_feature_size") / 2 - 5 : settings.get("min_wall_line_width") / 2 - 5; + = settings_.get("fill_outline_gaps") ? settings_.get("min_feature_size") / 2 - 5 : settings_.get("min_wall_line_width") / 2 - 5; const coord_t epsilon_offset = (allowed_distance / 2) - 1; - const auto transitioning_angle = settings.get("wall_transition_angle"); + const auto transitioning_angle = settings_.get("wall_transition_angle"); constexpr coord_t discretization_step_size = MM2INT(0.8); // Simplify outline for boost::voronoi consumption. Absolutely no self intersections or near-self intersections allowed: // TODO: Open question: Does this indeed fix all (or all-but-one-in-a-million) cases for manifold but otherwise possibly complex polygons? - Polygons prepared_outline = outline.offset(-open_close_distance).offset(open_close_distance * 2).offset(-open_close_distance); - scripta::log("prepared_outline_0", prepared_outline, section_type, layer_idx); - prepared_outline.removeSmallAreas(small_area_length * small_area_length, false); - prepared_outline = Simplify(settings).polygon(prepared_outline); - if (settings.get("meshfix_fluid_motion_enabled") && section_type != SectionType::SUPPORT) + Polygons prepared_outline = outline_.offset(-open_close_distance).offset(open_close_distance * 2).offset(-open_close_distance); + scripta::log("prepared_outline_0", prepared_outline, section_type_, layer_idx_); + prepared_outline.removeSmallAreas(small_area_length_ * small_area_length_, false); + prepared_outline = Simplify(settings_).polygon(prepared_outline); + if (settings_.get("meshfix_fluid_motion_enabled") && section_type_ != SectionType::SUPPORT) { // No need to smooth support walls - auto smoother = actions::smooth(settings); + auto smoother = actions::smooth(settings_); for (auto& polygon : prepared_outline) { polygon = smoother(polygon); @@ -108,43 +108,43 @@ const std::vector& WallToolPaths::generate() PolygonUtils::fixSelfIntersections(epsilon_offset, prepared_outline); prepared_outline.removeDegenerateVerts(); prepared_outline = prepared_outline.unionPolygons(); - prepared_outline = Simplify(settings).polygon(prepared_outline); + prepared_outline = Simplify(settings_).polygon(prepared_outline); if (prepared_outline.area() <= 0) { - assert(toolpaths.empty()); - return toolpaths; + assert(toolpaths_.empty()); + return toolpaths_; } - const coord_t wall_transition_length = settings.get("wall_transition_length"); + const coord_t wall_transition_length = settings_.get("wall_transition_length"); // When to split the middle wall into two: - const double min_even_wall_line_width = settings.get("min_even_wall_line_width"); - const double wall_line_width_0 = settings.get("wall_line_width_0"); + const double min_even_wall_line_width = settings_.get("min_even_wall_line_width"); + const double wall_line_width_0 = settings_.get("wall_line_width_0"); const Ratio wall_split_middle_threshold = std::max(1.0, std::min(99.0, 100.0 * (2.0 * min_even_wall_line_width - wall_line_width_0) / wall_line_width_0)) / 100.0; // When to add a new middle in between the innermost two walls: - const double min_odd_wall_line_width = settings.get("min_odd_wall_line_width"); - const double wall_line_width_x = settings.get("wall_line_width_x"); + const double min_odd_wall_line_width = settings_.get("min_odd_wall_line_width"); + const double wall_line_width_x = settings_.get("wall_line_width_x"); const Ratio wall_add_middle_threshold = std::max(1.0, std::min(99.0, 100.0 * min_odd_wall_line_width / wall_line_width_x)) / 100.0; - const int wall_distribution_count = settings.get("wall_distribution_count"); - const size_t max_bead_count = (inset_count < std::numeric_limits::max() / 2) ? 2 * inset_count : std::numeric_limits::max(); + const int wall_distribution_count = settings_.get("wall_distribution_count"); + const size_t max_bead_count = (inset_count_ < std::numeric_limits::max() / 2) ? 2 * inset_count_ : std::numeric_limits::max(); const auto beading_strat = BeadingStrategyFactory::makeStrategy( - bead_width_0, - bead_width_x, + bead_width_0_, + bead_width_x_, wall_transition_length, transitioning_angle, - print_thin_walls, - min_bead_width, - min_feature_size, + print_thin_walls_, + min_bead_width_, + min_feature_size_, wall_split_middle_threshold, wall_add_middle_threshold, max_bead_count, - wall_0_inset, + wall_0_inset_, wall_distribution_count); - const auto transition_filter_dist = settings.get("wall_transition_filter_distance"); - const auto allowed_filter_deviation = settings.get("wall_transition_filter_deviation"); + const auto transition_filter_dist = settings_.get("wall_transition_filter_distance"); + const auto allowed_filter_deviation = settings_.get("wall_transition_filter_deviation"); SkeletalTrapezoidation wall_maker( prepared_outline, *beading_strat, @@ -153,50 +153,50 @@ const std::vector& WallToolPaths::generate() transition_filter_dist, allowed_filter_deviation, wall_transition_length, - layer_idx, - section_type); - wall_maker.generateToolpaths(toolpaths); + layer_idx_, + section_type_); + wall_maker.generateToolpaths(toolpaths_); scripta::log( "toolpaths_0", - toolpaths, - section_type, - layer_idx, + toolpaths_, + section_type_, + layer_idx_, scripta::CellVDI{ "is_closed", &ExtrusionLine::is_closed }, scripta::CellVDI{ "is_odd", &ExtrusionLine::is_odd }, scripta::CellVDI{ "inset_idx", &ExtrusionLine::inset_idx }, scripta::PointVDI{ "width", &ExtrusionJunction::w }, scripta::PointVDI{ "perimeter_index", &ExtrusionJunction::perimeter_index }); - stitchToolPaths(toolpaths, settings); + stitchToolPaths(toolpaths_, settings_); scripta::log( "toolpaths_1", - toolpaths, - section_type, - layer_idx, + toolpaths_, + section_type_, + layer_idx_, scripta::CellVDI{ "is_closed", &ExtrusionLine::is_closed }, scripta::CellVDI{ "is_odd", &ExtrusionLine::is_odd }, scripta::CellVDI{ "inset_idx", &ExtrusionLine::inset_idx }, scripta::PointVDI{ "width", &ExtrusionJunction::w }, scripta::PointVDI{ "perimeter_index", &ExtrusionJunction::perimeter_index }); - removeSmallLines(toolpaths); + removeSmallLines(toolpaths_); scripta::log( "toolpaths_2", - toolpaths, - section_type, - layer_idx, + toolpaths_, + section_type_, + layer_idx_, scripta::CellVDI{ "is_closed", &ExtrusionLine::is_closed }, scripta::CellVDI{ "is_odd", &ExtrusionLine::is_odd }, scripta::CellVDI{ "inset_idx", &ExtrusionLine::inset_idx }, scripta::PointVDI{ "width", &ExtrusionJunction::w }, scripta::PointVDI{ "perimeter_index", &ExtrusionJunction::perimeter_index }); - simplifyToolPaths(toolpaths, settings); + simplifyToolPaths(toolpaths_, settings_); scripta::log( "toolpaths_3", - toolpaths, - section_type, - layer_idx, + toolpaths_, + section_type_, + layer_idx_, scripta::CellVDI{ "is_closed", &ExtrusionLine::is_closed }, scripta::CellVDI{ "is_odd", &ExtrusionLine::is_odd }, scripta::CellVDI{ "inset_idx", &ExtrusionLine::inset_idx }, @@ -205,12 +205,12 @@ const std::vector& WallToolPaths::generate() separateOutInnerContour(); - removeEmptyToolPaths(toolpaths); + removeEmptyToolPaths(toolpaths_); scripta::log( "toolpaths_4", - toolpaths, - section_type, - layer_idx, + toolpaths_, + section_type_, + layer_idx_, scripta::CellVDI{ "is_closed", &ExtrusionLine::is_closed }, scripta::CellVDI{ "is_odd", &ExtrusionLine::is_odd }, scripta::CellVDI{ "inset_idx", &ExtrusionLine::inset_idx }, @@ -218,25 +218,25 @@ const std::vector& WallToolPaths::generate() scripta::PointVDI{ "perimeter_index", &ExtrusionJunction::perimeter_index }); assert( std::is_sorted( - toolpaths.cbegin(), - toolpaths.cend(), + toolpaths_.cbegin(), + toolpaths_.cend(), [](const VariableWidthLines& l, const VariableWidthLines& r) { return l.front().inset_idx < r.front().inset_idx; }) && "WallToolPaths should be sorted from the outer 0th to inner_walls"); - toolpaths_generated = true; + toolpaths_generated_ = true; scripta::log( "toolpaths_5", - toolpaths, - section_type, - layer_idx, + toolpaths_, + section_type_, + layer_idx_, scripta::CellVDI{ "is_closed", &ExtrusionLine::is_closed }, scripta::CellVDI{ "is_odd", &ExtrusionLine::is_odd }, scripta::CellVDI{ "inset_idx", &ExtrusionLine::inset_idx }, scripta::PointVDI{ "width", &ExtrusionJunction::w }, scripta::PointVDI{ "perimeter_index", &ExtrusionJunction::perimeter_index }); - return toolpaths; + return toolpaths_; } @@ -322,31 +322,31 @@ void WallToolPaths::simplifyToolPaths(std::vector& toolpaths const std::vector& WallToolPaths::getToolPaths() { - if (! toolpaths_generated) + if (! toolpaths_generated_) { return generate(); } - return toolpaths; + return toolpaths_; } void WallToolPaths::pushToolPaths(std::vector& paths) { - if (! toolpaths_generated) + if (! toolpaths_generated_) { generate(); } - paths.insert(paths.end(), toolpaths.begin(), toolpaths.end()); + paths.insert(paths.end(), toolpaths_.begin(), toolpaths_.end()); } void WallToolPaths::separateOutInnerContour() { // We'll remove all 0-width paths from the original toolpaths and store them separately as polygons. std::vector actual_toolpaths; - actual_toolpaths.reserve(toolpaths.size()); // A bit too much, but the correct order of magnitude. + actual_toolpaths.reserve(toolpaths_.size()); // A bit too much, but the correct order of magnitude. std::vector contour_paths; - contour_paths.reserve(toolpaths.size() / inset_count); - inner_contour.clear(); - for (const VariableWidthLines& inset : toolpaths) + contour_paths.reserve(toolpaths_.size() / inset_count_); + inner_contour_.clear(); + for (const VariableWidthLines& inset : toolpaths_) { if (inset.empty()) { @@ -389,7 +389,7 @@ void WallToolPaths::separateOutInnerContour() } else if (line.is_closed) // sometimes an very small even polygonal wall is not stitched into a polygon { - inner_contour.emplace_back(line.toPolygon()); + inner_contour_.emplace_back(line.toPolygon()); } } } @@ -400,11 +400,11 @@ void WallToolPaths::separateOutInnerContour() } if (! actual_toolpaths.empty()) { - toolpaths = std::move(actual_toolpaths); // Filtered out the 0-width paths. + toolpaths_ = std::move(actual_toolpaths); // Filtered out the 0-width paths. } else { - toolpaths.clear(); + toolpaths_.clear(); } // The output walls from the skeletal trapezoidation have no known winding order, especially if they are joined together from polylines. @@ -412,20 +412,20 @@ void WallToolPaths::separateOutInnerContour() // To get a correct shape, we need to make the outside contour positive and any holes inside negative. // This can be done by applying the even-odd rule to the shape. This rule is not sensitive to the winding order of the polygon. // The even-odd rule would be incorrect if the polygon self-intersects, but that should never be generated by the skeletal trapezoidation. - inner_contour = inner_contour.processEvenOdd(); + inner_contour_ = inner_contour_.processEvenOdd(); } const Polygons& WallToolPaths::getInnerContour() { - if (! toolpaths_generated && inset_count > 0) + if (! toolpaths_generated_ && inset_count_ > 0) { generate(); } - else if (inset_count == 0) + else if (inset_count_ == 0) { - return outline; + return outline_; } - return inner_contour; + return inner_contour_; } bool WallToolPaths::removeEmptyToolPaths(std::vector& toolpaths) diff --git a/src/WallsComputation.cpp b/src/WallsComputation.cpp index f0415ce0d1..594d439e1b 100644 --- a/src/WallsComputation.cpp +++ b/src/WallsComputation.cpp @@ -15,8 +15,8 @@ namespace cura { WallsComputation::WallsComputation(const Settings& settings, const LayerIndex layer_nr) - : settings(settings) - , layer_nr(layer_nr) + : settings_(settings) + , layer_nr_(layer_nr) { } @@ -28,7 +28,7 @@ WallsComputation::WallsComputation(const Settings& settings, const LayerIndex la */ void WallsComputation::generateWalls(SliceLayerPart* part, SectionType section_type) { - size_t wall_count = settings.get("wall_line_count"); + size_t wall_count = settings_.get("wall_line_count"); if (wall_count == 0) // Early out if no walls are to be generated { part->print_outline = part->outline; @@ -36,46 +36,46 @@ void WallsComputation::generateWalls(SliceLayerPart* part, SectionType section_t return; } - const bool spiralize = settings.get("magic_spiralize"); - const size_t alternate = ((layer_nr % 2) + 2) % 2; - if (spiralize && layer_nr < LayerIndex(settings.get("initial_bottom_layers")) + const bool spiralize = settings_.get("magic_spiralize"); + const size_t alternate = ((layer_nr_ % 2) + 2) % 2; + if (spiralize && layer_nr_ < LayerIndex(settings_.get("initial_bottom_layers")) && alternate == 1) // Add extra insets every 2 layers when spiralizing. This makes bottoms of cups watertight. { wall_count += 5; } - if (settings.get("alternate_extra_perimeter")) + if (settings_.get("alternate_extra_perimeter")) { wall_count += alternate; } - const bool first_layer = layer_nr == 0; - const Ratio line_width_0_factor = first_layer ? settings.get("wall_0_extruder_nr").settings_.get("initial_layer_line_width_factor") : 1.0_r; - const coord_t line_width_0 = settings.get("wall_line_width_0") * line_width_0_factor; - const coord_t wall_0_inset = settings.get("wall_0_inset"); + const bool first_layer = layer_nr_ == 0; + const Ratio line_width_0_factor = first_layer ? settings_.get("wall_0_extruder_nr").settings_.get("initial_layer_line_width_factor") : 1.0_r; + const coord_t line_width_0 = settings_.get("wall_line_width_0") * line_width_0_factor; + const coord_t wall_0_inset = settings_.get("wall_0_inset"); - const Ratio line_width_x_factor = first_layer ? settings.get("wall_x_extruder_nr").settings_.get("initial_layer_line_width_factor") : 1.0_r; - const coord_t line_width_x = settings.get("wall_line_width_x") * line_width_x_factor; + const Ratio line_width_x_factor = first_layer ? settings_.get("wall_x_extruder_nr").settings_.get("initial_layer_line_width_factor") : 1.0_r; + const coord_t line_width_x = settings_.get("wall_line_width_x") * line_width_x_factor; // When spiralizing, generate the spiral insets using simple offsets instead of generating toolpaths if (spiralize) { - const bool recompute_outline_based_on_outer_wall = settings.get("support_enable") && ! settings.get("fill_outline_gaps"); + const bool recompute_outline_based_on_outer_wall = settings_.get("support_enable") && ! settings_.get("fill_outline_gaps"); generateSpiralInsets(part, line_width_0, wall_0_inset, recompute_outline_based_on_outer_wall); - if (layer_nr <= static_cast(settings.get("initial_bottom_layers"))) + if (layer_nr_ <= static_cast(settings_.get("initial_bottom_layers"))) { - WallToolPaths wall_tool_paths(part->outline, line_width_0, line_width_x, wall_count, wall_0_inset, settings, layer_nr, section_type); + WallToolPaths wall_tool_paths(part->outline, line_width_0, line_width_x, wall_count, wall_0_inset, settings_, layer_nr_, section_type); part->wall_toolpaths = wall_tool_paths.getToolPaths(); part->inner_area = wall_tool_paths.getInnerContour(); } } else { - WallToolPaths wall_tool_paths(part->outline, line_width_0, line_width_x, wall_count, wall_0_inset, settings, layer_nr, section_type); + WallToolPaths wall_tool_paths(part->outline, line_width_0, line_width_x, wall_count, wall_0_inset, settings_, layer_nr_, section_type); part->wall_toolpaths = wall_tool_paths.getToolPaths(); part->inner_area = wall_tool_paths.getInnerContour(); } - part->outline = PolygonsPart{ Simplify(settings).polygon(part->outline) }; + part->outline = PolygonsPart{ Simplify(settings_).polygon(part->outline) }; part->print_outline = part->outline; } @@ -94,7 +94,7 @@ void WallsComputation::generateWalls(SliceLayer* layer, SectionType section) // Remove the parts which did not generate a wall. As these parts are too small to print, // and later code can now assume that there is always minimal 1 wall line. - if (settings.get("wall_line_count") >= 1 && ! settings.get("fill_outline_gaps")) + if (settings_.get("wall_line_count") >= 1 && ! settings_.get("fill_outline_gaps")) { for (size_t part_idx = 0; part_idx < layer->parts.size(); part_idx++) { @@ -116,7 +116,7 @@ void WallsComputation::generateSpiralInsets(SliceLayerPart* part, coord_t line_w part->spiral_wall = part->outline.offset(-line_width_0 / 2 - wall_0_inset); // Optimize the wall. This prevents buffer underruns in the printer firmware, and reduces processing time in CuraEngine. - const ExtruderTrain& train_wall = settings.get("wall_0_extruder_nr"); + const ExtruderTrain& train_wall = settings_.get("wall_0_extruder_nr"); part->spiral_wall = Simplify(train_wall.settings_).polygon(part->spiral_wall); part->spiral_wall.removeDegenerateVerts(); if (recompute_outline_based_on_outer_wall) diff --git a/src/infill/LightningDistanceField.cpp b/src/infill/LightningDistanceField.cpp index 698e31b365..d0d0b5f2a3 100644 --- a/src/infill/LightningDistanceField.cpp +++ b/src/infill/LightningDistanceField.cpp @@ -15,44 +15,44 @@ LightningDistanceField::LightningDistanceField const Polygons& current_outline, const Polygons& current_overhang ) -: cell_size(radius / radius_per_cell_size) -, grid(cell_size) -, supporting_radius(radius) -, current_outline(current_outline) -, current_overhang(current_overhang) +: cell_size_(radius / radius_per_cell_size) +, grid_(cell_size_) +, supporting_radius_(radius) +, current_outline_(current_outline) +, current_overhang_(current_overhang) { - std::vector regular_dots = PolygonUtils::spreadDotsArea(current_overhang, cell_size); + std::vector regular_dots = PolygonUtils::spreadDotsArea(current_overhang, cell_size_); for (const auto& p : regular_dots) { const ClosestPolygonPoint cpp = PolygonUtils::findClosest(p, current_outline); const coord_t dist_to_boundary = vSize(p - cpp.p()); - unsupported_points.emplace_back(p, dist_to_boundary); + unsupported_points_.emplace_back(p, dist_to_boundary); } - unsupported_points.sort + unsupported_points_.sort ( [&radius](const UnsupCell& a, const UnsupCell& b) { constexpr coord_t prime_for_hash = 191; return - std::abs(b.dist_to_boundary - a.dist_to_boundary) > radius ? - a.dist_to_boundary < b.dist_to_boundary : - (std::hash{}(a.loc) % prime_for_hash) < (std::hash{}(b.loc) % prime_for_hash); + std::abs(b.dist_to_boundary_ - a.dist_to_boundary_) > radius ? + a.dist_to_boundary_ < b.dist_to_boundary_ : + (std::hash{}(a.loc_) % prime_for_hash) < (std::hash{}(b.loc_) % prime_for_hash); } ); - for (auto it = unsupported_points.begin(); it != unsupported_points.end(); ++it) + for (auto it = unsupported_points_.begin(); it != unsupported_points_.end(); ++it) { UnsupCell& cell = *it; - unsupported_points_grid.emplace(grid.toGridPoint(cell.loc), it); + unsupported_points_grid_.emplace(grid_.toGridPoint(cell.loc_), it); } } bool LightningDistanceField::tryGetNextPoint(Point* p) const { - if (unsupported_points.empty()) + if (unsupported_points_.empty()) { return false; } - *p = unsupported_points.front().loc; + *p = unsupported_points_.front().loc_; return true; } @@ -61,15 +61,15 @@ void LightningDistanceField::update(const Point& to_node, const Point& added_lea auto process_func = [added_leaf, this](const SquareGrid::GridPoint& grid_loc) { - auto it = unsupported_points_grid.find(grid_loc); - if (it != unsupported_points_grid.end()) + auto it = unsupported_points_grid_.find(grid_loc); + if (it != unsupported_points_grid_.end()) { std::list::iterator& list_it = it->second; UnsupCell& cell = *list_it; - if (shorterThen(cell.loc - added_leaf, supporting_radius)) + if (shorterThen(cell.loc_ - added_leaf, supporting_radius_)) { - unsupported_points.erase(list_it); - unsupported_points_grid.erase(it); + unsupported_points_.erase(list_it); + unsupported_points_grid_.erase(it); } } return true; @@ -78,16 +78,16 @@ void LightningDistanceField::update(const Point& to_node, const Point& added_lea const Point b = added_leaf; Point ab = b - a; Point ab_T = turn90CCW(ab); - Point extent = normal(ab_T, supporting_radius); + Point extent = normal(ab_T, supporting_radius_); // TODO: process cells only once; make use of PolygonUtils::spreadDotsArea - grid.processLineCells(std::make_pair(a + extent, a - extent), + grid_.processLineCells(std::make_pair(a + extent, a - extent), [this, ab, extent, &process_func] (const SquareGrid::GridPoint& p) { - grid.processLineCells(std::make_pair(p, p + ab), process_func); + grid_.processLineCells(std::make_pair(p, p + ab), process_func); return true; } ); - grid.processNearby(added_leaf, supporting_radius, process_func); + grid_.processNearby(added_leaf, supporting_radius_, process_func); } } \ No newline at end of file diff --git a/src/support.cpp b/src/support.cpp index 4fcc69630e..810d78cd9c 100644 --- a/src/support.cpp +++ b/src/support.cpp @@ -237,10 +237,10 @@ void AreaSupport::generateGradualSupport(SliceDataStorage& storage) Polygons less_dense_support = infill_area; // one step less dense with each density_step for (unsigned int density_step = 0; density_step < max_density_steps; ++density_step) { - LayerIndex min_layer{ layer_nr + density_step * gradual_support_step_layer_count + static_cast(layer_skip_count) }; - LayerIndex max_layer{ layer_nr + (density_step + 1) * gradual_support_step_layer_count }; + LayerIndex actual_min_layer{ layer_nr + density_step * gradual_support_step_layer_count + static_cast(layer_skip_count) }; + LayerIndex actual_max_layer{ layer_nr + (density_step + 1) * gradual_support_step_layer_count }; - for (double upper_layer_idx = min_layer; upper_layer_idx <= max_layer; upper_layer_idx += layer_skip_count) + for (double upper_layer_idx = actual_min_layer; upper_layer_idx <= actual_max_layer; upper_layer_idx += layer_skip_count) { if (static_cast(upper_layer_idx) >= total_layer_count) { @@ -573,8 +573,6 @@ Polygons AreaSupport::join(const SliceDataStorage& storage, const Polygons& supp // first offset the layer a little inwards; this way tiny area's will not be joined // (narrow areas; ergo small areas will be removed in a later step using this same offset) // this inwards offset is later reversed by increasing the outwards offset - const coord_t join_distance = infill_settings.get("support_join_distance"); - const coord_t support_line_width = infill_settings.get("support_line_width"); const coord_t min_even_wall_line_width = infill_settings.get("min_even_wall_line_width"); auto half_min_feature_width = min_even_wall_line_width + 10; @@ -1360,9 +1358,10 @@ void AreaSupport::generateSupportAreasForMesh( max_checking_layer_idx, [&](const size_t layer_idx) { - constexpr bool no_support = false; - constexpr bool no_prime_tower = false; - support_areas[layer_idx] = support_areas[layer_idx].difference(storage.getLayerOutlines(layer_idx + layer_z_distance_top - 1, no_support, no_prime_tower)); + constexpr bool no_support_here = false; + constexpr bool no_prime_tower_here = false; + support_areas[layer_idx] + = support_areas[layer_idx].difference(storage.getLayerOutlines(layer_idx + layer_z_distance_top - 1, no_support_here, no_prime_tower_here)); }); } @@ -1700,7 +1699,6 @@ void AreaSupport::handleWallStruts(const Settings& settings, Polygons& supportLa PolygonRef poly = supportLayer_this[p]; if (poly.size() < 6) // might be a single wall { - PolygonRef poly = supportLayer_this[p]; int best = -1; int best_length2 = -1; for (unsigned int i = 0; i < poly.size(); i++) diff --git a/tests/LayerPlanTest.cpp b/tests/LayerPlanTest.cpp index 0cfecdec15..f04a22e605 100644 --- a/tests/LayerPlanTest.cpp +++ b/tests/LayerPlanTest.cpp @@ -357,40 +357,40 @@ class AddTravelTest : public LayerPlanTest, public testing::WithParamInterface>> sections; sections.emplace_back(); - coord_t last_path_mono_projection = projectPathAlongAxis(object_under_test.paths.front(), monotonic_axis); - for (const auto& path : object_under_test.paths) + coord_t last_path_mono_projection = projectPathAlongAxis(object_under_test.paths_.front(), monotonic_axis); + for (const auto& path : object_under_test.paths_) { const coord_t path_mono_projection{ projectPathAlongAxis(path, monotonic_axis) }; if (path_mono_projection < last_path_mono_projection && ! sections.back().empty()) From c56e75561084a667de40ea6a263dc775eacc06a2 Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Wed, 22 Nov 2023 09:32:24 +0100 Subject: [PATCH 26/48] Fixed last variable shadowing warnings --- CMakeLists.txt | 3 +- include/PathOrderOptimizer.h | 14 +- include/TreeSupportUtils.h | 6 +- include/communication/CommandLine.h | 4 +- include/infill/LightningTreeNode.h | 12 +- include/infill/SierpinskiFill.h | 18 +- include/infill/SubDivCube.h | 16 +- include/pathPlanning/Comb.h | 64 +++--- include/settings/AdaptiveLayerHeights.h | 26 +-- include/settings/ZSeamConfig.h | 10 +- include/utils/AABB.h | 2 +- include/utils/AABB3D.h | 4 +- include/utils/Date.h | 12 +- include/utils/ExtrusionJunction.h | 10 +- include/utils/ExtrusionLine.h | 129 ++++++------ include/utils/ListPolyIt.h | 100 ++++++---- include/utils/ProximityPointLink.h | 61 ------ include/utils/Simplify.h | 119 ++++++------ include/utils/SparseGrid.h | 16 +- include/utils/SparseLineGrid.h | 14 +- include/utils/SparsePointGrid.h | 2 +- include/utils/VoxelUtils.h | 7 +- src/FffGcodeWriter.cpp | 8 +- src/FffPolygonGenerator.cpp | 40 ++-- src/InsetOrderOptimizer.cpp | 40 ++-- src/LayerPlan.cpp | 46 ++--- src/SkeletalTrapezoidation.cpp | 40 ++-- src/TopSurface.cpp | 2 +- src/TreeSupportTipGenerator.cpp | 13 +- src/WallToolPaths.cpp | 100 +++++----- src/bridge.cpp | 2 +- src/communication/CommandLine.cpp | 38 ++-- src/gcodeExport.cpp | 30 +-- src/infill.cpp | 40 ++-- src/infill/GyroidInfill.cpp | 8 +- src/infill/ImageBasedDensityProvider.cpp | 8 +- src/infill/LightningTreeNode.cpp | 162 +++++++-------- src/infill/SierpinskiFill.cpp | 110 +++++------ src/infill/SierpinskiFillProvider.cpp | 2 +- src/infill/SubDivCube.cpp | 59 +++--- src/mesh.cpp | 8 +- src/pathPlanning/Comb.cpp | 238 +++++++++++------------ src/settings/AdaptiveLayerHeights.cpp | 70 +++---- src/settings/ZSeamConfig.cpp | 10 +- src/sliceDataStorage.cpp | 8 +- src/slicer.cpp | 4 +- src/support.cpp | 8 +- src/utils/AABB.cpp | 90 ++++----- src/utils/AABB3D.cpp | 62 +++--- src/utils/Date.cpp | 26 +-- src/utils/ExtrusionJunction.cpp | 12 +- src/utils/ExtrusionLine.cpp | 45 +++-- src/utils/ExtrusionSegment.cpp | 30 +-- src/utils/ListPolyIt.cpp | 4 +- src/utils/PolygonConnector.cpp | 6 +- src/utils/PolylineStitcher.cpp | 6 +- src/utils/ProximityPointLink.cpp | 28 --- src/utils/SVG.cpp | 50 ++--- src/utils/Simplify.cpp | 30 +-- src/utils/ToolpathVisualizer.cpp | 36 ++-- src/utils/VoxelUtils.cpp | 14 +- src/utils/channel.cpp | 14 +- src/utils/polygonUtils.cpp | 28 +-- tests/integration/SlicePhaseTest.cpp | 4 +- tests/utils/AABB3DTest.cpp | 4 +- tests/utils/AABBTest.cpp | 6 +- 66 files changed, 1091 insertions(+), 1147 deletions(-) delete mode 100644 include/utils/ProximityPointLink.h delete mode 100644 src/utils/ProximityPointLink.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 27fcdf5bd8..3189c3c8ce 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -142,7 +142,6 @@ set(engine_SRCS # Except main.cpp. src/utils/polygonUtils.cpp src/utils/polygon.cpp src/utils/PolylineStitcher.cpp - src/utils/ProximityPointLink.cpp src/utils/Simplify.cpp src/utils/SVG.cpp src/utils/socket.cpp @@ -278,4 +277,4 @@ endif () if (ENABLE_BENCHMARKS) add_subdirectory(benchmark) -endif () \ No newline at end of file +endif () diff --git a/include/PathOrderOptimizer.h b/include/PathOrderOptimizer.h index 8a46854aed..71c6e92891 100644 --- a/include/PathOrderOptimizer.h +++ b/include/PathOrderOptimizer.h @@ -199,7 +199,7 @@ class PathOrderOptimizer // For some Z seam types the start position can be pre-computed. // This is faster since we don't need to re-compute the start position at each step then. - precompute_start &= seam_config_.type == EZSeamType::RANDOM || seam_config_.type == EZSeamType::USER_SPECIFIED || seam_config_.type == EZSeamType::SHARPEST_CORNER; + precompute_start &= seam_config_.type_ == EZSeamType::RANDOM || seam_config_.type_ == EZSeamType::USER_SPECIFIED || seam_config_.type_ == EZSeamType::SHARPEST_CORNER; if (precompute_start) { for (auto& path : paths_) @@ -208,7 +208,7 @@ class PathOrderOptimizer { continue; // Can't pre-compute the seam for open polylines since they're at the endpoint nearest to the current position. } - path.start_vertex_ = findStartLocation(path, seam_config_.pos); + path.start_vertex_ = findStartLocation(path, seam_config_.pos_); } } @@ -566,7 +566,7 @@ class PathOrderOptimizer } const bool precompute_start - = seam_config_.type == EZSeamType::RANDOM || seam_config_.type == EZSeamType::USER_SPECIFIED || seam_config_.type == EZSeamType::SHARPEST_CORNER; + = seam_config_.type_ == EZSeamType::RANDOM || seam_config_.type_ == EZSeamType::USER_SPECIFIED || seam_config_.type_ == EZSeamType::SHARPEST_CORNER; if (! path->is_closed_ || ! precompute_start) // Find the start location unless we've already precomputed it. { path->start_vertex_ = findStartLocation(*path, start_position); @@ -629,7 +629,7 @@ class PathOrderOptimizer // Rest of the function only deals with (closed) polygons. We need to be able to find the seam location of those polygons. - if (seam_config_.type == EZSeamType::RANDOM) + if (seam_config_.type_ == EZSeamType::RANDOM) { size_t vert = getRandomPointInPolygon(*path.converted_); return vert; @@ -653,7 +653,7 @@ class PathOrderOptimizer // For most seam types, the shortest distance matters. Not for SHARPEST_CORNER though. // For SHARPEST_CORNER, use a fixed starting score of 0. const coord_t distance = (combing_boundary_ == nullptr) ? getDirectDistance(here, target_pos) : getCombingDistance(here, target_pos); - const double score_distance = (seam_config_.type == EZSeamType::SHARPEST_CORNER && seam_config_.corner_pref != EZSeamCornerPrefType::Z_SEAM_CORNER_PREF_NONE) + const double score_distance = (seam_config_.type_ == EZSeamType::SHARPEST_CORNER && seam_config_.corner_pref_ != EZSeamCornerPrefType::Z_SEAM_CORNER_PREF_NONE) ? MM2INT(10) : vSize2(here - target_pos); @@ -662,7 +662,7 @@ class PathOrderOptimizer // angles > 0 are convex (right turning) double corner_shift; - if (seam_config_.type == EZSeamType::SHORTEST) + if (seam_config_.type_ == EZSeamType::SHORTEST) { // the more a corner satisfies our criteria, the closer it appears to be // shift 10mm for a very acute corner @@ -678,7 +678,7 @@ class PathOrderOptimizer } double score = score_distance; - switch (seam_config_.corner_pref) + switch (seam_config_.corner_pref_) { default: case EZSeamCornerPrefType::Z_SEAM_CORNER_PREF_INNER: diff --git a/include/TreeSupportUtils.h b/include/TreeSupportUtils.h index fd6ab60526..7782fef79e 100644 --- a/include/TreeSupportUtils.h +++ b/include/TreeSupportUtils.h @@ -68,12 +68,12 @@ class TreeSupportUtils Polygon result_line; for (ExtrusionJunction junction : line) { - result_line.add(junction.p); + result_line.add(junction.p_); } - if (line.is_closed) + if (line.is_closed_) { - result_line.add(line[0].p); + result_line.add(line[0].p_); } result.add(result_line); diff --git a/include/communication/CommandLine.h b/include/communication/CommandLine.h index fbae3e3010..6190a30df4 100644 --- a/include/communication/CommandLine.h +++ b/include/communication/CommandLine.h @@ -154,12 +154,12 @@ class CommandLine : public Communication /* * \brief The command line arguments that the application was called with. */ - std::vector arguments; + std::vector arguments_; /* * The last progress update that we output to stdcerr. */ - unsigned int last_shown_progress; + unsigned int last_shown_progress_; /* * \brief Get the default search directories to search for definition files. diff --git a/include/infill/LightningTreeNode.h b/include/infill/LightningTreeNode.h index 21c63bde3b..e4b4fec264 100644 --- a/include/infill/LightningTreeNode.h +++ b/include/infill/LightningTreeNode.h @@ -149,7 +149,7 @@ class LightningTreeNode : public std::enable_shared_from_this */ bool isRoot() const { - return is_root; + return is_root_; } /*! @@ -262,12 +262,12 @@ class LightningTreeNode : public std::enable_shared_from_this void removeJunctionOverlap(Polygons& polylines, const coord_t line_width) const; - bool is_root; - Point p; - std::weak_ptr parent; - std::vector children; + bool is_root_; + Point p_; + std::weak_ptr parent_; + std::vector children_; - std::optional last_grounding_location; // last_grounding_location_; // sequence; + std::list sequence_; /*! diff --git a/include/infill/SubDivCube.h b/include/infill/SubDivCube.h index d2c7d60f16..26fdb2d6da 100644 --- a/include/infill/SubDivCube.h +++ b/include/infill/SubDivCube.h @@ -94,14 +94,14 @@ class SubDivCube */ void addLineAndCombine(Polygons& group, Point from, Point to); - size_t depth; //!< the recursion depth of the cube (0 is most recursed) - Point3 center; //!< center location of the cube in absolute coordinates - std::array, 8> children; //!< pointers to this cube's eight octree children - static std::vector cube_properties_per_recursion_step; //!< precomputed array of basic properties of cubes based on recursion depth. - static Ratio radius_multiplier; //!< multiplier for the bounding radius when determining if a cube should be subdivided - static Point3Matrix rotation_matrix; //!< The rotation matrix to get from axis aligned cubes to cubes standing on a corner point aligned with the infill_angle - static PointMatrix infill_rotation_matrix; //!< Horizontal rotation applied to infill - static coord_t radius_addition; //!< addition to the bounding radius when determining if a cube should be subdivided + size_t depth_; //!< the recursion depth of the cube (0 is most recursed) + Point3 center_; //!< center location of the cube in absolute coordinates + std::array, 8> children_; //!< pointers to this cube's eight octree children + static std::vector cube_properties_per_recursion_step_; //!< precomputed array of basic properties of cubes based on recursion depth. + static Ratio radius_multiplier_; //!< multiplier for the bounding radius when determining if a cube should be subdivided + static Point3Matrix rotation_matrix_; //!< The rotation matrix to get from axis aligned cubes to cubes standing on a corner point aligned with the infill_angle + static PointMatrix infill_rotation_matrix_; //!< Horizontal rotation applied to infill + static coord_t radius_addition_; //!< addition to the bounding radius when determining if a cube should be subdivided }; } // namespace cura diff --git a/include/pathPlanning/Comb.h b/include/pathPlanning/Comb.h index aff135d416..93bff84b30 100644 --- a/include/pathPlanning/Comb.h +++ b/include/pathPlanning/Comb.h @@ -52,13 +52,13 @@ class Comb class Crossing { public: - bool dest_is_inside; //!< Whether the startPoint or endPoint is inside the inside boundary - Point in_or_mid; //!< The point on the inside boundary, or in between the inside and outside boundary if the start/end point isn't inside the inside boudary - Point out; //!< The point on the outside boundary - PolygonsPart dest_part; //!< The assembled inside-boundary PolygonsPart in which the dest_point lies. (will only be initialized when Crossing::dest_is_inside holds) - std::optional dest_crossing_poly; //!< The polygon of the part in which dest_point lies, which will be crossed (often will be the outside polygon) - const Polygons& boundary_inside; //!< The inside boundary as in \ref Comb::boundary_inside - const LocToLineGrid& inside_loc_to_line; //!< The loc to line grid \ref Comb::inside_loc_to_line + bool dest_is_inside_; //!< Whether the startPoint or endPoint is inside the inside boundary + Point in_or_mid_; //!< The point on the inside boundary, or in between the inside and outside boundary if the start/end point isn't inside the inside boudary + Point out_; //!< The point on the outside boundary + PolygonsPart dest_part_; //!< The assembled inside-boundary PolygonsPart in which the dest_point lies. (will only be initialized when Crossing::dest_is_inside holds) + std::optional dest_crossing_poly_; //!< The polygon of the part in which dest_point lies, which will be crossed (often will be the outside polygon) + const Polygons& boundary_inside_; //!< The inside boundary as in \ref Comb::boundary_inside + const LocToLineGrid& inside_loc_to_line_; //!< The loc to line grid \ref Comb::inside_loc_to_line /*! * Simple constructor @@ -94,8 +94,8 @@ class Comb bool findOutside(const ExtruderTrain& train, const Polygons& outside, const Point close_to, const bool fail_on_unavoidable_obstacles, Comb& comber); private: - const Point dest_point; //!< Either the eventual startPoint or the eventual endPoint of this combing move - unsigned int dest_part_idx; //!< The index into Comb:partsView_inside of the part in which the \p dest_point is. + const Point dest_point_; //!< Either the eventual startPoint or the eventual endPoint of this combing move + unsigned int dest_part_idx_; //!< The index into Comb:partsView_inside of the part in which the \p dest_point is. /*! * Find the best crossing from some inside polygon to the outside boundary. @@ -113,29 +113,29 @@ class Comb }; - const SliceDataStorage& storage; //!< The storage from which to compute the outside boundary, when needed. - const LayerIndex layer_nr; //!< The layer number for the layer for which to compute the outside boundary, when needed. - - const coord_t travel_avoid_distance; //!< - const coord_t offset_from_outlines; //!< Offset from the boundary of a part to the comb path. (nozzle width / 2) - const coord_t max_moveInside_distance2; //!< Maximal distance of a point to the Comb::boundary_inside which is still to be considered inside. (very sharp corners not allowed :S) - const coord_t offset_from_inside_to_outside; //!< The sum of the offsets for the inside and outside boundary Comb::offset_from_outlines and Comb::offset_from_outlines_outside - const coord_t max_crossing_dist2; //!< The maximal distance by which to cross the in_between area between inside and outside - static const coord_t max_moveOutside_distance2 = std::numeric_limits::max(); //!< Any point which is not inside should be considered outside. - static constexpr coord_t offset_dist_to_get_from_on_the_polygon_to_outside = 40; //!< in order to prevent on-boundary vs crossing boundary confusions (precision thing) - static constexpr coord_t offset_extra_start_end = 100; //!< Distance to move start point and end point toward eachother to extra avoid collision with the boundaries. - - Polygons boundary_inside_minimum; //!< The boundary within which to comb. (Will be reordered by the partsView_inside_minimum) - Polygons boundary_inside_optimal; //!< The boundary within which to comb. (Will be reordered by the partsView_inside_optimal) - const PartsView partsView_inside_minimum; //!< Structured indices onto boundary_inside_minimum which shows which polygons belong to which part. - const PartsView partsView_inside_optimal; //!< Structured indices onto boundary_inside_optimal which shows which polygons belong to which part. - std::unique_ptr inside_loc_to_line_minimum; //!< The SparsePointGridInclusive mapping locations to line segments of the inner boundary. - std::unique_ptr inside_loc_to_line_optimal; //!< The SparsePointGridInclusive mapping locations to line segments of the inner boundary. - std::unordered_map boundary_outside; //!< The boundary outside of which to stay to avoid collision with other layer parts. This is a pointer cause we only compute it when we move outside the boundary (so not when there is only a single part in the layer) - std::unordered_map model_boundary; //!< The boundary of the model itself - std::unordered_map> outside_loc_to_line; //!< The SparsePointGridInclusive mapping locations to line segments of the outside boundary. - std::unordered_map> model_boundary_loc_to_line; //!< The SparsePointGridInclusive mapping locations to line segments of the model boundary - coord_t move_inside_distance; //!< When using comb_boundary_inside_minimum for combing it tries to move points inside by this amount after calculating the path to move it from the border a bit. + const SliceDataStorage& storage_; //!< The storage from which to compute the outside boundary, when needed. + const LayerIndex layer_nr_; //!< The layer number for the layer for which to compute the outside boundary, when needed. + + const coord_t travel_avoid_distance_; //!< + const coord_t offset_from_outlines_; //!< Offset from the boundary of a part to the comb path. (nozzle width / 2) + const coord_t max_moveInside_distance2_; //!< Maximal distance of a point to the Comb::boundary_inside which is still to be considered inside. (very sharp corners not allowed :S) + const coord_t offset_from_inside_to_outside_; //!< The sum of the offsets for the inside and outside boundary Comb::offset_from_outlines and Comb::offset_from_outlines_outside + const coord_t max_crossing_dist2_; //!< The maximal distance by which to cross the in_between area between inside and outside + static const coord_t max_moveOutside_distance2_ = std::numeric_limits::max(); //!< Any point which is not inside should be considered outside. + static constexpr coord_t offset_dist_to_get_from_on_the_polygon_to_outside_ = 40; //!< in order to prevent on-boundary vs crossing boundary confusions (precision thing) + static constexpr coord_t offset_extra_start_end_ = 100; //!< Distance to move start point and end point toward eachother to extra avoid collision with the boundaries. + + Polygons boundary_inside_minimum_; //!< The boundary within which to comb. (Will be reordered by the partsView_inside_minimum) + Polygons boundary_inside_optimal_; //!< The boundary within which to comb. (Will be reordered by the partsView_inside_optimal) + const PartsView parts_view_inside_minimum_; //!< Structured indices onto boundary_inside_minimum which shows which polygons belong to which part. + const PartsView parts_view_inside_optimal_; //!< Structured indices onto boundary_inside_optimal which shows which polygons belong to which part. + std::unique_ptr inside_loc_to_line_minimum_; //!< The SparsePointGridInclusive mapping locations to line segments of the inner boundary. + std::unique_ptr inside_loc_to_line_optimal_; //!< The SparsePointGridInclusive mapping locations to line segments of the inner boundary. + std::unordered_map boundary_outside_; //!< The boundary outside of which to stay to avoid collision with other layer parts. This is a pointer cause we only compute it when we move outside the boundary (so not when there is only a single part in the layer) + std::unordered_map model_boundary_; //!< The boundary of the model itself + std::unordered_map> outside_loc_to_line_; //!< The SparsePointGridInclusive mapping locations to line segments of the outside boundary. + std::unordered_map> model_boundary_loc_to_line_; //!< The SparsePointGridInclusive mapping locations to line segments of the model boundary + coord_t move_inside_distance_; //!< When using comb_boundary_inside_minimum for combing it tries to move points inside by this amount after calculating the path to move it from the border a bit. /*! * Get the SparsePointGridInclusive mapping locations to line segments of the outside boundary. Calculate it when it hasn't been calculated yet. diff --git a/include/settings/AdaptiveLayerHeights.h b/include/settings/AdaptiveLayerHeights.h index 218d2ba58e..94ff6845d5 100644 --- a/include/settings/AdaptiveLayerHeights.h +++ b/include/settings/AdaptiveLayerHeights.h @@ -16,17 +16,17 @@ class AdaptiveLayer /*! * Height of the layer in microns. */ - coord_t layer_height; + coord_t layer_height_; /*! * The absolute z position of the layer. */ - coord_t z_position; + coord_t z_position_; /*! * Temperature to use for this layer. */ - int temperature; + int temperature_; explicit AdaptiveLayer(const coord_t layer_height); }; @@ -65,41 +65,41 @@ class AdaptiveLayerHeights /*! * Stores the found layer heights */ - std::vector layers; + std::vector layers_; /*! * Stores the allowed layer heights in microns. */ - std::vector allowed_layer_heights; + std::vector allowed_layer_heights_; /** * The base layer height. */ - coord_t base_layer_height; + coord_t base_layer_height_; /** * The maximum deviation from the base layer height. */ - coord_t max_variation; + coord_t max_variation_; /** * The layer height change per step to try between min and max deviation from the base layer height. */ - coord_t step_size; + coord_t step_size_; /*! * Target topography size. Adaptive layers will try to keep the horizontal * distance the same. */ - coord_t threshold; + coord_t threshold_; /*! * Stores the found slopes of each face using the same index. */ - std::vector face_slopes; - std::vector face_min_z_values; - std::vector face_max_z_values; - const MeshGroup* meshgroup; + std::vector face_slopes_; + std::vector face_min_z_values_; + std::vector face_max_z_values_; + const MeshGroup* meshgroup_; /*! * Calculate the allowed layer heights depending on variation and step input diff --git a/include/settings/ZSeamConfig.h b/include/settings/ZSeamConfig.h index 7d301e6f00..c82090de5c 100644 --- a/include/settings/ZSeamConfig.h +++ b/include/settings/ZSeamConfig.h @@ -22,25 +22,25 @@ struct ZSeamConfig * Strategy to place the seam (user-specified, shortest distance, sharpest * corner, etc.). */ - EZSeamType type; + EZSeamType type_; /*! * When using a user-specified position for the seam, this is the position * that the user specified. */ - Point pos; + Point pos_; /*! * Corner preference type, if using the sharpest corner strategy. */ - EZSeamCornerPrefType corner_pref; + EZSeamCornerPrefType corner_pref_; /*! * Prevent 'smoothed out' corners (corners that are spread over multiple, very close together vertices), * by simplifying the polygon that the corners are detected on by this ammount. * This does _not_ influence the path, the simplified polygon is a temporary constructed within the algorithm. */ - coord_t simplify_curvature; + coord_t simplify_curvature_; /*! * Create a seam configuration with a custom configuration. @@ -60,4 +60,4 @@ struct ZSeamConfig } //Cura namespace. -#endif //ZSEAMCONFIG_H \ No newline at end of file +#endif //ZSEAMCONFIG_H diff --git a/include/utils/AABB.h b/include/utils/AABB.h index 160e5ac217..eded125621 100644 --- a/include/utils/AABB.h +++ b/include/utils/AABB.h @@ -17,7 +17,7 @@ class Polygons; class AABB { public: - Point min, max; + Point min_, max_; AABB(); //!< initializes with invalid min and max AABB(const Point& min, const Point& max); //!< initializes with given min and max diff --git a/include/utils/AABB3D.h b/include/utils/AABB3D.h index c7fca9c486..68911b2f87 100644 --- a/include/utils/AABB3D.h +++ b/include/utils/AABB3D.h @@ -15,8 +15,8 @@ An Axis Aligned Bounding Box. Has a min and max vector, representing minimal and */ struct AABB3D { - Point3 min; //!< The minimal coordinates in x, y and z direction - Point3 max; //!< The maximal coordinates in x, y and z direction + Point3 min_; //!< The minimal coordinates in x, y and z direction + Point3 max_; //!< The maximal coordinates in x, y and z direction /*! * Create an AABB3D with coordinates at the numeric limits. diff --git a/include/utils/Date.h b/include/utils/Date.h index a89ba2df3d..7d0e44e6a0 100644 --- a/include/utils/Date.h +++ b/include/utils/Date.h @@ -1,5 +1,5 @@ -//Copyright (c) 2020 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2020 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef UTILS_DATE_H #define UTILS_DATE_H @@ -18,10 +18,12 @@ class Date Date(int year, int month, int day); //!< Simple constructor static Date getDate(); //!< Get the current date (compile time) std::string toStringDashed(); //!< Get a formatted string: yyyy-mm-dd + protected: - int year; //!< Year, e.g. 2016 - int month; //!< Month, e.g. 12, i.e. starting at 1 - int day; //!< Day, e.g. 31, i.e. starting at 1 + int year_; //!< Year, e.g. 2016 + int month_; //!< Month, e.g. 12, i.e. starting at 1 + int day_; //!< Day, e.g. 31, i.e. starting at 1 + private: Date(); //!< Simple constructor initializing all to -1 }; diff --git a/include/utils/ExtrusionJunction.h b/include/utils/ExtrusionJunction.h index 2fc40e64c0..ce38e1900b 100644 --- a/include/utils/ExtrusionJunction.h +++ b/include/utils/ExtrusionJunction.h @@ -22,12 +22,12 @@ struct ExtrusionJunction * The position of the centreline of the path when it reaches this junction. * This is the position that should end up in the g-code eventually. */ - Point p; + Point p_; /*! * The width of the extruded path at this junction. */ - coord_t w; + coord_t w_; /*! * Which perimeter this junction is part of. @@ -35,7 +35,7 @@ struct ExtrusionJunction * Perimeters are counted from the outside inwards. The outer wall has index * 0. */ - size_t perimeter_index; + size_t perimeter_index_; ExtrusionJunction(const Point p, const coord_t w, const coord_t perimeter_index); @@ -44,13 +44,13 @@ struct ExtrusionJunction inline Point operator-(const ExtrusionJunction& a, const ExtrusionJunction& b) { - return a.p - b.p; + return a.p_ - b.p_; } // Identity function, used to be able to make templated algorithms that do their operations on 'point-like' input. inline const Point& make_point(const ExtrusionJunction& ej) { - return ej.p; + return ej.p_; } using LineJunctions = std::vector; // junctions_; /*! * Gets the number of vertices in this polygon. @@ -47,7 +54,7 @@ struct ExtrusionLine */ size_t size() const { - return junctions.size(); + return junctions_.size(); } /*! @@ -55,160 +62,158 @@ struct ExtrusionLine */ bool empty() const { - return junctions.empty(); + return junctions_.empty(); } - /*! - * The list of vertices along which this path runs. - * - * Each junction has a width, making this path a variable-width path. - */ - std::vector junctions; - ExtrusionLine(const size_t inset_idx, const bool is_odd); ExtrusionLine() - : inset_idx(-1) - , is_odd(true) - , is_closed(false) - {} + : inset_idx_(-1) + , is_odd_(true) + , is_closed_(false) + { + } ExtrusionLine(const ExtrusionLine& other) - : inset_idx(other.inset_idx) - , is_odd(other.is_odd) - , is_closed(other.is_closed) - , junctions(other.junctions) - {} - + : inset_idx_(other.inset_idx_) + , is_odd_(other.is_odd_) + , is_closed_(other.is_closed_) + , junctions_(other.junctions_) + { + } + ExtrusionLine& operator=(ExtrusionLine&& other) { - junctions = std::move(other.junctions); - inset_idx = other.inset_idx; - is_odd = other.is_odd; - is_closed = other.is_closed; + junctions_ = std::move(other.junctions_); + inset_idx_ = other.inset_idx_; + is_odd_ = other.is_odd_; + is_closed_ = other.is_closed_; return *this; } ExtrusionLine& operator=(const ExtrusionLine& other) { - junctions = other.junctions; - inset_idx = other.inset_idx; - is_odd = other.is_odd; - is_closed = other.is_closed; + junctions_ = other.junctions_; + inset_idx_ = other.inset_idx_; + is_odd_ = other.is_odd_; + is_closed_ = other.is_closed_; return *this; } - + std::vector::const_iterator begin() const { - return junctions.begin(); + return junctions_.begin(); } std::vector::const_iterator end() const { - return junctions.end(); + return junctions_.end(); } std::vector::const_reverse_iterator rbegin() const { - return junctions.rbegin(); + return junctions_.rbegin(); } std::vector::const_reverse_iterator rend() const { - return junctions.rend(); + return junctions_.rend(); } std::vector::const_reference front() const { - return junctions.front(); + return junctions_.front(); } std::vector::const_reference back() const { - return junctions.back(); + return junctions_.back(); } - const ExtrusionJunction& operator[] (unsigned int index) const + const ExtrusionJunction& operator[](unsigned int index) const { - return junctions[index]; + return junctions_[index]; } - ExtrusionJunction& operator[] (unsigned int index) + ExtrusionJunction& operator[](unsigned int index) { - return junctions[index]; + return junctions_[index]; } std::vector::iterator begin() { - return junctions.begin(); + return junctions_.begin(); } std::vector::iterator end() { - return junctions.end(); + return junctions_.end(); } std::vector::reference front() { - return junctions.front(); + return junctions_.front(); } std::vector::reference back() { - return junctions.back(); + return junctions_.back(); } - template + template void emplace_back(Args&&... args) { - junctions.emplace_back(args...); + junctions_.emplace_back(args...); } void remove(unsigned int index) { - junctions.erase(junctions.begin() + index); + junctions_.erase(junctions_.begin() + index); } void insert(size_t index, const ExtrusionJunction& p) { - junctions.insert(junctions.begin() + index, p); + junctions_.insert(junctions_.begin() + index, p); } - template + template std::vector::iterator insert(std::vector::const_iterator pos, iterator first, iterator last) { - return junctions.insert(pos, first, last); + return junctions_.insert(pos, first, last); } void clear() { - junctions.clear(); + junctions_.clear(); } void reverse() { - std::reverse(junctions.begin(), junctions.end()); + std::reverse(junctions_.begin(), junctions_.end()); } - + /*! * Sum the total length of this path. */ coord_t getLength() const; - coord_t polylineLength() const { return getLength(); } + coord_t polylineLength() const + { + return getLength(); + } /*! * Put all junction locations into a polygon object. - * + * * When this path is not closed the returned Polygon should be handled as a polyline, rather than a polygon. */ Polygon toPolygon() const { Polygon ret; - - for (const ExtrusionJunction& j : junctions) - ret.add(j.p); - + + for (const ExtrusionJunction& j : junctions_) + ret.add(j.p_); + return ret; } diff --git a/include/utils/ListPolyIt.h b/include/utils/ListPolyIt.h index 2f6cf2ed02..0af99f0e7d 100644 --- a/include/utils/ListPolyIt.h +++ b/include/utils/ListPolyIt.h @@ -1,18 +1,17 @@ -//Copyright (c) 2018 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2018 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef UTILS_LIST_POLY_IT_H #define UTILS_LIST_POLY_IT_H -#include #include - +#include #include "IntPoint.h" #include "polygon.h" -namespace cura +namespace cura { /*! @@ -21,99 +20,117 @@ namespace cura class ListPolyIt { public: - ListPolygon* poly; //!< The polygon - ListPolygon::iterator it; //!< The iterator into ListPolyIt::poly ListPolyIt(const ListPolyIt& other) - : poly(other.poly) - , it(other.it) + : poly_(other.poly_) + , it_(other.it_) { } + ListPolyIt(ListPolygon& poly, ListPolygon::iterator it) - : poly(&poly) - , it(it) + : poly_(&poly) + , it_(it) { } + Point& p() const { - return *it; + return *it_; } + /*! * Test whether two iterators refer to the same polygon in the same polygon list. - * + * * \param other The ListPolyIt to test for equality * \return Wether the right argument refers to the same polygon in the same ListPolygon as the left argument. */ bool operator==(const ListPolyIt& other) const { - return poly == other.poly && it == other.it; + return poly_ == other.poly_ && it_ == other.it_; } + bool operator!=(const ListPolyIt& other) const { - return !(*this == other); + return ! (*this == other); } + ListPolyIt& operator=(const ListPolyIt& other) { - poly = other.poly; - it = other.it; + poly_ = other.poly_; + it_ = other.it_; return *this; } + //! move the iterator forward (and wrap around at the end) - ListPolyIt& operator++() - { - ++it; - if (it == poly->end()) { it = poly->begin(); } - return *this; + ListPolyIt& operator++() + { + ++it_; + if (it_ == poly_->end()) + { + it_ = poly_->begin(); + } + return *this; } + //! move the iterator backward (and wrap around at the beginning) - ListPolyIt& operator--() - { - if (it == poly->begin()) { it = poly->end(); } - --it; - return *this; + ListPolyIt& operator--() + { + if (it_ == poly_->begin()) + { + it_ = poly_->end(); + } + --it_; + return *this; } + //! move the iterator forward (and wrap around at the end) - ListPolyIt next() const + ListPolyIt next() const { ListPolyIt ret(*this); ++ret; return ret; } + //! move the iterator backward (and wrap around at the beginning) - ListPolyIt prev() const + ListPolyIt prev() const { ListPolyIt ret(*this); --ret; return ret; } + //! Remove this point from the list polygon void remove() const { - poly->erase(it); + poly_->erase(it_); } + /*! * Convert Polygons to ListPolygons - * + * * \param polys The polygons to convert * \param result The converted polygons */ static void convertPolygonsToLists(const Polygons& polys, ListPolygons& result); + /*! * Convert Polygons to ListPolygons - * + * * \param polys The polygons to convert * \param result The converted polygons */ static void convertPolygonToList(ConstPolygonRef poly, ListPolygon& result); + /*! * Convert ListPolygons to Polygons - * + * * \param list_polygons The polygons to convert * \param polygons The converted polygons */ static void convertListPolygonsToPolygons(const ListPolygons& list_polygons, Polygons& polygons); + /*! * Convert ListPolygons to Polygons - * + * * \param list_polygons The polygons to convert * \param polygons The converted polygons */ @@ -121,24 +138,28 @@ class ListPolyIt /*! * Insert a point into a ListPolygon if it's not a duplicate of the point before or the point after. - * + * * \param before Iterator to the point before the point to insert * \param after Iterator to the point after the point to insert * \param to_insert The point to insert into the ListPolygon in between \p before and \p after * \return Iterator to the newly inserted point, or \p before or \p after in case to_insert was already in the polygon */ static ListPolyIt insertPointNonDuplicate(const ListPolyIt before, const ListPolyIt after, const Point to_insert); + +private: + ListPolygon* poly_; //!< The polygon + ListPolygon::iterator it_; //!< The iterator into ListPolyIt::poly }; -}//namespace cura +} // namespace cura namespace std { /*! * Hash function for \ref ListPolyIt */ -template <> +template<> struct hash { size_t operator()(const cura::ListPolyIt& lpi) const @@ -146,8 +167,7 @@ struct hash return std::hash()(lpi.p()); } }; -}//namespace std - +} // namespace std -#endif//UTILS_LIST_POLY_IT_H +#endif // UTILS_LIST_POLY_IT_H diff --git a/include/utils/ProximityPointLink.h b/include/utils/ProximityPointLink.h deleted file mode 100644 index be60e23ef0..0000000000 --- a/include/utils/ProximityPointLink.h +++ /dev/null @@ -1,61 +0,0 @@ -//Copyright (c) 2018 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. - -#ifndef PROXIMITY_POINT_LINK_H -#define PROXIMITY_POINT_LINK_H - -#include // hash function object -#include -#include -#include -#include // pair -#include - -#include "ListPolyIt.h" - - -namespace cura -{ - -/*! - * Type of ProximityPointLink signifying why/how it was created - */ -enum class ProximityPointLinkType -{ - NORMAL, // Point is close to line segment or to another point - ENDING, // link where two line segments diverge and have the maximum proximity, i.e. where the overlap will be zero - ENDING_CORNER, // when an overlap area ends in a point - SHARP_CORNER // The corner in the polygon is so sharp that it will overlap with itself -}; - -/*! - * A class recording the amount of overlap implicitly by recording the distance between two points on two different polygons or one and the same polygon. - * The order of the two points doesn't matter. - */ -struct ProximityPointLink -{ - const ListPolyIt a; //!< the one point (invalidated after list_polygons have been cleared!) - const ListPolyIt b; //!< the other point (invalidated after list_polygons have been cleared!) - coord_t dist; //!< The distance between the two points - const ProximityPointLinkType type; //!< The type of link; why/how it was created - void setDist(coord_t dist) const; //!< Set the distance. This disregards cosntness, which is only relevant for the equality check and hash operation. - ProximityPointLink(const ListPolyIt a, const ListPolyIt b, int dist, const ProximityPointLinkType type); - bool operator==(const ProximityPointLink& other) const; -}; - -}//namespace cura - -namespace std -{ -template <> -struct hash -{ - size_t operator()(const cura::ProximityPointLink & pp) const - { // has to be symmetric wrt a and b! - return std::hash()(pp.a.p()) + std::hash()(pp.b.p()); - } -}; -}//namespace std - - -#endif//PROXIMITY_POINT_LINK_H diff --git a/include/utils/Simplify.h b/include/utils/Simplify.h index 6cad5fcaf5..e1cacd9a8f 100644 --- a/include/utils/Simplify.h +++ b/include/utils/Simplify.h @@ -1,13 +1,13 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef UTILS_SIMPLIFY_H #define UTILS_SIMPLIFY_H -#include "polygon.h" +#include "../settings/Settings.h" //To load the parameters from a Settings object. #include "ExtrusionLine.h" #include "linearAlg2D.h" //To calculate line deviations and intersecting lines. -#include "../settings/Settings.h" //To load the parameters from a Settings object. +#include "polygon.h" namespace cura { @@ -108,35 +108,18 @@ class Simplify */ ExtrusionLine polyline(const ExtrusionLine& polyline) const; - /*! - * Line segments shorter than this size should be considered for removal. - */ - coord_t max_resolution; - - /*! - * If removing a vertex causes a deviation further than this, it may not be - * removed. - */ - coord_t max_deviation; - - /*! - * If removing a vertex causes the covered area of the line segments to - * change by more than this, it may not be removed. - */ - coord_t max_area_deviation; - protected: /*! * Line segments smaller than this should not occur in the output. * If a vertex causes deviation of less than this, it should always be * removed. */ - constexpr static coord_t min_resolution = 5; //5 units, regardless of how big those are, to allow for rounding errors. + constexpr static coord_t min_resolution = 5; // 5 units, regardless of how big those are, to allow for rounding errors. template bool detectSmall(const Polygonal& polygon, const coord_t& min_size) const { - if (polygon.size() < min_size) //For polygon, 2 or fewer vertices is degenerate. Delete it. For polyline, 1 vertex is degenerate. + if (polygon.size() < min_size) // For polygon, 2 or fewer vertices is degenerate. Delete it. For polyline, 1 vertex is degenerate. { return true; } @@ -169,7 +152,7 @@ class Simplify { return createEmpty(polygon); } - if(polygon.size() == min_size) //For polygon, don't reduce below 3. For polyline, not below 2. + if (polygon.size() == min_size) // For polygon, don't reduce below 3. For polyline, not below 2. { return polygon; } @@ -181,12 +164,12 @@ class Simplify }; std::priority_queue, std::vector>, decltype(comparator)> by_importance(comparator); - Polygonal result = polygon; //Make a copy so that we can also shift vertices. + Polygonal result = polygon; // Make a copy so that we can also shift vertices. for (int64_t current_removed = -1; (polygon.size() - current_removed) > min_size && current_removed != 0;) { current_removed = 0; - //Add the initial points. + // Add the initial points. for (size_t i = 0; i < result.size(); ++i) { if (to_delete[i]) @@ -197,33 +180,33 @@ class Simplify by_importance.emplace(i, vertex_importance); } - //Iteratively remove the least important point until a threshold. + // Iteratively remove the least important point until a threshold. coord_t vertex_importance = 0; while (! by_importance.empty() && (polygon.size() - current_removed) > min_size) { std::pair vertex = by_importance.top(); by_importance.pop(); - //The importance may have changed since this vertex was inserted. Re-compute it now. - //If it doesn't change, it's safe to process. + // The importance may have changed since this vertex was inserted. Re-compute it now. + // If it doesn't change, it's safe to process. vertex_importance = importance(result, to_delete, vertex.first, is_closed); if (vertex_importance != vertex.second) { - by_importance.emplace(vertex.first, vertex_importance); //Re-insert with updated importance. + by_importance.emplace(vertex.first, vertex_importance); // Re-insert with updated importance. continue; } - if (vertex_importance <= max_deviation * max_deviation) + if (vertex_importance <= max_deviation_ * max_deviation_) { current_removed += remove(result, to_delete, vertex.first, vertex_importance, is_closed) ? 1 : 0; } } } - //Now remove the marked vertices in one sweep. + // Now remove the marked vertices in one sweep. Polygonal filtered = createEmpty(polygon); - for(size_t i = 0; i < result.size(); ++i) + for (size_t i = 0; i < result.size(); ++i) { - if(!to_delete[i]) + if (! to_delete[i]) { appendVertex(filtered, result[i]); } @@ -251,18 +234,18 @@ class Simplify coord_t importance(const Polygonal& polygon, const std::vector& to_delete, const size_t index, const bool is_closed) const { const size_t poly_size = polygon.size(); - if(!is_closed && (index == 0 || index == poly_size - 1)) + if (! is_closed && (index == 0 || index == poly_size - 1)) { - return std::numeric_limits::max(); //Endpoints of the polyline must always be retained. + return std::numeric_limits::max(); // Endpoints of the polyline must always be retained. } - //From here on out we can safely look at the vertex neighbors and assume it's a polygon. We won't go out of bounds of the polyline. + // From here on out we can safely look at the vertex neighbors and assume it's a polygon. We won't go out of bounds of the polyline. const Point& vertex = getPosition(polygon[index]); const size_t before_index = previousNotDeleted(index, to_delete); const size_t after_index = nextNotDeleted(index, to_delete); const coord_t area_deviation = getAreaDeviation(polygon[before_index], polygon[index], polygon[after_index]); - if(area_deviation > max_area_deviation) //Removing this line causes the variable line width to get flattened out too much. + if (area_deviation > max_area_deviation_) // Removing this line causes the variable line width to get flattened out too much. { return std::numeric_limits::max(); } @@ -270,13 +253,13 @@ class Simplify const Point& before = getPosition(polygon[before_index]); const Point& after = getPosition(polygon[after_index]); const coord_t deviation2 = LinearAlg2D::getDist2FromLine(vertex, before, after); - if(deviation2 <= min_resolution * min_resolution) //Deviation so small that it's always desired to remove them. + if (deviation2 <= min_resolution * min_resolution) // Deviation so small that it's always desired to remove them. { return deviation2; } - if(vSize2(before - vertex) > max_resolution * max_resolution && vSize2(after - vertex) > max_resolution * max_resolution) + if (vSize2(before - vertex) > max_resolution_ * max_resolution_ && vSize2(after - vertex) > max_resolution_ * max_resolution_) { - return std::numeric_limits::max(); //Long line segments, no need to remove this one. + return std::numeric_limits::max(); // Long line segments, no need to remove this one. } return deviation2; } @@ -300,10 +283,10 @@ class Simplify template bool remove(Polygonal& polygon, std::vector& to_delete, const size_t vertex, const coord_t deviation2, const bool is_closed) const { - if(deviation2 <= min_resolution * min_resolution) + if (deviation2 <= min_resolution * min_resolution) { - //At less than the minimum resolution we're always allowed to delete the vertex. - //Even if the adjacent line segments are very long. + // At less than the minimum resolution we're always allowed to delete the vertex. + // Even if the adjacent line segments are very long. to_delete[vertex] = true; return true; } @@ -316,22 +299,22 @@ class Simplify const coord_t length2_before = vSize2(vertex_position - before_position); const coord_t length2_after = vSize2(vertex_position - after_position); - if(length2_before <= max_resolution * max_resolution && length2_after <= max_resolution * max_resolution) //Both adjacent line segments are short. + if (length2_before <= max_resolution_ * max_resolution_ && length2_after <= max_resolution_ * max_resolution_) // Both adjacent line segments are short. { - //Removing this vertex does little harm. No long lines will be shifted. + // Removing this vertex does little harm. No long lines will be shifted. to_delete[vertex] = true; return true; } - //Otherwise, one edge next to this vertex is longer than max_resolution. The other is shorter. - //In this case we want to remove the short edge by replacing it with a vertex where the two surrounding edges intersect. - //Find the two line segments surrounding the short edge here ("before" and "after" edges). + // Otherwise, one edge next to this vertex is longer than max_resolution. The other is shorter. + // In this case we want to remove the short edge by replacing it with a vertex where the two surrounding edges intersect. + // Find the two line segments surrounding the short edge here ("before" and "after" edges). Point before_from, before_to, after_from, after_to; - if(length2_before <= length2_after) //Before is the shorter line. + if (length2_before <= length2_after) // Before is the shorter line. { - if(!is_closed && before == 0) //No edge before the short edge. + if (! is_closed && before == 0) // No edge before the short edge. { - return false; //Edge cannot be deleted without shifting a long edge. Don't remove anything. + return false; // Edge cannot be deleted without shifting a long edge. Don't remove anything. } const size_t before_before = previousNotDeleted(before, to_delete); before_from = getPosition(polygon[before_before]); @@ -341,9 +324,9 @@ class Simplify } else { - if(!is_closed && after == polygon.size() - 1) //No edge after the short edge. + if (! is_closed && after == polygon.size() - 1) // No edge after the short edge. { - return false; //Edge cannot be deleted without shifting a long edge. Don't remove anything. + return false; // Edge cannot be deleted without shifting a long edge. Don't remove anything. } const size_t after_after = nextNotDeleted(after, to_delete); before_from = getPosition(polygon[before]); @@ -353,12 +336,12 @@ class Simplify } Point intersection; const bool did_intersect = LinearAlg2D::lineLineIntersection(before_from, before_to, after_from, after_to, intersection); - if(!did_intersect) //Lines are parallel. + if (! did_intersect) // Lines are parallel. { - return false; //Cannot remove edge without shifting a long edge. Don't remove anything. + return false; // Cannot remove edge without shifting a long edge. Don't remove anything. } const coord_t intersection_deviation = LinearAlg2D::getDist2FromLineSegment(before_to, intersection, after_from); - if(intersection_deviation <= max_deviation * max_deviation) //Intersection point doesn't deviate too much. Use it! + if (intersection_deviation <= max_deviation_ * max_deviation_) // Intersection point doesn't deviate too much. Use it! { to_delete[vertex] = true; polygon[length2_before <= length2_after ? before : after] = createIntersection(polygon[before], intersection, polygon[after]); @@ -488,8 +471,26 @@ class Simplify * \return The area deviation that would be caused by removing the vertex. */ coord_t getAreaDeviation(const ExtrusionJunction& before, const ExtrusionJunction& vertex, const ExtrusionJunction& after) const; + +private: + /*! + * Line segments shorter than this size should be considered for removal. + */ + coord_t max_resolution_; + + /*! + * If removing a vertex causes a deviation further than this, it may not be + * removed. + */ + coord_t max_deviation_; + + /*! + * If removing a vertex causes the covered area of the line segments to + * change by more than this, it may not be removed. + */ + coord_t max_area_deviation_; }; -} //namespace cura +} // namespace cura -#endif //UTILS_SIMPLIFY_H +#endif // UTILS_SIMPLIFY_H diff --git a/include/utils/SparseGrid.h b/include/utils/SparseGrid.h index f31631c206..3e403a7266 100644 --- a/include/utils/SparseGrid.h +++ b/include/utils/SparseGrid.h @@ -47,22 +47,22 @@ class SparseGrid : public SquareGrid iterator begin() { - return m_grid.begin(); + return grid_.begin(); } iterator end() { - return m_grid.end(); + return grid_.end(); } const_iterator begin() const { - return m_grid.begin(); + return grid_.begin(); } const_iterator end() const { - return m_grid.end(); + return grid_.end(); } /*! \brief Returns all data within radius of query_pt. @@ -134,7 +134,7 @@ class SparseGrid : public SquareGrid bool processFromCell(const GridPoint& grid_pt, const std::function& process_func) const; /*! \brief Map from grid locations (GridPoint) to elements (Elem). */ - GridMap m_grid; + GridMap grid_; }; @@ -146,17 +146,17 @@ SGI_THIS::SparseGrid(coord_t cell_size, size_t elem_reserve, double max_load_fac : SquareGrid(cell_size) { // Must be before the reserve call. - m_grid.max_load_factor(max_load_factor); + grid_.max_load_factor(max_load_factor); if (elem_reserve != 0U) { - m_grid.reserve(elem_reserve); + grid_.reserve(elem_reserve); } } SGI_TEMPLATE bool SGI_THIS::processFromCell(const GridPoint& grid_pt, const std::function& process_func) const { - auto grid_range = m_grid.equal_range(grid_pt); + auto grid_range = grid_.equal_range(grid_pt); for (auto iter = grid_range.first; iter != grid_range.second; ++iter) { if (! process_func(iter->second)) diff --git a/include/utils/SparseLineGrid.h b/include/utils/SparseLineGrid.h index d851664aea..d5462414b1 100644 --- a/include/utils/SparseLineGrid.h +++ b/include/utils/SparseLineGrid.h @@ -29,6 +29,7 @@ class SparseLineGrid : public SparseGrid { public: using Elem = ElemT; + using typename SparseGrid::GridMap; /*! \brief Constructs a sparse grid with the specified cell size. * @@ -71,17 +72,16 @@ SGI_TEMPLATE void SGI_THIS::insert(const Elem& elem) { const std::pair line = m_locator(elem); - using GridMap = std::unordered_multimap; // below is a workaround for the fact that lambda functions cannot access private or protected members // first we define a lambda which works on any GridMap and then we bind it to the actual protected GridMap of the parent class - std::function process_cell_func_ = [&elem, this](GridMap* m_grid, const GridPoint grid_loc) + std::function process_cell_func_ = [&elem, this](GridMap* grid, const GridPoint grid_loc) { - m_grid->emplace(grid_loc, elem); + grid->emplace(grid_loc, elem); return true; }; using namespace std::placeholders; // for _1, _2, _3... - GridMap* m_grid = &(this->m_grid); - std::function process_cell_func(std::bind(process_cell_func_, m_grid, _1)); + GridMap* grid = &(this->grid_); + std::function process_cell_func(std::bind(process_cell_func_, grid, _1)); SparseGrid::processLineCells(line, process_cell_func); } @@ -90,13 +90,13 @@ SGI_TEMPLATE void SGI_THIS::debugHTML(std::string filename) { AABB aabb; - for (std::pair cell : SparseGrid::m_grid) + for (std::pair cell : SparseGrid::grid_) { aabb.include(SparseGrid::toLowerCorner(cell.first)); aabb.include(SparseGrid::toLowerCorner(cell.first + GridPoint(SparseGrid::nonzero_sign(cell.first.X), SparseGrid::nonzero_sign(cell.first.Y)))); } SVG svg(filename.c_str(), aabb); - for (std::pair cell : SparseGrid::m_grid) + for (std::pair cell : SparseGrid::grid_) { // doesn't draw cells at x = 0 or y = 0 correctly (should be double size) Point lb = SparseGrid::toLowerCorner(cell.first); diff --git a/include/utils/SparsePointGrid.h b/include/utils/SparsePointGrid.h index 214fc1fdc1..748f79124e 100644 --- a/include/utils/SparsePointGrid.h +++ b/include/utils/SparsePointGrid.h @@ -76,7 +76,7 @@ void SGI_THIS::insert(const Elem& elem) Point loc = m_locator(elem); GridPoint grid_loc = SparseGrid::toGridPoint(loc); - SparseGrid::m_grid.emplace(grid_loc, elem); + SparseGrid::grid_.emplace(grid_loc, elem); } SGI_TEMPLATE diff --git a/include/utils/VoxelUtils.h b/include/utils/VoxelUtils.h index 30078b51b3..4cf4d97029 100644 --- a/include/utils/VoxelUtils.h +++ b/include/utils/VoxelUtils.h @@ -48,10 +48,11 @@ struct DilationKernel DIAMOND, PRISM }; + GridPoint3 kernel_size_; //!< Size of the kernel in number of voxel cells + Type type_; + std::vector relative_cells_; //!< All offset positions relative to some reference cell which is to be dilated + DilationKernel(GridPoint3 kernel_size, Type type); - GridPoint3 kernel_size; //!< Size of the kernel in number of voxel cells - Type type; - std::vector relative_cells; //!< All offset positions relative to some reference cell which is to be dilated }; /*! diff --git a/src/FffGcodeWriter.cpp b/src/FffGcodeWriter.cpp index 3e2831f857..a43924362d 100644 --- a/src/FffGcodeWriter.cpp +++ b/src/FffGcodeWriter.cpp @@ -1457,7 +1457,7 @@ std::vector FffGcodeWriter::calculateMeshOrder(const SliceDataStorage& s if (mesh.getExtruderIsUsed(extruder_nr)) { const Mesh& mesh_data = mesh_group->meshes[mesh_idx]; - const Point3 middle = (mesh_data.getAABB().min + mesh_data.getAABB().max) / 2; + const Point3 middle = (mesh_data.getAABB().min_ + mesh_data.getAABB().max_) / 2; mesh_idx_order_optimizer.addItem(Point(middle.x_, middle.y_), mesh_idx); } } @@ -2057,7 +2057,7 @@ bool FffGcodeWriter::processSingleLayerInfill( { start_paths = &wall_tool_paths[rand() % wall_tool_paths.size()]; } - near_start_location = (*start_paths)[0][0].junctions[0].p; + near_start_location = (*start_paths)[0][0].junctions_[0].p_; } } if (walls_generated) @@ -2521,7 +2521,7 @@ bool FffGcodeWriter::processInsets( const auto point_view = ranges::views::transform( [](auto extrusion_junction) { - return extrusion_junction.p; + return extrusion_junction.p_; }); for (const auto& path : part.wall_toolpaths) @@ -2595,7 +2595,7 @@ std::optional FffGcodeWriter::getSeamAvoidingLocation(const Polygons& fil // create a vector from the middle of the BB whose length is such that it can be rotated // around the middle of the BB and the end will always be a long way outside of the part's outline // and rotate the vector so that it is normal to the skin angle - const Point vec = rot.apply(Point(0, vSize(skin_part_bb.max - bb_middle) * 100)); + const Point vec = rot.apply(Point(0, vSize(skin_part_bb.max_ - bb_middle) * 100)); // find the vertex in the outline that is closest to the end of the rotated vector const PolygonsPointIndex pa = PolygonUtils::findNearestVert(bb_middle + vec, filling_part); // and find another outline vertex, this time using the vector + 180 deg diff --git a/src/FffPolygonGenerator.cpp b/src/FffPolygonGenerator.cpp index cb4d60f6d4..ae79c909fc 100644 --- a/src/FffPolygonGenerator.cpp +++ b/src/FffPolygonGenerator.cpp @@ -304,8 +304,8 @@ bool FffPolygonGenerator::sliceModel(MeshGroup* meshgroup, TimeKeeper& timeKeepe if (use_variable_layer_heights) { - meshStorage.layers[layer_nr].printZ = adaptive_layer_heights->getLayers()->at(layer_nr).z_position; - meshStorage.layers[layer_nr].thickness = adaptive_layer_heights->getLayers()->at(layer_nr).layer_height; + meshStorage.layers[layer_nr].printZ = adaptive_layer_heights->getLayers()->at(layer_nr).z_position_; + meshStorage.layers[layer_nr].thickness = adaptive_layer_heights->getLayers()->at(layer_nr).layer_height_; } else { @@ -1103,7 +1103,7 @@ void FffPolygonGenerator::processFuzzyWalls(SliceMeshStorage& mesh) std::vector result_paths; for (auto& toolpath : part.wall_toolpaths) { - if (toolpath.front().inset_idx != 0) + if (toolpath.front().inset_idx_ != 0) { result_paths.push_back(toolpath); continue; @@ -1116,7 +1116,7 @@ void FffPolygonGenerator::processFuzzyWalls(SliceMeshStorage& mesh) hole_area = part.print_outline.getOutsidePolygons().offset(-line_width); accumulate_is_in_hole = [&hole_area](const bool& prev_result, const ExtrusionJunction& junction) { - return prev_result || hole_area.inside(junction.p); + return prev_result || hole_area.inside(junction.p_); }; } for (auto& line : toolpath) @@ -1128,9 +1128,9 @@ void FffPolygonGenerator::processFuzzyWalls(SliceMeshStorage& mesh) } auto& result = result_lines.emplace_back(); - result.inset_idx = line.inset_idx; - result.is_odd = line.is_odd; - result.is_closed = line.is_closed; + result.inset_idx_ = line.inset_idx_; + result.is_odd_ = line.is_odd_; + result.is_closed_ = line.is_closed_; // generate points in between p0 and p1 int64_t dist_left_over @@ -1138,30 +1138,30 @@ void FffPolygonGenerator::processFuzzyWalls(SliceMeshStorage& mesh) auto* p0 = &line.front(); for (auto& p1 : line) { - if (p0->p == p1.p) // avoid seams + if (p0->p_ == p1.p_) // avoid seams { - result.emplace_back(p1.p, p1.w, p1.perimeter_index); + result.emplace_back(p1.p_, p1.w_, p1.perimeter_index_); continue; } // 'a' is the (next) new point between p0 and p1 - const Point p0p1 = p1.p - p0->p; + const Point p0p1 = p1.p_ - p0->p_; const int64_t p0p1_size = vSize(p0p1); int64_t p0pa_dist = dist_left_over; if (p0pa_dist >= p0p1_size) { - const Point p = p1.p - (p0p1 / 2); - const double width = (p1.w * vSize(p1.p - p) + p0->w * vSize(p0->p - p)) / p0p1_size; - result.emplace_back(p, width, p1.perimeter_index); + const Point p = p1.p_ - (p0p1 / 2); + const double width = (p1.w_ * vSize(p1.p_ - p) + p0->w_ * vSize(p0->p_ - p)) / p0p1_size; + result.emplace_back(p, width, p1.perimeter_index_); } for (; p0pa_dist < p0p1_size; p0pa_dist += min_dist_between_points + rand() % range_random_point_dist) { const int r = rand() % (fuzziness * 2) - fuzziness; const Point perp_to_p0p1 = turn90CCW(p0p1); const Point fuzz = normal(perp_to_p0p1, r); - const Point pa = p0->p + normal(p0p1, p0pa_dist); - const double width = (p1.w * vSize(p1.p - pa) + p0->w * vSize(p0->p - pa)) / p0p1_size; - result.emplace_back(pa + fuzz, width, p1.perimeter_index); + const Point pa = p0->p_ + normal(p0p1, p0pa_dist); + const double width = (p1.w_ * vSize(p1.p_ - pa) + p0->w_ * vSize(p0->p_ - pa)) / p0p1_size; + result.emplace_back(pa + fuzz, width, p1.perimeter_index_); } // p0pa_dist > p0p1_size now because we broke out of the for-loop dist_left_over = p0pa_dist - p0p1_size; @@ -1171,7 +1171,7 @@ void FffPolygonGenerator::processFuzzyWalls(SliceMeshStorage& mesh) while (result.size() < 3) { size_t point_idx = line.size() - 2; - result.emplace_back(line[point_idx].p, line[point_idx].w, line[point_idx].perimeter_index); + result.emplace_back(line[point_idx].p_, line[point_idx].w_, line[point_idx].perimeter_index_); if (point_idx == 0) { break; @@ -1183,12 +1183,12 @@ void FffPolygonGenerator::processFuzzyWalls(SliceMeshStorage& mesh) result.clear(); for (auto& p : line) { - result.emplace_back(p.p, p.w, p.perimeter_index); + result.emplace_back(p.p_, p.w_, p.perimeter_index_); } } - if (line.back().p == line.front().p) // avoid seams + if (line.back().p_ == line.front().p_) // avoid seams { - result.back().p = result.front().p; + result.back().p_ = result.front().p_; } } } diff --git a/src/InsetOrderOptimizer.cpp b/src/InsetOrderOptimizer.cpp index 9b2358aa62..63d8c4f82c 100644 --- a/src/InsetOrderOptimizer.cpp +++ b/src/InsetOrderOptimizer.cpp @@ -3,11 +3,8 @@ #include "InsetOrderOptimizer.h" -#include "ExtruderTrain.h" -#include "FffGcodeWriter.h" -#include "LayerPlan.h" -#include "utils/views/convert.h" -#include "utils/views/dfs.h" +#include +#include #include #include @@ -25,8 +22,11 @@ #include #include -#include -#include +#include "ExtruderTrain.h" +#include "FffGcodeWriter.h" +#include "LayerPlan.h" +#include "utils/views/convert.h" +#include "utils/views/dfs.h" namespace rg = ranges; namespace rv = ranges::views; @@ -101,7 +101,7 @@ bool InsetOrderOptimizer::addToLayer() for (const auto& line : walls_to_be_added) { - if (line.is_closed) + if (line.is_closed_) { order_optimizer.addPolygon(&line); } @@ -118,14 +118,14 @@ bool InsetOrderOptimizer::addToLayer() if (path.vertices_->empty()) continue; - const bool is_outer_wall = path.vertices_->inset_idx == 0; // or thin wall 'gap filler' - const bool is_gap_filler = path.vertices_->is_odd; + const bool is_outer_wall = path.vertices_->inset_idx_ == 0; // or thin wall 'gap filler' + const bool is_gap_filler = path.vertices_->is_odd_; const GCodePathConfig& non_bridge_config = is_outer_wall ? inset_0_non_bridge_config_ : inset_X_non_bridge_config_; const GCodePathConfig& bridge_config = is_outer_wall ? inset_0_bridge_config_ : inset_X_bridge_config_; const coord_t wipe_dist = is_outer_wall && ! is_gap_filler ? wall_0_wipe_dist_ : wall_x_wipe_dist_; const bool retract_before = is_outer_wall ? retract_before_outer_wall_ : false; - const bool revert_inset = alternate_walls && (path.vertices_->inset_idx % 2); + const bool revert_inset = alternate_walls && (path.vertices_->inset_idx_ % 2); const bool revert_layer = alternate_walls && (layer_nr_ % 2); const bool backwards = path.backwards_ != (revert_inset != revert_layer); const size_t start_index = (backwards != path.backwards_) ? path.vertices_->size() - (path.start_vertex_ + 1) : path.start_vertex_; @@ -163,7 +163,7 @@ InsetOrderOptimizer::value_type InsetOrderOptimizer::getRegionOrder(const auto& return LineLoc{ .line = line, .poly = poly, - .area = line->is_closed ? poly.area() : 0.0, + .area = line->is_closed_ ? poly.area() : 0.0, }; }) | rg::to_vector; @@ -226,7 +226,7 @@ InsetOrderOptimizer::value_type InsetOrderOptimizer::getRegionOrder(const auto& // find hole roots (defined by a positive area in clipper1), these are leaves of the tree structure // as odd walls are also leaves we filter them out by adding a non-zero area check - if (current_node != root && graph.count(current_node) == 1 && current_node->line->is_closed && current_node->area > 0) + if (current_node != root && graph.count(current_node) == 1 && current_node->line->is_closed_ && current_node->area > 0) { hole_roots.push_back(current_node); } @@ -297,21 +297,21 @@ InsetOrderOptimizer::value_type InsetOrderOptimizer::getInsetOrder(const auto& i for (const auto& line : input) { - if (line.is_odd) + if (line.is_odd_) { - if (line.inset_idx >= fillers_by_inset.size()) + if (line.inset_idx_ >= fillers_by_inset.size()) { - fillers_by_inset.resize(line.inset_idx + 1); + fillers_by_inset.resize(line.inset_idx_ + 1); } - fillers_by_inset[line.inset_idx].emplace_back(&line); + fillers_by_inset[line.inset_idx_].emplace_back(&line); } else { - if (line.inset_idx >= walls_by_inset.size()) + if (line.inset_idx_ >= walls_by_inset.size()) { - walls_by_inset.resize(line.inset_idx + 1); + walls_by_inset.resize(line.inset_idx_ + 1); } - walls_by_inset[line.inset_idx].emplace_back(&line); + walls_by_inset[line.inset_idx_].emplace_back(&line); } } for (size_t inset_idx = 0; inset_idx + 1 < walls_by_inset.size(); inset_idx++) diff --git a/src/LayerPlan.cpp b/src/LayerPlan.cpp index 5e8b6a1b2d..e4ddda09e6 100644 --- a/src/LayerPlan.cpp +++ b/src/LayerPlan.cpp @@ -928,14 +928,14 @@ void LayerPlan::addWall( const ExtrusionJunction& p0 = wall[point_idx]; const ExtrusionJunction& p1 = wall[(point_idx + 1) % wall.size()]; - if (PolygonUtils::polygonCollidesWithLineSegment(bridge_wall_mask_, p0.p, p1.p)) + if (PolygonUtils::polygonCollidesWithLineSegment(bridge_wall_mask_, p0.p_, p1.p_)) { // the line crosses the boundary between supported and non-supported regions so it will contain one or more bridge segments // determine which segments of the line are bridges Polygons line_polys; - line_polys.addLine(p0.p, p1.p); + line_polys.addLine(p0.p_, p1.p_); constexpr bool restitch = false; // only a single line doesn't need stitching line_polys = bridge_wall_mask_.intersectionPolyLines(line_polys, restitch); @@ -943,10 +943,10 @@ void LayerPlan::addWall( { // find the bridge line segment that's nearest to p0 int nearest = 0; - double smallest_dist2 = vSize2f(p0.p - line_polys[0][0]); + double smallest_dist2 = vSize2f(p0.p_ - line_polys[0][0]); for (unsigned i = 1; i < line_polys.size(); ++i) { - double dist2 = vSize2f(p0.p - line_polys[i][0]); + double dist2 = vSize2f(p0.p_ - line_polys[i][0]); if (dist2 < smallest_dist2) { nearest = i; @@ -959,14 +959,14 @@ void LayerPlan::addWall( Point b0 = bridge[0]; Point b1 = bridge[1]; - if (vSize2f(p0.p - b1) < vSize2f(p0.p - b0)) + if (vSize2f(p0.p_ - b1) < vSize2f(p0.p_ - b0)) { // swap vertex order b0 = bridge[1]; b1 = bridge[0]; } - distance_to_bridge_start += vSize(b0 - p0.p); + distance_to_bridge_start += vSize(b0 - p0.p_); const double bridge_line_len = vSize(b1 - b0); @@ -982,10 +982,10 @@ void LayerPlan::addWall( line_polys.remove(nearest); } } - else if (! bridge_wall_mask_.inside(p0.p, true)) + else if (! bridge_wall_mask_.inside(p0.p_, true)) { // none of the line is over air - distance_to_bridge_start += vSize(p1.p - p0.p); + distance_to_bridge_start += vSize(p1.p_ - p0.p_); } } @@ -997,7 +997,7 @@ void LayerPlan::addWall( bool first_line = true; const coord_t small_feature_max_length = settings.get("small_feature_max_length"); - const bool is_small_feature = (small_feature_max_length > 0) && (layer_nr_ == 0 || wall.inset_idx == 0) && cura::shorterThan(wall, small_feature_max_length); + const bool is_small_feature = (small_feature_max_length > 0) && (layer_nr_ == 0 || wall.inset_idx_ == 0) && cura::shorterThan(wall, small_feature_max_length); Ratio small_feature_speed_factor = settings.get((layer_nr_ == 0) ? "small_feature_speed_factor_0" : "small_feature_speed_factor"); const Velocity min_speed = fan_speed_layer_time_settings_per_extruder_[getLastPlannedExtruderTrain()->extruder_nr_].cool_min_speed; small_feature_speed_factor = std::max((double)small_feature_speed_factor, (double)(min_speed / non_bridge_config.getSpeed())); @@ -1019,7 +1019,7 @@ void LayerPlan::addWall( if (first_line) { - addTravel(p0.p, always_retract); + addTravel(p0.p_, always_retract); first_line = false; } @@ -1035,8 +1035,8 @@ void LayerPlan::addWall( pieces we'd want to get low enough deviation, then check if each piece is not too short at the end. */ - const coord_t delta_line_width = p1.w - p0.w; - const Point line_vector = p1.p - p0.p; + const coord_t delta_line_width = p1.w_ - p0.w_; + const Point line_vector = p1.p_ - p0.p_; const coord_t line_length = vSize(line_vector); /* Calculate how much the line would deviate from the trapezoidal shape if printed at average width. @@ -1055,8 +1055,8 @@ void LayerPlan::addWall( for (size_t piece = 0; piece < pieces; ++piece) { const double average_progress = (double(piece) + 0.5) / pieces; // How far along this line to sample the line width in the middle of this piece. - const coord_t line_width = p0.w + average_progress * delta_line_width; - const Point destination = p0.p + normal(line_vector, piece_length * (piece + 1)); + const coord_t line_width = p0.w_ + average_progress * delta_line_width; + const Point destination = p0.p_ + normal(line_vector, piece_length * (piece + 1)); if (is_small_feature) { constexpr bool spiralize = false; @@ -1071,7 +1071,7 @@ void LayerPlan::addWall( } else { - const Point origin = p0.p + normal(line_vector, piece_length * piece); + const Point origin = p0.p_ + normal(line_vector, piece_length * piece); addWallLine( origin, destination, @@ -1110,14 +1110,14 @@ void LayerPlan::addWall( int p0p1_dist = vSize(p1 - p0); if (distance_traversed + p0p1_dist >= wall_0_wipe_dist) { - Point vector = p1.p - p0.p; - Point half_way = p0.p + normal(vector, wall_0_wipe_dist - distance_traversed); + Point vector = p1.p_ - p0.p_; + Point half_way = p0.p_ + normal(vector, wall_0_wipe_dist - distance_traversed); addTravel_simple(half_way); break; } else { - addTravel_simple(p1.p); + addTravel_simple(p1.p_); distance_traversed += p0p1_dist; } p0 = p1; @@ -1135,14 +1135,14 @@ void LayerPlan::addInfillWall(const ExtrusionLine& wall, const GCodePathConfig& { assert(("All empty walls should have been filtered at this stage", ! wall.empty())); ExtrusionJunction junction{ *wall.begin() }; - addTravel(junction.p, force_retract); + addTravel(junction.p_, force_retract); for (const auto& junction_n : wall) { - const Ratio width_factor{ static_cast(junction_n.w) / Ratio{ static_cast(path_config.getLineWidth()) } }; + const Ratio width_factor{ static_cast(junction_n.w_) / Ratio{ static_cast(path_config.getLineWidth()) } }; constexpr SpaceFillType space_fill_type = SpaceFillType::Polygons; constexpr Ratio flow = 1.0_r; - addExtrusionMove(junction_n.p, path_config, space_fill_type, flow, width_factor); + addExtrusionMove(junction_n.p_, path_config, space_fill_type, flow, width_factor); junction = junction_n; } } @@ -2176,9 +2176,9 @@ void LayerPlan::writeGCode(GCodeExport& gcode) if (extruder.settings_.get("cool_lift_head") && extruder_plan.extra_time_ > 0.0) { gcode.writeComment("Small layer, adding delay"); - const RetractionAndWipeConfig& retraction_config + const RetractionAndWipeConfig& actual_retraction_config = current_mesh ? current_mesh->retraction_wipe_config : storage_.retraction_wipe_config_per_extruder[gcode.getExtruderNr()]; - gcode.writeRetraction(retraction_config.retraction_config); + gcode.writeRetraction(actual_retraction_config.retraction_config); if (extruder_plan_idx == extruder_plans_.size() - 1 || ! extruder.settings_.get("machine_extruder_end_pos_abs")) { // only do the z-hop if it's the last extruder plan; otherwise it's already at the switching bay area // or do it anyway when we switch extruder in-place diff --git a/src/SkeletalTrapezoidation.cpp b/src/SkeletalTrapezoidation.cpp index 94adbffe11..eaebbb1683 100644 --- a/src/SkeletalTrapezoidation.cpp +++ b/src/SkeletalTrapezoidation.cpp @@ -2024,40 +2024,40 @@ void SkeletalTrapezoidation::addToolpathSegment(const ExtrusionJunction& from, c std::vector& generated_toolpaths = *p_generated_toolpaths; - size_t inset_idx = from.perimeter_index; + size_t inset_idx = from.perimeter_index_; if (inset_idx >= generated_toolpaths.size()) { generated_toolpaths.resize(inset_idx + 1); } - assert((generated_toolpaths[inset_idx].empty() || ! generated_toolpaths[inset_idx].back().junctions.empty()) && "empty extrusion lines should never have been generated"); - if (generated_toolpaths[inset_idx].empty() || generated_toolpaths[inset_idx].back().is_odd != is_odd - || generated_toolpaths[inset_idx].back().junctions.back().perimeter_index != inset_idx // inset_idx should always be consistent + assert((generated_toolpaths[inset_idx].empty() || ! generated_toolpaths[inset_idx].back().junctions_.empty()) && "empty extrusion lines should never have been generated"); + if (generated_toolpaths[inset_idx].empty() || generated_toolpaths[inset_idx].back().is_odd_ != is_odd + || generated_toolpaths[inset_idx].back().junctions_.back().perimeter_index_ != inset_idx // inset_idx should always be consistent ) { force_new_path = true; } - if (! force_new_path && shorterThen(generated_toolpaths[inset_idx].back().junctions.back().p - from.p, 10) - && std::abs(generated_toolpaths[inset_idx].back().junctions.back().w - from.w) < 10 && ! from_is_3way // force new path at 3way intersection + if (! force_new_path && shorterThen(generated_toolpaths[inset_idx].back().junctions_.back().p_ - from.p_, 10) + && std::abs(generated_toolpaths[inset_idx].back().junctions_.back().w_ - from.w_) < 10 && ! from_is_3way // force new path at 3way intersection ) { - generated_toolpaths[inset_idx].back().junctions.push_back(to); + generated_toolpaths[inset_idx].back().junctions_.push_back(to); } else if ( - ! force_new_path && shorterThen(generated_toolpaths[inset_idx].back().junctions.back().p - to.p, 10) - && std::abs(generated_toolpaths[inset_idx].back().junctions.back().w - to.w) < 10 && ! to_is_3way // force new path at 3way intersection + ! force_new_path && shorterThen(generated_toolpaths[inset_idx].back().junctions_.back().p_ - to.p_, 10) + && std::abs(generated_toolpaths[inset_idx].back().junctions_.back().w_ - to.w_) < 10 && ! to_is_3way // force new path at 3way intersection ) { if (! is_odd) { spdlog::error("Reversing even wall line causes it to be printed CCW instead of CW!"); } - generated_toolpaths[inset_idx].back().junctions.push_back(from); + generated_toolpaths[inset_idx].back().junctions_.push_back(from); } else { generated_toolpaths[inset_idx].emplace_back(inset_idx, is_odd); - generated_toolpaths[inset_idx].back().junctions.push_back(from); - generated_toolpaths[inset_idx].back().junctions.push_back(to); + generated_toolpaths[inset_idx].back().junctions_.push_back(from); + generated_toolpaths[inset_idx].back().junctions_.push_back(to); } }; @@ -2111,7 +2111,7 @@ void SkeletalTrapezoidation::connectJunctions(ptr_vector_t& edge_ if (edge_to_peak->prev_) { LineJunctions from_prev_junctions = *edge_to_peak->prev_->data_.getExtrusionJunctions(); - while (! from_junctions.empty() && ! from_prev_junctions.empty() && from_junctions.back().perimeter_index <= from_prev_junctions.front().perimeter_index) + while (! from_junctions.empty() && ! from_prev_junctions.empty() && from_junctions.back().perimeter_index_ <= from_prev_junctions.front().perimeter_index_) { from_junctions.pop_back(); } @@ -2126,7 +2126,7 @@ void SkeletalTrapezoidation::connectJunctions(ptr_vector_t& edge_ if (edge_from_peak->next_) { LineJunctions to_next_junctions = *edge_from_peak->next_->twin_->data_.getExtrusionJunctions(); - while (! to_junctions.empty() && ! to_next_junctions.empty() && to_junctions.back().perimeter_index <= to_next_junctions.front().perimeter_index) + while (! to_junctions.empty() && ! to_next_junctions.empty() && to_junctions.back().perimeter_index_ <= to_next_junctions.front().perimeter_index_) { to_junctions.pop_back(); } @@ -2152,19 +2152,19 @@ void SkeletalTrapezoidation::connectJunctions(ptr_vector_t& edge_ { ExtrusionJunction& from = from_junctions[from_junctions.size() - 1 - junction_rev_idx]; ExtrusionJunction& to = to_junctions[to_junctions.size() - 1 - junction_rev_idx]; - assert(from.perimeter_index == to.perimeter_index); - if (from.perimeter_index != to.perimeter_index) + assert(from.perimeter_index_ == to.perimeter_index_); + if (from.perimeter_index_ != to.perimeter_index_) { - spdlog::warn("Connecting two perimeters with different indices! Perimeter {} and {}", from.perimeter_index, to.perimeter_index); + spdlog::warn("Connecting two perimeters with different indices! Perimeter {} and {}", from.perimeter_index_, to.perimeter_index_); } const bool from_is_odd = quad_start->to_->data_.bead_count_ > 0 && quad_start->to_->data_.bead_count_ % 2 == 1 // quad contains single bead segment && quad_start->to_->data_.transition_ratio_ == 0 // We're not in a transition && junction_rev_idx == segment_count - 1 // Is single bead segment - && shorterThen(from.p - quad_start->to_->p_, 5); + && shorterThen(from.p_ - quad_start->to_->p_, 5); const bool to_is_odd = quad_end->from_->data_.bead_count_ > 0 && quad_end->from_->data_.bead_count_ % 2 == 1 // quad contains single bead segment && quad_end->from_->data_.transition_ratio_ == 0 // We're not in a transition && junction_rev_idx == segment_count - 1 // Is single bead segment - && shorterThen(to.p - quad_end->from_->p_, 5); + && shorterThen(to.p_ - quad_end->from_->p_, 5); const bool is_odd_segment = from_is_odd && to_is_odd; if (is_odd_segment && passed_odd_edges.count(quad_start->next_->twin_) > 0) // Only generate toolpath for odd segments once @@ -2215,7 +2215,7 @@ void SkeletalTrapezoidation::generateLocalMaximaSingleBeads() for (coord_t segment = 0; segment < n_segments; segment++) { double a = 2.0 * std::numbers::pi / n_segments * segment; - line.junctions.emplace_back(node.p_ + Point(r * cos(a), r * sin(a)), width, inset_index); + line.junctions_.emplace_back(node.p_ + Point(r * cos(a), r * sin(a)), width, inset_index); } } } diff --git a/src/TopSurface.cpp b/src/TopSurface.cpp index b27abb3a54..f3b9b8974a 100644 --- a/src/TopSurface.cpp +++ b/src/TopSurface.cpp @@ -135,7 +135,7 @@ bool TopSurface::ironing(const SliceDataStorage& storage, const SliceMeshStorage PointMatrix rotate(-direction + 90); const Point center = bounding_box.getMiddle(); const Point far_away = rotate.apply( - Point(0, vSize(bounding_box.max - center) * 100)); // Some direction very far away in the direction perpendicular to the ironing lines, relative to the centre. + Point(0, vSize(bounding_box.max_ - center) * 100)); // Some direction very far away in the direction perpendicular to the ironing lines, relative to the centre. // Two options to start, both perpendicular to the ironing lines. Which is closer? const Point front_side = PolygonUtils::findNearestVert(center + far_away, ironed_areas).p(); const Point back_side = PolygonUtils::findNearestVert(center - far_away, ironed_areas).p(); diff --git a/src/TreeSupportTipGenerator.cpp b/src/TreeSupportTipGenerator.cpp index c6c57d901f..4c993cd487 100644 --- a/src/TreeSupportTipGenerator.cpp +++ b/src/TreeSupportTipGenerator.cpp @@ -391,8 +391,8 @@ std::shared_ptr TreeSupportTipGenerator::generateCrossFi const coord_t aabb_expansion = mesh.settings.get("support_offset"); AABB3D aabb_here(mesh.bounding_box); - aabb_here.include(aabb_here.min - Point3(-aabb_expansion, -aabb_expansion, 0)); - aabb_here.include(aabb_here.max + Point3(-aabb_expansion, -aabb_expansion, 0)); + aabb_here.include(aabb_here.min_ - Point3(-aabb_expansion, -aabb_expansion, 0)); + aabb_here.include(aabb_here.max_ + Point3(-aabb_expansion, -aabb_expansion, 0)); aabb.include(aabb_here); const std::string cross_subdisivion_spec_image_file = mesh.settings.get("cross_support_density_image"); @@ -664,9 +664,9 @@ void TreeSupportTipGenerator::addPointAsInfluenceArea( support_tree_branch_reach_limit); elem->area_ = new Polygons(area); - for (Point p : additional_ovalization_targets) + for (Point target : additional_ovalization_targets) { - elem->additional_ovalization_targets_.emplace_back(p); + elem->additional_ovalization_targets_.emplace_back(target); } move_bounds[insert_layer].emplace(elem); @@ -879,17 +879,16 @@ void TreeSupportTipGenerator::generateTips( = relevant_forbidden.offset(EPSILON) .unionPolygons(); // Prevent rounding errors down the line, points placed directly on the line of the forbidden area may not be added otherwise. - std::function generateLines = [&](const Polygons& area, bool roof, LayerIndex layer_idx) + std::function generateLines = [&](const Polygons& area, bool roof, LayerIndex generate_layer_idx) { coord_t upper_line_distance = support_supporting_branch_distance; coord_t line_distance = std::max(roof ? support_roof_line_distance : support_tree_branch_distance, upper_line_distance); - return TreeSupportUtils::generateSupportInfillLines( area, config, roof && ! use_fake_roof, - layer_idx, + generate_layer_idx, line_distance, cross_fill_provider, roof && ! use_fake_roof, diff --git a/src/WallToolPaths.cpp b/src/WallToolPaths.cpp index edf90d751a..75a98b843a 100644 --- a/src/WallToolPaths.cpp +++ b/src/WallToolPaths.cpp @@ -3,6 +3,14 @@ #include "WallToolPaths.h" +#include //For std::partition_copy and std::min_element. +#include + +#include +#include +#include +#include + #include "ExtruderTrain.h" #include "SkeletalTrapezoidation.h" #include "utils/PolylineStitcher.h" @@ -11,14 +19,6 @@ #include "utils/actions/smooth.h" #include "utils/polygonUtils.h" -#include -#include -#include -#include - -#include //For std::partition_copy and std::min_element. -#include - namespace cura { @@ -161,11 +161,11 @@ const std::vector& WallToolPaths::generate() toolpaths_, section_type_, layer_idx_, - scripta::CellVDI{ "is_closed", &ExtrusionLine::is_closed }, - scripta::CellVDI{ "is_odd", &ExtrusionLine::is_odd }, - scripta::CellVDI{ "inset_idx", &ExtrusionLine::inset_idx }, - scripta::PointVDI{ "width", &ExtrusionJunction::w }, - scripta::PointVDI{ "perimeter_index", &ExtrusionJunction::perimeter_index }); + scripta::CellVDI{ "is_closed", &ExtrusionLine::is_closed_ }, + scripta::CellVDI{ "is_odd", &ExtrusionLine::is_odd_ }, + scripta::CellVDI{ "inset_idx", &ExtrusionLine::inset_idx_ }, + scripta::PointVDI{ "width", &ExtrusionJunction::w_ }, + scripta::PointVDI{ "perimeter_index", &ExtrusionJunction::perimeter_index_ }); stitchToolPaths(toolpaths_, settings_); scripta::log( @@ -173,11 +173,11 @@ const std::vector& WallToolPaths::generate() toolpaths_, section_type_, layer_idx_, - scripta::CellVDI{ "is_closed", &ExtrusionLine::is_closed }, - scripta::CellVDI{ "is_odd", &ExtrusionLine::is_odd }, - scripta::CellVDI{ "inset_idx", &ExtrusionLine::inset_idx }, - scripta::PointVDI{ "width", &ExtrusionJunction::w }, - scripta::PointVDI{ "perimeter_index", &ExtrusionJunction::perimeter_index }); + scripta::CellVDI{ "is_closed", &ExtrusionLine::is_closed_ }, + scripta::CellVDI{ "is_odd", &ExtrusionLine::is_odd_ }, + scripta::CellVDI{ "inset_idx", &ExtrusionLine::inset_idx_ }, + scripta::PointVDI{ "width", &ExtrusionJunction::w_ }, + scripta::PointVDI{ "perimeter_index", &ExtrusionJunction::perimeter_index_ }); removeSmallLines(toolpaths_); scripta::log( @@ -185,11 +185,11 @@ const std::vector& WallToolPaths::generate() toolpaths_, section_type_, layer_idx_, - scripta::CellVDI{ "is_closed", &ExtrusionLine::is_closed }, - scripta::CellVDI{ "is_odd", &ExtrusionLine::is_odd }, - scripta::CellVDI{ "inset_idx", &ExtrusionLine::inset_idx }, - scripta::PointVDI{ "width", &ExtrusionJunction::w }, - scripta::PointVDI{ "perimeter_index", &ExtrusionJunction::perimeter_index }); + scripta::CellVDI{ "is_closed", &ExtrusionLine::is_closed_ }, + scripta::CellVDI{ "is_odd", &ExtrusionLine::is_odd_ }, + scripta::CellVDI{ "inset_idx", &ExtrusionLine::inset_idx_ }, + scripta::PointVDI{ "width", &ExtrusionJunction::w_ }, + scripta::PointVDI{ "perimeter_index", &ExtrusionJunction::perimeter_index_ }); simplifyToolPaths(toolpaths_, settings_); scripta::log( @@ -197,11 +197,11 @@ const std::vector& WallToolPaths::generate() toolpaths_, section_type_, layer_idx_, - scripta::CellVDI{ "is_closed", &ExtrusionLine::is_closed }, - scripta::CellVDI{ "is_odd", &ExtrusionLine::is_odd }, - scripta::CellVDI{ "inset_idx", &ExtrusionLine::inset_idx }, - scripta::PointVDI{ "width", &ExtrusionJunction::w }, - scripta::PointVDI{ "perimeter_index", &ExtrusionJunction::perimeter_index }); + scripta::CellVDI{ "is_closed", &ExtrusionLine::is_closed_ }, + scripta::CellVDI{ "is_odd", &ExtrusionLine::is_odd_ }, + scripta::CellVDI{ "inset_idx", &ExtrusionLine::inset_idx_ }, + scripta::PointVDI{ "width", &ExtrusionJunction::w_ }, + scripta::PointVDI{ "perimeter_index", &ExtrusionJunction::perimeter_index_ }); separateOutInnerContour(); @@ -211,18 +211,18 @@ const std::vector& WallToolPaths::generate() toolpaths_, section_type_, layer_idx_, - scripta::CellVDI{ "is_closed", &ExtrusionLine::is_closed }, - scripta::CellVDI{ "is_odd", &ExtrusionLine::is_odd }, - scripta::CellVDI{ "inset_idx", &ExtrusionLine::inset_idx }, - scripta::PointVDI{ "width", &ExtrusionJunction::w }, - scripta::PointVDI{ "perimeter_index", &ExtrusionJunction::perimeter_index }); + scripta::CellVDI{ "is_closed", &ExtrusionLine::is_closed_ }, + scripta::CellVDI{ "is_odd", &ExtrusionLine::is_odd_ }, + scripta::CellVDI{ "inset_idx", &ExtrusionLine::inset_idx_ }, + scripta::PointVDI{ "width", &ExtrusionJunction::w_ }, + scripta::PointVDI{ "perimeter_index", &ExtrusionJunction::perimeter_index_ }); assert( std::is_sorted( toolpaths_.cbegin(), toolpaths_.cend(), [](const VariableWidthLines& l, const VariableWidthLines& r) { - return l.front().inset_idx < r.front().inset_idx; + return l.front().inset_idx_ < r.front().inset_idx_; }) && "WallToolPaths should be sorted from the outer 0th to inner_walls"); toolpaths_generated_ = true; @@ -231,11 +231,11 @@ const std::vector& WallToolPaths::generate() toolpaths_, section_type_, layer_idx_, - scripta::CellVDI{ "is_closed", &ExtrusionLine::is_closed }, - scripta::CellVDI{ "is_odd", &ExtrusionLine::is_odd }, - scripta::CellVDI{ "inset_idx", &ExtrusionLine::inset_idx }, - scripta::PointVDI{ "width", &ExtrusionJunction::w }, - scripta::PointVDI{ "perimeter_index", &ExtrusionJunction::perimeter_index }); + scripta::CellVDI{ "is_closed", &ExtrusionLine::is_closed_ }, + scripta::CellVDI{ "is_odd", &ExtrusionLine::is_odd_ }, + scripta::CellVDI{ "inset_idx", &ExtrusionLine::inset_idx_ }, + scripta::PointVDI{ "width", &ExtrusionJunction::w_ }, + scripta::PointVDI{ "perimeter_index", &ExtrusionJunction::perimeter_index_ }); return toolpaths_; } @@ -256,17 +256,17 @@ void WallToolPaths::stitchToolPaths(std::vector& toolpaths, for (ExtrusionLine& wall_polygon : closed_polygons) { - if (wall_polygon.junctions.empty()) + if (wall_polygon.junctions_.empty()) { continue; } - wall_polygon.is_closed = true; + wall_polygon.is_closed_ = true; wall_lines.emplace_back(std::move(wall_polygon)); // add stitched polygons to result } #ifdef DEBUG for (ExtrusionLine& line : wall_lines) { - assert(line.inset_idx == wall_idx); + assert(line.inset_idx_ == wall_idx); } #endif // DEBUG } @@ -282,9 +282,9 @@ void WallToolPaths::removeSmallLines(std::vector& toolpaths) coord_t min_width = std::numeric_limits::max(); for (const ExtrusionJunction& j : line) { - min_width = std::min(min_width, j.w); + min_width = std::min(min_width, j.w_); } - if (line.is_odd && ! line.is_closed && shorterThan(line, min_width / 2)) + if (line.is_odd_ && ! line.is_closed_ && shorterThan(line, min_width / 2)) { // remove line line = std::move(inset.back()); inset.erase(--inset.end()); @@ -303,9 +303,9 @@ void WallToolPaths::simplifyToolPaths(std::vector& toolpaths | ranges::views::transform( [&simplifier](auto& line) { - auto line_ = line.is_closed ? simplifier.polygon(line) : simplifier.polyline(line); + auto line_ = line.is_closed_ ? simplifier.polygon(line) : simplifier.polyline(line); - if (line_.is_closed && line_.size() >= 2 && line_.front() != line_.back()) + if (line_.is_closed_ && line_.size() >= 2 && line_.front() != line_.back()) { line_.emplace_back(line_.front()); } @@ -357,7 +357,7 @@ void WallToolPaths::separateOutInnerContour() { for (const ExtrusionJunction& j : line) { - if (j.w == 0) + if (j.w_ == 0) { is_contour = true; } @@ -377,17 +377,17 @@ void WallToolPaths::separateOutInnerContour() { for (const ExtrusionJunction& j : line) { - assert(j.w == 0); + assert(j.w_ == 0); } } #endif // DEBUG for (const ExtrusionLine& line : inset) { - if (line.is_odd) + if (line.is_odd_) { continue; // odd lines don't contribute to the contour } - else if (line.is_closed) // sometimes an very small even polygonal wall is not stitched into a polygon + else if (line.is_closed_) // sometimes an very small even polygonal wall is not stitched into a polygon { inner_contour_.emplace_back(line.toPolygon()); } diff --git a/src/bridge.cpp b/src/bridge.cpp index a5a1ab40ac..30ed81ed9c 100644 --- a/src/bridge.cpp +++ b/src/bridge.cpp @@ -117,7 +117,7 @@ int bridgeAngle( // It needs to be shrunk slightly so that the vertices of the skin polygon that would otherwise fall exactly on // the air boundary do appear to be supported - const int bb_max_dim = std::max(boundary_box.max.X - boundary_box.min.X, boundary_box.max.Y - boundary_box.min.Y); + const int bb_max_dim = std::max(boundary_box.max_.X - boundary_box.min_.X, boundary_box.max_.Y - boundary_box.min_.Y); const Polygons air_below(bb_poly.offset(bb_max_dim).difference(prev_layer_outline).offset(-10)); Polygons skin_perimeter_lines; diff --git a/src/communication/CommandLine.cpp b/src/communication/CommandLine.cpp index de365e2bf9..4b608dfbfb 100644 --- a/src/communication/CommandLine.cpp +++ b/src/communication/CommandLine.cpp @@ -25,8 +25,8 @@ namespace cura { CommandLine::CommandLine(const std::vector& arguments) - : arguments(arguments) - , last_shown_progress(0) + : arguments_(arguments) + , last_shown_progress_(0) { } @@ -67,7 +67,7 @@ void CommandLine::setLayerForSend(const LayerIndex::value_type&) bool CommandLine::hasSlice() const { - return ! arguments.empty(); + return ! arguments_.empty(); } bool CommandLine::isSequential() const @@ -101,7 +101,7 @@ void CommandLine::sendPrintTimeMaterialEstimates() const void CommandLine::sendProgress(double progress) const { const unsigned int rounded_amount = 100 * progress; - if (last_shown_progress == rounded_amount) // No need to send another tiny update step. + if (last_shown_progress_ == rounded_amount) // No need to send another tiny update step. { return; } @@ -114,9 +114,9 @@ void CommandLine::sliceNext() // Count the number of mesh groups to slice for. size_t num_mesh_groups = 1; - for (size_t argument_index = 2; argument_index < arguments.size(); argument_index++) + for (size_t argument_index = 2; argument_index < arguments_.size(); argument_index++) { - if (arguments[argument_index].find("--next") == 0) // Starts with "--next". + if (arguments_[argument_index].find("--next") == 0) // Starts with "--next". { num_mesh_groups++; } @@ -128,16 +128,16 @@ void CommandLine::sliceNext() size_t mesh_group_index = 0; Settings* last_settings = &slice.scene.settings; - slice.scene.extruders.reserve(arguments.size() >> 1); // Allocate enough memory to prevent moves. + slice.scene.extruders.reserve(arguments_.size() >> 1); // Allocate enough memory to prevent moves. slice.scene.extruders.emplace_back(0, &slice.scene.settings); // Always have one extruder. ExtruderTrain* last_extruder = &slice.scene.extruders[0]; bool force_read_parent = false; bool force_read_nondefault = false; - for (size_t argument_index = 2; argument_index < arguments.size(); argument_index++) + for (size_t argument_index = 2; argument_index < arguments_.size(); argument_index++) { - std::string argument = arguments[argument_index]; + std::string argument = arguments_[argument_index]; if (argument[0] == '-') // Starts with "-". { if (argument[1] == '-') // Starts with "--". @@ -185,7 +185,7 @@ void CommandLine::sliceNext() } else // Starts with "-" but not with "--". { - argument = arguments[argument_index]; + argument = arguments_[argument_index]; switch (argument[1]) { case 'v': @@ -207,12 +207,12 @@ void CommandLine::sliceNext() case 'j': { argument_index++; - if (argument_index >= arguments.size()) + if (argument_index >= arguments_.size()) { spdlog::error("Missing JSON file with -j argument."); exit(1); } - argument = arguments[argument_index]; + argument = arguments_[argument_index]; if (loadJSON(argument, *last_settings, force_read_parent, force_read_nondefault)) { spdlog::error("Failed to load JSON file: {}", argument); @@ -250,12 +250,12 @@ void CommandLine::sliceNext() case 'l': { argument_index++; - if (argument_index >= arguments.size()) + if (argument_index >= arguments_.size()) { spdlog::error("Missing model file with -l argument."); exit(1); } - argument = arguments[argument_index]; + argument = arguments_[argument_index]; const Matrix4x3D transformation = last_settings->get("mesh_rotation_matrix"); // The transformation applied to the model when loaded. @@ -273,12 +273,12 @@ void CommandLine::sliceNext() case 'o': { argument_index++; - if (argument_index >= arguments.size()) + if (argument_index >= arguments_.size()) { spdlog::error("Missing output file with -o argument."); exit(1); } - argument = arguments[argument_index]; + argument = arguments_[argument_index]; if (! FffProcessor::getInstance()->setTargetFile(argument.c_str())) { spdlog::error("Failed to open {} for output.", argument.c_str()); @@ -296,12 +296,12 @@ void CommandLine::sliceNext() { // Parse the given setting and store it. argument_index++; - if (argument_index >= arguments.size()) + if (argument_index >= arguments_.size()) { spdlog::error("Missing setting name and value with -s argument."); exit(1); } - argument = arguments[argument_index]; + argument = arguments_[argument_index]; const size_t value_position = argument.find("="); std::string key = argument.substr(0, value_position); if (value_position == std::string::npos) @@ -333,7 +333,7 @@ void CommandLine::sliceNext() } } - arguments.clear(); // We've processed all arguments now. + arguments_.clear(); // We've processed all arguments now. #ifndef DEBUG try diff --git a/src/gcodeExport.cpp b/src/gcodeExport.cpp index 5e4e1db16e..8d87717fa3 100644 --- a/src/gcodeExport.cpp +++ b/src/gcodeExport.cpp @@ -249,18 +249,18 @@ std::string GCodeExport::getFileHeader( prefix << ";PRINT.GROUPS:" << Application::getInstance().current_slice_->scene.mesh_groups.size() << new_line_; - if (total_bounding_box_.min.x_ > total_bounding_box_.max.x_) // We haven't encountered any movement (yet). This probably means we're command-line slicing. + if (total_bounding_box_.min_.x_ > total_bounding_box_.max_.x_) // We haven't encountered any movement (yet). This probably means we're command-line slicing. { // Put some small default in there. - total_bounding_box_.min = Point3(0, 0, 0); - total_bounding_box_.max = Point3(10, 10, 10); + total_bounding_box_.min_ = Point3(0, 0, 0); + total_bounding_box_.max_ = Point3(10, 10, 10); } - prefix << ";PRINT.SIZE.MIN.X:" << INT2MM(total_bounding_box_.min.x_) << new_line_; - prefix << ";PRINT.SIZE.MIN.Y:" << INT2MM(total_bounding_box_.min.y_) << new_line_; - prefix << ";PRINT.SIZE.MIN.Z:" << INT2MM(total_bounding_box_.min.z_) << new_line_; - prefix << ";PRINT.SIZE.MAX.X:" << INT2MM(total_bounding_box_.max.x_) << new_line_; - prefix << ";PRINT.SIZE.MAX.Y:" << INT2MM(total_bounding_box_.max.y_) << new_line_; - prefix << ";PRINT.SIZE.MAX.Z:" << INT2MM(total_bounding_box_.max.z_) << new_line_; + prefix << ";PRINT.SIZE.MIN.X:" << INT2MM(total_bounding_box_.min_.x_) << new_line_; + prefix << ";PRINT.SIZE.MIN.Y:" << INT2MM(total_bounding_box_.min_.y_) << new_line_; + prefix << ";PRINT.SIZE.MIN.Z:" << INT2MM(total_bounding_box_.min_.z_) << new_line_; + prefix << ";PRINT.SIZE.MAX.X:" << INT2MM(total_bounding_box_.max_.x_) << new_line_; + prefix << ";PRINT.SIZE.MAX.Y:" << INT2MM(total_bounding_box_.max_.y_) << new_line_; + prefix << ";PRINT.SIZE.MAX.Z:" << INT2MM(total_bounding_box_.max_.z_) << new_line_; prefix << ";SLICE_UUID:" << slice_uuid_ << new_line_; prefix << ";END_OF_HEADER" << new_line_; break; @@ -302,12 +302,12 @@ std::string GCodeExport::getFileHeader( prefix << new_line_; prefix << ";Layer height: " << Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("layer_height") << new_line_; } - prefix << ";MINX:" << INT2MM(total_bounding_box_.min.x_) << new_line_; - prefix << ";MINY:" << INT2MM(total_bounding_box_.min.y_) << new_line_; - prefix << ";MINZ:" << INT2MM(total_bounding_box_.min.z_) << new_line_; - prefix << ";MAXX:" << INT2MM(total_bounding_box_.max.x_) << new_line_; - prefix << ";MAXY:" << INT2MM(total_bounding_box_.max.y_) << new_line_; - prefix << ";MAXZ:" << INT2MM(total_bounding_box_.max.z_) << new_line_; + prefix << ";MINX:" << INT2MM(total_bounding_box_.min_.x_) << new_line_; + prefix << ";MINY:" << INT2MM(total_bounding_box_.min_.y_) << new_line_; + prefix << ";MINZ:" << INT2MM(total_bounding_box_.min_.z_) << new_line_; + prefix << ";MAXX:" << INT2MM(total_bounding_box_.max_.x_) << new_line_; + prefix << ";MAXY:" << INT2MM(total_bounding_box_.max_.y_) << new_line_; + prefix << ";MAXZ:" << INT2MM(total_bounding_box_.max_.z_) << new_line_; prefix << ";TARGET_MACHINE.NAME:" << transliterate(machine_name_) << new_line_; } diff --git a/src/infill.cpp b/src/infill.cpp index 6c7f5e80dc..2deda6f1b8 100644 --- a/src/infill.cpp +++ b/src/infill.cpp @@ -144,11 +144,11 @@ void Infill::generate( small_infill_paths, section_type, layer_idx, - scripta::CellVDI{ "is_closed", &ExtrusionLine::is_closed }, - scripta::CellVDI{ "is_odd", &ExtrusionLine::is_odd }, - scripta::CellVDI{ "inset_idx", &ExtrusionLine::inset_idx }, - scripta::PointVDI{ "width", &ExtrusionJunction::w }, - scripta::PointVDI{ "perimeter_index", &ExtrusionJunction::perimeter_index }); + scripta::CellVDI{ "is_closed", &ExtrusionLine::is_closed_ }, + scripta::CellVDI{ "is_odd", &ExtrusionLine::is_odd_ }, + scripta::CellVDI{ "inset_idx", &ExtrusionLine::inset_idx_ }, + scripta::PointVDI{ "width", &ExtrusionJunction::w_ }, + scripta::PointVDI{ "perimeter_index", &ExtrusionJunction::perimeter_index_ }); for (const auto& small_infill_path : small_infill_paths) { toolpaths.emplace_back(small_infill_path); @@ -207,11 +207,11 @@ void Infill::generate( toolpaths, section_type, layer_idx, - scripta::CellVDI{ "is_closed", &ExtrusionLine::is_closed }, - scripta::CellVDI{ "is_odd", &ExtrusionLine::is_odd }, - scripta::CellVDI{ "inset_idx", &ExtrusionLine::inset_idx }, - scripta::PointVDI{ "width", &ExtrusionJunction::w }, - scripta::PointVDI{ "perimeter_index", &ExtrusionJunction::perimeter_index }); + scripta::CellVDI{ "is_closed", &ExtrusionLine::is_closed_ }, + scripta::CellVDI{ "is_odd", &ExtrusionLine::is_odd_ }, + scripta::CellVDI{ "inset_idx", &ExtrusionLine::inset_idx_ }, + scripta::PointVDI{ "width", &ExtrusionJunction::w_ }, + scripta::PointVDI{ "perimeter_index", &ExtrusionJunction::perimeter_index_ }); if (connect_polygons_) { // remove too small polygons @@ -240,11 +240,11 @@ void Infill::generate( toolpaths, section_type, layer_idx, - scripta::CellVDI{ "is_closed", &ExtrusionLine::is_closed }, - scripta::CellVDI{ "is_odd", &ExtrusionLine::is_odd }, - scripta::CellVDI{ "inset_idx", &ExtrusionLine::inset_idx }, - scripta::PointVDI{ "width", &ExtrusionJunction::w }, - scripta::PointVDI{ "perimeter_index", &ExtrusionJunction::perimeter_index }); + scripta::CellVDI{ "is_closed", &ExtrusionLine::is_closed_ }, + scripta::CellVDI{ "is_odd", &ExtrusionLine::is_odd_ }, + scripta::CellVDI{ "inset_idx", &ExtrusionLine::inset_idx_ }, + scripta::PointVDI{ "width", &ExtrusionJunction::w_ }, + scripta::PointVDI{ "perimeter_index", &ExtrusionJunction::perimeter_index_ }); } } @@ -566,7 +566,7 @@ void Infill::addLineInfill( assert(! connect_lines_ && "connectLines() should add the infill lines, not addLineInfill"); unsigned int scanline_idx = 0; - for (coord_t x = scanline_min_idx * line_distance + shift; x < boundary.max.X; x += line_distance) + for (coord_t x = scanline_min_idx * line_distance + shift; x < boundary.max_.X; x += line_distance) { if (scanline_idx >= cut_list.size()) { @@ -666,8 +666,8 @@ void Infill::generateLinearBasedInfill( AABB boundary(outline); - int scanline_min_idx = computeScanSegmentIdx(boundary.min.X - shift, line_distance); - int line_count = computeScanSegmentIdx(boundary.max.X - shift, line_distance) + 1 - scanline_min_idx; + int scanline_min_idx = computeScanSegmentIdx(boundary.min_.X - shift, line_distance); + int line_count = computeScanSegmentIdx(boundary.max_.X - shift, line_distance) + 1 - scanline_min_idx; std::vector> cut_list(line_count); // mapping from scanline to all intersections with polygon segments @@ -692,8 +692,8 @@ void Infill::generateLinearBasedInfill( } }; std::vector> crossings_per_scanline; // For each scanline, a list of crossings. - const int min_scanline_index = computeScanSegmentIdx(boundary.min.X - shift, line_distance) + 1; - const int max_scanline_index = computeScanSegmentIdx(boundary.max.X - shift, line_distance) + 1; + const int min_scanline_index = computeScanSegmentIdx(boundary.min_.X - shift, line_distance) + 1; + const int max_scanline_index = computeScanSegmentIdx(boundary.max_.X - shift, line_distance) + 1; crossings_per_scanline.resize(max_scanline_index - min_scanline_index); if (connect_lines_) { diff --git a/src/infill/GyroidInfill.cpp b/src/infill/GyroidInfill.cpp index dbabec6f61..253cabdea9 100644 --- a/src/infill/GyroidInfill.cpp +++ b/src/infill/GyroidInfill.cpp @@ -62,14 +62,14 @@ void GyroidInfill::generateTotalGyroidInfill(Polygons& result_lines, bool zig_za } const unsigned num_coords = odd_line_coords.size(); unsigned num_columns = 0; - for (coord_t x = (std::floor(aabb.min.X / pitch) - 2.25) * pitch; x <= aabb.max.X + pitch / 2; x += pitch / 2) + for (coord_t x = (std::floor(aabb.min_.X / pitch) - 2.25) * pitch; x <= aabb.max_.X + pitch / 2; x += pitch / 2) { bool is_first_point = true; Point last; bool last_inside = false; unsigned chain_end_index = 0; Point chain_end[2]; - for (coord_t y = (std::floor(aabb.min.Y / pitch) - 1) * pitch; y <= aabb.max.Y + pitch; y += pitch) + for (coord_t y = (std::floor(aabb.min_.Y / pitch) - 1) * pitch; y <= aabb.max_.Y + pitch; y += pitch) { for (unsigned i = 0; i < num_coords; ++i) { @@ -154,14 +154,14 @@ void GyroidInfill::generateTotalGyroidInfill(Polygons& result_lines, bool zig_za } const unsigned num_coords = odd_line_coords.size(); unsigned num_rows = 0; - for (coord_t y = (std::floor(aabb.min.Y / pitch) - 1) * pitch; y <= aabb.max.Y + pitch / 2; y += pitch / 2) + for (coord_t y = (std::floor(aabb.min_.Y / pitch) - 1) * pitch; y <= aabb.max_.Y + pitch / 2; y += pitch / 2) { bool is_first_point = true; Point last; bool last_inside = false; unsigned chain_end_index = 0; Point chain_end[2]; - for (coord_t x = (std::floor(aabb.min.X / pitch) - 1) * pitch; x <= aabb.max.X + pitch; x += pitch) + for (coord_t x = (std::floor(aabb.min_.X / pitch) - 1) * pitch; x <= aabb.max_.X + pitch; x += pitch) { for (unsigned i = 0; i < num_coords; ++i) { diff --git a/src/infill/ImageBasedDensityProvider.cpp b/src/infill/ImageBasedDensityProvider.cpp index 4d2344e454..2835d05351 100644 --- a/src/infill/ImageBasedDensityProvider.cpp +++ b/src/infill/ImageBasedDensityProvider.cpp @@ -36,7 +36,7 @@ ImageBasedDensityProvider::ImageBasedDensityProvider(const std::string filename, } { // compute aabb Point middle = model_aabb.getMiddle(); - Point model_aabb_size = model_aabb.max - model_aabb.min; + Point model_aabb_size = model_aabb.max_ - model_aabb.min_; Point image_size2 = Point(image_size.x_, image_size.y_); double aabb_aspect_ratio = double(model_aabb_size.X) / double(model_aabb_size.Y); double image_aspect_ratio = double(image_size.x_) / double(image_size.y_); @@ -65,9 +65,9 @@ ImageBasedDensityProvider::~ImageBasedDensityProvider() double ImageBasedDensityProvider::operator()(const AABB3D& query_cube) const { - AABB query_box(Point(query_cube.min.x_, query_cube.min.y_), Point(query_cube.max.x_, query_cube.max.y_)); - Point img_min = (query_box.min - print_aabb.min - Point(1, 1)) * image_size.x_ / (print_aabb.max.X - print_aabb.min.X); - Point img_max = (query_box.max - print_aabb.min + Point(1, 1)) * image_size.y_ / (print_aabb.max.Y - print_aabb.min.Y); + AABB query_box(Point(query_cube.min_.x_, query_cube.min_.y_), Point(query_cube.max_.x_, query_cube.max_.y_)); + Point img_min = (query_box.min_ - print_aabb.min_ - Point(1, 1)) * image_size.x_ / (print_aabb.max_.X - print_aabb.min_.X); + Point img_max = (query_box.max_ - print_aabb.min_ + Point(1, 1)) * image_size.y_ / (print_aabb.max_.Y - print_aabb.min_.Y); long total_lightness = 0; int value_count = 0; for (int x = std::max((coord_t)0, img_min.X); x <= std::min((coord_t)image_size.x_ - 1, img_max.X); x++) diff --git a/src/infill/LightningTreeNode.cpp b/src/infill/LightningTreeNode.cpp index cdde2d374d..3347a2ae63 100644 --- a/src/infill/LightningTreeNode.cpp +++ b/src/infill/LightningTreeNode.cpp @@ -15,7 +15,7 @@ coord_t LightningTreeNode::getWeightedDistance(const Point& unsupported_location constexpr coord_t max_valence_for_boost = 4; constexpr coord_t valence_boost_multiplier = 4; - const size_t valence = (! is_root) + children.size(); + const size_t valence = (! is_root_) + children_.size(); const coord_t valence_boost = (min_valence_for_boost < valence && valence < max_valence_for_boost) ? valence_boost_multiplier * supporting_radius : 0; const coord_t dist_here = vSize(getLocation() - unsupported_location); return dist_here - valence_boost; @@ -27,7 +27,7 @@ bool LightningTreeNode::hasOffspring(const LightningTreeNodeSPtr& to_be_checked) { return true; } - for (auto& child_ptr : children) + for (auto& child_ptr : children_) { if (child_ptr->hasOffspring(to_be_checked)) return true; @@ -37,17 +37,17 @@ bool LightningTreeNode::hasOffspring(const LightningTreeNodeSPtr& to_be_checked) const Point& LightningTreeNode::getLocation() const { - return p; + return p_; } void LightningTreeNode::setLocation(const Point& loc) { - p = loc; + p_ = loc; } LightningTreeNodeSPtr LightningTreeNode::addChild(const Point& child_loc) { - assert(p != child_loc); + assert(p_ != child_loc); LightningTreeNodeSPtr child = LightningTreeNode::create(child_loc); return addChild(child); } @@ -56,9 +56,9 @@ LightningTreeNodeSPtr LightningTreeNode::addChild(LightningTreeNodeSPtr& new_chi { assert(new_child != shared_from_this()); // assert(p != new_child->p); // NOTE: No problem for now. Issue to solve later. Maybe even afetr final. Low prio. - children.push_back(new_child); - new_child->parent = shared_from_this(); - new_child->is_root = false; + children_.push_back(new_child); + new_child->parent_ = shared_from_this(); + new_child->is_root_ = false; return new_child; } @@ -84,10 +84,10 @@ void LightningTreeNode::propagateToNextLayer( // Skips the root (because that has no root itself), but all initial nodes will have the root point anyway. void LightningTreeNode::visitBranches(const std::function& visitor) const { - for (const auto& node : children) + for (const auto& node : children_) { - assert(node->parent.lock() == shared_from_this()); - visitor(p, node->p); + assert(node->parent_.lock() == shared_from_this()); + visitor(p_, node->p_); node->visitBranches(visitor); } } @@ -96,69 +96,69 @@ void LightningTreeNode::visitBranches(const std::function& visitor) { visitor(shared_from_this()); - for (const auto& node : children) + for (const auto& node : children_) { - assert(node->parent.lock() == shared_from_this()); + assert(node->parent_.lock() == shared_from_this()); node->visitNodes(visitor); } } LightningTreeNode::LightningTreeNode(const Point& p, const std::optional& last_grounding_location /*= std::nullopt*/) - : is_root(true) - , p(p) - , last_grounding_location(last_grounding_location) + : is_root_(true) + , p_(p) + , last_grounding_location_(last_grounding_location) { } LightningTreeNodeSPtr LightningTreeNode::deepCopy() const { - LightningTreeNodeSPtr local_root = LightningTreeNode::create(p); - local_root->is_root = is_root; - if (is_root) + LightningTreeNodeSPtr local_root = LightningTreeNode::create(p_); + local_root->is_root_ = is_root_; + if (is_root_) { - local_root->last_grounding_location = last_grounding_location.value_or(p); + local_root->last_grounding_location_ = last_grounding_location_.value_or(p_); } - local_root->children.reserve(children.size()); - for (const auto& node : children) + local_root->children_.reserve(children_.size()); + for (const auto& node : children_) { LightningTreeNodeSPtr child = node->deepCopy(); - child->parent = local_root; - local_root->children.push_back(child); + child->parent_ = local_root; + local_root->children_.push_back(child); } return local_root; } void LightningTreeNode::reroot(LightningTreeNodeSPtr new_parent /*= nullptr*/) { - if (! is_root) + if (! is_root_) { - auto old_parent = parent.lock(); + auto old_parent = parent_.lock(); old_parent->reroot(shared_from_this()); - children.push_back(old_parent); + children_.push_back(old_parent); } if (new_parent) { - children.erase(std::remove(children.begin(), children.end(), new_parent), children.end()); - is_root = false; - parent = new_parent; + children_.erase(std::remove(children_.begin(), children_.end(), new_parent), children_.end()); + is_root_ = false; + parent_ = new_parent; } else { - is_root = true; - parent.reset(); + is_root_ = true; + parent_.reset(); } } LightningTreeNodeSPtr LightningTreeNode::closestNode(const Point& loc) { LightningTreeNodeSPtr result = shared_from_this(); - coord_t closest_dist2 = vSize2(p - loc); + coord_t closest_dist2 = vSize2(p_ - loc); - for (const auto& child : children) + for (const auto& child : children_) { LightningTreeNodeSPtr candidate_node = child->closestNode(loc); - const coord_t child_dist2 = vSize2(candidate_node->p - loc); + const coord_t child_dist2 = vSize2(candidate_node->p_ - loc); if (child_dist2 < closest_dist2) { closest_dist2 = child_dist2; @@ -176,7 +176,7 @@ bool LightningTreeNode::realign(const Polygons& outlines, const LocToLineGrid& o return false; } - if (outlines.inside(p, true)) + if (outlines.inside(p_, true)) { // Only keep children that have an unbroken connection to here, realign will put the rest in rerooted parts due to recursion: Point coll; @@ -185,11 +185,11 @@ bool LightningTreeNode::realign(const Polygons& outlines, const LocToLineGrid& o [&](const LightningTreeNodeSPtr& child) { bool connect_branch = child->realign(outlines, outline_locator, rerooted_parts); - if (connect_branch && PolygonUtils::lineSegmentPolygonsIntersection(child->p, p, outlines, outline_locator, coll, outline_locator.getCellSize() * 2)) + if (connect_branch && PolygonUtils::lineSegmentPolygonsIntersection(child->p_, p_, outlines, outline_locator, coll, outline_locator.getCellSize() * 2)) { - child->last_grounding_location.reset(); - child->parent.reset(); - child->is_root = true; + child->last_grounding_location_.reset(); + child->parent_.reset(); + child->is_root_ = true; rerooted_parts.push_back(child); reground_me = true; @@ -198,33 +198,33 @@ bool LightningTreeNode::realign(const Polygons& outlines, const LocToLineGrid& o return ! connect_branch; } }; - children.erase(std::remove_if(children.begin(), children.end(), remove_unconnected_func), children.end()); + children_.erase(std::remove_if(children_.begin(), children_.end(), remove_unconnected_func), children_.end()); if (reground_me) { - last_grounding_location.reset(); + last_grounding_location_.reset(); } return true; } // 'Lift' any decendants out of this tree: - for (auto& child : children) + for (auto& child : children_) { if (child->realign(outlines, outline_locator, rerooted_parts)) { - child->last_grounding_location = p; - child->parent.reset(); - child->is_root = true; + child->last_grounding_location_ = p_; + child->parent_.reset(); + child->is_root_ = true; rerooted_parts.push_back(child); } } - children.clear(); + children_.clear(); return false; } void LightningTreeNode::straighten(const coord_t magnitude, const coord_t max_remove_colinear_dist) { - straighten(magnitude, p, 0, max_remove_colinear_dist * max_remove_colinear_dist); + straighten(magnitude, p_, 0, max_remove_colinear_dist * max_remove_colinear_dist); } LightningTreeNode::RectilinearJunction @@ -234,10 +234,10 @@ LightningTreeNode::RectilinearJunction constexpr coord_t junction_magnitude_factor_denominator = 4; const coord_t junction_magnitude = magnitude * junction_magnitude_factor_numerator / junction_magnitude_factor_denominator; - if (children.size() == 1) + if (children_.size() == 1) { - auto child_p = children.front(); - coord_t child_dist = vSize(p - child_p->p); + auto child_p = children_.front(); + coord_t child_dist = vSize(p_ - child_p->p_); RectilinearJunction junction_below = child_p->straighten(magnitude, junction_above, accumulated_dist + child_dist, max_remove_colinear_dist2); coord_t total_dist_to_junction_below = junction_below.total_recti_dist; Point a = junction_above; @@ -246,25 +246,25 @@ LightningTreeNode::RectilinearJunction { Point ab = b - a; Point destination = a + ab * accumulated_dist / std::max(coord_t(1), total_dist_to_junction_below); - if (shorterThen(destination - p, magnitude)) + if (shorterThen(destination - p_, magnitude)) { - p = destination; + p_ = destination; } else { - p = p + normal(destination - p, magnitude); + p_ = p_ + normal(destination - p_, magnitude); } } { // remove nodes on linear segments constexpr coord_t close_enough = 10; - child_p = children.front(); // recursive call to straighten might have removed the child - const LightningTreeNodeSPtr& parent_node = parent.lock(); - if (parent_node && vSize2(child_p->p - parent_node->p) < max_remove_colinear_dist2 - && LinearAlg2D::getDist2FromLineSegment(parent_node->p, p, child_p->p) < close_enough) + child_p = children_.front(); // recursive call to straighten might have removed the child + const LightningTreeNodeSPtr& parent_node = parent_.lock(); + if (parent_node && vSize2(child_p->p_ - parent_node->p_) < max_remove_colinear_dist2 + && LinearAlg2D::getDist2FromLineSegment(parent_node->p_, p_, child_p->p_) < close_enough) { - child_p->parent = parent; - for (auto& sibling : parent_node->children) + child_p->parent_ = parent_; + for (auto& sibling : parent_node->children_) { // find this node among siblings if (sibling == shared_from_this()) { @@ -279,29 +279,29 @@ LightningTreeNode::RectilinearJunction else { constexpr coord_t weight = 1000; - Point junction_moving_dir = normal(junction_above - p, weight); + Point junction_moving_dir = normal(junction_above - p_, weight); bool prevent_junction_moving = false; - for (auto& child_p : children) + for (auto& child_p : children_) { - const coord_t child_dist = vSize(p - child_p->p); - RectilinearJunction below = child_p->straighten(magnitude, p, child_dist, max_remove_colinear_dist2); + const coord_t child_dist = vSize(p_ - child_p->p_); + RectilinearJunction below = child_p->straighten(magnitude, p_, child_dist, max_remove_colinear_dist2); - junction_moving_dir += normal(below.junction_loc - p, weight); + junction_moving_dir += normal(below.junction_loc - p_, weight); if (below.total_recti_dist < magnitude) // TODO: make configurable? { prevent_junction_moving = true; // prevent flipflopping in branches due to straightening and junctoin moving clashing } } - if (junction_moving_dir != Point(0, 0) && ! children.empty() && ! is_root && ! prevent_junction_moving) + if (junction_moving_dir != Point(0, 0) && ! children_.empty() && ! is_root_ && ! prevent_junction_moving) { coord_t junction_moving_dir_len = vSize(junction_moving_dir); if (junction_moving_dir_len > junction_magnitude) { junction_moving_dir = junction_moving_dir * junction_magnitude / junction_moving_dir_len; } - p += junction_moving_dir; + p_ += junction_moving_dir; } - return RectilinearJunction{ accumulated_dist, p }; + return RectilinearJunction{ accumulated_dist, p_ }; } } @@ -314,7 +314,7 @@ coord_t LightningTreeNode::prune(const coord_t& pruning_distance) } coord_t max_distance_pruned = 0; - for (auto child_it = children.begin(); child_it != children.end();) + for (auto child_it = children_.begin(); child_it != children_.end();) { auto& child = *child_it; coord_t dist_pruned_child = child->prune(pruning_distance); @@ -331,9 +331,9 @@ coord_t LightningTreeNode::prune(const coord_t& pruning_distance) const coord_t ab_len = vSize(ba); if (dist_pruned_child + ab_len <= pruning_distance) { // we're still in the process of pruning - assert(child->children.empty() && "when pruning away a node all it's children must already have been pruned away"); + assert(child->children_.empty() && "when pruning away a node all it's children must already have been pruned away"); max_distance_pruned = std::max(max_distance_pruned, dist_pruned_child + ab_len); - child_it = children.erase(child_it); + child_it = children_.erase(child_it); } else { // pruning stops in between this node and the child @@ -351,7 +351,7 @@ coord_t LightningTreeNode::prune(const coord_t& pruning_distance) const std::optional& LightningTreeNode::getLastGroundingLocation() const { - return last_grounding_location; + return last_grounding_location_; } void LightningTreeNode::convertToPolylines(Polygons& output, const coord_t line_width) const @@ -365,23 +365,23 @@ void LightningTreeNode::convertToPolylines(Polygons& output, const coord_t line_ void LightningTreeNode::convertToPolylines(size_t long_line_idx, Polygons& output) const { - if (children.empty()) + if (children_.empty()) { - output[long_line_idx].add(p); + output[long_line_idx].add(p_); return; } - size_t first_child_idx = rand() % children.size(); - children[first_child_idx]->convertToPolylines(long_line_idx, output); - output[long_line_idx].add(p); + size_t first_child_idx = rand() % children_.size(); + children_[first_child_idx]->convertToPolylines(long_line_idx, output); + output[long_line_idx].add(p_); - for (size_t idx_offset = 1; idx_offset < children.size(); idx_offset++) + for (size_t idx_offset = 1; idx_offset < children_.size(); idx_offset++) { - size_t child_idx = (first_child_idx + idx_offset) % children.size(); - const LightningTreeNode& child = *children[child_idx]; + size_t child_idx = (first_child_idx + idx_offset) % children_.size(); + const LightningTreeNode& child = *children_[child_idx]; output.newPoly(); size_t child_line_idx = output.size() - 1; child.convertToPolylines(child_line_idx, output); - output[child_line_idx].add(p); + output[child_line_idx].add(p_); } } diff --git a/src/infill/SierpinskiFill.cpp b/src/infill/SierpinskiFill.cpp index b3a15b3b46..b1dc6f545a 100644 --- a/src/infill/SierpinskiFill.cpp +++ b/src/infill/SierpinskiFill.cpp @@ -27,18 +27,18 @@ static constexpr double allowed_length_error = 0.01; static constexpr bool deep_debug_checking = false; SierpinskiFill::SierpinskiFill(const DensityProvider& density_provider, const AABB aabb, int max_depth, const coord_t line_width, bool dithering) - : dithering(dithering) - , constraint_error_diffusion(dithering) - , density_provider(density_provider) - , aabb(aabb) - , line_width(line_width) - , max_depth(max_depth) + : dithering_(dithering) + , constraint_error_diffusion_(dithering) + , density_provider_(density_provider) + , aabb_(aabb) + , line_width_(line_width) + , max_depth_(max_depth) { createTree(); createLowerBoundSequence(); - for (SierpinskiTriangle* node : sequence) + for (SierpinskiTriangle* node : sequence_) { if (node->getValueError() < -allowed_length_error) { @@ -66,27 +66,27 @@ SierpinskiFill::~SierpinskiFill() void SierpinskiFill::createTree() { - Point lt = Point(aabb.min.X, aabb.max.Y); - Point rb = Point(aabb.max.X, aabb.min.Y); + Point lt = Point(aabb_.min_.X, aabb_.max_.Y); + Point rb = Point(aabb_.max_.X, aabb_.min_.Y); bool root_straight_corner_is_left = false; int root_depth = 1; - root.children.emplace_back(rb, aabb.min, aabb.max, SierpinskiTriangle::SierpinskiDirection::AC_TO_AB, root_straight_corner_is_left, root_depth); - root.children.emplace_back(lt, aabb.max, aabb.min, SierpinskiTriangle::SierpinskiDirection::AC_TO_AB, root_straight_corner_is_left, root_depth); - for (SierpinskiTriangle& triangle : root.children) + root_.children.emplace_back(rb, aabb_.min_, aabb_.max_, SierpinskiTriangle::SierpinskiDirection::AC_TO_AB, root_straight_corner_is_left, root_depth); + root_.children.emplace_back(lt, aabb_.max_, aabb_.min_, SierpinskiTriangle::SierpinskiDirection::AC_TO_AB, root_straight_corner_is_left, root_depth); + for (SierpinskiTriangle& triangle : root_.children) { createTree(triangle); } // calculate node statistics - createTreeStatistics(root); + createTreeStatistics(root_); - createTreeRequestedLengths(root); + createTreeRequestedLengths(root_); } void SierpinskiFill::createTree(SierpinskiTriangle& sub_root) { - if (sub_root.depth_ < max_depth) // We need to subdivide. + if (sub_root.depth_ < max_depth_) // We need to subdivide. { SierpinskiTriangle& t = sub_root; Point middle = (t.a_ + t.b_) / 2; @@ -140,9 +140,9 @@ void SierpinskiFill::createTreeRequestedLengths(SierpinskiTriangle& triangle) triangle_aabb.include(triangle.a_); triangle_aabb.include(triangle.b_); triangle_aabb.include(triangle.straight_corner_); - AABB3D triangle_aabb3d(Point3(triangle_aabb.min.X, triangle_aabb.min.Y, 0), Point3(triangle_aabb.max.X, triangle_aabb.max.Y, 1)); - double density = density_provider(triangle_aabb3d); // The density of the square around the triangle is a rough estimate of the density of the triangle. - triangle.requested_length_ = density * triangle.area_ / INT2MM(line_width); + AABB3D triangle_aabb3d(Point3(triangle_aabb.min_.X, triangle_aabb.min_.Y, 0), Point3(triangle_aabb.max_.X, triangle_aabb.max_.Y, 1)); + double density = density_provider_(triangle_aabb3d); // The density of the square around the triangle is a rough estimate of the density of the triangle. + triangle.requested_length_ = density * triangle.area_ / INT2MM(line_width_); } else { // bubble total up requested_length and total_child_realized_length @@ -158,7 +158,7 @@ void SierpinskiFill::createTreeRequestedLengths(SierpinskiTriangle& triangle) void SierpinskiFill::createLowerBoundSequence() { - sequence.emplace_front(&root); + sequence_.emplace_front(&root_); if (deep_debug_checking) debugCheck(); @@ -169,7 +169,7 @@ void SierpinskiFill::createLowerBoundSequence() if (deep_debug_checking) debugCheck(); - if (constraint_error_diffusion) + if (constraint_error_diffusion_) { change |= bubbleUpConstraintErrors(); if (deep_debug_checking) @@ -178,7 +178,7 @@ void SierpinskiFill::createLowerBoundSequence() if (! change) { - spdlog::debug("Finished after {} iterations, with a max depth of {}.", iteration + 1, max_depth); + spdlog::debug("Finished after {} iterations, with a max depth of {}.", iteration + 1, max_depth_); break; } } @@ -186,9 +186,9 @@ void SierpinskiFill::createLowerBoundSequence() std::vector::iterator>> SierpinskiFill::getDepthOrdered() { - std::vector::iterator>> depth_ordered(max_depth + 1); - depth_ordered.resize(max_depth); - for (std::list::iterator it = sequence.begin(); it != sequence.end(); ++it) + std::vector::iterator>> depth_ordered(max_depth_ + 1); + depth_ordered.resize(max_depth_); + for (std::list::iterator it = sequence_.begin(); it != sequence_.end(); ++it) { SierpinskiTriangle* node = *it; depth_ordered[node->depth_].emplace_back(it); @@ -212,11 +212,11 @@ bool SierpinskiFill::subdivideAll() // so then the range will be two long rather than one. std::list::iterator begin = it; std::list::iterator end = std::next(it); - if (triangle.dir_ == SierpinskiTriangle::SierpinskiDirection::AC_TO_AB && end != sequence.end()) + if (triangle.dir_ == SierpinskiTriangle::SierpinskiDirection::AC_TO_AB && end != sequence_.end()) { continue; // don't subdivide these two triangles just yet, wait till next iteration } - if (triangle.dir_ == SierpinskiTriangle::SierpinskiDirection::AB_TO_BC && begin != sequence.begin()) + if (triangle.dir_ == SierpinskiTriangle::SierpinskiDirection::AB_TO_BC && begin != sequence_.begin()) { begin = std::prev(it); assert((*begin)->depth_ == triangle.depth_ || isConstrainedBackward(it)); @@ -229,7 +229,7 @@ bool SierpinskiFill::subdivideAll() // Don't check for constraining in between the cells in the range; // the range is defined as the range of triangles which are constraining each other simultaneously. - if (node->depth_ == max_depth) // Never subdivide beyond maximum depth. + if (node->depth_ == max_depth_) // Never subdivide beyond maximum depth. continue; double total_subdiv_error = getSubdivisionError(begin, end); if (! node->children.empty() && total_subdiv_error >= 0 && ! is_constrained) @@ -248,7 +248,7 @@ bool SierpinskiFill::bubbleUpConstraintErrors() bool redistributed_anything = false; - for (int depth = max_depth; depth >= 0; depth--) + for (int depth = max_depth_; depth >= 0; depth--) { std::vector::iterator>& depth_nodes = depth_ordered[depth]; for (std::list::iterator it : depth_nodes) @@ -323,13 +323,13 @@ std::list::iterator assert(! node->children.empty() && "cannot subdivide node with no children!"); for (SierpinskiTriangle& child : node->children) { - sequence.insert(begin, &child); + sequence_.insert(begin, &child); } } first_child_it++; // removal of parents std::list::iterator last_child_it = std::prev(begin); - sequence.erase(begin, end); + sequence_.erase(begin, end); if (redistribute_errors && deep_debug_checking) debugCheck(false); @@ -357,19 +357,19 @@ void SierpinskiFill::redistributeLeftoverErrors(std::list:: for (auto it = begin; it != end && std::next(it) != end; ++it) { SierpinskiTriangle* node = *it; - SierpinskiTriangle* next = *std::next(it); - if (std::abs(node->error_right_ + next->error_left_) > allowed_length_error) + SierpinskiTriangle* other = *std::next(it); + if (std::abs(node->error_right_ + other->error_left_) > allowed_length_error) { - spdlog::warn("Nodes aren't balanced! er: {} next el: {}", node->error_right_, next->error_left_); + spdlog::warn("Nodes aren't balanced! er: {} other el: {}", node->error_right_, other->error_left_); assert(false); } double exchange = node->error_right_; - if (node->error_right_ < next->error_left_) + if (node->error_right_ < other->error_left_) { exchange *= -1; } node->error_right_ -= exchange; - next->error_left_ += exchange; + other->error_left_ += exchange; } double total_superfluous_error = 0; @@ -387,7 +387,7 @@ void SierpinskiFill::redistributeLeftoverErrors(std::list:: } return; } - if (begin != sequence.begin() && end != sequence.end() && first->error_left_ > allowed_length_error && last->error_right_ > allowed_length_error) + if (begin != sequence_.begin() && end != sequence_.end() && first->error_left_ > allowed_length_error && last->error_right_ > allowed_length_error) { double total_error_input = first->error_left_ + last->error_right_; total_superfluous_error = std::min(total_superfluous_error, total_error_input); // total superfluous error cannot be more than the influx of error @@ -398,14 +398,14 @@ void SierpinskiFill::redistributeLeftoverErrors(std::list:: (*std::prev(end))->error_right_ -= right_spillover; next->error_left_ += right_spillover; } - else if (begin != sequence.begin() && first->error_left_ > allowed_length_error) + else if (begin != sequence_.begin() && first->error_left_ > allowed_length_error) { total_superfluous_error = std::min(total_superfluous_error, first->error_left_); // total superfluous error cannot be more than the influx of error (*begin)->error_left_ -= total_superfluous_error; prev->error_right_ += total_superfluous_error; assert(first->error_left_ > -allowed_length_error); } - else if (end != sequence.end() && last->error_right_ > allowed_length_error) + else if (end != sequence_.end() && last->error_right_ > allowed_length_error) { total_superfluous_error = std::min(total_superfluous_error, last->error_right_); // total superfluous error cannot be more than the influx of error last->error_right_ -= total_superfluous_error; @@ -532,24 +532,24 @@ void SierpinskiFill::diffuseError() int unconstrained_nodes = 0; int subdivided_nodes = 0; double error = 0; - for (std::list::iterator it = sequence.begin(); it != sequence.end(); ++it) + for (std::list::iterator it = sequence_.begin(); it != sequence_.end(); ++it) { SierpinskiTriangle& triangle = *(*it); double boundary = (triangle.realized_length_ + triangle.total_child_realized_length_) * 0.5; - double nodal_value = ((use_errors_in_dithering) ? triangle.getErroredValue() : triangle.requested_length_); + double nodal_value = ((use_errors_in_dithering_) ? triangle.getErroredValue() : triangle.requested_length_); double boundary_error = nodal_value - boundary + error; std::list::iterator begin = it; std::list::iterator end = std::next(it); - if (triangle.dir_ == SierpinskiTriangle::SierpinskiDirection::AC_TO_AB && end != sequence.end()) + if (triangle.dir_ == SierpinskiTriangle::SierpinskiDirection::AC_TO_AB && end != sequence_.end()) { pair_constrained_nodes++; continue; // don't subdivide these two triangles just yet, wait till next iteration } - if (triangle.dir_ == SierpinskiTriangle::SierpinskiDirection::AB_TO_BC && begin != sequence.begin()) + if (triangle.dir_ == SierpinskiTriangle::SierpinskiDirection::AB_TO_BC && begin != sequence_.begin()) { begin = std::prev(it); assert((*begin)->depth_ == triangle.depth_ || isConstrainedBackward(it)); @@ -572,12 +572,12 @@ void SierpinskiFill::diffuseError() { subdivided_nodes++; it = subdivide(begin, end, false); - if (dithering) + if (dithering_) error += nodal_value - triangle.total_child_realized_length_; } else { - if (dithering) + if (dithering_) error += nodal_value - triangle.realized_length_; } } @@ -593,7 +593,7 @@ bool SierpinskiFill::isConstrainedBackward(std::list::itera { SierpinskiTriangle* node = *it; SierpinskiTriangle* prev = *std::prev(it); - if (it != sequence.begin() && node->dir_ == SierpinskiTriangle::SierpinskiDirection::AB_TO_BC && prev->depth_ < node->depth_) + if (it != sequence_.begin() && node->dir_ == SierpinskiTriangle::SierpinskiDirection::AB_TO_BC && prev->depth_ < node->depth_) return true; return false; } @@ -601,7 +601,7 @@ bool SierpinskiFill::isConstrainedForward(std::list::iterat { SierpinskiTriangle* node = *it; SierpinskiTriangle* next = *std::next(it); - if (std::next(it) != sequence.end() && node->dir_ == SierpinskiTriangle::SierpinskiDirection::AC_TO_AB && next->depth_ < node->depth_) + if (std::next(it) != sequence_.end() && node->dir_ == SierpinskiTriangle::SierpinskiDirection::AC_TO_AB && next->depth_ < node->depth_) return true; return false; } @@ -620,10 +620,10 @@ double SierpinskiFill::getSubdivisionError(std::list::itera void SierpinskiFill::debugOutput(SVG& svg) { - svg.writePolygon(aabb.toPolygon(), SVG::Color::RED); + svg.writePolygon(aabb_.toPolygon(), SVG::Color::RED); // draw triangles - for (SierpinskiTriangle* node : sequence) + for (SierpinskiTriangle* node : sequence_) { SierpinskiTriangle& triangle = *node; svg.writeLine(triangle.a_, triangle.b_, SVG::Color::GRAY); @@ -702,7 +702,7 @@ Polygon SierpinskiFill::generateCross() const { Polygon ret; - for (SierpinskiTriangle* max_level_it : sequence) + for (SierpinskiTriangle* max_level_it : sequence_) { SierpinskiTriangle& triangle = *max_level_it; Point edge_middle = triangle.a_ + triangle.b_ + triangle.straight_corner_; @@ -722,7 +722,7 @@ Polygon SierpinskiFill::generateCross() const } double realized_length = INT2MM(ret.polygonLength()); - double requested_length = root.requested_length_; + double requested_length = root_.requested_length_; double error = (realized_length - requested_length) / requested_length; spdlog::debug("realized_length: {}, requested_length: {} :: {}% error", realized_length, requested_length, 0.01 * static_cast(10000 * error)); return ret; @@ -746,7 +746,7 @@ Polygon SierpinskiFill::generateCross(coord_t z, coord_t min_dist_to_side, coord }; SierpinskiTriangle* last_triangle = nullptr; - for (SierpinskiTriangle* node : sequence) + for (SierpinskiTriangle* node : sequence_) { SierpinskiTriangle& triangle = *node; @@ -813,20 +813,20 @@ Polygon SierpinskiFill::generateCross(coord_t z, coord_t min_dist_to_side, coord void SierpinskiFill::debugCheck(bool check_subdivision) { - if (std::abs(sequence.front()->error_left_) > allowed_length_error) + if (std::abs(sequence_.front()->error_left_) > allowed_length_error) { spdlog::warn("First node has error left!"); assert(false); } - if (std::abs(sequence.back()->error_right_) > allowed_length_error) + if (std::abs(sequence_.back()->error_right_) > allowed_length_error) { spdlog::warn("Last node has error right!"); assert(false); } - for (auto it = sequence.begin(); it != sequence.end(); ++it) + for (auto it = sequence_.begin(); it != sequence_.end(); ++it) { - if (std::next(it) == sequence.end()) + if (std::next(it) == sequence_.end()) { break; } diff --git a/src/infill/SierpinskiFillProvider.cpp b/src/infill/SierpinskiFillProvider.cpp index 2668641842..17b27068bf 100644 --- a/src/infill/SierpinskiFillProvider.cpp +++ b/src/infill/SierpinskiFillProvider.cpp @@ -65,7 +65,7 @@ SierpinskiFillProvider::~SierpinskiFillProvider() SierpinskiFillProvider::FractalConfig SierpinskiFillProvider::getFractalConfig(const AABB3D aabb_3d, coord_t min_line_distance) { AABB model_aabb = aabb_3d.flatten(); - Point model_aabb_size = model_aabb.max - model_aabb.min; + Point model_aabb_size = model_aabb.max_ - model_aabb.min_; coord_t max_side_length = std::max(model_aabb_size.X, model_aabb_size.Y); Point model_middle = model_aabb.getMiddle(); diff --git a/src/infill/SubDivCube.cpp b/src/infill/SubDivCube.cpp index 1d35ba0140..6f3a3873fb 100644 --- a/src/infill/SubDivCube.cpp +++ b/src/infill/SubDivCube.cpp @@ -18,14 +18,14 @@ namespace cura { -std::vector SubDivCube::cube_properties_per_recursion_step; -coord_t SubDivCube::radius_addition = 0; -Point3Matrix SubDivCube::rotation_matrix; -PointMatrix SubDivCube::infill_rotation_matrix; +std::vector SubDivCube::cube_properties_per_recursion_step_; +coord_t SubDivCube::radius_addition_ = 0; +Point3Matrix SubDivCube::rotation_matrix_; +PointMatrix SubDivCube::infill_rotation_matrix_; void SubDivCube::precomputeOctree(SliceMeshStorage& mesh, const Point& infill_origin) { - radius_addition = mesh.settings.get("sub_div_rad_add"); + radius_addition_ = mesh.settings.get("sub_div_rad_add"); // if infill_angles is not empty use the first value, otherwise use 0 const std::vector infill_angles = mesh.settings.get>("infill_angles"); @@ -41,8 +41,8 @@ void SubDivCube::precomputeOctree(SliceMeshStorage& mesh, const Point& infill_or { for (coord_t curr_side_length = infill_line_distance * 2; curr_side_length < max_side_length * 2; curr_side_length *= 2) { - cube_properties_per_recursion_step.emplace_back(); - CubeProperties& cube_properties_here = cube_properties_per_recursion_step.back(); + cube_properties_per_recursion_step_.emplace_back(); + CubeProperties& cube_properties_here = cube_properties_per_recursion_step_.back(); cube_properties_here.side_length = curr_side_length; cube_properties_here.height = sqrt(3) * curr_side_length; cube_properties_here.square_height = sqrt(2) * curr_side_length; @@ -75,17 +75,17 @@ void SubDivCube::precomputeOctree(SliceMeshStorage& mesh, const Point& infill_or tilt.matrix[7] = ONE_OVER_SQRT_3; tilt.matrix[8] = ONE_OVER_SQRT_3; - infill_rotation_matrix = PointMatrix(infill_angle); - Point3Matrix infill_angle_mat(infill_rotation_matrix); + infill_rotation_matrix_ = PointMatrix(infill_angle); + Point3Matrix infill_angle_mat(infill_rotation_matrix_); - rotation_matrix = infill_angle_mat.compose(tilt); + rotation_matrix_ = infill_angle_mat.compose(tilt); mesh.base_subdiv_cube = std::make_shared(mesh, center, curr_recursion_depth - 1); } void SubDivCube::generateSubdivisionLines(const coord_t z, Polygons& result) { - if (cube_properties_per_recursion_step.empty()) // Infill is set to 0%. + if (cube_properties_per_recursion_step_.empty()) // Infill is set to 0%. { return; } @@ -105,9 +105,9 @@ void SubDivCube::generateSubdivisionLines(const coord_t z, Polygons& result) void SubDivCube::generateSubdivisionLines(const coord_t z, Polygons (&directional_line_groups)[3]) { - CubeProperties cube_properties = cube_properties_per_recursion_step[depth]; + CubeProperties cube_properties = cube_properties_per_recursion_step_[depth_]; - const coord_t z_diff = std::abs(z - center.z_); //!< the difference between the cube center and the target layer. + const coord_t z_diff = std::abs(z - center_.z_); //!< the difference between the cube center and the target layer. if (z_diff > cube_properties.height / 2) //!< this cube does not touch the target layer. Early exit. { return; @@ -118,16 +118,16 @@ void SubDivCube::generateSubdivisionLines(const coord_t z, Polygons (&directiona Point a, b; //!< absolute coordinates of line endpoints relative_a.X = (cube_properties.square_height / 2) * (cube_properties.max_draw_z_diff - z_diff) / cube_properties.max_draw_z_diff; relative_b.X = -relative_a.X; - relative_a.Y = cube_properties.max_line_offset - ((z - (center.z_ - cube_properties.max_draw_z_diff)) * ONE_OVER_SQRT_2); + relative_a.Y = cube_properties.max_line_offset - ((z - (center_.z_ - cube_properties.max_draw_z_diff)) * ONE_OVER_SQRT_2); relative_b.Y = relative_a.Y; rotatePointInitial(relative_a); rotatePointInitial(relative_b); for (int dir_idx = 0; dir_idx < 3; dir_idx++) //!< draw the line, then rotate 120 degrees. { - a.X = center.x_ + relative_a.X; - a.Y = center.y_ + relative_a.Y; - b.X = center.x_ + relative_b.X; - b.Y = center.y_ + relative_b.Y; + a.X = center_.x_ + relative_a.X; + a.Y = center_.y_ + relative_a.Y; + b.X = center_.x_ + relative_b.X; + b.Y = center_.y_ + relative_b.Y; addLineAndCombine(directional_line_groups[dir_idx], a, b); if (dir_idx < 2) { @@ -138,30 +138,29 @@ void SubDivCube::generateSubdivisionLines(const coord_t z, Polygons (&directiona } for (int idx = 0; idx < 8; idx++) //!< draws the eight children { - if (children[idx] != nullptr) + if (children_[idx] != nullptr) { - children[idx]->generateSubdivisionLines(z, directional_line_groups); + children_[idx]->generateSubdivisionLines(z, directional_line_groups); } } } SubDivCube::SubDivCube(SliceMeshStorage& mesh, Point3& center, size_t depth) + : depth_(depth) + , center_(center) { - this->depth = depth; - this->center = center; - - if (depth == 0) // lowest layer, no need for subdivision, exit. + if (depth_ == 0) // lowest layer, no need for subdivision, exit. { return; } - if (depth >= cube_properties_per_recursion_step.size()) // Depth is out of bounds of what we pre-computed. + if (depth_ >= cube_properties_per_recursion_step_.size()) // Depth is out of bounds of what we pre-computed. { return; } - CubeProperties cube_properties = cube_properties_per_recursion_step[depth]; + CubeProperties cube_properties = cube_properties_per_recursion_step_[depth]; Point3 child_center; - coord_t radius = double(cube_properties.height) / 4.0 + radius_addition; + coord_t radius = double(cube_properties.height) / 4.0 + radius_addition_; int child_nr = 0; std::vector rel_child_centers; @@ -175,10 +174,10 @@ SubDivCube::SubDivCube(SliceMeshStorage& mesh, Point3& center, size_t depth) rel_child_centers.emplace_back(-1, -1, 1); for (Point3 rel_child_center : rel_child_centers) { - child_center = center + rotation_matrix.apply(rel_child_center * int32_t(cube_properties.side_length / 4)); + child_center = center + rotation_matrix_.apply(rel_child_center * int32_t(cube_properties.side_length / 4)); if (isValidSubdivision(mesh, child_center, radius)) { - children[child_nr] = std::make_shared(mesh, child_center, depth - 1); + children_[child_nr] = std::make_shared(mesh, child_center, depth - 1); child_nr++; } } @@ -250,7 +249,7 @@ coord_t SubDivCube::distanceFromPointToMesh(SliceMeshStorage& mesh, const LayerI void SubDivCube::rotatePointInitial(Point& target) { - target = infill_rotation_matrix.apply(target); + target = infill_rotation_matrix_.apply(target); } void SubDivCube::rotatePoint120(Point& target) diff --git a/src/mesh.cpp b/src/mesh.cpp index 377e72c69a..8224fbfc2f 100644 --- a/src/mesh.cpp +++ b/src/mesh.cpp @@ -79,11 +79,11 @@ void Mesh::finish() Point3 Mesh::min() const { - return aabb_.min; + return aabb_.min_; } Point3 Mesh::max() const { - return aabb_.max; + return aabb_.max_; } AABB3D Mesh::getAABB() const { @@ -103,8 +103,8 @@ void Mesh::transform(const Matrix4x3D& transformation) { v.p_ = transformation.apply(v.p_); } - aabb_.min = transformation.apply(aabb_.min); - aabb_.max = transformation.apply(aabb_.max); + aabb_.min_ = transformation.apply(aabb_.min_); + aabb_.max_ = transformation.apply(aabb_.max_); } diff --git a/src/pathPlanning/Comb.cpp b/src/pathPlanning/Comb.cpp index 328ec18b97..7da890d3d9 100644 --- a/src/pathPlanning/Comb.cpp +++ b/src/pathPlanning/Comb.cpp @@ -22,40 +22,40 @@ namespace cura LocToLineGrid& Comb::getOutsideLocToLine(const ExtruderTrain& train) { - if (outside_loc_to_line[train.extruder_nr_] == nullptr) + if (outside_loc_to_line_[train.extruder_nr_] == nullptr) { - outside_loc_to_line[train.extruder_nr_] = PolygonUtils::createLocToLineGrid(getBoundaryOutside(train), offset_from_inside_to_outside * 3 / 2); + outside_loc_to_line_[train.extruder_nr_] = PolygonUtils::createLocToLineGrid(getBoundaryOutside(train), offset_from_inside_to_outside_ * 3 / 2); } - return *outside_loc_to_line[train.extruder_nr_]; + return *outside_loc_to_line_[train.extruder_nr_]; } Polygons& Comb::getBoundaryOutside(const ExtruderTrain& train) { - if (boundary_outside[train.extruder_nr_].empty()) + if (boundary_outside_[train.extruder_nr_].empty()) { bool travel_avoid_supports = train.settings_.get("travel_avoid_supports"); - boundary_outside[train.extruder_nr_] = storage.getLayerOutlines(layer_nr, travel_avoid_supports, travel_avoid_supports).offset(travel_avoid_distance); + boundary_outside_[train.extruder_nr_] = storage_.getLayerOutlines(layer_nr_, travel_avoid_supports, travel_avoid_supports).offset(travel_avoid_distance_); } - return boundary_outside[train.extruder_nr_]; + return boundary_outside_[train.extruder_nr_]; } Polygons& Comb::getModelBoundary(const ExtruderTrain& train) { - if (model_boundary[train.extruder_nr_].empty()) + if (model_boundary_[train.extruder_nr_].empty()) { bool travel_avoid_supports = train.settings_.get("travel_avoid_supports"); - model_boundary[train.extruder_nr_] = storage.getLayerOutlines(layer_nr, travel_avoid_supports, travel_avoid_supports); + model_boundary_[train.extruder_nr_] = storage_.getLayerOutlines(layer_nr_, travel_avoid_supports, travel_avoid_supports); } - return boundary_outside[train.extruder_nr_]; + return boundary_outside_[train.extruder_nr_]; } LocToLineGrid& Comb::getModelBoundaryLocToLine(const ExtruderTrain& train) { - if (model_boundary_loc_to_line[train.extruder_nr_] == nullptr) + if (model_boundary_loc_to_line_[train.extruder_nr_] == nullptr) { - model_boundary_loc_to_line[train.extruder_nr_] = PolygonUtils::createLocToLineGrid(getModelBoundary(train), offset_from_inside_to_outside * 3 / 2); + model_boundary_loc_to_line_[train.extruder_nr_] = PolygonUtils::createLocToLineGrid(getModelBoundary(train), offset_from_inside_to_outside_ * 3 / 2); } - return *model_boundary_loc_to_line[train.extruder_nr_]; + return *model_boundary_loc_to_line_[train.extruder_nr_]; } Comb::Comb( @@ -66,22 +66,22 @@ Comb::Comb( coord_t comb_boundary_offset, coord_t travel_avoid_distance, coord_t move_inside_distance) - : storage(storage) - , layer_nr(layer_nr) - , offset_from_outlines(comb_boundary_offset) // between second wall and infill / other walls - , max_moveInside_distance2(offset_from_outlines * offset_from_outlines) - , offset_from_inside_to_outside(offset_from_outlines + travel_avoid_distance) - , max_crossing_dist2( - offset_from_inside_to_outside * offset_from_inside_to_outside + : storage_(storage) + , layer_nr_(layer_nr) + , offset_from_outlines_(comb_boundary_offset) // between second wall and infill / other walls + , max_moveInside_distance2_(offset_from_outlines_ * offset_from_outlines_) + , offset_from_inside_to_outside_(offset_from_outlines_ + travel_avoid_distance) + , max_crossing_dist2_( + offset_from_inside_to_outside_ * offset_from_inside_to_outside_ * 2) // so max_crossing_dist = offset_from_inside_to_outside * sqrt(2) =approx 1.5 to allow for slightly diagonal crossings and slightly inaccurate crossing computation - , boundary_inside_minimum(comb_boundary_inside_minimum) // copy the boundary, because the partsView_inside will reorder the polygons - , boundary_inside_optimal(comb_boundary_inside_optimal) // copy the boundary, because the partsView_inside will reorder the polygons - , partsView_inside_minimum(boundary_inside_minimum.splitIntoPartsView()) // WARNING !! changes the order of boundary_inside !! - , partsView_inside_optimal(boundary_inside_optimal.splitIntoPartsView()) // WARNING !! changes the order of boundary_inside !! - , inside_loc_to_line_minimum(PolygonUtils::createLocToLineGrid(boundary_inside_minimum, comb_boundary_offset)) - , inside_loc_to_line_optimal(PolygonUtils::createLocToLineGrid(boundary_inside_optimal, comb_boundary_offset)) - , move_inside_distance(move_inside_distance) - , travel_avoid_distance(travel_avoid_distance) + , boundary_inside_minimum_(comb_boundary_inside_minimum) // copy the boundary, because the partsView_inside will reorder the polygons + , boundary_inside_optimal_(comb_boundary_inside_optimal) // copy the boundary, because the partsView_inside will reorder the polygons + , parts_view_inside_minimum_(boundary_inside_minimum_.splitIntoPartsView()) // WARNING !! changes the order of boundary_inside !! + , parts_view_inside_optimal_(boundary_inside_optimal_.splitIntoPartsView()) // WARNING !! changes the order of boundary_inside !! + , inside_loc_to_line_minimum_(PolygonUtils::createLocToLineGrid(boundary_inside_minimum_, comb_boundary_offset)) + , inside_loc_to_line_optimal_(PolygonUtils::createLocToLineGrid(boundary_inside_optimal_, comb_boundary_offset)) + , move_inside_distance_(move_inside_distance) + , travel_avoid_distance_(travel_avoid_distance) { } @@ -104,30 +104,30 @@ bool Comb::calc( const Point travel_end_point_before_combing = end_point; // Move start and end point inside the optimal comb boundary unsigned int start_inside_poly = NO_INDEX; - const bool start_inside = moveInside(boundary_inside_optimal, _start_inside, inside_loc_to_line_optimal.get(), start_point, start_inside_poly); + const bool start_inside = moveInside(boundary_inside_optimal_, _start_inside, inside_loc_to_line_optimal_.get(), start_point, start_inside_poly); unsigned int end_inside_poly = NO_INDEX; - const bool end_inside = moveInside(boundary_inside_optimal, _end_inside, inside_loc_to_line_optimal.get(), end_point, end_inside_poly); + const bool end_inside = moveInside(boundary_inside_optimal_, _end_inside, inside_loc_to_line_optimal_.get(), end_point, end_inside_poly); unsigned int start_part_boundary_poly_idx = NO_INDEX; // Added initial value to stop MSVC throwing an exception in debug mode unsigned int end_part_boundary_poly_idx = NO_INDEX; - unsigned int start_part_idx = (start_inside_poly == NO_INDEX) ? NO_INDEX : partsView_inside_optimal.getPartContaining(start_inside_poly, &start_part_boundary_poly_idx); - unsigned int end_part_idx = (end_inside_poly == NO_INDEX) ? NO_INDEX : partsView_inside_optimal.getPartContaining(end_inside_poly, &end_part_boundary_poly_idx); + unsigned int start_part_idx = (start_inside_poly == NO_INDEX) ? NO_INDEX : parts_view_inside_optimal_.getPartContaining(start_inside_poly, &start_part_boundary_poly_idx); + unsigned int end_part_idx = (end_inside_poly == NO_INDEX) ? NO_INDEX : parts_view_inside_optimal_.getPartContaining(end_inside_poly, &end_part_boundary_poly_idx); const bool fail_on_unavoidable_obstacles = perform_z_hops && perform_z_hops_only_when_collides; // normal combing within part using optimal comb boundary if (start_inside && end_inside && start_part_idx == end_part_idx) { - PolygonsPart part = partsView_inside_optimal.assemblePart(start_part_idx); + PolygonsPart part = parts_view_inside_optimal_.assemblePart(start_part_idx); comb_paths.emplace_back(); const bool combing_succeeded = LinePolygonsCrossings::comb( part, - *inside_loc_to_line_optimal, + *inside_loc_to_line_optimal_, start_point, end_point, comb_paths.back(), - -offset_dist_to_get_from_on_the_polygon_to_outside, + -offset_dist_to_get_from_on_the_polygon_to_outside_, max_comb_distance_ignored, fail_on_unavoidable_obstacles); // If the endpoint of the travel path changes with combing, then it means that we are moving to an outer wall @@ -138,16 +138,16 @@ bool Comb::calc( // Move start and end point inside the minimum comb boundary unsigned int start_inside_poly_min = NO_INDEX; - const bool start_inside_min = moveInside(boundary_inside_minimum, _start_inside, inside_loc_to_line_minimum.get(), start_point, start_inside_poly_min); + const bool start_inside_min = moveInside(boundary_inside_minimum_, _start_inside, inside_loc_to_line_minimum_.get(), start_point, start_inside_poly_min); unsigned int end_inside_poly_min = NO_INDEX; - const bool end_inside_min = moveInside(boundary_inside_minimum, _end_inside, inside_loc_to_line_minimum.get(), end_point, end_inside_poly_min); + const bool end_inside_min = moveInside(boundary_inside_minimum_, _end_inside, inside_loc_to_line_minimum_.get(), end_point, end_inside_poly_min); unsigned int start_part_boundary_poly_idx_min{}; unsigned int end_part_boundary_poly_idx_min{}; unsigned int start_part_idx_min - = (start_inside_poly_min == NO_INDEX) ? NO_INDEX : partsView_inside_minimum.getPartContaining(start_inside_poly_min, &start_part_boundary_poly_idx_min); - unsigned int end_part_idx_min = (end_inside_poly_min == NO_INDEX) ? NO_INDEX : partsView_inside_minimum.getPartContaining(end_inside_poly_min, &end_part_boundary_poly_idx_min); + = (start_inside_poly_min == NO_INDEX) ? NO_INDEX : parts_view_inside_minimum_.getPartContaining(start_inside_poly_min, &start_part_boundary_poly_idx_min); + unsigned int end_part_idx_min = (end_inside_poly_min == NO_INDEX) ? NO_INDEX : parts_view_inside_minimum_.getPartContaining(end_inside_poly_min, &end_part_boundary_poly_idx_min); CombPath result_path; bool comb_result; @@ -155,19 +155,19 @@ bool Comb::calc( // normal combing within part using minimum comb boundary if (start_inside_min && end_inside_min && start_part_idx_min == end_part_idx_min) { - PolygonsPart part = partsView_inside_minimum.assemblePart(start_part_idx_min); + PolygonsPart part = parts_view_inside_minimum_.assemblePart(start_part_idx_min); comb_paths.emplace_back(); comb_result = LinePolygonsCrossings::comb( part, - *inside_loc_to_line_minimum, + *inside_loc_to_line_minimum_, start_point, end_point, result_path, - -offset_dist_to_get_from_on_the_polygon_to_outside, + -offset_dist_to_get_from_on_the_polygon_to_outside_, max_comb_distance_ignored, fail_on_unavoidable_obstacles); - Comb::moveCombPathInside(boundary_inside_minimum, boundary_inside_optimal, result_path, comb_paths.back()); // add altered result_path to combPaths.back() + Comb::moveCombPathInside(boundary_inside_minimum_, boundary_inside_optimal_, result_path, comb_paths.back()); // add altered result_path to combPaths.back() // If the endpoint of the travel path changes with combing, then it means that we are moving to an outer wall // and we should unretract before the last travel move when travelling to that outer wall unretract_before_last_travel_move = comb_result && end_point != travel_end_point_before_combing; @@ -188,16 +188,16 @@ bool Comb::calc( // Find the crossings using the minimum comb boundary, since it's guaranteed to be as close as we can get to the destination. // Getting as close as possible prevents exiting the polygon in the wrong direction (e.g. into a hole instead of to the outside). - Crossing start_crossing(start_point, start_inside_min, start_part_idx_min, start_part_boundary_poly_idx_min, boundary_inside_minimum, *inside_loc_to_line_minimum); - Crossing end_crossing(end_point, end_inside_min, end_part_idx_min, end_part_boundary_poly_idx_min, boundary_inside_minimum, *inside_loc_to_line_minimum); + Crossing start_crossing(start_point, start_inside_min, start_part_idx_min, start_part_boundary_poly_idx_min, boundary_inside_minimum_, *inside_loc_to_line_minimum_); + Crossing end_crossing(end_point, end_inside_min, end_part_idx_min, end_part_boundary_poly_idx_min, boundary_inside_minimum_, *inside_loc_to_line_minimum_); { // find crossing over the in-between area between inside and outside - start_crossing.findCrossingInOrMid(partsView_inside_minimum, end_point); - end_crossing.findCrossingInOrMid(partsView_inside_minimum, start_crossing.in_or_mid); + start_crossing.findCrossingInOrMid(parts_view_inside_minimum_, end_point); + end_crossing.findCrossingInOrMid(parts_view_inside_minimum_, start_crossing.in_or_mid_); } bool skip_avoid_other_parts_path = false; - if (vSize2(start_crossing.in_or_mid - end_crossing.in_or_mid) < offset_from_inside_to_outside * offset_from_inside_to_outside * 4) + if (vSize2(start_crossing.in_or_mid_ - end_crossing.in_or_mid_) < offset_from_inside_to_outside_ * offset_from_inside_to_outside_ * 4) { // parts are next to each other, i.e. the direct crossing will always be smaller than two crossings via outside skip_avoid_other_parts_path = true; } @@ -208,12 +208,12 @@ bool Comb::calc( { // compute the crossing points when moving through air // comb through all air, since generally the outside consists of a single part - bool success = start_crossing.findOutside(train, getBoundaryOutside(train), end_crossing.in_or_mid, fail_on_unavoidable_obstacles, *this); + bool success = start_crossing.findOutside(train, getBoundaryOutside(train), end_crossing.in_or_mid_, fail_on_unavoidable_obstacles, *this); if (! success) { return false; } - success = end_crossing.findOutside(train, getBoundaryOutside(train), start_crossing.out, fail_on_unavoidable_obstacles, *this); + success = end_crossing.findOutside(train, getBoundaryOutside(train), start_crossing.out_, fail_on_unavoidable_obstacles, *this); if (! success) { return false; @@ -224,29 +224,29 @@ bool Comb::calc( if (start_inside_min) { // start to boundary - assert(start_crossing.dest_part.size() > 0 && "The part we start inside when combing should have been computed already!"); + assert(start_crossing.dest_part_.size() > 0 && "The part we start inside when combing should have been computed already!"); comb_paths.emplace_back(); // If we're inside the optimal bound, first try the optimal combing path. If it fails, use the minimum path instead. constexpr bool fail_for_optimum_bound = true; bool combing_succeeded = start_inside && LinePolygonsCrossings::comb( - boundary_inside_optimal, - *inside_loc_to_line_optimal, + boundary_inside_optimal_, + *inside_loc_to_line_optimal_, start_point, - start_crossing.in_or_mid, + start_crossing.in_or_mid_, comb_paths.back(), - -offset_dist_to_get_from_on_the_polygon_to_outside, + -offset_dist_to_get_from_on_the_polygon_to_outside_, max_comb_distance_ignored, fail_for_optimum_bound); if (! combing_succeeded) { combing_succeeded = LinePolygonsCrossings::comb( - start_crossing.dest_part, - *inside_loc_to_line_minimum, + start_crossing.dest_part_, + *inside_loc_to_line_minimum_, start_point, - start_crossing.in_or_mid, + start_crossing.in_or_mid_, comb_paths.back(), - -offset_dist_to_get_from_on_the_polygon_to_outside, + -offset_dist_to_get_from_on_the_polygon_to_outside_, max_comb_distance_ignored, fail_on_unavoidable_obstacles); } @@ -262,10 +262,10 @@ bool Comb::calc( { comb_paths.emplace_back(); comb_paths.throughAir = true; - if (vSize(start_crossing.in_or_mid - end_crossing.in_or_mid) < vSize(start_crossing.in_or_mid - start_crossing.out) + vSize(end_crossing.in_or_mid - end_crossing.out)) + if (vSize(start_crossing.in_or_mid_ - end_crossing.in_or_mid_) < vSize(start_crossing.in_or_mid_ - start_crossing.out_) + vSize(end_crossing.in_or_mid_ - end_crossing.out_)) { // via outside is moving more over the in-between zone - comb_paths.back().push_back(start_crossing.in_or_mid); - comb_paths.back().push_back(end_crossing.in_or_mid); + comb_paths.back().push_back(start_crossing.in_or_mid_); + comb_paths.back().push_back(end_crossing.in_or_mid_); } else { @@ -273,10 +273,10 @@ bool Comb::calc( bool combing_succeeded = LinePolygonsCrossings::comb( getBoundaryOutside(train), getOutsideLocToLine(train), - start_crossing.out, - end_crossing.out, + start_crossing.out_, + end_crossing.out_, tmp_comb_path, - offset_dist_to_get_from_on_the_polygon_to_outside, + offset_dist_to_get_from_on_the_polygon_to_outside_, max_comb_distance_ignored, true); @@ -293,8 +293,8 @@ bool Comb::calc( comb_paths.emplace_back(); comb_paths.throughAir = true; comb_paths.back().cross_boundary = true; - comb_paths.back().push_back(start_crossing.in_or_mid); - comb_paths.back().push_back(end_crossing.in_or_mid); + comb_paths.back().push_back(start_crossing.in_or_mid_); + comb_paths.back().push_back(end_crossing.in_or_mid_); if (fail_on_unavoidable_obstacles) { @@ -308,8 +308,8 @@ bool Comb::calc( comb_paths.emplace_back(); comb_paths.throughAir = true; comb_paths.back().cross_boundary = true; // note: we don't actually know whether this is cross boundary, but it might very well be - comb_paths.back().push_back(start_crossing.in_or_mid); - comb_paths.back().push_back(end_crossing.in_or_mid); + comb_paths.back().push_back(start_crossing.in_or_mid_); + comb_paths.back().push_back(end_crossing.in_or_mid_); } if (skip_avoid_other_parts_path) { @@ -317,7 +317,7 @@ bool Comb::calc( { if (start_inside) { // both start and end are inside - comb_paths.back().cross_boundary = PolygonUtils::polygonCollidesWithLineSegment(start_point, end_point, *inside_loc_to_line_optimal); + comb_paths.back().cross_boundary = PolygonUtils::polygonCollidesWithLineSegment(start_point, end_point, *inside_loc_to_line_optimal_); } else { // both start and end are outside @@ -333,29 +333,29 @@ bool Comb::calc( if (end_inside) { // boundary to end - assert(end_crossing.dest_part.size() > 0 && "The part we end up inside when combing should have been computed already!"); + assert(end_crossing.dest_part_.size() > 0 && "The part we end up inside when combing should have been computed already!"); comb_paths.emplace_back(); // If we're inside the optimal bound, first try the optimal combing path. If it fails, use the minimum path instead. constexpr bool fail_for_optimum_bound = true; bool combing_succeeded = end_inside && LinePolygonsCrossings::comb( - boundary_inside_optimal, - *inside_loc_to_line_optimal, - end_crossing.in_or_mid, + boundary_inside_optimal_, + *inside_loc_to_line_optimal_, + end_crossing.in_or_mid_, end_point, comb_paths.back(), - -offset_dist_to_get_from_on_the_polygon_to_outside, + -offset_dist_to_get_from_on_the_polygon_to_outside_, max_comb_distance_ignored, fail_for_optimum_bound); if (! combing_succeeded) { combing_succeeded = LinePolygonsCrossings::comb( - end_crossing.dest_part, - *inside_loc_to_line_minimum, - end_crossing.in_or_mid, + end_crossing.dest_part_, + *inside_loc_to_line_minimum_, + end_crossing.in_or_mid_, end_point, comb_paths.back(), - -offset_dist_to_get_from_on_the_polygon_to_outside, + -offset_dist_to_get_from_on_the_polygon_to_outside_, max_comb_distance_ignored, fail_on_unavoidable_obstacles); } @@ -375,7 +375,7 @@ bool Comb::calc( // Try to move comb_path_input points inside by the amount of `move_inside_distance` and see if the points are still in boundary_inside_optimal, add result in comb_path_output void Comb::moveCombPathInside(Polygons& boundary_inside, Polygons& boundary_inside_optimal, CombPath& comb_path_input, CombPath& comb_path_output) { - const coord_t dist = move_inside_distance; + const coord_t dist = move_inside_distance_; const coord_t dist2 = dist * dist; if (comb_path_input.size() == 0) @@ -410,15 +410,15 @@ Comb::Crossing::Crossing( const unsigned int dest_part_boundary_crossing_poly_idx, const Polygons& boundary_inside, const LocToLineGrid& inside_loc_to_line) - : dest_is_inside(dest_is_inside) - , boundary_inside(boundary_inside) - , inside_loc_to_line(inside_loc_to_line) - , dest_point(dest_point) - , dest_part_idx(dest_part_idx) + : dest_is_inside_(dest_is_inside) + , boundary_inside_(boundary_inside) + , inside_loc_to_line_(inside_loc_to_line) + , dest_point_(dest_point) + , dest_part_idx_(dest_part_idx) { if (dest_is_inside) { - dest_crossing_poly.emplace(boundary_inside[dest_part_boundary_crossing_poly_idx]); // initialize with most obvious poly, cause mostly a combing move will move outside the + dest_crossing_poly_.emplace(boundary_inside[dest_part_boundary_crossing_poly_idx]); // initialize with most obvious poly, cause mostly a combing move will move outside the // part, rather than inside a hole in the part } } @@ -428,7 +428,7 @@ bool Comb::moveInside(Polygons& boundary_inside, bool is_inside, LocToLineGrid* if (is_inside) { ClosestPolygonPoint cpp - = PolygonUtils::ensureInsideOrOutside(boundary_inside, dest_point, offset_extra_start_end, max_moveInside_distance2, &boundary_inside, inside_loc_to_line); + = PolygonUtils::ensureInsideOrOutside(boundary_inside, dest_point, offset_extra_start_end_, max_moveInside_distance2_, &boundary_inside, inside_loc_to_line); if (! cpp.isValid()) { return false; @@ -444,21 +444,21 @@ bool Comb::moveInside(Polygons& boundary_inside, bool is_inside, LocToLineGrid* void Comb::Crossing::findCrossingInOrMid(const PartsView& partsView_inside, const Point close_to) { - if (dest_is_inside) + if (dest_is_inside_) { // in-case // find the point on the start inside-polygon closest to the endpoint, but also kind of close to the start point - Point _dest_point(dest_point); // copy to local variable for lambda capture + Point _dest_point(dest_point_); // copy to local variable for lambda capture std::function close_towards_start_penalty_function( [_dest_point](Point candidate) { return vSize2((candidate - _dest_point) / 10); }); - dest_part = partsView_inside.assemblePart(dest_part_idx); + dest_part_ = partsView_inside.assemblePart(dest_part_idx_); ClosestPolygonPoint boundary_crossing_point; { // set [result] to a point on the destination part closest to close_to (but also a bit close to _dest_point) std::unordered_set dest_part_poly_indices; - for (unsigned int poly_idx : partsView_inside[dest_part_idx]) + for (unsigned int poly_idx : partsView_inside[dest_part_idx_]) { dest_part_poly_indices.emplace(poly_idx); } @@ -479,72 +479,72 @@ void Comb::Crossing::findCrossingInOrMid(const PartsView& partsView_inside, cons } return true; }; - inside_loc_to_line.processLine(std::make_pair(dest_point, close_to), line_processor); + inside_loc_to_line_.processLine(std::make_pair(dest_point_, close_to), line_processor); } Point result(boundary_crossing_point.p()); // the inside point of the crossing if (! boundary_crossing_point.isValid()) { // no point has been found in the sparse grid - result = dest_point; + result = dest_point_; } ClosestPolygonPoint crossing_1_in_cp = PolygonUtils::ensureInsideOrOutside( - dest_part, + dest_part_, result, boundary_crossing_point, - offset_dist_to_get_from_on_the_polygon_to_outside, - &boundary_inside, - &inside_loc_to_line, + offset_dist_to_get_from_on_the_polygon_to_outside_, + &boundary_inside_, + &inside_loc_to_line_, close_towards_start_penalty_function); if (crossing_1_in_cp.isValid()) { - dest_crossing_poly = crossing_1_in_cp.poly_; - in_or_mid = result; + dest_crossing_poly_ = crossing_1_in_cp.poly_; + in_or_mid_ = result; } else { // part is too small to be ensuring a point inside with the given distance - in_or_mid = dest_point; // just use the startPoint or endPoint itself + in_or_mid_ = dest_point_; // just use the startPoint or endPoint itself } } else { // mid-case - in_or_mid = dest_point; + in_or_mid_ = dest_point_; } } bool Comb::Crossing::findOutside(const ExtruderTrain& train, const Polygons& outside, const Point close_to, const bool fail_on_unavoidable_obstacles, Comb& comber) { - out = in_or_mid; - if (dest_is_inside || outside.inside(in_or_mid, true)) // start in_between + out_ = in_or_mid_; + if (dest_is_inside_ || outside.inside(in_or_mid_, true)) // start in_between { // move outside - Point preferred_crossing_1_out = in_or_mid + normal(close_to - in_or_mid, comber.offset_from_inside_to_outside); + Point preferred_crossing_1_out = in_or_mid_ + normal(close_to - in_or_mid_, comber.offset_from_inside_to_outside_); std::function close_to_penalty_function( [preferred_crossing_1_out](Point candidate) { return vSize2((candidate - preferred_crossing_1_out) / 2); }); - std::optional crossing_1_out_cpp = PolygonUtils::findClose(in_or_mid, outside, comber.getOutsideLocToLine(train), close_to_penalty_function); + std::optional crossing_1_out_cpp = PolygonUtils::findClose(in_or_mid_, outside, comber.getOutsideLocToLine(train), close_to_penalty_function); if (crossing_1_out_cpp) { - out = PolygonUtils::moveOutside(*crossing_1_out_cpp, comber.offset_dist_to_get_from_on_the_polygon_to_outside); + out_ = PolygonUtils::moveOutside(*crossing_1_out_cpp, comber.offset_dist_to_get_from_on_the_polygon_to_outside_); } else { - PolygonUtils::moveOutside(outside, out, comber.offset_dist_to_get_from_on_the_polygon_to_outside); + PolygonUtils::moveOutside(outside, out_, comber.offset_dist_to_get_from_on_the_polygon_to_outside_); } } - int64_t in_out_dist2_1 = vSize2(out - in_or_mid); - if (dest_is_inside && in_out_dist2_1 > comber.max_crossing_dist2) // moveInside moved too far + int64_t in_out_dist2_1 = vSize2(out_ - in_or_mid_); + if (dest_is_inside_ && in_out_dist2_1 > comber.max_crossing_dist2_) // moveInside moved too far { // if move is too far over in_between // find crossing closer by - assert(dest_crossing_poly && "destination crossing poly should have been instantiated!"); - std::shared_ptr> best = findBestCrossing(train, outside, **dest_crossing_poly, dest_point, close_to, comber); + assert(dest_crossing_poly_ && "destination crossing poly should have been instantiated!"); + std::shared_ptr> best = findBestCrossing(train, outside, **dest_crossing_poly_, dest_point_, close_to, comber); if (best) { - in_or_mid = PolygonUtils::moveInside(best->first, comber.offset_dist_to_get_from_on_the_polygon_to_outside); - out = PolygonUtils::moveOutside(best->second, comber.offset_dist_to_get_from_on_the_polygon_to_outside); + in_or_mid_ = PolygonUtils::moveInside(best->first, comber.offset_dist_to_get_from_on_the_polygon_to_outside_); + out_ = PolygonUtils::moveOutside(best->second, comber.offset_dist_to_get_from_on_the_polygon_to_outside_); } - if (fail_on_unavoidable_obstacles && vSize2(out - in_or_mid) > comber.max_crossing_dist2) // moveInside moved still too far + if (fail_on_unavoidable_obstacles && vSize2(out_ - in_or_mid_) > comber.max_crossing_dist2_) // moveInside moved still too far { return false; } @@ -570,7 +570,7 @@ std::shared_ptr> Comb::Cross for (std::pair& crossing_candidate : crossing_out_candidates) { const coord_t crossing_dist2 = vSize2(crossing_candidate.first.location_ - crossing_candidate.second.location_); - if (crossing_dist2 > comber.max_crossing_dist2 * 2) + if (crossing_dist2 > comber.max_crossing_dist2_ * 2) { // preliminary filtering continue; } @@ -586,11 +586,11 @@ std::shared_ptr> Comb::Cross // In the end we just want to choose between two points which have the _same_ crossing distance, modulo rounding error. if ((! seen_close_enough_connection && detour_score < best_detour_score) // keep the best as long as we havent seen one close enough (so that we may walk along the polygon // to find a closer connection from it in the code below) - || (! seen_close_enough_connection && crossing_dist2 <= comber.max_crossing_dist2) // make the one which is close enough the best as soon as we see one close enough - || (seen_close_enough_connection && crossing_dist2 <= comber.max_crossing_dist2 + || (! seen_close_enough_connection && crossing_dist2 <= comber.max_crossing_dist2_) // make the one which is close enough the best as soon as we see one close enough + || (seen_close_enough_connection && crossing_dist2 <= comber.max_crossing_dist2_ && detour_score < best_detour_score)) // update to keep the best crossing which is close enough already { - if (! seen_close_enough_connection && crossing_dist2 <= comber.max_crossing_dist2) + if (! seen_close_enough_connection && crossing_dist2 <= comber.max_crossing_dist2_) { seen_close_enough_connection = true; } @@ -604,11 +604,11 @@ std::shared_ptr> Comb::Cross { // i.e. if best_in == nullptr or if best_out == nullptr return std::shared_ptr>(); } - if (best_crossing_dist2 > comber.max_crossing_dist2) + if (best_crossing_dist2 > comber.max_crossing_dist2_) { // find closer point on line segments, rather than moving between vertices of the polygons only PolygonUtils::walkToNearestSmallestConnection(*best_in, *best_out); best_crossing_dist2 = vSize2(best_in->location_ - best_out->location_); - if (best_crossing_dist2 > comber.max_crossing_dist2) + if (best_crossing_dist2 > comber.max_crossing_dist2_) { return std::shared_ptr>(); } diff --git a/src/settings/AdaptiveLayerHeights.cpp b/src/settings/AdaptiveLayerHeights.cpp index 66fae223bf..14b37b8eaa 100644 --- a/src/settings/AdaptiveLayerHeights.cpp +++ b/src/settings/AdaptiveLayerHeights.cpp @@ -17,16 +17,16 @@ namespace cura { AdaptiveLayer::AdaptiveLayer(const coord_t layer_height) - : layer_height{ layer_height } + : layer_height_{ layer_height } { } AdaptiveLayerHeights::AdaptiveLayerHeights(const coord_t base_layer_height, const coord_t variation, const coord_t step_size, const coord_t threshold, const MeshGroup* meshgroup) - : base_layer_height{ base_layer_height } - , max_variation{ variation } - , step_size{ step_size } - , threshold{ threshold } - , meshgroup{ meshgroup } + : base_layer_height_{ base_layer_height } + , max_variation_{ variation } + , step_size_{ step_size } + , threshold_{ threshold } + , meshgroup_{ meshgroup } { calculateAllowedLayerHeights(); calculateMeshTriangleSlopes(); @@ -35,36 +35,36 @@ AdaptiveLayerHeights::AdaptiveLayerHeights(const coord_t base_layer_height, cons size_t AdaptiveLayerHeights::getLayerCount() const { - return layers.size(); + return layers_.size(); } std::vector* AdaptiveLayerHeights::getLayers() { - return &layers; + return &layers_; } void AdaptiveLayerHeights::calculateAllowedLayerHeights() { // calculate the allowed layer heights from variation and step size // note: the order is from thickest to thinnest height! - for (coord_t allowed_layer_height = base_layer_height + max_variation; allowed_layer_height >= base_layer_height - max_variation; allowed_layer_height -= step_size) + for (coord_t allowed_layer_height = base_layer_height_ + max_variation_; allowed_layer_height >= base_layer_height_ - max_variation_; allowed_layer_height -= step_size_) { // we should only consider using layer_heights that are > 0 if (allowed_layer_height <= 0) { break; } - allowed_layer_heights.push_back(allowed_layer_height); + allowed_layer_heights_.push_back(allowed_layer_height); } } void AdaptiveLayerHeights::calculateLayers() { - const coord_t minimum_layer_height = *std::min_element(allowed_layer_heights.begin(), allowed_layer_heights.end()); + const coord_t minimum_layer_height = *std::min_element(allowed_layer_heights_.begin(), allowed_layer_heights_.end()); Settings const& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; auto slicing_tolerance = mesh_group_settings.get("slicing_tolerance"); std::vector triangles_of_interest; - const coord_t model_max_z = meshgroup->max().z_; + const coord_t model_max_z = meshgroup_->max().z_; coord_t z_level = 0; coord_t previous_layer_height = 0; @@ -73,32 +73,32 @@ void AdaptiveLayerHeights::calculateLayers() z_level += initial_layer_height; AdaptiveLayer adaptive_layer(initial_layer_height); - adaptive_layer.z_position = z_level; - previous_layer_height = adaptive_layer.layer_height; - layers.push_back(adaptive_layer); + adaptive_layer.z_position_ = z_level; + previous_layer_height = adaptive_layer.layer_height_; + layers_.push_back(adaptive_layer); // loop while triangles are found - while (z_level <= model_max_z || layers.size() < 2) + while (z_level <= model_max_z || layers_.size() < 2) { double global_min_slope = std::numeric_limits::max(); // loop over all allowed layer heights starting with the largest bool has_added_layer = false; - for (auto& layer_height : allowed_layer_heights) + for (auto& layer_height : allowed_layer_heights_) { // use lower and upper bounds to filter on triangles that are interesting for this potential layer const coord_t lower_bound = z_level; // if slicing tolerance "middle" is used, a layer is interpreted as the middle of the upper and lower bounds. const coord_t upper_bound = z_level + ((slicing_tolerance == SlicingTolerance::MIDDLE) ? (layer_height / 2) : layer_height); - if (layer_height == allowed_layer_heights[0]) + if (layer_height == allowed_layer_heights_[0]) { // this is the max layer thickness, search through all of the triangles in the mesh to find those // that intersect with a layer this thick triangles_of_interest.clear(); - for (size_t i = 0; i < face_min_z_values.size(); ++i) + for (size_t i = 0; i < face_min_z_values_.size(); ++i) { - if (face_min_z_values[i] <= upper_bound && face_max_z_values[i] >= lower_bound) + if (face_min_z_values_[i] <= upper_bound && face_max_z_values_[i] >= lower_bound) { triangles_of_interest.push_back(i); } @@ -114,7 +114,7 @@ void AdaptiveLayerHeights::calculateLayers() for (const auto& i : last_triangles_of_interest) { - if (face_min_z_values[i] <= upper_bound) + if (face_min_z_values_[i] <= upper_bound) { triangles_of_interest.push_back(i); } @@ -131,7 +131,7 @@ void AdaptiveLayerHeights::calculateLayers() double minimum_slope = std::numeric_limits::max(); for (const size_t& triangle_index : triangles_of_interest) { - const double slope = face_slopes.at(triangle_index); + const double slope = face_slopes_.at(triangle_index); if (minimum_slope > slope) { minimum_slope = slope; @@ -144,11 +144,11 @@ void AdaptiveLayerHeights::calculateLayers() // check if the maximum step size has been exceeded depending on layer height direction bool has_exceeded_step_size = false; - if (previous_layer_height > layer_height && previous_layer_height - layer_height > step_size) + if (previous_layer_height > layer_height && previous_layer_height - layer_height > step_size_) { has_exceeded_step_size = true; } - else if (layer_height - previous_layer_height > step_size && layer_height > minimum_layer_height) + else if (layer_height - previous_layer_height > step_size_ && layer_height > minimum_layer_height) { continue; } @@ -158,13 +158,13 @@ void AdaptiveLayerHeights::calculateLayers() // 2) the layer height is the smallest it is allowed // 3) the layer is a flat surface (we can't divide by 0) const double minimum_slope_tan = std::tan(minimum_slope); - if (minimum_slope_tan == 0.0 || (layer_height / minimum_slope_tan) <= threshold || layer_height == minimum_layer_height || has_exceeded_step_size) + if (minimum_slope_tan == 0.0 || (layer_height / minimum_slope_tan) <= threshold_ || layer_height == minimum_layer_height || has_exceeded_step_size) { z_level += layer_height; - AdaptiveLayer adaptive_layer(layer_height); - adaptive_layer.z_position = z_level; - previous_layer_height = adaptive_layer.layer_height; - layers.push_back(adaptive_layer); + AdaptiveLayer adaptive_layer_add(layer_height); + adaptive_layer_add.z_position_ = z_level; + previous_layer_height = adaptive_layer_add.layer_height_; + layers_.push_back(adaptive_layer_add); has_added_layer = true; break; } @@ -174,12 +174,12 @@ void AdaptiveLayerHeights::calculateLayers() // in this case, we use the layer height with the lowest if (! has_added_layer) { - const auto& min_layer_height = allowed_layer_heights.back(); + const auto& min_layer_height = allowed_layer_heights_.back(); AdaptiveLayer minimum_adaptive_layer(min_layer_height); z_level += min_layer_height; - minimum_adaptive_layer.z_position = z_level; + minimum_adaptive_layer.z_position_ = z_level; previous_layer_height = min_layer_height; - layers.push_back(minimum_adaptive_layer); + layers_.push_back(minimum_adaptive_layer); } } } @@ -223,9 +223,9 @@ void AdaptiveLayerHeights::calculateMeshTriangleSlopes() z_angle = std::numbers::pi; } - face_min_z_values.push_back(MM2INT(min_z)); - face_max_z_values.push_back(MM2INT(max_z)); - face_slopes.push_back(z_angle); + face_min_z_values_.push_back(MM2INT(min_z)); + face_max_z_values_.push_back(MM2INT(max_z)); + face_slopes_.push_back(z_angle); } } } diff --git a/src/settings/ZSeamConfig.cpp b/src/settings/ZSeamConfig.cpp index b652657538..229722922b 100644 --- a/src/settings/ZSeamConfig.cpp +++ b/src/settings/ZSeamConfig.cpp @@ -7,11 +7,11 @@ namespace cura { ZSeamConfig::ZSeamConfig(const EZSeamType type, const Point pos, const EZSeamCornerPrefType corner_pref, const coord_t simplify_curvature) -: type(type) -, pos(pos) -, corner_pref(corner_pref) -, simplify_curvature(simplify_curvature) +: type_(type) +, pos_(pos) +, corner_pref_(corner_pref) +, simplify_curvature_(simplify_curvature) { } -} //Cura namespace. \ No newline at end of file +} //Cura namespace. diff --git a/src/sliceDataStorage.cpp b/src/sliceDataStorage.cpp index ddce31175b..f0e0c79a26 100644 --- a/src/sliceDataStorage.cpp +++ b/src/sliceDataStorage.cpp @@ -55,7 +55,7 @@ bool SliceLayerPart::hasWallAtInsetIndex(size_t inset_idx) const { for (const ExtrusionLine& line : lines) { - if (line.inset_idx == inset_idx) + if (line.inset_idx_ == inset_idx) { return true; } @@ -542,8 +542,8 @@ Polygons SliceDataStorage::getMachineBorder(int checking_extruder_nr) const case BuildPlateShape::ELLIPTIC: { // Construct an ellipse to approximate the build volume. - const coord_t width = machine_size.max.x_ - machine_size.min.x_; - const coord_t depth = machine_size.max.y_ - machine_size.min.y_; + const coord_t width = machine_size.max_.x_ - machine_size.min_.x_; + const coord_t depth = machine_size.max_.y_ - machine_size.min_.y_; constexpr unsigned int circle_resolution = 50; for (unsigned int i = 0; i < circle_resolution; i++) { @@ -569,7 +569,7 @@ Polygons SliceDataStorage::getMachineBorder(int checking_extruder_nr) const { for (Point& p : poly) { - p = Point(machine_size.max.x_ / 2 + p.X, machine_size.max.y_ / 2 - p.Y); + p = Point(machine_size.max_.x_ / 2 + p.X, machine_size.max_.y_ / 2 - p.Y); } } } diff --git a/src/slicer.cpp b/src/slicer.cpp index c2d62866ff..ee971db3b5 100644 --- a/src/slicer.cpp +++ b/src/slicer.cpp @@ -986,7 +986,7 @@ std::vector Slicer::buildLayersWithHeight( coord_t adjusted_layer_offset = initial_layer_thickness; if (use_variable_layer_heights) { - layers_res[0].z = (*adaptive_layers)[0].z_position; + layers_res[0].z = (*adaptive_layers)[0].z_position_; } else if (slicing_tolerance == SlicingTolerance::MIDDLE) { @@ -999,7 +999,7 @@ std::vector Slicer::buildLayersWithHeight( { if (use_variable_layer_heights) { - layers_res[layer_nr].z = (*adaptive_layers)[layer_nr].z_position; + layers_res[layer_nr].z = (*adaptive_layers)[layer_nr].z_position_; } else { diff --git a/src/support.cpp b/src/support.cpp index 810d78cd9c..66bc59eb91 100644 --- a/src/support.cpp +++ b/src/support.cpp @@ -485,8 +485,8 @@ Polygons AreaSupport::join(const SliceDataStorage& storage, const Polygons& supp case BuildPlateShape::ELLIPTIC: { // Construct an ellipse to approximate the build volume. - const coord_t width = storage.machine_size.max.x_ - storage.machine_size.min.x_; - const coord_t depth = storage.machine_size.max.y_ - storage.machine_size.min.y_; + const coord_t width = storage.machine_size.max_.x_ - storage.machine_size.min_.x_; + const coord_t depth = storage.machine_size.max_.y_ - storage.machine_size.min_.y_; Polygon border_circle; constexpr unsigned int circle_resolution = 50; for (unsigned int i = 0; i < circle_resolution; i++) @@ -730,8 +730,8 @@ void AreaSupport::precomputeCrossInfillTree(SliceDataStorage& storage) } const coord_t aabb_expansion = infill_settings.get("support_offset"); AABB3D aabb_here(mesh.bounding_box); - aabb_here.include(aabb_here.min - Point3(-aabb_expansion, -aabb_expansion, 0)); - aabb_here.include(aabb_here.max + Point3(-aabb_expansion, -aabb_expansion, 0)); + aabb_here.include(aabb_here.min_ - Point3(-aabb_expansion, -aabb_expansion, 0)); + aabb_here.include(aabb_here.max_ + Point3(-aabb_expansion, -aabb_expansion, 0)); aabb.include(aabb_here); } diff --git a/src/utils/AABB.cpp b/src/utils/AABB.cpp index 1d6fab5e0f..2b966afe1b 100644 --- a/src/utils/AABB.cpp +++ b/src/utils/AABB.cpp @@ -10,55 +10,55 @@ namespace cura { -AABB::AABB() : min(POINT_MAX, POINT_MAX), max(POINT_MIN, POINT_MIN) +AABB::AABB() : min_(POINT_MAX, POINT_MAX), max_(POINT_MIN, POINT_MIN) { } -AABB::AABB(const Point& min, const Point& max) : min(min), max(max) +AABB::AABB(const Point& min, const Point& max) : min_(min), max_(max) { } -AABB::AABB(const Polygons& polys) : min(POINT_MAX, POINT_MAX), max(POINT_MIN, POINT_MIN) +AABB::AABB(const Polygons& polys) : min_(POINT_MAX, POINT_MAX), max_(POINT_MIN, POINT_MIN) { calculate(polys); } -AABB::AABB(ConstPolygonRef poly) : min(POINT_MAX, POINT_MAX), max(POINT_MIN, POINT_MIN) +AABB::AABB(ConstPolygonRef poly) : min_(POINT_MAX, POINT_MAX), max_(POINT_MIN, POINT_MIN) { calculate(poly); } Point AABB::getMiddle() const { - return (min + max) / 2; + return (min_ + max_) / 2; } coord_t AABB::distanceSquared(const Point& p) const { - const Point a = Point(max.X, min.Y); - const Point b = Point(min.X, max.Y); + const Point a = Point(max_.X, min_.Y); + const Point b = Point(min_.X, max_.Y); return (contains(p) ? -1 : 1) - * std::min({ LinearAlg2D::getDist2FromLineSegment(min, a, p), LinearAlg2D::getDist2FromLineSegment(a, max, p), LinearAlg2D::getDist2FromLineSegment(max, b, p), LinearAlg2D::getDist2FromLineSegment(b, min, p) }); + * std::min({ LinearAlg2D::getDist2FromLineSegment(min_, a, p), LinearAlg2D::getDist2FromLineSegment(a, max_, p), LinearAlg2D::getDist2FromLineSegment(max_, b, p), LinearAlg2D::getDist2FromLineSegment(b, min_, p) }); } coord_t AABB::distanceSquared(const AABB& other) const { return std::min({ - distanceSquared(other.min), - other.distanceSquared(min), - distanceSquared(other.max), - other.distanceSquared(max), - distanceSquared(Point(other.max.X, other.min.Y)), - other.distanceSquared(Point(max.X, min.Y)), - distanceSquared(Point(other.min.X, other.max.Y)), - other.distanceSquared(Point(min.X, max.Y)), + distanceSquared(other.min_), + other.distanceSquared(min_), + distanceSquared(other.max_), + other.distanceSquared(max_), + distanceSquared(Point(other.max_.X, other.min_.Y)), + other.distanceSquared(Point(max_.X, min_.Y)), + distanceSquared(Point(other.min_.X, other.max_.Y)), + other.distanceSquared(Point(min_.X, max_.Y)), }); } void AABB::calculate(const Polygons& polys) { - min = Point(POINT_MAX, POINT_MAX); - max = Point(POINT_MIN, POINT_MIN); + min_ = Point(POINT_MAX, POINT_MAX); + max_ = Point(POINT_MIN, POINT_MIN); for (unsigned int i = 0; i < polys.size(); i++) { for (unsigned int j = 0; j < polys[i].size(); j++) @@ -70,8 +70,8 @@ void AABB::calculate(const Polygons& polys) void AABB::calculate(ConstPolygonRef poly) { - min = Point(POINT_MAX, POINT_MAX); - max = Point(POINT_MIN, POINT_MIN); + min_ = Point(POINT_MAX, POINT_MAX); + max_ = Point(POINT_MIN, POINT_MIN); for (const Point& p : poly) { include(p); @@ -80,7 +80,7 @@ void AABB::calculate(ConstPolygonRef poly) bool AABB::contains(const Point& point) const { - return point.X >= min.X && point.X <= max.X && point.Y >= min.Y && point.Y <= max.Y; + return point.X >= min_.X && point.X <= max_.X && point.Y >= min_.Y && point.Y <= max_.Y; } bool AABB::contains(const AABB& other) const @@ -93,67 +93,67 @@ bool AABB::contains(const AABB& other) const { return true; } - return other.min.X >= min.X && other.max.X <= max.X && other.min.Y >= min.Y && other.max.Y <= max.Y; + return other.min_.X >= min_.X && other.max_.X <= max_.X && other.min_.Y >= min_.Y && other.max_.Y <= max_.Y; } coord_t AABB::area() const { - if (max.X < min.X || max.Y < min.Y) + if (max_.X < min_.X || max_.Y < min_.Y) { return -1; } // Do the unititialized check explicitly, so there aren't any problems with over/underflow and POINT_MAX/POINT_MIN. - return (max.X - min.X) * (max.Y - min.Y); + return (max_.X - min_.X) * (max_.Y - min_.Y); } bool AABB::hit(const AABB& other) const { - if (max.X < other.min.X) + if (max_.X < other.min_.X) return false; - if (min.X > other.max.X) + if (min_.X > other.max_.X) return false; - if (max.Y < other.min.Y) + if (max_.Y < other.min_.Y) return false; - if (min.Y > other.max.Y) + if (min_.Y > other.max_.Y) return false; return true; } void AABB::include(Point point) { - min.X = std::min(min.X, point.X); - min.Y = std::min(min.Y, point.Y); - max.X = std::max(max.X, point.X); - max.Y = std::max(max.Y, point.Y); + min_.X = std::min(min_.X, point.X); + min_.Y = std::min(min_.Y, point.Y); + max_.X = std::max(max_.X, point.X); + max_.Y = std::max(max_.Y, point.Y); } void AABB::include(const AABB other) { // Note that this is different from including the min and max points, since when 'min > max' it's used to denote an negative/empty box. - min.X = std::min(min.X, other.min.X); - min.Y = std::min(min.Y, other.min.Y); - max.X = std::max(max.X, other.max.X); - max.Y = std::max(max.Y, other.max.Y); + min_.X = std::min(min_.X, other.min_.X); + min_.Y = std::min(min_.Y, other.min_.Y); + max_.X = std::max(max_.X, other.max_.X); + max_.Y = std::max(max_.Y, other.max_.Y); } void AABB::expand(int dist) { - if (min == Point(POINT_MAX, POINT_MAX) || max == Point(POINT_MIN, POINT_MIN)) + if (min_ == Point(POINT_MAX, POINT_MAX) || max_ == Point(POINT_MIN, POINT_MIN)) { return; } - min.X -= dist; - min.Y -= dist; - max.X += dist; - max.Y += dist; + min_.X -= dist; + min_.Y -= dist; + max_.X += dist; + max_.Y += dist; } Polygon AABB::toPolygon() const { Polygon ret; - ret.add(min); - ret.add(Point(max.X, min.Y)); - ret.add(max); - ret.add(Point(min.X, max.Y)); + ret.add(min_); + ret.add(Point(max_.X, min_.Y)); + ret.add(max_); + ret.add(Point(min_.X, max_.Y)); return ret; } diff --git a/src/utils/AABB3D.cpp b/src/utils/AABB3D.cpp index b354ad0dc2..4ace7d4cea 100644 --- a/src/utils/AABB3D.cpp +++ b/src/utils/AABB3D.cpp @@ -11,31 +11,31 @@ namespace cura { AABB3D::AABB3D() - : min(std::numeric_limits::max(), std::numeric_limits::max(), std::numeric_limits::max()) - , max(std::numeric_limits::min(), std::numeric_limits::min(), std::numeric_limits::min()) + : min_(std::numeric_limits::max(), std::numeric_limits::max(), std::numeric_limits::max()) + , max_(std::numeric_limits::min(), std::numeric_limits::min(), std::numeric_limits::min()) { } AABB3D::AABB3D(Point3 min, Point3 max) - : min(min) - , max(max) + : min_(min) + , max_(max) { } Point3 AABB3D::getMiddle() const { - return (min + max) / 2; + return (min_ + max_) / 2; } AABB AABB3D::flatten() const { - return AABB(Point(min.x_, min.y_), Point(max.x_, max.y_)); + return AABB(Point(min_.x_, min_.y_), Point(max_.x_, max_.y_)); } bool AABB3D::hit(const AABB3D& other) const { - if (max.x_ < other.min.x_ || min.x_ > other.max.x_ || max.y_ < other.min.y_ || min.y_ > other.max.y_ || max.z_ < other.min.z_ || min.z_ > other.max.z_) + if (max_.x_ < other.min_.x_ || min_.x_ > other.max_.x_ || max_.y_ < other.min_.y_ || min_.y_ > other.max_.y_ || max_.z_ < other.min_.z_ || min_.z_ > other.max_.z_) { return false; } @@ -44,53 +44,53 @@ bool AABB3D::hit(const AABB3D& other) const AABB3D AABB3D::include(Point3 p) { - min.x_ = std::min(min.x_, p.x_); - min.y_ = std::min(min.y_, p.y_); - min.z_ = std::min(min.z_, p.z_); - max.x_ = std::max(max.x_, p.x_); - max.y_ = std::max(max.y_, p.y_); - max.z_ = std::max(max.z_, p.z_); + min_.x_ = std::min(min_.x_, p.x_); + min_.y_ = std::min(min_.y_, p.y_); + min_.z_ = std::min(min_.z_, p.z_); + max_.x_ = std::max(max_.x_, p.x_); + max_.y_ = std::max(max_.y_, p.y_); + max_.z_ = std::max(max_.z_, p.z_); return *this; } AABB3D AABB3D::include(const AABB3D& aabb) { // Note that this is different from including the min and max points, since when 'min > max' it's used to denote an negative/empty box. - min.x_ = std::min(min.x_, aabb.min.x_); - min.y_ = std::min(min.y_, aabb.min.y_); - min.z_ = std::min(min.z_, aabb.min.z_); - max.x_ = std::max(max.x_, aabb.max.x_); - max.y_ = std::max(max.y_, aabb.max.y_); - max.z_ = std::max(max.z_, aabb.max.z_); + min_.x_ = std::min(min_.x_, aabb.min_.x_); + min_.y_ = std::min(min_.y_, aabb.min_.y_); + min_.z_ = std::min(min_.z_, aabb.min_.z_); + max_.x_ = std::max(max_.x_, aabb.max_.x_); + max_.y_ = std::max(max_.y_, aabb.max_.y_); + max_.z_ = std::max(max_.z_, aabb.max_.z_); return *this; } AABB3D AABB3D::includeZ(coord_t z) { - min.z_ = std::min(min.z_, z); - max.z_ = std::max(max.z_, z); + min_.z_ = std::min(min_.z_, z); + max_.z_ = std::max(max_.z_, z); return *this; } AABB3D AABB3D::translate(Point3 offset) { - min += offset; - max += offset; + min_ += offset; + max_ += offset; return *this; } AABB3D AABB3D::translate(Point offset) { - min += offset; - max += offset; + min_ += offset; + max_ += offset; return *this; } AABB3D AABB3D::expand(coord_t outset) { - min -= Point3(outset, outset, outset); - max += Point3(outset, outset, outset); - if (min.x_ > max.x_ || min.y_ > max.y_ || min.z_ > max.z_) + min_ -= Point3(outset, outset, outset); + max_ += Point3(outset, outset, outset); + if (min_.x_ > max_.x_ || min_.y_ > max_.y_ || min_.z_ > max_.z_) { // make this AABB3D invalid *this = AABB3D(); } @@ -99,9 +99,9 @@ AABB3D AABB3D::expand(coord_t outset) AABB3D AABB3D::expandXY(coord_t outset) { - min -= Point3(outset, outset, 0); - max += Point3(outset, outset, 0); - if (min.x_ > max.x_ || min.y_ > max.y_) + min_ -= Point3(outset, outset, 0); + max_ += Point3(outset, outset, 0); + if (min_.x_ > max_.x_ || min_.y_ > max_.y_) { // make this AABB3D invalid *this = AABB3D(); } diff --git a/src/utils/Date.cpp b/src/utils/Date.cpp index d08f058158..52065c72bc 100644 --- a/src/utils/Date.cpp +++ b/src/utils/Date.cpp @@ -12,25 +12,25 @@ namespace cura { Date::Date(int year, int month, int day) -: year(year) -, month(month) -, day(day) +: year_(year) +, month_(month) +, day_(day) { } std::string Date::toStringDashed() { std::ostringstream str; - str << std::setfill('0') << std::setw(4) << year << "-" - << std::setfill('0') << std::setw(2) << month << "-" - << std::setfill('0') << std::setw(2) << day; + str << std::setfill('0') << std::setw(4) << year_ << "-" + << std::setfill('0') << std::setw(2) << month_ << "-" + << std::setfill('0') << std::setw(2) << day_; return str.str(); } Date::Date() -: year(-1) -, month(-1) -, day(-1) +: year_(-1) +, month_(-1) +, day_(-1) { } @@ -42,13 +42,13 @@ Date Date::getDate() char s_month[5]; static const char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec"; - std::sscanf(build_date, "%s %d %d", s_month, &ret.day, &ret.year); + std::sscanf(build_date, "%s %d %d", s_month, &ret.day_, &ret.year_); - ret.month = (strstr(month_names, s_month) - month_names) / 3; + ret.month_ = (strstr(month_names, s_month) - month_names) / 3; - ret.month++; // humans count Jan as month 1, not zero + ret.month_++; // humans count Jan as month 1, not zero return ret; } -} // namespace cura \ No newline at end of file +} // namespace cura diff --git a/src/utils/ExtrusionJunction.cpp b/src/utils/ExtrusionJunction.cpp index 972891a9f6..5a7cdb49b9 100644 --- a/src/utils/ExtrusionJunction.cpp +++ b/src/utils/ExtrusionJunction.cpp @@ -8,15 +8,15 @@ namespace cura bool ExtrusionJunction::operator ==(const ExtrusionJunction& other) const { - return p == other.p - && w == other.w - && perimeter_index == other.perimeter_index; + return p_ == other.p_ + && w_ == other.w_ + && perimeter_index_ == other.perimeter_index_; } ExtrusionJunction::ExtrusionJunction(const Point p, const coord_t w, const coord_t perimeter_index) - : p(p), - w(w), - perimeter_index(perimeter_index) + : p_(p), + w_(w), + perimeter_index_(perimeter_index) {} } diff --git a/src/utils/ExtrusionLine.cpp b/src/utils/ExtrusionLine.cpp index ac15007692..b16a247f63 100644 --- a/src/utils/ExtrusionLine.cpp +++ b/src/utils/ExtrusionLine.cpp @@ -1,48 +1,53 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. + +#include "utils/ExtrusionLine.h" #include -#include "utils/ExtrusionLine.h" -#include "utils/linearAlg2D.h" #include "utils/Simplify.h" +#include "utils/linearAlg2D.h" namespace cura { ExtrusionLine::ExtrusionLine(const size_t inset_idx, const bool is_odd) -: inset_idx(inset_idx) -, is_odd(is_odd) -, is_closed(false) -{} + : inset_idx_(inset_idx) + , is_odd_(is_odd) + , is_closed_(false) +{ +} coord_t ExtrusionLine::getLength() const { - if (junctions.empty()) + if (junctions_.empty()) { return 0; } coord_t len = 0; - ExtrusionJunction prev = junctions.front(); - for (const ExtrusionJunction& next : junctions) + ExtrusionJunction prev = junctions_.front(); + for (const ExtrusionJunction& next : junctions_) { - len += vSize(next.p - prev.p); + len += vSize(next.p_ - prev.p_); prev = next; } - if (is_closed) + if (is_closed_) { - len += vSize(front().p - back().p); + len += vSize(front().p_ - back().p_); } return len; } coord_t ExtrusionLine::getMinimalWidth() const { - return std::min_element(junctions.cbegin(), junctions.cend(), - [](const ExtrusionJunction& l, const ExtrusionJunction& r) - { - return l.w < r.w; - })->w; + return std::min_element( + junctions_.cbegin(), + junctions_.cend(), + [](const ExtrusionJunction& l, const ExtrusionJunction& r) + { + return l.w_ < r.w_; + }) + ->w_; } -} +} // namespace cura diff --git a/src/utils/ExtrusionSegment.cpp b/src/utils/ExtrusionSegment.cpp index 6c152c5612..9e6edb8c5d 100644 --- a/src/utils/ExtrusionSegment.cpp +++ b/src/utils/ExtrusionSegment.cpp @@ -18,7 +18,7 @@ Polygons ExtrusionSegment::toPolygons() Polygons ExtrusionSegment::toPolygons(bool reduced) { Polygons ret; - const Point vec = to_.p - from_.p; + const Point vec = to_.p_ - from_.p_; const coord_t vec_length = vSize(vec); if (vec_length <= 0) // Don't even output the endcaps. @@ -27,10 +27,10 @@ Polygons ExtrusionSegment::toPolygons(bool reduced) } PolygonRef poly = ret.newPoly(); - const double delta_r = 0.5 * std::abs(from_.w - to_.w); + const double delta_r = 0.5 * std::abs(from_.w_ - to_.w_); const double vec_length_fixed = std::max(delta_r, static_cast(vec_length)); float alpha = std::acos(delta_r / vec_length_fixed); // Angle between the slope along the edge of the polygon (due to varying line width) and the centerline. - if (to_.w > from_.w) + if (to_.w_ > from_.w_) { alpha = std::numbers::pi - alpha; } @@ -49,7 +49,7 @@ Polygons ExtrusionSegment::toPolygons(bool reduced) // Draw the endcap on the "from" vertex's end. { - poly.emplace_back(from_.p + Point(from_.w / 2 * cos(alpha + dir), from_.w / 2 * sin(alpha + dir))); + poly.emplace_back(from_.p_ + Point(from_.w_ / 2 * cos(alpha + dir), from_.w_ / 2 * sin(alpha + dir))); double start_a = 2 * std::numbers::pi; while (start_a > alpha + dir) @@ -67,18 +67,18 @@ Polygons ExtrusionSegment::toPolygons(bool reduced) // Draw the endcap. for (double a = start_a; a <= end_a; a += a_step) { - poly.emplace_back(from_.p + Point(from_.w / 2 * cos(a), from_.w / 2 * sin(a))); + poly.emplace_back(from_.p_ + Point(from_.w_ / 2 * cos(a), from_.w_ / 2 * sin(a))); } - poly.emplace_back(from_.p + Point(from_.w / 2 * cos(2 * std::numbers::pi - alpha + dir), from_.w / 2 * sin(2 * std::numbers::pi - alpha + dir))); + poly.emplace_back(from_.p_ + Point(from_.w_ / 2 * cos(2 * std::numbers::pi - alpha + dir), from_.w_ / 2 * sin(2 * std::numbers::pi - alpha + dir))); } // Draw the endcap on the "to" vertex's end. { poly.emplace_back( - to_.p + to_.p_ + Point( - to_.w / 2 * cos(2 * std::numbers::pi - alpha + dir), - to_.w / 2 * sin(2 * std::numbers::pi - alpha + dir))); // Also draws the main diagonal from the "from" vertex to the "to" vertex! + to_.w_ / 2 * cos(2 * std::numbers::pi - alpha + dir), + to_.w_ / 2 * sin(2 * std::numbers::pi - alpha + dir))); // Also draws the main diagonal from the "from" vertex to the "to" vertex! double start_a = 2 * std::numbers::pi; while (start_a > alpha + dir) @@ -109,18 +109,18 @@ Polygons ExtrusionSegment::toPolygons(bool reduced) { for (double a = end_a; a >= start_a; a -= a_step) // Go in the opposite direction. { - poly.emplace_back(to_.p + Point(to_.w / 2 * cos(a), to_.w / 2 * sin(a))); + poly.emplace_back(to_.p_ + Point(to_.w_ / 2 * cos(a), to_.w_ / 2 * sin(a))); } } else { for (double a = end_a; a <= start_a; a += a_step) { - poly.emplace_back(to_.p + Point(to_.w / 2 * cos(a), to_.w / 2 * sin(a))); + poly.emplace_back(to_.p_ + Point(to_.w_ / 2 * cos(a), to_.w_ / 2 * sin(a))); } } - poly.emplace_back(to_.p + Point(to_.w / 2 * cos(alpha + dir), to_.w / 2 * sin(alpha + dir))); + poly.emplace_back(to_.p_ + Point(to_.w_ / 2 * cos(alpha + dir), to_.w_ / 2 * sin(alpha + dir))); // The other main diagonal from the "to" vertex to the "from" vertex is implicit in the closing of the polygon. } @@ -138,15 +138,15 @@ Polygons ExtrusionSegment::toPolygons(bool reduced) std::vector ExtrusionSegment::discretize(coord_t step_size) { - Point a = from_.p; - Point b = to_.p; + Point a = from_.p_; + Point b = to_.p_; Point ab = b - a; coord_t ab_length = vSize(ab); coord_t step_count = std::max(static_cast(1), (ab_length + step_size / 2) / step_size); std::vector discretized; for (coord_t step = 0; step < step_count; step++) { - ExtrusionJunction mid(a + ab * (step + 1) / step_count, from_.w + (to_.w - from_.w) * (step + 1) / step_count, from_.perimeter_index); + ExtrusionJunction mid(a + ab * (step + 1) / step_count, from_.w_ + (to_.w_ - from_.w_) * (step + 1) / step_count, from_.perimeter_index_); discretized.emplace_back(from_, mid, is_odd_, true); from_ = mid; } diff --git a/src/utils/ListPolyIt.cpp b/src/utils/ListPolyIt.cpp index 86d8e44676..93cad91774 100644 --- a/src/utils/ListPolyIt.cpp +++ b/src/utils/ListPolyIt.cpp @@ -70,8 +70,8 @@ ListPolyIt ListPolyIt::insertPointNonDuplicate(const ListPolyIt before, const Li } else { - ListPolygon& poly = *after.poly; - return ListPolyIt(poly, poly.insert(after.it, to_insert)); + ListPolygon& poly = *after.poly_; + return ListPolyIt(poly, poly.insert(after.it_, to_insert)); } } diff --git a/src/utils/PolygonConnector.cpp b/src/utils/PolygonConnector.cpp index b984010dc9..5aae9257f2 100644 --- a/src/utils/PolygonConnector.cpp +++ b/src/utils/PolygonConnector.cpp @@ -51,7 +51,7 @@ Point PolygonConnector::getPosition(const Point& vertex) const Point PolygonConnector::getPosition(const ExtrusionJunction& junction) const { - return junction.p; + return junction.p_; } coord_t PolygonConnector::getWidth(const Point&) const @@ -61,7 +61,7 @@ coord_t PolygonConnector::getWidth(const Point&) const coord_t PolygonConnector::getWidth(const ExtrusionJunction& junction) const { - return junction.w; + return junction.w_; } void PolygonConnector::addVertex(Polygon& polygonal, const Point& position, const coord_t) const @@ -100,7 +100,7 @@ ExtrusionLine PolygonConnector::createEmpty() const constexpr size_t inset_index = 1; //Specialising to set inset_index to 1 instead of maximum int. Connected polys are not specific to any inset. constexpr bool is_odd = false; ExtrusionLine result(inset_index, is_odd); - result.is_closed = true; + result.is_closed_ = true; return result; //No copy, via RVO. } diff --git a/src/utils/PolylineStitcher.cpp b/src/utils/PolylineStitcher.cpp index 5bec622839..7346613e83 100644 --- a/src/utils/PolylineStitcher.cpp +++ b/src/utils/PolylineStitcher.cpp @@ -12,7 +12,7 @@ namespace cura template<> bool PolylineStitcher::canReverse(const PathsPointIndex& ppi) { - if ((*ppi.polygons_)[ppi.poly_idx_].is_odd) + if ((*ppi.polygons_)[ppi.poly_idx_].is_odd_) { return true; } @@ -31,7 +31,7 @@ bool PolylineStitcher::canReverse(const PathsPointInde template<> bool PolylineStitcher::canConnect(const ExtrusionLine& a, const ExtrusionLine& b) { - return a.is_odd == b.is_odd; + return a.is_odd_ == b.is_odd_; } template<> @@ -43,7 +43,7 @@ bool PolylineStitcher::canConnect(const Polygon&, cons template<> bool PolylineStitcher::isOdd(const ExtrusionLine& line) { - return line.is_odd; + return line.is_odd_; } template<> diff --git a/src/utils/ProximityPointLink.cpp b/src/utils/ProximityPointLink.cpp deleted file mode 100644 index 77944d3cc9..0000000000 --- a/src/utils/ProximityPointLink.cpp +++ /dev/null @@ -1,28 +0,0 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. - -#include "utils/ProximityPointLink.h" - -namespace cura -{ - -ProximityPointLink::ProximityPointLink(const ListPolyIt a, const ListPolyIt b, int dist, const ProximityPointLinkType type) -: a(a) -, b(b) -, dist(dist) -, type(type) -{ -} - -bool ProximityPointLink::operator==(const ProximityPointLink& other) const -{ - return (a == other.a && b == other.b) || (a == other.b && b == other.a); -} - -void ProximityPointLink::setDist(coord_t distance) const -{ - ProximityPointLink& thiss = *const_cast(this); - thiss.dist = distance; -} - -}//namespace cura diff --git a/src/utils/SVG.cpp b/src/utils/SVG.cpp index 317bd32fba..497f3fe6b7 100644 --- a/src/utils/SVG.cpp +++ b/src/utils/SVG.cpp @@ -64,21 +64,21 @@ SVG::SVG(std::string filename, AABB aabb, Point canvas_size, ColorObject backgro filename, aabb, std::min( - static_cast(canvas_size.X - canvas_size.X / 5 * 2) / static_cast(aabb.max.X - aabb.min.X), - static_cast(canvas_size.Y - canvas_size.Y / 5) / static_cast(aabb.max.Y - aabb.min.Y)), + static_cast(canvas_size.X - canvas_size.X / 5 * 2) / static_cast(aabb.max_.X - aabb.min_.X), + static_cast(canvas_size.Y - canvas_size.Y / 5) / static_cast(aabb.max_.Y - aabb.min_.Y)), canvas_size, background) { } SVG::SVG(std::string filename, AABB aabb, double scale, ColorObject background) - : SVG(filename, aabb, scale, (aabb.max - aabb.min) * scale, background) + : SVG(filename, aabb, scale, (aabb.max_ - aabb.min_) * scale, background) { } SVG::SVG(std::string filename, AABB aabb, double scale, Point canvas_size, ColorObject background) : aabb_(aabb) - , aabb_size_(aabb.max - aabb.min) + , aabb_size_(aabb.max_ - aabb.min_) , canvas_size_(canvas_size) , scale_(scale) , background_(background) @@ -100,8 +100,8 @@ SVG::SVG(std::string filename, AABB aabb, double scale, Point canvas_size, Color fprintf(out_, "(aabb_.max.Y - aabb_.min.Y)); - fprintf(out_, " width=\"%f\"\n", scale_ * static_cast(aabb_.max.X - aabb_.min.X)); + fprintf(out_, " height=\"%f\"\n", scale_ * static_cast(aabb_.max_.Y - aabb_.min_.Y)); + fprintf(out_, " width=\"%f\"\n", scale_ * static_cast(aabb_.max_.X - aabb_.min_.X)); fprintf(out_, " version=\"1.1\">\n"); fprintf(out_, " (p.X - aabb_.min.X) * scale_), std::llrint(static_cast(p.Y - aabb_.min.Y) * scale_)); + return Point(std::llrint(static_cast(p.X - aabb_.min_.X) * scale_), std::llrint(static_cast(p.Y - aabb_.min_.Y) * scale_)); } Point3D SVG::transformF(const Point& p) const { - return Point3D(static_cast(p.X - aabb_.min.X) * scale_, static_cast(p.Y - aabb_.min.Y) * scale_, 0.0); + return Point3D(static_cast(p.X - aabb_.min_.X) * scale_, static_cast(p.Y - aabb_.min_.Y) * scale_, 0.0); } void SVG::writeComment(const std::string& comment) const @@ -435,25 +435,25 @@ void SVG::writeLines(const VariableWidthLines& lines, const ColorObject color, c void SVG::writeLine(const ExtrusionLine& line, const ColorObject color, const double width_factor) const { constexpr double minimum_line_width = 10; // Always have some width, otherwise some lines become completely invisible. - if (line.junctions.empty()) // Only draw lines that have at least 2 junctions, otherwise they are degenerate. + if (line.junctions_.empty()) // Only draw lines that have at least 2 junctions, otherwise they are degenerate. { return; } - ExtrusionJunction start_vertex = line.junctions[0]; - for (size_t index = 1; index < line.junctions.size(); ++index) + ExtrusionJunction start_vertex = line.junctions_[0]; + for (size_t index = 1; index < line.junctions_.size(); ++index) { - ExtrusionJunction end_vertex = line.junctions[index]; + ExtrusionJunction end_vertex = line.junctions_[index]; // Compute the corners of the trapezoid for this variable-width line segment. - const Point direction_vector = end_vertex.p - start_vertex.p; + const Point direction_vector = end_vertex.p_ - start_vertex.p_; const Point direction_left = turn90CCW(direction_vector); const Point direction_right = -direction_left; // Opposite of left. const Point3D start_left - = transformF(start_vertex.p + normal(direction_left, std::llrint(std::max(minimum_line_width, static_cast(start_vertex.w) * width_factor)))); + = transformF(start_vertex.p_ + normal(direction_left, std::llrint(std::max(minimum_line_width, static_cast(start_vertex.w_) * width_factor)))); const Point3D start_right - = transformF(start_vertex.p + normal(direction_right, std::llrint(std::max(minimum_line_width, static_cast(start_vertex.w) * width_factor)))); - const Point3D end_left = transformF(end_vertex.p + normal(direction_left, std::llrint(std::max(minimum_line_width, static_cast(end_vertex.w) * width_factor)))); - const Point3D end_right = transformF(end_vertex.p + normal(direction_right, std::llrint(std::max(minimum_line_width, static_cast(end_vertex.w) * width_factor)))); + = transformF(start_vertex.p_ + normal(direction_right, std::llrint(std::max(minimum_line_width, static_cast(start_vertex.w_) * width_factor)))); + const Point3D end_left = transformF(end_vertex.p_ + normal(direction_left, std::llrint(std::max(minimum_line_width, static_cast(end_vertex.w_) * width_factor)))); + const Point3D end_right = transformF(end_vertex.p_ + normal(direction_right, std::llrint(std::max(minimum_line_width, static_cast(end_vertex.w_) * width_factor)))); fprintf( out_, @@ -475,22 +475,22 @@ void SVG::writeLine(const ExtrusionLine& line, const ColorObject color, const do void SVG::writeCoordinateGrid(const coord_t grid_size, const Color color, const double stroke_width, const double font_size) const { constexpr double dist_from_edge = 0.05; // As fraction of image width or height. - const coord_t min_x = aabb_.min.X - (aabb_.min.X % grid_size); - const coord_t min_y = aabb_.min.Y - (aabb_.min.Y % grid_size); + const coord_t min_x = aabb_.min_.X - (aabb_.min_.X % grid_size); + const coord_t min_y = aabb_.min_.Y - (aabb_.min_.Y % grid_size); - for (coord_t x = min_x; x < aabb_.max.X; x += grid_size) + for (coord_t x = min_x; x < aabb_.max_.X; x += grid_size) { - writeLine(Point(x, aabb_.min.Y), Point(x, aabb_.max.Y), color, stroke_width); + writeLine(Point(x, aabb_.min_.Y), Point(x, aabb_.max_.Y), color, stroke_width); std::stringstream ss; ss << INT2MM(x); - writeText(Point(x, std::llrint(static_cast(aabb_.min.Y) + static_cast(aabb_.max.Y - aabb_.min.Y) * dist_from_edge)), ss.str(), color, font_size); + writeText(Point(x, std::llrint(static_cast(aabb_.min_.Y) + static_cast(aabb_.max_.Y - aabb_.min_.Y) * dist_from_edge)), ss.str(), color, font_size); } - for (coord_t y = min_y; y < aabb_.max.Y; y += grid_size) + for (coord_t y = min_y; y < aabb_.max_.Y; y += grid_size) { - writeLine(Point(aabb_.min.X, y), Point(aabb_.max.Y, y), color, stroke_width); + writeLine(Point(aabb_.min_.X, y), Point(aabb_.max_.Y, y), color, stroke_width); std::stringstream ss; ss << INT2MM(y); - writeText(Point(std::llrint(static_cast(aabb_.min.X) + static_cast(aabb_.max.X - aabb_.min.X) * dist_from_edge), y), ss.str(), color, font_size); + writeText(Point(std::llrint(static_cast(aabb_.min_.X) + static_cast(aabb_.max_.X - aabb_.min_.X) * dist_from_edge), y), ss.str(), color, font_size); } } diff --git a/src/utils/Simplify.cpp b/src/utils/Simplify.cpp index 19ec8f04a4..ed2dc9edb5 100644 --- a/src/utils/Simplify.cpp +++ b/src/utils/Simplify.cpp @@ -10,15 +10,15 @@ namespace cura { Simplify::Simplify(const coord_t max_resolution, const coord_t max_deviation, const coord_t max_area_deviation) - : max_resolution(max_resolution) - , max_deviation(max_deviation) - , max_area_deviation(max_area_deviation) + : max_resolution_(max_resolution) + , max_deviation_(max_deviation) + , max_area_deviation_(max_area_deviation) {} Simplify::Simplify(const Settings& settings) - : max_resolution(settings.get("meshfix_maximum_resolution")) - , max_deviation(settings.get("meshfix_maximum_deviation")) - , max_area_deviation(settings.get("meshfix_maximum_extrusion_area_deviation")) + : max_resolution_(settings.get("meshfix_maximum_resolution")) + , max_deviation_(settings.get("meshfix_maximum_deviation")) + , max_area_deviation_(settings.get("meshfix_maximum_extrusion_area_deviation")) {} Polygons Simplify::polygon(const Polygons& polygons) const @@ -86,8 +86,8 @@ Polygon Simplify::createEmpty(const Polygon& original) const ExtrusionLine Simplify::createEmpty(const ExtrusionLine& original) const { - ExtrusionLine result(original.inset_idx, original.is_odd); - result.is_closed = original.is_closed; + ExtrusionLine result(original.inset_idx_, original.is_odd_); + result.is_closed_ = original.is_closed_; return result; } @@ -98,7 +98,7 @@ void Simplify::appendVertex(Polygon& polygon, const Point& vertex) const void Simplify::appendVertex(ExtrusionLine& extrusion_line, const ExtrusionJunction& vertex) const { - extrusion_line.junctions.push_back(vertex); + extrusion_line.junctions_.push_back(vertex); } const Point& Simplify::getPosition(const Point& vertex) const @@ -108,7 +108,7 @@ const Point& Simplify::getPosition(const Point& vertex) const const Point& Simplify::getPosition(const ExtrusionJunction& vertex) const { - return vertex.p; + return vertex.p_; } Point Simplify::createIntersection(const Point& before, const Point intersection, const Point& after) const @@ -121,7 +121,7 @@ ExtrusionJunction Simplify::createIntersection(const ExtrusionJunction& before, //Average the extrusion width of the line. //More correct would be to see where along the line the intersection occurs with a projection or something. //But these details are so small, and this solution is so much quicker and simpler. - return ExtrusionJunction(intersection, (before.w + after.w) / 2, before.perimeter_index); + return ExtrusionJunction(intersection, (before.w_ + after.w_) / 2, before.perimeter_index_); } coord_t Simplify::getAreaDeviation(const Point& before, const Point& vertex, const Point& after) const @@ -155,13 +155,13 @@ coord_t Simplify::getAreaDeviation(const ExtrusionJunction& before, const Extrus { return 0; //Either of the line segments is zero, so the deviation of one of the line segments doesn't matter (not printed). So effectively there is no deviation. } - const coord_t width_diff = std::max(std::abs(vertex.w - before.w), std::abs(after.w - vertex.w)); + const coord_t width_diff = std::max(std::abs(vertex.w_ - before.w_), std::abs(after.w_ - vertex.w_)); if (width_diff > 1) { // Adjust the width only if there is a difference, or else the rounding errors may produce the wrong // weighted average value. - const coord_t ab_weight = (before.w + vertex.w) / 2; - const coord_t bc_weight = (vertex.w + after.w) / 2; + const coord_t ab_weight = (before.w_ + vertex.w_) / 2; + const coord_t bc_weight = (vertex.w_ + after.w_) / 2; const coord_t weighted_average_width = (ab_length * ab_weight + bc_length * bc_weight) / ac_length; return std::abs(ab_weight - weighted_average_width) * ab_length + std::abs(bc_weight - weighted_average_width) * bc_length; } @@ -172,4 +172,4 @@ coord_t Simplify::getAreaDeviation(const ExtrusionJunction& before, const Extrus } } -} \ No newline at end of file +} diff --git a/src/utils/ToolpathVisualizer.cpp b/src/utils/ToolpathVisualizer.cpp index 1b5d294b89..22b3b489f3 100644 --- a/src/utils/ToolpathVisualizer.cpp +++ b/src/utils/ToolpathVisualizer.cpp @@ -22,8 +22,8 @@ void ToolpathVisualizer::toolpaths(const std::vector& all_segm for (size_t segment_idx = 0; segment_idx < all_segments.size(); segment_idx++) { ExtrusionSegment s = all_segments[segment_idx]; - s.from_.w *= w / .9; - s.to_.w *= w / .9; + s.from_.w_ *= w / .9; + s.to_.w_ *= w / .9; Polygons covered = s.toPolygons(false); polys.add(covered); } @@ -65,23 +65,23 @@ void ToolpathVisualizer::width_legend(const Polygons& input, coord_t nozzle_size return ss.str(); }; AABB aabb(input); - ExtrusionJunction legend_btm(Point(aabb.max.X + nozzle_size + max_dev, aabb.max.Y), nozzle_size - max_dev, 0); - ExtrusionJunction legend_top(Point(aabb.max.X + nozzle_size + max_dev, aabb.min.Y), nozzle_size + max_dev, 0); - ExtrusionJunction legend_mid((legend_top.p + legend_btm.p) / 2, (legend_top.w + legend_btm.w) / 2, 0); - legend_btm.p += (legend_mid.p - legend_btm.p) / 4; - legend_top.p += (legend_mid.p - legend_top.p) / 4; + ExtrusionJunction legend_btm(Point(aabb.max_.X + nozzle_size + max_dev, aabb.max_.Y), nozzle_size - max_dev, 0); + ExtrusionJunction legend_top(Point(aabb.max_.X + nozzle_size + max_dev, aabb.min_.Y), nozzle_size + max_dev, 0); + ExtrusionJunction legend_mid((legend_top.p_ + legend_btm.p_) / 2, (legend_top.w_ + legend_btm.w_) / 2, 0); + legend_btm.p_ += (legend_mid.p_ - legend_btm.p_) / 4; + legend_top.p_ += (legend_mid.p_ - legend_top.p_) / 4; ExtrusionSegment legend_segment(legend_btm, legend_top, true, false); svg_.writeAreas(legend_segment.toPolygons(false), SVG::ColorObject(200, 200, 200), SVG::Color::NONE); // real outline std::vector all_segments_plus; all_segments_plus.emplace_back(legend_segment); // colored Point legend_text_offset(nozzle_size, 0); - svg_.writeText(legend_top.p + legend_text_offset, to_string(INT2MM(legend_top.w))); - svg_.writeText(legend_btm.p + legend_text_offset, to_string(INT2MM(legend_btm.w))); - svg_.writeText(legend_mid.p + legend_text_offset, to_string(INT2MM(legend_mid.w))); - svg_.writeLine(legend_top.p, legend_top.p + legend_text_offset); - svg_.writeLine(legend_btm.p, legend_btm.p + legend_text_offset); - svg_.writeLine(legend_mid.p, legend_mid.p + legend_text_offset); + svg_.writeText(legend_top.p_ + legend_text_offset, to_string(INT2MM(legend_top.w_))); + svg_.writeText(legend_btm.p_ + legend_text_offset, to_string(INT2MM(legend_btm.w_))); + svg_.writeText(legend_mid.p_ + legend_text_offset, to_string(INT2MM(legend_mid.w_))); + svg_.writeLine(legend_top.p_, legend_top.p_ + legend_text_offset); + svg_.writeLine(legend_btm.p_, legend_btm.p_ + legend_text_offset); + svg_.writeLine(legend_mid.p_, legend_mid.p_ + legend_text_offset); widths(all_segments_plus, nozzle_size, max_dev, min_w, rounded_visualization); } @@ -113,7 +113,7 @@ void ToolpathVisualizer::widths( // ss.to.w *= w; for (ExtrusionSegment s : ss.discretize(MM2INT(0.1))) { - coord_t avg_w = (s.from_.w + s.to_.w) / 2; + coord_t avg_w = (s.from_.w_ + s.to_.w_) / 2; Point3 clr; double color_ratio = std::min(1.0, double(std::abs(avg_w - nozzle_size)) / max_dev); color_ratio = color_ratio * .5 + .5 * sqrt(color_ratio); @@ -133,16 +133,16 @@ void ToolpathVisualizer::widths( // clr.y = clr.y * (255 - 92 * clr.dot(green) / green.vSize() / 255) / 255; if (exaggerate_widths) { - s.from_.w = std::max(min_w, min_w + (s.from_.w - (nozzle_size - max_dev)) * 5 / 4); - s.to_.w = std::max(min_w, min_w + (s.to_.w - (nozzle_size - max_dev)) * 5 / 4); + s.from_.w_ = std::max(min_w, min_w + (s.from_.w_ - (nozzle_size - max_dev)) * 5 / 4); + s.to_.w_ = std::max(min_w, min_w + (s.to_.w_ - (nozzle_size - max_dev)) * 5 / 4); } // else // { // s.from.w *= 0.9; // s.to.w *= 0.9; // } - s.from_.w *= w / .9; - s.to_.w *= w / .9; + s.from_.w_ *= w / .9; + s.to_.w_ *= w / .9; Polygons covered = s.toPolygons(); svg_.writeAreas(covered, SVG::ColorObject(clr.x_, clr.y_, clr.z_), SVG::Color::NONE); } diff --git a/src/utils/VoxelUtils.cpp b/src/utils/VoxelUtils.cpp index a00b0d4dfd..31ecf2bf4c 100644 --- a/src/utils/VoxelUtils.cpp +++ b/src/utils/VoxelUtils.cpp @@ -9,11 +9,11 @@ namespace cura { DilationKernel::DilationKernel(GridPoint3 kernel_size, DilationKernel::Type type) - : kernel_size(kernel_size) - , type(type) + : kernel_size_(kernel_size) + , type_(type) { coord_t mult = kernel_size.x_ * kernel_size.y_ * kernel_size.z_; // multiplier for division to avoid rounding and to avoid use of floating point numbers - relative_cells.reserve(mult); + relative_cells_.reserve(mult); GridPoint3 half_kernel = kernel_size / 2; GridPoint3 start = -half_kernel; @@ -40,7 +40,7 @@ DilationKernel::DilationKernel(GridPoint3 kernel_size, DilationKernel::Type type continue; // don't consider this cell } } - relative_cells.emplace_back(x, y, z); + relative_cells_.emplace_back(x, y, z); } } } @@ -116,7 +116,7 @@ bool VoxelUtils::walkPolygons(const Polygons& polys, coord_t z, const std::funct bool VoxelUtils::walkDilatedPolygons(const Polygons& polys, coord_t z, const DilationKernel& kernel, const std::function& process_cell_func) const { Polygons translated = polys; - const Point3 translation = (Point3(1, 1, 1) - kernel.kernel_size % 2) * cell_size_ / 2; + const Point3 translation = (Point3(1, 1, 1) - kernel.kernel_size_ % 2) * cell_size_ / 2; if (translation.x_ && translation.y_) { translated.translate(Point(translation.x_, translation.y_)); @@ -152,7 +152,7 @@ bool VoxelUtils::_walkAreas(const Polygons& polys, coord_t z, const std::functio bool VoxelUtils::walkDilatedAreas(const Polygons& polys, coord_t z, const DilationKernel& kernel, const std::function& process_cell_func) const { Polygons translated = polys; - const Point3 translation = (Point3(1, 1, 1) - kernel.kernel_size % 2) * cell_size_ / 2 // offset half a cell when using a n even kernel + const Point3 translation = (Point3(1, 1, 1) - kernel.kernel_size_ % 2) * cell_size_ / 2 // offset half a cell when using a n even kernel - cell_size_ / 2; // offset half a cell so that the dots of spreadDotsArea are centered on the middle of the cell isntead of the lower corners. if (translation.x_ && translation.y_) { @@ -165,7 +165,7 @@ std::function VoxelUtils::dilate(const DilationKernel& kernel, { return [&process_cell_func, &kernel](GridPoint3 loc) { - for (const GridPoint3& rel : kernel.relative_cells) + for (const GridPoint3& rel : kernel.relative_cells_) { bool continue_ = process_cell_func(loc + rel); if (! continue_) diff --git a/src/utils/channel.cpp b/src/utils/channel.cpp index 2a4c775767..45d1711b1b 100644 --- a/src/utils/channel.cpp +++ b/src/utils/channel.cpp @@ -3,11 +3,11 @@ #include "utils/channel.h" -#include "utils/resources/certificate.pem.h" - #include #include +#include "utils/resources/certificate.pem.h" + namespace cura::utils { namespace details @@ -17,23 +17,23 @@ inline constexpr static bool ALLOW_REMOTE_CHANNELS = ENABLE_REMOTE_PLUGINS; std::shared_ptr createChannel(const ChannelSetupConfiguration& config) { - constexpr auto create_credentials = [](const ChannelSetupConfiguration& config) + constexpr auto create_credentials = [](const ChannelSetupConfiguration& actual_config) { - if (config.host == "localhost" || config.host == "127.0.0.1") + if (actual_config.host == "localhost" || actual_config.host == "127.0.0.1") { - spdlog::info("Create local channel on port {}.", config.port); + spdlog::info("Create local channel on port {}.", actual_config.port); return grpc::InsecureChannelCredentials(); } if (details::ALLOW_REMOTE_CHANNELS) { - spdlog::info("Create local channel on port {}.", config.port); + spdlog::info("Create local channel on port {}.", actual_config.port); auto creds_config = grpc::SslCredentialsOptions(); creds_config.pem_root_certs = resources::certificate; return grpc::SslCredentials(creds_config); } // Create empty credentials, so it'll make a dummy channel where all operations fail. // This is consistent with creating a channel with the wrong credentials as it where. - spdlog::warn("Remote plugins where disabled, will not connect to {}:{}.", config.host, config.port); + spdlog::warn("Remote plugins where disabled, will not connect to {}:{}.", actual_config.host, actual_config.port); return std::shared_ptr(); }; grpc::ChannelArguments args; diff --git a/src/utils/polygonUtils.cpp b/src/utils/polygonUtils.cpp index a3d6b3c315..e314c1e5f9 100644 --- a/src/utils/polygonUtils.cpp +++ b/src/utils/polygonUtils.cpp @@ -655,17 +655,19 @@ ClosestPolygonPoint PolygonUtils::ensureInsideOrOutside( } // try once more with half the preferred distance inside - int64_t max_dist2_here = std::numeric_limits::max(); // we already concluded we are close enough to the closest_poly when we obtained the closest_polygon_point - moveInside2(*loc_to_line_polygons, closest_poly, from, preferred_dist_inside / 2, max_dist2_here, loc_to_line_grid, penalty_function); - bool is_inside = closest_poly.inside(from) == is_outside_boundary; // inside a hole is outside the part - if (is_inside == (preferred_dist_inside > 0)) - { // we ended up on the right side of the polygon - // assume we didn't overshoot another polygon in [polygons] - return closest_polygon_point; + { + int64_t max_dist2_here = std::numeric_limits::max(); // we already concluded we are close enough to the closest_poly when we obtained the closest_polygon_point + moveInside2(*loc_to_line_polygons, closest_poly, from, preferred_dist_inside / 2, max_dist2_here, loc_to_line_grid, penalty_function); + bool is_inside = closest_poly.inside(from) == is_outside_boundary; // inside a hole is outside the part + if (is_inside == (preferred_dist_inside > 0)) + { // we ended up on the right side of the polygon + // assume we didn't overshoot another polygon in [polygons] + return closest_polygon_point; + } } + // if above fails, we perform an offset and sit directly on the offsetted polygon (and keep the result from the above moveInside) // The offset is performed on the closest reference polygon in order to save computation time - else { const coord_t offset = (is_outside_boundary) ? -preferred_dist_inside : preferred_dist_inside; // perform inset on outer boundary and outset on holes Polygons insetted @@ -1058,7 +1060,7 @@ std::vector> Point x = p0 + normal(p0p1, middle_point_nr * grid_size); dist_to_p1 -= grid_size; - std::optional best_here = findClose(x, destination, destination_loc_to_line, penalty_function); + best_here = findClose(x, destination, destination_loc_to_line, penalty_function); if (best_here) { ret.push_back(std::make_pair(ClosestPolygonPoint(x, p0_idx, from), *best_here)); @@ -1336,8 +1338,8 @@ bool PolygonUtils::polygonOutlinesAdjacent(const ConstPolygonRef inner_poly, con // Heuristic check if their AABBs are near first. AABB inner_aabb(inner_poly); AABB outer_aabb(outer_poly); - inner_aabb.max += Point(max_gap, max_gap); // Expand one of them by way of a "distance" by checking intersection with the expanded rectangle. - inner_aabb.min -= Point(max_gap, max_gap); + inner_aabb.max_ += Point(max_gap, max_gap); // Expand one of them by way of a "distance" by checking intersection with the expanded rectangle. + inner_aabb.min_ -= Point(max_gap, max_gap); if (! inner_aabb.hit(outer_aabb)) { return false; @@ -1562,8 +1564,8 @@ Polygons PolygonUtils::clipPolygonWithAABB(const Polygons& src, const AABB& aabb auto sides = [aabb](const Point& p) { - return int(p.X < aabb.min.X) * int(Side::Left) + int(p.X > aabb.max.X) * int(Side::Right) + int(p.Y < aabb.min.Y) * int(Side::Bottom) - + int(p.Y > aabb.max.Y) * int(Side::Top); + return int(p.X < aabb.min_.X) * int(Side::Left) + int(p.X > aabb.max_.X) * int(Side::Right) + int(p.Y < aabb.min_.Y) * int(Side::Bottom) + + int(p.Y > aabb.max_.Y) * int(Side::Top); }; int sides_prev = sides(path.back()); diff --git a/tests/integration/SlicePhaseTest.cpp b/tests/integration/SlicePhaseTest.cpp index c357169170..291c2acd15 100644 --- a/tests/integration/SlicePhaseTest.cpp +++ b/tests/integration/SlicePhaseTest.cpp @@ -79,7 +79,7 @@ TEST_F(SlicePhaseTest, Cube) const auto initial_layer_thickness = scene.settings.get("layer_height_0"); constexpr bool variable_layer_height = false; constexpr std::vector* variable_layer_height_values = nullptr; - const size_t num_layers = (cube_mesh.getAABB().max.z - initial_layer_thickness) / layer_thickness + 1; + const size_t num_layers = (cube_mesh.getAABB().max_.z - initial_layer_thickness) / layer_thickness + 1; Slicer slicer(&cube_mesh, layer_thickness, num_layers, variable_layer_height, variable_layer_height_values); ASSERT_EQ(slicer.layers.size(), num_layers) << "The number of layers in the output must equal the requested number of layers."; @@ -140,7 +140,7 @@ TEST_F(SlicePhaseTest, Cylinder1000) const auto initial_layer_thickness = scene.settings.get("layer_height_0"); constexpr bool variable_layer_height = false; constexpr std::vector* variable_layer_height_values = nullptr; - const size_t num_layers = (cylinder_mesh.getAABB().max.z - initial_layer_thickness) / layer_thickness + 1; + const size_t num_layers = (cylinder_mesh.getAABB().max_.z - initial_layer_thickness) / layer_thickness + 1; Slicer slicer(&cylinder_mesh, layer_thickness, num_layers, variable_layer_height, variable_layer_height_values); ASSERT_EQ(slicer.layers.size(), num_layers) << "The number of layers in the output must equal the requested number of layers."; diff --git a/tests/utils/AABB3DTest.cpp b/tests/utils/AABB3DTest.cpp index 854d25dcc5..7bfb51d7db 100644 --- a/tests/utils/AABB3DTest.cpp +++ b/tests/utils/AABB3DTest.cpp @@ -112,8 +112,8 @@ TEST(AABB3DTest, TestInclude) AABB3D empty; box2.include(empty); - EXPECT_EQ(box2.min, a) << "Inclusion of an 'empty' or negative box should not change the minimum of the original."; - EXPECT_EQ(box2.max, b) << "Inclusion of an 'empty' or negative box should not change the maximum of the original."; + EXPECT_EQ(box2.min_, a) << "Inclusion of an 'empty' or negative box should not change the minimum of the original."; + EXPECT_EQ(box2.max_, b) << "Inclusion of an 'empty' or negative box should not change the maximum of the original."; } TEST(AABB3DTest, TestTranslate) diff --git a/tests/utils/AABBTest.cpp b/tests/utils/AABBTest.cpp index f70d4162c4..e09245e3bb 100644 --- a/tests/utils/AABBTest.cpp +++ b/tests/utils/AABBTest.cpp @@ -131,8 +131,8 @@ TEST(AABBTest, TestInclude) AABB empty; box2.include(empty); - EXPECT_EQ(box2.min, a) << "Inclusion of an 'empty' or negative box should not change the minimum of the original."; - EXPECT_EQ(box2.max, b) << "Inclusion of an 'empty' or negative box should not change the maximum of the original."; + EXPECT_EQ(box2.min_, a) << "Inclusion of an 'empty' or negative box should not change the minimum of the original."; + EXPECT_EQ(box2.max_, b) << "Inclusion of an 'empty' or negative box should not change the maximum of the original."; } TEST(AABBTest, TestExpand) @@ -156,7 +156,7 @@ TEST(AABBTest, TestToPolygon) Polygon polygon = box.toPolygon(); - EXPECT_EQ(polygon.area(), (box.max.X - box.min.X) * (box.max.Y - box.min.Y)) << "The polygon from the bounding box should have the same area."; + EXPECT_EQ(polygon.area(), (box.max_.X - box.min_.X) * (box.max_.Y - box.min_.Y)) << "The polygon from the bounding box should have the same area."; EXPECT_EQ(polygon.centerOfMass(), box.getMiddle()) << "The center of mass of an (AA) rectangle is its middle."; } // NOLINTEND(*-magic-numbers) From ddfbb1ea50ccdb4fe9c8a2ccf8db23a039d42659 Mon Sep 17 00:00:00 2001 From: wawanbreton Date: Wed, 22 Nov 2023 08:33:24 +0000 Subject: [PATCH 27/48] Applied clang-format. --- .../OuterWallInsetBeadingStrategy.h | 50 +-- include/ExtruderTrain.h | 10 +- include/InsetOrderOptimizer.h | 6 +- include/InterlockingGenerator.h | 73 ++-- include/MeshGroup.h | 12 +- include/PathOrder.h | 19 +- include/PathOrdering.h | 25 +- include/SkeletalTrapezoidationEdge.h | 4 +- include/TreeModelVolumes.h | 44 +-- include/TreeSupportElement.h | 281 +++++++-------- include/TreeSupportSettings.h | 319 ++++++++---------- include/TreeSupportUtils.h | 4 +- include/WallToolPaths.h | 30 +- include/WallsComputation.h | 8 +- include/gcodeExport.h | 4 +- include/infill/LightningTreeNode.h | 6 +- include/pathPlanning/Comb.h | 99 +++--- include/pathPlanning/LinePolygonsCrossings.h | 97 +++--- include/plugins/pluginproxy.h | 26 +- include/progress/ProgressEstimatorLinear.h | 7 +- include/settings/FlowTempGraph.h | 15 +- include/settings/ZSeamConfig.h | 16 +- include/utils/AABB.h | 25 +- include/utils/ExtrusionJunction.h | 6 +- include/utils/PolygonConnector.h | 267 ++++++++------- include/utils/PolylineStitcher.h | 166 ++++----- include/utils/SquareGrid.h | 30 +- .../OuterWallInsetBeadingStrategy.cpp | 20 +- src/ExtruderTrain.cpp | 11 +- src/PathOrderPath.cpp | 70 ++-- src/Preheat.cpp | 3 +- src/Slice.cpp | 6 +- src/communication/CommandLine.cpp | 16 +- src/gcodeExport.cpp | 3 +- src/infill/LightningDistanceField.cpp | 77 ++--- src/infill/ZigzagConnectorProcessor.cpp | 19 +- src/multiVolumes.cpp | 4 +- src/pathPlanning/Comb.cpp | 8 +- src/progress/ProgressStageEstimator.cpp | 16 +- src/settings/ZSeamConfig.cpp | 14 +- src/utils/AABB.cpp | 25 +- src/utils/Date.cpp | 22 +- src/utils/ExtrusionJunction.cpp | 21 +- src/utils/FMatrix4x3.cpp | 3 +- src/utils/ListPolyIt.cpp | 9 +- src/utils/PolygonConnector.cpp | 28 +- src/utils/PolygonsPointIndex.cpp | 6 +- src/utils/PolylineStitcher.cpp | 7 +- src/utils/Simplify.cpp | 38 ++- src/utils/SquareGrid.cpp | 48 ++- 50 files changed, 1083 insertions(+), 1040 deletions(-) diff --git a/include/BeadingStrategy/OuterWallInsetBeadingStrategy.h b/include/BeadingStrategy/OuterWallInsetBeadingStrategy.h index 87fb2b8258..c8c6eae31d 100644 --- a/include/BeadingStrategy/OuterWallInsetBeadingStrategy.h +++ b/include/BeadingStrategy/OuterWallInsetBeadingStrategy.h @@ -1,5 +1,5 @@ -//Copyright (c) 2020 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2020 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef OUTER_WALL_INSET_BEADING_STRATEGY_H #define OUTER_WALL_INSET_BEADING_STRATEGY_H @@ -8,28 +8,28 @@ namespace cura { - /* - * This is a meta strategy that allows for the outer wall to be inset towards the inside of the model. - */ - class OuterWallInsetBeadingStrategy : public BeadingStrategy - { - public: - OuterWallInsetBeadingStrategy(coord_t outer_wall_offset, BeadingStrategyPtr parent); - - virtual ~OuterWallInsetBeadingStrategy() = default; - - Beading compute(coord_t thickness, coord_t bead_count) const override; - - coord_t getOptimalThickness(coord_t bead_count) const override; - coord_t getTransitionThickness(coord_t lower_bead_count) const override; - coord_t getOptimalBeadCount(coord_t thickness) const override; - coord_t getTransitioningLength(coord_t lower_bead_count) const override; - - virtual std::string toString() const; - - private: - BeadingStrategyPtr parent_; - coord_t outer_wall_offset_; - }; +/* + * This is a meta strategy that allows for the outer wall to be inset towards the inside of the model. + */ +class OuterWallInsetBeadingStrategy : public BeadingStrategy +{ +public: + OuterWallInsetBeadingStrategy(coord_t outer_wall_offset, BeadingStrategyPtr parent); + + virtual ~OuterWallInsetBeadingStrategy() = default; + + Beading compute(coord_t thickness, coord_t bead_count) const override; + + coord_t getOptimalThickness(coord_t bead_count) const override; + coord_t getTransitionThickness(coord_t lower_bead_count) const override; + coord_t getOptimalBeadCount(coord_t thickness) const override; + coord_t getTransitioningLength(coord_t lower_bead_count) const override; + + virtual std::string toString() const; + +private: + BeadingStrategyPtr parent_; + coord_t outer_wall_offset_; +}; } // namespace cura #endif // OUTER_WALL_INSET_BEADING_STRATEGY_H diff --git a/include/ExtruderTrain.h b/include/ExtruderTrain.h index 14ede169f4..1aaccf715a 100644 --- a/include/ExtruderTrain.h +++ b/include/ExtruderTrain.h @@ -1,14 +1,14 @@ -//Copyright (c) 2018 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2018 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef EXTRUDER_TRAIN_H #define EXTRUDER_TRAIN_H #include "settings/Settings.h" -namespace cura +namespace cura { - + class ExtruderTrain { public: @@ -32,5 +32,5 @@ class ExtruderTrain const size_t extruder_nr_; }; -}//namespace cura +} // namespace cura #endif // EXTRUDER_TRAIN_H diff --git a/include/InsetOrderOptimizer.h b/include/InsetOrderOptimizer.h index e5592806a2..eadde17b9a 100644 --- a/include/InsetOrderOptimizer.h +++ b/include/InsetOrderOptimizer.h @@ -4,11 +4,11 @@ #ifndef INSET_ORDER_OPTIMIZER_H #define INSET_ORDER_OPTIMIZER_H +#include + #include "settings/ZSeamConfig.h" #include "sliceDataStorage.h" -#include - namespace cura { @@ -105,7 +105,7 @@ class InsetOrderOptimizer std::vector> inset_polys_; // vector of vectors holding the inset polygons Polygons retraction_region_; // After printing an outer wall, move into this region so that retractions do not leave visible blobs. Calculated lazily if needed (see - // retraction_region_calculated). + // retraction_region_calculated). /*! * Determine if the paths should be reversed diff --git a/include/InterlockingGenerator.h b/include/InterlockingGenerator.h index 5ff35fd9fc..02bebde68b 100644 --- a/include/InterlockingGenerator.h +++ b/include/InterlockingGenerator.h @@ -1,15 +1,15 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef INTERLOCKING_GENERATOR_H #define INTERLOCKING_GENERATOR_H -#include #include #include +#include -#include "utils/polygon.h" #include "utils/VoxelUtils.h" +#include "utils/polygon.h" namespace cura { @@ -18,17 +18,17 @@ class Slicer; /*! * Class for generating an interlocking structure between two adjacent models of a different extruder. - * + * * The structure consists of horizontal beams of the two materials interlaced. * In the z direction the direction of these beams is alternated with 90*. - * + * * Example with two materials # and O * Even beams: Odd beams: * ###### ##OO##OO * OOOOOO ##OO##OO * ###### ##OO##OO * OOOOOO ##OO##OO - * + * * One material of a single cell of the structure looks like this: * .-*-. * .-* *-. @@ -41,7 +41,7 @@ class Slicer; * | *-.-* .-* *-|-* * *-. | .-* * *-|-* - * + * * We set up a voxel grid of (2*beam_w,2*beam_w,2*beam_h) and mark all the voxels which contain both meshes. * We then remove all voxels which also contain air, so that the interlocking pattern will not be visible from the outside. * We then generate and combine the polygons for each voxel and apply those areas to the outlines ofthe meshes. @@ -71,21 +71,33 @@ class InterlockingGenerator * \param beam_layer_count The number of layers for the height of the beams * \param interface_dilation The thicknening kernel for the interface * \param air_dilation The thickening kernel applied to air so that cells near the outside of the model won't be generated - * \param air_filtering Whether to fully remove all of the interlocking cells which would be visible on the outside (i.e. touching air). If no air filtering then those cells will be cut off in the middle of a beam. + * \param air_filtering Whether to fully remove all of the interlocking cells which would be visible on the outside (i.e. touching air). If no air filtering then those cells + * will be cut off in the middle of a beam. */ - InterlockingGenerator(Slicer& mesh_a, Slicer& mesh_b, coord_t beam_width_a, coord_t beam_width_b, const PointMatrix& rotation, Point3 cell_size, coord_t beam_layer_count, DilationKernel interface_dilation, DilationKernel air_dilation, bool air_filtering) - : mesh_a_(mesh_a) - , mesh_b_(mesh_b) - , beam_width_a_(beam_width_a) - , beam_width_b_(beam_width_b) - , vu_(cell_size) - , rotation_(rotation) - , cell_size_(cell_size) - , beam_layer_count_(beam_layer_count) - , interface_dilation_(interface_dilation) - , air_dilation_(air_dilation) - , air_filtering_(air_filtering) - {} + InterlockingGenerator( + Slicer& mesh_a, + Slicer& mesh_b, + coord_t beam_width_a, + coord_t beam_width_b, + const PointMatrix& rotation, + Point3 cell_size, + coord_t beam_layer_count, + DilationKernel interface_dilation, + DilationKernel air_dilation, + bool air_filtering) + : mesh_a_(mesh_a) + , mesh_b_(mesh_b) + , beam_width_a_(beam_width_a) + , beam_width_b_(beam_width_b) + , vu_(cell_size) + , rotation_(rotation) + , cell_size_(cell_size) + , beam_layer_count_(beam_layer_count) + , interface_dilation_(interface_dilation) + , air_dilation_(air_dilation) + , air_filtering_(air_filtering) + { + } /*! Given two polygons, return the parts that border on air, and grow 'perpendicular' up to 'detect' distance. * @@ -106,16 +118,16 @@ class InterlockingGenerator /*! * Compute the voxels overlapping with the shell of both models. * This includes the walls, but also top/bottom skin. - * + * * \param kernel The dilation kernel to give the returned voxel shell more thickness * \return The shell voxels for mesh a and those for mesh b */ std::vector> getShellVoxels(const DilationKernel& kernel) const; - + /*! * Compute the voxels overlapping with the shell of some layers. * This includes the walls, but also top/bottom skin. - * + * * \param layers The layer outlines for which to compute the shell voxels * \param kernel The dilation kernel to give the returned voxel shell more thickness * \param[out] cells The output cells which elong to the shell @@ -124,7 +136,7 @@ class InterlockingGenerator /*! * Compute the regions occupied by both models. - * + * * A morphological close is performed so that we don't register small gaps between the two models as being separate. * \return layer_regions The computed layer regions */ @@ -138,7 +150,7 @@ class InterlockingGenerator /*! * Change the outlines of the meshes with the computed interlocking structure. - * + * * \param cells The cells where we want to apply the interlocking structure. * \param layer_regions The total volume of the two meshes combined (and small gaps closed) */ @@ -158,9 +170,10 @@ class InterlockingGenerator const coord_t beam_layer_count_; const DilationKernel interface_dilation_; const DilationKernel air_dilation_; - const bool air_filtering_; //!< Whether to fully remove all of the interlocking cells which would be visible on the outside. If no air filtering then those cells will be cut off midway in a beam. + const bool air_filtering_; //!< Whether to fully remove all of the interlocking cells which would be visible on the outside. If no air filtering then those cells will be cut + //!< off midway in a beam. }; -}//namespace cura +} // namespace cura -#endif//INTERLOCKING_GENERATOR_H +#endif // INTERLOCKING_GENERATOR_H diff --git a/include/MeshGroup.h b/include/MeshGroup.h index 71ba1f6a6f..51a12be124 100644 --- a/include/MeshGroup.h +++ b/include/MeshGroup.h @@ -1,5 +1,5 @@ -//Copyright (C) 2020 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (C) 2020 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef MESH_GROUP_H #define MESH_GROUP_H @@ -14,7 +14,7 @@ class Matrix4x3D; /*! * A MeshGroup is a collection with 1 or more 3D meshes. - * + * * One MeshGroup is a whole which is printed at once. * Generally there is one single MeshGroup, though when using one-at-a-time printing, multiple MeshGroups are processed consecutively. */ @@ -43,7 +43,7 @@ class MeshGroup : public NoCopy /*! * Load a Mesh from file and store it in the \p meshgroup. - * + * * \param meshgroup The meshgroup where to store the mesh * \param filename The filename of the mesh file * \param transformation The transformation applied to all vertices @@ -52,6 +52,6 @@ class MeshGroup : public NoCopy */ bool loadMeshIntoMeshGroup(MeshGroup* meshgroup, const char* filename, const Matrix4x3D& transformation, Settings& object_parent_settings); -} //namespace cura +} // namespace cura -#endif //MESH_GROUP_H +#endif // MESH_GROUP_H diff --git a/include/PathOrder.h b/include/PathOrder.h index bb87aa0a44..53b4a3543a 100644 --- a/include/PathOrder.h +++ b/include/PathOrder.h @@ -1,5 +1,5 @@ -//Copyright (c) 2021 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2021 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef PATHORDER_H #define PATHORDER_H @@ -28,7 +28,6 @@ template class PathOrder { public: - /*! * After reordering, this contains the paths that need to be printed in the * correct order. @@ -108,25 +107,25 @@ class PathOrder */ void detectLoops() { - for(PathOrdering& path : paths_) + for (PathOrdering& path : paths_) { - if(path.is_closed_) //Already a polygon. No need to detect loops. + if (path.is_closed_) // Already a polygon. No need to detect loops. { continue; } - if(path.converted_->size() < 3) //Not enough vertices to really be a closed loop. + if (path.converted_->size() < 3) // Not enough vertices to really be a closed loop. { continue; } - if(vSize2(path.converted_->back() - path.converted_->front()) < coincident_point_distance_ * coincident_point_distance_) + if (vSize2(path.converted_->back() - path.converted_->front()) < coincident_point_distance_ * coincident_point_distance_) { - //Endpoints are really close to one another. Consider it a closed loop. + // Endpoints are really close to one another. Consider it a closed loop. path.is_closed_ = true; } } } }; -} +} // namespace cura -#endif //PATHORDER_H +#endif // PATHORDER_H diff --git a/include/PathOrdering.h b/include/PathOrdering.h index 96ce53863d..0ec185e700 100644 --- a/include/PathOrdering.h +++ b/include/PathOrdering.h @@ -1,5 +1,5 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef PATH_ORDER_PATH_H #define PATH_ORDER_PATH_H @@ -38,7 +38,8 @@ struct PathOrdering , start_vertex_(start_vertex) , is_closed_(is_closed) , backwards_(backwards) - {} + { + } /*! * The vertex data of the path. @@ -60,11 +61,11 @@ struct PathOrdering size_t start_vertex_; /*! - * Whether the path should be closed at the ends or not. - * - * If this path should be closed, it represents a polygon. If it should - * not be closed, it represents a polyline. - */ + * Whether the path should be closed at the ends or not. + * + * If this path should be closed, it represents a polygon. If it should + * not be closed, it represents a polyline. + */ bool is_closed_; /*! @@ -74,8 +75,8 @@ struct PathOrdering * backwards direction, if the last vertex is closer than the first. */ bool backwards_; - - + + /*! * Get vertex data from the custom path type. * @@ -102,6 +103,6 @@ struct PathOrdering std::optional cached_vertices_; }; -} +} // namespace cura -#endif //PATH_ORDER_PATH_H +#endif // PATH_ORDER_PATH_H diff --git a/include/SkeletalTrapezoidationEdge.h b/include/SkeletalTrapezoidationEdge.h index 75b0c06b73..a50abb9e65 100644 --- a/include/SkeletalTrapezoidationEdge.h +++ b/include/SkeletalTrapezoidationEdge.h @@ -4,12 +4,12 @@ #ifndef SKELETAL_TRAPEZOIDATION_EDGE_H #define SKELETAL_TRAPEZOIDATION_EDGE_H -#include "utils/ExtrusionJunction.h" - #include #include // smart pointers #include +#include "utils/ExtrusionJunction.h" + namespace cura { diff --git a/include/TreeModelVolumes.h b/include/TreeModelVolumes.h index 8418a9d2c4..9c9013888d 100644 --- a/include/TreeModelVolumes.h +++ b/include/TreeModelVolumes.h @@ -33,8 +33,7 @@ class TreeModelVolumes { public: TreeModelVolumes() = default; - TreeModelVolumes - ( + TreeModelVolumes( const SliceDataStorage& storage, coord_t max_move, coord_t max_move_slow, @@ -42,8 +41,7 @@ class TreeModelVolumes size_t current_mesh_idx, double progress_multiplier, double progress_offset, - const std::vector& additional_excluded_areas = std::vector() - ); + const std::vector& additional_excluded_areas = std::vector()); TreeModelVolumes(TreeModelVolumes&&) = default; TreeModelVolumes& operator=(TreeModelVolumes&&) = default; @@ -123,11 +121,9 @@ class TreeModelVolumes const Polygons& getPlaceableAreas(coord_t radius, LayerIndex layer_idx); /*! - * \brief Provides the area that represents the walls, as in the printed area, of the model. This is an abstract representation not equal with the outline. See calculateWallRestrictions for better description. - * \param radius The radius of the node of interest. - * \param layer_idx The layer of interest. - * \param min_xy_dist is the minimum xy distance used. - * \return Polygons object + * \brief Provides the area that represents the walls, as in the printed area, of the model. This is an abstract representation not equal with the outline. See + * calculateWallRestrictions for better description. \param radius The radius of the node of interest. \param layer_idx The layer of interest. \param min_xy_dist is the minimum + * xy distance used. \return Polygons object */ const Polygons& getWallRestriction(coord_t radius, LayerIndex layer_idx, bool min_xy_dist); @@ -289,7 +285,8 @@ class TreeModelVolumes void calculatePlaceables(const std::deque& keys); /*! - * \brief Creates the areas that have to be avoided by the tree's branches to prevent collision with the model without being able to place a branch with given radius on a single layer. + * \brief Creates the areas that have to be avoided by the tree's branches to prevent collision with the model without being able to place a branch with given radius on a + * single layer. * * The result is a 2D area that would cause nodes of radius \p radius to * collide with the model in a not wanted way. Result is saved in the cache. @@ -299,7 +296,8 @@ class TreeModelVolumes void calculateAvoidanceToModel(const std::deque& keys); /*! - * \brief Creates the areas that have to be avoided by the tree's branches to prevent collision with the model without being able to place a branch with given radius on a single layer. + * \brief Creates the areas that have to be avoided by the tree's branches to prevent collision with the model without being able to place a branch with given radius on a + * single layer. * * The result is a 2D area that would cause nodes of radius \p radius to * collide with the model in a not wanted way. Result is saved in the cache. @@ -311,9 +309,11 @@ class TreeModelVolumes } /*! - * \brief Creates the areas that can not be passed when expanding an area downwards. As such these areas are an somewhat abstract representation of a wall (as in a printed object). + * \brief Creates the areas that can not be passed when expanding an area downwards. As such these areas are an somewhat abstract representation of a wall (as in a printed + * object). * - * These areas are at least xy_min_dist wide. When calculating it is always assumed that every wall is printed on top of another (as in has an overlap with the wall a layer below). Result is saved in the corresponding cache. + * These areas are at least xy_min_dist wide. When calculating it is always assumed that every wall is printed on top of another (as in has an overlap with the wall a layer + * below). Result is saved in the corresponding cache. * * \param keys RadiusLayerPairs of all requested areas. Every radius will be calculated up to the provided layer. * @@ -322,9 +322,9 @@ class TreeModelVolumes void calculateWallRestrictions(const std::deque& keys); /*! - * \brief Creates the areas that can not be passed when expanding an area downwards. As such these areas are an somewhat abstract representation of a wall (as in a printed object). - * These areas are at least xy_min_dist wide. When calculating it is always assumed that every wall is printed on top of another (as in has an overlap with the wall a layer below). Result is saved in the corresponding cache. - * \param key RadiusLayerPair of the requested area. It well be will be calculated up to the provided layer. + * \brief Creates the areas that can not be passed when expanding an area downwards. As such these areas are an somewhat abstract representation of a wall (as in a printed + * object). These areas are at least xy_min_dist wide. When calculating it is always assumed that every wall is printed on top of another (as in has an overlap with the wall a + * layer below). Result is saved in the corresponding cache. \param key RadiusLayerPair of the requested area. It well be will be calculated up to the provided layer. */ void calculateWallRestrictions(RadiusLayerPair key) { @@ -336,7 +336,7 @@ class TreeModelVolumes * \param key RadiusLayerPair of the requested areas. The radius will be calculated up to the provided layer. * \return A wrapped optional reference of the requested area (if it was found, an empty optional if nothing was found) */ - template + template const std::optional> getArea(const std::unordered_map& cache, const KEY key) const; bool checkSettingsEquality(const Settings& me, const Settings& other) const; @@ -499,7 +499,8 @@ class TreeModelVolumes std::unique_ptr critical_placeable_areas_cache_ = std::make_unique(); /*! - * \brief Caches to avoid holes smaller than the radius until which the radius is always increased, as they are free of holes. Also called safe avoidances, as they are safe regarding not running into holes. + * \brief Caches to avoid holes smaller than the radius until which the radius is always increased, as they are free of holes. Also called safe avoidances, as they are safe + * regarding not running into holes. */ mutable std::unordered_map avoidance_cache_hole_; std::unique_ptr critical_avoidance_cache_holefree_ = std::make_unique(); @@ -513,7 +514,8 @@ class TreeModelVolumes mutable std::unordered_map wall_restrictions_cache_; std::unique_ptr critical_wall_restrictions_cache_ = std::make_unique(); - // A different cache for min_xy_dist as the maximal safe distance an influence area can be increased(guaranteed overlap of two walls in consecutive layer) is much smaller when min_xy_dist is used. This causes the area of the wall restriction to be thinner and as such just using the min_xy_dist wall restriction would be slower. + // A different cache for min_xy_dist as the maximal safe distance an influence area can be increased(guaranteed overlap of two walls in consecutive layer) is much smaller when + // min_xy_dist is used. This causes the area of the wall restriction to be thinner and as such just using the min_xy_dist wall restriction would be slower. mutable std::unordered_map wall_restrictions_cache_min_; std::unique_ptr critical_wall_restrictions_cache_min_ = std::make_unique(); @@ -522,6 +524,6 @@ class TreeModelVolumes Simplify simplifier_ = Simplify(0, 0, 0); // a simplifier to simplify polygons. Will be properly initialised in the constructor. }; -} +} // namespace cura -#endif //TREEMODELVOLUMES_H +#endif // TREEMODELVOLUMES_H diff --git a/include/TreeSupportElement.h b/include/TreeSupportElement.h index a463ce30fe..95bbb73eee 100644 --- a/include/TreeSupportElement.h +++ b/include/TreeSupportElement.h @@ -1,48 +1,41 @@ -//CuraEngine is released under the terms of the AGPLv3 or higher. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef TREESUPPORTELEMENT_H #define TREESUPPORTELEMENT_H +#include +#include + +#include + #include "TreeModelVolumes.h" #include "TreeSupportBaseCircle.h" #include "TreeSupportEnums.h" #include "settings/types/LayerIndex.h" #include "utils/Coord_t.h" #include "utils/polygon.h" -#include - -#include -#include namespace cura { struct AreaIncreaseSettings { - AreaIncreaseSettings() : - type_(AvoidanceType::FAST), - increase_speed_(0), - increase_radius_(false), - no_error_(false), - use_min_distance_(false), - move_(false) + AreaIncreaseSettings() + : type_(AvoidanceType::FAST) + , increase_speed_(0) + , increase_radius_(false) + , no_error_(false) + , use_min_distance_(false) + , move_(false) { } - AreaIncreaseSettings - ( - AvoidanceType type, - coord_t increase_speed, - bool increase_radius, - bool simplify, - bool use_min_distance, - bool move - ) : - type_(type), - increase_speed_(increase_speed), - increase_radius_(increase_radius), - no_error_(simplify), - use_min_distance_(use_min_distance), - move_(move) + AreaIncreaseSettings(AvoidanceType type, coord_t increase_speed, bool increase_radius, bool simplify, bool use_min_distance, bool move) + : type_(type) + , increase_speed_(increase_speed) + , increase_radius_(increase_radius) + , no_error_(simplify) + , use_min_distance_(use_min_distance) + , move_(move) { } @@ -55,20 +48,14 @@ struct AreaIncreaseSettings bool operator==(const AreaIncreaseSettings& other) const { - return - increase_radius_ == other.increase_radius_ && - increase_speed_ == other.increase_speed_ && - type_ == other.type_ && - no_error_ == other.no_error_ && - use_min_distance_ == other.use_min_distance_ && - move_ == other.move_; + return increase_radius_ == other.increase_radius_ && increase_speed_ == other.increase_speed_ && type_ == other.type_ && no_error_ == other.no_error_ + && use_min_distance_ == other.use_min_distance_ && move_ == other.move_; } }; struct TreeSupportElement { - TreeSupportElement - ( + TreeSupportElement( coord_t distance_to_top, size_t target_height, Point target_position, @@ -81,59 +68,58 @@ struct TreeSupportElement bool force_tips_to_roof, bool skip_ovalisation, bool influence_area_limit_active, - coord_t influence_area_limit_range - ) : - target_height_(target_height), - target_position_(target_position), - next_position_(target_position), - next_height_(target_height), - effective_radius_height_(distance_to_top), - to_buildplate_(to_buildplate), - distance_to_top_(distance_to_top), - area_(nullptr), - result_on_layer_(target_position), - increased_to_model_radius_(0), - to_model_gracious_(to_model_gracious), - buildplate_radius_increases_(0), - use_min_xy_dist_(use_min_xy_dist), - supports_roof_(supports_roof), - dont_move_until_(dont_move_until), - can_use_safe_radius_(can_use_safe_radius), - last_area_increase_(AreaIncreaseSettings(AvoidanceType::FAST, 0, false, false, false, false)), - missing_roof_layers_(force_tips_to_roof ? dont_move_until : 0), - skip_ovalisation_(skip_ovalisation), - all_tips_({ target_position }), - influence_area_limit_active_(influence_area_limit_active), - influence_area_limit_range_(influence_area_limit_range - ) + coord_t influence_area_limit_range) + : target_height_(target_height) + , target_position_(target_position) + , next_position_(target_position) + , next_height_(target_height) + , effective_radius_height_(distance_to_top) + , to_buildplate_(to_buildplate) + , distance_to_top_(distance_to_top) + , area_(nullptr) + , result_on_layer_(target_position) + , increased_to_model_radius_(0) + , to_model_gracious_(to_model_gracious) + , buildplate_radius_increases_(0) + , use_min_xy_dist_(use_min_xy_dist) + , supports_roof_(supports_roof) + , dont_move_until_(dont_move_until) + , can_use_safe_radius_(can_use_safe_radius) + , last_area_increase_(AreaIncreaseSettings(AvoidanceType::FAST, 0, false, false, false, false)) + , missing_roof_layers_(force_tips_to_roof ? dont_move_until : 0) + , skip_ovalisation_(skip_ovalisation) + , all_tips_({ target_position }) + , influence_area_limit_active_(influence_area_limit_active) + , influence_area_limit_range_(influence_area_limit_range) { RecreateInfluenceLimitArea(); } - TreeSupportElement(const TreeSupportElement& elem, Polygons* newArea = nullptr) : // copy constructor with possibility to set a new area - target_height_(elem.target_height_), - target_position_(elem.target_position_), - next_position_(elem.next_position_), - next_height_(elem.next_height_), - effective_radius_height_(elem.effective_radius_height_), - to_buildplate_(elem.to_buildplate_), - distance_to_top_(elem.distance_to_top_), - area_(newArea != nullptr ? newArea : elem.area_), - result_on_layer_(elem.result_on_layer_), - increased_to_model_radius_(elem.increased_to_model_radius_), - to_model_gracious_(elem.to_model_gracious_), - buildplate_radius_increases_(elem.buildplate_radius_increases_), - use_min_xy_dist_(elem.use_min_xy_dist_), - supports_roof_(elem.supports_roof_), - dont_move_until_(elem.dont_move_until_), - can_use_safe_radius_(elem.can_use_safe_radius_), - last_area_increase_(elem.last_area_increase_), - missing_roof_layers_(elem.missing_roof_layers_), - skip_ovalisation_(elem.skip_ovalisation_), - all_tips_(elem.all_tips_), - influence_area_limit_area_(elem.influence_area_limit_area_), - influence_area_limit_range_(elem.influence_area_limit_range_), - influence_area_limit_active_(elem.influence_area_limit_active_) + TreeSupportElement(const TreeSupportElement& elem, Polygons* newArea = nullptr) + : // copy constructor with possibility to set a new area + target_height_(elem.target_height_) + , target_position_(elem.target_position_) + , next_position_(elem.next_position_) + , next_height_(elem.next_height_) + , effective_radius_height_(elem.effective_radius_height_) + , to_buildplate_(elem.to_buildplate_) + , distance_to_top_(elem.distance_to_top_) + , area_(newArea != nullptr ? newArea : elem.area_) + , result_on_layer_(elem.result_on_layer_) + , increased_to_model_radius_(elem.increased_to_model_radius_) + , to_model_gracious_(elem.to_model_gracious_) + , buildplate_radius_increases_(elem.buildplate_radius_increases_) + , use_min_xy_dist_(elem.use_min_xy_dist_) + , supports_roof_(elem.supports_roof_) + , dont_move_until_(elem.dont_move_until_) + , can_use_safe_radius_(elem.can_use_safe_radius_) + , last_area_increase_(elem.last_area_increase_) + , missing_roof_layers_(elem.missing_roof_layers_) + , skip_ovalisation_(elem.skip_ovalisation_) + , all_tips_(elem.all_tips_) + , influence_area_limit_area_(elem.influence_area_limit_area_) + , influence_area_limit_range_(elem.influence_area_limit_range_) + , influence_area_limit_active_(elem.influence_area_limit_active_) { parents_.insert(parents_.begin(), elem.parents_.begin(), elem.parents_.end()); } @@ -141,37 +127,37 @@ struct TreeSupportElement /*! * \brief Create a new Element for one layer below the element of the pointer supplied. */ - TreeSupportElement(TreeSupportElement* element_above) : - target_height_(element_above->target_height_), - target_position_(element_above->target_position_), - next_position_(element_above->next_position_), - next_height_(element_above->next_height_), - effective_radius_height_(element_above->effective_radius_height_), - to_buildplate_(element_above->to_buildplate_), - distance_to_top_(element_above->distance_to_top_ + 1), - area_(element_above->area_), - result_on_layer_(Point(-1, -1)), // set to invalid as we are a new node on a new layer - increased_to_model_radius_(element_above->increased_to_model_radius_), - to_model_gracious_(element_above->to_model_gracious_), - buildplate_radius_increases_(element_above->buildplate_radius_increases_), - use_min_xy_dist_(element_above->use_min_xy_dist_), - supports_roof_(element_above->supports_roof_), - dont_move_until_(element_above->dont_move_until_), - can_use_safe_radius_(element_above->can_use_safe_radius_), - last_area_increase_(element_above->last_area_increase_), - missing_roof_layers_(element_above->missing_roof_layers_), - skip_ovalisation_(false), - all_tips_(element_above->all_tips_), - influence_area_limit_area_(element_above->influence_area_limit_area_), - influence_area_limit_range_(element_above->influence_area_limit_range_), - influence_area_limit_active_(element_above->influence_area_limit_active_) + TreeSupportElement(TreeSupportElement* element_above) + : target_height_(element_above->target_height_) + , target_position_(element_above->target_position_) + , next_position_(element_above->next_position_) + , next_height_(element_above->next_height_) + , effective_radius_height_(element_above->effective_radius_height_) + , to_buildplate_(element_above->to_buildplate_) + , distance_to_top_(element_above->distance_to_top_ + 1) + , area_(element_above->area_) + , result_on_layer_(Point(-1, -1)) + , // set to invalid as we are a new node on a new layer + increased_to_model_radius_(element_above->increased_to_model_radius_) + , to_model_gracious_(element_above->to_model_gracious_) + , buildplate_radius_increases_(element_above->buildplate_radius_increases_) + , use_min_xy_dist_(element_above->use_min_xy_dist_) + , supports_roof_(element_above->supports_roof_) + , dont_move_until_(element_above->dont_move_until_) + , can_use_safe_radius_(element_above->can_use_safe_radius_) + , last_area_increase_(element_above->last_area_increase_) + , missing_roof_layers_(element_above->missing_roof_layers_) + , skip_ovalisation_(false) + , all_tips_(element_above->all_tips_) + , influence_area_limit_area_(element_above->influence_area_limit_area_) + , influence_area_limit_range_(element_above->influence_area_limit_range_) + , influence_area_limit_active_(element_above->influence_area_limit_active_) { parents_ = { element_above }; } // ONLY to be called in merge as it assumes a few assurances made by it. - TreeSupportElement - ( + TreeSupportElement( const TreeSupportElement& first, const TreeSupportElement& second, size_t next_height, @@ -180,18 +166,17 @@ struct TreeSupportElement const std::function& getRadius, double diameter_scale_bp_radius, coord_t branch_radius, - double diameter_angle_scale_factor - ) : - next_position_(next_position), - next_height_(next_height), - area_(nullptr), - increased_to_model_radius_(increased_to_model_radius), - use_min_xy_dist_(first.use_min_xy_dist_ || second.use_min_xy_dist_), - supports_roof_(first.supports_roof_ || second.supports_roof_), - dont_move_until_(std::max(first.dont_move_until_, second.dont_move_until_)), - can_use_safe_radius_(first.can_use_safe_radius_ || second.can_use_safe_radius_), - missing_roof_layers_(std::min(first.missing_roof_layers_, second.missing_roof_layers_)), - skip_ovalisation_(false) + double diameter_angle_scale_factor) + : next_position_(next_position) + , next_height_(next_height) + , area_(nullptr) + , increased_to_model_radius_(increased_to_model_radius) + , use_min_xy_dist_(first.use_min_xy_dist_ || second.use_min_xy_dist_) + , supports_roof_(first.supports_roof_ || second.supports_roof_) + , dont_move_until_(std::max(first.dont_move_until_, second.dont_move_until_)) + , can_use_safe_radius_(first.can_use_safe_radius_ || second.can_use_safe_radius_) + , missing_roof_layers_(std::min(first.missing_roof_layers_, second.missing_roof_layers_)) + , skip_ovalisation_(false) { if (first.target_height_ > second.target_height_) { @@ -215,38 +200,31 @@ struct TreeSupportElement buildplate_radius_increases_ = 0; if (diameter_scale_bp_radius > 0) { - const coord_t foot_increase_radius = - std::abs - ( - std::max - ( - getRadius(second.effective_radius_height_, second.buildplate_radius_increases_), - getRadius(first.effective_radius_height_, first.buildplate_radius_increases_)) - getRadius(effective_radius_height_, buildplate_radius_increases_ - ) - ); + const coord_t foot_increase_radius = std::abs( + std::max( + getRadius(second.effective_radius_height_, second.buildplate_radius_increases_), + getRadius(first.effective_radius_height_, first.buildplate_radius_increases_)) + - getRadius(effective_radius_height_, buildplate_radius_increases_)); // 'buildplate_radius_increases' has to be recalculated, as when a smaller tree with a larger buildplate_radius_increases merge with a larger branch, // the buildplate_radius_increases may have to be lower as otherwise the radius suddenly increases. This results often in a non integer value. buildplate_radius_increases_ = foot_increase_radius / (branch_radius * (diameter_scale_bp_radius - diameter_angle_scale_factor)); } // set last settings to the best out of both parents. If this is wrong, it will only cause a small performance penalty instead of weird behavior. - last_area_increase_ = - AreaIncreaseSettings - ( - std::min(first.last_area_increase_.type_, second.last_area_increase_.type_), - std::min(first.last_area_increase_.increase_speed_, second.last_area_increase_.increase_speed_), - first.last_area_increase_.increase_radius_ || second.last_area_increase_.increase_radius_, - first.last_area_increase_.no_error_ || second.last_area_increase_.no_error_, - first.last_area_increase_.use_min_distance_ && second.last_area_increase_.use_min_distance_, - first.last_area_increase_.move_ || second.last_area_increase_.move_ - ); + last_area_increase_ = AreaIncreaseSettings( + std::min(first.last_area_increase_.type_, second.last_area_increase_.type_), + std::min(first.last_area_increase_.increase_speed_, second.last_area_increase_.increase_speed_), + first.last_area_increase_.increase_radius_ || second.last_area_increase_.increase_radius_, + first.last_area_increase_.no_error_ || second.last_area_increase_.no_error_, + first.last_area_increase_.use_min_distance_ && second.last_area_increase_.use_min_distance_, + first.last_area_increase_.move_ || second.last_area_increase_.move_); all_tips_ = first.all_tips_; all_tips_.insert(all_tips_.end(), second.all_tips_.begin(), second.all_tips_.end()); influence_area_limit_range_ = std::max(first.influence_area_limit_range_, second.influence_area_limit_range_); influence_area_limit_active_ = first.influence_area_limit_active_ || second.influence_area_limit_active_; RecreateInfluenceLimitArea(); - if(first.to_buildplate_ != second.to_buildplate_) + if (first.to_buildplate_ != second.to_buildplate_) { setToBuildplateForAllParents(to_buildplate_); } @@ -388,7 +366,7 @@ struct TreeSupportElement bool operator<(const TreeSupportElement& other) const // true if me < other { - return !(*this == other) && !(*this > other); + return ! (*this == other) && ! (*this > other); } bool operator>(const TreeSupportElement& other) const @@ -440,29 +418,30 @@ struct TreeSupportElement void setToBuildplateForAllParents(bool new_value) { to_buildplate_ = new_value; - std::vector grandparents {parents_}; - while (!grandparents.empty()){ + std::vector grandparents{ parents_ }; + while (! grandparents.empty()) + { std::vector next_parents; - for (TreeSupportElement* grandparent:grandparents){ - next_parents.insert(next_parents.end(),grandparent->parents_.begin(),grandparent->parents_.end()); + for (TreeSupportElement* grandparent : grandparents) + { + next_parents.insert(next_parents.end(), grandparent->parents_.begin(), grandparent->parents_.end()); grandparent->to_buildplate_ = new_value; } grandparents = next_parents; } } - + inline bool isResultOnLayerSet() const { return result_on_layer_ != Point(-1, -1); } - }; } // namespace cura namespace std { -template <> +template<> struct hash { size_t operator()(const cura::TreeSupportElement& node) const diff --git a/include/TreeSupportSettings.h b/include/TreeSupportSettings.h index 4f973cc430..a550bb530b 100644 --- a/include/TreeSupportSettings.h +++ b/include/TreeSupportSettings.h @@ -1,8 +1,10 @@ -//CuraEngine is released under the terms of the AGPLv3 or higher. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef TREESUPPORTSETTINGS_H #define TREESUPPORTSETTINGS_H +#include + #include "TreeSupportElement.h" #include "TreeSupportEnums.h" #include "settings/EnumSettings.h" @@ -10,7 +12,6 @@ #include "settings/types/Angle.h" #include "utils/Coord_t.h" #include "utils/Simplify.h" -#include namespace cura { @@ -22,60 +23,68 @@ struct TreeSupportSettings { TreeSupportSettings() = default; // required for the definition of the config variable in the TreeSupport class. - TreeSupportSettings(const Settings& mesh_group_settings) : - angle(mesh_group_settings.get("support_tree_angle")), - angle_slow(mesh_group_settings.get("support_tree_angle_slow")), - support_line_width(mesh_group_settings.get("support_line_width")), - layer_height(mesh_group_settings.get("layer_height")), - branch_radius(mesh_group_settings.get("support_tree_branch_diameter") / 2), - min_radius(mesh_group_settings.get("support_tree_tip_diameter") / 2), // The actual radius is 50 microns larger as the resulting branches will be increased by 50 microns to avoid rounding errors effectively increasing the xydistance - max_radius(mesh_group_settings.get("support_tree_max_diameter")/2), - maximum_move_distance((angle < TAU / 4) ? (coord_t)(tan(angle) * layer_height) : std::numeric_limits::max()), - maximum_move_distance_slow((angle_slow < TAU / 4) ? (coord_t)(tan(angle_slow) * layer_height) : std::numeric_limits::max()), - support_bottom_layers(mesh_group_settings.get("support_bottom_enable") ? round_divide(mesh_group_settings.get("support_bottom_height"), layer_height) : 0), - tip_layers(std::max((branch_radius - min_radius) / (support_line_width / 3), branch_radius / layer_height)), // Ensure lines always stack nicely even if layer height is large - diameter_angle_scale_factor(sin(mesh_group_settings.get("support_tree_branch_diameter_angle")) * layer_height / branch_radius), - max_to_model_radius_increase(mesh_group_settings.get("support_tree_max_diameter_increase_by_merges_when_support_to_model") / 2), - min_dtt_to_model(round_up_divide(mesh_group_settings.get("support_tree_min_height_to_model"), layer_height)), - increase_radius_until_radius(mesh_group_settings.get("support_tree_branch_diameter") / 2), - increase_radius_until_dtt(increase_radius_until_radius <= branch_radius ? tip_layers * (increase_radius_until_radius / branch_radius) : (increase_radius_until_radius - branch_radius) / (branch_radius * diameter_angle_scale_factor)), - support_rests_on_model(mesh_group_settings.get("support_type") == ESupportType::EVERYWHERE), - support_rest_preference((support_rests_on_model && mesh_group_settings.get("support_tree_rest_preference") == "graceful") ? RestPreference::GRACEFUL : RestPreference::BUILDPLATE), - xy_distance(mesh_group_settings.get("support_xy_distance")), - bp_radius(mesh_group_settings.get("support_tree_bp_diameter") / 2), - diameter_scale_bp_radius(std::min(sin(0.7) * layer_height / branch_radius, 1.0 / (branch_radius / (support_line_width / 2.0)))), // Either 40° or as much as possible so that 2 lines will overlap by at least 50%, whichever is smaller. - support_overrides(mesh_group_settings.get("support_xy_overrides_z")), - xy_min_distance(support_overrides == SupportDistPriority::Z_OVERRIDES_XY ? mesh_group_settings.get("support_xy_distance_overhang") : xy_distance), - z_distance_top_layers(round_up_divide(mesh_group_settings.get("support_top_distance"), layer_height)), - z_distance_bottom_layers(round_up_divide(mesh_group_settings.get("support_bottom_distance"), layer_height)), - performance_interface_skip_layers(round_up_divide(mesh_group_settings.get("support_interface_skip_height"), layer_height)), - support_infill_angles(mesh_group_settings.get>("support_infill_angles")), - support_roof_angles(mesh_group_settings.get>("support_roof_angles")), - roof_pattern(mesh_group_settings.get("support_roof_pattern")), - support_pattern(mesh_group_settings.get("support_pattern")), - support_roof_line_width(mesh_group_settings.get("support_roof_line_width")), - support_line_distance(mesh_group_settings.get("support_line_distance")), - support_bottom_offset(mesh_group_settings.get("support_bottom_offset")), - support_wall_count(mesh_group_settings.get("support_wall_count")), - support_roof_wall_count(mesh_group_settings.get("support_roof_wall_count")), - zig_zaggify_support(mesh_group_settings.get("zig_zaggify_support")), - maximum_deviation(mesh_group_settings.get("meshfix_maximum_deviation")), - maximum_resolution(mesh_group_settings.get("meshfix_maximum_resolution")), - support_roof_line_distance(mesh_group_settings.get("support_roof_line_distance")), // in the end the actual infill has to be calculated to subtract interface from support areas according to interface_preference. - skip_some_zags(mesh_group_settings.get("support_skip_some_zags")), - zag_skip_count(mesh_group_settings.get("support_zag_skip_count")), - connect_zigzags(mesh_group_settings.get("support_connect_zigzags")), - settings(mesh_group_settings), - min_feature_size(mesh_group_settings.get("min_feature_size")), - min_wall_line_width(settings.get("min_wall_line_width")), - fill_outline_gaps(settings.get("fill_outline_gaps")), - simplifier(Simplify(mesh_group_settings)) + TreeSupportSettings(const Settings& mesh_group_settings) + : angle(mesh_group_settings.get("support_tree_angle")) + , angle_slow(mesh_group_settings.get("support_tree_angle_slow")) + , support_line_width(mesh_group_settings.get("support_line_width")) + , layer_height(mesh_group_settings.get("layer_height")) + , branch_radius(mesh_group_settings.get("support_tree_branch_diameter") / 2) + , min_radius(mesh_group_settings.get("support_tree_tip_diameter") / 2) + , // The actual radius is 50 microns larger as the resulting branches will be increased by 50 microns to avoid rounding errors effectively increasing the xydistance + max_radius(mesh_group_settings.get("support_tree_max_diameter") / 2) + , maximum_move_distance((angle < TAU / 4) ? (coord_t)(tan(angle) * layer_height) : std::numeric_limits::max()) + , maximum_move_distance_slow((angle_slow < TAU / 4) ? (coord_t)(tan(angle_slow) * layer_height) : std::numeric_limits::max()) + , support_bottom_layers(mesh_group_settings.get("support_bottom_enable") ? round_divide(mesh_group_settings.get("support_bottom_height"), layer_height) : 0) + , tip_layers(std::max((branch_radius - min_radius) / (support_line_width / 3), branch_radius / layer_height)) + , // Ensure lines always stack nicely even if layer height is large + diameter_angle_scale_factor(sin(mesh_group_settings.get("support_tree_branch_diameter_angle")) * layer_height / branch_radius) + , max_to_model_radius_increase(mesh_group_settings.get("support_tree_max_diameter_increase_by_merges_when_support_to_model") / 2) + , min_dtt_to_model(round_up_divide(mesh_group_settings.get("support_tree_min_height_to_model"), layer_height)) + , increase_radius_until_radius(mesh_group_settings.get("support_tree_branch_diameter") / 2) + , increase_radius_until_dtt( + increase_radius_until_radius <= branch_radius ? tip_layers * (increase_radius_until_radius / branch_radius) + : (increase_radius_until_radius - branch_radius) / (branch_radius * diameter_angle_scale_factor)) + , support_rests_on_model(mesh_group_settings.get("support_type") == ESupportType::EVERYWHERE) + , support_rest_preference( + (support_rests_on_model && mesh_group_settings.get("support_tree_rest_preference") == "graceful") ? RestPreference::GRACEFUL + : RestPreference::BUILDPLATE) + , xy_distance(mesh_group_settings.get("support_xy_distance")) + , bp_radius(mesh_group_settings.get("support_tree_bp_diameter") / 2) + , diameter_scale_bp_radius(std::min(sin(0.7) * layer_height / branch_radius, 1.0 / (branch_radius / (support_line_width / 2.0)))) + , // Either 40° or as much as possible so that 2 lines will overlap by at least 50%, whichever is smaller. + support_overrides(mesh_group_settings.get("support_xy_overrides_z")) + , xy_min_distance(support_overrides == SupportDistPriority::Z_OVERRIDES_XY ? mesh_group_settings.get("support_xy_distance_overhang") : xy_distance) + , z_distance_top_layers(round_up_divide(mesh_group_settings.get("support_top_distance"), layer_height)) + , z_distance_bottom_layers(round_up_divide(mesh_group_settings.get("support_bottom_distance"), layer_height)) + , performance_interface_skip_layers(round_up_divide(mesh_group_settings.get("support_interface_skip_height"), layer_height)) + , support_infill_angles(mesh_group_settings.get>("support_infill_angles")) + , support_roof_angles(mesh_group_settings.get>("support_roof_angles")) + , roof_pattern(mesh_group_settings.get("support_roof_pattern")) + , support_pattern(mesh_group_settings.get("support_pattern")) + , support_roof_line_width(mesh_group_settings.get("support_roof_line_width")) + , support_line_distance(mesh_group_settings.get("support_line_distance")) + , support_bottom_offset(mesh_group_settings.get("support_bottom_offset")) + , support_wall_count(mesh_group_settings.get("support_wall_count")) + , support_roof_wall_count(mesh_group_settings.get("support_roof_wall_count")) + , zig_zaggify_support(mesh_group_settings.get("zig_zaggify_support")) + , maximum_deviation(mesh_group_settings.get("meshfix_maximum_deviation")) + , maximum_resolution(mesh_group_settings.get("meshfix_maximum_resolution")) + , support_roof_line_distance(mesh_group_settings.get("support_roof_line_distance")) + , // in the end the actual infill has to be calculated to subtract interface from support areas according to interface_preference. + skip_some_zags(mesh_group_settings.get("support_skip_some_zags")) + , zag_skip_count(mesh_group_settings.get("support_zag_skip_count")) + , connect_zigzags(mesh_group_settings.get("support_connect_zigzags")) + , settings(mesh_group_settings) + , min_feature_size(mesh_group_settings.get("min_feature_size")) + , min_wall_line_width(settings.get("min_wall_line_width")) + , fill_outline_gaps(settings.get("fill_outline_gaps")) + , simplifier(Simplify(mesh_group_settings)) { layer_start_bp_radius = (bp_radius - branch_radius) / (branch_radius * diameter_scale_bp_radius); - // safeOffsetInc can only work in steps of the size xy_min_distance in the worst case => xy_min_distance has to be a bit larger than 0 in this worst case and should be large enough for performance to not suffer extremely - // When for all meshes the z bottom and top distance is more than one layer though the worst case is xy_min_distance + min_feature_size - // This is not the best solution, but the only one to ensure areas can not lag though walls at high maximum_move_distance. + // safeOffsetInc can only work in steps of the size xy_min_distance in the worst case => xy_min_distance has to be a bit larger than 0 in this worst case and should be + // large enough for performance to not suffer extremely When for all meshes the z bottom and top distance is more than one layer though the worst case is xy_min_distance + + // min_feature_size This is not the best solution, but the only one to ensure areas can not lag though walls at high maximum_move_distance. if (has_to_rely_on_min_xy_dist_only) { xy_min_distance = std::max(coord_t(100), xy_min_distance); // If set to low rounding errors WILL cause errors. Best to keep it above 25. @@ -83,49 +92,47 @@ struct TreeSupportSettings xy_distance = std::max(xy_distance, xy_min_distance); - const std::function&, EFillMethod)> getInterfaceAngles = - [&](std::vector& angles, EFillMethod pattern) { // (logic) from getInterfaceAngles in FFFGcodeWriter. - if (angles.empty()) - { - if (pattern == EFillMethod::CONCENTRIC) - { - angles.push_back(0); // Concentric has no rotation. - } - else if (pattern == EFillMethod::TRIANGLES) - { - angles.push_back(90); // Triangular support interface shouldn't alternate every layer. - } - else - { - if (TreeSupportSettings::some_model_contains_thick_roof) - { - // Some roofs are quite thick. - // Alternate between the two kinds of diagonal: / and \ . - angles.push_back(45); - angles.push_back(135); - } - if (angles.empty()) - { - angles.push_back(90); // Perpendicular to support lines. - } - } - } - }; - - if(support_infill_angles.empty()) + const std::function&, EFillMethod)> getInterfaceAngles + = [&](std::vector& angles, EFillMethod pattern) { // (logic) from getInterfaceAngles in FFFGcodeWriter. + if (angles.empty()) + { + if (pattern == EFillMethod::CONCENTRIC) + { + angles.push_back(0); // Concentric has no rotation. + } + else if (pattern == EFillMethod::TRIANGLES) + { + angles.push_back(90); // Triangular support interface shouldn't alternate every layer. + } + else + { + if (TreeSupportSettings::some_model_contains_thick_roof) + { + // Some roofs are quite thick. + // Alternate between the two kinds of diagonal: / and \ . + angles.push_back(45); + angles.push_back(135); + } + if (angles.empty()) + { + angles.push_back(90); // Perpendicular to support lines. + } + } + } + }; + + if (support_infill_angles.empty()) { support_infill_angles.push_back(0); } getInterfaceAngles(support_roof_angles, roof_pattern); - const std::unordered_map interface_map = - { - { "support_area_overwrite_interface_area", InterfacePreference::SUPPORT_AREA_OVERWRITES_INTERFACE }, + const std::unordered_map interface_map + = { { "support_area_overwrite_interface_area", InterfacePreference::SUPPORT_AREA_OVERWRITES_INTERFACE }, { "interface_area_overwrite_support_area", InterfacePreference::INTERFACE_AREA_OVERWRITES_SUPPORT }, { "support_lines_overwrite_interface_area", InterfacePreference::SUPPORT_LINES_OVERWRITE_INTERFACE }, { "interface_lines_overwrite_support_area", InterfacePreference::INTERFACE_LINES_OVERWRITE_SUPPORT }, - { "nothing", InterfacePreference::NOTHING } - }; + { "nothing", InterfacePreference::NOTHING } }; interface_preference = interface_map.at(mesh_group_settings.get("support_interface_priority")); } @@ -236,7 +243,8 @@ struct TreeSupportSettings coord_t layer_start_bp_radius; /*! - * \brief Factor by which to increase the branch radius to reach the required bp_radius at layer 0. Note that this radius increase will not happen in the tip, to ensure the tip is structurally sound. + * \brief Factor by which to increase the branch radius to reach the required bp_radius at layer 0. Note that this radius increase will not happen in the tip, to ensure the tip + * is structurally sound. */ double diameter_scale_bp_radius; @@ -321,7 +329,8 @@ struct TreeSupportSettings coord_t maximum_deviation; /*! - * \brief Maximum allowed resolution (length of a line segment) when simplifying. The resolution is higher when this variable is smaller => Minimum size a line segment may have. + * \brief Maximum allowed resolution (length of a line segment) when simplifying. The resolution is higher when this variable is smaller => Minimum size a line segment may + * have. */ coord_t maximum_resolution; @@ -375,83 +384,55 @@ struct TreeSupportSettings */ Simplify simplifier = Simplify(0, 0, 0); - public: +public: bool operator==(const TreeSupportSettings& other) const { - return - branch_radius == other.branch_radius && - tip_layers == other.tip_layers && - diameter_angle_scale_factor == other.diameter_angle_scale_factor && - layer_start_bp_radius == other.layer_start_bp_radius && - bp_radius == other.bp_radius && - diameter_scale_bp_radius == other.diameter_scale_bp_radius && - min_radius == other.min_radius && - xy_min_distance == other.xy_min_distance && // as a recalculation of the collision areas is required to set a new min_radius. - xy_distance - xy_min_distance == other.xy_distance - other.xy_min_distance && // if the delta of xy_min_distance and xy_distance is different the collision areas have to be recalculated. - support_rests_on_model == other.support_rests_on_model && - increase_radius_until_dtt == other.increase_radius_until_dtt && - min_dtt_to_model == other.min_dtt_to_model && - max_to_model_radius_increase == other.max_to_model_radius_increase && - maximum_move_distance == other.maximum_move_distance && - maximum_move_distance_slow == other.maximum_move_distance_slow && - z_distance_bottom_layers == other.z_distance_bottom_layers && - support_line_width == other.support_line_width && - support_overrides == other.support_overrides && - support_line_distance == other.support_line_distance && - support_roof_line_width == other.support_roof_line_width && // can not be set on a per-mesh basis currently, so code to enable processing different roof line width in the same iteration seems useless. - support_bottom_offset == other.support_bottom_offset && - support_wall_count == other.support_wall_count && - support_pattern == other.support_pattern && - roof_pattern == other.roof_pattern && // can not be set on a per-mesh basis currently, so code to enable processing different roof patterns in the same iteration seems useless. - support_roof_angles == other.support_roof_angles && - support_infill_angles == other.support_infill_angles && - increase_radius_until_radius == other.increase_radius_until_radius && - support_bottom_layers == other.support_bottom_layers && - layer_height == other.layer_height && - z_distance_top_layers == other.z_distance_top_layers && - maximum_deviation == other.maximum_deviation && // Infill generation depends on deviation and resolution. - maximum_resolution == other.maximum_resolution && - support_roof_line_distance == other.support_roof_line_distance && - skip_some_zags == other.skip_some_zags && - zag_skip_count == other.zag_skip_count && - connect_zigzags == other.connect_zigzags && - interface_preference == other.interface_preference && - min_feature_size == other.min_feature_size && // interface_preference should be identical to ensure the tree will correctly interact with the roof. - support_rest_preference == other.support_rest_preference && - max_radius == other.max_radius && - min_wall_line_width == other.min_wall_line_width && - fill_outline_gaps == other.fill_outline_gaps && - // The infill class now wants the settings object and reads a lot of settings, and as the infill class is used to calculate support roof lines for interface-preference. Not all of these may be required to be identical, but as I am not sure, better safe than sorry - ( - interface_preference == InterfacePreference::INTERFACE_AREA_OVERWRITES_SUPPORT || - interface_preference == InterfacePreference::SUPPORT_AREA_OVERWRITES_INTERFACE || - ( - settings.get("fill_outline_gaps") == other.settings.get("fill_outline_gaps") && - settings.get("min_bead_width") == other.settings.get("min_bead_width") && - settings.get("wall_transition_angle") == other.settings.get("wall_transition_angle") && - settings.get("wall_transition_length") == other.settings.get("wall_transition_length") && - settings.get("min_odd_wall_line_width") == other.settings.get("min_odd_wall_line_width") && - settings.get("min_even_wall_line_width") == other.settings.get("min_even_wall_line_width") && - settings.get("wall_distribution_count") == other.settings.get("wall_distribution_count") && - settings.get("wall_transition_filter_distance") == other.settings.get("wall_transition_filter_distance") && - settings.get("wall_transition_filter_deviation") == other.settings.get("wall_transition_filter_deviation") && - settings.get("wall_line_width_x") == other.settings.get("wall_line_width_x") && - settings.get("meshfix_maximum_extrusion_area_deviation") == other.settings.get("meshfix_maximum_extrusion_area_deviation") - ) - ); + return branch_radius == other.branch_radius && tip_layers == other.tip_layers && diameter_angle_scale_factor == other.diameter_angle_scale_factor + && layer_start_bp_radius == other.layer_start_bp_radius && bp_radius == other.bp_radius && diameter_scale_bp_radius == other.diameter_scale_bp_radius + && min_radius == other.min_radius && xy_min_distance == other.xy_min_distance && // as a recalculation of the collision areas is required to set a new min_radius. + xy_distance - xy_min_distance == other.xy_distance - other.xy_min_distance + && // if the delta of xy_min_distance and xy_distance is different the collision areas have to be recalculated. + support_rests_on_model == other.support_rests_on_model && increase_radius_until_dtt == other.increase_radius_until_dtt && min_dtt_to_model == other.min_dtt_to_model + && max_to_model_radius_increase == other.max_to_model_radius_increase && maximum_move_distance == other.maximum_move_distance + && maximum_move_distance_slow == other.maximum_move_distance_slow && z_distance_bottom_layers == other.z_distance_bottom_layers + && support_line_width == other.support_line_width && support_overrides == other.support_overrides && support_line_distance == other.support_line_distance + && support_roof_line_width == other.support_roof_line_width + && // can not be set on a per-mesh basis currently, so code to enable processing different roof line width in the same iteration seems useless. + support_bottom_offset == other.support_bottom_offset && support_wall_count == other.support_wall_count && support_pattern == other.support_pattern + && roof_pattern == other.roof_pattern + && // can not be set on a per-mesh basis currently, so code to enable processing different roof patterns in the same iteration seems useless. + support_roof_angles == other.support_roof_angles && support_infill_angles == other.support_infill_angles + && increase_radius_until_radius == other.increase_radius_until_radius && support_bottom_layers == other.support_bottom_layers && layer_height == other.layer_height + && z_distance_top_layers == other.z_distance_top_layers && maximum_deviation == other.maximum_deviation && // Infill generation depends on deviation and resolution. + maximum_resolution == other.maximum_resolution && support_roof_line_distance == other.support_roof_line_distance && skip_some_zags == other.skip_some_zags + && zag_skip_count == other.zag_skip_count && connect_zigzags == other.connect_zigzags && interface_preference == other.interface_preference + && min_feature_size == other.min_feature_size && // interface_preference should be identical to ensure the tree will correctly interact with the roof. + support_rest_preference == other.support_rest_preference && max_radius == other.max_radius && min_wall_line_width == other.min_wall_line_width + && fill_outline_gaps == other.fill_outline_gaps && + // The infill class now wants the settings object and reads a lot of settings, and as the infill class is used to calculate support roof lines for + // interface-preference. Not all of these may be required to be identical, but as I am not sure, better safe than sorry + (interface_preference == InterfacePreference::INTERFACE_AREA_OVERWRITES_SUPPORT || interface_preference == InterfacePreference::SUPPORT_AREA_OVERWRITES_INTERFACE + || (settings.get("fill_outline_gaps") == other.settings.get("fill_outline_gaps") + && settings.get("min_bead_width") == other.settings.get("min_bead_width") + && settings.get("wall_transition_angle") == other.settings.get("wall_transition_angle") + && settings.get("wall_transition_length") == other.settings.get("wall_transition_length") + && settings.get("min_odd_wall_line_width") == other.settings.get("min_odd_wall_line_width") + && settings.get("min_even_wall_line_width") == other.settings.get("min_even_wall_line_width") + && settings.get("wall_distribution_count") == other.settings.get("wall_distribution_count") + && settings.get("wall_transition_filter_distance") == other.settings.get("wall_transition_filter_distance") + && settings.get("wall_transition_filter_deviation") == other.settings.get("wall_transition_filter_deviation") + && settings.get("wall_line_width_x") == other.settings.get("wall_line_width_x") + && settings.get("meshfix_maximum_extrusion_area_deviation") == other.settings.get("meshfix_maximum_extrusion_area_deviation"))); } /*! - * \brief Get the Distance to top regarding the real radius this part will have. This is different from distance_to_top, which is can be used to calculate the top most layer of the branch. - * \param elem[in] The SupportElement one wants to know the effectiveDTT - * \return The Effective DTT. + * \brief Get the Distance to top regarding the real radius this part will have. This is different from distance_to_top, which is can be used to calculate the top most layer of + * the branch. \param elem[in] The SupportElement one wants to know the effectiveDTT \return The Effective DTT. */ [[nodiscard]] inline size_t getEffectiveDTT(const TreeSupportElement& elem) const { - return - elem.effective_radius_height_ < increase_radius_until_dtt ? - (elem.distance_to_top_ < increase_radius_until_dtt ? elem.distance_to_top_ : increase_radius_until_dtt) : - elem.effective_radius_height_; + return elem.effective_radius_height_ < increase_radius_until_dtt ? (elem.distance_to_top_ < increase_radius_until_dtt ? elem.distance_to_top_ : increase_radius_until_dtt) + : elem.effective_radius_height_; } /*! @@ -462,15 +443,13 @@ struct TreeSupportSettings */ [[nodiscard]] inline coord_t getRadius(size_t distance_to_top, const double buildplate_radius_increases = 0) const { - coord_t uncapped_radius = - ( - distance_to_top <= tip_layers ? - /* tip */ min_radius + (branch_radius - min_radius) * distance_to_top / tip_layers : - /* base */ branch_radius + - /* gradual increase */ branch_radius * (distance_to_top - tip_layers) * diameter_angle_scale_factor) + - branch_radius * buildplate_radius_increases * (std::max(diameter_scale_bp_radius - diameter_angle_scale_factor, 0.0) - ); - return std::min(uncapped_radius,max_radius); + coord_t uncapped_radius = (distance_to_top <= tip_layers ? + /* tip */ min_radius + (branch_radius - min_radius) * distance_to_top / tip_layers + : + /* base */ branch_radius + + /* gradual increase */ branch_radius * (distance_to_top - tip_layers) * diameter_angle_scale_factor) + + branch_radius * buildplate_radius_increases * (std::max(diameter_scale_bp_radius - diameter_angle_scale_factor, 0.0)); + return std::min(uncapped_radius, max_radius); } /*! @@ -480,7 +459,7 @@ struct TreeSupportSettings */ [[nodiscard]] inline coord_t getRadius(const TreeSupportElement& elem) const { - return getRadius(getEffectiveDTT(elem), (elem.isResultOnLayerSet() || !support_rests_on_model) && elem.to_buildplate_ ? elem.buildplate_radius_increases_ : 0); + return getRadius(getEffectiveDTT(elem), (elem.isResultOnLayerSet() || ! support_rests_on_model) && elem.to_buildplate_ ? elem.buildplate_radius_increases_ : 0); } /*! @@ -501,7 +480,7 @@ struct TreeSupportSettings [[nodiscard]] inline coord_t recommendedMinRadius(LayerIndex layer_idx) const { const double scale = (layer_start_bp_radius - layer_idx) * diameter_scale_bp_radius; - return scale > 0 ? std::min(coord_t(branch_radius + branch_radius * scale),max_radius) : 0; + return scale > 0 ? std::min(coord_t(branch_radius + branch_radius * scale), max_radius) : 0; } /*! diff --git a/include/TreeSupportUtils.h b/include/TreeSupportUtils.h index 7782fef79e..750665ef01 100644 --- a/include/TreeSupportUtils.h +++ b/include/TreeSupportUtils.h @@ -4,6 +4,8 @@ #ifndef TREESUPPORTTUTILS_H #define TREESUPPORTTUTILS_H +#include + #include "TreeModelVolumes.h" #include "TreeSupportBaseCircle.h" #include "TreeSupportElement.h" @@ -17,8 +19,6 @@ #include "utils/Coord_t.h" #include "utils/polygon.h" -#include - namespace cura { diff --git a/include/WallToolPaths.h b/include/WallToolPaths.h index 22e1f13a3d..70ded7d889 100644 --- a/include/WallToolPaths.h +++ b/include/WallToolPaths.h @@ -25,7 +25,14 @@ class WallToolPaths * \param wall_0_inset How far to inset the outer wall, to make it adhere better to other walls. * \param settings The settings as provided by the user */ - WallToolPaths(const Polygons& outline, const coord_t nominal_bead_width, const size_t inset_count, const coord_t wall_0_inset, const Settings& settings, const int layer_idx, SectionType section_type); + WallToolPaths( + const Polygons& outline, + const coord_t nominal_bead_width, + const size_t inset_count, + const coord_t wall_0_inset, + const Settings& settings, + const int layer_idx, + SectionType section_type); /*! * A class that creates the toolpaths given an outline, nominal bead width and maximum amount of walls @@ -36,7 +43,15 @@ class WallToolPaths * \param wall_0_inset How far to inset the outer wall, to make it adhere better to other walls. * \param settings The settings as provided by the user */ - WallToolPaths(const Polygons& outline, const coord_t bead_width_0, const coord_t bead_width_x, const size_t inset_count, const coord_t wall_0_inset, const Settings& settings, const int layer_idx, SectionType section_type); + WallToolPaths( + const Polygons& outline, + const coord_t bead_width_0, + const coord_t bead_width_x, + const size_t inset_count, + const coord_t wall_0_inset, + const Settings& settings, + const int layer_idx, + SectionType section_type); /*! * Generates the Toolpaths @@ -87,9 +102,9 @@ class WallToolPaths protected: /*! * Stitch the polylines together and form closed polygons. - * + * * Works on both toolpaths and inner contours simultaneously. - * + * * \param settings The settings as provided by the user */ static void stitchToolPaths(std::vector& toolpaths, const Settings& settings); @@ -109,17 +124,18 @@ class WallToolPaths private: const Polygons& outline_; // toolpaths_; // #include #include #include +#include "../utils/polygon.h" +#include "../utils/polygonUtils.h" + namespace cura { diff --git a/include/pathPlanning/Comb.h b/include/pathPlanning/Comb.h index 93bff84b30..49757fbf1a 100644 --- a/include/pathPlanning/Comb.h +++ b/include/pathPlanning/Comb.h @@ -1,17 +1,17 @@ -//Copyright (c) 2021 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2021 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef PATH_PLANNING_COMB_H #define PATH_PLANNING_COMB_H -#include // shared_ptr #include // To find the maximum for coord_t. +#include // shared_ptr #include "../settings/types/LayerIndex.h" // To store the layer on which we comb. #include "../utils/polygon.h" #include "../utils/polygonUtils.h" -namespace cura +namespace cura { class CombPath; @@ -43,10 +43,11 @@ class SliceDataStorage; class Comb { friend class LinePolygonsCrossings; + private: /*! * A crossing from the inside boundary to the outside boundary. - * + * * 'dest' is either the startPoint or the endpoint of a whole combing move. */ class Crossing @@ -62,26 +63,32 @@ class Comb /*! * Simple constructor - * + * * \param dest_point Either the eventual startPoint or the eventual endPoint of this combing move. * \param dest_is_inside Whether the startPoint or endPoint is inside the inside boundary. * \param dest_part_idx The index into Comb:partsView_inside of the part in which the \p dest_point is. - * \param dest_part_boundary_crossing_poly_idx The index in \p boundary_inside of the polygon of the part in which dest_point lies, which will be crossed (often will be the outside polygon). - * \param boundary_inside The boundary within which to comb. + * \param dest_part_boundary_crossing_poly_idx The index in \p boundary_inside of the polygon of the part in which dest_point lies, which will be crossed (often will be the + * outside polygon). \param boundary_inside The boundary within which to comb. */ - Crossing(const Point& dest_point, const bool dest_is_inside, const unsigned int dest_part_idx, const unsigned int dest_part_boundary_crossing_poly_idx, const Polygons& boundary_inside, const LocToLineGrid& inside_loc_to_line); + Crossing( + const Point& dest_point, + const bool dest_is_inside, + const unsigned int dest_part_idx, + const unsigned int dest_part_boundary_crossing_poly_idx, + const Polygons& boundary_inside, + const LocToLineGrid& inside_loc_to_line); /*! * Find the not-outside location (Combing::in_or_mid) of the crossing between to the outside boundary - * - * \param partsView_inside Structured indices onto Comb::boundary_inside which shows which polygons belong to which part. + * + * \param partsView_inside Structured indices onto Comb::boundary_inside which shows which polygons belong to which part. * \param close_to[in] Try to get a crossing close to this point */ void findCrossingInOrMid(const PartsView& partsView_inside, const Point close_to); /*! * Find the outside location (Combing::out) - * + * * \param outside The outside boundary polygons. * \param close_to A point to get closer to when there are multiple * candidates on the outside boundary which are almost equally close to @@ -99,9 +106,9 @@ class Comb /*! * Find the best crossing from some inside polygon to the outside boundary. - * + * * The detour from \p estimated_start to \p estimated_end is minimized. - * + * * \param outside The outside boundary polygons * \param from From which inside boundary the crossing to the outside starts or ends * \param estimated_start The one point to which to stay close when evaluating crossings which cross about the same distance @@ -109,7 +116,8 @@ class Comb * \param comber[in] The combing calculator which has references to the offsets and boundaries to use in combing. * \return A pair of which the first is the crossing point on the inside boundary and the second the crossing point on the outside boundary */ - std::shared_ptr> findBestCrossing(const ExtruderTrain& train, const Polygons& outside, ConstPolygonRef from, const Point estimated_start, const Point estimated_end, Comb& comber); + std::shared_ptr> + findBestCrossing(const ExtruderTrain& train, const Polygons& outside, ConstPolygonRef from, const Point estimated_start, const Point estimated_end, Comb& comber); }; @@ -118,7 +126,8 @@ class Comb const coord_t travel_avoid_distance_; //!< const coord_t offset_from_outlines_; //!< Offset from the boundary of a part to the comb path. (nozzle width / 2) - const coord_t max_moveInside_distance2_; //!< Maximal distance of a point to the Comb::boundary_inside which is still to be considered inside. (very sharp corners not allowed :S) + const coord_t + max_moveInside_distance2_; //!< Maximal distance of a point to the Comb::boundary_inside which is still to be considered inside. (very sharp corners not allowed :S) const coord_t offset_from_inside_to_outside_; //!< The sum of the offsets for the inside and outside boundary Comb::offset_from_outlines and Comb::offset_from_outlines_outside const coord_t max_crossing_dist2_; //!< The maximal distance by which to cross the in_between area between inside and outside static const coord_t max_moveOutside_distance2_ = std::numeric_limits::max(); //!< Any point which is not inside should be considered outside. @@ -131,20 +140,23 @@ class Comb const PartsView parts_view_inside_optimal_; //!< Structured indices onto boundary_inside_optimal which shows which polygons belong to which part. std::unique_ptr inside_loc_to_line_minimum_; //!< The SparsePointGridInclusive mapping locations to line segments of the inner boundary. std::unique_ptr inside_loc_to_line_optimal_; //!< The SparsePointGridInclusive mapping locations to line segments of the inner boundary. - std::unordered_map boundary_outside_; //!< The boundary outside of which to stay to avoid collision with other layer parts. This is a pointer cause we only compute it when we move outside the boundary (so not when there is only a single part in the layer) + std::unordered_map boundary_outside_; //!< The boundary outside of which to stay to avoid collision with other layer parts. This is a pointer cause we only + //!< compute it when we move outside the boundary (so not when there is only a single part in the layer) std::unordered_map model_boundary_; //!< The boundary of the model itself std::unordered_map> outside_loc_to_line_; //!< The SparsePointGridInclusive mapping locations to line segments of the outside boundary. - std::unordered_map> model_boundary_loc_to_line_; //!< The SparsePointGridInclusive mapping locations to line segments of the model boundary - coord_t move_inside_distance_; //!< When using comb_boundary_inside_minimum for combing it tries to move points inside by this amount after calculating the path to move it from the border a bit. + std::unordered_map> + model_boundary_loc_to_line_; //!< The SparsePointGridInclusive mapping locations to line segments of the model boundary + coord_t move_inside_distance_; //!< When using comb_boundary_inside_minimum for combing it tries to move points inside by this amount after calculating the path to move it from + //!< the border a bit. /*! * Get the SparsePointGridInclusive mapping locations to line segments of the outside boundary. Calculate it when it hasn't been calculated yet. */ LocToLineGrid& getOutsideLocToLine(const ExtruderTrain& train); - /*! - * Get the boundary_outside, which is an offset from the outlines of all meshes in the layer. Calculate it when it hasn't been calculated yet. - */ + /*! + * Get the boundary_outside, which is an offset from the outlines of all meshes in the layer. Calculate it when it hasn't been calculated yet. + */ Polygons& getBoundaryOutside(const ExtruderTrain& train); /*! @@ -172,10 +184,10 @@ class Comb public: /*! * Initialises the combing areas for every mesh in the layer (not support). - * + * * \warning \ref Comb::calc changes the order of polygons in * \p Comb::comb_boundary_inside - * + * * \param storage Where the layer polygon data is stored. * \param layer_nr The number of the layer for which to generate the combing * areas. @@ -191,30 +203,30 @@ class Comb * combing it tries to move points inside by this amount after calculating * the path to move it from the border a bit. */ - Comb(const SliceDataStorage& storage, const LayerIndex layer_nr, const Polygons& comb_boundary_inside_minimum, const Polygons& comb_boundary_inside_optimal, coord_t offset_from_outlines, coord_t travel_avoid_distance, coord_t move_inside_distance); + Comb( + const SliceDataStorage& storage, + const LayerIndex layer_nr, + const Polygons& comb_boundary_inside_minimum, + const Polygons& comb_boundary_inside_optimal, + coord_t offset_from_outlines, + coord_t travel_avoid_distance, + coord_t move_inside_distance); /*! * \brief Calculate the comb paths (if any), one for each polygon combed * alternated with travel paths. - * + * * \warning Changes the order of polygons in \ref Comb::comb_boundary_inside * \param perform_z_hops Whether to Z hop when retracted. * \param perform_z_hops_only_when_collides Whether to Z hop only over printed parts. - * \param train Extruder train, for settings and extruder-nr. NOTE: USe for travel settings and 'extruder-nr' only, don't use for z-hop/retraction/wipe settings, as that should also be settable per mesh! - * \param startPoint Where to start moving from. - * \param endPoint Where to move to. - * \param[out] combPoints The points along the combing path, excluding the - * \p startPoint (?) and \p endPoint. - * \param startInside Whether we want to start inside the comb boundary. - * \param endInside Whether we want to end up inside the comb boundary. - * \param unretract_before_last_travel_move Whether we should unretract before the last travel move when travelling - * because of combing. If the endpoint of a travel path changes with combing, then it means that an outer wall is - * involved, which means that we should then unretract before the last travel move to that wall to avoid any blips - * being introduced due to the unretraction. - * \return Whether combing has succeeded; otherwise a retraction is needed. + * \param train Extruder train, for settings and extruder-nr. NOTE: USe for travel settings and 'extruder-nr' only, don't use for z-hop/retraction/wipe settings, as that should + * also be settable per mesh! \param startPoint Where to start moving from. \param endPoint Where to move to. \param[out] combPoints The points along the combing path, + * excluding the \p startPoint (?) and \p endPoint. \param startInside Whether we want to start inside the comb boundary. \param endInside Whether we want to end up inside the + * comb boundary. \param unretract_before_last_travel_move Whether we should unretract before the last travel move when travelling because of combing. If the endpoint of a + * travel path changes with combing, then it means that an outer wall is involved, which means that we should then unretract before the last travel move to that wall to avoid + * any blips being introduced due to the unretraction. \return Whether combing has succeeded; otherwise a retraction is needed. */ - bool calc - ( + bool calc( bool perform_z_hops, bool perform_z_hops_only_when_collides, const ExtruderTrain& train, @@ -224,10 +236,9 @@ class Comb bool startInside, bool endInside, coord_t max_comb_distance_ignored, - bool &unretract_before_last_travel_move - ); + bool& unretract_before_last_travel_move); }; -}//namespace cura +} // namespace cura -#endif//PATH_PLANNING_COMB_H +#endif // PATH_PLANNING_COMB_H diff --git a/include/pathPlanning/LinePolygonsCrossings.h b/include/pathPlanning/LinePolygonsCrossings.h index 70802800f2..5fcea84545 100644 --- a/include/pathPlanning/LinePolygonsCrossings.h +++ b/include/pathPlanning/LinePolygonsCrossings.h @@ -1,33 +1,32 @@ -//Copyright (c) 2018 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2018 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef PATH_PLANNING_LINE_POLYGONS_CROSSINGS_H #define PATH_PLANNING_LINE_POLYGONS_CROSSINGS_H -#include "CombPath.h" #include "../utils/polygon.h" #include "../utils/polygonUtils.h" +#include "CombPath.h" -namespace cura +namespace cura { /*! * Class for generating a combing move action from point a to point b and avoiding collision with other parts when moving through air. * See LinePolygonsCrossings::comb. - * + * * The general implementation is by rotating everything such that the the line segment from a to b is aligned with the x-axis. * We call the line on which a and b lie the 'scanline'. - * - * The basic path is generated by following the scanline until it hits a polygon, then follow the polygon until the last point where it hits the scanline, + * + * The basic path is generated by following the scanline until it hits a polygon, then follow the polygon until the last point where it hits the scanline, * follow the scanline again, etc. * The path is offsetted from the polygons, so that it doesn't intersect with them. - * + * * Next the basic path is optimized by taking shortcuts where possible. Only shortcuts which skip a single point are considered, in order to reduce computational complexity. */ class LinePolygonsCrossings { private: - /*! * A Crossing holds data on a single point where a polygon crosses the scanline. */ @@ -36,7 +35,7 @@ class LinePolygonsCrossings size_t poly_idx_; //!< The index of the polygon which crosses the scanline coord_t x_; //!< x coordinate of crossings between the polygon and the scanline. size_t point_idx_; //!< The index of the first point of the line segment which crosses the scanline - + /*! * Creates a Crossing with minimal initialization * \param poly_idx The index of the polygon in LinePolygonsCrossings::boundary @@ -45,76 +44,79 @@ class LinePolygonsCrossings */ Crossing(const size_t poly_idx, const coord_t x, const size_t point_idx); }; - + std::vector crossings_; //!< All crossings of polygons in the LinePolygonsCrossings::boundary with the scanline. - + const Polygons& boundary_; //!< The boundary not to cross during combing. LocToLineGrid& loc_to_line_grid_; //!< Mapping from locations to line segments of \ref LinePolygonsCrossings::boundary Point start_point_; //!< The start point of the scanline. Point end_point_; //!< The end point of the scanline. - - int64_t dist_to_move_boundary_point_outside_; //!< The distance used to move outside or inside so that a boundary point doesn't intersect with the boundary anymore. Neccesary due to computational rounding problems. Use negative value for insicde combing. - + + int64_t dist_to_move_boundary_point_outside_; //!< The distance used to move outside or inside so that a boundary point doesn't intersect with the boundary anymore. Neccesary + //!< due to computational rounding problems. Use negative value for insicde combing. + PointMatrix transformation_matrix_; //!< The transformation which rotates everything such that the scanline is aligned with the x-axis. - Point transformed_start_point_; //!< The LinePolygonsCrossings::startPoint as transformed by Comb::transformation_matrix such that it has (roughly) the same Y as transformed_endPoint - Point transformed_end_point_; //!< The LinePolygonsCrossings::endPoint as transformed by Comb::transformation_matrix such that it has (roughly) the same Y as transformed_startPoint + Point transformed_start_point_; //!< The LinePolygonsCrossings::startPoint as transformed by Comb::transformation_matrix such that it has (roughly) the same Y as + //!< transformed_endPoint + Point transformed_end_point_; //!< The LinePolygonsCrossings::endPoint as transformed by Comb::transformation_matrix such that it has (roughly) the same Y as + //!< transformed_startPoint + - /*! * Check if we are crossing the boundaries, and pre-calculate some values. - * + * * Sets Comb::transformation_matrix, Comb::transformed_startPoint and Comb::transformed_endPoint * \return Whether the line segment from LinePolygonsCrossings::startPoint to LinePolygonsCrossings::endPoint collides with the boundary */ bool lineSegmentCollidesWithBoundary(); - + /*! * Calculate Comb::crossings. * \param fail_on_unavoidable_obstacles When moving over other parts is inavoidable, stop calculation early and return false. * \return Whether combing succeeded, i.e. when fail_on_unavoidable_obstacles: we didn't cross any gaps/other parts */ bool calcScanlineCrossings(bool fail_on_unavoidable_obstacles); - - /*! + + /*! * Generate the basic combing path and optimize it. - * + * * \param combPath Output parameter: the points along the combing path. * \param fail_on_unavoidable_obstacles When moving over other parts is inavoidable, stop calculation early and return false. * \return Whether combing succeeded, i.e. we didn't cross any gaps/other parts */ bool generateCombingPath(CombPath& combPath, int64_t max_comb_distance_ignored, bool fail_on_unavoidable_obstacles); - - /*! + + /*! * Generate the basic combing path, without shortcuts. The path goes straight toward the endPoint and follows the boundary when it hits it, until it passes the scanline again. - * + * * Walk trough the crossings, for every boundary we cross, find the initial cross point and the exit point. Then add all the points in between * to the \p combPath and continue with the next boundary we will cross, until there are no more boundaries to cross. * This gives a path from the start to finish curved around the holes that it encounters. - * + * * \param combPath Output parameter: the points along the combing path. */ void generateBasicCombingPath(CombPath& combPath); - - /*! + + /*! * Generate the basic combing path, following a single boundary polygon when it hits it, until it passes the scanline again. - * + * * Find the initial cross point and the exit point. Then add all the points in between * to the \p combPath and continue with the next boundary we will cross, until there are no more boundaries to cross. * This gives a path from the start to finish curved around the polygon that it encounters. - * + * * \param combPath Output parameter: where to add the points along the combing path. */ void generateBasicCombingPath(const Crossing& min, const Crossing& max, CombPath& combPath); /*! * Optimize the \p comb_path: skip each point we could already reach by not crossing a boundary. This smooths out the path and makes it skip some unneeded corners. - * + * * \param comb_path The unoptimized combing path. * \param optimized_comb_path Output parameter: The points of optimized combing path * \return Whether it turns out that the basic comb path already crossed a boundary */ bool optimizePath(CombPath& comb_path, CombPath& optimized_comb_path); - + /*! * Create a LinePolygonsCrossings with minimal initialization. * \param boundary The boundary which not to cross during combing @@ -123,16 +125,15 @@ class LinePolygonsCrossings * \param dist_to_move_boundary_point_outside Distance used to move a point from a boundary so that it doesn't intersect with it anymore. (Precision issue) */ LinePolygonsCrossings(const Polygons& boundary, LocToLineGrid& loc_to_line_grid, Point& start, Point& end, int64_t dist_to_move_boundary_point_outside) - : boundary_(boundary) - , loc_to_line_grid_(loc_to_line_grid) - , start_point_(start) - , end_point_(end) - , dist_to_move_boundary_point_outside_(dist_to_move_boundary_point_outside) + : boundary_(boundary) + , loc_to_line_grid_(loc_to_line_grid) + , start_point_(start) + , end_point_(end) + , dist_to_move_boundary_point_outside_(dist_to_move_boundary_point_outside) { } - -public: - + +public: /*! * The main function of this class: calculate one combing path within the boundary. * \param boundary The polygons to follow when calculating the basic combing path @@ -143,13 +144,21 @@ class LinePolygonsCrossings * \param fail_on_unavoidable_obstacles When moving over other parts is inavoidable, stop calculation early and return false. * \return Whether combing succeeded, i.e. we didn't cross any gaps/other parts */ - static bool comb(const Polygons& boundary, LocToLineGrid& loc_to_line_grid, Point startPoint, Point endPoint, CombPath& combPath, int64_t dist_to_move_boundary_point_outside, int64_t max_comb_distance_ignored, bool fail_on_unavoidable_obstacles) + static bool comb( + const Polygons& boundary, + LocToLineGrid& loc_to_line_grid, + Point startPoint, + Point endPoint, + CombPath& combPath, + int64_t dist_to_move_boundary_point_outside, + int64_t max_comb_distance_ignored, + bool fail_on_unavoidable_obstacles) { LinePolygonsCrossings linePolygonsCrossings(boundary, loc_to_line_grid, startPoint, endPoint, dist_to_move_boundary_point_outside); return linePolygonsCrossings.generateCombingPath(combPath, max_comb_distance_ignored, fail_on_unavoidable_obstacles); }; }; -}//namespace cura +} // namespace cura -#endif//PATH_PLANNING_LINE_POLYGONS_CROSSINGS_H +#endif // PATH_PLANNING_LINE_POLYGONS_CROSSINGS_H diff --git a/include/plugins/pluginproxy.h b/include/plugins/pluginproxy.h index 3059287b4a..44be2830b9 100644 --- a/include/plugins/pluginproxy.h +++ b/include/plugins/pluginproxy.h @@ -4,18 +4,7 @@ #ifndef PLUGINS_PLUGINPROXY_H #define PLUGINS_PLUGINPROXY_H -#include "Application.h" -#include "cura/plugins/slots/broadcast/v0/broadcast.grpc.pb.h" -#include "cura/plugins/slots/broadcast/v0/broadcast.pb.h" -#include "cura/plugins/slots/handshake/v0/handshake.grpc.pb.h" -#include "cura/plugins/slots/handshake/v0/handshake.pb.h" -#include "cura/plugins/v0/slot_id.pb.h" -#include "plugins/broadcasts.h" -#include "plugins/exception.h" -#include "plugins/metadata.h" -#include "utils/format/thread_id.h" -#include "utils/types/char_range_literal.h" -#include "utils/types/generic.h" +#include #include #include @@ -30,7 +19,18 @@ #include #include -#include +#include "Application.h" +#include "cura/plugins/slots/broadcast/v0/broadcast.grpc.pb.h" +#include "cura/plugins/slots/broadcast/v0/broadcast.pb.h" +#include "cura/plugins/slots/handshake/v0/handshake.grpc.pb.h" +#include "cura/plugins/slots/handshake/v0/handshake.pb.h" +#include "cura/plugins/v0/slot_id.pb.h" +#include "plugins/broadcasts.h" +#include "plugins/exception.h" +#include "plugins/metadata.h" +#include "utils/format/thread_id.h" +#include "utils/types/char_range_literal.h" +#include "utils/types/generic.h" #if __has_include() #include #elif __has_include() diff --git a/include/progress/ProgressEstimatorLinear.h b/include/progress/ProgressEstimatorLinear.h index 178338a560..ba99ab8086 100644 --- a/include/progress/ProgressEstimatorLinear.h +++ b/include/progress/ProgressEstimatorLinear.h @@ -1,5 +1,5 @@ -//Copyright (c) 2020 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2020 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef PROGRESS_PROGRESS_ESTIMATOR_LINEAR_H #define PROGRESS_PROGRESS_ESTIMATOR_LINEAR_H @@ -15,9 +15,10 @@ namespace cura class ProgressEstimatorLinear : public ProgressEstimator { unsigned int total_steps_; + public: ProgressEstimatorLinear(unsigned int total_steps) - : total_steps_(total_steps) + : total_steps_(total_steps) { } double progress(int current_step) diff --git a/include/settings/FlowTempGraph.h b/include/settings/FlowTempGraph.h index 3cb26e91dd..c1c3166f09 100644 --- a/include/settings/FlowTempGraph.h +++ b/include/settings/FlowTempGraph.h @@ -1,5 +1,5 @@ -//Copyright (c) 2020 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2020 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef FLOW_TEMP_GRAPH #define FLOW_TEMP_GRAPH @@ -24,19 +24,20 @@ class FlowTempGraph const double flow_; //!< The flow in mm^3/s const Temperature temp_; //!< The temperature in *C Datum(const double flow, const Temperature temp) - : flow_(flow) - , temp_(temp) - {} + : flow_(flow) + , temp_(temp) + { + } }; std::vector data_; //!< The points of the graph between which the graph is linearly interpolated /*! * Get the temperature corresponding to a specific flow. - * + * * For flows outside of the chart, the temperature at the minimal or maximal flow is returned. * When the graph is empty, the @p material_print_temperature is returned. - * + * * \param flow the flow in mm^3/s * \param material_print_temperature The default printing temp (backward compatibility for when the graph fails) * \return the corresponding temp diff --git a/include/settings/ZSeamConfig.h b/include/settings/ZSeamConfig.h index c82090de5c..1086248d59 100644 --- a/include/settings/ZSeamConfig.h +++ b/include/settings/ZSeamConfig.h @@ -1,11 +1,11 @@ -//Copyright (c) 2020 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2020 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef ZSEAMCONFIG_H #define ZSEAMCONFIG_H -#include "EnumSettings.h" //For EZSeamType and EZSeamCornerPrefType. #include "../utils/IntPoint.h" //To store the preferred seam position. +#include "EnumSettings.h" //For EZSeamType and EZSeamCornerPrefType. namespace cura { @@ -49,15 +49,13 @@ struct ZSeamConfig * \param corner_pref The corner preference, when using the sharpest corner strategy. * \param by how much to simplify the curvature (when detecting corners), as otherwise 'smooth' corners are penalized. */ - ZSeamConfig - ( + ZSeamConfig( const EZSeamType type = EZSeamType::SHORTEST, const Point pos = Point(0, 0), const EZSeamCornerPrefType corner_pref = EZSeamCornerPrefType::Z_SEAM_CORNER_PREF_NONE, - const coord_t simplify_curvature = 0 - ); + const coord_t simplify_curvature = 0); }; -} //Cura namespace. +} // namespace cura -#endif //ZSEAMCONFIG_H +#endif // ZSEAMCONFIG_H diff --git a/include/utils/AABB.h b/include/utils/AABB.h index eded125621..988eb3b7ff 100644 --- a/include/utils/AABB.h +++ b/include/utils/AABB.h @@ -1,5 +1,5 @@ -//Copyright (c) 2018 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2018 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef UTILS_AABB_H #define UTILS_AABB_H @@ -64,9 +64,9 @@ class AABB /*! * Check whether this aabb overlaps with another. - * + * * In the boundary case false is returned. - * + * * \param other the aabb to check for overlaps with * \return Whether the two aabbs overlap */ @@ -74,27 +74,27 @@ class AABB /*! * \brief Includes the specified point in the bounding box. - * + * * The bounding box is expanded if the point is not within the bounding box. - * + * * \param point The point to include in the bounding box. */ void include(Point point); /*! * \brief Includes the specified bounding box in the bounding box. - * + * * The bounding box is expanded to include the other bounding box. - * + * * This performs a union on two bounding boxes. - * + * * \param other The bounding box to include in this one. */ void include(const AABB other); /*! * Expand the borders of the bounding box in each direction with the given amount - * + * * \param dist The distance by which to expand the borders of the bounding box */ void expand(int dist); @@ -106,6 +106,5 @@ class AABB Polygon toPolygon() const; }; -}//namespace cura -#endif//UTILS_AABB_H - +} // namespace cura +#endif // UTILS_AABB_H diff --git a/include/utils/ExtrusionJunction.h b/include/utils/ExtrusionJunction.h index ce38e1900b..71cd71a636 100644 --- a/include/utils/ExtrusionJunction.h +++ b/include/utils/ExtrusionJunction.h @@ -1,5 +1,5 @@ -//Copyright (c) 2021 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2021 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef UTILS_EXTRUSION_JUNCTION_H @@ -55,5 +55,5 @@ inline const Point& make_point(const ExtrusionJunction& ej) using LineJunctions = std::vector; // //To allow tests to use protected members. +#include //To allow tests to use protected members. #endif #include #include "IntPoint.h" +#include "linearAlg2D.h" #include "polygon.h" #include "polygonUtils.h" -#include "linearAlg2D.h" -namespace cura +namespace cura { /*! @@ -105,7 +105,8 @@ class PolygonConnector std::vector input_polygons_; //!< The polygons assembled by calls to \ref PolygonConnector::add. std::vector input_paths_; //!< The paths assembled by calls to \ref PolygonConnector::add. - constexpr static Ratio max_gap_ = 0.5; //!< The maximum allowed gap between lines that get connected, in multiples of the local line width. Allows connections inside corners where the endpoints are slightly apart. + constexpr static Ratio max_gap_ = 0.5; //!< The maximum allowed gap between lines that get connected, in multiples of the local line width. Allows connections inside corners + //!< where the endpoints are slightly apart. /*! * Line segment to connect two polygons, with all the necessary information @@ -166,12 +167,12 @@ class PolygonConnector * connection. */ PolygonConnection(Polygonal* from_poly, const size_t from_segment, const Point from_point, Polygonal* to_poly, const size_t to_segment, const Point to_point) - : from_poly_(from_poly) - , from_segment_(from_segment) - , from_point_(from_point) - , to_poly_(to_poly) - , to_segment_(to_segment) - , to_point_(to_point) + : from_poly_(from_poly) + , from_segment_(from_segment) + , from_point_(from_point) + , to_poly_(to_poly) + , to_segment_(to_segment) + , to_point_(to_point) { } @@ -195,7 +196,7 @@ class PolygonConnector * a ^ ^ b --> connection a is always the left one * ^ ^ --> direction of the two connections themselves. * -----o-----o---- - * + * * The resulting polygon will travel along the edges in a direction different from each other. */ template @@ -204,8 +205,10 @@ class PolygonConnector PolygonConnection a_; //!< first connection PolygonConnection b_; //!< second connection PolygonBridge(const PolygonConnection& a, const PolygonConnection& b) - : a_(a), b_(b) - {} + : a_(a) + , b_(b) + { + } }; /*! @@ -222,9 +225,9 @@ class PolygonConnector std::vector connectGroup(std::vector& to_connect) { std::vector result; - while(!to_connect.empty()) + while (! to_connect.empty()) { - if(to_connect.size() == 1) //Nothing to connect it to any more. + if (to_connect.size() == 1) // Nothing to connect it to any more. { result.push_back(to_connect[0]); break; @@ -232,18 +235,18 @@ class PolygonConnector Polygonal current = std::move(to_connect.back()); to_connect.pop_back(); - if(!isClosed(current)) //Only bridge closed contours. + if (! isClosed(current)) // Only bridge closed contours. { result.push_back(current); continue; } std::optional> bridge = getBridge(current, to_connect); - if(bridge) + if (bridge) { - connectPolygonsAlongBridge(*bridge, *bridge->a_.to_poly_); //Connect the polygons, and store the result in the to_poly. - //Don't store the current polygon. It has just been merged into the other one. + connectPolygonsAlongBridge(*bridge, *bridge->a_.to_poly_); // Connect the polygons, and store the result in the to_poly. + // Don't store the current polygon. It has just been merged into the other one. } - else //Can't connect this to anything. Leave it as-is. + else // Can't connect this to anything. Leave it as-is. { result.push_back(current); } @@ -371,8 +374,14 @@ class PolygonConnector template coord_t getSpace(const PolygonConnection& connection) const { - const coord_t from_width = interpolateWidth(connection.from_point_, (*connection.from_poly_)[connection.from_segment_], (*connection.from_poly_)[(connection.from_segment_ + 1) % connection.from_poly_->size()]); - const coord_t to_width = interpolateWidth(connection.to_point_, (*connection.to_poly_)[connection.to_segment_], (*connection.to_poly_)[(connection.to_segment_ + 1) % connection.to_poly_->size()]); + const coord_t from_width = interpolateWidth( + connection.from_point_, + (*connection.from_poly_)[connection.from_segment_], + (*connection.from_poly_)[(connection.from_segment_ + 1) % connection.from_poly_->size()]); + const coord_t to_width = interpolateWidth( + connection.to_point_, + (*connection.to_poly_)[connection.to_segment_], + (*connection.to_poly_)[(connection.to_segment_ + 1) % connection.to_poly_->size()]); return vSize(connection.to_point_ - connection.from_point_) - from_width / 2 - to_width / 2; } @@ -390,9 +399,9 @@ class PolygonConnector coord_t interpolateWidth(const Point position, Vertex a, Vertex b) const { const coord_t total_length = vSize(getPosition(a) - getPosition(b)); - if(total_length == 0) //Prevent division by 0 when the vertices are on top of each other. + if (total_length == 0) // Prevent division by 0 when the vertices are on top of each other. { - return getWidth(a); //Just return one of them. They are on top of each other anyway. + return getWidth(a); // Just return one of them. They are on top of each other anyway. } const coord_t position_along_length = vSize(position - getPosition(a)); return round_divide(getWidth(b) * position_along_length, total_length) + round_divide(getWidth(a) * (total_length - position_along_length), total_length); @@ -405,27 +414,27 @@ class PolygonConnector template std::optional> findConnection(Polygonal& from_poly, std::vector& to_polygons) { - //Optimise for finding the best connection. - coord_t best_distance = line_width_ * max_gap_; //Allow up to the max_gap. + // Optimise for finding the best connection. + coord_t best_distance = line_width_ * max_gap_; // Allow up to the max_gap. std::optional> best_connection; std::optional> best_second_connection; - //The smallest connection will be from one of the vertices. So go through all of the vertices to find the closest place where they approach. - for(size_t poly_index = 0; poly_index < to_polygons.size(); ++poly_index) + // The smallest connection will be from one of the vertices. So go through all of the vertices to find the closest place where they approach. + for (size_t poly_index = 0; poly_index < to_polygons.size(); ++poly_index) { - if(!isClosed(to_polygons[poly_index])) + if (! isClosed(to_polygons[poly_index])) { continue; } - for(size_t to_index = 0; to_index < to_polygons[poly_index].size(); ++to_index) + for (size_t to_index = 0; to_index < to_polygons[poly_index].size(); ++to_index) { - const Point to_pos1 = getPosition(to_polygons[poly_index][to_index]); + const Point to_pos1 = getPosition(to_polygons[poly_index][to_index]); const coord_t to_width1 = getWidth(to_polygons[poly_index][to_index]); - const Point to_pos2 = getPosition(to_polygons[poly_index][(to_index + 1) % to_polygons[poly_index].size()]); + const Point to_pos2 = getPosition(to_polygons[poly_index][(to_index + 1) % to_polygons[poly_index].size()]); const coord_t to_width2 = getWidth(to_polygons[poly_index][(to_index + 1) % to_polygons[poly_index].size()]); const coord_t smallest_to_width = std::min(to_width1, to_width2); - for(size_t from_index = 0; from_index < from_poly.size(); ++from_index) + for (size_t from_index = 0; from_index < from_poly.size(); ++from_index) { const Point from_pos1 = getPosition(from_poly[from_index]); const coord_t from_width1 = getWidth(from_poly[from_index]); @@ -433,22 +442,24 @@ class PolygonConnector const coord_t from_width2 = getWidth(from_poly[(from_index + 1) % from_poly.size()]); const coord_t smallest_from_width = std::min(from_width1, from_width2); - //Try a naive distance first. Faster to compute, but it may estimate the distance too small. + // Try a naive distance first. Faster to compute, but it may estimate the distance too small. coord_t naive_dist = LinearAlg2D::getDistFromLine(from_pos1, to_pos1, to_pos2); - if(naive_dist - from_width1 - smallest_to_width < line_width_ * max_gap_) + if (naive_dist - from_width1 - smallest_to_width < line_width_ * max_gap_) { const Point closest_point = LinearAlg2D::getClosestOnLineSegment(from_pos1, to_pos1, to_pos2); - if(closest_point == to_pos2) //The last endpoint of a vertex is considered to be part of the next segment. Let that one handle it. + if (closest_point == to_pos2) // The last endpoint of a vertex is considered to be part of the next segment. Let that one handle it. { continue; } - const coord_t width_at_closest = interpolateWidth(closest_point, to_polygons[poly_index][to_index], to_polygons[poly_index][(to_index + 1) % to_polygons[poly_index].size()]); - const coord_t distance = vSize(closest_point - from_pos1) - from_width1 - width_at_closest; //Actual, accurate distance to the other polygon. - if(distance < best_distance) + const coord_t width_at_closest + = interpolateWidth(closest_point, to_polygons[poly_index][to_index], to_polygons[poly_index][(to_index + 1) % to_polygons[poly_index].size()]); + const coord_t distance = vSize(closest_point - from_pos1) - from_width1 - width_at_closest; // Actual, accurate distance to the other polygon. + if (distance < best_distance) { - PolygonConnection first_connection = PolygonConnection(&from_poly, from_index, from_pos1, &to_polygons[poly_index], to_index, closest_point); + PolygonConnection first_connection + = PolygonConnection(&from_poly, from_index, from_pos1, &to_polygons[poly_index], to_index, closest_point); std::optional> second_connection = getSecondConnection(first_connection, (width_at_closest + from_width1) / 2); - if(second_connection) //Second connection is also valid. + if (second_connection) // Second connection is also valid. { best_distance = distance; best_connection = first_connection; @@ -457,22 +468,23 @@ class PolygonConnector } } - //Also try the other way around: From the line segment of the from_poly to a vertex in the to_polygons. + // Also try the other way around: From the line segment of the from_poly to a vertex in the to_polygons. naive_dist = LinearAlg2D::getDistFromLine(to_pos1, from_pos1, from_pos2); - if(naive_dist - smallest_from_width - to_width1 < line_width_ * max_gap_) + if (naive_dist - smallest_from_width - to_width1 < line_width_ * max_gap_) { const Point closest_point = LinearAlg2D::getClosestOnLineSegment(to_pos1, from_pos1, from_pos2); - if(closest_point == from_pos2) //The last endpoint of a vertex is considered to be part of the next segment. Let that one handle it. + if (closest_point == from_pos2) // The last endpoint of a vertex is considered to be part of the next segment. Let that one handle it. { continue; } const coord_t width_at_closest = interpolateWidth(closest_point, from_poly[from_index], from_poly[(from_index + 1) % from_poly.size()]); - const coord_t distance = vSize(closest_point - to_pos1) - width_at_closest - to_width1; //Actual, accurate distance. - if(distance < best_distance) + const coord_t distance = vSize(closest_point - to_pos1) - width_at_closest - to_width1; // Actual, accurate distance. + if (distance < best_distance) { - PolygonConnection first_connection = PolygonConnection(&from_poly, from_index, closest_point, &to_polygons[poly_index], to_index, to_pos1); + PolygonConnection first_connection + = PolygonConnection(&from_poly, from_index, closest_point, &to_polygons[poly_index], to_index, to_pos1); std::optional> second_connection = getSecondConnection(first_connection, (to_width1 + width_at_closest) / 2); - if(second_connection) //Second connection is also valid. + if (second_connection) // Second connection is also valid. { best_distance = distance; best_connection = first_connection; @@ -484,7 +496,7 @@ class PolygonConnector } } - if(best_connection) + if (best_connection) { return PolygonBridge(*best_connection, *best_second_connection); } @@ -496,15 +508,15 @@ class PolygonConnector /*! * Get the bridge to cross between two polygons. - * + * * If no bridge is possible, or if no bridge is found for any reason, then no object is returned. - * + * * Algorithm outline: * - find the closest first connection between a \p poly and all (other) \p polygons * - find the best second connection parallel to that one at a line_width away - * + * * if no second connection is found: - * - find the second connection at half a line width away and + * - find the second connection at half a line width away and * - the first connection at a whole line distance away * So as to try and find a bridge which is centered around the initiall found first connection */ @@ -512,13 +524,13 @@ class PolygonConnector std::optional> getBridge(Polygonal& from_poly, std::vector& to_polygons) { std::optional> connection = findConnection(from_poly, to_polygons); - if(!connection) //We didn't find a connection. No bridge. + if (! connection) // We didn't find a connection. No bridge. { return std::nullopt; } - //Ensure that B is always the right connection and A the left. - if(LinearAlg2D::pointIsLeftOfLine(connection->b_.from_point_, connection->a_.from_point_, connection->a_.to_point_) > 0) + // Ensure that B is always the right connection and A the left. + if (LinearAlg2D::pointIsLeftOfLine(connection->b_.from_point_, connection->a_.from_point_, connection->a_.to_point_) > 0) { std::swap(connection->a_, connection->b_); } @@ -546,37 +558,38 @@ class PolygonConnector * ``std::nullopt``. */ template - std::optional> walkUntilDistanceFromLine(const Polygonal& poly, const size_t start_index, const coord_t distance, const Point& line_a, const Point& line_b, const short direction) + std::optional> + walkUntilDistanceFromLine(const Polygonal& poly, const size_t start_index, const coord_t distance, const Point& line_a, const Point& line_b, const short direction) { const size_t poly_size = poly.size(); - const coord_t line_magnitude = vSize(line_b - line_a); //Pre-compute, used for line distance calculation. - if(line_magnitude == 0) + const coord_t line_magnitude = vSize(line_b - line_a); // Pre-compute, used for line distance calculation. + if (line_magnitude == 0) { - return std::nullopt; //Line doesn't have a direction, so we can't be on any one side of it. + return std::nullopt; // Line doesn't have a direction, so we can't be on any one side of it. } - for(size_t index = (start_index + direction + poly_size) % poly_size; index != start_index; index = (index + direction + poly_size) % poly_size) + for (size_t index = (start_index + direction + poly_size) % poly_size; index != start_index; index = (index + direction + poly_size) % poly_size) { const Point vertex_pos = getPosition(poly[index]); - const coord_t vertex_distance = cross(line_a - line_b, line_a - vertex_pos) / line_magnitude; //Signed distance! - if(std::abs(vertex_distance) >= distance) //Further away from the line than the threshold. + const coord_t vertex_distance = cross(line_a - line_b, line_a - vertex_pos) / line_magnitude; // Signed distance! + if (std::abs(vertex_distance) >= distance) // Further away from the line than the threshold. { - //Interpolate over that last line segment to find the point at exactly the right distance. + // Interpolate over that last line segment to find the point at exactly the right distance. const size_t previous_index = (index - direction + poly_size) % poly_size; const Point previous_pos = getPosition(poly[previous_index]); const coord_t previous_distance = cross(line_a - line_b, line_a - previous_pos) / line_magnitude; - if(previous_distance == vertex_distance) //0-length line segment, or parallel to line. + if (previous_distance == vertex_distance) // 0-length line segment, or parallel to line. { continue; } const double interpolation_pos = double(distance - previous_distance) / (vertex_distance - previous_distance); const double interpolation_neg = double(-distance - previous_distance) / (vertex_distance - previous_distance); double interpolation; - if(interpolation_pos >= 0 && interpolation_pos < 1) + if (interpolation_pos >= 0 && interpolation_pos < 1) { interpolation = interpolation_pos; } - else if(interpolation_neg >= 0 && interpolation_neg < 1) + else if (interpolation_neg >= 0 && interpolation_neg < 1) { interpolation = interpolation_neg; } @@ -585,19 +598,19 @@ class PolygonConnector continue; } const Point interpolated_point = previous_pos + (vertex_pos - previous_pos) * interpolation; - return std::make_pair(interpolated_point, (direction == +1) ? previous_index : index); //Choose the "earlier" index of the two, regardless of direction. + return std::make_pair(interpolated_point, (direction == +1) ? previous_index : index); // Choose the "earlier" index of the two, regardless of direction. } } - return std::nullopt; //None of the vertices were far enough away from the line. + return std::nullopt; // None of the vertices were far enough away from the line. } /*! * Get a connection parallel to a given \p first connection at an orthogonal distance line_width from the \p first connection. - * + * * From a given \p first connection, * walk along both polygons in each direction * until we are at a distance of line_width away orthogonally from the line segment of the \p first connection. - * + * * For all combinations of such found points: * - check whether they are both on the same side of the \p first connection * - choose the connection which woukd form the smalles bridge @@ -608,23 +621,27 @@ class PolygonConnector std::optional> result = std::nullopt; coord_t best_connection_length = std::numeric_limits::max(); - //Find the four intersections, on both sides of the initial connection, and on both polygons. - std::optional> from_forward_intersection = walkUntilDistanceFromLine(*first.from_poly_, first.from_segment_, adjacent_distance, first.from_point_, first.to_point_, +1); - std::optional> from_backward_intersection = walkUntilDistanceFromLine(*first.from_poly_, first.from_segment_, adjacent_distance, first.from_point_, first.to_point_, -1); - std::optional> to_forward_intersection = walkUntilDistanceFromLine(*first.to_poly_, first.to_segment_, adjacent_distance, first.from_point_, first.to_point_, +1); - std::optional> to_backward_intersection = walkUntilDistanceFromLine(*first.to_poly_, first.to_segment_, adjacent_distance, first.from_point_, first.to_point_, -1); - - for(const std::optional>& from_intersection : {from_forward_intersection, from_backward_intersection}) + // Find the four intersections, on both sides of the initial connection, and on both polygons. + std::optional> from_forward_intersection + = walkUntilDistanceFromLine(*first.from_poly_, first.from_segment_, adjacent_distance, first.from_point_, first.to_point_, +1); + std::optional> from_backward_intersection + = walkUntilDistanceFromLine(*first.from_poly_, first.from_segment_, adjacent_distance, first.from_point_, first.to_point_, -1); + std::optional> to_forward_intersection + = walkUntilDistanceFromLine(*first.to_poly_, first.to_segment_, adjacent_distance, first.from_point_, first.to_point_, +1); + std::optional> to_backward_intersection + = walkUntilDistanceFromLine(*first.to_poly_, first.to_segment_, adjacent_distance, first.from_point_, first.to_point_, -1); + + for (const std::optional>& from_intersection : { from_forward_intersection, from_backward_intersection }) { - if(!from_intersection) + if (! from_intersection) { continue; } - //Find the shortest of the connections in the to_poly. + // Find the shortest of the connections in the to_poly. const bool original_side = LinearAlg2D::pointIsLeftOfLine(first.to_point_, first.from_point_, from_intersection->first) > 0; - for(const std::optional>& to_intersection : {to_forward_intersection, to_backward_intersection}) + for (const std::optional>& to_intersection : { to_forward_intersection, to_backward_intersection }) { - if(!to_intersection) + if (! to_intersection) { continue; } @@ -633,9 +650,10 @@ class PolygonConnector { continue; } - PolygonConnection connection(first.from_poly_, from_intersection->second, from_intersection->first, first.to_poly_, to_intersection->second, to_intersection->first); + PolygonConnection + connection(first.from_poly_, from_intersection->second, from_intersection->first, first.to_poly_, to_intersection->second, to_intersection->first); const coord_t connection_length = getSpace(connection); - if(connection_length < max_gap_ * line_width_ && connection_length < best_connection_length) //Connection is allowed. + if (connection_length < max_gap_ * line_width_ && connection_length < best_connection_length) // Connection is allowed. { result = connection; best_connection_length = connection_length; @@ -648,63 +666,67 @@ class PolygonConnector template void connectPolygonsAlongBridge(const PolygonBridge& bridge, Polygonal& result) { - //We'll traverse the following path: + // We'll traverse the following path: // - // <<<<<>>>>>X......X>>>>>>> from_poly + // <<<<<>>>>>X......X>>>>>>> from_poly // - //To do this, from_poly and to_poly might need to be traversed in reverse order. This function figures all of that out. + // To do this, from_poly and to_poly might need to be traversed in reverse order. This function figures all of that out. - Polygonal ret = createEmpty(); //Create a temporary result that we'll move into the result. + Polygonal ret = createEmpty(); // Create a temporary result that we'll move into the result. const size_t from_size = bridge.b_.from_poly_->size(); - //Add the from-endpoint of B. - const coord_t b_from_width = interpolateWidth(bridge.b_.from_point_, (*bridge.b_.from_poly_)[bridge.b_.from_segment_], (*bridge.b_.from_poly_)[(bridge.b_.from_segment_ + 1) % from_size]); + // Add the from-endpoint of B. + const coord_t b_from_width + = interpolateWidth(bridge.b_.from_point_, (*bridge.b_.from_poly_)[bridge.b_.from_segment_], (*bridge.b_.from_poly_)[(bridge.b_.from_segment_ + 1) % from_size]); addVertex(ret, bridge.b_.from_point_, b_from_width); - //Add the from-polygonal from B to A. + // Add the from-polygonal from B to A. short forwards; - if(bridge.a_.from_segment_ == bridge.b_.from_segment_) //If we start and end on the same segment, iterate in the direction from A to B. + if (bridge.a_.from_segment_ == bridge.b_.from_segment_) // If we start and end on the same segment, iterate in the direction from A to B. { - const Point vertex = getPosition((*bridge.b_.from_poly_)[bridge.b_.from_segment_]); //Same vertex for A and B. + const Point vertex = getPosition((*bridge.b_.from_poly_)[bridge.b_.from_segment_]); // Same vertex for A and B. const Point next_vertex = getPosition((*bridge.b_.from_poly_)[(bridge.b_.from_segment_ + 1) % from_size]); - const Point direction = next_vertex - vertex; //Direction we'd go into when forward iterating. + const Point direction = next_vertex - vertex; // Direction we'd go into when forward iterating. const Point a_to_b = bridge.b_.from_point_ - bridge.a_.from_point_; forwards = vSize2(direction - a_to_b) < vSize2(-direction - a_to_b); } else { - //If not the same segment, traverse in whichever direction is the long way around. - forwards = ((bridge.b_.from_segment_ + from_size - bridge.a_.from_segment_) % from_size) < ((bridge.a_.from_segment_ + from_size - bridge.b_.from_segment_) % from_size); + // If not the same segment, traverse in whichever direction is the long way around. + forwards + = ((bridge.b_.from_segment_ + from_size - bridge.a_.from_segment_) % from_size) < ((bridge.a_.from_segment_ + from_size - bridge.b_.from_segment_) % from_size); } size_t first_segment = forwards ? (bridge.b_.from_segment_ + 1) % from_size : (bridge.b_.from_segment_ + from_size) % from_size; size_t last_segment = forwards ? bridge.a_.from_segment_ : bridge.a_.from_segment_; - if(first_segment == last_segment) last_segment = (last_segment + from_size - 2 * forwards + 1) % from_size; + if (first_segment == last_segment) + last_segment = (last_segment + from_size - 2 * forwards + 1) % from_size; size_t i = first_segment; - do //Since we might start and end on the same segment, do a do_while loop to iterate at least once. + do // Since we might start and end on the same segment, do a do_while loop to iterate at least once. { addVertex(ret, (*bridge.b_.from_poly_)[i]); i = (i + 2 * forwards - 1 + from_size) % from_size; - } - while(i != (last_segment + from_size + 2 * forwards - 1) % from_size); + } while (i != (last_segment + from_size + 2 * forwards - 1) % from_size); - //Add the from-endpoint of A. - const coord_t a_from_width = interpolateWidth(bridge.a_.from_point_, (*bridge.b_.from_poly_)[bridge.a_.from_segment_], (*bridge.b_.from_poly_)[(bridge.a_.from_segment_ + 1) % from_size]); + // Add the from-endpoint of A. + const coord_t a_from_width + = interpolateWidth(bridge.a_.from_point_, (*bridge.b_.from_poly_)[bridge.a_.from_segment_], (*bridge.b_.from_poly_)[(bridge.a_.from_segment_ + 1) % from_size]); addVertex(ret, bridge.a_.from_point_, a_from_width); const size_t to_size = bridge.b_.to_poly_->size(); - //Add the to-endpoint of A. - const coord_t a_to_width = interpolateWidth(bridge.a_.to_point_, (*bridge.a_.to_poly_)[bridge.a_.to_segment_], (*bridge.a_.to_poly_)[(bridge.a_.to_segment_ + 1) % to_size]); + // Add the to-endpoint of A. + const coord_t a_to_width + = interpolateWidth(bridge.a_.to_point_, (*bridge.a_.to_poly_)[bridge.a_.to_segment_], (*bridge.a_.to_poly_)[(bridge.a_.to_segment_ + 1) % to_size]); addVertex(ret, bridge.a_.to_point_, a_to_width); - //Add the to_polygonal from A to B. - if(bridge.a_.to_segment_ == bridge.b_.to_segment_) + // Add the to_polygonal from A to B. + if (bridge.a_.to_segment_ == bridge.b_.to_segment_) { - const Point vertex = getPosition((*bridge.b_.to_poly_)[bridge.b_.to_segment_]); //Same vertex for A and B. + const Point vertex = getPosition((*bridge.b_.to_poly_)[bridge.b_.to_segment_]); // Same vertex for A and B. const Point next_vertex = getPosition((*bridge.b_.to_poly_)[(bridge.b_.to_segment_ + 1) % to_size]); const Point direction = next_vertex - vertex; const Point a_to_b = bridge.b_.to_point_ - bridge.a_.to_point_; @@ -721,25 +743,24 @@ class PolygonConnector { addVertex(ret, (*bridge.b_.to_poly_)[i]); i = (i + 2 * forwards - 1 + to_size) % to_size; - } - while(i != end_segment); + } while (i != end_segment); - //Add the to-endpoint of B. - const coord_t b_to_width = interpolateWidth(bridge.b_.to_point_, (*bridge.b_.to_poly_)[bridge.b_.to_segment_], (*bridge.b_.to_poly_)[(bridge.b_.to_segment_ + 1) % to_size]); + // Add the to-endpoint of B. + const coord_t b_to_width + = interpolateWidth(bridge.b_.to_point_, (*bridge.b_.to_poly_)[bridge.b_.to_segment_], (*bridge.b_.to_poly_)[(bridge.b_.to_segment_ + 1) % to_size]); addVertex(ret, bridge.b_.to_point_, b_to_width); - if(getPosition(ret.back()) != getPosition(ret.front())) + if (getPosition(ret.back()) != getPosition(ret.front())) { addVertex(ret, getPosition(ret.front()), getWidth(ret.front())); } - result = std::move(ret); //Override the result with the new combined shape. + result = std::move(ret); // Override the result with the new combined shape. } }; -}//namespace cura - +} // namespace cura -#endif//UTILS_POLYGON_CONNECTOR_H +#endif // UTILS_POLYGON_CONNECTOR_H diff --git a/include/utils/PolylineStitcher.h b/include/utils/PolylineStitcher.h index 6a2063c1b9..2942a0840e 100644 --- a/include/utils/PolylineStitcher.h +++ b/include/utils/PolylineStitcher.h @@ -1,16 +1,16 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef UTILS_POLYLINE_STITCHER_H #define UTILS_POLYLINE_STITCHER_H -#include "polygon.h" -#include "SparsePointGrid.h" -#include "PolygonsPointIndex.h" +#include +#include +#include "PolygonsPointIndex.h" +#include "SparsePointGrid.h" #include "SymmetricPair.h" -#include -#include +#include "polygon.h" namespace cura { @@ -29,14 +29,14 @@ class PolylineStitcher * Only introduce new segments shorter than \p max_stitch_distance, and * larger than \p snap_distance but always try to take the shortest * connection possible. - * + * * Only stitch polylines into closed polygons if they are larger than 3 * * \p max_stitch_distance, in order to prevent small segments to * accidentally get closed into a polygon. - * + * * \warning Tiny polylines (smaller than 3 * max_stitch_distance) will not * be closed into polygons. - * + * * \note Resulting polylines and polygons are added onto the existing * containers, so you can directly output onto a polygons container with * existing polygons in it. However, you shouldn't call this function with @@ -60,7 +60,7 @@ class PolylineStitcher } SparsePointGrid, PathsPointIndexLocator> grid(max_stitch_distance, lines.size() * 2); - + // populate grid for (size_t line_idx = 0; line_idx < lines.size(); line_idx++) { @@ -68,9 +68,9 @@ class PolylineStitcher grid.insert(PathsPointIndex(&lines, line_idx, 0)); grid.insert(PathsPointIndex(&lines, line_idx, line.size() - 1)); } - + std::vector processed(lines.size(), false); - + for (size_t line_idx = 0; line_idx < lines.size(); line_idx++) { if (processed[line_idx]) @@ -80,7 +80,7 @@ class PolylineStitcher processed[line_idx] = true; const auto line = lines[line_idx]; bool should_close = isOdd(line); - + Path chain = line; bool closest_is_closing_polygon = false; for (bool go_in_reverse_direction : { false, true }) // first go in the unreversed direction, to try to prevent the chain.reverse() operation. @@ -94,75 +94,86 @@ class PolylineStitcher while (true) { Point from = make_point(chain.back()); - + PathsPointIndex closest; coord_t closest_distance = std::numeric_limits::max(); - grid.processNearby(from, max_stitch_distance, - std::function&)> ( - [from, &chain, &closest, &closest_is_closing_polygon, &closest_distance, &processed, &chain_length, go_in_reverse_direction, max_stitch_distance, snap_distance, should_close] - (const PathsPointIndex& nearby)->bool - { - bool is_closing_segment = false; - coord_t dist = vSize(nearby.p() - from); - if (dist > max_stitch_distance) - { - return true; // keep looking - } - if(vSize2(nearby.p() - make_point(chain.front())) < snap_distance * snap_distance) + grid.processNearby( + from, + max_stitch_distance, + std::function&)>( + [from, + &chain, + &closest, + &closest_is_closing_polygon, + &closest_distance, + &processed, + &chain_length, + go_in_reverse_direction, + max_stitch_distance, + snap_distance, + should_close](const PathsPointIndex& nearby) -> bool { - if (chain_length + dist < 3 * max_stitch_distance // prevent closing of small poly, cause it might be able to continue making a larger polyline - || chain.size() <= 2) // don't make 2 vert polygons + bool is_closing_segment = false; + coord_t dist = vSize(nearby.p() - from); + if (dist > max_stitch_distance) { - return true; // look for a better next line + return true; // keep looking } - is_closing_segment = true; - if(!should_close) + if (vSize2(nearby.p() - make_point(chain.front())) < snap_distance * snap_distance) { - dist += 10; // prefer continuing polyline over closing a polygon; avoids closed zigzags from being printed separately - // continue to see if closing segment is also the closest - // there might be a segment smaller than [max_stitch_distance] which closes the polygon better + if (chain_length + dist < 3 * max_stitch_distance // prevent closing of small poly, cause it might be able to continue making a larger polyline + || chain.size() <= 2) // don't make 2 vert polygons + { + return true; // look for a better next line + } + is_closing_segment = true; + if (! should_close) + { + dist += 10; // prefer continuing polyline over closing a polygon; avoids closed zigzags from being printed separately + // continue to see if closing segment is also the closest + // there might be a segment smaller than [max_stitch_distance] which closes the polygon better + } + else + { + dist -= 10; // Prefer closing the polygon if it's 100% even lines. Used to create closed contours. + // Continue to see if closing segment is also the closest. + } } - else + else if (processed[nearby.poly_idx_]) + { // it was already moved to output + return true; // keep looking for a connection + } + bool nearby_would_be_reversed = nearby.point_idx_ != 0; + nearby_would_be_reversed + = nearby_would_be_reversed != go_in_reverse_direction; // flip nearby_would_be_reversed when searching in the reverse direction + if (! canReverse(nearby) && nearby_would_be_reversed) + { // connecting the segment would reverse the polygon direction + return true; // keep looking for a connection + } + if (! canConnect(chain, (*nearby.polygons_)[nearby.poly_idx_])) { - dist -= 10; //Prefer closing the polygon if it's 100% even lines. Used to create closed contours. - //Continue to see if closing segment is also the closest. + return true; // keep looking for a connection } - } - else if (processed[nearby.poly_idx_]) - { // it was already moved to output - return true; // keep looking for a connection - } - bool nearby_would_be_reversed = nearby.point_idx_ != 0; - nearby_would_be_reversed = nearby_would_be_reversed != go_in_reverse_direction; // flip nearby_would_be_reversed when searching in the reverse direction - if ( ! canReverse(nearby) && nearby_would_be_reversed) - { // connecting the segment would reverse the polygon direction - return true; // keep looking for a connection - } - if ( ! canConnect(chain, (*nearby.polygons_)[nearby.poly_idx_])) - { - return true; // keep looking for a connection - } - if (dist < closest_distance) - { - closest_distance = dist; - closest = nearby; - closest_is_closing_polygon = is_closing_segment; - } - if (dist < snap_distance) - { // we have found a good enough next line - return false; // stop looking for alternatives - } - return true; // keep processing elements - }) - ); - - if (!closest.initialized() // we couldn't find any next line - || closest_is_closing_polygon // we closed the polygon + if (dist < closest_distance) + { + closest_distance = dist; + closest = nearby; + closest_is_closing_polygon = is_closing_segment; + } + if (dist < snap_distance) + { // we have found a good enough next line + return false; // stop looking for alternatives + } + return true; // keep processing elements + })); + + if (! closest.initialized() // we couldn't find any next line + || closest_is_closing_polygon // we closed the polygon ) { break; } - + coord_t segment_dist = vSize(make_point(chain.back()) - closest.p()); assert(segment_dist <= max_stitch_distance + 10); @@ -185,12 +196,12 @@ class PolylineStitcher } chain.insert(chain.end(), start_pos, (*closest.polygons_)[closest.poly_idx_].rend()); } - for(size_t i = old_size; i < chain.size(); ++i) //Update chain length. + for (size_t i = old_size; i < chain.size(); ++i) // Update chain length. { chain_length += vSize(chain[i] - chain[i - 1]); } - should_close = should_close & !isOdd((*closest.polygons_)[closest.poly_idx_]); //If we connect an even to an odd line, we should no longer try to close it. - assert( ! processed[closest.poly_idx_]); + should_close = should_close & ! isOdd((*closest.polygons_)[closest.poly_idx_]); // If we connect an even to an odd line, we should no longer try to close it. + assert(! processed[closest.poly_idx_]); processed[closest.poly_idx_] = true; } @@ -212,7 +223,7 @@ class PolylineStitcher else { PathsPointIndex ppi_here(&lines, line_idx, 0); - if ( ! canReverse(ppi_here)) + if (! canReverse(ppi_here)) { // Since closest_is_closing_polygon is false we went through the second iterations of the for-loop, where go_in_reverse_direction is true // the polyline isn't allowed to be reversed, so we re-reverse it. chain.reverse(); @@ -221,7 +232,7 @@ class PolylineStitcher } } } - + /*! * Whether a polyline is allowed to be reversed. (Not true for wall polylines which are not odd) */ @@ -236,6 +247,5 @@ class PolylineStitcher static bool isOdd(const Path& line); }; -}//namespace cura -#endif//UTILS_POLYLINE_STITCHER_H - +} // namespace cura +#endif // UTILS_POLYLINE_STITCHER_H diff --git a/include/utils/SquareGrid.h b/include/utils/SquareGrid.h index 0ed6e7305a..515cf0cf9d 100644 --- a/include/utils/SquareGrid.h +++ b/include/utils/SquareGrid.h @@ -1,17 +1,18 @@ -//Copyright (c) 2021 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2021 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef UTILS_SQUARE_GRID_H #define UTILS_SQUARE_GRID_H -#include "IntPoint.h" - #include +#include #include #include -#include -namespace cura { +#include "IntPoint.h" + +namespace cura +{ /*! * Helper class to calculate coordinates on a square grid, and providing some @@ -45,7 +46,7 @@ class SquareGrid * for each cell. Processing stops if function returns false. * \return Whether we need to continue processing after this function. */ - bool processLineCells(const std::pair line, const std::function& process_cell_func); + bool processLineCells(const std::pair line, const std::function& process_cell_func); /*! \brief Process cells along a line indicated by \p line. * @@ -54,7 +55,7 @@ class SquareGrid * for each cell. Processing stops if function returns false. * \return Whether we need to continue processing after this function. */ - bool processLineCells(const std::pair line, const std::function& process_cell_func) const; + bool processLineCells(const std::pair line, const std::function& process_cell_func) const; /*! * Process all cells in an axis-aligned right triangle. @@ -89,8 +90,8 @@ class SquareGrid * good candidate has been found. * \return Whether we need to continue processing after this function. */ - bool processAxisAlignedTriangle(const Point from, const Point to, const std::function& process_cell_func) const; - bool processAxisAlignedTriangle(const Point from, const Point to, bool to_the_right, const std::function& process_cell_func) const; + bool processAxisAlignedTriangle(const Point from, const Point to, const std::function& process_cell_func) const; + bool processAxisAlignedTriangle(const Point from, const Point to, bool to_the_right, const std::function& process_cell_func) const; /*! \brief Process cells that might contain sought after points. * @@ -104,8 +105,7 @@ class SquareGrid * ``false``. * \return Whether we need to continue processing after this function. */ - bool processNearby(const Point &query_pt, coord_t radius, - const std::function& process_func) const; + bool processNearby(const Point& query_pt, coord_t radius, const std::function& process_func) const; /*! \brief Compute the grid coordinates of a point. * \param point The actual location. @@ -125,7 +125,7 @@ class SquareGrid * \param location The grid location. * \return The print space coordinates that correspond to \p location. */ - Point toLowerCorner(const GridPoint& location) const; + Point toLowerCorner(const GridPoint& location) const; /*! \brief Compute the lowest coord in a grid cell. * The lowest point is the point in the grid cell closest to the origin. @@ -133,7 +133,7 @@ class SquareGrid * \param grid_coord The grid coordinate. * \return The print space coordinate that corresponds to \p grid_coord. */ - coord_t toLowerCoord(const grid_coord_t& grid_coord) const; + coord_t toLowerCoord(const grid_coord_t& grid_coord) const; protected: /*! \brief The cell (square) size. */ @@ -152,4 +152,4 @@ class SquareGrid } // namespace cura -#endif //UTILS_SQUARE_GRID_H +#endif // UTILS_SQUARE_GRID_H diff --git a/src/BeadingStrategy/OuterWallInsetBeadingStrategy.cpp b/src/BeadingStrategy/OuterWallInsetBeadingStrategy.cpp index c7d81cd798..bc49bd6f27 100644 --- a/src/BeadingStrategy/OuterWallInsetBeadingStrategy.cpp +++ b/src/BeadingStrategy/OuterWallInsetBeadingStrategy.cpp @@ -1,5 +1,5 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #include "BeadingStrategy/OuterWallInsetBeadingStrategy.h" @@ -7,10 +7,10 @@ namespace cura { -OuterWallInsetBeadingStrategy::OuterWallInsetBeadingStrategy(coord_t outer_wall_offset, BeadingStrategyPtr parent) : - BeadingStrategy(*parent), - parent_(std::move(parent)), - outer_wall_offset_(outer_wall_offset) +OuterWallInsetBeadingStrategy::OuterWallInsetBeadingStrategy(coord_t outer_wall_offset, BeadingStrategyPtr parent) + : BeadingStrategy(*parent) + , parent_(std::move(parent)) + , outer_wall_offset_(outer_wall_offset) { name_ = "OuterWallOfsetBeadingStrategy"; } @@ -46,7 +46,13 @@ BeadingStrategy::Beading OuterWallInsetBeadingStrategy::compute(coord_t thicknes Beading ret = parent_->compute(thickness, bead_count); // Actual count and thickness as represented by extant walls. Don't count any potential zero-width 'signaling' walls. - bead_count = std::count_if(ret.bead_widths.begin(), ret.bead_widths.end(), [](const coord_t width) { return width > 0; }); + bead_count = std::count_if( + ret.bead_widths.begin(), + ret.bead_widths.end(), + [](const coord_t width) + { + return width > 0; + }); // No need to apply any inset if there is just a single wall. if (bead_count < 2) diff --git a/src/ExtruderTrain.cpp b/src/ExtruderTrain.cpp index a06131472c..59d930aa88 100644 --- a/src/ExtruderTrain.cpp +++ b/src/ExtruderTrain.cpp @@ -1,14 +1,15 @@ -//Copyright (c) 2020 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2020 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #include "ExtruderTrain.h" -namespace cura +namespace cura { -ExtruderTrain::ExtruderTrain(const size_t extruder_nr, Settings* parent_settings) : extruder_nr_(extruder_nr) +ExtruderTrain::ExtruderTrain(const size_t extruder_nr, Settings* parent_settings) + : extruder_nr_(extruder_nr) { settings_.setParent(parent_settings); } -}//namespace cura +} // namespace cura diff --git a/src/PathOrderPath.cpp b/src/PathOrderPath.cpp index 7ee8e49d55..cfca513fa9 100644 --- a/src/PathOrderPath.cpp +++ b/src/PathOrderPath.cpp @@ -1,5 +1,5 @@ -//Copyright (c) 2023 UltiMaker -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2023 UltiMaker +// CuraEngine is released under the terms of the AGPLv3 or higher. #include "PathOrdering.h" //The definitions we're implementing here. #include "WallToolPaths.h" @@ -8,43 +8,43 @@ namespace cura { - template<> - ConstPolygonRef PathOrdering::getVertexData() - { - return *vertices_; - } +template<> +ConstPolygonRef PathOrdering::getVertexData() +{ + return *vertices_; +} - template<> - ConstPolygonRef PathOrdering::getVertexData() - { - return *vertices_; - } +template<> +ConstPolygonRef PathOrdering::getVertexData() +{ + return *vertices_; +} - template<> - ConstPolygonRef PathOrdering::getVertexData() - { - return vertices_->outline.outerPolygon(); - } +template<> +ConstPolygonRef PathOrdering::getVertexData() +{ + return vertices_->outline.outerPolygon(); +} - template<> - ConstPolygonRef PathOrdering::getVertexData() - { - return vertices_->outline.outerPolygon(); - } +template<> +ConstPolygonRef PathOrdering::getVertexData() +{ + return vertices_->outline.outerPolygon(); +} - template<> - ConstPolygonRef PathOrdering::getVertexData() - { - return vertices_->outline_.outerPolygon(); - } - template<> - ConstPolygonRef PathOrdering::getVertexData() +template<> +ConstPolygonRef PathOrdering::getVertexData() +{ + return vertices_->outline_.outerPolygon(); +} +template<> +ConstPolygonRef PathOrdering::getVertexData() +{ + if (! cached_vertices_) { - if ( ! cached_vertices_) - { - cached_vertices_ = vertices_->toPolygon(); - } - return ConstPolygonRef(*cached_vertices_); + cached_vertices_ = vertices_->toPolygon(); } - + return ConstPolygonRef(*cached_vertices_); } + +} // namespace cura diff --git a/src/Preheat.cpp b/src/Preheat.cpp index 914da06595..d2190cb9a3 100644 --- a/src/Preheat.cpp +++ b/src/Preheat.cpp @@ -1,11 +1,12 @@ // Copyright (c) 2022 Ultimaker B.V. // CuraEngine is released under the terms of the AGPLv3 or higher +#include "Preheat.h" + #include #include "Application.h" //To get settings. #include "ExtruderTrain.h" -#include "Preheat.h" #include "Slice.h" #include "settings/FlowTempGraph.h" #include "settings/types/Ratio.h" diff --git a/src/Slice.cpp b/src/Slice.cpp index 4782604e00..eb92ae1d68 100644 --- a/src/Slice.cpp +++ b/src/Slice.cpp @@ -1,15 +1,17 @@ // Copyright (c) 2022 Ultimaker B.V. // CuraEngine is released under the terms of the AGPLv3 or higher +#include "Slice.h" + #include #include "ExtruderTrain.h" -#include "Slice.h" namespace cura { -Slice::Slice(const size_t num_mesh_groups) : scene(num_mesh_groups) +Slice::Slice(const size_t num_mesh_groups) + : scene(num_mesh_groups) { } diff --git a/src/communication/CommandLine.cpp b/src/communication/CommandLine.cpp index 4b608dfbfb..e1a7b36e37 100644 --- a/src/communication/CommandLine.cpp +++ b/src/communication/CommandLine.cpp @@ -3,14 +3,6 @@ #include "communication/CommandLine.h" -#include "Application.h" //To get the extruders for material estimates. -#include "ExtruderTrain.h" -#include "FffProcessor.h" //To start a slice and get time estimates. -#include "Slice.h" -#include "utils/Matrix4x3D.h" //For the mesh_rotation_matrix setting. - -#include - #include //For strtok and strcopy. #include // error number when trying to read file #include @@ -21,6 +13,14 @@ #include #include +#include + +#include "Application.h" //To get the extruders for material estimates. +#include "ExtruderTrain.h" +#include "FffProcessor.h" //To start a slice and get time estimates. +#include "Slice.h" +#include "utils/Matrix4x3D.h" //For the mesh_rotation_matrix setting. + namespace cura { diff --git a/src/gcodeExport.cpp b/src/gcodeExport.cpp index 8d87717fa3..d719f8b236 100644 --- a/src/gcodeExport.cpp +++ b/src/gcodeExport.cpp @@ -98,7 +98,8 @@ void GCodeExport::preSetup(const size_t start_extruder) const Settings& extruder_settings = Application::getInstance().current_slice_->scene.extruders[extruder_nr].settings_; if (use_extruder_offset_to_offset_coords_) { - extruder_attr_[extruder_nr].nozzle_offset_ = Point(extruder_settings.get("machine_nozzle_offset_x"), extruder_settings.get("machine_nozzle_offset_y")); + extruder_attr_[extruder_nr].nozzle_offset_ + = Point(extruder_settings.get("machine_nozzle_offset_x"), extruder_settings.get("machine_nozzle_offset_y")); } else { diff --git a/src/infill/LightningDistanceField.cpp b/src/infill/LightningDistanceField.cpp index d0d0b5f2a3..0c532b8ced 100644 --- a/src/infill/LightningDistanceField.cpp +++ b/src/infill/LightningDistanceField.cpp @@ -1,25 +1,21 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #include "infill/LightningDistanceField.h" //Class we're implementing. + #include "utils/polygonUtils.h" //For spreadDotsArea helper function. namespace cura { -constexpr coord_t radius_per_cell_size = 6; // The cell-size should be small compared to the radius, but not so small as to be inefficient. +constexpr coord_t radius_per_cell_size = 6; // The cell-size should be small compared to the radius, but not so small as to be inefficient. -LightningDistanceField::LightningDistanceField -( - const coord_t& radius, - const Polygons& current_outline, - const Polygons& current_overhang -) -: cell_size_(radius / radius_per_cell_size) -, grid_(cell_size_) -, supporting_radius_(radius) -, current_outline_(current_outline) -, current_overhang_(current_overhang) +LightningDistanceField::LightningDistanceField(const coord_t& radius, const Polygons& current_outline, const Polygons& current_overhang) + : cell_size_(radius / radius_per_cell_size) + , grid_(cell_size_) + , supporting_radius_(radius) + , current_outline_(current_outline) + , current_overhang_(current_overhang) { std::vector regular_dots = PolygonUtils::spreadDotsArea(current_overhang, cell_size_); for (const auto& p : regular_dots) @@ -28,17 +24,13 @@ LightningDistanceField::LightningDistanceField const coord_t dist_to_boundary = vSize(p - cpp.p()); unsupported_points_.emplace_back(p, dist_to_boundary); } - unsupported_points_.sort - ( + unsupported_points_.sort( [&radius](const UnsupCell& a, const UnsupCell& b) { constexpr coord_t prime_for_hash = 191; - return - std::abs(b.dist_to_boundary_ - a.dist_to_boundary_) > radius ? - a.dist_to_boundary_ < b.dist_to_boundary_ : - (std::hash{}(a.loc_) % prime_for_hash) < (std::hash{}(b.loc_) % prime_for_hash); - } - ); + return std::abs(b.dist_to_boundary_ - a.dist_to_boundary_) > radius ? a.dist_to_boundary_ < b.dist_to_boundary_ + : (std::hash{}(a.loc_) % prime_for_hash) < (std::hash{}(b.loc_) % prime_for_hash); + }); for (auto it = unsupported_points_.begin(); it != unsupported_points_.end(); ++it) { UnsupCell& cell = *it; @@ -58,36 +50,35 @@ bool LightningDistanceField::tryGetNextPoint(Point* p) const void LightningDistanceField::update(const Point& to_node, const Point& added_leaf) { - auto process_func = - [added_leaf, this](const SquareGrid::GridPoint& grid_loc) + auto process_func = [added_leaf, this](const SquareGrid::GridPoint& grid_loc) + { + auto it = unsupported_points_grid_.find(grid_loc); + if (it != unsupported_points_grid_.end()) { - auto it = unsupported_points_grid_.find(grid_loc); - if (it != unsupported_points_grid_.end()) + std::list::iterator& list_it = it->second; + UnsupCell& cell = *list_it; + if (shorterThen(cell.loc_ - added_leaf, supporting_radius_)) { - std::list::iterator& list_it = it->second; - UnsupCell& cell = *list_it; - if (shorterThen(cell.loc_ - added_leaf, supporting_radius_)) - { - unsupported_points_.erase(list_it); - unsupported_points_grid_.erase(it); - } + unsupported_points_.erase(list_it); + unsupported_points_grid_.erase(it); } - return true; - }; + } + return true; + }; const Point a = to_node; const Point b = added_leaf; Point ab = b - a; Point ab_T = turn90CCW(ab); Point extent = normal(ab_T, supporting_radius_); // TODO: process cells only once; make use of PolygonUtils::spreadDotsArea - grid_.processLineCells(std::make_pair(a + extent, a - extent), - [this, ab, extent, &process_func] (const SquareGrid::GridPoint& p) - { - grid_.processLineCells(std::make_pair(p, p + ab), process_func); - return true; - } - ); + grid_.processLineCells( + std::make_pair(a + extent, a - extent), + [this, ab, extent, &process_func](const SquareGrid::GridPoint& p) + { + grid_.processLineCells(std::make_pair(p, p + ab), process_func); + return true; + }); grid_.processNearby(added_leaf, supporting_radius_, process_func); } -} \ No newline at end of file +} // namespace cura \ No newline at end of file diff --git a/src/infill/ZigzagConnectorProcessor.cpp b/src/infill/ZigzagConnectorProcessor.cpp index 1853ff77a5..5c579841a8 100644 --- a/src/infill/ZigzagConnectorProcessor.cpp +++ b/src/infill/ZigzagConnectorProcessor.cpp @@ -1,9 +1,10 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. -#include #include "infill/ZigzagConnectorProcessor.h" +#include + using namespace cura; @@ -76,9 +77,8 @@ bool ZigzagConnectorProcessor::shouldAddCurrentConnector(int start_scanline_idx, } } - const bool should_add = - (is_this_connection_even && !is_this_endpiece && !should_skip_this_connection) // normal connections that should be added - || (use_endpieces_ && is_this_endpiece); // end piece if it is enabled; + const bool should_add = (is_this_connection_even && ! is_this_endpiece && ! should_skip_this_connection) // normal connections that should be added + || (use_endpieces_ && is_this_endpiece); // end piece if it is enabled; return should_add; } @@ -116,11 +116,10 @@ void ZigzagConnectorProcessor::registerPolyFinished() { int scanline_start_index = last_connector_index_; int scanline_end_index = first_connector_end_scanline_index_; - const bool is_endpiece = is_first_connector_ || (!is_first_connector_ && scanline_start_index == scanline_end_index); + const bool is_endpiece = is_first_connector_ || (! is_first_connector_ && scanline_start_index == scanline_end_index); // decides whether to add this zag according to the following rules - if ((is_endpiece && use_endpieces_) - || (!is_endpiece && shouldAddCurrentConnector(scanline_start_index, scanline_end_index))) + if ((is_endpiece && use_endpieces_) || (! is_endpiece && shouldAddCurrentConnector(scanline_start_index, scanline_end_index))) { // for convenience, put every point in one vector for (const Point& point : first_connector_) @@ -145,7 +144,7 @@ void ZigzagConnectorProcessor::addZagConnector(std::vector& points, bool return; } Polygon polyline(points); - if (is_endpiece && !connected_endpieces_) + if (is_endpiece && ! connected_endpieces_) { polyline.pop_back(); } diff --git a/src/multiVolumes.cpp b/src/multiVolumes.cpp index e4e5398725..220523c723 100644 --- a/src/multiVolumes.cpp +++ b/src/multiVolumes.cpp @@ -3,6 +3,8 @@ #include "multiVolumes.h" +#include + #include "Application.h" #include "Slice.h" #include "settings/EnumSettings.h" @@ -10,8 +12,6 @@ #include "slicer.h" #include "utils/PolylineStitcher.h" -#include - namespace cura { diff --git a/src/pathPlanning/Comb.cpp b/src/pathPlanning/Comb.cpp index 7da890d3d9..e3243a344b 100644 --- a/src/pathPlanning/Comb.cpp +++ b/src/pathPlanning/Comb.cpp @@ -147,7 +147,8 @@ bool Comb::calc( unsigned int end_part_boundary_poly_idx_min{}; unsigned int start_part_idx_min = (start_inside_poly_min == NO_INDEX) ? NO_INDEX : parts_view_inside_minimum_.getPartContaining(start_inside_poly_min, &start_part_boundary_poly_idx_min); - unsigned int end_part_idx_min = (end_inside_poly_min == NO_INDEX) ? NO_INDEX : parts_view_inside_minimum_.getPartContaining(end_inside_poly_min, &end_part_boundary_poly_idx_min); + unsigned int end_part_idx_min + = (end_inside_poly_min == NO_INDEX) ? NO_INDEX : parts_view_inside_minimum_.getPartContaining(end_inside_poly_min, &end_part_boundary_poly_idx_min); CombPath result_path; bool comb_result; @@ -262,7 +263,8 @@ bool Comb::calc( { comb_paths.emplace_back(); comb_paths.throughAir = true; - if (vSize(start_crossing.in_or_mid_ - end_crossing.in_or_mid_) < vSize(start_crossing.in_or_mid_ - start_crossing.out_) + vSize(end_crossing.in_or_mid_ - end_crossing.out_)) + if (vSize(start_crossing.in_or_mid_ - end_crossing.in_or_mid_) + < vSize(start_crossing.in_or_mid_ - start_crossing.out_) + vSize(end_crossing.in_or_mid_ - end_crossing.out_)) { // via outside is moving more over the in-between zone comb_paths.back().push_back(start_crossing.in_or_mid_); comb_paths.back().push_back(end_crossing.in_or_mid_); @@ -419,7 +421,7 @@ Comb::Crossing::Crossing( if (dest_is_inside) { dest_crossing_poly_.emplace(boundary_inside[dest_part_boundary_crossing_poly_idx]); // initialize with most obvious poly, cause mostly a combing move will move outside the - // part, rather than inside a hole in the part + // part, rather than inside a hole in the part } } diff --git a/src/progress/ProgressStageEstimator.cpp b/src/progress/ProgressStageEstimator.cpp index e587141a0b..1ae0d6c713 100644 --- a/src/progress/ProgressStageEstimator.cpp +++ b/src/progress/ProgressStageEstimator.cpp @@ -1,17 +1,17 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #include "progress/ProgressStageEstimator.h" -namespace cura +namespace cura { -ProgressStageEstimator::ProgressStageEstimator(std::vector< double >& relative_time_estimates) -: total_estimated_time_(0) -, accumulated_estimate_(0) -, current_stage_idx_(-1) +ProgressStageEstimator::ProgressStageEstimator(std::vector& relative_time_estimates) + : total_estimated_time_(0) + , accumulated_estimate_(0) + , current_stage_idx_(-1) { stages_.reserve(relative_time_estimates.size()); for (double relative_estimated_time : relative_time_estimates) @@ -51,4 +51,4 @@ void ProgressStageEstimator::nextStage(ProgressEstimator* stage) } -} // namespace cura +} // namespace cura diff --git a/src/settings/ZSeamConfig.cpp b/src/settings/ZSeamConfig.cpp index 229722922b..ea91b0f516 100644 --- a/src/settings/ZSeamConfig.cpp +++ b/src/settings/ZSeamConfig.cpp @@ -1,5 +1,5 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #include "settings/ZSeamConfig.h" //The definitions we're implementing. @@ -7,11 +7,11 @@ namespace cura { ZSeamConfig::ZSeamConfig(const EZSeamType type, const Point pos, const EZSeamCornerPrefType corner_pref, const coord_t simplify_curvature) -: type_(type) -, pos_(pos) -, corner_pref_(corner_pref) -, simplify_curvature_(simplify_curvature) + : type_(type) + , pos_(pos) + , corner_pref_(corner_pref) + , simplify_curvature_(simplify_curvature) { } -} //Cura namespace. +} // namespace cura diff --git a/src/utils/AABB.cpp b/src/utils/AABB.cpp index 2b966afe1b..d31a64af21 100644 --- a/src/utils/AABB.cpp +++ b/src/utils/AABB.cpp @@ -2,28 +2,38 @@ // CuraEngine is released under the terms of the AGPLv3 or higher #include "utils/AABB.h" + +#include + #include "utils/linearAlg2D.h" #include "utils/polygon.h" //To create the AABB of a polygon. -#include namespace cura { -AABB::AABB() : min_(POINT_MAX, POINT_MAX), max_(POINT_MIN, POINT_MIN) +AABB::AABB() + : min_(POINT_MAX, POINT_MAX) + , max_(POINT_MIN, POINT_MIN) { } -AABB::AABB(const Point& min, const Point& max) : min_(min), max_(max) +AABB::AABB(const Point& min, const Point& max) + : min_(min) + , max_(max) { } -AABB::AABB(const Polygons& polys) : min_(POINT_MAX, POINT_MAX), max_(POINT_MIN, POINT_MIN) +AABB::AABB(const Polygons& polys) + : min_(POINT_MAX, POINT_MAX) + , max_(POINT_MIN, POINT_MIN) { calculate(polys); } -AABB::AABB(ConstPolygonRef poly) : min_(POINT_MAX, POINT_MAX), max_(POINT_MIN, POINT_MIN) +AABB::AABB(ConstPolygonRef poly) + : min_(POINT_MAX, POINT_MAX) + , max_(POINT_MIN, POINT_MIN) { calculate(poly); } @@ -38,7 +48,10 @@ coord_t AABB::distanceSquared(const Point& p) const const Point a = Point(max_.X, min_.Y); const Point b = Point(min_.X, max_.Y); return (contains(p) ? -1 : 1) - * std::min({ LinearAlg2D::getDist2FromLineSegment(min_, a, p), LinearAlg2D::getDist2FromLineSegment(a, max_, p), LinearAlg2D::getDist2FromLineSegment(max_, b, p), LinearAlg2D::getDist2FromLineSegment(b, min_, p) }); + * std::min({ LinearAlg2D::getDist2FromLineSegment(min_, a, p), + LinearAlg2D::getDist2FromLineSegment(a, max_, p), + LinearAlg2D::getDist2FromLineSegment(max_, b, p), + LinearAlg2D::getDist2FromLineSegment(b, min_, p) }); } coord_t AABB::distanceSquared(const AABB& other) const diff --git a/src/utils/Date.cpp b/src/utils/Date.cpp index 52065c72bc..890936622b 100644 --- a/src/utils/Date.cpp +++ b/src/utils/Date.cpp @@ -1,36 +1,34 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #include "utils/Date.h" -#include #include // sscanf #include // strstr #include // setw, setfill +#include namespace cura { Date::Date(int year, int month, int day) -: year_(year) -, month_(month) -, day_(day) + : year_(year) + , month_(month) + , day_(day) { } std::string Date::toStringDashed() { std::ostringstream str; - str << std::setfill('0') << std::setw(4) << year_ << "-" - << std::setfill('0') << std::setw(2) << month_ << "-" - << std::setfill('0') << std::setw(2) << day_; + str << std::setfill('0') << std::setw(4) << year_ << "-" << std::setfill('0') << std::setw(2) << month_ << "-" << std::setfill('0') << std::setw(2) << day_; return str.str(); } Date::Date() -: year_(-1) -, month_(-1) -, day_(-1) + : year_(-1) + , month_(-1) + , day_(-1) { } diff --git a/src/utils/ExtrusionJunction.cpp b/src/utils/ExtrusionJunction.cpp index 5a7cdb49b9..4e83ad3c24 100644 --- a/src/utils/ExtrusionJunction.cpp +++ b/src/utils/ExtrusionJunction.cpp @@ -1,22 +1,21 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #include "utils/ExtrusionJunction.h" namespace cura { -bool ExtrusionJunction::operator ==(const ExtrusionJunction& other) const +bool ExtrusionJunction::operator==(const ExtrusionJunction& other) const { - return p_ == other.p_ - && w_ == other.w_ - && perimeter_index_ == other.perimeter_index_; + return p_ == other.p_ && w_ == other.w_ && perimeter_index_ == other.perimeter_index_; } ExtrusionJunction::ExtrusionJunction(const Point p, const coord_t w, const coord_t perimeter_index) - : p_(p), - w_(w), - perimeter_index_(perimeter_index) -{} - + : p_(p) + , w_(w) + , perimeter_index_(perimeter_index) +{ } + +} // namespace cura diff --git a/src/utils/FMatrix4x3.cpp b/src/utils/FMatrix4x3.cpp index bdf5adb257..99d5bc0646 100644 --- a/src/utils/FMatrix4x3.cpp +++ b/src/utils/FMatrix4x3.cpp @@ -1,10 +1,9 @@ // Copyright (c) 2022 Ultimaker B.V. // CuraEngine is released under the terms of the AGPLv3 or higher. -#include "utils/Matrix4x3D.h" //The definitions we're implementing. - #include "settings/types/Ratio.h" //Scale factor. #include "utils/IntPoint.h" //Conversion directly into integer-based coordinates. +#include "utils/Matrix4x3D.h" //The definitions we're implementing. #include "utils/Point3D.h" //This matrix gets applied to floating point coordinates. namespace cura diff --git a/src/utils/ListPolyIt.cpp b/src/utils/ListPolyIt.cpp index 93cad91774..c640a9884e 100644 --- a/src/utils/ListPolyIt.cpp +++ b/src/utils/ListPolyIt.cpp @@ -1,5 +1,5 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #include "utils/ListPolyIt.h" @@ -9,7 +9,7 @@ #include "utils/AABB.h" // for debug output svg html #include "utils/SVG.h" -namespace cura +namespace cura { @@ -76,5 +76,4 @@ ListPolyIt ListPolyIt::insertPointNonDuplicate(const ListPolyIt before, const Li } - -}//namespace cura +} // namespace cura diff --git a/src/utils/PolygonConnector.cpp b/src/utils/PolygonConnector.cpp index 5aae9257f2..62b7b968a3 100644 --- a/src/utils/PolygonConnector.cpp +++ b/src/utils/PolygonConnector.cpp @@ -1,17 +1,18 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #include "utils/PolygonConnector.h" -#include "utils/linearAlg2D.h" #include "utils/AABB.h" +#include "utils/linearAlg2D.h" -namespace cura +namespace cura { PolygonConnector::PolygonConnector(const coord_t line_width) -: line_width_(line_width) -{} + : line_width_(line_width) +{ +} void PolygonConnector::add(const Polygons& input) { @@ -23,9 +24,9 @@ void PolygonConnector::add(const Polygons& input) void PolygonConnector::add(const std::vector& input) { - for(const VariableWidthLines& lines : input) + for (const VariableWidthLines& lines : input) { - for(const ExtrusionLine& line : lines) + for (const ExtrusionLine& line : lines) { input_paths_.push_back(line); } @@ -35,7 +36,7 @@ void PolygonConnector::add(const std::vector& input) void PolygonConnector::connect(Polygons& output_polygons, std::vector& output_paths) { std::vector result_polygons = connectGroup(input_polygons_); - for(Polygon& polygon : result_polygons) + for (Polygon& polygon : result_polygons) { output_polygons.add(polygon); } @@ -76,7 +77,7 @@ void PolygonConnector::addVertex(Polygon& polygonal, const Point& vertex) const void PolygonConnector::addVertex(ExtrusionLine& polygonal, const Point& position, const coord_t width) const { - polygonal.emplace_back(position, width, 1); //Perimeter indices don't make sense any more once perimeters are merged. Use 1 as placeholder, being the first "normal" wall. + polygonal.emplace_back(position, width, 1); // Perimeter indices don't make sense any more once perimeters are merged. Use 1 as placeholder, being the first "normal" wall. } void PolygonConnector::addVertex(ExtrusionLine& polygonal, const ExtrusionJunction& vertex) const @@ -97,12 +98,11 @@ bool PolygonConnector::isClosed(ExtrusionLine& polygonal) const template<> ExtrusionLine PolygonConnector::createEmpty() const { - constexpr size_t inset_index = 1; //Specialising to set inset_index to 1 instead of maximum int. Connected polys are not specific to any inset. + constexpr size_t inset_index = 1; // Specialising to set inset_index to 1 instead of maximum int. Connected polys are not specific to any inset. constexpr bool is_odd = false; ExtrusionLine result(inset_index, is_odd); result.is_closed_ = true; - return result; //No copy, via RVO. + return result; // No copy, via RVO. } -}//namespace cura - +} // namespace cura diff --git a/src/utils/PolygonsPointIndex.cpp b/src/utils/PolygonsPointIndex.cpp index 9cc2d3cf18..d41092baba 100644 --- a/src/utils/PolygonsPointIndex.cpp +++ b/src/utils/PolygonsPointIndex.cpp @@ -1,5 +1,5 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #include "utils/PolygonsPointIndex.h" @@ -12,4 +12,4 @@ ConstPolygonRef PathsPointIndex::getPolygon() const return (*polygons_)[poly_idx_]; } -} +} // namespace cura diff --git a/src/utils/PolylineStitcher.cpp b/src/utils/PolylineStitcher.cpp index 7346613e83..98a839e673 100644 --- a/src/utils/PolylineStitcher.cpp +++ b/src/utils/PolylineStitcher.cpp @@ -1,5 +1,5 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #include "utils/PolylineStitcher.h" @@ -52,5 +52,4 @@ bool PolylineStitcher::isOdd(const Polygon&) return false; } -}//namespace cura - +} // namespace cura diff --git a/src/utils/Simplify.cpp b/src/utils/Simplify.cpp index ed2dc9edb5..caefbf74de 100644 --- a/src/utils/Simplify.cpp +++ b/src/utils/Simplify.cpp @@ -1,11 +1,11 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. + +#include "utils/Simplify.h" #include #include //Priority queue to prioritise removing unimportant vertices. -#include "utils/Simplify.h" - namespace cura { @@ -13,18 +13,20 @@ Simplify::Simplify(const coord_t max_resolution, const coord_t max_deviation, co : max_resolution_(max_resolution) , max_deviation_(max_deviation) , max_area_deviation_(max_area_deviation) -{} +{ +} Simplify::Simplify(const Settings& settings) : max_resolution_(settings.get("meshfix_maximum_resolution")) , max_deviation_(settings.get("meshfix_maximum_deviation")) , max_area_deviation_(settings.get("meshfix_maximum_extrusion_area_deviation")) -{} +{ +} Polygons Simplify::polygon(const Polygons& polygons) const { Polygons result; - for(size_t i = 0; i < polygons.size(); ++i) + for (size_t i = 0; i < polygons.size(); ++i) { result.addIfNotEmpty(polygon(polygons[i])); } @@ -46,7 +48,7 @@ ExtrusionLine Simplify::polygon(const ExtrusionLine& polygon) const Polygons Simplify::polyline(const Polygons& polylines) const { Polygons result; - for(size_t i = 0; i < polylines.size(); ++i) + for (size_t i = 0; i < polylines.size(); ++i) { result.addIfNotEmpty(polyline(polylines[i])); } @@ -68,14 +70,16 @@ ExtrusionLine Simplify::polyline(const ExtrusionLine& polyline) const size_t Simplify::nextNotDeleted(size_t index, const std::vector& to_delete) const { const size_t size = to_delete.size(); - for(index = (index + 1) % size; to_delete[index]; index = (index + 1) % size); //Changes the index variable in-place until we found one that is not deleted. + for (index = (index + 1) % size; to_delete[index]; index = (index + 1) % size) + ; // Changes the index variable in-place until we found one that is not deleted. return index; } size_t Simplify::previousNotDeleted(size_t index, const std::vector& to_delete) const { const size_t size = to_delete.size(); - for(index = (index + size - 1) % size; to_delete[index]; index = (index + size - 1) % size); //Changes the index variable in-place until we found one that is not deleted. + for (index = (index + size - 1) % size; to_delete[index]; index = (index + size - 1) % size) + ; // Changes the index variable in-place until we found one that is not deleted. return index; } @@ -118,15 +122,15 @@ Point Simplify::createIntersection(const Point& before, const Point intersection ExtrusionJunction Simplify::createIntersection(const ExtrusionJunction& before, const Point intersection, const ExtrusionJunction& after) const { - //Average the extrusion width of the line. - //More correct would be to see where along the line the intersection occurs with a projection or something. - //But these details are so small, and this solution is so much quicker and simpler. + // Average the extrusion width of the line. + // More correct would be to see where along the line the intersection occurs with a projection or something. + // But these details are so small, and this solution is so much quicker and simpler. return ExtrusionJunction(intersection, (before.w_ + after.w_) / 2, before.perimeter_index_); } coord_t Simplify::getAreaDeviation(const Point& before, const Point& vertex, const Point& after) const { - return 0; //Fixed-width polygons don't have any deviation. + return 0; // Fixed-width polygons don't have any deviation. } coord_t Simplify::getAreaDeviation(const ExtrusionJunction& before, const ExtrusionJunction& vertex, const ExtrusionJunction& after) const @@ -151,9 +155,9 @@ coord_t Simplify::getAreaDeviation(const ExtrusionJunction& before, const Extrus const coord_t ab_length = vSize(vertex - before); const coord_t bc_length = vSize(after - vertex); const coord_t ac_length = vSize(after - before); - if(ab_length == 0 || ac_length == 0 || bc_length == 0) + if (ab_length == 0 || ac_length == 0 || bc_length == 0) { - return 0; //Either of the line segments is zero, so the deviation of one of the line segments doesn't matter (not printed). So effectively there is no deviation. + return 0; // Either of the line segments is zero, so the deviation of one of the line segments doesn't matter (not printed). So effectively there is no deviation. } const coord_t width_diff = std::max(std::abs(vertex.w_ - before.w_), std::abs(after.w_ - vertex.w_)); if (width_diff > 1) @@ -172,4 +176,4 @@ coord_t Simplify::getAreaDeviation(const ExtrusionJunction& before, const Extrus } } -} +} // namespace cura diff --git a/src/utils/SquareGrid.cpp b/src/utils/SquareGrid.cpp index 46f7a41534..29d1d9fec8 100644 --- a/src/utils/SquareGrid.cpp +++ b/src/utils/SquareGrid.cpp @@ -1,5 +1,5 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #include "utils/SquareGrid.h" @@ -8,19 +8,20 @@ using namespace cura; -SquareGrid::SquareGrid(coord_t cell_size) : cell_size_(cell_size) +SquareGrid::SquareGrid(coord_t cell_size) + : cell_size_(cell_size) { assert(cell_size > 0U); } -SquareGrid::GridPoint SquareGrid::toGridPoint(const Point &point) const +SquareGrid::GridPoint SquareGrid::toGridPoint(const Point& point) const { return Point(toGridCoord(point.X), toGridCoord(point.Y)); } -SquareGrid::grid_coord_t SquareGrid::toGridCoord(const coord_t& coord) const +SquareGrid::grid_coord_t SquareGrid::toGridCoord(const coord_t& coord) const { // This mapping via truncation results in the cells with // GridPoint.x==0 being twice as large and similarly for @@ -32,13 +33,13 @@ SquareGrid::grid_coord_t SquareGrid::toGridCoord(const coord_t& coord) const } -cura::Point SquareGrid::toLowerCorner(const GridPoint& location) const +cura::Point SquareGrid::toLowerCorner(const GridPoint& location) const { return cura::Point(toLowerCoord(location.X), toLowerCoord(location.Y)); } -cura::coord_t SquareGrid::toLowerCoord(const grid_coord_t& grid_coord) const +cura::coord_t SquareGrid::toLowerCoord(const grid_coord_t& grid_coord) const { // This mapping via truncation results in the cells with // GridPoint.x==0 being twice as large and similarly for @@ -50,13 +51,13 @@ cura::coord_t SquareGrid::toLowerCoord(const grid_coord_t& grid_coord) const } -bool SquareGrid::processLineCells(const std::pair line, const std::function& process_cell_func) +bool SquareGrid::processLineCells(const std::pair line, const std::function& process_cell_func) { return static_cast(this)->processLineCells(line, process_cell_func); } -bool SquareGrid::processLineCells(const std::pair line, const std::function& process_cell_func) const +bool SquareGrid::processLineCells(const std::pair line, const std::function& process_cell_func) const { Point start = line.first; Point end = line.second; @@ -117,13 +118,7 @@ bool SquareGrid::processLineCells(const std::pair line, const std: return false; } -bool SquareGrid::processAxisAlignedTriangle -( - const Point from, - const Point to, - bool to_the_right, - const std::function& process_cell_func -) const +bool SquareGrid::processAxisAlignedTriangle(const Point from, const Point to, bool to_the_right, const std::function& process_cell_func) const { Point a = from; Point b = to; @@ -134,12 +129,13 @@ bool SquareGrid::processAxisAlignedTriangle return processAxisAlignedTriangle(a, b, process_cell_func); } -bool SquareGrid::processAxisAlignedTriangle(const Point from, const Point to, const std::function& process_cell_func) const +bool SquareGrid::processAxisAlignedTriangle(const Point from, const Point to, const std::function& process_cell_func) const { GridPoint last; GridPoint grid_to = toGridPoint(to); - return processLineCells(std::make_pair(from, to), - [grid_to, &last, &process_cell_func, this] (const GridPoint grid_loc) + return processLineCells( + std::make_pair(from, to), + [grid_to, &last, &process_cell_func, this](const GridPoint grid_loc) { if (grid_loc.Y != last.Y) { @@ -161,16 +157,10 @@ bool SquareGrid::processAxisAlignedTriangle(const Point from, const Point to, co } last = grid_loc; return true; - } - ); + }); } -bool SquareGrid::processNearby -( - const Point &query_pt, - coord_t radius, - const std::function& process_func -) const +bool SquareGrid::processNearby(const Point& query_pt, coord_t radius, const std::function& process_func) const { const Point min_loc(query_pt.X - radius, query_pt.Y - radius); const Point max_loc(query_pt.X + radius, query_pt.Y + radius); @@ -182,8 +172,8 @@ bool SquareGrid::processNearby { for (coord_t grid_x = min_grid.X; grid_x <= max_grid.X; ++grid_x) { - GridPoint grid_pt(grid_x,grid_y); - if (!process_func(grid_pt)) + GridPoint grid_pt(grid_x, grid_y); + if (! process_func(grid_pt)) { return false; } From 3b65d4b1e5d59a20a0f1e63068bf34e89300c8bd Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Wed, 22 Nov 2023 09:40:44 +0100 Subject: [PATCH 28/48] Removed unused ClientSocket class --- CMakeLists.txt | 1 - include/utils/socket.h | 32 --------- src/utils/socket.cpp | 146 ----------------------------------------- 3 files changed, 179 deletions(-) delete mode 100644 include/utils/socket.h delete mode 100644 src/utils/socket.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 3189c3c8ce..9832338c20 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -144,7 +144,6 @@ set(engine_SRCS # Except main.cpp. src/utils/PolylineStitcher.cpp src/utils/Simplify.cpp src/utils/SVG.cpp - src/utils/socket.cpp src/utils/SquareGrid.cpp src/utils/ThreadPool.cpp src/utils/ToolpathVisualizer.cpp diff --git a/include/utils/socket.h b/include/utils/socket.h deleted file mode 100644 index 19097ccdc8..0000000000 --- a/include/utils/socket.h +++ /dev/null @@ -1,32 +0,0 @@ -//Copyright (c) 2020 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. - -#ifndef SOCKET_H -#define SOCKET_H - -#include -namespace cura -{ - -class ClientSocket -{ - int sockfd; -public: - ClientSocket(); - ~ClientSocket(); - - void connectTo(std::string host, int port); - - void sendInt32(int32_t nr); - void sendFloat32(float f); - void sendAll(const void* data, int length); - - int32_t recvInt32(); - float recvFloat32(); - void recvAll(void* data, int length); - - void close(); -}; - -}//namespace cura -#endif//SOCKET_H diff --git a/src/utils/socket.cpp b/src/utils/socket.cpp deleted file mode 100644 index 8e6c7a722e..0000000000 --- a/src/utils/socket.cpp +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright (c) 2022 Ultimaker B.V. -// CuraEngine is released under the terms of the AGPLv3 or higher - -#include -#include - -#ifdef _WIN32 -#include -#else -#include -#include -#include -#include -#include -#endif - -#include - -#include "utils/socket.h" - -namespace cura -{ - -#ifdef _WIN32 -bool wsaStartupDone = false; -#endif - -ClientSocket::ClientSocket() -{ - sockfd = -1; - -#ifdef _WIN32 - if (! wsaStartupDone) - { - WSADATA wsaData; - memset(&wsaData, 0, sizeof(WSADATA)); - // WSAStartup needs to be called on windows before sockets can be used. Request version 1.1, which is supported on windows 98 and higher. - WSAStartup(MAKEWORD(1, 1), &wsaData); - wsaStartupDone = true; - } -#endif -} - -void ClientSocket::connectTo(std::string host, int port) -{ - struct sockaddr_in serv_addr; - sockfd = socket(AF_INET, SOCK_STREAM, 0); - - memset(&serv_addr, '0', sizeof(serv_addr)); - serv_addr.sin_family = AF_INET; - serv_addr.sin_port = htons(port); - serv_addr.sin_addr.s_addr = inet_addr(host.c_str()); - - if (connect(sockfd, reinterpret_cast(&serv_addr), sizeof(serv_addr)) < 0) - { - printf("Connect to %s:%d failed\n", host.c_str(), port); - close(); - return; - } -} - -ClientSocket::~ClientSocket() -{ - close(); -} - -void ClientSocket::sendInt32(int32_t nr) -{ - sendAll(&nr, sizeof(int32_t)); -} - -void ClientSocket::sendFloat32(float f) -{ - sendAll(&f, sizeof(float)); -} - - -void ClientSocket::sendAll(const void* data, int length) -{ - if (sockfd == -1) - return; - const char* ptr = static_cast(data); - while (length > 0) - { - int n = send(sockfd, ptr, length, 0); - if (n <= 0) - { - close(); - return; - } - ptr += length; - length -= n; - } -} - -int32_t ClientSocket::recvInt32() -{ - int32_t ret = -1; - recvAll(&ret, sizeof(int32_t)); - return ret; -} - -float ClientSocket::recvFloat32() -{ - float ret = 0; - recvAll(&ret, sizeof(float)); - return ret; -} - -void ClientSocket::recvAll(void* data, int length) -{ - if (sockfd == -1) - return; - char* ptr = static_cast(data); - while (length > 0) - { - int n = recv(sockfd, ptr, length, 0); - if (n == 0) - { - close(); - return; - } - if (n < 0) - { - spdlog::error("ClientSocket::recvAll error..."); - close(); - return; - } - ptr += n; - length -= n; - } -} - -void ClientSocket::close() -{ - if (sockfd == -1) - return; -#ifdef _WIN32 - closesocket(sockfd); -#else - ::close(sockfd); -#endif - sockfd = -1; -} - -} // namespace cura \ No newline at end of file From 6c24ce4d1e718ea24ac805aa13e35e979c066e6d Mon Sep 17 00:00:00 2001 From: wawanbreton Date: Wed, 22 Nov 2023 08:45:53 +0000 Subject: [PATCH 29/48] Applied clang-format. --- include/WallToolPaths.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/WallToolPaths.h b/include/WallToolPaths.h index 70ded7d889..07b67ebfcd 100644 --- a/include/WallToolPaths.h +++ b/include/WallToolPaths.h @@ -125,7 +125,7 @@ class WallToolPaths const Polygons& outline_; // Date: Wed, 22 Nov 2023 10:00:30 +0100 Subject: [PATCH 30/48] Geometry classes naming consistency --- CMakeLists.txt | 4 +- include/BeadingStrategy/BeadingStrategy.h | 2 +- include/BoostInterface.hpp | 39 +- include/ExtruderPlan.h | 8 +- include/FffGcodeWriter.h | 2 +- include/InterlockingGenerator.h | 4 +- include/LayerPlan.h | 28 +- include/MeshGroup.h | 4 +- include/PathOrder.h | 2 +- include/PathOrderMonotonic.h | 22 +- include/PathOrderOptimizer.h | 48 +-- include/PrimeTower.h | 4 +- include/SkeletalTrapezoidation.h | 26 +- include/SkeletalTrapezoidationGraph.h | 8 +- include/SkeletalTrapezoidationJoint.h | 2 +- include/TreeSupportElement.h | 24 +- include/TreeSupportTipGenerator.h | 14 +- include/TreeSupportUtils.h | 8 +- include/communication/ArcusCommunication.h | 4 +- include/communication/CommandLine.h | 4 +- include/communication/Communication.h | 6 +- include/gcodeExport.h | 20 +- include/infill.h | 24 +- include/infill/ImageBasedDensityProvider.h | 2 +- include/infill/LightningDistanceField.h | 6 +- include/infill/LightningLayer.h | 8 +- include/infill/LightningTreeNode.h | 24 +- include/infill/NoZigZagConnectorProcessor.h | 4 +- include/infill/SierpinskiFill.h | 10 +- include/infill/SubDivCube.h | 20 +- include/infill/ZigzagConnectorProcessor.h | 14 +- include/mesh.h | 16 +- include/pathPlanning/Comb.h | 20 +- include/pathPlanning/CombPath.h | 4 +- include/pathPlanning/GCodePath.h | 4 +- include/pathPlanning/LinePolygonsCrossings.h | 14 +- include/plugins/slots.h | 2 +- include/plugins/types.h | 2 +- include/settings/ZSeamConfig.h | 6 +- include/sliceDataStorage.h | 6 +- include/slicer.h | 8 +- include/utils/AABB.h | 14 +- include/utils/AABB3D.h | 16 +- include/utils/ExtrusionJunction.h | 10 +- include/utils/ExtrusionSegment.h | 2 +- include/utils/HalfEdge.h | 2 +- include/utils/HalfEdgeNode.h | 6 +- include/utils/ListPolyIt.h | 8 +- include/utils/Matrix4x3D.h | 10 +- include/utils/MinimumSpanningTree.h | 18 +- include/utils/{IntPoint.h => Point2LL.h} | 124 +++---- include/utils/Point3D.h | 10 +- include/utils/Point3F.h | 2 +- include/utils/{Point3.h => Point3LL.h} | 58 +-- include/utils/PolygonConnector.h | 72 ++-- include/utils/PolygonsPointIndex.h | 18 +- include/utils/PolygonsSegmentIndex.h | 4 +- include/utils/PolylineStitcher.h | 2 +- include/utils/SVG.h | 28 +- include/utils/Simplify.h | 28 +- include/utils/SparseGrid.h | 18 +- include/utils/SparseLineGrid.h | 80 ++--- include/utils/SparsePointGrid.h | 8 +- include/utils/SparsePointGridInclusive.h | 16 +- include/utils/SquareGrid.h | 18 +- include/utils/VoronoiUtils.h | 20 +- include/utils/VoxelUtils.h | 18 +- include/utils/actions/smooth.h | 2 +- include/utils/linearAlg2D.h | 74 ++-- include/utils/orderOptimizer.h | 16 +- include/utils/polygon.h | 92 ++--- include/utils/polygonUtils.h | 92 ++--- src/FffGcodeWriter.cpp | 74 ++-- src/FffPolygonGenerator.cpp | 14 +- src/GCodePathConfig.cpp | 2 +- src/InterlockingGenerator.cpp | 18 +- src/LayerPlan.cpp | 132 +++---- src/LayerPlanBuffer.cpp | 6 +- src/MeshGroup.cpp | 40 +-- src/Mold.cpp | 2 +- src/PrimeTower.cpp | 16 +- src/SkeletalTrapezoidation.cpp | 146 ++++---- src/SkeletalTrapezoidationGraph.cpp | 16 +- src/SkirtBrim.cpp | 2 +- src/TopSurface.cpp | 12 +- src/TreeSupport.cpp | 52 +-- src/TreeSupportTipGenerator.cpp | 54 +-- src/bridge.cpp | 8 +- src/communication/ArcusCommunication.cpp | 18 +- .../ArcusCommunicationPrivate.cpp | 2 +- src/communication/CommandLine.cpp | 4 +- src/gcodeExport.cpp | 64 ++-- src/infill.cpp | 48 +-- src/infill/GyroidInfill.cpp | 24 +- src/infill/ImageBasedDensityProvider.cpp | 18 +- src/infill/LightningDistanceField.cpp | 18 +- src/infill/LightningLayer.cpp | 16 +- src/infill/LightningTreeNode.cpp | 46 +-- src/infill/NoZigZagConnectorProcessor.cpp | 4 +- src/infill/SierpinskiFill.cpp | 24 +- src/infill/SierpinskiFillProvider.cpp | 6 +- src/infill/SubDivCube.cpp | 32 +- src/infill/ZigzagConnectorProcessor.cpp | 8 +- src/layerPart.cpp | 2 +- src/mesh.cpp | 10 +- src/multiVolumes.cpp | 2 +- src/pathPlanning/Comb.cpp | 36 +- src/pathPlanning/LinePolygonsCrossings.cpp | 32 +- src/plugins/converters.cpp | 12 +- src/settings/ZSeamConfig.cpp | 2 +- src/sliceDataStorage.cpp | 28 +- src/slicer.cpp | 48 +-- src/support.cpp | 16 +- src/utils/AABB.cpp | 38 +- src/utils/AABB3D.cpp | 20 +- src/utils/ExtrusionJunction.cpp | 2 +- src/utils/ExtrusionSegment.cpp | 24 +- src/utils/LinearAlg2D.cpp | 46 +-- src/utils/ListPolyIt.cpp | 8 +- src/utils/{FMatrix4x3.cpp => Matrix4x3D.cpp} | 14 +- src/utils/MinimumSpanningTree.cpp | 34 +- src/utils/Point3.cpp | 76 ---- src/utils/Point3LL.cpp | 76 ++++ src/utils/PolygonConnector.cpp | 12 +- src/utils/PolygonsSegmentIndex.cpp | 4 +- src/utils/PolylineStitcher.cpp | 6 +- src/utils/SVG.cpp | 52 +-- src/utils/Simplify.cpp | 12 +- src/utils/SquareGrid.cpp | 30 +- src/utils/ToolpathVisualizer.cpp | 14 +- src/utils/VoronoiUtils.cpp | 66 ++-- src/utils/VoxelUtils.cpp | 30 +- src/utils/polygon.cpp | 166 ++++----- src/utils/polygonUtils.cpp | 338 +++++++++--------- tests/ExtruderPlanTest.cpp | 44 +-- tests/GCodeExportTest.cpp | 22 +- tests/LayerPlanTest.cpp | 52 +-- tests/PathOrderMonotonicTest.cpp | 16 +- tests/PathOrderOptimizerTest.cpp | 22 +- tests/arcus/ArcusCommunicationTest.cpp | 2 +- tests/utils/AABB3DTest.cpp | 56 +-- tests/utils/AABBTest.cpp | 92 ++--- tests/utils/IntPointTest.cpp | 16 +- tests/utils/LinearAlg2DTest.cpp | 182 +++++----- tests/utils/MinimumSpanningTreeTest.cpp | 44 +-- tests/utils/PolygonConnectorTest.cpp | 4 +- tests/utils/PolygonTest.cpp | 176 ++++----- tests/utils/PolygonUtilsTest.cpp | 166 ++++----- tests/utils/SimplifyTest.cpp | 66 ++-- tests/utils/SmoothTest.cpp | 66 ++-- tests/utils/SparseGridTest.cpp | 126 ++++--- tests/utils/StringTest.cpp | 2 +- 152 files changed, 2354 insertions(+), 2345 deletions(-) rename include/utils/{IntPoint.h => Point2LL.h} (68%) rename include/utils/{Point3.h => Point3LL.h} (68%) rename src/utils/{FMatrix4x3.cpp => Matrix4x3D.cpp} (83%) delete mode 100644 src/utils/Point3.cpp create mode 100644 src/utils/Point3LL.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 9832338c20..efe1adfbcb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -130,12 +130,12 @@ set(engine_SRCS # Except main.cpp. src/utils/ExtrusionJunction.cpp src/utils/ExtrusionLine.cpp src/utils/ExtrusionSegment.cpp - src/utils/FMatrix4x3.cpp src/utils/gettime.cpp src/utils/LinearAlg2D.cpp src/utils/ListPolyIt.cpp + src/utils/Matrix4x3D.cpp src/utils/MinimumSpanningTree.cpp - src/utils/Point3.cpp + src/utils/Point3LL.cpp src/utils/PolygonConnector.cpp src/utils/PolygonsPointIndex.cpp src/utils/PolygonsSegmentIndex.cpp diff --git a/include/BeadingStrategy/BeadingStrategy.h b/include/BeadingStrategy/BeadingStrategy.h index ab628788cd..d72645592f 100644 --- a/include/BeadingStrategy/BeadingStrategy.h +++ b/include/BeadingStrategy/BeadingStrategy.h @@ -8,7 +8,7 @@ #include "../settings/types/Angle.h" #include "../settings/types/Ratio.h" //For the wall transition threshold. -#include "../utils/IntPoint.h" +#include "../utils/Point2LL.h" namespace cura { diff --git a/include/BoostInterface.hpp b/include/BoostInterface.hpp index 52cf9e9f84..a294450a11 100644 --- a/include/BoostInterface.hpp +++ b/include/BoostInterface.hpp @@ -1,13 +1,13 @@ -//Copyright (c) 2020 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2020 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef BOOST_INTERFACE_HPP #define BOOST_INTERFACE_HPP -#include #include +#include -#include "utils/IntPoint.h" +#include "utils/Point2LL.h" #include "utils/PolygonsSegmentIndex.h" #include "utils/polygon.h" @@ -16,47 +16,48 @@ using CSegment = cura::PolygonsSegmentIndex; using CPolygon = boost::polygon::polygon_data; using CPolygonSet = std::vector; -namespace boost { -namespace polygon { +namespace boost +{ +namespace polygon +{ -template <> -struct geometry_concept +template<> +struct geometry_concept { typedef point_concept type; }; -template <> -struct point_traits +template<> +struct point_traits { typedef cura::coord_t coordinate_type; - static inline coordinate_type get( - const cura::Point& point, orientation_2d orient) + static inline coordinate_type get(const cura::Point2LL& point, orientation_2d orient) { return (orient == HORIZONTAL) ? point.X : point.Y; } }; -template <> +template<> struct geometry_concept { typedef segment_concept type; }; -template <> +template<> struct segment_traits { typedef cura::coord_t coordinate_type; - typedef cura::Point point_type; - static inline point_type get(const CSegment& CSegment, direction_1d dir) { + typedef cura::Point2LL point_type; + static inline point_type get(const CSegment& CSegment, direction_1d dir) + { return dir.to_int() ? CSegment.p() : CSegment.next().p(); } }; - -} // polygon -} // boost +} // namespace polygon +} // namespace boost #endif // BOOST_INTERFACE_HPP diff --git a/include/ExtruderPlan.h b/include/ExtruderPlan.h index ab0fef772e..17e45d0013 100644 --- a/include/ExtruderPlan.h +++ b/include/ExtruderPlan.h @@ -12,7 +12,7 @@ #include "pathPlanning/TimeMaterialEstimates.h" #include "settings/types/LayerIndex.h" #include "settings/types/Ratio.h" -#include "utils/IntPoint.h" +#include "utils/Point2LL.h" #ifdef BUILD_TESTS #include //Friend tests, so that they can inspect the privates. @@ -97,7 +97,7 @@ class ExtruderPlan * \param minTime Maximum minimum layer time for all extruders in this layer * \param time_other_extr_plans The time spent on the other extruder plans in this layer */ - void processFanSpeedForMinimalLayerTime(Point starting_position, Duration maximum_cool_min_layer_time, double time_other_extr_plans); + void processFanSpeedForMinimalLayerTime(Point2LL starting_position, Duration maximum_cool_min_layer_time, double time_other_extr_plans); /*! * Applying fan speed changes for the first layers. @@ -191,7 +191,7 @@ class ExtruderPlan /*! * @return distance between p0 and p1 as well as the time spend on the segment */ - std::pair getPointToPointTime(const Point& p0, const Point& p1, const GCodePath& path); + std::pair getPointToPointTime(const Point2LL& p0, const Point2LL& p1, const GCodePath& path); /*! * Compute naive time estimates (without accounting for slow down at corners etc.) and naive material estimates. @@ -200,7 +200,7 @@ class ExtruderPlan * \param starting_position The position the head was in before starting this layer * \return the total estimates of this layer */ - TimeMaterialEstimates computeNaiveTimeEstimates(Point starting_position); + TimeMaterialEstimates computeNaiveTimeEstimates(Point2LL starting_position); }; } // namespace cura diff --git a/include/FffGcodeWriter.h b/include/FffGcodeWriter.h index d63547692e..68c1cb9986 100644 --- a/include/FffGcodeWriter.h +++ b/include/FffGcodeWriter.h @@ -601,7 +601,7 @@ class FffGcodeWriter : public NoCopy * \param last_position The position the print head is in before going to fill the part * \return The location near where to start filling the part */ - std::optional getSeamAvoidingLocation(const Polygons& filling_part, int filling_angle, Point last_position) const; + std::optional getSeamAvoidingLocation(const Polygons& filling_part, int filling_angle, Point2LL last_position) const; /*! * Add the g-code for ironing the top surface. diff --git a/include/InterlockingGenerator.h b/include/InterlockingGenerator.h index 02bebde68b..da37b66e53 100644 --- a/include/InterlockingGenerator.h +++ b/include/InterlockingGenerator.h @@ -80,7 +80,7 @@ class InterlockingGenerator coord_t beam_width_a, coord_t beam_width_b, const PointMatrix& rotation, - Point3 cell_size, + Point3LL cell_size, coord_t beam_layer_count, DilationKernel interface_dilation, DilationKernel air_dilation, @@ -166,7 +166,7 @@ class InterlockingGenerator const VoxelUtils vu_; const PointMatrix rotation_; - const Point3 cell_size_; + const Point3LL cell_size_; const coord_t beam_layer_count_; const DilationKernel interface_dilation_; const DilationKernel air_dilation_; diff --git a/include/LayerPlan.h b/include/LayerPlan.h index aff1b0304a..d978cbdbd7 100644 --- a/include/LayerPlan.h +++ b/include/LayerPlan.h @@ -66,9 +66,9 @@ class LayerPlan : public NoCopy const bool is_raft_layer_; //!< Whether this is a layer which is part of the raft coord_t layer_thickness_; - std::vector layer_start_pos_per_extruder_; //!< The starting position of a layer for each extruder + std::vector layer_start_pos_per_extruder_; //!< The starting position of a layer for each extruder std::vector has_prime_tower_planned_per_extruder_; //!< For each extruder, whether the prime tower is planned yet or not. - std::optional last_planned_position_; //!< The last planned XY position of the print head (if known) + std::optional last_planned_position_; //!< The last planned XY position of the print head (if known) std::shared_ptr current_mesh_; //!< The mesh of the last planned move. @@ -83,7 +83,7 @@ class LayerPlan : public NoCopy size_t last_extruder_previous_layer_; //!< The last id of the extruder with which was printed in the previous layer ExtruderTrain* last_planned_extruder_; //!< The extruder for which a move has most recently been planned. - std::optional first_travel_destination_; //!< The destination of the first (travel) move (if this layer is not empty) + std::optional first_travel_destination_; //!< The destination of the first (travel) move (if this layer is not empty) bool first_travel_destination_is_inside_; //!< Whether the destination of the first planned travel move is inside a layer part std::optional> first_extrusion_acc_jerk_; //!< The acceleration and jerk rates of the first extruded move (if this layer is not empty). std::optional> next_layer_acc_jerk_; //!< If there is a next layer, the first acceleration and jerk it starts with. @@ -183,7 +183,7 @@ class LayerPlan : public NoCopy * * \warning The layer start position might be outside of the build plate! */ - Point getLastPlannedPositionOrStartingPosition() const; + Point2LL getLastPlannedPositionOrStartingPosition() const; /*! * return whether the last position planned was inside the mesh (used in combing) @@ -213,7 +213,7 @@ class LayerPlan : public NoCopy * * Returns nothing if the layer is empty and no travel move was ever made. */ - std::optional> getFirstTravelDestinationState() const; + std::optional> getFirstTravelDestinationState() const; /*! * Set whether the next destination is inside a layer part or not. @@ -283,7 +283,7 @@ class LayerPlan : public NoCopy * \param p The point to travel to. * \param force_retract Whether to force a retraction to occur. */ - GCodePath& addTravel(const Point& p, const bool force_retract = false, const coord_t z_offset = 0); + GCodePath& addTravel(const Point2LL& p, const bool force_retract = false, const coord_t z_offset = 0); /*! * Add a travel path to a certain point and retract if needed. @@ -293,7 +293,7 @@ class LayerPlan : public NoCopy * \param p The point to travel to * \param path (optional) The travel path to which to add the point \p p */ - GCodePath& addTravel_simple(const Point& p, GCodePath* path = nullptr); + GCodePath& addTravel_simple(const Point2LL& p, GCodePath* path = nullptr); /*! * Plan a prime blob at the current location. @@ -319,7 +319,7 @@ class LayerPlan : public NoCopy * \param fan_speed Fan speed override for this path. */ void addExtrusionMove( - const Point p, + const Point2LL p, const GCodePathConfig& config, const SpaceFillType space_fill_type, const Ratio& flow = 1.0_r, @@ -386,7 +386,7 @@ class LayerPlan : public NoCopy const Ratio flow_ratio = 1.0_r, bool always_retract = false, bool reverse_order = false, - const std::optional start_near_location = std::optional()); + const std::optional start_near_location = std::optional()); /*! * Add a single line that is part of a wall to the gcode. @@ -409,8 +409,8 @@ class LayerPlan : public NoCopy * the first bridge segment. */ void addWallLine( - const Point& p0, - const Point& p1, + const Point2LL& p0, + const Point2LL& p1, const Settings& settings, const GCodePathConfig& non_bridge_config, const GCodePathConfig& bridge_config, @@ -527,7 +527,7 @@ class LayerPlan : public NoCopy const bool enable_travel_optimization = false, const coord_t wipe_dist = 0, const Ratio flow_ratio = 1.0, - const std::optional near_start_location = std::optional(), + const std::optional near_start_location = std::optional(), const double fan_speed = GCodePathConfig::FAN_SPEED_DEFAULT, const bool reverse_print_direction = false, const std::unordered_multimap& order_requirements = PathOrderOptimizer::no_order_requirements_); @@ -630,7 +630,7 @@ class LayerPlan : public NoCopy while (true) { - const Point& vertex = cura::make_point(wall[curr_idx]); + const Point2LL& vertex = cura::make_point(wall[curr_idx]); if (! air_below.inside(vertex, true)) { // vertex isn't above air so it's OK to use @@ -691,7 +691,7 @@ class LayerPlan : public NoCopy * * \param starting_position The position of the print head when the first extruder plan of this layer starts */ - void processFanSpeedAndMinimalLayerTime(Point starting_position); + void processFanSpeedAndMinimalLayerTime(Point2LL starting_position); /*! * Add a travel move to the layer plan to move inside the current layer part diff --git a/include/MeshGroup.h b/include/MeshGroup.h index 51a12be124..232bf08662 100644 --- a/include/MeshGroup.h +++ b/include/MeshGroup.h @@ -24,8 +24,8 @@ class MeshGroup : public NoCopy std::vector meshes; Settings settings; - Point3 min() const; //! minimal corner of bounding box - Point3 max() const; //! maximal corner of bounding box + Point3LL min() const; //! minimal corner of bounding box + Point3LL max() const; //! maximal corner of bounding box void clear(); diff --git a/include/PathOrder.h b/include/PathOrder.h index 53b4a3543a..bd95594ee7 100644 --- a/include/PathOrder.h +++ b/include/PathOrder.h @@ -42,7 +42,7 @@ class PathOrder * The location where the nozzle is assumed to start from before printing * these parts. */ - Point start_point_; + Point2LL start_point_; /*! * Seam settings. diff --git a/include/PathOrderMonotonic.h b/include/PathOrderMonotonic.h index 267fcc7261..356eb248f5 100644 --- a/include/PathOrderMonotonic.h +++ b/include/PathOrderMonotonic.h @@ -44,7 +44,7 @@ class PathOrderMonotonic : public PathOrder using Path = PathOrdering; using PathOrder::coincident_point_distance_; - PathOrderMonotonic(const AngleRadians monotonic_direction, const coord_t max_adjacent_distance, const Point start_point) + PathOrderMonotonic(const AngleRadians monotonic_direction, const coord_t max_adjacent_distance, const Point2LL start_point) // The monotonic vector needs to rotate clockwise instead of counter-clockwise, the same as how the infill patterns are generated. : monotonic_vector_(-std::cos(monotonic_direction) * monotonic_vector_resolution_, std::sin(monotonic_direction) * monotonic_vector_resolution_) , max_adjacent_distance_(max_adjacent_distance) @@ -124,7 +124,7 @@ class PathOrderMonotonic : public PathOrder // The ``starting_lines`` set indicates possible locations to start from. Each starting line represents one "sequence", which is either a set of adjacent line segments or a // string of polylines. The ``connections`` map indicates, starting from each starting segment, the sequence of line segments to print in order. Note that for performance // reasons, the ``connections`` map will sometimes link the end of one segment to the start of the next segment. This link should be ignored. - const Point perpendicular = turn90CCW(monotonic_vector_); // To project on to detect adjacent lines. + const Point2LL perpendicular = turn90CCW(monotonic_vector_); // To project on to detect adjacent lines. std::unordered_set connected_lines; // Lines that are reachable from one of the starting lines through its connections. std::unordered_set starting_lines; // Starting points of a linearly connected segment. @@ -219,7 +219,7 @@ class PathOrderMonotonic : public PathOrder }); // Now that we have the segments of overlapping lines, and know in which order to print the segments, print segments in monotonic order. - Point current_pos = this->start_point_; + Point2LL current_pos = this->start_point_; for (Path* line : starting_lines_monotonic) { optimizeClosestStartPoint(*line, current_pos); @@ -254,7 +254,7 @@ class PathOrderMonotonic : public PathOrder * The resulting ordering will cause clusters of paths to be sorted * according to their projection on this vector. */ - Point monotonic_vector_; + Point2LL monotonic_vector_; /*! * Maximum distance at which lines are considered to be adjacent. @@ -279,7 +279,7 @@ class PathOrderMonotonic : public PathOrder * \param current_pos The last position of the nozzle before printing this * path. */ - void optimizeClosestStartPoint(Path& path, Point& current_pos) + void optimizeClosestStartPoint(Path& path, Point2LL& current_pos) { if (path.start_vertex_ == path.converted_->size()) { @@ -310,7 +310,7 @@ class PathOrderMonotonic : public PathOrder * printed. All paths in this string already have their start_vertex set * correctly. */ - std::deque findPolylineString(Path* polyline, const SparsePointGridInclusive& line_bucket_grid, const Point monotonic_vector) + std::deque findPolylineString(Path* polyline, const SparsePointGridInclusive& line_bucket_grid, const Point2LL monotonic_vector) { std::deque result; if (polyline->converted_->empty()) @@ -321,8 +321,8 @@ class PathOrderMonotonic : public PathOrder // Find the two endpoints of the polyline string, on either side. result.push_back(polyline); polyline->start_vertex_ = 0; - Point first_endpoint = polyline->converted_->front(); - Point last_endpoint = polyline->converted_->back(); + Point2LL first_endpoint = polyline->converted_->front(); + Point2LL last_endpoint = polyline->converted_->back(); std::vector> lines_before = line_bucket_grid.getNearby(first_endpoint, coincident_point_distance_); auto close_line_before = std::find_if( lines_before.begin(), @@ -403,7 +403,7 @@ class PathOrderMonotonic : public PathOrder * \param point The point to get far away from. * \return The vertex index of the endpoint that is farthest away. */ - size_t getFarthestEndpoint(Path* polyline, const Point point) + size_t getFarthestEndpoint(Path* polyline, const Point2LL point) { const coord_t front_dist = vSize2(polyline->converted_->front() - point); const coord_t back_dist = vSize2(polyline->converted_->back() - point); @@ -427,7 +427,7 @@ class PathOrderMonotonic : public PathOrder * calculated. * \param polylines The sorted list of polylines. */ - std::vector getOverlappingLines(const typename std::vector::iterator polyline_it, const Point perpendicular, const std::vector& polylines) + std::vector getOverlappingLines(const typename std::vector::iterator polyline_it, const Point2LL perpendicular, const std::vector& polylines) { const coord_t max_adjacent_projected_distance = max_adjacent_distance_ * monotonic_vector_resolution_; // How far this extends in the monotonic direction, to make sure we only go up to max_adjacent_distance in that direction. @@ -504,7 +504,7 @@ class PathOrderMonotonic : public PathOrder * struct of the bucket grid contains not only the actual path (via pointer) * but also the endpoint of it that it found to be nearby. */ - static bool canConnectToPolyline(const Point nearby_endpoint, SparsePointGridInclusiveImpl::SparsePointGridInclusiveElem found_path) + static bool canConnectToPolyline(const Point2LL nearby_endpoint, SparsePointGridInclusiveImpl::SparsePointGridInclusiveElem found_path) { return found_path.val->start_vertex_ == found_path.val->converted_->size() // Don't find any line already in the string. && vSize2(found_path.point - nearby_endpoint) < coincident_point_distance_ * coincident_point_distance_; // And only find close lines. diff --git a/include/PathOrderOptimizer.h b/include/PathOrderOptimizer.h index 71c6e92891..56212693d2 100644 --- a/include/PathOrderOptimizer.h +++ b/include/PathOrderOptimizer.h @@ -80,7 +80,7 @@ class PathOrderOptimizer * The location where the nozzle is assumed to start from before printing * these parts. */ - const Point start_point_; + const Point2LL start_point_; /*! * Seam settings. @@ -104,7 +104,7 @@ class PathOrderOptimizer * \param combing_boundary Boundary to avoid when making travel moves. */ PathOrderOptimizer( - const Point start_point, + const Point2LL start_point, const ZSeamConfig seam_config = ZSeamConfig(), const bool detect_loops = false, const Polygons* combing_boundary = nullptr, @@ -185,7 +185,7 @@ class PathOrderOptimizer } if (path.is_closed_) { - for (const Point& point : *path.converted_) + for (const Point2LL& point : *path.converted_) { line_bucket_grid.insert(point, i); // Store by index so that we can also mark them down in the `picked` vector. } @@ -296,7 +296,7 @@ class PathOrderOptimizer { std::vector optimized_order; // To store our result in. - Point current_position = start_point_; + Point2LL current_position = start_point_; std::unordered_map picked(paths_.size()); // Fixed size boolean flag for whether each path is already in the optimized vector. @@ -381,7 +381,7 @@ class PathOrderOptimizer // We used a shared visited set between runs of dfs. This is for the case when we reverse the ordering tree. // In this case two roots can share the same children nodes, but we don't want to print them twice. std::unordered_set visited; - Point current_position = start_point_; + Point2LL current_position = start_point_; std::function(const Path, const std::unordered_multimap&)> get_neighbours = [current_position, this](const Path current_node, const std::unordered_multimap& graph) @@ -536,7 +536,7 @@ class PathOrderOptimizer return reversed; } - Path findClosestPathVertices(Point start_position, std::unordered_set candidate_paths) + Path findClosestPathVertices(Point2LL start_position, std::unordered_set candidate_paths) { std::vector candidate_orderable_paths; @@ -549,7 +549,7 @@ class PathOrderOptimizer return best_candidate->vertices_; } - OrderablePath* findClosestPath(Point start_position, std::vector candidate_paths) + OrderablePath* findClosestPath(Point2LL start_position, std::vector candidate_paths) { coord_t best_distance2 = std::numeric_limits::max(); OrderablePath* best_candidate = 0; @@ -575,7 +575,7 @@ class PathOrderOptimizer path->backwards_ = path->start_vertex_ > 0; } } - const Point candidate_position = (*path->converted_)[path->start_vertex_]; + const Point2LL candidate_position = (*path->converted_)[path->start_vertex_]; coord_t distance2 = getDirectDistance(start_position, candidate_position); if (distance2 < best_distance2 && combing_boundary_) // If direct distance is longer than best combing distance, the combing distance can never be better, so only compute combing if necessary. @@ -608,7 +608,7 @@ class PathOrderOptimizer * endpoints rather than * \return An index to a vertex in that path where printing must start. */ - size_t findStartLocation(const OrderablePath& path, const Point& target_pos) + size_t findStartLocation(const OrderablePath& path, const Point2LL& target_pos) { if (! path.is_closed_) { @@ -640,7 +640,7 @@ class PathOrderOptimizer coord_t total_length = 0; for (const auto& [i, here] : **path.converted_ | ranges::views::enumerate) { - const Point& next = (*path.converted_)[(i + 1) % path.converted_->size()]; + const Point2LL& next = (*path.converted_)[(i + 1) % path.converted_->size()]; const coord_t segment_size = vSize(next - here); segments_sizes[i] = segment_size; total_length += segment_size; @@ -714,7 +714,7 @@ class PathOrderOptimizer // ties are broken by favouring points with lower x-coord // if x-coord for both points are equal then break ties by // favouring points with lower y-coord - const Point& best_point = (*path.converted_)[best_i]; + const Point2LL& best_point = (*path.converted_)[best_i]; if (std::abs(here.Y - best_point.Y) <= EPSILON ? best_point.X < here.X : best_point.Y < here.Y) { best_score = std::min(best_score, score); @@ -747,7 +747,7 @@ class PathOrderOptimizer * \param segments_sizes The pre-computed sizes of the segments * \return The position of the path a the given distance from the reference point */ - static Point findNeighbourPoint(const OrderablePath& path, int here, coord_t distance, const std::vector& segments_sizes) + static Point2LL findNeighbourPoint(const OrderablePath& path, int here, coord_t distance, const std::vector& segments_sizes) { const int direction = distance > 0 ? 1 : -1; const int size_delta = distance > 0 ? -1 : 0; @@ -764,17 +764,17 @@ class PathOrderOptimizer travelled_distance += segment_size; } - const Point& next_pos = (*path.converted_)[(here + actual_delta + path.converted_->size()) % path.converted_->size()]; + const Point2LL& next_pos = (*path.converted_)[(here + actual_delta + path.converted_->size()) % path.converted_->size()]; if (travelled_distance > distance) [[likely]] { // We have overtaken the required distance, go backward on the last segment int prev = (here + actual_delta - direction + path.converted_->size()) % path.converted_->size(); - const Point& prev_pos = (*path.converted_)[prev]; + const Point2LL& prev_pos = (*path.converted_)[prev]; - const Point vector = next_pos - prev_pos; - const Point unit_vector = (vector * 1000) / segment_size; - const Point vector_delta = unit_vector * (segment_size - (travelled_distance - distance)); + const Point2LL vector = next_pos - prev_pos; + const Point2LL unit_vector = (vector * 1000) / segment_size; + const Point2LL vector_delta = unit_vector * (segment_size - (travelled_distance - distance)); return prev_pos + vector_delta / 1000; } else @@ -800,9 +800,9 @@ class PathOrderOptimizer static double cornerAngle(const OrderablePath& path, int i, const std::vector& segments_sizes, coord_t total_length, const coord_t angle_query_distance = 1000) { const coord_t bounded_distance = std::min(angle_query_distance, total_length / 2); - const Point& here = (*path.converted_)[i]; - const Point next = findNeighbourPoint(path, i, bounded_distance, segments_sizes); - const Point previous = findNeighbourPoint(path, i, -bounded_distance, segments_sizes); + const Point2LL& here = (*path.converted_)[i]; + const Point2LL next = findNeighbourPoint(path, i, bounded_distance, segments_sizes); + const Point2LL previous = findNeighbourPoint(path, i, -bounded_distance, segments_sizes); double angle = LinearAlg2D::getAngleLeft(previous, here, next) - std::numbers::pi; @@ -816,7 +816,7 @@ class PathOrderOptimizer * \param b Another point, to compute distance to \ref a. * \return The distance between the two points. */ - coord_t getDirectDistance(const Point& a, const Point& b) const + coord_t getDirectDistance(const Point2LL& a, const Point2LL& b) const { return vSize2(a - b); } @@ -831,7 +831,7 @@ class PathOrderOptimizer * \param b Another point, to compute distance to \ref a. * \return The combing distance between the two points. */ - coord_t getCombingDistance(const Point& a, const Point& b) + coord_t getCombingDistance(const Point2LL& a, const Point2LL& b) { if (! PolygonUtils::polygonCollidesWithLineSegment(*combing_boundary_, a, b)) { @@ -858,8 +858,8 @@ class PathOrderOptimizer LinePolygonsCrossings::comb(*combing_boundary_, *combing_grid_, a, b, comb_path, rounding_error, tiny_travel_threshold, fail_on_unavoidable_obstacles); coord_t sum = 0; - Point last_point = a; - for (const Point& point : comb_path) + Point2LL last_point = a; + for (const Point2LL& point : comb_path) { sum += vSize(point - last_point); last_point = point; diff --git a/include/PrimeTower.h b/include/PrimeTower.h index 9761c12e0f..a4a31a26b9 100644 --- a/include/PrimeTower.h +++ b/include/PrimeTower.h @@ -32,9 +32,9 @@ class PrimeTower size_t extruder_count_; //!< Number of extruders bool wipe_from_middle_; //!< Whether to wipe on the inside of the hollow prime tower - Point middle_; //!< The middle of the prime tower + Point2LL middle_; //!< The middle of the prime tower - Point post_wipe_point_; //!< Location to post-wipe the unused nozzle off on + Point2LL post_wipe_point_; //!< Location to post-wipe the unused nozzle off on std::vector prime_tower_start_locations_; //!< The differernt locations where to pre-wipe the active nozzle const unsigned int number_of_prime_tower_start_locations_ = 21; //!< The required size of \ref PrimeTower::wipe_locations diff --git a/include/SkeletalTrapezoidation.h b/include/SkeletalTrapezoidation.h index b277ffd0ce..86f13f2782 100644 --- a/include/SkeletalTrapezoidation.h +++ b/include/SkeletalTrapezoidation.h @@ -167,7 +167,7 @@ class SkeletalTrapezoidation */ void constructFromPolygons(const Polygons& polys); - node_t& makeNode(vd_t::vertex_type& vd_node, Point p); //!< Get the node which the VD node maps to, or create a new mapping if there wasn't any yet. + node_t& makeNode(vd_t::vertex_type& vd_node, Point2LL p); //!< Get the node which the VD node maps to, or create a new mapping if there wasn't any yet. /*! * (Eventual) returned 'polylines per index' result (from generateToolpaths): @@ -181,13 +181,13 @@ class SkeletalTrapezoidation * \p prev_edge serves as input and output. May be null as input. */ void transferEdge( - Point from, - Point to, + Point2LL from, + Point2LL to, vd_t::edge_type& vd_edge, edge_t*& prev_edge, - Point& start_source_point, - Point& end_source_point, - const std::vector& points, + Point2LL& start_source_point, + Point2LL& end_source_point, + const std::vector& points, const std::vector& segments); /*! @@ -215,7 +215,7 @@ class SkeletalTrapezoidation * \return A number of coordinates along the edge where the edge is broken * up into discrete pieces. */ - std::vector discretize(const vd_t::edge_type& segment, const std::vector& points, const std::vector& segments); + std::vector discretize(const vd_t::edge_type& segment, const std::vector& points, const std::vector& segments); /*! * Compute the range of line segments that surround a cell of the skeletal @@ -243,11 +243,11 @@ class SkeletalTrapezoidation */ bool computePointCellRange( vd_t::cell_type& cell, - Point& start_source_point, - Point& end_source_point, + Point2LL& start_source_point, + Point2LL& end_source_point, vd_t::edge_type*& starting_vd_edge, vd_t::edge_type*& ending_vd_edge, - const std::vector& points, + const std::vector& points, const std::vector& segments); /*! @@ -276,11 +276,11 @@ class SkeletalTrapezoidation */ void computeSegmentCellRange( vd_t::cell_type& cell, - Point& start_source_point, - Point& end_source_point, + Point2LL& start_source_point, + Point2LL& end_source_point, vd_t::edge_type*& starting_vd_edge, vd_t::edge_type*& ending_vd_edge, - const std::vector& points, + const std::vector& points, const std::vector& segments); /*! diff --git a/include/SkeletalTrapezoidationGraph.h b/include/SkeletalTrapezoidationGraph.h index 4a3f9bc594..ab6e589d16 100644 --- a/include/SkeletalTrapezoidationGraph.h +++ b/include/SkeletalTrapezoidationGraph.h @@ -51,7 +51,7 @@ class STHalfEdgeNode : public HalfEdgeNode insertRib(edge_t& edge, node_t* mid_node); protected: - std::pair getSource(const edge_t& edge); + std::pair getSource(const edge_t& edge); }; } diff --git a/include/SkeletalTrapezoidationJoint.h b/include/SkeletalTrapezoidationJoint.h index 0c596b6599..daa9087cdf 100644 --- a/include/SkeletalTrapezoidationJoint.h +++ b/include/SkeletalTrapezoidationJoint.h @@ -7,7 +7,7 @@ #include // smart pointers #include "BeadingStrategy/BeadingStrategy.h" -#include "utils/IntPoint.h" +#include "utils/Point2LL.h" namespace cura { diff --git a/include/TreeSupportElement.h b/include/TreeSupportElement.h index 95bbb73eee..3fa5c3eafd 100644 --- a/include/TreeSupportElement.h +++ b/include/TreeSupportElement.h @@ -58,7 +58,7 @@ struct TreeSupportElement TreeSupportElement( coord_t distance_to_top, size_t target_height, - Point target_position, + Point2LL target_position, bool to_buildplate, bool to_model_gracious, bool use_min_xy_dist, @@ -136,7 +136,7 @@ struct TreeSupportElement , to_buildplate_(element_above->to_buildplate_) , distance_to_top_(element_above->distance_to_top_ + 1) , area_(element_above->area_) - , result_on_layer_(Point(-1, -1)) + , result_on_layer_(Point2LL(-1, -1)) , // set to invalid as we are a new node on a new layer increased_to_model_radius_(element_above->increased_to_model_radius_) , to_model_gracious_(element_above->to_model_gracious_) @@ -161,7 +161,7 @@ struct TreeSupportElement const TreeSupportElement& first, const TreeSupportElement& second, size_t next_height, - Point next_position, + Point2LL next_position, coord_t increased_to_model_radius, const std::function& getRadius, double diameter_scale_bp_radius, @@ -238,12 +238,12 @@ struct TreeSupportElement /*! * \brief The position this support elements wants to support on layer=target_height */ - Point target_position_; + Point2LL target_position_; /*! * \brief The next position this support elements wants to reach. NOTE: This is mainly a suggestion regarding direction inside the influence area. */ - Point next_position_; + Point2LL next_position_; /*! @@ -283,7 +283,7 @@ struct TreeSupportElement * \brief The resulting center point around which a circle will be drawn later. * Will be set by setPointsOnAreas */ - Point result_on_layer_ = Point(-1, -1); + Point2LL result_on_layer_ = Point2LL(-1, -1); /*! * \brief The amount of extra radius we got from merging branches that could have reached the buildplate, but merged with ones that can not. */ @@ -336,7 +336,7 @@ struct TreeSupportElement /*! * \brief The coordinates of all tips supported by this branch. */ - std::vector all_tips_; + std::vector all_tips_; /*! * \brief Whether the range of an influence area is limited @@ -356,7 +356,7 @@ struct TreeSupportElement /*! * \brief Additional locations that the tip should reach */ - std::vector additional_ovalization_targets_; + std::vector additional_ovalization_targets_; bool operator==(const TreeSupportElement& other) const @@ -397,10 +397,10 @@ struct TreeSupportElement { influence_area_limit_area_.clear(); - for (Point p : all_tips_) + for (Point2LL p : all_tips_) { Polygon circle; - for (Point corner : TreeSupportBaseCircle::getBaseCircle()) + for (Point2LL corner : TreeSupportBaseCircle::getBaseCircle()) { circle.add(p + corner * influence_area_limit_range_ / double(TreeSupportBaseCircle::base_radius)); } @@ -433,7 +433,7 @@ struct TreeSupportElement inline bool isResultOnLayerSet() const { - return result_on_layer_ != Point(-1, -1); + return result_on_layer_ != Point2LL(-1, -1); } }; @@ -446,7 +446,7 @@ struct hash { size_t operator()(const cura::TreeSupportElement& node) const { - size_t hash_node = hash()(node.target_position_); + size_t hash_node = hash()(node.target_position_); boost::hash_combine(hash_node, size_t(node.target_height_)); return hash_node; } diff --git a/include/TreeSupportTipGenerator.h b/include/TreeSupportTipGenerator.h index 13c9dc6a80..eaf85c0c3d 100644 --- a/include/TreeSupportTipGenerator.h +++ b/include/TreeSupportTipGenerator.h @@ -54,7 +54,7 @@ class TreeSupportTipGenerator TO_BP_SAFE }; - using LineInformation = std::vector>; + using LineInformation = std::vector>; /*! * \brief Converts a Polygons object representing a line into the internal format. @@ -79,7 +79,7 @@ class TreeSupportTipGenerator * \param current_layer[in] The layer on which the point lies * \return A function that can be called to evaluate a point. */ - std::function)> getEvaluatePointForNextLayerFunction(size_t current_layer); + std::function)> getEvaluatePointForNextLayerFunction(size_t current_layer); /*! * \brief Evaluates which points of some lines are not valid one layer below and which are. Assumes all points are valid on the current layer. Validity is evaluated using @@ -91,7 +91,7 @@ class TreeSupportTipGenerator */ std::pair, std::vector> splitLines( std::vector lines, - std::function)> evaluatePoint); // assumes all Points on the current line are valid + std::function)> evaluatePoint); // assumes all Points on the current line are valid /*! * \brief Ensures that every line segment is about distance in length. The resulting lines may differ from the original but all points are on the original @@ -141,13 +141,13 @@ class TreeSupportTipGenerator */ void addPointAsInfluenceArea( std::vector>& move_bounds, - std::pair p, + std::pair p, size_t dtt, LayerIndex insert_layer, size_t dont_move_until, bool roof, bool skip_ovalisation, - std::vector additional_ovalization_targets = std::vector()); + std::vector additional_ovalization_targets = std::vector()); /*! @@ -293,7 +293,7 @@ class TreeSupportTipGenerator /*! * \brief Map that saves locations of already inserted tips. Used to prevent tips far to close together from being added. */ - std::vector> already_inserted; + std::vector> already_inserted; /*! * \brief Areas that will be saved as support roof @@ -312,4 +312,4 @@ class TreeSupportTipGenerator } // namespace cura -#endif /* TREESUPPORT_H */ \ No newline at end of file +#endif /* TREESUPPORT_H */ diff --git a/include/TreeSupportUtils.h b/include/TreeSupportUtils.h index 750665ef01..ca301b6ad4 100644 --- a/include/TreeSupportUtils.h +++ b/include/TreeSupportUtils.h @@ -118,7 +118,7 @@ class TreeSupportUtils const int support_shift = roof ? 0 : support_infill_distance / 2; const size_t wall_line_count = include_walls ? (! roof ? config.support_wall_count : config.support_roof_wall_count) : 0; constexpr coord_t narrow_area_width = 0; - const Point infill_origin; + const Point2LL infill_origin; constexpr bool skip_stitching = false; constexpr bool fill_gaps = true; constexpr bool use_endpieces = true; @@ -298,11 +298,11 @@ class TreeSupportUtils for (auto line : polylines) { Polygon next_line; - for (Point p : line) + for (Point2LL p : line) { if (area.inside(p)) { - Point next_outside = p; + Point2LL next_outside = p; PolygonUtils::moveOutside(area, next_outside); if (vSize2(p - next_outside) < max_allowed_distance * max_allowed_distance) { @@ -336,7 +336,7 @@ class TreeSupportUtils { ExtrusionLine vwl_line(1, true); - for (Point p : path) + for (Point2LL p : path) { vwl_line.emplace_back(p, line_width, 1); } diff --git a/include/communication/ArcusCommunication.h b/include/communication/ArcusCommunication.h index 37855fa368..ebc687deb4 100644 --- a/include/communication/ArcusCommunication.h +++ b/include/communication/ArcusCommunication.h @@ -84,7 +84,7 @@ class ArcusCommunication : public Communication * This may indicate the starting position (or any other jump in the path). * \param position The current position to start the next line at. */ - void sendCurrentPosition(const Point& position) override; + void sendCurrentPosition(const Point2LL& position) override; /* * \brief Sends a message to indicate that all the slicing is done. @@ -130,7 +130,7 @@ class ArcusCommunication : public Communication * \param line_thickness The thickness (in the Z direction) of the line. * \param velocity The velocity of printing this polygon. */ - void sendLineTo(const PrintFeatureType& type, const Point& to, const coord_t& line_width, const coord_t& line_thickness, const Velocity& velocity) override; + void sendLineTo(const PrintFeatureType& type, const Point2LL& to, const coord_t& line_width, const coord_t& line_thickness, const Velocity& velocity) override; /* * \brief Send the sliced layer data to the front-end after the optimisation diff --git a/include/communication/CommandLine.h b/include/communication/CommandLine.h index 6190a30df4..ac7c1ccda7 100644 --- a/include/communication/CommandLine.h +++ b/include/communication/CommandLine.h @@ -59,7 +59,7 @@ class CommandLine : public Communication * The command line doesn't do anything with the current position so this is * ignored. */ - void sendCurrentPosition(const Point&) override; + void sendCurrentPosition(const Point2LL&) override; /* * \brief Indicate to the command line that we finished slicing. @@ -93,7 +93,7 @@ class CommandLine : public Communication * * The command line doesn't show any layer view so this is ignored. */ - void sendLineTo(const PrintFeatureType&, const Point&, const coord_t&, const coord_t&, const Velocity&) override; + void sendLineTo(const PrintFeatureType&, const Point2LL&, const coord_t&, const coord_t&, const Velocity&) override; /* * \brief Complete a layer to show it in layer view. diff --git a/include/communication/Communication.h b/include/communication/Communication.h index 48186c133b..0b8a509a5b 100644 --- a/include/communication/Communication.h +++ b/include/communication/Communication.h @@ -6,7 +6,7 @@ #include "settings/types/LayerIndex.h" #include "settings/types/Velocity.h" -#include "utils/IntPoint.h" +#include "utils/Point2LL.h" namespace cura { @@ -104,7 +104,7 @@ class Communication * \param line_thickness The thickness (in the Z direction) of the line. * \param velocity The velocity of printing this polygon. */ - virtual void sendLineTo(const PrintFeatureType& type, const Point& to, const coord_t& line_width, const coord_t& line_thickness, const Velocity& velocity) = 0; + virtual void sendLineTo(const PrintFeatureType& type, const Point2LL& to, const coord_t& line_width, const coord_t& line_thickness, const Velocity& velocity) = 0; /* * \brief Send the current position to visualise. @@ -112,7 +112,7 @@ class Communication * This may indicate the starting position (or any other jump in the path). * \param position The current position to start the next line at. */ - virtual void sendCurrentPosition(const Point& position) = 0; + virtual void sendCurrentPosition(const Point2LL& position) = 0; /* * \brief Set which extruder is being used for the following calls to diff --git a/include/gcodeExport.h b/include/gcodeExport.h index d4cc80c564..29582eb649 100644 --- a/include/gcodeExport.h +++ b/include/gcodeExport.h @@ -19,7 +19,7 @@ #include "sliceDataStorage.h" #include "timeEstimate.h" #include "utils/AABB3D.h" //To track the used build volume for the Griffin header. -#include "utils/IntPoint.h" +#include "utils/Point2LL.h" #include "utils/NoCopy.h" namespace cura @@ -90,7 +90,7 @@ class GCodeExport : public NoCopy double last_e_value_after_wipe_; //!< The current material amount extruded since last wipe unsigned fan_number_; // nozzle print cooling fan number - Point nozzle_offset_; //!< Cache of setting machine_nozzle_offset_[xy] + Point2LL nozzle_offset_; //!< Cache of setting machine_nozzle_offset_[xy] bool machine_firmware_retract_; //!< Cache of setting machine_firmware_retract std::deque extruded_volume_at_previous_n_retractions_; // in mm^3 @@ -127,7 +127,7 @@ class GCodeExport : public NoCopy double max_extrusion_offset_; //!< 0 to turn it off, normally 4 double extrusion_offset_factor_; //!< default 1 - Point3 current_position_; //!< The last build plate coordinates written to gcode (which might be different from actually written gcode coordinates when the extruder offset is + Point3LL current_position_; //!< The last build plate coordinates written to gcode (which might be different from actually written gcode coordinates when the extruder offset is //!< encoded in the gcode) Velocity current_speed_; //!< The current speed (F values / 60) in mm/s Acceleration current_print_acceleration_; //!< The current acceleration (in mm/s^2) used for print moves (and also for travel moves if the gcode flavor doesn't have separate @@ -249,7 +249,7 @@ class GCodeExport : public NoCopy bool getExtruderIsUsed(const int extruder_nr) const; //!< return whether the extruder has been used throughout printing all meshgroup up till now - Point getGcodePos(const coord_t x, const coord_t y, const int extruder_train) const; + Point2LL getGcodePos(const coord_t x, const coord_t y, const int extruder_train) const; void setFlavor(EGCodeFlavor flavor); EGCodeFlavor getFlavor() const; @@ -265,9 +265,9 @@ class GCodeExport : public NoCopy */ void addExtraPrimeAmount(double extra_prime_volume); - Point3 getPosition() const; + Point3LL getPosition() const; - Point getPositionXY() const; + Point2LL getPositionXY() const; int getPositionZ() const; @@ -348,7 +348,7 @@ class GCodeExport : public NoCopy * \param p location to go to * \param speed movement speed */ - void writeTravel(const Point& p, const Velocity& speed); + void writeTravel(const Point2LL& p, const Velocity& speed); /*! * Coordinates are build plate coordinates, which might be offsetted when extruder offsets are encoded in the gcode. @@ -358,7 +358,7 @@ class GCodeExport : public NoCopy * \param feature the feature that's currently printing * \param update_extrusion_offset whether to update the extrusion offset to match the current flow rate */ - void writeExtrusion(const Point& p, const Velocity& speed, double extrusion_mm3_per_mm, PrintFeatureType feature, bool update_extrusion_offset = false); + void writeExtrusion(const Point2LL& p, const Velocity& speed, double extrusion_mm3_per_mm, PrintFeatureType feature, bool update_extrusion_offset = false); /*! * Go to a X/Y location with the z-hopped Z value @@ -367,7 +367,7 @@ class GCodeExport : public NoCopy * \param p location to go to * \param speed movement speed */ - void writeTravel(const Point3& p, const Velocity& speed); + void writeTravel(const Point3LL& p, const Velocity& speed); /*! * Go to a X/Y location with the extrusion Z @@ -381,7 +381,7 @@ class GCodeExport : public NoCopy * \param feature the feature that's currently printing * \param update_extrusion_offset whether to update the extrusion offset to match the current flow rate */ - void writeExtrusion(const Point3& p, const Velocity& speed, double extrusion_mm3_per_mm, PrintFeatureType feature, bool update_extrusion_offset = false); + void writeExtrusion(const Point3LL& p, const Velocity& speed, double extrusion_mm3_per_mm, PrintFeatureType feature, bool update_extrusion_offset = false); /*! * Initialize the extruder trains. diff --git a/include/infill.h b/include/infill.h index 806d5b89b5..3f0cc19943 100644 --- a/include/infill.h +++ b/include/infill.h @@ -15,7 +15,7 @@ #include "settings/types/Angle.h" #include "utils/AABB.h" #include "utils/ExtrusionLine.h" -#include "utils/IntPoint.h" +#include "utils/Point2LL.h" #include "utils/section_type.h" namespace cura @@ -48,7 +48,7 @@ class Infill coord_t max_deviation_{}; //!< Max deviation fro the original poly when enforcing max_resolution size_t wall_line_count_{}; //!< Number of walls to generate at the boundary of the infill region, spaced \ref infill_line_width apart coord_t small_area_width_{}; //!< Maximum width of a small infill region to be filled with walls - Point infill_origin_{}; //!< origin of the infill pattern + Point2LL infill_origin_{}; //!< origin of the infill pattern bool skip_line_stitching_{ false }; //!< Whether to bypass the line stitching normally performed for polyline type infills bool fill_gaps_{ true }; //!< Whether to fill gaps in strips of infill that would be too thin to fit the infill lines. If disabled, those areas are left empty. bool connected_zigzags_{ false }; //!< (ZigZag) Whether endpieces of zigzag infill should be connected to the nearest infill line on both sides of the zigzag connector @@ -116,7 +116,7 @@ class Infill coord_t max_deviation, size_t wall_line_count, coord_t small_area_width, - Point infill_origin, + Point2LL infill_origin, bool skip_line_stitching) noexcept : pattern_{ pattern } , zig_zaggify_{ zig_zaggify } @@ -154,7 +154,7 @@ class Infill coord_t max_deviation, size_t wall_line_count, coord_t small_area_width, - Point infill_origin, + Point2LL infill_origin, bool skip_line_stitching, bool fill_gaps, bool connected_zigzags, @@ -245,7 +245,7 @@ class Infill * \param start Where the line segment starts. * \param end Where the line segment ends. */ - InfillLineSegment(const Point start, const size_t start_segment, const size_t start_polygon, const Point end, const size_t end_segment, const size_t end_polygon) + InfillLineSegment(const Point2LL start, const size_t start_segment, const size_t start_polygon, const Point2LL end, const size_t end_segment, const size_t end_polygon) : start_(start) , altered_start_(start) , start_segment_(start_segment) @@ -262,14 +262,14 @@ class Infill /*! * Where the line segment starts. */ - Point start_; + Point2LL start_; /*! * If the line-segment starts at a different point due to prevention of crossing near the boundary, it gets saved here. * * The original start-point is still used to determine ordering then, so it can't just be overwritten. */ - Point altered_start_; + Point2LL altered_start_; /*! * Which polygon line segment the start of this infill line belongs to. @@ -291,19 +291,19 @@ class Infill /*! * If the line-segment needs to prevent crossing with another line near its start, a point is inserted near the start. */ - std::optional start_bend_; + std::optional start_bend_; /*! * Where the line segment ends. */ - Point end_; + Point2LL end_; /*! * If the line-segment ends at a different point due to prevention of crossing near the boundary, it gets saved here. * * The original end-point is still used to determine ordering then, so it can't just be overwritten. */ - Point altered_end_; + Point2LL altered_end_; /*! * Which polygon line segment the end of this infill line belongs to. @@ -325,7 +325,7 @@ class Infill /*! * If the line-segment needs to prevent crossing with another line near its end, a point is inserted near the end. */ - std::optional end_bend_; + std::optional end_bend_; /*! * The previous line segment that this line segment is connected to, if @@ -610,7 +610,7 @@ class Infill * \param a The first line-segment. * \param b The second line-segment. */ - void resolveIntersection(const coord_t at_distance, const Point& intersect, Point& connect_start, Point& connect_end, InfillLineSegment* a, InfillLineSegment* b); + void resolveIntersection(const coord_t at_distance, const Point2LL& intersect, Point2LL& connect_start, Point2LL& connect_end, InfillLineSegment* a, InfillLineSegment* b); /*! * Connects infill lines together so that they form polylines. diff --git a/include/infill/ImageBasedDensityProvider.h b/include/infill/ImageBasedDensityProvider.h index cd5e8afb37..f8b215ecd7 100644 --- a/include/infill/ImageBasedDensityProvider.h +++ b/include/infill/ImageBasedDensityProvider.h @@ -23,7 +23,7 @@ class ImageBasedDensityProvider : public DensityProvider virtual double operator()(const AABB3D& aabb) const; protected: - Point3 image_size; //!< dimensions of the image. Third dimension is the amount of channels. + Point3LL image_size; //!< dimensions of the image. Third dimension is the amount of channels. unsigned char* image = nullptr; //!< image data: rows of channel data per pixel. AABB print_aabb; //!< bounding box of print coordinates in which to apply the image diff --git a/include/infill/LightningDistanceField.h b/include/infill/LightningDistanceField.h index 2dbfc00256..3624fd72c7 100644 --- a/include/infill/LightningDistanceField.h +++ b/include/infill/LightningDistanceField.h @@ -37,7 +37,7 @@ class LightningDistanceField * \return ``true`` if successful, or ``false`` if there are no more points * to consider. */ - bool tryGetNextPoint(Point* p) const; + bool tryGetNextPoint(Point2LL* p) const; /*! * Update the distance field with a newly added branch. @@ -51,7 +51,7 @@ class LightningDistanceField * \param added_leaf The location of the leaf of the newly added branch, * drawing a straight line to the node. */ - void update(const Point& to_node, const Point& added_leaf); + void update(const Point2LL& to_node, const Point2LL& added_leaf); protected: using GridPoint = SquareGrid::GridPoint; @@ -92,7 +92,7 @@ class LightningDistanceField /*! * The position of the center of this cell. */ - Point loc_; + Point2LL loc_; /*! * How far this cell is removed from the ``current_outline`` polygon, diff --git a/include/infill/LightningLayer.h b/include/infill/LightningLayer.h index 64540ea896..e9cd2b77c0 100644 --- a/include/infill/LightningLayer.h +++ b/include/infill/LightningLayer.h @@ -22,7 +22,7 @@ struct GroundingLocation { LightningTreeNodeSPtr tree_node; //!< not null if the gounding location is on a tree std::optional boundary_location; //!< in case the gounding location is on the boundary - Point p() const; + Point2LL p() const; }; /*! @@ -46,7 +46,7 @@ class LightningLayer * \param min_dist_from_boundary_for_tree If the unsupported point is closer to the boundary than this then don't consider connecting it to a tree */ GroundingLocation getBestGroundingLocation( - const Point& unsupported_location, + const Point2LL& unsupported_location, const Polygons& current_outlines, const LocToLineGrid& outline_locator, const coord_t supporting_radius, @@ -59,7 +59,7 @@ class LightningLayer * \param[out] new_root The new root node if one had been made * \return Whether a new root was added */ - bool attach(const Point& unsupported_location, const GroundingLocation& ground, LightningTreeNodeSPtr& new_child, LightningTreeNodeSPtr& new_root); + bool attach(const Point2LL& unsupported_location, const GroundingLocation& ground, LightningTreeNodeSPtr& new_child, LightningTreeNodeSPtr& new_root); void reconnectRoots( std::vector& to_be_reconnected_tree_roots, @@ -70,7 +70,7 @@ class LightningLayer Polygons convertToLines(const Polygons& limit_to_outline, const coord_t line_width) const; - coord_t getWeightedDistance(const Point& boundary_loc, const Point& unsupported_location); + coord_t getWeightedDistance(const Point2LL& boundary_loc, const Point2LL& unsupported_location); void fillLocator(SparseLightningTreeNodeGrid& tree_node_locator); }; diff --git a/include/infill/LightningTreeNode.h b/include/infill/LightningTreeNode.h index 3ab0d17b36..0ebd5503a8 100644 --- a/include/infill/LightningTreeNode.h +++ b/include/infill/LightningTreeNode.h @@ -55,13 +55,13 @@ class LightningTreeNode : public std::enable_shared_from_this * path to print. * \return The position that this node represents. */ - const Point& getLocation() const; + const Point2LL& getLocation() const; /*! * Change the position on this layer that the node represents. * \param p The position that the node needs to represent. */ - void setLocation(const Point& p); + void setLocation(const Point2LL& p); /*! * Construct a new ``LightningTreeNode`` instance and add it as a child of @@ -69,7 +69,7 @@ class LightningTreeNode : public std::enable_shared_from_this * \param p The location of the new node. * \return A shared pointer to the new node. */ - LightningTreeNodeSPtr addChild(const Point& p); + LightningTreeNodeSPtr addChild(const Point2LL& p); /*! * Add an existing ``LightningTreeNode`` as a child of this node. @@ -115,7 +115,7 @@ class LightningTreeNode : public std::enable_shared_from_this * \param visitor A function to execute for every branch in the node's sub- * tree. */ - void visitBranches(const std::function& visitor) const; + void visitBranches(const std::function& visitor) const; /*! * Execute a given function for every node in this node's sub-tree. @@ -139,7 +139,7 @@ class LightningTreeNode : public std::enable_shared_from_this * \param supporting_radius The maximum distance which can be bridged without (infill) supporting it. * \return The weighted distance. */ - coord_t getWeightedDistance(const Point& unsupported_location, const coord_t& supporting_radius) const; + coord_t getWeightedDistance(const Point2LL& unsupported_location, const coord_t& supporting_radius) const; /*! * Returns whether this node is the root of a lightning tree. It is the root @@ -166,7 +166,7 @@ class LightningTreeNode : public std::enable_shared_from_this * \param loc The specified location. * \result The branch that starts at the position closest to the location within this tree. */ - LightningTreeNodeSPtr closestNode(const Point& loc); + LightningTreeNodeSPtr closestNode(const Point2LL& loc); /*! * Returns whether the given tree node is a descendant of this node. @@ -188,7 +188,7 @@ class LightningTreeNode : public std::enable_shared_from_this * Connecting other nodes to this node indicates that a line segment should * be drawn between those two physical positions. */ - LightningTreeNode(const Point& p, const std::optional& last_grounding_location = std::nullopt); + LightningTreeNode(const Point2LL& p, const std::optional& last_grounding_location = std::nullopt); /*! * Copy this node and its entire sub-tree. @@ -205,7 +205,7 @@ class LightningTreeNode : public std::enable_shared_from_this struct RectilinearJunction { coord_t total_recti_dist; //!< rectilinear distance along the tree from the last junction above to the junction below - Point junction_loc; //!< junction location below + Point2LL junction_loc; //!< junction location below }; /*! @@ -222,7 +222,7 @@ class LightningTreeNode : public std::enable_shared_from_this * \param max_remove_colinear_dist2 Maximum distance _squared_ of the (compound) line-segment from which a co-linear point may be removed. * \return the total distance along the tree from the last junction above to the first next junction below and the location of the next junction below */ - RectilinearJunction straighten(const coord_t magnitude, const Point& junction_above, const coord_t accumulated_dist, const coord_t max_remove_colinear_dist2); + RectilinearJunction straighten(const coord_t magnitude, const Point2LL& junction_above, const coord_t accumulated_dist, const coord_t max_remove_colinear_dist2); /*! Prune the tree from the extremeties (leaf-nodes) until the pruning distance is reached. * \return The distance that has been pruned. If less than \p distance, then the whole tree was puned away. @@ -245,7 +245,7 @@ class LightningTreeNode : public std::enable_shared_from_this * * This needs to be known when roots are reconnected, so that the last (higher) layer is supported by the next one. */ - const std::optional& getLastGroundingLocation() const; + const std::optional& getLastGroundingLocation() const; protected: /*! @@ -263,11 +263,11 @@ class LightningTreeNode : public std::enable_shared_from_this void removeJunctionOverlap(Polygons& polylines, const coord_t line_width) const; bool is_root_; - Point p_; + Point2LL p_; std::weak_ptr parent_; std::vector children_; - std::optional last_grounding_location_; // last_grounding_location_; //, 8> children_; //!< pointers to this cube's eight octree children static std::vector cube_properties_per_recursion_step_; //!< precomputed array of basic properties of cubes based on recursion depth. static Ratio radius_multiplier_; //!< multiplier for the bounding radius when determining if a cube should be subdivided diff --git a/include/infill/ZigzagConnectorProcessor.h b/include/infill/ZigzagConnectorProcessor.h index 46761af97a..513ad9d8f1 100644 --- a/include/infill/ZigzagConnectorProcessor.h +++ b/include/infill/ZigzagConnectorProcessor.h @@ -129,7 +129,7 @@ class ZigzagConnectorProcessor * Handle the next vertex on the outer boundary. * \param vertex The vertex */ - virtual void registerVertex(const Point& vertex); + virtual void registerVertex(const Point2LL& vertex); /*! * Handle the next intersection between a scanline and the outer boundary. @@ -137,7 +137,7 @@ class ZigzagConnectorProcessor * \param intersection The intersection * \param scanline_index Index of the current scanline */ - virtual void registerScanlineSegmentIntersection(const Point& intersection, int scanline_index); + virtual void registerScanlineSegmentIntersection(const Point2LL& intersection, int scanline_index); /*! * Handle the end of a polygon and prepare for the next. @@ -175,7 +175,7 @@ class ZigzagConnectorProcessor * \param first_point The first of the points * \param second_point The second of the points */ - void checkAndAddZagConnectorLine(Point* first_point, Point* second_point); + void checkAndAddZagConnectorLine(Point2LL* first_point, Point2LL* second_point); /*! * Adds a Zag connector represented by the given points. The last line of the connector will not be @@ -184,7 +184,7 @@ class ZigzagConnectorProcessor * \param points All the points on this connector * \param is_endpiece Whether this connector is an end piece */ - void addZagConnector(std::vector& points, bool is_endpiece); + void addZagConnector(std::vector& points, bool is_endpiece); protected: const PointMatrix& rotation_matrix_; //!< The rotation matrix used to enforce the infill angle @@ -205,11 +205,11 @@ class ZigzagConnectorProcessor * * Because the boundary polygon may start in in the middle of a zigzag connector, */ - std::vector first_connector_; + std::vector first_connector_; /*! * The currently built up zigzag connector (not the first/last) or end piece or discarded boundary segment */ - std::vector current_connector_; + std::vector current_connector_; }; // @@ -228,7 +228,7 @@ inline void ZigzagConnectorProcessor::reset() inline void ZigzagConnectorProcessor::addPolyline(PolygonRef polyline) { result_.emplace_back(polyline); - for (Point& p : result_.back()) + for (Point2LL& p : result_.back()) { p = rotation_matrix_.unapply(p); } diff --git a/include/mesh.h b/include/mesh.h index e50b1303a7..17ba1fffcd 100644 --- a/include/mesh.h +++ b/include/mesh.h @@ -18,10 +18,10 @@ Keeps track of which faces connect to it. class MeshVertex { public: - Point3 p_; //!< location of the vertex + Point3LL p_; //!< location of the vertex std::vector connected_faces_; //!< list of the indices of connected faces - MeshVertex(Point3 p) + MeshVertex(Point3LL p) : p_(p) { connected_faces_.reserve(8); @@ -77,12 +77,12 @@ class Mesh Mesh(Settings& parent); Mesh(); - void addFace(Point3& v0, Point3& v1, Point3& v2); //!< add a face to the mesh without settings it's connected_faces. + void addFace(Point3LL& v0, Point3LL& v1, Point3LL& v2); //!< add a face to the mesh without settings it's connected_faces. void clear(); //!< clears all data void finish(); //!< complete the model : set the connected_face_index fields of the faces. - Point3 min() const; //!< min (in x,y and z) vertex of the bounding box - Point3 max() const; //!< max (in x,y and z) vertex of the bounding box + Point3LL min() const; //!< min (in x,y and z) vertex of the bounding box + Point3LL max() const; //!< max (in x,y and z) vertex of the bounding box AABB3D getAABB() const; //!< Get the axis aligned bounding box void expandXY(int64_t offset); //!< Register applied horizontal expansion in the AABB @@ -90,9 +90,9 @@ class Mesh * Offset the whole mesh (all vertices and the bounding box). * \param offset The offset byu which to offset the whole mesh. */ - void translate(Point3 offset) + void translate(Point3LL offset) { - if (offset == Point3(0, 0, 0)) + if (offset == Point3LL(0, 0, 0)) { return; } @@ -126,7 +126,7 @@ class Mesh private: mutable bool has_disconnected_faces; //!< Whether it has been logged that this mesh contains disconnected faces mutable bool has_overlapping_faces; //!< Whether it has been logged that this mesh contains overlapping faces - int findIndexOfVertex(const Point3& v); //!< find index of vertex close to the given point, or create a new vertex and return its index. + int findIndexOfVertex(const Point3LL& v); //!< find index of vertex close to the given point, or create a new vertex and return its index. /*! * Get the index of the face connected to the face with index \p notFaceIdx, via vertices \p idx0 and \p idx1. diff --git a/include/pathPlanning/Comb.h b/include/pathPlanning/Comb.h index 49757fbf1a..c766bb0820 100644 --- a/include/pathPlanning/Comb.h +++ b/include/pathPlanning/Comb.h @@ -54,8 +54,8 @@ class Comb { public: bool dest_is_inside_; //!< Whether the startPoint or endPoint is inside the inside boundary - Point in_or_mid_; //!< The point on the inside boundary, or in between the inside and outside boundary if the start/end point isn't inside the inside boudary - Point out_; //!< The point on the outside boundary + Point2LL in_or_mid_; //!< The point on the inside boundary, or in between the inside and outside boundary if the start/end point isn't inside the inside boudary + Point2LL out_; //!< The point on the outside boundary PolygonsPart dest_part_; //!< The assembled inside-boundary PolygonsPart in which the dest_point lies. (will only be initialized when Crossing::dest_is_inside holds) std::optional dest_crossing_poly_; //!< The polygon of the part in which dest_point lies, which will be crossed (often will be the outside polygon) const Polygons& boundary_inside_; //!< The inside boundary as in \ref Comb::boundary_inside @@ -71,7 +71,7 @@ class Comb * outside polygon). \param boundary_inside The boundary within which to comb. */ Crossing( - const Point& dest_point, + const Point2LL& dest_point, const bool dest_is_inside, const unsigned int dest_part_idx, const unsigned int dest_part_boundary_crossing_poly_idx, @@ -84,7 +84,7 @@ class Comb * \param partsView_inside Structured indices onto Comb::boundary_inside which shows which polygons belong to which part. * \param close_to[in] Try to get a crossing close to this point */ - void findCrossingInOrMid(const PartsView& partsView_inside, const Point close_to); + void findCrossingInOrMid(const PartsView& partsView_inside, const Point2LL close_to); /*! * Find the outside location (Combing::out) @@ -98,10 +98,10 @@ class Comb * \param comber[in] The combing calculator which has references to the * offsets and boundaries to use in combing. */ - bool findOutside(const ExtruderTrain& train, const Polygons& outside, const Point close_to, const bool fail_on_unavoidable_obstacles, Comb& comber); + bool findOutside(const ExtruderTrain& train, const Polygons& outside, const Point2LL close_to, const bool fail_on_unavoidable_obstacles, Comb& comber); private: - const Point dest_point_; //!< Either the eventual startPoint or the eventual endPoint of this combing move + const Point2LL dest_point_; //!< Either the eventual startPoint or the eventual endPoint of this combing move unsigned int dest_part_idx_; //!< The index into Comb:partsView_inside of the part in which the \p dest_point is. /*! @@ -117,7 +117,7 @@ class Comb * \return A pair of which the first is the crossing point on the inside boundary and the second the crossing point on the outside boundary */ std::shared_ptr> - findBestCrossing(const ExtruderTrain& train, const Polygons& outside, ConstPolygonRef from, const Point estimated_start, const Point estimated_end, Comb& comber); + findBestCrossing(const ExtruderTrain& train, const Polygons& outside, ConstPolygonRef from, const Point2LL estimated_start, const Point2LL estimated_end, Comb& comber); }; @@ -177,7 +177,7 @@ class Comb * \param start_inside_poly[out] The polygon in which the point has been moved * \return Whether we have moved the point inside */ - bool moveInside(Polygons& boundary_inside, bool is_inside, LocToLineGrid* inside_loc_to_line, Point& dest_point, unsigned int& start_inside_poly); + bool moveInside(Polygons& boundary_inside, bool is_inside, LocToLineGrid* inside_loc_to_line, Point2LL& dest_point, unsigned int& start_inside_poly); void moveCombPathInside(Polygons& boundary_inside, Polygons& boundary_inside_optimal, CombPath& comb_path_input, CombPath& comb_path_output); @@ -230,8 +230,8 @@ class Comb bool perform_z_hops, bool perform_z_hops_only_when_collides, const ExtruderTrain& train, - Point startPoint, - Point endPoint, + Point2LL startPoint, + Point2LL endPoint, CombPaths& combPaths, bool startInside, bool endInside, diff --git a/include/pathPlanning/CombPath.h b/include/pathPlanning/CombPath.h index fe94109540..b1811352ea 100644 --- a/include/pathPlanning/CombPath.h +++ b/include/pathPlanning/CombPath.h @@ -4,12 +4,12 @@ #ifndef PATH_PLANNING_COMB_PATH_H #define PATH_PLANNING_COMB_PATH_H -#include "../utils/IntPoint.h" +#include "../utils/Point2LL.h" namespace cura { -class CombPath : public std::vector //!< A single path either inside or outise the parts +class CombPath : public std::vector //!< A single path either inside or outise the parts { public: bool cross_boundary = false; //!< Whether the path crosses a boundary. diff --git a/include/pathPlanning/GCodePath.h b/include/pathPlanning/GCodePath.h index da4efd30aa..e94fb8edfc 100644 --- a/include/pathPlanning/GCodePath.h +++ b/include/pathPlanning/GCodePath.h @@ -12,7 +12,7 @@ #include "TimeMaterialEstimates.h" #include "settings/types/Ratio.h" #include "sliceDataStorage.h" -#include "utils/IntPoint.h" +#include "utils/Point2LL.h" namespace cura { @@ -45,7 +45,7 @@ struct GCodePath bool perform_z_hop{ false }; //!< Whether to perform a z_hop in this path, which is assumed to be a travel path. bool perform_prime{ false }; //!< Whether this path is preceded by a prime (blob) bool skip_agressive_merge_hint{ false }; //!< Wheter this path needs to skip merging if any travel paths are in between the extrusions. - std::vector points; //!< The points constituting this path. + std::vector points; //!< The points constituting this path. bool done{ false }; //!< Path is finished, no more moves should be added, and a new path should be started instead of any appending done to this one. double fan_speed{ GCodePathConfig::FAN_SPEED_DEFAULT }; //!< fan speed override for this path, value should be within range 0-100 (inclusive) and ignored otherwise TimeMaterialEstimates estimates{}; //!< Naive time and material estimates diff --git a/include/pathPlanning/LinePolygonsCrossings.h b/include/pathPlanning/LinePolygonsCrossings.h index 5fcea84545..551577ae2e 100644 --- a/include/pathPlanning/LinePolygonsCrossings.h +++ b/include/pathPlanning/LinePolygonsCrossings.h @@ -49,16 +49,16 @@ class LinePolygonsCrossings const Polygons& boundary_; //!< The boundary not to cross during combing. LocToLineGrid& loc_to_line_grid_; //!< Mapping from locations to line segments of \ref LinePolygonsCrossings::boundary - Point start_point_; //!< The start point of the scanline. - Point end_point_; //!< The end point of the scanline. + Point2LL start_point_; //!< The start point of the scanline. + Point2LL end_point_; //!< The end point of the scanline. int64_t dist_to_move_boundary_point_outside_; //!< The distance used to move outside or inside so that a boundary point doesn't intersect with the boundary anymore. Neccesary //!< due to computational rounding problems. Use negative value for insicde combing. PointMatrix transformation_matrix_; //!< The transformation which rotates everything such that the scanline is aligned with the x-axis. - Point transformed_start_point_; //!< The LinePolygonsCrossings::startPoint as transformed by Comb::transformation_matrix such that it has (roughly) the same Y as + Point2LL transformed_start_point_; //!< The LinePolygonsCrossings::startPoint as transformed by Comb::transformation_matrix such that it has (roughly) the same Y as //!< transformed_endPoint - Point transformed_end_point_; //!< The LinePolygonsCrossings::endPoint as transformed by Comb::transformation_matrix such that it has (roughly) the same Y as + Point2LL transformed_end_point_; //!< The LinePolygonsCrossings::endPoint as transformed by Comb::transformation_matrix such that it has (roughly) the same Y as //!< transformed_startPoint @@ -124,7 +124,7 @@ class LinePolygonsCrossings * \param end the end point * \param dist_to_move_boundary_point_outside Distance used to move a point from a boundary so that it doesn't intersect with it anymore. (Precision issue) */ - LinePolygonsCrossings(const Polygons& boundary, LocToLineGrid& loc_to_line_grid, Point& start, Point& end, int64_t dist_to_move_boundary_point_outside) + LinePolygonsCrossings(const Polygons& boundary, LocToLineGrid& loc_to_line_grid, Point2LL& start, Point2LL& end, int64_t dist_to_move_boundary_point_outside) : boundary_(boundary) , loc_to_line_grid_(loc_to_line_grid) , start_point_(start) @@ -147,8 +147,8 @@ class LinePolygonsCrossings static bool comb( const Polygons& boundary, LocToLineGrid& loc_to_line_grid, - Point startPoint, - Point endPoint, + Point2LL startPoint, + Point2LL endPoint, CombPath& combPath, int64_t dist_to_move_boundary_point_outside, int64_t max_comb_distance_ignored, diff --git a/include/plugins/slots.h b/include/plugins/slots.h index ed7c91a4e6..c519553114 100644 --- a/include/plugins/slots.h +++ b/include/plugins/slots.h @@ -16,7 +16,7 @@ #include "plugins/slotproxy.h" #include "plugins/types.h" #include "plugins/validator.h" -#include "utils/IntPoint.h" +#include "utils/Point2LL.h" #include "utils/Simplify.h" // TODO: Remove once the simplify slot has been removed #include "utils/polygon.h" #include "utils/types/char_range_literal.h" diff --git a/include/plugins/types.h b/include/plugins/types.h index 1585d5ff47..1a9ab54d59 100644 --- a/include/plugins/types.h +++ b/include/plugins/types.h @@ -5,7 +5,7 @@ #define PLUGINS_TYPES_H #include "cura/plugins/v0/slot_id.pb.h" -#include "utils/IntPoint.h" +#include "utils/Point2LL.h" #include "utils/polygon.h" #include diff --git a/include/settings/ZSeamConfig.h b/include/settings/ZSeamConfig.h index 1086248d59..db1fb49ef9 100644 --- a/include/settings/ZSeamConfig.h +++ b/include/settings/ZSeamConfig.h @@ -4,7 +4,7 @@ #ifndef ZSEAMCONFIG_H #define ZSEAMCONFIG_H -#include "../utils/IntPoint.h" //To store the preferred seam position. +#include "../utils/Point2LL.h" //To store the preferred seam position. #include "EnumSettings.h" //For EZSeamType and EZSeamCornerPrefType. namespace cura @@ -28,7 +28,7 @@ struct ZSeamConfig * When using a user-specified position for the seam, this is the position * that the user specified. */ - Point pos_; + Point2LL pos_; /*! * Corner preference type, if using the sharpest corner strategy. @@ -51,7 +51,7 @@ struct ZSeamConfig */ ZSeamConfig( const EZSeamType type = EZSeamType::SHORTEST, - const Point pos = Point(0, 0), + const Point2LL pos = Point2LL(0, 0), const EZSeamCornerPrefType corner_pref = EZSeamCornerPrefType::Z_SEAM_CORNER_PREF_NONE, const coord_t simplify_curvature = 0); }; diff --git a/include/sliceDataStorage.h b/include/sliceDataStorage.h index 6db1cd605a..3442f0b08d 100644 --- a/include/sliceDataStorage.h +++ b/include/sliceDataStorage.h @@ -18,7 +18,7 @@ #include "settings/types/LayerIndex.h" #include "utils/AABB.h" #include "utils/AABB3D.h" -#include "utils/IntPoint.h" +#include "utils/Point2LL.h" #include "utils/NoCopy.h" #include "utils/polygon.h" @@ -326,7 +326,7 @@ class SliceMeshStorage /*! * \return the mesh's user specified z seam hint */ - Point getZSeamHint() const; + Point2LL getZSeamHint() const; }; /*! @@ -343,7 +343,7 @@ class SliceDataStorage : public NoCopy public: size_t print_layer_count; //!< The total number of layers (except the raft and filler layers) - Point3 model_size, model_min, model_max; + Point3LL model_size, model_min, model_max; AABB3D machine_size; //!< The bounding box with the width, height and depth of the printer. std::vector> meshes; diff --git a/include/slicer.h b/include/slicer.h index 789da58a8c..37cd45f122 100644 --- a/include/slicer.h +++ b/include/slicer.h @@ -25,7 +25,7 @@ class MeshVertex; class SlicerSegment { public: - Point start, end; + Point2LL start, end; int faceIndex = -1; // The index of the other face connected via the edge that created end int endOtherFaceIdx = -1; @@ -115,9 +115,9 @@ class SlicerLayer */ void stitch(Polygons& open_polylines); - std::optional findPolygonGapCloser(Point ip0, Point ip1); + std::optional findPolygonGapCloser(Point2LL ip0, Point2LL ip1); - std::optional findPolygonPointClosestTo(Point input); + std::optional findPolygonPointClosestTo(Point2LL input); /*! * Try to close up polylines into polygons while they have large gaps in them. @@ -513,7 +513,7 @@ class Slicer * \param z The Z coordinate of the layer to intersect with. * \return A slicer segment. */ - static SlicerSegment project2D(const Point3& p0, const Point3& p1, const Point3& p2, const coord_t z); + static SlicerSegment project2D(const Point3LL& p0, const Point3LL& p1, const Point3LL& p2, const coord_t z); /*! Creates an array of "z bounding boxes" for each face. * \param[in] mesh The mesh which is analyzed. diff --git a/include/utils/AABB.h b/include/utils/AABB.h index 988eb3b7ff..b69d8c2c57 100644 --- a/include/utils/AABB.h +++ b/include/utils/AABB.h @@ -4,7 +4,7 @@ #ifndef UTILS_AABB_H #define UTILS_AABB_H -#include "IntPoint.h" +#include "Point2LL.h" namespace cura { @@ -17,10 +17,10 @@ class Polygons; class AABB { public: - Point min_, max_; + Point2LL min_, max_; AABB(); //!< initializes with invalid min and max - AABB(const Point& min, const Point& max); //!< initializes with given min and max + AABB(const Point2LL& min, const Point2LL& max); //!< initializes with given min and max AABB(const Polygons& polys); //!< Computes the boundary box for the given polygons AABB(ConstPolygonRef poly); //!< Computes the boundary box for the given polygons @@ -33,7 +33,7 @@ class AABB * \return ``true`` if the bounding box contains the specified point, or * ``false`` otherwise. */ - bool contains(const Point& point) const; + bool contains(const Point2LL& point) const; /*! * Whether this bounding box contains the other bounding box. @@ -49,12 +49,12 @@ class AABB /*! * Get the middle of the bounding box. */ - Point getMiddle() const; + Point2LL getMiddle() const; /*! * If point outside of bounding box: positive distance-squared to the bounding box edges, otherwise negative. */ - coord_t distanceSquared(const Point& p) const; + coord_t distanceSquared(const Point2LL& p) const; /*! * If other aabb outside of this bounding box: positive distance-squared to the bounding box edges, @@ -79,7 +79,7 @@ class AABB * * \param point The point to include in the bounding box. */ - void include(Point point); + void include(Point2LL point); /*! * \brief Includes the specified bounding box in the bounding box. diff --git a/include/utils/AABB3D.h b/include/utils/AABB3D.h index 68911b2f87..48142d24ce 100644 --- a/include/utils/AABB3D.h +++ b/include/utils/AABB3D.h @@ -4,7 +4,7 @@ #ifndef UTILS_AABB3D_H #define UTILS_AABB3D_H -#include "IntPoint.h" +#include "Point2LL.h" #include "utils/AABB.h" namespace cura @@ -15,8 +15,8 @@ An Axis Aligned Bounding Box. Has a min and max vector, representing minimal and */ struct AABB3D { - Point3 min_; //!< The minimal coordinates in x, y and z direction - Point3 max_; //!< The maximal coordinates in x, y and z direction + Point3LL min_; //!< The minimal coordinates in x, y and z direction + Point3LL max_; //!< The maximal coordinates in x, y and z direction /*! * Create an AABB3D with coordinates at the numeric limits. @@ -26,12 +26,12 @@ struct AABB3D /*! * Create an AABB3D with given limits */ - AABB3D(Point3 min, Point3 max); + AABB3D(Point3LL min, Point3LL max); /*! * Get the middle of the bounding box */ - Point3 getMiddle() const; + Point3LL getMiddle() const; /*! * Creates a 2D version of this bounding box by leaving away the Z @@ -56,7 +56,7 @@ struct AABB3D * \param p The point to include with the bounding box. * \return this object (which has changed) */ - AABB3D include(Point3 p); + AABB3D include(Point3LL p); /*! * Expand the AABB3D to include the bounding box \p aabb. @@ -79,14 +79,14 @@ struct AABB3D * \param offset The offset with which to offset the AABB3D. * \return this object (which has changed) */ - AABB3D translate(Point3 offset); + AABB3D translate(Point3LL offset); /*! * Offset the coordinates of the bounding box. * \param offset The offset with which to offset the AABB3D. * \return this object (which has changed) */ - AABB3D translate(Point offset); + AABB3D translate(Point2LL offset); /*! * Offset the bounding box in the horizontal direction; outward or inward. diff --git a/include/utils/ExtrusionJunction.h b/include/utils/ExtrusionJunction.h index 71cd71a636..66cb46c9cc 100644 --- a/include/utils/ExtrusionJunction.h +++ b/include/utils/ExtrusionJunction.h @@ -5,7 +5,7 @@ #ifndef UTILS_EXTRUSION_JUNCTION_H #define UTILS_EXTRUSION_JUNCTION_H -#include "IntPoint.h" +#include "Point2LL.h" namespace cura { @@ -22,7 +22,7 @@ struct ExtrusionJunction * The position of the centreline of the path when it reaches this junction. * This is the position that should end up in the g-code eventually. */ - Point p_; + Point2LL p_; /*! * The width of the extruded path at this junction. @@ -37,18 +37,18 @@ struct ExtrusionJunction */ size_t perimeter_index_; - ExtrusionJunction(const Point p, const coord_t w, const coord_t perimeter_index); + ExtrusionJunction(const Point2LL p, const coord_t w, const coord_t perimeter_index); bool operator==(const ExtrusionJunction& other) const; }; -inline Point operator-(const ExtrusionJunction& a, const ExtrusionJunction& b) +inline Point2LL operator-(const ExtrusionJunction& a, const ExtrusionJunction& b) { return a.p_ - b.p_; } // Identity function, used to be able to make templated algorithms that do their operations on 'point-like' input. -inline const Point& make_point(const ExtrusionJunction& ej) +inline const Point2LL& make_point(const ExtrusionJunction& ej) { return ej.p_; } diff --git a/include/utils/ExtrusionSegment.h b/include/utils/ExtrusionSegment.h index 318c2e25cf..99430f8789 100644 --- a/include/utils/ExtrusionSegment.h +++ b/include/utils/ExtrusionSegment.h @@ -8,7 +8,7 @@ #include #include "ExtrusionJunction.h" -#include "IntPoint.h" +#include "Point2LL.h" #include "polygon.h" #include "polygonUtils.h" diff --git a/include/utils/HalfEdge.h b/include/utils/HalfEdge.h index 34df6f2a48..ae8736f589 100644 --- a/include/utils/HalfEdge.h +++ b/include/utils/HalfEdge.h @@ -7,7 +7,7 @@ #include #include -#include "../utils/IntPoint.h" +#include "../utils/Point2LL.h" #include "Coord_t.h" namespace cura diff --git a/include/utils/HalfEdgeNode.h b/include/utils/HalfEdgeNode.h index 3da47ba7fe..163b45d07b 100644 --- a/include/utils/HalfEdgeNode.h +++ b/include/utils/HalfEdgeNode.h @@ -6,7 +6,7 @@ #include -#include "IntPoint.h" +#include "Point2LL.h" namespace cura { @@ -19,10 +19,10 @@ class HalfEdgeNode public: node_data_t data_; - Point p_; + Point2LL p_; edge_t* incident_edge_ = nullptr; - HalfEdgeNode(node_data_t data, Point p) + HalfEdgeNode(node_data_t data, Point2LL p) : data_(data) , p_(p) { diff --git a/include/utils/ListPolyIt.h b/include/utils/ListPolyIt.h index 0af99f0e7d..0847305bdf 100644 --- a/include/utils/ListPolyIt.h +++ b/include/utils/ListPolyIt.h @@ -7,7 +7,7 @@ #include #include -#include "IntPoint.h" +#include "Point2LL.h" #include "polygon.h" @@ -32,7 +32,7 @@ class ListPolyIt { } - Point& p() const + Point2LL& p() const { return *it_; } @@ -144,7 +144,7 @@ class ListPolyIt * \param to_insert The point to insert into the ListPolygon in between \p before and \p after * \return Iterator to the newly inserted point, or \p before or \p after in case to_insert was already in the polygon */ - static ListPolyIt insertPointNonDuplicate(const ListPolyIt before, const ListPolyIt after, const Point to_insert); + static ListPolyIt insertPointNonDuplicate(const ListPolyIt before, const ListPolyIt after, const Point2LL to_insert); private: ListPolygon* poly_; //!< The polygon @@ -164,7 +164,7 @@ struct hash { size_t operator()(const cura::ListPolyIt& lpi) const { - return std::hash()(lpi.p()); + return std::hash()(lpi.p()); } }; } // namespace std diff --git a/include/utils/Matrix4x3D.h b/include/utils/Matrix4x3D.h index b4b9aed3cc..9945ee9f30 100644 --- a/include/utils/Matrix4x3D.h +++ b/include/utils/Matrix4x3D.h @@ -10,7 +10,7 @@ namespace cura { class Point3D; -class Point3; +class Point3LL; /*! * A 4x3 affine transformation matrix. @@ -28,8 +28,8 @@ class Matrix4x3D * is reduced, all coordinates will go towards this origin. If the scale is * increased, all coordinates will go away from this origin. */ - static Matrix4x3D scale(const Ratio scale, const Point3 origin); - static Matrix4x3D scale(const Ratio scale_x, const Ratio scale_y, const Ratio scale_z, const Point3 origin); + static Matrix4x3D scale(const Ratio scale, const Point3LL origin); + static Matrix4x3D scale(const Ratio scale_x, const Ratio scale_y, const Ratio scale_z, const Point3LL origin); /*! * The matrix data, row-endian. @@ -51,14 +51,14 @@ class Matrix4x3D * \param p The coordinate to transform. * \return A transformed coordinate. */ - Point3 apply(const Point3D& p) const; + Point3LL apply(const Point3D& p) const; /*! * Apply this transformation to a coordinate. * \param p The coordinate to transform. * \return A transformed coordinate. */ - Point3 apply(const Point3& p) const; + Point3LL apply(const Point3LL& p) const; }; } // namespace cura diff --git a/include/utils/MinimumSpanningTree.h b/include/utils/MinimumSpanningTree.h index a1b7866664..9e0f53d4cf 100644 --- a/include/utils/MinimumSpanningTree.h +++ b/include/utils/MinimumSpanningTree.h @@ -8,7 +8,7 @@ #include #include -#include "IntPoint.h" +#include "Point2LL.h" namespace cura { @@ -30,40 +30,40 @@ class MinimumSpanningTree /** * The point at which this edge starts. */ - const Point start; + const Point2LL start; /** * The point at which this edge ends. */ - const Point end; + const Point2LL end; }; public: MinimumSpanningTree() = default; /*! * \brief Constructs a minimum spanning tree that spans all given vertices. */ - MinimumSpanningTree(std::vector vertices); + MinimumSpanningTree(std::vector vertices); /*! * \brief Gets the nodes that are adjacent to the specified node. * \return A list of nodes that are adjacent. */ - std::vector adjacentNodes(Point node) const; + std::vector adjacentNodes(Point2LL node) const; /*! * \brief Gets the leaves of the tree. * \return A list of nodes that are all leaves of the tree. */ - std::vector leaves() const; + std::vector leaves() const; /*! * \brief Gets all vertices of the tree. * \return A list of vertices of the tree. */ - std::vector vertices() const; + std::vector vertices() const; private: - using AdjacencyGraph_t = std::unordered_map>; + using AdjacencyGraph_t = std::unordered_map>; AdjacencyGraph_t adjacency_graph; /*! @@ -73,7 +73,7 @@ class MinimumSpanningTree * \param vertices The vertices to span. * \return An adjacency graph with for each point one or more edges. */ - AdjacencyGraph_t prim(std::vector vertices) const; + AdjacencyGraph_t prim(std::vector vertices) const; }; } diff --git a/include/utils/IntPoint.h b/include/utils/Point2LL.h similarity index 68% rename from include/utils/IntPoint.h rename to include/utils/Point2LL.h index 6b35405074..76f8df39b1 100644 --- a/include/utils/IntPoint.h +++ b/include/utils/Point2LL.h @@ -19,7 +19,7 @@ Integer points are used to avoid floating point rounding errors, and because Cli #include #include "../utils/math.h" // for PI. Use relative path to avoid pulling -#include "Point3.h" //For applying Point3Matrices. +#include "Point3LL.h" //For applying Point3Matrices. #ifdef __GNUC__ #define DEPRECATED(func) func __attribute__((deprecated)) @@ -35,67 +35,67 @@ namespace cura { /* 64bit Points are used mostly throughout the code, these are the 2D points from ClipperLib */ -typedef ClipperLib::IntPoint Point; +typedef ClipperLib::IntPoint Point2LL; #define POINT_MIN std::numeric_limits::min() #define POINT_MAX std::numeric_limits::max() -static Point no_point(std::numeric_limits::min(), std::numeric_limits::min()); +static Point2LL no_point(std::numeric_limits::min(), std::numeric_limits::min()); /* Extra operators to make it easier to do math with the 64bit Point objects */ -INLINE Point operator-(const Point& p0) +INLINE Point2LL operator-(const Point2LL& p0) { - return Point(-p0.X, -p0.Y); + return Point2LL(-p0.X, -p0.Y); } -INLINE Point operator+(const Point& p0, const Point& p1) +INLINE Point2LL operator+(const Point2LL& p0, const Point2LL& p1) { - return Point(p0.X + p1.X, p0.Y + p1.Y); + return Point2LL(p0.X + p1.X, p0.Y + p1.Y); } -INLINE Point operator-(const Point& p0, const Point& p1) +INLINE Point2LL operator-(const Point2LL& p0, const Point2LL& p1) { - return Point(p0.X - p1.X, p0.Y - p1.Y); + return Point2LL(p0.X - p1.X, p0.Y - p1.Y); } -INLINE Point operator*(const Point& p0, const coord_t i) +INLINE Point2LL operator*(const Point2LL& p0, const coord_t i) { - return Point(p0.X * i, p0.Y * i); + return Point2LL(p0.X * i, p0.Y * i); } template::value, T>::type> // Use only for numeric types. -INLINE Point operator*(const Point& p0, const T i) +INLINE Point2LL operator*(const Point2LL& p0, const T i) { - return Point(std::llrint(static_cast(p0.X) * i), std::llrint(static_cast(p0.Y) * i)); + return Point2LL(std::llrint(static_cast(p0.X) * i), std::llrint(static_cast(p0.Y) * i)); } template::value, T>::type> // Use only for numeric types. -INLINE Point operator*(const T i, const Point& p0) +INLINE Point2LL operator*(const T i, const Point2LL& p0) { return p0 * i; } -INLINE Point operator/(const Point& p0, const coord_t i) +INLINE Point2LL operator/(const Point2LL& p0, const coord_t i) { - return Point(p0.X / i, p0.Y / i); + return Point2LL(p0.X / i, p0.Y / i); } -INLINE Point operator/(const Point& p0, const Point& p1) +INLINE Point2LL operator/(const Point2LL& p0, const Point2LL& p1) { - return Point(p0.X / p1.X, p0.Y / p1.Y); + return Point2LL(p0.X / p1.X, p0.Y / p1.Y); } -INLINE Point operator%(const Point& p0, const coord_t i) +INLINE Point2LL operator%(const Point2LL& p0, const coord_t i) { - return Point(p0.X % i, p0.Y % i); + return Point2LL(p0.X % i, p0.Y % i); } -INLINE Point& operator+=(Point& p0, const Point& p1) +INLINE Point2LL& operator+=(Point2LL& p0, const Point2LL& p1) { p0.X += p1.X; p0.Y += p1.Y; return p0; } -INLINE Point& operator-=(Point& p0, const Point& p1) +INLINE Point2LL& operator-=(Point2LL& p0, const Point2LL& p1) { p0.X -= p1.X; p0.Y -= p1.Y; return p0; } -INLINE bool operator<(const Point& p0, const Point& p1) +INLINE bool operator<(const Point2LL& p0, const Point2LL& p1) { return p0.X < p1.X || (p0.X == p1.X && p0.Y < p1.Y); } @@ -112,16 +112,16 @@ INLINE bool operator<(const Point& p0, const Point& p1) // INLINE bool operator==(const Point& p0, const Point& p1) { return p0.X==p1.X&&p0.Y==p1.Y; } // INLINE bool operator!=(const Point& p0, const Point& p1) { return p0.X!=p1.X||p0.Y!=p1.Y; } -INLINE coord_t vSize2(const Point& p0) +INLINE coord_t vSize2(const Point2LL& p0) { return p0.X * p0.X + p0.Y * p0.Y; } -INLINE double vSize2f(const Point& p0) +INLINE double vSize2f(const Point2LL& p0) { return static_cast(p0.X) * static_cast(p0.X) + static_cast(p0.Y) * static_cast(p0.Y); } -INLINE bool shorterThen(const Point& p0, const coord_t len) +INLINE bool shorterThen(const Point2LL& p0, const coord_t len) { if (p0.X > len || p0.X < -len) { @@ -134,56 +134,56 @@ INLINE bool shorterThen(const Point& p0, const coord_t len) return vSize2(p0) <= len * len; } -INLINE bool shorterThan(const Point& p0, const coord_t len) +INLINE bool shorterThan(const Point2LL& p0, const coord_t len) { return shorterThen(p0, len); } -INLINE coord_t vSize(const Point& p0) +INLINE coord_t vSize(const Point2LL& p0) { return std::llrint(sqrt(static_cast(vSize2(p0)))); } -INLINE double vSizeMM(const Point& p0) +INLINE double vSizeMM(const Point2LL& p0) { double fx = INT2MM(p0.X); double fy = INT2MM(p0.Y); return sqrt(fx * fx + fy * fy); } -INLINE Point normal(const Point& p0, coord_t len) +INLINE Point2LL normal(const Point2LL& p0, coord_t len) { coord_t _len = vSize(p0); if (_len < 1) - return Point(len, 0); + return Point2LL(len, 0); return p0 * len / _len; } -INLINE Point turn90CCW(const Point& p0) +INLINE Point2LL turn90CCW(const Point2LL& p0) { - return Point(-p0.Y, p0.X); + return Point2LL(-p0.Y, p0.X); } -INLINE Point rotate(const Point& p0, double angle) +INLINE Point2LL rotate(const Point2LL& p0, double angle) { const double cos_component = std::cos(angle); const double sin_component = std::sin(angle); const double x = static_cast(p0.X); const double y = static_cast(p0.Y); - return Point(std::llrint(cos_component * x - sin_component * y), std::llrint(sin_component * x + cos_component * y)); + return Point2LL(std::llrint(cos_component * x - sin_component * y), std::llrint(sin_component * x + cos_component * y)); } -INLINE coord_t dot(const Point& p0, const Point& p1) +INLINE coord_t dot(const Point2LL& p0, const Point2LL& p1) { return p0.X * p1.X + p0.Y * p1.Y; } -INLINE coord_t cross(const Point& p0, const Point& p1) +INLINE coord_t cross(const Point2LL& p0, const Point2LL& p1) { return p0.X * p1.Y - p0.Y * p1.X; } -INLINE int angle(const Point& p) +INLINE int angle(const Point2LL& p) { double angle = std::atan2(p.X, p.Y) / std::numbers::pi * 180.0; if (angle < 0.0) @@ -192,7 +192,7 @@ INLINE int angle(const Point& p) } // Identity function, used to be able to make templated algorithms where the input is sometimes points, sometimes things that contain or can be converted to points. -INLINE const Point& make_point(const Point& p) +INLINE const Point2LL& make_point(const Point2LL& p) { return p; } @@ -202,9 +202,9 @@ INLINE const Point& make_point(const Point& p) namespace std { template<> -struct hash +struct hash { - size_t operator()(const cura::Point& pp) const + size_t operator()(const cura::Point2LL& pp) const { static int prime = 31; int result = 89; @@ -240,7 +240,7 @@ class PointMatrix matrix[3] = matrix[0]; } - PointMatrix(const Point p) + PointMatrix(const Point2LL p) { matrix[0] = static_cast(p.X); matrix[1] = static_cast(p.Y); @@ -259,21 +259,21 @@ class PointMatrix return ret; } - Point apply(const Point p) const + Point2LL apply(const Point2LL p) const { const double x = static_cast(p.X); const double y = static_cast(p.Y); - return Point(std::llrint(x * matrix[0] + y * matrix[1]), std::llrint(x * matrix[2] + y * matrix[3])); + return Point2LL(std::llrint(x * matrix[0] + y * matrix[1]), std::llrint(x * matrix[2] + y * matrix[3])); } /*! * \warning only works on a rotation matrix! Output is incorrect for other types of matrix */ - Point unapply(const Point p) const + Point2LL unapply(const Point2LL p) const { const double x = static_cast(p.X); const double y = static_cast(p.Y); - return Point(std::llrint(x * matrix[0] + y * matrix[2]), std::llrint(x * matrix[1] + y * matrix[3])); + return Point2LL(std::llrint(x * matrix[0] + y * matrix[2]), std::llrint(x * matrix[1] + y * matrix[3])); } PointMatrix inverse() const @@ -323,12 +323,12 @@ class Point3Matrix matrix[8] = 1; } - Point3 apply(const Point3 p) const + Point3LL apply(const Point3LL p) const { const double x = static_cast(p.x_); const double y = static_cast(p.y_); const double z = static_cast(p.z_); - return Point3( + return Point3LL( std::llrint(x * matrix[0] + y * matrix[1] + z * matrix[2]), std::llrint(x * matrix[3] + y * matrix[4] + z * matrix[5]), std::llrint(x * matrix[6] + y * matrix[7] + z * matrix[8])); @@ -337,13 +337,13 @@ class Point3Matrix /*! * Apply matrix to vector as homogeneous coordinates. */ - Point apply(const Point p) const + Point2LL apply(const Point2LL p) const { - Point3 result = apply(Point3(p.X, p.Y, 1)); - return Point(result.x_ / result.z_, result.y_ / result.z_); + Point3LL result = apply(Point3LL(p.X, p.Y, 1)); + return Point2LL(result.x_ / result.z_, result.y_ / result.z_); } - static Point3Matrix translate(const Point p) + static Point3Matrix translate(const Point2LL p) { Point3Matrix ret; // uniform matrix ret.matrix[2] = static_cast(p.X); @@ -370,37 +370,37 @@ class Point3Matrix }; -inline Point3 operator+(const Point3& p3, const Point& p2) +inline Point3LL operator+(const Point3LL& p3, const Point2LL& p2) { - return Point3(p3.x_ + p2.X, p3.y_ + p2.Y, p3.z_); + return Point3LL(p3.x_ + p2.X, p3.y_ + p2.Y, p3.z_); } -inline Point3& operator+=(Point3& p3, const Point& p2) +inline Point3LL& operator+=(Point3LL& p3, const Point2LL& p2) { p3.x_ += p2.X; p3.y_ += p2.Y; return p3; } -inline Point operator+(const Point& p2, const Point3& p3) +inline Point2LL operator+(const Point2LL& p2, const Point3LL& p3) { - return Point(p3.x_ + p2.X, p3.y_ + p2.Y); + return Point2LL(p3.x_ + p2.X, p3.y_ + p2.Y); } -inline Point3 operator-(const Point3& p3, const Point& p2) +inline Point3LL operator-(const Point3LL& p3, const Point2LL& p2) { - return Point3(p3.x_ - p2.X, p3.y_ - p2.Y, p3.z_); + return Point3LL(p3.x_ - p2.X, p3.y_ - p2.Y, p3.z_); } -inline Point3& operator-=(Point3& p3, const Point& p2) +inline Point3LL& operator-=(Point3LL& p3, const Point2LL& p2) { p3.x_ -= p2.X; p3.y_ -= p2.Y; return p3; } -inline Point operator-(const Point& p2, const Point3& p3) +inline Point2LL operator-(const Point2LL& p2, const Point3LL& p3) { - return Point(p2.X - p3.x_, p2.Y - p3.y_); + return Point2LL(p2.X - p3.x_, p2.Y - p3.y_); } } // namespace cura diff --git a/include/utils/Point3D.h b/include/utils/Point3D.h index c44f6e79e6..8405d03c4d 100644 --- a/include/utils/Point3D.h +++ b/include/utils/Point3D.h @@ -7,7 +7,7 @@ #include #include -#include "IntPoint.h" +#include "Point2LL.h" namespace cura @@ -33,7 +33,7 @@ class Point3D { } - Point3D(const Point3& p) + Point3D(const Point3LL& p) : x_(static_cast(p.x_) * .001) , y_(static_cast(p.y_) * .001) , z_(static_cast(p.z_) * .001) @@ -122,14 +122,14 @@ class Point3D return Point3D(y_ * p.z_ - z_ * p.y_, z_ * p.x_ - x_ * p.z_, x_ * p.y_ - y_ * p.x_); } - static Point3D cross(const Point3& a, const Point3& b) + static Point3D cross(const Point3LL& a, const Point3LL& b) { return Point3D(a).cross(Point3D(b)); } - Point3 toPoint3() + Point3LL toPoint3() { - return Point3(MM2INT(x_), MM2INT(y_), MM2INT(z_)); + return Point3LL(MM2INT(x_), MM2INT(y_), MM2INT(z_)); } }; diff --git a/include/utils/Point3F.h b/include/utils/Point3F.h index 0772521240..44262ad2b0 100644 --- a/include/utils/Point3F.h +++ b/include/utils/Point3F.h @@ -7,7 +7,7 @@ #include #include -#include "IntPoint.h" +#include "Point2LL.h" #include "Point3D.h" diff --git a/include/utils/Point3.h b/include/utils/Point3LL.h similarity index 68% rename from include/utils/Point3.h rename to include/utils/Point3LL.h index 54c3819e22..c992bcb3d5 100644 --- a/include/utils/Point3.h +++ b/include/utils/Point3LL.h @@ -17,47 +17,47 @@ namespace cura { -class Point3 +class Point3LL { public: coord_t x_, y_, z_; - Point3() + Point3LL() { } - Point3(const coord_t x, const coord_t y, const coord_t z) + Point3LL(const coord_t x, const coord_t y, const coord_t z) : x_(x) , y_(y) , z_(z) { } - Point3 operator+(const Point3& p) const; - Point3 operator-() const; - Point3 operator-(const Point3& p) const; - Point3 operator*(const Point3& p) const; //!< Element-wise multiplication. For dot product, use .dot()! - Point3 operator/(const Point3& p) const; + Point3LL operator+(const Point3LL& p) const; + Point3LL operator-() const; + Point3LL operator-(const Point3LL& p) const; + Point3LL operator*(const Point3LL& p) const; //!< Element-wise multiplication. For dot product, use .dot()! + Point3LL operator/(const Point3LL& p) const; template::value, num_t>::type> - Point3 operator*(const num_t i) const + Point3LL operator*(const num_t i) const { - return Point3(std::llround(static_cast(x_) * i), std::llround(static_cast(y_) * i), std::llround(static_cast(z_) * i)); + return Point3LL(std::llround(static_cast(x_) * i), std::llround(static_cast(y_) * i), std::llround(static_cast(z_) * i)); } template::value, num_t>::type> - Point3 operator/(const num_t i) const + Point3LL operator/(const num_t i) const { - return Point3(x_ / i, y_ / i, z_ / i); + return Point3LL(x_ / i, y_ / i, z_ / i); } template::value, num_t>::type> - Point3 operator%(const num_t i) const + Point3LL operator%(const num_t i) const { - return Point3(x_ % i, y_ % i, z_ % i); + return Point3LL(x_ % i, y_ % i, z_ % i); } - Point3& operator+=(const Point3& p); - Point3& operator-=(const Point3& p); - Point3& operator*=(const Point3& p); - Point3& operator/=(const Point3& p); + Point3LL& operator+=(const Point3LL& p); + Point3LL& operator-=(const Point3LL& p); + Point3LL& operator*=(const Point3LL& p); + Point3LL& operator/=(const Point3LL& p); template::value, num_t>::type> - Point3& operator*=(const num_t i) + Point3LL& operator*=(const num_t i) { x_ *= i; y_ *= i; @@ -65,7 +65,7 @@ class Point3 return *this; } template::value, num_t>::type> - Point3& operator/=(const num_t i) + Point3LL& operator/=(const num_t i) { x_ /= i; y_ /= i; @@ -73,12 +73,12 @@ class Point3 return *this; } - bool operator==(const Point3& p) const; - bool operator!=(const Point3& p) const; + bool operator==(const Point3LL& p) const; + bool operator!=(const Point3LL& p) const; template - friend std::basic_ostream& operator<<(std::basic_ostream& os, const Point3& p) + friend std::basic_ostream& operator<<(std::basic_ostream& os, const Point3LL& p) { return os << "(" << p.x_ << ", " << p.y_ << ", " << p.z_ << ")"; } @@ -122,7 +122,7 @@ class Point3 return sqrt(fx * fx + fy * fy + fz * fz); } - coord_t dot(const Point3& p) const + coord_t dot(const Point3LL& p) const { return x_ * p.x_ + y_ * p.y_ + z_ * p.z_; } @@ -142,7 +142,7 @@ class Point3 } const coord_t& operator[](const size_t index) const { - return const_cast(this)->operator[](index); + return const_cast(this)->operator[](index); } }; @@ -151,10 +151,10 @@ class Point3 * * Its value is something that is rarely used. */ -static Point3 no_point3(std::numeric_limits::min(), std::numeric_limits::min(), std::numeric_limits::min()); +static Point3LL no_point3(std::numeric_limits::min(), std::numeric_limits::min(), std::numeric_limits::min()); template::value, num_t>::type> -inline Point3 operator*(const num_t i, const Point3& rhs) +inline Point3LL operator*(const num_t i, const Point3LL& rhs) { return rhs * i; } @@ -165,9 +165,9 @@ inline Point3 operator*(const num_t i, const Point3& rhs) namespace std { template<> -struct hash +struct hash { - size_t operator()(const cura::Point3& pp) const + size_t operator()(const cura::Point3LL& pp) const { static int prime = 31; int result = 89; diff --git a/include/utils/PolygonConnector.h b/include/utils/PolygonConnector.h index 325613bb31..3dc7b75dec 100644 --- a/include/utils/PolygonConnector.h +++ b/include/utils/PolygonConnector.h @@ -9,7 +9,7 @@ #endif #include -#include "IntPoint.h" +#include "Point2LL.h" #include "linearAlg2D.h" #include "polygon.h" #include "polygonUtils.h" @@ -134,7 +134,7 @@ class PolygonConnector /*! * The precise location of the source of the connection. */ - Point from_point_; + Point2LL from_point_; /*! * The polygon at the destination of the connection. @@ -151,7 +151,7 @@ class PolygonConnector /*! * The precise location of the destination of the connection. */ - Point to_point_; + Point2LL to_point_; /*! * Create a new connection. @@ -166,7 +166,7 @@ class PolygonConnector * \param to_point The precise location at the destination of the * connection. */ - PolygonConnection(Polygonal* from_poly, const size_t from_segment, const Point from_point, Polygonal* to_poly, const size_t to_segment, const Point to_point) + PolygonConnection(Polygonal* from_poly, const size_t from_segment, const Point2LL from_point, Polygonal* to_poly, const size_t to_segment, const Point2LL to_point) : from_poly_(from_poly) , from_segment_(from_segment) , from_point_(from_point) @@ -263,7 +263,7 @@ class PolygonConnector * \param vertex The vertex to get the position of. * \return The position of that vertex. */ - Point getPosition(const Point& vertex) const; + Point2LL getPosition(const Point2LL& vertex) const; /*! * Get the position of a vertex, if the vertex is a junction. @@ -272,7 +272,7 @@ class PolygonConnector * \param vertex The vertex to get the position of. * \return The position of that vertex. */ - Point getPosition(const ExtrusionJunction& vertex) const; + Point2LL getPosition(const ExtrusionJunction& vertex) const; /*! * Get the width at a certain vertex. @@ -282,7 +282,7 @@ class PolygonConnector * \param vertex The vertex to get the width of. * \return The line width of the polygon. */ - coord_t getWidth(const Point& vertex) const; + coord_t getWidth(const Point2LL& vertex) const; /*! * Get the width at a certain junction. @@ -302,7 +302,7 @@ class PolygonConnector * \param position The position of the vertex to add. * \param width The width of the vertex to add, ignored in this overload. */ - void addVertex(Polygon& polygonal, const Point& position, const coord_t width) const; + void addVertex(Polygon& polygonal, const Point2LL& position, const coord_t width) const; /*! * Add a vertex at the end of the polygonal object. @@ -311,7 +311,7 @@ class PolygonConnector * \param polygonal The polygon to add a vertex to. * \param vertex The vertex to add. */ - void addVertex(Polygon& polygonal, const Point& vertex) const; + void addVertex(Polygon& polygonal, const Point2LL& vertex) const; /*! * Add a vertex at the end of the polygonal object. @@ -321,7 +321,7 @@ class PolygonConnector * \param position The position of the vertex to add. * \param width The width of the vertex to add. */ - void addVertex(ExtrusionLine& polygonal, const Point& position, const coord_t width) const; + void addVertex(ExtrusionLine& polygonal, const Point2LL& position, const coord_t width) const; /*! * Add a vertex at the end of the polygonal object. @@ -396,7 +396,7 @@ class PolygonConnector * \param b The other vertex between which to interpolate. */ template - coord_t interpolateWidth(const Point position, Vertex a, Vertex b) const + coord_t interpolateWidth(const Point2LL position, Vertex a, Vertex b) const { const coord_t total_length = vSize(getPosition(a) - getPosition(b)); if (total_length == 0) // Prevent division by 0 when the vertices are on top of each other. @@ -428,17 +428,17 @@ class PolygonConnector } for (size_t to_index = 0; to_index < to_polygons[poly_index].size(); ++to_index) { - const Point to_pos1 = getPosition(to_polygons[poly_index][to_index]); + const Point2LL to_pos1 = getPosition(to_polygons[poly_index][to_index]); const coord_t to_width1 = getWidth(to_polygons[poly_index][to_index]); - const Point to_pos2 = getPosition(to_polygons[poly_index][(to_index + 1) % to_polygons[poly_index].size()]); + const Point2LL to_pos2 = getPosition(to_polygons[poly_index][(to_index + 1) % to_polygons[poly_index].size()]); const coord_t to_width2 = getWidth(to_polygons[poly_index][(to_index + 1) % to_polygons[poly_index].size()]); const coord_t smallest_to_width = std::min(to_width1, to_width2); for (size_t from_index = 0; from_index < from_poly.size(); ++from_index) { - const Point from_pos1 = getPosition(from_poly[from_index]); + const Point2LL from_pos1 = getPosition(from_poly[from_index]); const coord_t from_width1 = getWidth(from_poly[from_index]); - const Point from_pos2 = getPosition(from_poly[(from_index + 1) % from_poly.size()]); + const Point2LL from_pos2 = getPosition(from_poly[(from_index + 1) % from_poly.size()]); const coord_t from_width2 = getWidth(from_poly[(from_index + 1) % from_poly.size()]); const coord_t smallest_from_width = std::min(from_width1, from_width2); @@ -446,7 +446,7 @@ class PolygonConnector coord_t naive_dist = LinearAlg2D::getDistFromLine(from_pos1, to_pos1, to_pos2); if (naive_dist - from_width1 - smallest_to_width < line_width_ * max_gap_) { - const Point closest_point = LinearAlg2D::getClosestOnLineSegment(from_pos1, to_pos1, to_pos2); + const Point2LL closest_point = LinearAlg2D::getClosestOnLineSegment(from_pos1, to_pos1, to_pos2); if (closest_point == to_pos2) // The last endpoint of a vertex is considered to be part of the next segment. Let that one handle it. { continue; @@ -472,7 +472,7 @@ class PolygonConnector naive_dist = LinearAlg2D::getDistFromLine(to_pos1, from_pos1, from_pos2); if (naive_dist - smallest_from_width - to_width1 < line_width_ * max_gap_) { - const Point closest_point = LinearAlg2D::getClosestOnLineSegment(to_pos1, from_pos1, from_pos2); + const Point2LL closest_point = LinearAlg2D::getClosestOnLineSegment(to_pos1, from_pos1, from_pos2); if (closest_point == from_pos2) // The last endpoint of a vertex is considered to be part of the next segment. Let that one handle it. { continue; @@ -558,8 +558,8 @@ class PolygonConnector * ``std::nullopt``. */ template - std::optional> - walkUntilDistanceFromLine(const Polygonal& poly, const size_t start_index, const coord_t distance, const Point& line_a, const Point& line_b, const short direction) + std::optional> + walkUntilDistanceFromLine(const Polygonal& poly, const size_t start_index, const coord_t distance, const Point2LL& line_a, const Point2LL& line_b, const short direction) { const size_t poly_size = poly.size(); const coord_t line_magnitude = vSize(line_b - line_a); // Pre-compute, used for line distance calculation. @@ -570,13 +570,13 @@ class PolygonConnector for (size_t index = (start_index + direction + poly_size) % poly_size; index != start_index; index = (index + direction + poly_size) % poly_size) { - const Point vertex_pos = getPosition(poly[index]); + const Point2LL vertex_pos = getPosition(poly[index]); const coord_t vertex_distance = cross(line_a - line_b, line_a - vertex_pos) / line_magnitude; // Signed distance! if (std::abs(vertex_distance) >= distance) // Further away from the line than the threshold. { // Interpolate over that last line segment to find the point at exactly the right distance. const size_t previous_index = (index - direction + poly_size) % poly_size; - const Point previous_pos = getPosition(poly[previous_index]); + const Point2LL previous_pos = getPosition(poly[previous_index]); const coord_t previous_distance = cross(line_a - line_b, line_a - previous_pos) / line_magnitude; if (previous_distance == vertex_distance) // 0-length line segment, or parallel to line. { @@ -597,7 +597,7 @@ class PolygonConnector { continue; } - const Point interpolated_point = previous_pos + (vertex_pos - previous_pos) * interpolation; + const Point2LL interpolated_point = previous_pos + (vertex_pos - previous_pos) * interpolation; return std::make_pair(interpolated_point, (direction == +1) ? previous_index : index); // Choose the "earlier" index of the two, regardless of direction. } } @@ -622,16 +622,16 @@ class PolygonConnector coord_t best_connection_length = std::numeric_limits::max(); // Find the four intersections, on both sides of the initial connection, and on both polygons. - std::optional> from_forward_intersection + std::optional> from_forward_intersection = walkUntilDistanceFromLine(*first.from_poly_, first.from_segment_, adjacent_distance, first.from_point_, first.to_point_, +1); - std::optional> from_backward_intersection + std::optional> from_backward_intersection = walkUntilDistanceFromLine(*first.from_poly_, first.from_segment_, adjacent_distance, first.from_point_, first.to_point_, -1); - std::optional> to_forward_intersection + std::optional> to_forward_intersection = walkUntilDistanceFromLine(*first.to_poly_, first.to_segment_, adjacent_distance, first.from_point_, first.to_point_, +1); - std::optional> to_backward_intersection + std::optional> to_backward_intersection = walkUntilDistanceFromLine(*first.to_poly_, first.to_segment_, adjacent_distance, first.from_point_, first.to_point_, -1); - for (const std::optional>& from_intersection : { from_forward_intersection, from_backward_intersection }) + for (const std::optional>& from_intersection : { from_forward_intersection, from_backward_intersection }) { if (! from_intersection) { @@ -639,7 +639,7 @@ class PolygonConnector } // Find the shortest of the connections in the to_poly. const bool original_side = LinearAlg2D::pointIsLeftOfLine(first.to_point_, first.from_point_, from_intersection->first) > 0; - for (const std::optional>& to_intersection : { to_forward_intersection, to_backward_intersection }) + for (const std::optional>& to_intersection : { to_forward_intersection, to_backward_intersection }) { if (! to_intersection) { @@ -689,10 +689,10 @@ class PolygonConnector short forwards; if (bridge.a_.from_segment_ == bridge.b_.from_segment_) // If we start and end on the same segment, iterate in the direction from A to B. { - const Point vertex = getPosition((*bridge.b_.from_poly_)[bridge.b_.from_segment_]); // Same vertex for A and B. - const Point next_vertex = getPosition((*bridge.b_.from_poly_)[(bridge.b_.from_segment_ + 1) % from_size]); - const Point direction = next_vertex - vertex; // Direction we'd go into when forward iterating. - const Point a_to_b = bridge.b_.from_point_ - bridge.a_.from_point_; + const Point2LL vertex = getPosition((*bridge.b_.from_poly_)[bridge.b_.from_segment_]); // Same vertex for A and B. + const Point2LL next_vertex = getPosition((*bridge.b_.from_poly_)[(bridge.b_.from_segment_ + 1) % from_size]); + const Point2LL direction = next_vertex - vertex; // Direction we'd go into when forward iterating. + const Point2LL a_to_b = bridge.b_.from_point_ - bridge.a_.from_point_; forwards = vSize2(direction - a_to_b) < vSize2(-direction - a_to_b); } else @@ -726,10 +726,10 @@ class PolygonConnector // Add the to_polygonal from A to B. if (bridge.a_.to_segment_ == bridge.b_.to_segment_) { - const Point vertex = getPosition((*bridge.b_.to_poly_)[bridge.b_.to_segment_]); // Same vertex for A and B. - const Point next_vertex = getPosition((*bridge.b_.to_poly_)[(bridge.b_.to_segment_ + 1) % to_size]); - const Point direction = next_vertex - vertex; - const Point a_to_b = bridge.b_.to_point_ - bridge.a_.to_point_; + const Point2LL vertex = getPosition((*bridge.b_.to_poly_)[bridge.b_.to_segment_]); // Same vertex for A and B. + const Point2LL next_vertex = getPosition((*bridge.b_.to_poly_)[(bridge.b_.to_segment_ + 1) % to_size]); + const Point2LL direction = next_vertex - vertex; + const Point2LL a_to_b = bridge.b_.to_point_ - bridge.a_.to_point_; forwards = vSize2(direction - a_to_b) > vSize2(-direction - a_to_b); } else diff --git a/include/utils/PolygonsPointIndex.h b/include/utils/PolygonsPointIndex.h index a72a33af2c..1b973f94da 100644 --- a/include/utils/PolygonsPointIndex.h +++ b/include/utils/PolygonsPointIndex.h @@ -6,7 +6,7 @@ #include -#include "IntPoint.h" +#include "Point2LL.h" #include "polygon.h" @@ -59,11 +59,11 @@ class PathsPointIndex */ PathsPointIndex(const PathsPointIndex& original) = default; - Point p() const + Point2LL p() const { if (! polygons_) { - return Point(0, 0); + return Point2LL(0, 0); } return make_point((*polygons_)[poly_idx_][point_idx_]); } @@ -153,13 +153,13 @@ using PolygonsPointIndex = PathsPointIndex; */ struct PolygonsPointIndexSegmentLocator { - std::pair operator()(const PolygonsPointIndex& val) const + std::pair operator()(const PolygonsPointIndex& val) const { ConstPolygonRef poly = (*val.polygons_)[val.poly_idx_]; - Point start = poly[val.point_idx_]; + Point2LL start = poly[val.point_idx_]; unsigned int next_point_idx = (val.point_idx_ + 1) % poly.size(); - Point end = poly[next_point_idx]; - return std::pair(start, end); + Point2LL end = poly[next_point_idx]; + return std::pair(start, end); } }; @@ -170,7 +170,7 @@ struct PolygonsPointIndexSegmentLocator template struct PathsPointIndexLocator { - Point operator()(const PathsPointIndex& val) const + Point2LL operator()(const PathsPointIndex& val) const { return make_point(val.p()); } @@ -190,7 +190,7 @@ struct hash { size_t operator()(const cura::PolygonsPointIndex& lpi) const { - return std::hash()(lpi.p()); + return std::hash()(lpi.p()); } }; } // namespace std diff --git a/include/utils/PolygonsSegmentIndex.h b/include/utils/PolygonsSegmentIndex.h index 8f0e0e2d23..b5462a7a16 100644 --- a/include/utils/PolygonsSegmentIndex.h +++ b/include/utils/PolygonsSegmentIndex.h @@ -20,9 +20,9 @@ class PolygonsSegmentIndex : public PolygonsPointIndex PolygonsSegmentIndex(); PolygonsSegmentIndex(const Polygons* polygons, unsigned int poly_idx, unsigned int point_idx); - Point from() const; + Point2LL from() const; - Point to() const; + Point2LL to() const; }; diff --git a/include/utils/PolylineStitcher.h b/include/utils/PolylineStitcher.h index 2942a0840e..7d608f1ee7 100644 --- a/include/utils/PolylineStitcher.h +++ b/include/utils/PolylineStitcher.h @@ -93,7 +93,7 @@ class PolylineStitcher while (true) { - Point from = make_point(chain.back()); + Point2LL from = make_point(chain.back()); PathsPointIndex closest; coord_t closest_distance = std::numeric_limits::max(); diff --git a/include/utils/SVG.h b/include/utils/SVG.h index 8fda644264..82646e1df6 100644 --- a/include/utils/SVG.h +++ b/include/utils/SVG.h @@ -8,7 +8,7 @@ #include "AABB.h" #include "ExtrusionLine.h" //To accept variable-width paths. -#include "IntPoint.h" +#include "Point2LL.h" #include "NoCopy.h" namespace cura @@ -62,8 +62,8 @@ class SVG : NoCopy FILE* out_; // the output file const AABB aabb_; // the boundary box to display - const Point aabb_size_; - const Point canvas_size_; + const Point2LL aabb_size_; + const Point2LL canvas_size_; const double scale_; ColorObject background_; size_t layer_nr_ = 1; @@ -71,9 +71,9 @@ class SVG : NoCopy bool output_is_html_; public: - SVG(std::string filename, const AABB aabb, const Point canvas_size = Point(1024, 1024), const ColorObject background = Color::NONE); + SVG(std::string filename, const AABB aabb, const Point2LL canvas_size = Point2LL(1024, 1024), const ColorObject background = Color::NONE); SVG(std::string filename, const AABB aabb, const double scale, const ColorObject background = Color::NONE); - SVG(std::string filename, const AABB aabb, const double scale, const Point canvas_size, const ColorObject background = Color::NONE); + SVG(std::string filename, const AABB aabb, const double scale, const Point2LL canvas_size, const ColorObject background = Color::NONE); ~SVG(); @@ -87,12 +87,12 @@ class SVG : NoCopy /*! * transform a point in real space to canvas space */ - Point transform(const Point& p) const; + Point2LL transform(const Point2LL& p) const; /*! * transform a point in real space to canvas space with more precision */ - Point3D transformF(const Point& p) const; + Point3D transformF(const Point2LL& p) const; void writeComment(const std::string& comment) const; @@ -100,7 +100,7 @@ class SVG : NoCopy void writeAreas(ConstPolygonRef polygon, const ColorObject color = Color::GRAY, const ColorObject outline_color = Color::BLACK, const double stroke_width = 1.0) const; - void writePoint(const Point& p, const bool write_coords = false, const double size = 5.0, const ColorObject color = Color::BLACK) const; + void writePoint(const Point2LL& p, const bool write_coords = false, const double size = 5.0, const ColorObject color = Color::BLACK) const; void writePoints(ConstPolygonRef poly, const bool write_coords = false, const double size = 5.0, const ColorObject color = Color::BLACK) const; @@ -117,13 +117,13 @@ class SVG : NoCopy * \param color The colour of the line segments. If this is not specified, * black will be used. */ - void writeLines(const std::vector& polyline, const ColorObject color = Color::BLACK) const; + void writeLines(const std::vector& polyline, const ColorObject color = Color::BLACK) const; - void writeLine(const Point& a, const Point& b, const ColorObject color = Color::BLACK, const double stroke_width = 1.0) const; + void writeLine(const Point2LL& a, const Point2LL& b, const ColorObject color = Color::BLACK, const double stroke_width = 1.0) const; - void writeArrow(const Point& a, const Point& b, const ColorObject color = Color::BLACK, const double stroke_width = 1.0, const double head_size = 5.0) const; + void writeArrow(const Point2LL& a, const Point2LL& b, const ColorObject color = Color::BLACK, const double stroke_width = 1.0, const double head_size = 5.0) const; - void writeLineRGB(const Point& from, const Point& to, const int r = 0, const int g = 0, const int b = 0, const double stroke_width = 1.0) const; + void writeLineRGB(const Point2LL& from, const Point2LL& to, const int r = 0, const int g = 0, const int b = 0, const double stroke_width = 1.0) const; /*! * \brief Draws a dashed line on the canvas from point A to point B. @@ -134,12 +134,12 @@ class SVG : NoCopy * \param b The ending endpoint of the line. * \param color The stroke colour of the line. */ - void writeDashedLine(const Point& a, const Point& b, ColorObject color = Color::BLACK) const; + void writeDashedLine(const Point2LL& a, const Point2LL& b, ColorObject color = Color::BLACK) const; template void printf(const char* txt, Args&&... args) const; - void writeText(const Point& p, const std::string& txt, const ColorObject color = Color::BLACK, const double font_size = 10.0) const; + void writeText(const Point2LL& p, const std::string& txt, const ColorObject color = Color::BLACK, const double font_size = 10.0) const; void writePolygons(const Polygons& polys, const ColorObject color = Color::BLACK, const double stroke_width = 1.0) const; diff --git a/include/utils/Simplify.h b/include/utils/Simplify.h index e1cacd9a8f..91c0eeca61 100644 --- a/include/utils/Simplify.h +++ b/include/utils/Simplify.h @@ -240,7 +240,7 @@ class Simplify } // From here on out we can safely look at the vertex neighbors and assume it's a polygon. We won't go out of bounds of the polyline. - const Point& vertex = getPosition(polygon[index]); + const Point2LL& vertex = getPosition(polygon[index]); const size_t before_index = previousNotDeleted(index, to_delete); const size_t after_index = nextNotDeleted(index, to_delete); @@ -250,8 +250,8 @@ class Simplify return std::numeric_limits::max(); } - const Point& before = getPosition(polygon[before_index]); - const Point& after = getPosition(polygon[after_index]); + const Point2LL& before = getPosition(polygon[before_index]); + const Point2LL& after = getPosition(polygon[after_index]); const coord_t deviation2 = LinearAlg2D::getDist2FromLine(vertex, before, after); if (deviation2 <= min_resolution * min_resolution) // Deviation so small that it's always desired to remove them. { @@ -293,9 +293,9 @@ class Simplify const size_t before = previousNotDeleted(vertex, to_delete); const size_t after = nextNotDeleted(vertex, to_delete); - const Point& vertex_position = getPosition(polygon[vertex]); - const Point& before_position = getPosition(polygon[before]); - const Point& after_position = getPosition(polygon[after]); + const Point2LL& vertex_position = getPosition(polygon[vertex]); + const Point2LL& before_position = getPosition(polygon[before]); + const Point2LL& after_position = getPosition(polygon[after]); const coord_t length2_before = vSize2(vertex_position - before_position); const coord_t length2_after = vSize2(vertex_position - after_position); @@ -309,7 +309,7 @@ class Simplify // Otherwise, one edge next to this vertex is longer than max_resolution. The other is shorter. // In this case we want to remove the short edge by replacing it with a vertex where the two surrounding edges intersect. // Find the two line segments surrounding the short edge here ("before" and "after" edges). - Point before_from, before_to, after_from, after_to; + Point2LL before_from, before_to, after_from, after_to; if (length2_before <= length2_after) // Before is the shorter line. { if (! is_closed && before == 0) // No edge before the short edge. @@ -334,7 +334,7 @@ class Simplify after_from = getPosition(polygon[after]); after_to = getPosition(polygon[after_after]); } - Point intersection; + Point2LL intersection; const bool did_intersect = LinearAlg2D::lineLineIntersection(before_from, before_to, after_from, after_to, intersection); if (! did_intersect) // Lines are parallel. { @@ -399,7 +399,7 @@ class Simplify * \param polygon The polygon to add to. * \param vertex The vertex to add. */ - void appendVertex(Polygon& polygon, const Point& vertex) const; + void appendVertex(Polygon& polygon, const Point2LL& vertex) const; /*! * Append a vertex to this extrusion line. @@ -418,7 +418,7 @@ class Simplify * \param vertex A vertex to get the coordinates of. * \return The coordinates of that vertex. */ - const Point& getPosition(const Point& vertex) const; + const Point2LL& getPosition(const Point2LL& vertex) const; /*! * Get the coordinates of a vertex. @@ -427,7 +427,7 @@ class Simplify * \param vertex A vertex to get the coordinates of. * \return The coordinates of that vertex. */ - const Point& getPosition(const ExtrusionJunction& vertex) const; + const Point2LL& getPosition(const ExtrusionJunction& vertex) const; /*! * Create an intersection vertex that can be placed in a polygon. @@ -437,7 +437,7 @@ class Simplify * \param after One of the vertices of a removed edge. Unused in this * overload. */ - Point createIntersection(const Point& before, const Point intersection, const Point& after) const; + Point2LL createIntersection(const Point2LL& before, const Point2LL intersection, const Point2LL& after) const; /*! * Create an intersection vertex that can be placed in an ExtrusionLine. @@ -447,7 +447,7 @@ class Simplify * \param after One of the vertices of the edge that gets replaced by an * intersection vertex. */ - ExtrusionJunction createIntersection(const ExtrusionJunction& before, const Point intersection, const ExtrusionJunction& after) const; + ExtrusionJunction createIntersection(const ExtrusionJunction& before, const Point2LL intersection, const ExtrusionJunction& after) const; /*! * Get the extrusion area deviation that would be caused by removing this @@ -460,7 +460,7 @@ class Simplify * \param after The vertex after the one that is to be removed. * \return The area deviation that would be caused by removing the vertex. */ - coord_t getAreaDeviation(const Point& before, const Point& vertex, const Point& after) const; + coord_t getAreaDeviation(const Point2LL& before, const Point2LL& vertex, const Point2LL& after) const; /*! * Get the extrusion area deviation that would be caused by removing this diff --git a/include/utils/SparseGrid.h b/include/utils/SparseGrid.h index 3e403a7266..11b0708942 100644 --- a/include/utils/SparseGrid.h +++ b/include/utils/SparseGrid.h @@ -10,7 +10,7 @@ #include #include -#include "IntPoint.h" +#include "Point2LL.h" #include "SquareGrid.h" namespace cura @@ -80,7 +80,7 @@ class SparseGrid : public SquareGrid * \param[in] radius The search radius. * \return Vector of elements found */ - std::vector getNearby(const Point& query_pt, coord_t radius) const; + std::vector getNearby(const Point2LL& query_pt, coord_t radius) const; static const std::function no_precondition; @@ -94,7 +94,7 @@ class SparseGrid : public SquareGrid * to be considered for output * \return True if and only if an object has been found within the radius. */ - bool getNearest(const Point& query_pt, coord_t radius, Elem& elem_nearest, const std::function precondition = no_precondition) const; + bool getNearest(const Point2LL& query_pt, coord_t radius, Elem& elem_nearest, const std::function precondition = no_precondition) const; /*! \brief Process elements from cells that might contain sought after points. * @@ -109,7 +109,7 @@ class SparseGrid : public SquareGrid * called for each element in the cell. Processing stops if function returns false. * \return Whether we need to continue processing after this function */ - bool processNearby(const Point& query_pt, coord_t radius, const std::function& process_func) const; + bool processNearby(const Point2LL& query_pt, coord_t radius, const std::function& process_func) const; /*! \brief Process elements from cells that might contain sought after points along a line. * @@ -121,7 +121,7 @@ class SparseGrid : public SquareGrid * called for each element in the cells. Processing stops if function returns false. * \return Whether we need to continue processing after this function */ - bool processLine(const std::pair query_line, const std::function& process_elem_func) const; + bool processLine(const std::pair query_line, const std::function& process_elem_func) const; protected: /*! \brief Process elements from the cell indicated by \p grid_pt. @@ -168,7 +168,7 @@ bool SGI_THIS::processFromCell(const GridPoint& grid_pt, const std::function& process_func) const +bool SGI_THIS::processNearby(const Point2LL& query_pt, coord_t radius, const std::function& process_func) const { return SquareGrid::processNearby( query_pt, @@ -180,7 +180,7 @@ bool SGI_THIS::processNearby(const Point& query_pt, coord_t radius, const std::f } SGI_TEMPLATE -bool SGI_THIS::processLine(const std::pair query_line, const std::function& process_elem_func) const +bool SGI_THIS::processLine(const std::pair query_line, const std::function& process_elem_func) const { const std::function process_cell_func = [&process_elem_func, this](GridPoint grid_loc) { @@ -190,7 +190,7 @@ bool SGI_THIS::processLine(const std::pair query_line, const std:: } SGI_TEMPLATE -std::vector SGI_THIS::getNearby(const Point& query_pt, coord_t radius) const +std::vector SGI_THIS::getNearby(const Point2LL& query_pt, coord_t radius) const { std::vector ret; const std::function process_func = [&ret](const Elem& elem) @@ -209,7 +209,7 @@ const std::function SGI_THIS::no_precondit }; SGI_TEMPLATE -bool SGI_THIS::getNearest(const Point& query_pt, coord_t radius, Elem& elem_nearest, const std::function precondition) const +bool SGI_THIS::getNearest(const Point2LL& query_pt, coord_t radius, Elem& elem_nearest, const std::function precondition) const { bool found = false; int64_t best_dist2 = static_cast(radius) * radius; diff --git a/include/utils/SparseLineGrid.h b/include/utils/SparseLineGrid.h index d5462414b1..5b22818797 100644 --- a/include/utils/SparseLineGrid.h +++ b/include/utils/SparseLineGrid.h @@ -10,7 +10,7 @@ #include #include -#include "IntPoint.h" +#include "Point2LL.h" #include "SVG.h" // debug #include "SparseGrid.h" @@ -71,7 +71,7 @@ SGI_THIS::SparseLineGrid(coord_t cell_size, size_t elem_reserve, double max_load SGI_TEMPLATE void SGI_THIS::insert(const Elem& elem) { - const std::pair line = m_locator(elem); + const std::pair line = m_locator(elem); // below is a workaround for the fact that lambda functions cannot access private or protected members // first we define a lambda which works on any GridMap and then we bind it to the actual protected GridMap of the parent class std::function process_cell_func_ = [&elem, this](GridMap* grid, const GridPoint grid_loc) @@ -99,10 +99,10 @@ void SGI_THIS::debugHTML(std::string filename) for (std::pair cell : SparseGrid::grid_) { // doesn't draw cells at x = 0 or y = 0 correctly (should be double size) - Point lb = SparseGrid::toLowerCorner(cell.first); - Point lt = SparseGrid::toLowerCorner(cell.first + GridPoint(0, SparseGrid::nonzero_sign(cell.first.Y))); - Point rt = SparseGrid::toLowerCorner(cell.first + GridPoint(SparseGrid::nonzero_sign(cell.first.X), SparseGrid::nonzero_sign(cell.first.Y))); - Point rb = SparseGrid::toLowerCorner(cell.first + GridPoint(SparseGrid::nonzero_sign(cell.first.X), 0)); + Point2LL lb = SparseGrid::toLowerCorner(cell.first); + Point2LL lt = SparseGrid::toLowerCorner(cell.first + GridPoint(0, SparseGrid::nonzero_sign(cell.first.Y))); + Point2LL rt = SparseGrid::toLowerCorner(cell.first + GridPoint(SparseGrid::nonzero_sign(cell.first.X), SparseGrid::nonzero_sign(cell.first.Y))); + Point2LL rb = SparseGrid::toLowerCorner(cell.first + GridPoint(SparseGrid::nonzero_sign(cell.first.X), 0)); if (lb.X == 0) { lb.X = -SparseGrid::cell_size_; @@ -119,7 +119,7 @@ void SGI_THIS::debugHTML(std::string filename) svg.writeLine(rt, rb, SVG::Color::GRAY); svg.writeLine(rb, lb, SVG::Color::GRAY); - std::pair line = m_locator(cell.second); + std::pair line = m_locator(cell.second); svg.writePoint(line.first, true); svg.writePoint(line.second, true); svg.writeLine(line.first, line.second, SVG::Color::BLACK); @@ -131,53 +131,53 @@ void SGI_THIS::debugTest() { struct PairLocator { - std::pair operator()(const std::pair& val) const + std::pair operator()(const std::pair& val) const { return val; } }; - SparseLineGrid, PairLocator> line_grid(10); + SparseLineGrid, PairLocator> line_grid(10); // straight lines - line_grid.insert(std::make_pair(Point(50, 0), Point(50, 70))); - line_grid.insert(std::make_pair(Point(0, 90), Point(50, 90))); - line_grid.insert(std::make_pair(Point(253, 103), Point(253, 173))); - line_grid.insert(std::make_pair(Point(203, 193), Point(253, 193))); - line_grid.insert(std::make_pair(Point(-50, 0), Point(-50, -70))); - line_grid.insert(std::make_pair(Point(0, -90), Point(-50, -90))); - line_grid.insert(std::make_pair(Point(-253, -103), Point(-253, -173))); - line_grid.insert(std::make_pair(Point(-203, -193), Point(-253, -193))); + line_grid.insert(std::make_pair(Point2LL(50, 0), Point2LL(50, 70))); + line_grid.insert(std::make_pair(Point2LL(0, 90), Point2LL(50, 90))); + line_grid.insert(std::make_pair(Point2LL(253, 103), Point2LL(253, 173))); + line_grid.insert(std::make_pair(Point2LL(203, 193), Point2LL(253, 193))); + line_grid.insert(std::make_pair(Point2LL(-50, 0), Point2LL(-50, -70))); + line_grid.insert(std::make_pair(Point2LL(0, -90), Point2LL(-50, -90))); + line_grid.insert(std::make_pair(Point2LL(-253, -103), Point2LL(-253, -173))); + line_grid.insert(std::make_pair(Point2LL(-203, -193), Point2LL(-253, -193))); // diagonal lines - line_grid.insert(std::make_pair(Point(113, 133), Point(166, 125))); - line_grid.insert(std::make_pair(Point(13, 73), Point(26, 25))); - line_grid.insert(std::make_pair(Point(166, 33), Point(113, 25))); - line_grid.insert(std::make_pair(Point(26, 173), Point(13, 125))); - line_grid.insert(std::make_pair(Point(-24, -18), Point(-19, -64))); - line_grid.insert(std::make_pair(Point(-113, -133), Point(-166, -125))); - line_grid.insert(std::make_pair(Point(-166, -33), Point(-113, -25))); - line_grid.insert(std::make_pair(Point(-26, -173), Point(-13, -125))); + line_grid.insert(std::make_pair(Point2LL(113, 133), Point2LL(166, 125))); + line_grid.insert(std::make_pair(Point2LL(13, 73), Point2LL(26, 25))); + line_grid.insert(std::make_pair(Point2LL(166, 33), Point2LL(113, 25))); + line_grid.insert(std::make_pair(Point2LL(26, 173), Point2LL(13, 125))); + line_grid.insert(std::make_pair(Point2LL(-24, -18), Point2LL(-19, -64))); + line_grid.insert(std::make_pair(Point2LL(-113, -133), Point2LL(-166, -125))); + line_grid.insert(std::make_pair(Point2LL(-166, -33), Point2LL(-113, -25))); + line_grid.insert(std::make_pair(Point2LL(-26, -173), Point2LL(-13, -125))); // diagonal lines exactly crossing cell corners - line_grid.insert(std::make_pair(Point(160, 190), Point(220, 170))); - line_grid.insert(std::make_pair(Point(60, 130), Point(80, 70))); - line_grid.insert(std::make_pair(Point(220, 90), Point(160, 70))); - line_grid.insert(std::make_pair(Point(80, 220), Point(60, 160))); - line_grid.insert(std::make_pair(Point(-160, -190), Point(-220, -170))); - line_grid.insert(std::make_pair(Point(-60, -130), Point(-80, -70))); - line_grid.insert(std::make_pair(Point(-220, -90), Point(-160, -70))); - line_grid.insert(std::make_pair(Point(-80, -220), Point(-60, -160))); + line_grid.insert(std::make_pair(Point2LL(160, 190), Point2LL(220, 170))); + line_grid.insert(std::make_pair(Point2LL(60, 130), Point2LL(80, 70))); + line_grid.insert(std::make_pair(Point2LL(220, 90), Point2LL(160, 70))); + line_grid.insert(std::make_pair(Point2LL(80, 220), Point2LL(60, 160))); + line_grid.insert(std::make_pair(Point2LL(-160, -190), Point2LL(-220, -170))); + line_grid.insert(std::make_pair(Point2LL(-60, -130), Point2LL(-80, -70))); + line_grid.insert(std::make_pair(Point2LL(-220, -90), Point2LL(-160, -70))); + line_grid.insert(std::make_pair(Point2LL(-80, -220), Point2LL(-60, -160))); // single cell - line_grid.insert(std::make_pair(Point(203, 213), Point(203, 213))); - line_grid.insert(std::make_pair(Point(223, 213), Point(223, 215))); - line_grid.insert(std::make_pair(Point(243, 213), Point(245, 213))); - line_grid.insert(std::make_pair(Point(263, 213), Point(265, 215))); - line_grid.insert(std::make_pair(Point(283, 215), Point(285, 213))); - line_grid.insert(std::make_pair(Point(-203, -213), Point(-203, -213))); + line_grid.insert(std::make_pair(Point2LL(203, 213), Point2LL(203, 213))); + line_grid.insert(std::make_pair(Point2LL(223, 213), Point2LL(223, 215))); + line_grid.insert(std::make_pair(Point2LL(243, 213), Point2LL(245, 213))); + line_grid.insert(std::make_pair(Point2LL(263, 213), Point2LL(265, 215))); + line_grid.insert(std::make_pair(Point2LL(283, 215), Point2LL(285, 213))); + line_grid.insert(std::make_pair(Point2LL(-203, -213), Point2LL(-203, -213))); // around origin - line_grid.insert(std::make_pair(Point(20, -20), Point(-20, 20))); + line_grid.insert(std::make_pair(Point2LL(20, -20), Point2LL(-20, 20))); line_grid.debugHTML("line_grid.html"); } diff --git a/include/utils/SparsePointGrid.h b/include/utils/SparsePointGrid.h index 748f79124e..4565a5dc4a 100644 --- a/include/utils/SparsePointGrid.h +++ b/include/utils/SparsePointGrid.h @@ -9,7 +9,7 @@ #include #include -#include "IntPoint.h" +#include "Point2LL.h" #include "SparseGrid.h" namespace cura @@ -51,7 +51,7 @@ class SparsePointGrid : public SparseGrid * \param query_pt The point to query for an object nearby. * \param radius The radius of what is considered "nearby". */ - const ElemT* getAnyNearby(const Point& query_pt, coord_t radius); + const ElemT* getAnyNearby(const Point2LL& query_pt, coord_t radius); protected: using GridPoint = typename SparseGrid::GridPoint; @@ -73,14 +73,14 @@ SGI_THIS::SparsePointGrid(coord_t cell_size, size_t elem_reserve, double max_loa SGI_TEMPLATE void SGI_THIS::insert(const Elem& elem) { - Point loc = m_locator(elem); + Point2LL loc = m_locator(elem); GridPoint grid_loc = SparseGrid::toGridPoint(loc); SparseGrid::grid_.emplace(grid_loc, elem); } SGI_TEMPLATE -const ElemT* SGI_THIS::getAnyNearby(const Point& query_pt, coord_t radius) +const ElemT* SGI_THIS::getAnyNearby(const Point2LL& query_pt, coord_t radius) { const ElemT* ret = nullptr; const std::function& process_func = [&ret, query_pt, radius, this](const ElemT& maybe_nearby) diff --git a/include/utils/SparsePointGridInclusive.h b/include/utils/SparsePointGridInclusive.h index 7e4cdce82e..962c0d602e 100644 --- a/include/utils/SparsePointGridInclusive.h +++ b/include/utils/SparsePointGridInclusive.h @@ -9,7 +9,7 @@ #include #include -#include "IntPoint.h" +#include "Point2LL.h" #include "SparsePointGrid.h" namespace cura @@ -26,20 +26,20 @@ struct SparsePointGridInclusiveElem { } - SparsePointGridInclusiveElem(const Point& point_, const Val& val_) + SparsePointGridInclusiveElem(const Point2LL& point_, const Val& val_) : point(point_) , val(val_) { } - Point point; + Point2LL point; Val val; }; template struct Locatoror { - Point operator()(const SparsePointGridInclusiveElem& elem) + Point2LL operator()(const SparsePointGridInclusiveElem& elem) { return elem.point; } @@ -73,7 +73,7 @@ class SparsePointGridInclusive : public SparsePointGrid getNearbyVals(const Point& query_pt, coord_t radius) const; + std::vector getNearbyVals(const Point2LL& query_pt, coord_t radius) const; }; #define SG_TEMPLATE template @@ -99,14 +99,14 @@ SG_THIS::SparsePointGridInclusive(coord_t cell_size, size_t elem_reserve, double } SG_TEMPLATE -void SG_THIS::insert(const Point& point, const Val& val) +void SG_THIS::insert(const Point2LL& point, const Val& val) { typename SG_THIS::Elem elem(point, val); Base::insert(elem); } SG_TEMPLATE -std::vector SG_THIS::getNearbyVals(const Point& query_pt, coord_t radius) const +std::vector SG_THIS::getNearbyVals(const Point2LL& query_pt, coord_t radius) const { std::vector ret; std::function&)> process_func = [&ret](const typename SG_THIS::Elem& elem) diff --git a/include/utils/SquareGrid.h b/include/utils/SquareGrid.h index 515cf0cf9d..ebbab19ca2 100644 --- a/include/utils/SquareGrid.h +++ b/include/utils/SquareGrid.h @@ -9,7 +9,7 @@ #include #include -#include "IntPoint.h" +#include "Point2LL.h" namespace cura { @@ -36,7 +36,7 @@ class SquareGrid */ coord_t getCellSize() const; - using GridPoint = Point; + using GridPoint = Point2LL; using grid_coord_t = coord_t; /*! \brief Process cells along a line indicated by \p line. @@ -46,7 +46,7 @@ class SquareGrid * for each cell. Processing stops if function returns false. * \return Whether we need to continue processing after this function. */ - bool processLineCells(const std::pair line, const std::function& process_cell_func); + bool processLineCells(const std::pair line, const std::function& process_cell_func); /*! \brief Process cells along a line indicated by \p line. * @@ -55,7 +55,7 @@ class SquareGrid * for each cell. Processing stops if function returns false. * \return Whether we need to continue processing after this function. */ - bool processLineCells(const std::pair line, const std::function& process_cell_func) const; + bool processLineCells(const std::pair line, const std::function& process_cell_func) const; /*! * Process all cells in an axis-aligned right triangle. @@ -90,8 +90,8 @@ class SquareGrid * good candidate has been found. * \return Whether we need to continue processing after this function. */ - bool processAxisAlignedTriangle(const Point from, const Point to, const std::function& process_cell_func) const; - bool processAxisAlignedTriangle(const Point from, const Point to, bool to_the_right, const std::function& process_cell_func) const; + bool processAxisAlignedTriangle(const Point2LL from, const Point2LL to, const std::function& process_cell_func) const; + bool processAxisAlignedTriangle(const Point2LL from, const Point2LL to, bool to_the_right, const std::function& process_cell_func) const; /*! \brief Process cells that might contain sought after points. * @@ -105,13 +105,13 @@ class SquareGrid * ``false``. * \return Whether we need to continue processing after this function. */ - bool processNearby(const Point& query_pt, coord_t radius, const std::function& process_func) const; + bool processNearby(const Point2LL& query_pt, coord_t radius, const std::function& process_func) const; /*! \brief Compute the grid coordinates of a point. * \param point The actual location. * \return The grid coordinates that correspond to \p point. */ - GridPoint toGridPoint(const Point& point) const; + GridPoint toGridPoint(const Point2LL& point) const; /*! \brief Compute the grid coordinate of a real space coordinate. * \param coord The actual location. @@ -125,7 +125,7 @@ class SquareGrid * \param location The grid location. * \return The print space coordinates that correspond to \p location. */ - Point toLowerCorner(const GridPoint& location) const; + Point2LL toLowerCorner(const GridPoint& location) const; /*! \brief Compute the lowest coord in a grid cell. * The lowest point is the point in the grid cell closest to the origin. diff --git a/include/utils/VoronoiUtils.h b/include/utils/VoronoiUtils.h index 4c0c196cc4..287b6765b1 100644 --- a/include/utils/VoronoiUtils.h +++ b/include/utils/VoronoiUtils.h @@ -25,22 +25,22 @@ class VoronoiUtils using voronoi_data_t = double; using vd_t = boost::polygon::voronoi_diagram; - static Point getSourcePoint(const vd_t::cell_type& cell, const std::vector& points, const std::vector& segments); - static const Segment& getSourceSegment(const vd_t::cell_type& cell, const std::vector& points, const std::vector& segments); - static PolygonsPointIndex getSourcePointIndex(const vd_t::cell_type& cell, const std::vector& points, const std::vector& segments); + static Point2LL getSourcePoint(const vd_t::cell_type& cell, const std::vector& points, const std::vector& segments); + static const Segment& getSourceSegment(const vd_t::cell_type& cell, const std::vector& points, const std::vector& segments); + static PolygonsPointIndex getSourcePointIndex(const vd_t::cell_type& cell, const std::vector& points, const std::vector& segments); - static Point p(const vd_t::vertex_type* node); + static Point2LL p(const vd_t::vertex_type* node); - static bool isSourcePoint(Point p, const vd_t::cell_type& cell, const std::vector& points, const std::vector& segments, coord_t snap_dist = 10); + static bool isSourcePoint(Point2LL p, const vd_t::cell_type& cell, const std::vector& points, const std::vector& segments, coord_t snap_dist = 10); - static coord_t getDistance(Point p, const vd_t::cell_type& cell, const std::vector& points, const std::vector& segments); + static coord_t getDistance(Point2LL p, const vd_t::cell_type& cell, const std::vector& points, const std::vector& segments); /*! * Discretize a parabola based on (approximate) step size. * The \p approximate_step_size is measured parallel to the \p source_segment, not along the parabola. */ - static std::vector - discretizeParabola(const Point& source_point, const Segment& source_segment, Point start, Point end, coord_t approximate_step_size, double transitioning_angle); + static std::vector + discretizeParabola(const Point2LL& source_point, const Segment& source_segment, Point2LL start, Point2LL end, coord_t approximate_step_size, double transitioning_angle); protected: /*! @@ -66,7 +66,7 @@ class VoronoiUtils * Important: * discretization should contain both edge endpoints initially. */ - static void discretize(const Point& point, const Segment& segment, const coord_t max_dist, std::vector* discretization); + static void discretize(const Point2LL& point, const Segment& segment, const coord_t max_dist, std::vector* discretization); /*! * adapted from boost::polygon::voronoi_visual_utils.cpp @@ -84,7 +84,7 @@ class VoronoiUtils * transformed one and vice versa. The assumption is made that projection of * the point lies between the start-point and endpoint of the segment. */ - static double getPointProjection(const Point& point, const Segment& segment); + static double getPointProjection(const Point2LL& point, const Segment& segment); }; } // namespace cura diff --git a/include/utils/VoxelUtils.h b/include/utils/VoxelUtils.h index 4cf4d97029..f6cd123677 100644 --- a/include/utils/VoxelUtils.h +++ b/include/utils/VoxelUtils.h @@ -7,13 +7,13 @@ #include #include -#include "utils/IntPoint.h" +#include "utils/Point2LL.h" #include "utils/polygon.h" namespace cura { -using GridPoint3 = Point3; +using GridPoint3 = Point3LL; /*! * Class for holding the relative positiongs wrt a reference cell on which to perform a dilation. @@ -65,9 +65,9 @@ class VoxelUtils public: using grid_coord_t = coord_t; - Point3 cell_size_; + Point3LL cell_size_; - VoxelUtils(Point3 cell_size) + VoxelUtils(Point3LL cell_size) : cell_size_(cell_size) { } @@ -80,7 +80,7 @@ class VoxelUtils * \param process_cell_func Function to perform on each cell the line crosses * \return Whether executing was stopped short as indicated by the \p cell_processing_function */ - bool walkLine(Point3 start, Point3 end, const std::function& process_cell_func) const; + bool walkLine(Point3LL start, Point3LL end, const std::function& process_cell_func) const; /*! * Process voxels which the line segments of a polygon crosses. @@ -151,7 +151,7 @@ class VoxelUtils */ std::function dilate(const DilationKernel& kernel, const std::function& process_cell_func) const; - GridPoint3 toGridPoint(const Point3& point) const + GridPoint3 toGridPoint(const Point3LL& point) const { return GridPoint3(toGridCoord(point.x_, 0), toGridCoord(point.y_, 1), toGridCoord(point.z_, 2)); } @@ -162,9 +162,9 @@ class VoxelUtils return coord / cell_size_[dim] - (coord < 0); } - Point3 toLowerCorner(const GridPoint3& location) const + Point3LL toLowerCorner(const GridPoint3& location) const { - return cura::Point3(toLowerCoord(location.x_, 0), toLowerCoord(location.y_, 1), toLowerCoord(location.z_, 2)); + return cura::Point3LL(toLowerCoord(location.x_, 0), toLowerCoord(location.y_, 1), toLowerCoord(location.z_, 2)); } coord_t toLowerCoord(const grid_coord_t& grid_coord, const size_t dim) const @@ -179,7 +179,7 @@ class VoxelUtils Polygon toPolygon(const GridPoint3 p) const { Polygon ret; - Point3 c = toLowerCorner(p); + Point3LL c = toLowerCorner(p); ret.emplace_back(c.x_, c.y_); ret.emplace_back(c.x_ + cell_size_.x_, c.y_); ret.emplace_back(c.x_ + cell_size_.x_, c.y_ + cell_size_.y_); diff --git a/include/utils/actions/smooth.h b/include/utils/actions/smooth.h index a450a9fe40..a414d9850a 100644 --- a/include/utils/actions/smooth.h +++ b/include/utils/actions/smooth.h @@ -186,7 +186,7 @@ struct smooth_fn requires utils::point2d || utils::junction inline constexpr auto cosAngle(Vector& a, Vector& b) const noexcept { - return cosAngle(a, b, magnitude(a), magnitude(b)); + return cosAngle(a, b, magnitude(a), magnitude(b)); } template diff --git a/include/utils/linearAlg2D.h b/include/utils/linearAlg2D.h index dce7acf95c..42b57a16d9 100644 --- a/include/utils/linearAlg2D.h +++ b/include/utils/linearAlg2D.h @@ -4,14 +4,14 @@ #ifndef UTILS_LINEAR_ALG_2D_H #define UTILS_LINEAR_ALG_2D_H -#include "IntPoint.h" +#include "Point2LL.h" namespace cura { class LinearAlg2D { public: - static short pointLiesOnTheRightOfLine(const Point& p, const Point& p0, const Point& p1) + static short pointLiesOnTheRightOfLine(const Point2LL& p, const Point2LL& p0, const Point2LL& p1) { // no tests unless the segment p0-p1 is at least partly at, or to right of, p.X if (std::max(p0.X, p1.X) >= p.X) @@ -64,12 +64,12 @@ class LinearAlg2D return -1; } - static bool lineLineIntersection(const Point& a, const Point& b, const Point& c, const Point& d, Point& output) + static bool lineLineIntersection(const Point2LL& a, const Point2LL& b, const Point2LL& c, const Point2LL& d, Point2LL& output) { // Adapted from Apex: https://github.com/Ghostkeeper/Apex/blob/eb75f0d96e36c7193d1670112826842d176d5214/include/apex/line_segment.hpp#L91 // Adjusted to work with lines instead of line segments. - const Point l1_delta = b - a; - const Point l2_delta = d - c; + const Point2LL l1_delta = b - a; + const Point2LL l2_delta = d - c; const coord_t divisor = cross(l1_delta, l2_delta); // Pre-compute divisor needed for the intersection check. if (divisor == 0) { @@ -82,9 +82,9 @@ class LinearAlg2D // Parametric equation is L = P + Vt (where P and V are a starting point and directional vector). // We'll map the starting point of one line onto the parameter system of the other line. // Then using the divisor we can see whether and where they cross. - const Point starts_delta = a - c; + const Point2LL starts_delta = a - c; const coord_t l1_parametric = cross(l2_delta, starts_delta); - Point result = a + Point(round_divide_signed(l1_parametric * l1_delta.X, divisor), round_divide_signed(l1_parametric * l1_delta.Y, divisor)); + Point2LL result = a + Point2LL(round_divide_signed(l1_parametric * l1_delta.X, divisor), round_divide_signed(l1_parametric * l1_delta.Y, divisor)); if (std::abs(result.X) > std::numeric_limits::max() || std::abs(result.Y) > std::numeric_limits::max()) { @@ -107,10 +107,10 @@ class LinearAlg2D * \param b The end point of the line segment * \return the sign of the projection wrt the line segment */ - inline static short pointIsProjectedBeyondLine(const Point& from, const Point& a, const Point& b) + inline static short pointIsProjectedBeyondLine(const Point2LL& from, const Point2LL& a, const Point2LL& b) { - const Point vec = b - a; - const Point point_vec = from - a; + const Point2LL vec = b - a; + const Point2LL point_vec = from - a; const coord_t dot_prod = dot(point_vec, vec); if (dot_prod < 0) { // point is projected to before ab @@ -126,10 +126,10 @@ class LinearAlg2D /*! * Find the point closest to \p from on the line segment from \p p0 to \p p1 */ - static Point getClosestOnLineSegment(const Point& from, const Point& p0, const Point& p1) + static Point2LL getClosestOnLineSegment(const Point2LL& from, const Point2LL& p0, const Point2LL& p1) { - const Point direction = p1 - p0; - const Point to_from = from - p0; + const Point2LL direction = p1 - p0; + const Point2LL to_from = from - p0; const coord_t projected_x = dot(to_from, direction); const coord_t x_p0 = 0; @@ -162,17 +162,17 @@ class LinearAlg2D /*! * Find the point closest to \p from on the line through \p p0 to \p p1 */ - static Point getClosestOnLine(const Point& from, const Point& p0, const Point& p1) + static Point2LL getClosestOnLine(const Point2LL& from, const Point2LL& p0, const Point2LL& p1) { if (p1 == p0) { return p0; } - const Point direction = p1 - p0; - const Point to_from = from - p0; + const Point2LL direction = p1 - p0; + const Point2LL to_from = from - p0; const coord_t projected_x = dot(to_from, direction); - Point ret = p0 + projected_x / vSize(direction) * direction / vSize(direction); + Point2LL ret = p0 + projected_x / vSize(direction) * direction / vSize(direction); return ret; } @@ -187,7 +187,7 @@ class LinearAlg2D * \param b2 second point on line b * \return A pair: the first point on line a and the second pouint on line b */ - static std::pair getClosestConnection(Point a1, Point a2, Point b1, Point b2); + static std::pair getClosestConnection(Point2LL a1, Point2LL a2, Point2LL b1, Point2LL b2); /*! * Get the squared distance from point \p b to a line *segment* from \p a to \p c. @@ -199,7 +199,7 @@ class LinearAlg2D * \param c the second point on the line segment * \param b_is_beyond_ac optional output parameter: whether \p b is closest to the line segment (0), to \p a (-1) or \p b (1) */ - static coord_t getDist2FromLineSegment(const Point& a, const Point& b, const Point& c, int16_t* b_is_beyond_ac = nullptr) + static coord_t getDist2FromLineSegment(const Point2LL& a, const Point2LL& b, const Point2LL& c, int16_t* b_is_beyond_ac = nullptr) { /* * a, @@ -216,10 +216,10 @@ class LinearAlg2D * xb = ab - ax * error = vSize(xb) */ - const Point ac = c - a; + const Point2LL ac = c - a; const coord_t ac_size = vSize(ac); - const Point ab = b - a; + const Point2LL ab = b - a; if (ac_size == 0) { const coord_t ab_dist2 = vSize2(ab); @@ -254,8 +254,8 @@ class LinearAlg2D { *b_is_beyond_ac = 0; } - const Point ax = ac * ax_size / ac_size; - const Point bx = ab - ax; + const Point2LL ax = ac * ax_size / ac_size; + const Point2LL bx = ab - ax; return vSize2(bx); // return vSize2(ab) - ax_size*ax_size; // less accurate } @@ -270,7 +270,7 @@ class LinearAlg2D * \param d Another end point of the second line segment * \param max_dist The maximal distance between the two line segments for which this function will return true. */ - static bool lineSegmentsAreCloserThan(const Point& a, const Point& b, const Point& c, const Point& d, const coord_t max_dist) + static bool lineSegmentsAreCloserThan(const Point2LL& a, const Point2LL& b, const Point2LL& c, const Point2LL& d, const coord_t max_dist) { const coord_t max_dist2 = max_dist * max_dist; @@ -287,7 +287,7 @@ class LinearAlg2D * \param c One end point of the second line segment * \param d Another end point of the second line segment */ - static coord_t getDist2BetweenLineSegments(const Point& a, const Point& b, const Point& c, const Point& d) + static coord_t getDist2BetweenLineSegments(const Point2LL& a, const Point2LL& b, const Point2LL& c, const Point2LL& d) { return std::min(getDist2FromLineSegment(a, c, b), std::min(getDist2FromLineSegment(a, d, b), std::min(getDist2FromLineSegment(c, a, d), getDist2FromLineSegment(c, b, d)))); } @@ -306,7 +306,7 @@ class LinearAlg2D * \param b_from_transformed The transformed to location of line b * \return Whether the two line segments collide */ - static bool lineSegmentsCollide(const Point& a_from_transformed, const Point& a_to_transformed, Point b_from_transformed, Point b_to_transformed); + static bool lineSegmentsCollide(const Point2LL& a_from_transformed, const Point2LL& a_to_transformed, Point2LL b_from_transformed, Point2LL b_to_transformed); /*! * Compute the angle between two consecutive line segments. @@ -325,7 +325,7 @@ class LinearAlg2D * \param c end of second line segment * \return the angle in radians between 0 and 2 * pi of the corner in \p b */ - static double getAngleLeft(const Point& a, const Point& b, const Point& c); + static double getAngleLeft(const Point2LL& a, const Point2LL& b, const Point2LL& c); /*! * Returns the determinant of the 2D matrix defined by the the vectors ab and ap as rows. @@ -338,7 +338,7 @@ class LinearAlg2D * \param b the to point of the line * \return a positive value when \p p lies to the left of the line from \p a to \p b */ - static inline coord_t pointIsLeftOfLine(const Point& p, const Point& a, const Point& b) + static inline coord_t pointIsLeftOfLine(const Point2LL& p, const Point2LL& a, const Point2LL& b) { return (b.X - a.X) * (p.Y - a.Y) - (b.Y - a.Y) * (p.X - a.X); } @@ -355,7 +355,7 @@ class LinearAlg2D * \param[out] result The result (if any was found) * \return Whether any such point has been found */ - static bool getPointOnLineWithDist(const Point& p, const Point& a, const Point& b, const coord_t dist, Point& result); + static bool getPointOnLineWithDist(const Point2LL& p, const Point2LL& a, const Point2LL& b, const coord_t dist, Point2LL& result); /*! * Get the squared distance from a point \p p to the line on which \p a and @@ -365,7 +365,7 @@ class LinearAlg2D * \param b One of the points through which the line goes. * \return The distance between the point and the line, squared. */ - static coord_t getDist2FromLine(const Point& p, const Point& a, const Point& b); + static coord_t getDist2FromLine(const Point2LL& p, const Point2LL& a, const Point2LL& b); /*! * Get the distance from a point \p p to the line on which \p a and \p b lie. @@ -378,7 +378,7 @@ class LinearAlg2D * \param b One of the points through which the line goes. * \return The distance between the point and the line. */ - static coord_t getDistFromLine(const Point& p, const Point& a, const Point& b); + static coord_t getDistFromLine(const Point2LL& p, const Point2LL& a, const Point2LL& b); /*! * Check whether a corner is acute or obtuse. @@ -393,17 +393,17 @@ class LinearAlg2D * \param c end of second line segment * \return positive if acute, negative if obtuse, zero if 90 degree corner */ - static inline int isAcuteCorner(const Point& a, const Point& b, const Point& c) + static inline int isAcuteCorner(const Point2LL& a, const Point2LL& b, const Point2LL& c) { - const Point ba = a - b; - const Point bc = c - b; + const Point2LL ba = a - b; + const Point2LL bc = c - b; return dot(ba, bc); } /*! * Get the rotation matrix for rotating around a specific point in place. */ - static Point3Matrix rotateAround(const Point& middle, double rotation) + static Point3Matrix rotateAround(const Point2LL& middle, double rotation) { PointMatrix rotation_matrix(rotation); Point3Matrix rotation_matrix_homogeneous(rotation_matrix); @@ -417,7 +417,7 @@ class LinearAlg2D * * Test whether the \p query_point is inside of a polygon w.r.t a single corner. */ - static bool isInsideCorner(const Point a, const Point b, const Point c, const Point query_point); + static bool isInsideCorner(const Point2LL a, const Point2LL b, const Point2LL c, const Point2LL query_point); /*! * Finds the vector for the bisection of a-b as seen from the intersection point. @@ -429,7 +429,7 @@ class LinearAlg2D * \param b The second point. * \param vec_len The lenght of the resultant vector. It's not wise to set this to 1, since we do tend to do integer math here. */ - static Point getBisectorVector(const Point& intersect, const Point& a, const Point& b, const coord_t vec_len); + static Point2LL getBisectorVector(const Point2LL& intersect, const Point2LL& a, const Point2LL& b, const coord_t vec_len); }; diff --git a/include/utils/orderOptimizer.h b/include/utils/orderOptimizer.h index a72a447b54..e990cecbac 100644 --- a/include/utils/orderOptimizer.h +++ b/include/utils/orderOptimizer.h @@ -8,7 +8,7 @@ #include #include #include // pair -#include "IntPoint.h" +#include "Point2LL.h" namespace cura { @@ -23,29 +23,29 @@ template class OrderOptimizer { public: - std::vector> items; //!< the items in arbitrary order + std::vector> items; //!< the items in arbitrary order OrderOptimizer() { } - void addItem(const Point location, const T item); + void addItem(const Point2LL location, const T item); /*! * Optimize the order of \ref OrderOptimizer::items * \return A vector of the ordered indices into \ref OrderOptimizer::items */ - std::list optimize(const Point& start_position); + std::list optimize(const Point2LL& start_position); }; template -void OrderOptimizer::addItem(const Point location, const T item) +void OrderOptimizer::addItem(const Point2LL location, const T item) { items.emplace_back(location, item); } template -std::list OrderOptimizer::optimize(const Point& start_position) +std::list OrderOptimizer::optimize(const Point2LL& start_position) { // Use the nearest mesh ordering std::list order; @@ -60,7 +60,7 @@ std::list OrderOptimizer::optimize(const Point& start_position) { item_idx_list.emplace_back(i); } - const Point* last_item_position = &start_position; + const Point2LL* last_item_position = &start_position; while (!item_idx_list.empty()) { @@ -71,7 +71,7 @@ std::list OrderOptimizer::optimize(const Point& start_position) for (size_t idx = 0; idx < item_idx_list.size(); idx++) { const size_t item_idx = item_idx_list[idx]; - const Point& position = items[item_idx].first; + const Point2LL& position = items[item_idx].first; const coord_t distance = vSize(position - *last_item_position); if (distance < shortest_distance) { diff --git a/include/utils/polygon.h b/include/utils/polygon.h index 7036e256d5..5b3eb781af 100644 --- a/include/utils/polygon.h +++ b/include/utils/polygon.h @@ -17,7 +17,7 @@ #include "../settings/types/Angle.h" //For angles between vertices. #include "../settings/types/Ratio.h" -#include "IntPoint.h" +#include "Point2LL.h" #define CHECK_POLY_ACCESS #ifdef CHECK_POLY_ACCESS @@ -56,7 +56,7 @@ class PolygonRef; class ListPolyIt; -typedef std::list ListPolygon; //!< A polygon represented by a linked list instead of a vector +typedef std::list ListPolygon; //!< A polygon represented by a linked list instead of a vector typedef std::vector ListPolygons; //!< Polygons represented by a vector of linked lists instead of a vector of vectors const static int clipper_init = (0); @@ -108,7 +108,7 @@ class ConstPolygonRef */ bool empty() const; - const Point& operator[](size_t index) const + const Point2LL& operator[](size_t index) const { POLY_ASSERT(index < size()); return (*path)[index]; @@ -175,10 +175,10 @@ class ConstPolygonRef coord_t polylineLength() const { coord_t length = 0; - Point p0 = path->front(); + Point2LL p0 = path->front(); for (size_t n = 1; n < path->size(); n++) { - Point p1 = (*path)[n]; + Point2LL p1 = (*path)[n]; length += vSize(p0 - p1); p0 = p1; } @@ -201,10 +201,10 @@ class ConstPolygonRef bool shorterThan(const coord_t check_length) const; - Point min() const + Point2LL min() const { - Point ret = Point(POINT_MAX, POINT_MAX); - for (Point p : *path) + Point2LL ret = Point2LL(POINT_MAX, POINT_MAX); + for (Point2LL p : *path) { ret.X = std::min(ret.X, p.X); ret.Y = std::min(ret.Y, p.Y); @@ -212,10 +212,10 @@ class ConstPolygonRef return ret; } - Point max() const + Point2LL max() const { - Point ret = Point(POINT_MIN, POINT_MIN); - for (Point p : *path) + Point2LL ret = Point2LL(POINT_MIN, POINT_MIN); + for (Point2LL p : *path) { ret.X = std::max(ret.X, p.X); ret.Y = std::max(ret.Y, p.Y); @@ -228,17 +228,17 @@ class ConstPolygonRef return ClipperLib::Area(*path); } - Point centerOfMass() const + Point2LL centerOfMass() const { if (path->size() > 0) { - Point p0 = (*path)[0]; + Point2LL p0 = (*path)[0]; if (path->size() > 1) { double x = 0, y = 0; for (size_t n = 1; n <= path->size(); n++) { - Point p1 = (*path)[n % path->size()]; + Point2LL p1 = (*path)[n % path->size()]; double second_factor = static_cast((p0.X * p1.Y) - (p1.X * p0.Y)); x += double(p0.X + p1.X) * second_factor; @@ -251,7 +251,7 @@ class ConstPolygonRef x = x / 6 / area; y = y / 6 / area; - return Point(std::llrint(x), std::llrint(y)); + return Point2LL(std::llrint(x), std::llrint(y)); } else { @@ -260,13 +260,13 @@ class ConstPolygonRef } else { - return Point(); + return Point2LL(); } } - Point closestPointTo(Point p) const + Point2LL closestPointTo(Point2LL p) const { - Point ret = p; + Point2LL ret = p; double bestDist = std::numeric_limits::max(); for (size_t n = 0; n < path->size(); n++) { @@ -298,7 +298,7 @@ class ConstPolygonRef * \param border_result What to return when the point is exactly on the border * \return Whether the point \p p is inside this polygon (or \p border_result when it is on the border) */ - bool _inside(Point p, bool border_result = false) const; + bool _inside(Point2LL p, bool border_result = false) const; /*! * Clipper function. @@ -306,7 +306,7 @@ class ConstPolygonRef * * http://www.angusj.com/delphi/clipper/documentation/Docs/Units/ClipperLib/Functions/PointInPolygon.htm */ - bool inside(Point p, bool border_result = false) const + bool inside(Point2LL p, bool border_result = false) const { int res = ClipperLib::PointInPolygon(p, *path); if (res == -1) @@ -389,15 +389,15 @@ class ConstPolygonRef * \param cos_angle The cosine on the angle in L 012 */ static void smooth_corner_simple( - const Point p0, - const Point p1, - const Point p2, + const Point2LL p0, + const Point2LL p1, + const Point2LL p2, const ListPolyIt p0_it, const ListPolyIt p1_it, const ListPolyIt p2_it, - const Point v10, - const Point v12, - const Point v02, + const Point2LL v10, + const Point2LL v12, + const Point2LL v02, const int64_t shortcut_length, double cos_angle); @@ -415,7 +415,7 @@ class ConstPolygonRef * \param shortcut_length The desired length ofthe shortcutting line * \return Whether this whole polygon whould be removed by the smoothing */ - static bool smooth_corner_complex(const Point p1, ListPolyIt& p0_it, ListPolyIt& p2_it, const int64_t shortcut_length); + static bool smooth_corner_complex(const Point2LL p1, ListPolyIt& p0_it, ListPolyIt& p2_it, const int64_t shortcut_length); /*! * Try to take a step away from the corner point in order to take a bigger shortcut. @@ -434,7 +434,7 @@ class ConstPolygonRef * \param[in,out] backward_is_too_far Whether trying another step backward is blocked by the shortcut length condition. Updated for the next iteration. */ static void smooth_outward_step( - const Point p1, + const Point2LL p1, const int64_t shortcut_length2, ListPolyIt& p0_it, ListPolyIt& p2_it, @@ -496,13 +496,13 @@ class PolygonRef : public ConstPolygonRef return *this; } - Point& operator[](unsigned int index) + Point2LL& operator[](unsigned int index) { POLY_ASSERT(index < size()); return (*path)[index]; } - const Point& operator[](unsigned int index) const + const Point2LL& operator[](unsigned int index) const { POLY_ASSERT(index < size()); return (*path)[index]; @@ -533,7 +533,7 @@ class PolygonRef : public ConstPolygonRef return path->data(); } - void add(const Point p) + void add(const Point2LL p) { path->push_back(p); } @@ -555,7 +555,7 @@ class PolygonRef : public ConstPolygonRef path->erase(path->begin() + index); } - void insert(size_t index, Point p) + void insert(size_t index, Point2LL p) { POLY_ASSERT(index < size() && index <= static_cast(std::numeric_limits::max())); path->insert(path->begin() + static_cast(index), p); @@ -576,9 +576,9 @@ class PolygonRef : public ConstPolygonRef * * \param translation The direction in which to move the polygon */ - void translate(Point translation) + void translate(Point2LL translation) { - for (Point& p : *this) + for (Point2LL& p : *this) { p += translation; } @@ -932,7 +932,7 @@ class Polygons /*! * Add a 'polygon' consisting of two points */ - void addLine(const Point from, const Point to) + void addLine(const Point2LL from, const Point2LL to) { paths.emplace_back(ClipperLib::Path{ from, to }); } @@ -1138,7 +1138,7 @@ class Polygons * \param border_result What to return when the point is exactly on the border * \return Whether the point \p p is inside this polygon (or \p border_result when it is on the border) */ - bool inside(Point p, bool border_result = false) const; + bool inside(Point2LL p, bool border_result = false) const; /*! * Check if we are inside the polygon. We do this by tracing from the point towards the positive X direction, @@ -1158,7 +1158,7 @@ class Polygons * \param border_result What to return when the point is exactly on the border * \return Whether the point \p p is inside this polygon (or \p border_result when it is on the border) */ - bool insideOld(Point p, bool border_result = false) const; + bool insideOld(Point2LL p, bool border_result = false) const; /*! * Find the polygon inside which point \p p resides. @@ -1173,7 +1173,7 @@ class Polygons * \param border_result Whether a point exactly on a polygon counts as inside * \return The index of the polygon inside which the point \p p resides */ - unsigned int findInside(Point p, bool border_result = false); + unsigned int findInside(Point2LL p, bool border_result = false); /*! * Approximates the convex hull of the polygons. @@ -1250,7 +1250,7 @@ class Polygons } } - void translate(const Point vec) + void translate(const Point2LL vec) { if (vec.X == 0 && vec.Y == 0) { @@ -1471,12 +1471,12 @@ class Polygons coord_t polyLineLength() const; - Point min() const + Point2LL min() const { - Point ret = Point(POINT_MAX, POINT_MAX); + Point2LL ret = Point2LL(POINT_MAX, POINT_MAX); for (const ClipperLib::Path& polygon : paths) { - for (Point p : polygon) + for (Point2LL p : polygon) { ret.X = std::min(ret.X, p.X); ret.Y = std::min(ret.Y, p.Y); @@ -1485,12 +1485,12 @@ class Polygons return ret; } - Point max() const + Point2LL max() const { - Point ret = Point(POINT_MIN, POINT_MIN); + Point2LL ret = Point2LL(POINT_MIN, POINT_MIN); for (const ClipperLib::Path& polygon : paths) { - for (Point p : polygon) + for (Point2LL p : polygon) { ret.X = std::max(ret.X, p.X); ret.Y = std::max(ret.Y, p.Y); @@ -1547,7 +1547,7 @@ class PolygonsPart : public Polygons * \param border_result If the point is exactly on the border, this will be * returned instead. */ - bool inside(Point p, bool border_result = false) const; + bool inside(Point2LL p, bool border_result = false) const; }; /*! diff --git a/include/utils/polygonUtils.h b/include/utils/polygonUtils.h index 9e2017d1b2..59d71a9354 100644 --- a/include/utils/polygonUtils.h +++ b/include/utils/polygonUtils.h @@ -22,12 +22,12 @@ namespace cura */ struct ClosestPolygonPoint { - Point location_; //!< Result location + Point2LL location_; //!< Result location ConstPolygonPointer poly_; //!< Polygon in which the result was found (or nullptr if no result was found) size_t poly_idx_; //!< The index of the polygon in some Polygons where ClosestPolygonPoint::poly can be found size_t point_idx_; //!< Index to the first point in the polygon of the line segment on which the result was found - ClosestPolygonPoint(Point p, size_t pos, ConstPolygonRef poly) + ClosestPolygonPoint(Point2LL p, size_t pos, ConstPolygonRef poly) : location_(p) , poly_(poly) , poly_idx_(NO_INDEX) @@ -35,7 +35,7 @@ struct ClosestPolygonPoint { } - ClosestPolygonPoint(Point p, size_t pos, ConstPolygonRef poly, size_t poly_idx) + ClosestPolygonPoint(Point2LL p, size_t pos, ConstPolygonRef poly, size_t poly_idx) : location_(p) , poly_(poly) , poly_idx_(poly_idx) @@ -56,7 +56,7 @@ struct ClosestPolygonPoint { } - Point p() const + Point2LL p() const { // conformity with other classes return location_; } @@ -83,7 +83,7 @@ struct hash { size_t operator()(const cura::ClosestPolygonPoint& cpp) const { - return std::hash()(cpp.p()); + return std::hash()(cpp.p()); } }; } // namespace std @@ -110,7 +110,7 @@ namespace cura */ struct GivenDistPoint { - Point location; //!< Result location + Point2LL location; //!< Result location int pos; //!< Index to the first point in the polygon of the line segment on which the result was found }; @@ -119,7 +119,7 @@ typedef SparseLineGrid Loc class PolygonUtils { public: - static const std::function no_penalty_function; //!< Function always returning zero + static const std::function no_penalty_function; //!< Function always returning zero /*! * compute the length of a segment of a polygon @@ -152,19 +152,19 @@ class PolygonUtils /*! * Generate a grid of dots inside of the area of the \p polygons. */ - static std::vector spreadDotsArea(const Polygons& polygons, coord_t grid_size); + static std::vector spreadDotsArea(const Polygons& polygons, coord_t grid_size); - static std::vector spreadDotsArea(const Polygons& polygons, Point grid_size); + static std::vector spreadDotsArea(const Polygons& polygons, Point2LL grid_size); /*! * Whether a polygon intersects with a line-segment. If true, the closest collision point to 'b' is stored in the result. */ static bool lineSegmentPolygonsIntersection( - const Point& a, - const Point& b, + const Point2LL& a, + const Point2LL& b, const Polygons& current_outlines, const LocToLineGrid& outline_locator, - Point& result, + Point2LL& result, const coord_t within_max_dist); /*! @@ -175,7 +175,7 @@ class PolygonUtils * \param poly The polygon. * \param point_idx The index of the point in the polygon. */ - static Point getVertexInwardNormal(ConstPolygonRef poly, unsigned int point_idx); + static Point2LL getVertexInwardNormal(ConstPolygonRef poly, unsigned int point_idx); /*! * Get a point from the \p poly with a given \p offset. @@ -185,7 +185,7 @@ class PolygonUtils * \param offset The distance the point has to be moved outward from the polygon. * \return A point at the given distance inward from the point on the boundary polygon. */ - static Point getBoundaryPointWithOffset(ConstPolygonRef poly, unsigned int point_idx, int64_t offset); + static Point2LL getBoundaryPointWithOffset(ConstPolygonRef poly, unsigned int point_idx, int64_t offset); /*! * Move a point away from the boundary by looking at the boundary normal of the nearest vert. @@ -193,7 +193,7 @@ class PolygonUtils * \param point_on_boundary The object holding the point on the boundary along with the information of which line segment the point is on. * \param offset The distance the point has to be moved inward from the polygon. */ - static Point moveInsideDiagonally(ClosestPolygonPoint point_on_boundary, int64_t inset); + static Point2LL moveInsideDiagonally(ClosestPolygonPoint point_on_boundary, int64_t inset); /*! * Moves the point \p from onto the nearest polygon or leaves the point as-is, when the comb boundary is not within the root of \p max_dist2 distance. @@ -207,7 +207,7 @@ class PolygonUtils * \param max_dist2 The squared maximal allowed distance from the point to the nearest polygon. * \return The index to the polygon onto which we have moved the point. */ - static unsigned int moveInside(const Polygons& polygons, Point& from, int distance = 0, int64_t max_dist2 = std::numeric_limits::max()); + static unsigned int moveInside(const Polygons& polygons, Point2LL& from, int distance = 0, int64_t max_dist2 = std::numeric_limits::max()); /** * \brief Moves the point \p from onto the nearest polygon or leaves the @@ -225,7 +225,7 @@ class PolygonUtils * the polygon. * \return Always returns 0. */ - static unsigned int moveInside(const ConstPolygonRef polygon, Point& from, int distance = 0, int64_t max_dist2 = std::numeric_limits::max()); + static unsigned int moveInside(const ConstPolygonRef polygon, Point2LL& from, int distance = 0, int64_t max_dist2 = std::numeric_limits::max()); /*! * Moves the point \p from onto the nearest polygon or leaves the point as-is, when the comb boundary is not within the root of \p max_dist2 distance. @@ -248,12 +248,12 @@ class PolygonUtils */ static ClosestPolygonPoint moveInside2( const Polygons& polygons, - Point& from, + Point2LL& from, const int distance = 0, const int64_t max_dist2 = std::numeric_limits::max(), const Polygons* loc_to_line_polygons = nullptr, const LocToLineGrid* loc_to_line_grid = nullptr, - const std::function& penalty_function = no_penalty_function); + const std::function& penalty_function = no_penalty_function); /*! * Moves the point \p from onto the nearest segment of \p polygon or leaves the point as-is, when the comb boundary is not within the root of \p max_dist2 distance. @@ -277,11 +277,11 @@ class PolygonUtils static ClosestPolygonPoint moveInside2( const Polygons& loc_to_line_polygons, ConstPolygonRef polygon, - Point& from, + Point2LL& from, const int distance = 0, const int64_t max_dist2 = std::numeric_limits::max(), const LocToLineGrid* loc_to_line_grid = nullptr, - const std::function& penalty_function = no_penalty_function); + const std::function& penalty_function = no_penalty_function); /*! * The opposite of moveInside. @@ -298,7 +298,7 @@ class PolygonUtils * \param penalty_function A function returning a penalty term on the squared distance score of a candidate point. * \return The index to the polygon onto which we have moved the point. */ - static unsigned int moveOutside(const Polygons& polygons, Point& from, int distance = 0, int64_t max_dist2 = std::numeric_limits::max()); + static unsigned int moveOutside(const Polygons& polygons, Point2LL& from, int distance = 0, int64_t max_dist2 = std::numeric_limits::max()); /*! * Compute a point at a distance from a point on the boundary in orthogonal direction to the boundary. @@ -308,7 +308,7 @@ class PolygonUtils * \param distance The distance by which to move the point. * \return A point at a \p distance from the point in \p cpp orthogonal to the boundary there. */ - static Point moveInside(const ClosestPolygonPoint& cpp, const int distance); + static Point2LL moveInside(const ClosestPolygonPoint& cpp, const int distance); /*! * The opposite of moveInside. @@ -320,7 +320,7 @@ class PolygonUtils * \param distance The distance by which to move the point. * \return A point at a \p distance from the point in \p cpp orthogonal to the boundary there. */ - static Point moveOutside(const ClosestPolygonPoint& cpp, const int distance); + static Point2LL moveOutside(const ClosestPolygonPoint& cpp, const int distance); /*! * Moves the point \p from onto the nearest polygon or leaves the point as-is, when the comb boundary is not within \p distance. @@ -347,12 +347,12 @@ class PolygonUtils */ static ClosestPolygonPoint ensureInsideOrOutside( const Polygons& polygons, - Point& from, + Point2LL& from, int preferred_dist_inside, int64_t max_dist2 = std::numeric_limits::max(), const Polygons* loc_to_line_polygons = nullptr, const LocToLineGrid* loc_to_line_grid = nullptr, - const std::function& penalty_function = no_penalty_function); + const std::function& penalty_function = no_penalty_function); /*! * Moves the point \p from onto the nearest polygon or leaves the point as-is, when the comb boundary is not within \p distance. @@ -379,12 +379,12 @@ class PolygonUtils */ static ClosestPolygonPoint ensureInsideOrOutside( const Polygons& polygons, - Point& from, + Point2LL& from, const ClosestPolygonPoint& closest_polygon_point, int preferred_dist_inside, const Polygons* loc_to_line_polygons = nullptr, const LocToLineGrid* loc_to_line_grid = nullptr, - const std::function& penalty_function = no_penalty_function); + const std::function& penalty_function = no_penalty_function); /*! * @@ -400,7 +400,7 @@ class PolygonUtils * \param start_idx The index of the point in the polygon from which to start looking. * \return The nearest point from \p start_idx going along the \p polygon (in both directions) with a locally minimal distance to \p from. */ - static ClosestPolygonPoint findNearestClosest(Point from, ConstPolygonRef polygon, int start_idx); + static ClosestPolygonPoint findNearestClosest(Point2LL from, ConstPolygonRef polygon, int start_idx); /*! * Find the nearest closest point on a polygon from a given index walking in one direction along the polygon. @@ -411,7 +411,7 @@ class PolygonUtils * \param direction The direction to walk: 1 for walking along the \p polygon, -1 for walking in opposite direction * \return The nearest point from \p start_idx going along the \p polygon with a locally minimal distance to \p from. */ - static ClosestPolygonPoint findNearestClosest(const Point from, ConstPolygonRef polygon, int start_idx, int direction); + static ClosestPolygonPoint findNearestClosest(const Point2LL from, ConstPolygonRef polygon, int start_idx, int direction); /*! * Find the point closest to \p from in all polygons in \p polygons. @@ -420,7 +420,7 @@ class PolygonUtils * * \param penalty_function A function returning a penalty term on the squared distance score of a candidate point. */ - static ClosestPolygonPoint findClosest(Point from, const Polygons& polygons, const std::function& penalty_function = no_penalty_function); + static ClosestPolygonPoint findClosest(Point2LL from, const Polygons& polygons, const std::function& penalty_function = no_penalty_function); /*! * Find the point closest to \p from in the polygon \p polygon. @@ -429,7 +429,7 @@ class PolygonUtils * * \param penalty_function A function returning a penalty term on the squared distance score of a candidate point. */ - static ClosestPolygonPoint findClosest(Point from, ConstPolygonRef polygon, const std::function& penalty_function = no_penalty_function); + static ClosestPolygonPoint findClosest(Point2LL from, ConstPolygonRef polygon, const std::function& penalty_function = no_penalty_function); /*! * Find the nearest vertex to \p from in \p polys @@ -437,7 +437,7 @@ class PolygonUtils * \param polys The polygons in which to search * \return The nearest vertex on the polygons */ - static PolygonsPointIndex findNearestVert(const Point from, const Polygons& polys); + static PolygonsPointIndex findNearestVert(const Point2LL from, const Polygons& polys); /*! * Find the nearest vertex to \p from in \p poly @@ -445,7 +445,7 @@ class PolygonUtils * \param poly The polygon in which to search * \return The index to the nearest vertex on the polygon */ - static unsigned int findNearestVert(const Point from, ConstPolygonRef poly); + static unsigned int findNearestVert(const Point2LL from, ConstPolygonRef poly); /*! * Create a SparsePointGridInclusive mapping from locations to line segments occurring in the \p polygons @@ -471,7 +471,7 @@ class PolygonUtils * \return The nearest point on the polygon if the polygon was within a distance equal to the cell_size of the SparsePointGridInclusive */ static std::optional - findClose(Point from, const Polygons& polygons, const LocToLineGrid& loc_to_line, const std::function& penalty_function = no_penalty_function); + findClose(Point2LL from, const Polygons& polygons, const LocToLineGrid& loc_to_line, const std::function& penalty_function = no_penalty_function); /*! * Find the line segment closest to any point on \p from within cell-blocks of a size defined in the SparsePointGridInclusive \p destination_loc_to_line @@ -490,7 +490,7 @@ class PolygonUtils ConstPolygonRef from, const Polygons& destination, const LocToLineGrid& destination_loc_to_line, - const std::function& penalty_function = no_penalty_function); + const std::function& penalty_function = no_penalty_function); /*! * Checks whether a given line segment collides with polygons as given in a loc_to_line grid. @@ -506,7 +506,7 @@ class PolygonUtils * \param[out] collision_result (optional) The polygons segment intersecting with the line segment * \return whether the line segment collides with the boundary of the polygons */ - static bool polygonCollidesWithLineSegment(const Point from, const Point to, const LocToLineGrid& loc_to_line, PolygonsPointIndex* collision_result = nullptr); + static bool polygonCollidesWithLineSegment(const Point2LL from, const Point2LL to, const LocToLineGrid& loc_to_line, PolygonsPointIndex* collision_result = nullptr); /*! * Find the next point (going along the direction of the polygon) with a distance \p dist from the point \p from within the \p poly. @@ -517,7 +517,7 @@ class PolygonUtils * \param start_idx the index of the prev poly point on the poly. * \param poly_start_idx The index of the point in the polygon which is to be handled as the start of the polygon. No point further than this point will be the result. */ - static bool getNextPointWithDistance(Point from, int64_t dist, ConstPolygonRef poly, int start_idx, int poly_start_idx, GivenDistPoint& result); + static bool getNextPointWithDistance(Point2LL from, int64_t dist, ConstPolygonRef poly, int start_idx, int poly_start_idx, GivenDistPoint& result); /*! * Walk a given \p distance along the polygon from a given point \p from on the polygon @@ -536,7 +536,7 @@ class PolygonUtils * \param forward Whether to look forward from \p start in the direction of the polygon, or go in the other direction. * \return The earliest point on the polygon in the given direction which crosses a line parallel to the given one at the distance \p dist - if any */ - static std::optional getNextParallelIntersection(const ClosestPolygonPoint& start, const Point& line_to, const coord_t dist, const bool forward); + static std::optional getNextParallelIntersection(const ClosestPolygonPoint& start, const Point2LL& line_to, const coord_t dist, const bool forward); /*! * Checks whether a given line segment collides with a given polygon(s). @@ -558,7 +558,8 @@ class PolygonUtils * \return whether the line segment collides with the boundary of the * polygon(s) */ - static bool polygonCollidesWithLineSegment(ConstPolygonRef poly, const Point& transformed_startPoint, const Point& transformed_endPoint, PointMatrix transformation_matrix); + static bool + polygonCollidesWithLineSegment(ConstPolygonRef poly, const Point2LL& transformed_startPoint, const Point2LL& transformed_endPoint, PointMatrix transformation_matrix); /*! * Checks whether a given line segment collides with a given polygon(s). @@ -574,7 +575,7 @@ class PolygonUtils * \return whether the line segment collides with the boundary of the * polygon(s) */ - static bool polygonCollidesWithLineSegment(ConstPolygonRef poly, const Point& startPoint, const Point& endPoint); + static bool polygonCollidesWithLineSegment(ConstPolygonRef poly, const Point2LL& startPoint, const Point2LL& endPoint); /*! * Checks whether a given line segment collides with a given polygon(s). @@ -596,7 +597,8 @@ class PolygonUtils * \return whether the line segment collides with the boundary of the * polygon(s) */ - static bool polygonCollidesWithLineSegment(const Polygons& polys, const Point& transformed_startPoint, const Point& transformed_endPoint, PointMatrix transformation_matrix); + static bool + polygonCollidesWithLineSegment(const Polygons& polys, const Point2LL& transformed_startPoint, const Point2LL& transformed_endPoint, PointMatrix transformation_matrix); /*! * Checks whether a given line segment collides with a given polygon(s). @@ -612,7 +614,7 @@ class PolygonUtils * \return whether the line segment collides with the boundary of the * polygon(s) */ - static bool polygonCollidesWithLineSegment(const Polygons& polys, const Point& startPoint, const Point& endPoint); + static bool polygonCollidesWithLineSegment(const Polygons& polys, const Point2LL& startPoint, const Point2LL& endPoint); /*! * Checks whether two polygon groups intersect - does a BB hit check first and if that succeeds, the full intersection @@ -671,7 +673,7 @@ class PolygonUtils * \param a_step The angle between segments of the circle. * \return A new Polygon containing the circle. */ - static Polygon makeCircle(const Point mid, const coord_t radius, const AngleRadians a_step = std::numbers::pi / 8); + static Polygon makeCircle(const Point2LL mid, const coord_t radius, const AngleRadians a_step = std::numbers::pi / 8); /*! * Connect all polygons to their holes using zero widths hole channels, so that the polygons and their outlines are connected together @@ -722,7 +724,7 @@ class PolygonUtils * \param max_dist2 The squared maximal allowed distance from the point to the nearest polygon. * \return The point on the polygon closest to \p from */ - static ClosestPolygonPoint _moveInside2(const ClosestPolygonPoint& closest_polygon_point, const int distance, Point& from, const int64_t max_dist2); + static ClosestPolygonPoint _moveInside2(const ClosestPolygonPoint& closest_polygon_point, const int distance, Point2LL& from, const int64_t max_dist2); }; diff --git a/src/FffGcodeWriter.cpp b/src/FffGcodeWriter.cpp index a43924362d..8c0577e3bc 100644 --- a/src/FffGcodeWriter.cpp +++ b/src/FffGcodeWriter.cpp @@ -200,7 +200,7 @@ unsigned int FffGcodeWriter::findSpiralizedLayerSeamVertexIndex(const SliceDataS // If the user has specified a z-seam location, use the vertex closest to that location for the seam vertex // in the first layer that has a part with insets. This allows the user to alter the seam start location which // could be useful if the spiralization has a problem with a particular seam path. - Point seam_pos(0, 0); + Point2LL seam_pos(0, 0); if (mesh.settings.get("z_seam_type") == EZSeamType::USER_SPECIFIED) { seam_pos = mesh.getZSeamHint(); @@ -217,7 +217,7 @@ unsigned int FffGcodeWriter::findSpiralizedLayerSeamVertexIndex(const SliceDataS // This case is so rare that we don't bother with finding the best polygon to start with. Just start with the first polygon (`spiral_wall[0]`). ConstPolygonRef wall = layer.parts[0].spiral_wall[0]; const size_t n_points = wall.size(); - const Point last_wall_seam_vertex = last_wall[storage.spiralize_seam_vertex_indices[last_layer_nr]]; + const Point2LL last_wall_seam_vertex = last_wall[storage.spiralize_seam_vertex_indices[last_layer_nr]]; // seam_vertex_idx is going to be the index of the seam vertex in the current wall polygon // initially we choose the vertex that is closest to the seam vertex in the last spiralized layer processed @@ -230,10 +230,10 @@ unsigned int FffGcodeWriter::findSpiralizedLayerSeamVertexIndex(const SliceDataS if (vSize(last_wall_seam_vertex - wall[seam_vertex_idx]) >= mesh.settings.get("meshfix_maximum_resolution")) { // get the inward normal of the last layer seam vertex - Point last_wall_seam_vertex_inward_normal = PolygonUtils::getVertexInwardNormal(last_wall, storage.spiralize_seam_vertex_indices[last_layer_nr]); + Point2LL last_wall_seam_vertex_inward_normal = PolygonUtils::getVertexInwardNormal(last_wall, storage.spiralize_seam_vertex_indices[last_layer_nr]); // create a vector from the normal so that we can then test the vertex following the candidate seam vertex to make sure it is on the correct side - Point last_wall_seam_vertex_vector = last_wall_seam_vertex + last_wall_seam_vertex_inward_normal; + Point2LL last_wall_seam_vertex_vector = last_wall_seam_vertex + last_wall_seam_vertex_inward_normal; // now test the vertex following the candidate seam vertex and if it lies to the left of the vector, it's good to use double a = LinearAlg2D::getAngleLeft(last_wall_seam_vertex_vector, last_wall_seam_vertex, wall[(seam_vertex_idx + 1) % n_points]); @@ -546,7 +546,7 @@ void FffGcodeWriter::processNextMeshGroupCode(const SliceDataStorage& storage) Application::getInstance().communication_->sendCurrentPosition(gcode.getPositionXY()); gcode.writeTravel(gcode.getPositionXY(), Application::getInstance().current_slice_->scene.extruders[gcode.getExtruderNr()].settings_.get("speed_travel")); - Point start_pos(storage.model_min.x_, storage.model_min.y_); + Point2LL start_pos(storage.model_min.x_, storage.model_min.y_); gcode.writeTravel(start_pos, Application::getInstance().current_slice_->scene.extruders[gcode.getExtruderNr()].settings_.get("speed_travel")); gcode.processInitialLayerTemperature(storage, gcode.getExtruderNr()); @@ -574,7 +574,7 @@ void FffGcodeWriter::processRaft(const SliceDataStorage& storage) constexpr bool fill_gaps = true; Polygons raft_polygons; // should remain empty, since we only have the lines pattern for the raft... - std::optional last_planned_position = std::optional(); + std::optional last_planned_position = std::optional(); unsigned int current_extruder_nr = base_extruder_nr; @@ -613,7 +613,7 @@ void FffGcodeWriter::processRaft(const SliceDataStorage& storage) const coord_t small_area_width = 0; // A raft never has a small region due to the large horizontal expansion. const coord_t line_spacing = base_settings.get("raft_base_line_spacing"); const coord_t line_spacing_prime_tower = base_settings.get("prime_tower_raft_base_line_spacing"); - const Point& infill_origin = Point(); + const Point2LL& infill_origin = Point2LL(); constexpr bool skip_stitching = false; constexpr bool connected_zigzags = false; constexpr bool use_endpieces = true; @@ -771,7 +771,7 @@ void FffGcodeWriter::processRaft(const SliceDataStorage& storage) constexpr int wall_line_count = 0; const coord_t small_area_width = 0; // A raft never has a small region due to the large horizontal expansion. - const Point infill_origin = Point(); + const Point2LL infill_origin = Point2LL(); constexpr bool skip_stitching = false; constexpr bool connected_zigzags = false; constexpr bool use_endpieces = true; @@ -890,7 +890,7 @@ void FffGcodeWriter::processRaft(const SliceDataStorage& storage) constexpr size_t wall_line_count = 0; const coord_t small_area_width = 0; // A raft never has a small region due to the large horizontal expansion. - const Point& infill_origin = Point(); + const Point2LL& infill_origin = Point2LL(); constexpr bool skip_stitching = false; constexpr bool connected_zigzags = false; constexpr bool connect_polygons = false; // midway connections between polygons can make the surface less smooth @@ -1159,11 +1159,11 @@ void FffGcodeWriter::processSkirtBrim(const SliceDataStorage& storage, LayerPlan } // Start brim close to the prime location - Point start_close_to; + Point2LL start_close_to; if (train.settings_.get("prime_blob_enable")) { const auto prime_pos_is_abs = train.settings_.get("extruder_prime_pos_abs"); - const auto prime_pos = Point(train.settings_.get("extruder_prime_pos_x"), train.settings_.get("extruder_prime_pos_y")); + const auto prime_pos = Point2LL(train.settings_.get("extruder_prime_pos_x"), train.settings_.get("extruder_prime_pos_y")); start_close_to = prime_pos_is_abs ? prime_pos : gcode_layer.getLastPlannedPositionOrStartingPosition() + prime_pos; } else @@ -1214,7 +1214,7 @@ void FffGcodeWriter::processSkirtBrim(const SliceDataStorage& storage, LayerPlan all_brim_lines.back().add(line.front()); } ConstPolygonPointer pp(all_brim_lines.back()); - for (Point p : line) + for (Point2LL p : line) { grid.insert(p, BrimLineReference{ inset_idx, pp }); } @@ -1227,7 +1227,7 @@ void FffGcodeWriter::processSkirtBrim(const SliceDataStorage& storage, LayerPlan for (const std::pair>& p : grid) { const BrimLineReference& here = p.second.val; - Point loc_here = p.second.point; + Point2LL loc_here = p.second.point; std::vector nearby_verts = grid.getNearbyVals(loc_here, searching_radius); for (const BrimLineReference& nearby : nearby_verts) { @@ -1457,12 +1457,12 @@ std::vector FffGcodeWriter::calculateMeshOrder(const SliceDataStorage& s if (mesh.getExtruderIsUsed(extruder_nr)) { const Mesh& mesh_data = mesh_group->meshes[mesh_idx]; - const Point3 middle = (mesh_data.getAABB().min_ + mesh_data.getAABB().max_) / 2; - mesh_idx_order_optimizer.addItem(Point(middle.x_, middle.y_), mesh_idx); + const Point3LL middle = (mesh_data.getAABB().min_ + mesh_data.getAABB().max_) / 2; + mesh_idx_order_optimizer.addItem(Point2LL(middle.x_, middle.y_), mesh_idx); } } const ExtruderTrain& train = Application::getInstance().current_slice_->scene.extruders[extruder_nr]; - const Point layer_start_position(train.settings_.get("layer_start_x"), train.settings_.get("layer_start_y")); + const Point2LL layer_start_position(train.settings_.get("layer_start_x"), train.settings_.get("layer_start_y")); std::list mesh_indices_order = mesh_idx_order_optimizer.optimize(layer_start_position); std::vector ret; @@ -1661,8 +1661,8 @@ bool FffGcodeWriter::processMultiLayerInfill( = std::max(uint64_t(1), round_divide(mesh.settings.get("infill_sparse_thickness"), std::max(mesh.settings.get("layer_height"), coord_t(1)))); infill_angle = mesh.infill_angles.at((gcode_layer.getLayerNr() / combined_infill_layers) % mesh.infill_angles.size()); } - const Point3 mesh_middle = mesh.bounding_box.getMiddle(); - const Point infill_origin(mesh_middle.x_ + mesh.settings.get("infill_offset_x"), mesh_middle.y_ + mesh.settings.get("infill_offset_y")); + const Point3LL mesh_middle = mesh.bounding_box.getMiddle(); + const Point2LL infill_origin(mesh_middle.x_ + mesh.settings.get("infill_offset_x"), mesh_middle.y_ + mesh.settings.get("infill_offset_y")); // Print the thicker infill lines first. (double or more layer thickness, infill combined with previous layers) bool added_something = false; @@ -1750,7 +1750,7 @@ bool FffGcodeWriter::processMultiLayerInfill( if (! infill_lines.empty()) { - std::optional near_start_location; + std::optional near_start_location; if (mesh.settings.get("infill_randomize_start_location")) { srand(gcode_layer.getLayerNr()); @@ -1813,8 +1813,8 @@ bool FffGcodeWriter::processSingleLayerInfill( = std::max(uint64_t(1), round_divide(mesh.settings.get("infill_sparse_thickness"), std::max(mesh.settings.get("layer_height"), coord_t(1)))); infill_angle = mesh.infill_angles.at((static_cast(gcode_layer.getLayerNr()) / combined_infill_layers) % mesh.infill_angles.size()); } - const Point3 mesh_middle = mesh.bounding_box.getMiddle(); - const Point infill_origin(mesh_middle.x_ + mesh.settings.get("infill_offset_x"), mesh_middle.y_ + mesh.settings.get("infill_offset_y")); + const Point3LL mesh_middle = mesh.bounding_box.getMiddle(); + const Point2LL infill_origin(mesh_middle.x_ + mesh.settings.get("infill_offset_x"), mesh_middle.y_ + mesh.settings.get("infill_offset_y")); auto get_cut_offset = [](const bool zig_zaggify, const coord_t line_width, const size_t line_count) { @@ -2036,7 +2036,7 @@ bool FffGcodeWriter::processSingleLayerInfill( { added_something = true; gcode_layer.setIsInside(true); // going to print stuff inside print object - std::optional near_start_location; + std::optional near_start_location; if (mesh.settings.get("infill_randomize_start_location")) { srand(gcode_layer.getLayerNr()); @@ -2582,36 +2582,36 @@ bool FffGcodeWriter::processInsets( return added_something; } -std::optional FffGcodeWriter::getSeamAvoidingLocation(const Polygons& filling_part, int filling_angle, Point last_position) const +std::optional FffGcodeWriter::getSeamAvoidingLocation(const Polygons& filling_part, int filling_angle, Point2LL last_position) const { if (filling_part.empty()) { - return std::optional(); + return std::optional(); } // start with the BB of the outline AABB skin_part_bb(filling_part); PointMatrix rot((double)((-filling_angle + 90) % 360)); // create a matrix to rotate a vector so that it is normal to the skin angle - const Point bb_middle = skin_part_bb.getMiddle(); + const Point2LL bb_middle = skin_part_bb.getMiddle(); // create a vector from the middle of the BB whose length is such that it can be rotated // around the middle of the BB and the end will always be a long way outside of the part's outline // and rotate the vector so that it is normal to the skin angle - const Point vec = rot.apply(Point(0, vSize(skin_part_bb.max_ - bb_middle) * 100)); + const Point2LL vec = rot.apply(Point2LL(0, vSize(skin_part_bb.max_ - bb_middle) * 100)); // find the vertex in the outline that is closest to the end of the rotated vector const PolygonsPointIndex pa = PolygonUtils::findNearestVert(bb_middle + vec, filling_part); // and find another outline vertex, this time using the vector + 180 deg const PolygonsPointIndex pb = PolygonUtils::findNearestVert(bb_middle - vec, filling_part); if (! pa.initialized() || ! pb.initialized()) { - return std::optional(); + return std::optional(); } // now go to whichever of those vertices that is closest to where we are now if (vSize2(pa.p() - last_position) < vSize2(pb.p() - last_position)) { - return std::optional(std::in_place, pa.p()); + return std::optional(std::in_place, pa.p()); } else { - return std::optional(std::in_place, pb.p()); + return std::optional(std::in_place, pb.p()); } } @@ -2920,7 +2920,7 @@ void FffGcodeWriter::processSkinPrintFeature( const bool connect_polygons = mesh.settings.get("connect_skin_polygons"); coord_t max_resolution = mesh.settings.get("meshfix_maximum_resolution"); coord_t max_deviation = mesh.settings.get("meshfix_maximum_deviation"); - const Point infill_origin; + const Point2LL infill_origin; const bool skip_line_stitching = monotonic; constexpr bool fill_gaps = true; constexpr bool connected_zigzags = false; @@ -3046,7 +3046,7 @@ void FffGcodeWriter::processSkinPrintFeature( } else { - std::optional near_start_location; + std::optional near_start_location; const EFillMethod actual_pattern = (gcode_layer.getLayerNr() == 0) ? mesh.settings.get("top_bottom_pattern_0") : mesh.settings.get("top_bottom_pattern"); if (actual_pattern == EFillMethod::LINES || actual_pattern == EFillMethod::ZIG_ZAG) @@ -3224,7 +3224,7 @@ bool FffGcodeWriter::processSupportInfill(const SliceDataStorage& storage, Layer const auto support_connect_zigzags = infill_extruder.settings_.get("support_connect_zigzags"); const auto support_structure = infill_extruder.settings_.get("support_structure"); - const Point infill_origin; + const Point2LL infill_origin; constexpr bool use_endpieces = true; constexpr coord_t pocket_size = 0; @@ -3375,7 +3375,7 @@ bool FffGcodeWriter::processSupportInfill(const SliceDataStorage& storage, Layer constexpr bool spiralize = false; constexpr Ratio flow_ratio = 1.0_r; constexpr bool always_retract = false; - const std::optional start_near_location = std::optional(); + const std::optional start_near_location = std::optional(); gcode_layer.addPolygonsByOptimizer( support_polygons, @@ -3395,7 +3395,7 @@ bool FffGcodeWriter::processSupportInfill(const SliceDataStorage& storage, Layer constexpr bool enable_travel_optimization = false; constexpr coord_t wipe_dist = 0; constexpr Ratio flow_ratio = 1.0; - const std::optional near_start_location = std::optional(); + const std::optional near_start_location = std::optional(); constexpr double fan_speed = GCodePathConfig::FAN_SPEED_DEFAULT; gcode_layer.addLinesByOptimizer( @@ -3483,7 +3483,7 @@ bool FffGcodeWriter::addSupportRoofsToGCode( constexpr coord_t extra_infill_shift = 0; const auto wall_line_count = roof_extruder.settings_.get("support_roof_wall_count"); const coord_t small_area_width = roof_extruder.settings_.get("min_even_wall_line_width") * 2; // Maximum width of a region that can still be filled with one wall. - const Point infill_origin; + const Point2LL infill_origin; constexpr bool skip_stitching = false; constexpr bool fill_gaps = true; constexpr bool use_endpieces = true; @@ -3613,7 +3613,7 @@ bool FffGcodeWriter::addSupportBottomsToGCode(const SliceDataStorage& storage, L const auto wall_line_count = bottom_extruder.settings_.get("support_bottom_wall_count"); const coord_t small_area_width = bottom_extruder.settings_.get("min_even_wall_line_width") * 2; // Maximum width of a region that can still be filled with one wall. - const Point infill_origin; + const Point2LL infill_origin; constexpr bool skip_stitching = false; constexpr bool fill_gaps = true; constexpr bool use_endpieces = true; @@ -3714,7 +3714,7 @@ void FffGcodeWriter::setExtruder_addPrime(const SliceDataStorage& storage, Layer if (train.settings_.get("prime_blob_enable")) // Don't travel to the prime-blob position if not enabled though. { bool prime_pos_is_abs = train.settings_.get("extruder_prime_pos_abs"); - Point prime_pos = Point(train.settings_.get("extruder_prime_pos_x"), train.settings_.get("extruder_prime_pos_y")); + Point2LL prime_pos = Point2LL(train.settings_.get("extruder_prime_pos_x"), train.settings_.get("extruder_prime_pos_y")); gcode_layer.addTravel(prime_pos_is_abs ? prime_pos : gcode_layer.getLastPlannedPositionOrStartingPosition() + prime_pos); gcode_layer.planPrime(); } diff --git a/src/FffPolygonGenerator.cpp b/src/FffPolygonGenerator.cpp index ae79c909fc..fa25f1e1db 100644 --- a/src/FffPolygonGenerator.cpp +++ b/src/FffPolygonGenerator.cpp @@ -672,8 +672,8 @@ void FffPolygonGenerator::processDerivedWallsSkinInfill(SliceMeshStorage& mesh) // SubDivCube Pre-compute Octree if (mesh.settings.get("infill_line_distance") > 0 && mesh.settings.get("infill_pattern") == EFillMethod::CUBICSUBDIV) { - const Point3 mesh_middle = mesh.bounding_box.getMiddle(); - const Point infill_origin(mesh_middle.x_ + mesh.settings.get("infill_offset_x"), mesh_middle.y_ + mesh.settings.get("infill_offset_y")); + const Point3LL mesh_middle = mesh.bounding_box.getMiddle(); + const Point2LL infill_origin(mesh_middle.x_ + mesh.settings.get("infill_offset_x"), mesh_middle.y_ + mesh.settings.get("infill_offset_y")); SubDivCube::precomputeOctree(mesh, infill_origin); } @@ -1145,21 +1145,21 @@ void FffPolygonGenerator::processFuzzyWalls(SliceMeshStorage& mesh) } // 'a' is the (next) new point between p0 and p1 - const Point p0p1 = p1.p_ - p0->p_; + const Point2LL p0p1 = p1.p_ - p0->p_; const int64_t p0p1_size = vSize(p0p1); int64_t p0pa_dist = dist_left_over; if (p0pa_dist >= p0p1_size) { - const Point p = p1.p_ - (p0p1 / 2); + const Point2LL p = p1.p_ - (p0p1 / 2); const double width = (p1.w_ * vSize(p1.p_ - p) + p0->w_ * vSize(p0->p_ - p)) / p0p1_size; result.emplace_back(p, width, p1.perimeter_index_); } for (; p0pa_dist < p0p1_size; p0pa_dist += min_dist_between_points + rand() % range_random_point_dist) { const int r = rand() % (fuzziness * 2) - fuzziness; - const Point perp_to_p0p1 = turn90CCW(p0p1); - const Point fuzz = normal(perp_to_p0p1, r); - const Point pa = p0->p_ + normal(p0p1, p0pa_dist); + const Point2LL perp_to_p0p1 = turn90CCW(p0p1); + const Point2LL fuzz = normal(perp_to_p0p1, r); + const Point2LL pa = p0->p_ + normal(p0p1, p0pa_dist); const double width = (p1.w_ * vSize(p1.p_ - pa) + p0->w_ * vSize(p0->p_ - pa)) / p0p1_size; result.emplace_back(pa + fuzz, width, p1.perimeter_index_); } diff --git a/src/GCodePathConfig.cpp b/src/GCodePathConfig.cpp index 2aacd198ad..6cdfbd5d66 100644 --- a/src/GCodePathConfig.cpp +++ b/src/GCodePathConfig.cpp @@ -3,7 +3,7 @@ #include "GCodePathConfig.h" -#include "utils/IntPoint.h" // INT2MM +#include "utils/Point2LL.h" // INT2MM namespace cura { diff --git a/src/InterlockingGenerator.cpp b/src/InterlockingGenerator.cpp index 13bd3141ae..ba4528eb51 100644 --- a/src/InterlockingGenerator.cpp +++ b/src/InterlockingGenerator.cpp @@ -60,7 +60,7 @@ void InterlockingGenerator::generateInterlockingStructure(std::vector& const DilationKernel air_dilation(GridPoint3(boundary_avoidance, boundary_avoidance, boundary_avoidance), DilationKernel::Type::PRISM); const coord_t cell_width = beam_width_a + beam_width_b; - const Point3 cell_size(cell_width, cell_width, 2 * beam_layer_count); + const Point3LL cell_size(cell_width, cell_width, 2 * beam_layer_count); InterlockingGenerator gen(mesh_a, mesh_b, beam_width_a, beam_width_b, rotation, cell_size, beam_layer_count, interface_dilation, air_dilation, air_filtering); gen.generateInterlockingStructure(); @@ -108,7 +108,7 @@ void InterlockingGenerator::handleThinAreas(const std::unordered_set near_interlock_per_layer.assign(std::min(mesh_a_.layers.size(), mesh_b_.layers.size()), Polygons()); for (const auto& cell : has_all_meshes) { - const Point3 bottom_corner = vu_.toLowerCorner(cell); + const Point3LL bottom_corner = vu_.toLowerCorner(cell); for (int layer_nr = bottom_corner.z_; layer_nr < bottom_corner.z_ + cell_size_.z_ && layer_nr < near_interlock_per_layer.size(); ++layer_nr) { near_interlock_per_layer[layer_nr].add(vu_.toPolygon(cell)); @@ -252,21 +252,21 @@ std::vector> InterlockingGenerator::generateMicrostructure const coord_t width[2] = { middle, cell_size_.x_ - middle }; for (size_t mesh_idx : { 0, 1 }) { - Point offset(mesh_idx ? middle : 0, 0); - Point area_size(width[mesh_idx], cell_size_.y_); + Point2LL offset(mesh_idx ? middle : 0, 0); + Point2LL area_size(width[mesh_idx], cell_size_.y_); PolygonRef poly = cell_area_per_mesh_per_layer[0][mesh_idx].newPoly(); poly.emplace_back(offset); - poly.emplace_back(offset + Point(area_size.X, 0)); + poly.emplace_back(offset + Point2LL(area_size.X, 0)); poly.emplace_back(offset + area_size); - poly.emplace_back(offset + Point(0, area_size.Y)); + poly.emplace_back(offset + Point2LL(0, area_size.Y)); } cell_area_per_mesh_per_layer[1] = cell_area_per_mesh_per_layer[0]; for (Polygons& polys : cell_area_per_mesh_per_layer[1]) { for (PolygonRef poly : polys) { - for (Point& p : poly) + for (Point2LL& p : poly) { std::swap(p.X, p.Y); } @@ -294,13 +294,13 @@ void InterlockingGenerator::applyMicrostructureToOutlines(const std::unordered_s // Only compute cell structure for half the layers, because since our beams are two layers high, every odd layer of the structure will be the same as the layer below. for (const GridPoint3& grid_loc : cells) { - Point3 bottom_corner = vu_.toLowerCorner(grid_loc); + Point3LL bottom_corner = vu_.toLowerCorner(grid_loc); for (size_t mesh_idx = 0; mesh_idx < 2; mesh_idx++) { for (LayerIndex layer_nr = bottom_corner.z_; layer_nr < bottom_corner.z_ + cell_size_.z_ && layer_nr < max_layer_count; layer_nr += beam_layer_count_) { Polygons areas_here = cell_area_per_mesh_per_layer[(layer_nr / beam_layer_count_) % cell_area_per_mesh_per_layer.size()][mesh_idx]; - areas_here.translate(Point(bottom_corner.x_, bottom_corner.y_)); + areas_here.translate(Point2LL(bottom_corner.x_, bottom_corner.y_)); structure_per_layer[mesh_idx][layer_nr / beam_layer_count_].add(areas_here); } } diff --git a/src/LayerPlan.cpp b/src/LayerPlan.cpp index e4ddda09e6..9ad194fb47 100644 --- a/src/LayerPlan.cpp +++ b/src/LayerPlan.cpp @@ -236,14 +236,14 @@ bool LayerPlan::setExtruder(const size_t extruder_nr) { // handle end position of the prev extruder ExtruderTrain* extruder = getLastPlannedExtruderTrain(); const bool end_pos_absolute = extruder->settings_.get("machine_extruder_end_pos_abs"); - Point end_pos(extruder->settings_.get("machine_extruder_end_pos_x"), extruder->settings_.get("machine_extruder_end_pos_y")); + Point2LL end_pos(extruder->settings_.get("machine_extruder_end_pos_x"), extruder->settings_.get("machine_extruder_end_pos_y")); if (! end_pos_absolute) { end_pos += getLastPlannedPositionOrStartingPosition(); } else { - const Point extruder_offset(extruder->settings_.get("machine_nozzle_offset_x"), extruder->settings_.get("machine_nozzle_offset_y")); + const Point2LL extruder_offset(extruder->settings_.get("machine_nozzle_offset_x"), extruder->settings_.get("machine_nozzle_offset_y")); end_pos += extruder_offset; // absolute end pos is given as a head position } if (end_pos_absolute || last_planned_position_) @@ -269,14 +269,14 @@ bool LayerPlan::setExtruder(const size_t extruder_nr) { // handle starting pos of the new extruder ExtruderTrain* extruder = getLastPlannedExtruderTrain(); const bool start_pos_absolute = extruder->settings_.get("machine_extruder_start_pos_abs"); - Point start_pos(extruder->settings_.get("machine_extruder_start_pos_x"), extruder->settings_.get("machine_extruder_start_pos_y")); + Point2LL start_pos(extruder->settings_.get("machine_extruder_start_pos_x"), extruder->settings_.get("machine_extruder_start_pos_y")); if (! start_pos_absolute) { start_pos += getLastPlannedPositionOrStartingPosition(); } else { - Point extruder_offset(extruder->settings_.get("machine_nozzle_offset_x"), extruder->settings_.get("machine_nozzle_offset_y")); + Point2LL extruder_offset(extruder->settings_.get("machine_nozzle_offset_x"), extruder->settings_.get("machine_nozzle_offset_y")); start_pos += extruder_offset; // absolute start pos is given as a head position } if (start_pos_absolute || last_planned_position_) @@ -295,7 +295,7 @@ void LayerPlan::moveInsideCombBoundary(const coord_t distance, const std::option { constexpr coord_t max_dist2 = MM2INT(2.0) * MM2INT(2.0); // if we are further than this distance, we conclude we are not inside even though we thought we were. // this function is to be used to move from the boundary of a part to inside the part - Point p = getLastPlannedPositionOrStartingPosition(); // copy, since we are going to move p + Point2LL p = getLastPlannedPositionOrStartingPosition(); // copy, since we are going to move p if (PolygonUtils::moveInside(comb_boundary_preferred_, p, distance, max_dist2) != NO_INDEX) { // Move inside again, so we move out of tight 90deg corners @@ -319,9 +319,9 @@ void LayerPlan::setPrimeTowerIsPlanned(unsigned int extruder_nr) has_prime_tower_planned_per_extruder_[extruder_nr] = true; } -std::optional> LayerPlan::getFirstTravelDestinationState() const +std::optional> LayerPlan::getFirstTravelDestinationState() const { - std::optional> ret; + std::optional> ret; if (first_travel_destination_) { ret = std::make_pair(*first_travel_destination_, first_travel_destination_is_inside_); @@ -329,7 +329,7 @@ std::optional> LayerPlan::getFirstTravelDestinationState( return ret; } -GCodePath& LayerPlan::addTravel(const Point& p, const bool force_retract, const coord_t z_offset) +GCodePath& LayerPlan::addTravel(const Point2LL& p, const bool force_retract, const coord_t z_offset) { const GCodePathConfig& travel_config = configs_storage_.travel_config_per_extruder[getExtruder()]; @@ -418,14 +418,14 @@ GCodePath& LayerPlan::addTravel(const Point& p, const bool force_retract, const const coord_t maximum_travel_resolution = mesh_or_extruder_settings.get("meshfix_maximum_travel_resolution"); coord_t distance = 0; - Point last_point((last_planned_position_) ? *last_planned_position_ : Point(0, 0)); + Point2LL last_point((last_planned_position_) ? *last_planned_position_ : Point2LL(0, 0)); for (CombPath& combPath : combPaths) { // add all comb paths (don't do anything special for paths which are moving through air) if (combPath.empty()) { continue; } - for (Point& comb_point : combPath) + for (Point2LL& comb_point : combPath) { if (path->points.empty() || vSize2(path->points.back() - comb_point) > maximum_travel_resolution * maximum_travel_resolution) { @@ -482,7 +482,7 @@ GCodePath& LayerPlan::addTravel(const Point& p, const bool force_retract, const return ret; } -GCodePath& LayerPlan::addTravel_simple(const Point& p, GCodePath* path) +GCodePath& LayerPlan::addTravel_simple(const Point2LL& p, GCodePath* path) { bool is_first_travel_of_layer = ! static_cast(last_planned_position_); if (is_first_travel_of_layer) @@ -502,7 +502,7 @@ GCodePath& LayerPlan::addTravel_simple(const Point& p, GCodePath* path) void LayerPlan::planPrime(double prime_blob_wipe_length) { forceNewPathStart(); - GCodePath& prime_travel = addTravel_simple(getLastPlannedPositionOrStartingPosition() + Point(0, MM2INT(prime_blob_wipe_length))); + GCodePath& prime_travel = addTravel_simple(getLastPlannedPositionOrStartingPosition() + Point2LL(0, MM2INT(prime_blob_wipe_length))); prime_travel.retract = false; prime_travel.perform_z_hop = false; prime_travel.perform_prime = true; @@ -510,7 +510,7 @@ void LayerPlan::planPrime(double prime_blob_wipe_length) } void LayerPlan::addExtrusionMove( - const Point p, + const Point2LL p, const GCodePathConfig& config, const SpaceFillType space_fill_type, const Ratio& flow, @@ -540,12 +540,12 @@ void LayerPlan::addPolygon( bool always_retract) { constexpr Ratio width_ratio = 1.0_r; // Not printed with variable line width. - Point p0 = polygon[start_idx]; + Point2LL p0 = polygon[start_idx]; addTravel(p0, always_retract, config.z_offset); const int direction = backwards ? -1 : 1; for (size_t point_idx = 1; point_idx < polygon.size(); point_idx++) { - Point p1 = polygon[(start_idx + point_idx * direction + polygon.size()) % polygon.size()]; + Point2LL p1 = polygon[(start_idx + point_idx * direction + polygon.size()) % polygon.size()]; addExtrusionMove(p1, config, SpaceFillType::Polygons, flow_ratio, width_ratio, spiralize); p0 = p1; } @@ -559,12 +559,12 @@ void LayerPlan::addPolygon( int distance_traversed = 0; for (size_t point_idx = 1;; point_idx++) { - Point p1 = polygon[(start_idx + point_idx * direction + polygon.size()) % polygon.size()]; + Point2LL p1 = polygon[(start_idx + point_idx * direction + polygon.size()) % polygon.size()]; int p0p1_dist = vSize(p1 - p0); if (distance_traversed + p0p1_dist >= wall_0_wipe_dist) { - Point vector = p1 - p0; - Point half_way = p0 + normal(vector, wall_0_wipe_dist - distance_traversed); + Point2LL vector = p1 - p0; + Point2LL half_way = p0 + normal(vector, wall_0_wipe_dist - distance_traversed); addTravel_simple(half_way); break; } @@ -593,7 +593,7 @@ void LayerPlan::addPolygonsByOptimizer( const Ratio flow_ratio, bool always_retract, bool reverse_order, - const std::optional start_near_location) + const std::optional start_near_location) { if (polygons.empty()) { @@ -626,8 +626,8 @@ void LayerPlan::addPolygonsByOptimizer( static constexpr double max_non_bridge_line_volume = MM2INT(100); // limit to accumulated "volume" of non-bridge lines which is proportional to distance x extrusion rate void LayerPlan::addWallLine( - const Point& p0, - const Point& p1, + const Point2LL& p0, + const Point2LL& p1, const Settings& settings, const GCodePathConfig& non_bridge_config, const GCodePathConfig& bridge_config, @@ -646,7 +646,7 @@ void LayerPlan::addWallLine( const Ratio bridge_wall_coast = settings.get("bridge_wall_coast"); const Ratio overhang_speed_factor = settings.get("wall_overhang_speed_factor"); - Point cur_point = p0; + Point2LL cur_point = p0; // helper function to add a single non-bridge line @@ -654,14 +654,14 @@ void LayerPlan::addWallLine( // alternatively, if the line follows a bridge line, it may be segmented and the print speed gradually increased to reduce under-extrusion - auto addNonBridgeLine = [&](const Point& line_end) + auto addNonBridgeLine = [&](const Point2LL& line_end) { coord_t distance_to_line_end = vSize(cur_point - line_end); while (distance_to_line_end > min_line_len) { // if we are accelerating after a bridge line, the segment length is less than the whole line length - Point segment_end = (speed_factor == 1 || distance_to_line_end < acceleration_segment_len) + Point2LL segment_end = (speed_factor == 1 || distance_to_line_end < acceleration_segment_len) ? line_end : cur_point + (line_end - cur_point) * acceleration_segment_len / distance_to_line_end; @@ -788,8 +788,8 @@ void LayerPlan::addWallLine( ConstPolygonRef bridge = line_polys[nearest]; // set b0 to the nearest vertex and b1 the furthest - Point b0 = bridge[0]; - Point b1 = bridge[1]; + Point2LL b0 = bridge[0]; + Point2LL b1 = bridge[1]; if (vSize2f(cur_point - b1) < vSize2f(cur_point - b0)) { @@ -870,7 +870,7 @@ void LayerPlan::addWall( std::for_each( wall.begin(), wall.end(), - [&dummy_perimeter_id, &nominal_line_width, &ewall](const Point& p) + [&dummy_perimeter_id, &nominal_line_width, &ewall](const Point2LL& p) { ewall.emplace_back(p, nominal_line_width, dummy_perimeter_id); }); @@ -956,8 +956,8 @@ void LayerPlan::addWall( ConstPolygonRef bridge = line_polys[nearest]; // set b0 to the nearest vertex and b1 the furthest - Point b0 = bridge[0]; - Point b1 = bridge[1]; + Point2LL b0 = bridge[0]; + Point2LL b1 = bridge[1]; if (vSize2f(p0.p_ - b1) < vSize2f(p0.p_ - b0)) { @@ -1036,7 +1036,7 @@ void LayerPlan::addWall( is not too short at the end. */ const coord_t delta_line_width = p1.w_ - p0.w_; - const Point line_vector = p1.p_ - p0.p_; + const Point2LL line_vector = p1.p_ - p0.p_; const coord_t line_length = vSize(line_vector); /* Calculate how much the line would deviate from the trapezoidal shape if printed at average width. @@ -1056,7 +1056,7 @@ void LayerPlan::addWall( { const double average_progress = (double(piece) + 0.5) / pieces; // How far along this line to sample the line width in the middle of this piece. const coord_t line_width = p0.w_ + average_progress * delta_line_width; - const Point destination = p0.p_ + normal(line_vector, piece_length * (piece + 1)); + const Point2LL destination = p0.p_ + normal(line_vector, piece_length * (piece + 1)); if (is_small_feature) { constexpr bool spiralize = false; @@ -1071,7 +1071,7 @@ void LayerPlan::addWall( } else { - const Point origin = p0.p_ + normal(line_vector, piece_length * piece); + const Point2LL origin = p0.p_ + normal(line_vector, piece_length * piece); addWallLine( origin, destination, @@ -1110,8 +1110,8 @@ void LayerPlan::addWall( int p0p1_dist = vSize(p1 - p0); if (distance_traversed + p0p1_dist >= wall_0_wipe_dist) { - Point vector = p1.p_ - p0.p_; - Point half_way = p0.p_ + normal(vector, wall_0_wipe_dist - distance_traversed); + Point2LL vector = p1.p_ - p0.p_; + Point2LL half_way = p0.p_ + normal(vector, wall_0_wipe_dist - distance_traversed); addTravel_simple(half_way); break; } @@ -1178,7 +1178,7 @@ void LayerPlan::addLinesByOptimizer( const bool enable_travel_optimization, const coord_t wipe_dist, const Ratio flow_ratio, - const std::optional near_start_location, + const std::optional near_start_location, const double fan_speed, const bool reverse_print_direction, const std::unordered_multimap& order_requirements) @@ -1239,7 +1239,7 @@ void LayerPlan::addLinesInGivenOrder( ConstPolygonRef polyline = *path.vertices_; const size_t start_idx = path.start_vertex_; assert(start_idx == 0 || start_idx == polyline.size() - 1 || path.is_closed_); - const Point start = polyline[start_idx]; + const Point2LL start = polyline[start_idx]; if (vSize2(getLastPlannedPositionOrStartingPosition() - start) < line_width_2) { @@ -1256,7 +1256,7 @@ void LayerPlan::addLinesInGivenOrder( addTravel(start, false, config.z_offset); } - Point p0 = start; + Point2LL p0 = start; for (size_t idx = 0; idx < polyline.size(); idx++) { size_t point_idx; @@ -1273,7 +1273,7 @@ void LayerPlan::addLinesInGivenOrder( assert(start_idx == polyline.size() - 1); point_idx = start_idx - idx; } - Point p1 = polyline[point_idx]; + Point2LL p1 = polyline[point_idx]; // ignore line segments that are less than 5uM long if (vSize2(p1 - p0) >= MINIMUM_SQUARED_LINE_LENGTH) @@ -1286,7 +1286,7 @@ void LayerPlan::addLinesInGivenOrder( } } - Point p1 = polyline[(start_idx == 0) ? polyline.size() - 1 : 0]; + Point2LL p1 = polyline[(start_idx == 0) ? polyline.size() - 1 : 0]; p0 = (polyline.size() <= 1) ? p1 : polyline[(start_idx == 0) ? polyline.size() - 2 : 1]; // Wipe @@ -1307,7 +1307,7 @@ void LayerPlan::addLinesInGivenOrder( const PathOrdering& next_path = paths[order_idx + 1]; ConstPolygonRef next_polygon = *next_path.vertices_; const size_t next_start = next_path.start_vertex_; - const Point& next_p0 = next_polygon[next_start]; + const Point2LL& next_p0 = next_polygon[next_start]; if (vSize2(next_p0 - p1) <= line_width * line_width * 4) { wipe = false; @@ -1340,7 +1340,7 @@ void LayerPlan::addLinesMonotonic( { const Polygons exclude_areas = area.tubeShape(exclude_distance, exclude_distance); const coord_t exclude_dist2 = exclude_distance * exclude_distance; - const Point last_position = getLastPlannedPositionOrStartingPosition(); + const Point2LL last_position = getLastPlannedPositionOrStartingPosition(); // First lay all adjacent lines next to each other, to have a sensible input to the monotonic part of the algorithm. PathOrderOptimizer line_order(last_position); @@ -1397,7 +1397,7 @@ void LayerPlan::spiralizeWallSlice( constexpr Ratio width_factor = 1.0_r; // once we are into the spiral we always start at the end point of the last layer (if any) - const Point origin = (last_seam_vertex_idx >= 0 && ! is_bottom_layer) ? last_wall[last_seam_vertex_idx] : wall[seam_vertex_idx]; + const Point2LL origin = (last_seam_vertex_idx >= 0 && ! is_bottom_layer) ? last_wall[last_seam_vertex_idx] : wall[seam_vertex_idx]; // NOTE: this used to use addTravel_simple() but if support is being generated then combed travel is required to avoid // the nozzle crossing the model on its return from printing the support. addTravel(origin); @@ -1407,7 +1407,7 @@ void LayerPlan::spiralizeWallSlice( // when not smoothing, we get to the (unchanged) outline for this layer as quickly as possible so that the remainder of the // outline wall has the correct direction - although this creates a little step, the end result is generally better because when the first // outline wall has the wrong direction (due to it starting from the finish point of the last layer) the visual effect is very noticeable - Point join_first_wall_at = LinearAlg2D::getClosestOnLineSegment(origin, wall[seam_vertex_idx % wall.size()], wall[(seam_vertex_idx + 1) % wall.size()]); + Point2LL join_first_wall_at = LinearAlg2D::getClosestOnLineSegment(origin, wall[seam_vertex_idx % wall.size()], wall[(seam_vertex_idx + 1) % wall.size()]); if (vSize(join_first_wall_at - origin) > 10) { constexpr Ratio flow = 1.0_r; @@ -1421,10 +1421,10 @@ void LayerPlan::spiralizeWallSlice( const int max_dist2 = config.getLineWidth() * config.getLineWidth() * 4; // (2 * lineWidth)^2; double total_length = 0.0; // determine the length of the complete wall - Point p0 = origin; + Point2LL p0 = origin; for (int wall_point_idx = 1; wall_point_idx <= n_points; ++wall_point_idx) { - const Point& p1 = wall[(seam_vertex_idx + wall_point_idx) % n_points]; + const Point2LL& p1 = wall[(seam_vertex_idx + wall_point_idx) % n_points]; total_length += vSizeMM(p1 - p0); p0 = p1; } @@ -1476,7 +1476,7 @@ void LayerPlan::spiralizeWallSlice( for (int wall_point_idx = 1; wall_point_idx <= n_points; ++wall_point_idx) { // p is a point from the current wall polygon - const Point& p = wall[(seam_vertex_idx + wall_point_idx) % n_points]; + const Point2LL& p = wall[(seam_vertex_idx + wall_point_idx) % n_points]; wall_length += vSizeMM(p - p0); p0 = p; @@ -1517,7 +1517,7 @@ void LayerPlan::spiralizeWallSlice( wall_length = 0; for (int wall_point_idx = 1; wall_point_idx <= n_points && distance_coasted < min_spiral_coast_dist; wall_point_idx++) { - const Point& p = wall[(seam_vertex_idx + wall_point_idx) % n_points]; + const Point2LL& p = wall[(seam_vertex_idx + wall_point_idx) % n_points]; const double seg_length = vSizeMM(p - p0); wall_length += seg_length; p0 = p; @@ -1620,15 +1620,15 @@ double ExtruderPlan::getRetractTime(const GCodePath& path) return retraction_config_.distance / (path.retract ? retraction_config_.speed : retraction_config_.primeSpeed); } -std::pair ExtruderPlan::getPointToPointTime(const Point& p0, const Point& p1, const GCodePath& path) +std::pair ExtruderPlan::getPointToPointTime(const Point2LL& p0, const Point2LL& p1, const GCodePath& path) { const double length = vSizeMM(p0 - p1); return { length, length / (path.config.getSpeed() * path.speed_factor) }; } -TimeMaterialEstimates ExtruderPlan::computeNaiveTimeEstimates(Point starting_position) +TimeMaterialEstimates ExtruderPlan::computeNaiveTimeEstimates(Point2LL starting_position) { - Point p0 = starting_position; + Point2LL p0 = starting_position; const double min_path_speed = fan_speed_layer_time_settings_.cool_min_speed; slowest_path_speed_ = std::accumulate( @@ -1680,7 +1680,7 @@ TimeMaterialEstimates ExtruderPlan::computeNaiveTimeEstimates(Point starting_pos path.estimates.unretracted_travel_time += 0.5 * retract_unretract_time; } } - for (Point& p1 : path.points) + for (Point2LL& p1 : path.points) { double length = vSizeMM(p0 - p1); if (is_extrusion_path) @@ -1701,7 +1701,7 @@ TimeMaterialEstimates ExtruderPlan::computeNaiveTimeEstimates(Point starting_pos return estimates_; } -void ExtruderPlan::processFanSpeedForMinimalLayerTime(Point starting_position, Duration minTime, double time_other_extr_plans) +void ExtruderPlan::processFanSpeedForMinimalLayerTime(Point2LL starting_position, Duration minTime, double time_other_extr_plans) { /* min layer time @@ -1768,7 +1768,7 @@ void ExtruderPlan::processFanSpeedForFirstLayers() } } -void LayerPlan::processFanSpeedAndMinimalLayerTime(Point starting_position) +void LayerPlan::processFanSpeedAndMinimalLayerTime(Point2LL starting_position) { // the minimum layer time behaviour is only applied to the last extruder. const size_t last_extruder_nr = ranges::max_element( @@ -1778,7 +1778,7 @@ void LayerPlan::processFanSpeedAndMinimalLayerTime(Point starting_position) return a.extruder_nr_ < b.extruder_nr_; }) ->extruder_nr_; - Point starting_position_last_extruder; + Point2LL starting_position_last_extruder; unsigned int last_extruder_idx; double other_extr_plan_time = 0.0; Duration maximum_cool_min_layer_time; @@ -2071,7 +2071,7 @@ void LayerPlan::writeGCode(GCodeExport& gcode) if (! path.perform_z_hop && final_travel_z_ != z_ && extruder_plan_idx == (extruder_plans_.size() - 1) && path_idx == (paths.size() - 1)) { // Before the final travel, move up to the next layer height, on the current spot, with a sensible speed. - Point3 current_position = gcode.getPosition(); + Point3LL current_position = gcode.getPosition(); current_position.z_ = final_travel_z_; gcode.writeTravel(current_position, extruder.settings_.get("speed_z_hop")); @@ -2105,7 +2105,7 @@ void LayerPlan::writeGCode(GCodeExport& gcode) } if (! coasting) // not same as 'else', cause we might have changed [coasting] in the line above... { // normal path to gcode algorithm - Point prev_point = gcode.getPositionXY(); + Point2LL prev_point = gcode.getPositionXY(); for (unsigned int point_idx = 0; point_idx < path.points.size(); point_idx++) { const auto [_, time] = extruder_plan.getPointToPointTime(prev_point, path.points[point_idx], path); @@ -2123,13 +2123,13 @@ void LayerPlan::writeGCode(GCodeExport& gcode) { // SPIRALIZE // If we need to spiralize then raise the head slowly by 1 layer as this path progresses. double totalLength = 0.0; - Point p0 = gcode.getPositionXY(); + Point2LL p0 = gcode.getPositionXY(); for (unsigned int _path_idx = path_idx; _path_idx < paths.size() && ! paths[_path_idx].isTravelPath(); _path_idx++) { GCodePath& _path = paths[_path_idx]; for (unsigned int point_idx = 0; point_idx < _path.points.size(); point_idx++) { - Point p1 = _path.points[point_idx]; + Point2LL p1 = _path.points[point_idx]; totalLength += vSizeMM(p0 - p1); p0 = p1; } @@ -2143,7 +2143,7 @@ void LayerPlan::writeGCode(GCodeExport& gcode) for (unsigned int point_idx = 0; point_idx < spiral_path.points.size(); point_idx++) { - const Point p1 = spiral_path.points[point_idx]; + const Point2LL p1 = spiral_path.points[point_idx]; length += vSizeMM(p0 - p1); p0 = p1; gcode.setZ(std::round(z_ + layer_thickness_ * length / totalLength)); @@ -2288,10 +2288,10 @@ bool LayerPlan::writePathWithCoasting( unsigned int acc_dist_idx_gt_coast_dist = NO_INDEX; // the index of the first point with accumulated_dist more than coasting_dist (= index into accumulated_dist_per_point) // == the point printed BEFORE the start point for coasting - const Point* last = &path.points[path.points.size() - 1]; + const Point2LL* last = &path.points[path.points.size() - 1]; for (unsigned int backward_point_idx = 1; backward_point_idx < path.points.size(); backward_point_idx++) { - const Point& point = path.points[path.points.size() - 1 - backward_point_idx]; + const Point2LL& point = path.points[path.points.size() - 1 - backward_point_idx]; const coord_t distance = vSize(point - *last); accumulated_dist += distance; accumulated_dist_per_point.push_back(accumulated_dist); @@ -2336,15 +2336,15 @@ bool LayerPlan::writePathWithCoasting( const size_t point_idx_before_start = path.points.size() - 1 - acc_dist_idx_gt_coast_dist; - Point start; + Point2LL start; { // computation of begin point of coasting const coord_t residual_dist = actual_coasting_dist - accumulated_dist_per_point[acc_dist_idx_gt_coast_dist - 1]; - const Point& a = path.points[point_idx_before_start]; - const Point& b = path.points[point_idx_before_start + 1]; + const Point2LL& a = path.points[point_idx_before_start]; + const Point2LL& b = path.points[point_idx_before_start + 1]; start = b + normal(a - b, residual_dist); } - Point prev_pt = gcode.getPositionXY(); + Point2LL prev_pt = gcode.getPositionXY(); { // write normal extrude path: Communication* communication = Application::getInstance().communication_; for (size_t point_idx = 0; point_idx <= point_idx_before_start; point_idx++) @@ -2438,7 +2438,7 @@ LayerIndex LayerPlan::getLayerNr() const return layer_nr_; } -Point LayerPlan::getLastPlannedPositionOrStartingPosition() const +Point2LL LayerPlan::getLastPlannedPositionOrStartingPosition() const { return last_planned_position_.value_or(layer_start_pos_per_extruder_[getExtruder()]); } diff --git a/src/LayerPlanBuffer.cpp b/src/LayerPlanBuffer.cpp index c2c85d9b8c..453d55f7f4 100644 --- a/src/LayerPlanBuffer.cpp +++ b/src/LayerPlanBuffer.cpp @@ -80,7 +80,7 @@ void LayerPlanBuffer::flush() void LayerPlanBuffer::addConnectingTravelMove(LayerPlan* prev_layer, const LayerPlan* newest_layer) { - std::optional> new_layer_destination_state = newest_layer->getFirstTravelDestinationState(); + std::optional> new_layer_destination_state = newest_layer->getFirstTravelDestinationState(); if (! new_layer_destination_state) { @@ -88,7 +88,7 @@ void LayerPlanBuffer::addConnectingTravelMove(LayerPlan* prev_layer, const Layer return; } - Point first_location_new_layer = new_layer_destination_state->first; + Point2LL first_location_new_layer = new_layer_destination_state->first; assert(newest_layer->extruder_plans_.front().paths_[0].points.size() == 1); assert(newest_layer->extruder_plans_.front().paths_[0].points[0] == first_location_new_layer); @@ -125,7 +125,7 @@ void LayerPlanBuffer::processFanSpeedLayerTime() // Assume the print head is homed at the start of a mesh group. // This introduces small inaccuracies for the naive layer time estimates of the first layer of the second mesh group. // It's not that bad, though. They are naive estimates any way. - Point starting_position(0, 0); + Point2LL starting_position(0, 0); if (buffer_.size() >= 2) { auto prev_layer_it = newest_layer_it; diff --git a/src/MeshGroup.cpp b/src/MeshGroup.cpp index 4940471de3..c31623cee6 100644 --- a/src/MeshGroup.cpp +++ b/src/MeshGroup.cpp @@ -40,13 +40,13 @@ void* fgets_(char* ptr, size_t len, FILE* f) return nullptr; } -Point3 MeshGroup::min() const +Point3LL MeshGroup::min() const { if (meshes.size() < 1) { - return Point3(0, 0, 0); + return Point3LL(0, 0, 0); } - Point3 ret(std::numeric_limits::max(), std::numeric_limits::max(), std::numeric_limits::max()); + Point3LL ret(std::numeric_limits::max(), std::numeric_limits::max(), std::numeric_limits::max()); for (const Mesh& mesh : meshes) { if (mesh.settings_.get("infill_mesh") || mesh.settings_.get("cutting_mesh") @@ -54,7 +54,7 @@ Point3 MeshGroup::min() const { continue; } - Point3 v = mesh.min(); + Point3LL v = mesh.min(); ret.x_ = std::min(ret.x_, v.x_); ret.y_ = std::min(ret.y_, v.y_); ret.z_ = std::min(ret.z_, v.z_); @@ -62,13 +62,13 @@ Point3 MeshGroup::min() const return ret; } -Point3 MeshGroup::max() const +Point3LL MeshGroup::max() const { if (meshes.size() < 1) { - return Point3(0, 0, 0); + return Point3LL(0, 0, 0); } - Point3 ret(std::numeric_limits::min(), std::numeric_limits::min(), std::numeric_limits::min()); + Point3LL ret(std::numeric_limits::min(), std::numeric_limits::min(), std::numeric_limits::min()); for (const Mesh& mesh : meshes) { if (mesh.settings_.get("infill_mesh") || mesh.settings_.get("cutting_mesh") @@ -76,7 +76,7 @@ Point3 MeshGroup::max() const { continue; } - Point3 v = mesh.max(); + Point3LL v = mesh.max(); ret.x_ = std::max(ret.x_, v.x_); ret.y_ = std::max(ret.y_, v.y_); ret.z_ = std::max(ret.z_, v.z_); @@ -95,7 +95,7 @@ void MeshGroup::clear() void MeshGroup::finalize() { // If the machine settings have been supplied, offset the given position vertices to the center of vertices (0,0,0) is at the bed center. - Point3 meshgroup_offset(0, 0, 0); + Point3LL meshgroup_offset(0, 0, 0); if (! settings.get("machine_center_is_zero")) { meshgroup_offset.x_ = settings.get("machine_width") / 2; @@ -105,13 +105,13 @@ void MeshGroup::finalize() // If a mesh position was given, put the mesh at this position in 3D space. for (Mesh& mesh : meshes) { - Point3 mesh_offset(mesh.settings_.get("mesh_position_x"), mesh.settings_.get("mesh_position_y"), mesh.settings_.get("mesh_position_z")); + Point3LL mesh_offset(mesh.settings_.get("mesh_position_x"), mesh.settings_.get("mesh_position_y"), mesh.settings_.get("mesh_position_z")); if (mesh.settings_.get("center_object")) { - Point3 object_min = mesh.min(); - Point3 object_max = mesh.max(); - Point3 object_size = object_max - object_min; - mesh_offset += Point3(-object_min.x_ - object_size.x_ / 2, -object_min.y_ - object_size.y_ / 2, -object_min.z_); + Point3LL object_min = mesh.min(); + Point3LL object_max = mesh.max(); + Point3LL object_size = object_max - object_min; + mesh_offset += Point3LL(-object_min.x_ - object_size.x_ / 2, -object_min.y_ - object_size.y_ / 2, -object_min.z_); } mesh.translate(mesh_offset + meshgroup_offset); } @@ -126,8 +126,8 @@ void MeshGroup::finalize() void MeshGroup::scaleFromBottom(const Ratio factor_xy, const Ratio factor_z) { - const Point3 center = (max() + min()) / 2; - const Point3 origin(center.x_, center.y_, 0); + const Point3LL center = (max() + min()) / 2; + const Point3LL origin(center.x_, center.y_, 0); const Matrix4x3D transformation = Matrix4x3D::scale(factor_xy, factor_xy, factor_z, origin); for (Mesh& mesh : meshes) @@ -142,7 +142,7 @@ bool loadMeshSTL_ascii(Mesh* mesh, const char* filename, const Matrix4x3D& matri char buffer[1024]; Point3F vertex; int n = 0; - Point3 v0(0, 0, 0), v1(0, 0, 0), v2(0, 0, 0); + Point3LL v0(0, 0, 0), v1(0, 0, 0), v2(0, 0, 0); while (fgets_(buffer, sizeof(buffer), f)) { if (sscanf(buffer, " vertex %f %f %f", &vertex.x_, &vertex.y_, &vertex.z_) == 3) @@ -212,9 +212,9 @@ bool loadMeshSTL_binary(Mesh* mesh, const char* filename, const Matrix4x3D& matr } float* v = ((float*)buffer) + 3; - Point3 v0 = matrix.apply(Point3F(v[0], v[1], v[2]).toPoint3d()); - Point3 v1 = matrix.apply(Point3F(v[3], v[4], v[5]).toPoint3d()); - Point3 v2 = matrix.apply(Point3F(v[6], v[7], v[8]).toPoint3d()); + Point3LL v0 = matrix.apply(Point3F(v[0], v[1], v[2]).toPoint3d()); + Point3LL v1 = matrix.apply(Point3F(v[3], v[4], v[5]).toPoint3d()); + Point3LL v2 = matrix.apply(Point3F(v[6], v[7], v[8]).toPoint3d()); mesh->addFace(v0, v1, v2); } fclose(f); diff --git a/src/Mold.cpp b/src/Mold.cpp index d46a9ef402..c5149467af 100644 --- a/src/Mold.cpp +++ b/src/Mold.cpp @@ -10,7 +10,7 @@ #include "settings/types/Ratio.h" #include "sliceDataStorage.h" #include "slicer.h" -#include "utils/IntPoint.h" +#include "utils/Point2LL.h" namespace cura { diff --git a/src/PrimeTower.cpp b/src/PrimeTower.cpp index 761103ee1c..b56c94913c 100644 --- a/src/PrimeTower.cpp +++ b/src/PrimeTower.cpp @@ -94,10 +94,10 @@ void PrimeTower::generateGroundpoly() const coord_t x = mesh_group_settings.get("prime_tower_position_x"); const coord_t y = mesh_group_settings.get("prime_tower_position_y"); const coord_t tower_radius = tower_size / 2; - outer_poly_.add(PolygonUtils::makeCircle(Point(x - tower_radius, y + tower_radius), tower_radius, TAU / CIRCLE_RESOLUTION)); - middle_ = Point(x - tower_size / 2, y + tower_size / 2); + outer_poly_.add(PolygonUtils::makeCircle(Point2LL(x - tower_radius, y + tower_radius), tower_radius, TAU / CIRCLE_RESOLUTION)); + middle_ = Point2LL(x - tower_size / 2, y + tower_size / 2); - post_wipe_point_ = Point(x - tower_size / 2, y + tower_size / 2); + post_wipe_point_ = Point2LL(x - tower_size / 2, y + tower_size / 2); } void PrimeTower::generatePaths(const SliceDataStorage& storage) @@ -230,9 +230,9 @@ void PrimeTower::addToGcode(const SliceDataStorage& storage, LayerPlan& gcode_la { // Make sure we wipe the old extruder on the prime tower. const Settings& previous_settings = Application::getInstance().current_slice_->scene.extruders[prev_extruder].settings_; - const Point previous_nozzle_offset = Point(previous_settings.get("machine_nozzle_offset_x"), previous_settings.get("machine_nozzle_offset_y")); + const Point2LL previous_nozzle_offset = Point2LL(previous_settings.get("machine_nozzle_offset_x"), previous_settings.get("machine_nozzle_offset_y")); const Settings& new_settings = Application::getInstance().current_slice_->scene.extruders[new_extruder].settings_; - const Point new_nozzle_offset = Point(new_settings.get("machine_nozzle_offset_x"), new_settings.get("machine_nozzle_offset_y")); + const Point2LL new_nozzle_offset = Point2LL(new_settings.get("machine_nozzle_offset_x"), new_settings.get("machine_nozzle_offset_y")); gcode_layer.addTravel(post_wipe_point_ - previous_nozzle_offset + new_nozzle_offset); } @@ -303,9 +303,9 @@ void PrimeTower::gotoStartLocation(LayerPlan& gcode_layer, const int extruder_nr const ExtruderTrain& train = Application::getInstance().current_slice_->scene.extruders[extruder_nr]; const coord_t inward_dist = train.settings_.get("machine_nozzle_size") * 3 / 2; const coord_t start_dist = train.settings_.get("machine_nozzle_size") * 2; - const Point prime_end = PolygonUtils::moveInsideDiagonally(wipe_location, inward_dist); - const Point outward_dir = wipe_location.location_ - prime_end; - const Point prime_start = wipe_location.location_ + normal(outward_dir, start_dist); + const Point2LL prime_end = PolygonUtils::moveInsideDiagonally(wipe_location, inward_dist); + const Point2LL outward_dir = wipe_location.location_ - prime_end; + const Point2LL prime_start = wipe_location.location_ + normal(outward_dir, start_dist); gcode_layer.addTravel(prime_start); } diff --git a/src/SkeletalTrapezoidation.cpp b/src/SkeletalTrapezoidation.cpp index eaebbb1683..9cd04a3cbc 100644 --- a/src/SkeletalTrapezoidation.cpp +++ b/src/SkeletalTrapezoidation.cpp @@ -25,7 +25,7 @@ namespace cura { -SkeletalTrapezoidation::node_t& SkeletalTrapezoidation::makeNode(vd_t::vertex_type& vd_node, Point p) +SkeletalTrapezoidation::node_t& SkeletalTrapezoidation::makeNode(vd_t::vertex_type& vd_node, Point2LL p) { auto he_node_it = vd_node_to_he_node_.find(&vd_node); if (he_node_it == vd_node_to_he_node_.end()) @@ -42,13 +42,13 @@ SkeletalTrapezoidation::node_t& SkeletalTrapezoidation::makeNode(vd_t::vertex_ty } void SkeletalTrapezoidation::transferEdge( - Point from, - Point to, + Point2LL from, + Point2LL to, vd_t::edge_type& vd_edge, edge_t*& prev_edge, - Point& start_source_point, - Point& end_source_point, - const std::vector& points, + Point2LL& start_source_point, + Point2LL& end_source_point, + const std::vector& points, const std::vector& segments) { auto he_edge_it = vd_edge_to_he_edge_.find(vd_edge.twin()); @@ -105,7 +105,7 @@ void SkeletalTrapezoidation::transferEdge( } else { - std::vector discretized = discretize(vd_edge, points, segments); + std::vector discretized = discretize(vd_edge, points, segments); assert(discretized.size() >= 2); if (discretized.size() < 2) { @@ -119,10 +119,10 @@ void SkeletalTrapezoidation::transferEdge( } node_t* v0 = (prev_edge) ? prev_edge->to_ : &makeNode(*vd_edge.vertex0(), from); // TODO: investigate whether boost:voronoi can produce multiple verts and violates consistency - Point p0 = discretized.front(); + Point2LL p0 = discretized.front(); for (size_t p1_idx = 1; p1_idx < discretized.size(); p1_idx++) { - Point p1 = discretized[p1_idx]; + Point2LL p1 = discretized[p1_idx]; node_t* v1; if (p1_idx < discretized.size() - 1) { @@ -161,7 +161,7 @@ void SkeletalTrapezoidation::transferEdge( } } -std::vector SkeletalTrapezoidation::discretize(const vd_t::edge_type& vd_edge, const std::vector& points, const std::vector& segments) +std::vector SkeletalTrapezoidation::discretize(const vd_t::edge_type& vd_edge, const std::vector& points, const std::vector& segments) { /*Terminology in this function assumes that the edge moves horizontally from left to right. This is not necessarily the case; the edge can go in any @@ -169,18 +169,18 @@ std::vector SkeletalTrapezoidation::discretize(const vd_t::edge_type& vd_ const vd_t::cell_type* left_cell = vd_edge.cell(); const vd_t::cell_type* right_cell = vd_edge.twin()->cell(); - Point start = VoronoiUtils::p(vd_edge.vertex0()); - Point end = VoronoiUtils::p(vd_edge.vertex1()); + Point2LL start = VoronoiUtils::p(vd_edge.vertex0()); + Point2LL end = VoronoiUtils::p(vd_edge.vertex1()); bool point_left = left_cell->contains_point(); bool point_right = right_cell->contains_point(); if ((! point_left && ! point_right) || vd_edge.is_secondary()) // Source vert is directly connected to source segment { - return std::vector({ start, end }); + return std::vector({ start, end }); } else if (point_left != point_right) // This is a parabolic edge between a point and a line. { - Point p = VoronoiUtils::getSourcePoint(*(point_left ? left_cell : right_cell), points, segments); + Point2LL p = VoronoiUtils::getSourcePoint(*(point_left ? left_cell : right_cell), points, segments); const Segment& s = VoronoiUtils::getSourceSegment(*(point_left ? right_cell : left_cell), points, segments); return VoronoiUtils::discretizeParabola(p, s, start, end, discretization_step_size_, transitioning_angle_); } @@ -189,16 +189,16 @@ std::vector SkeletalTrapezoidation::discretize(const vd_t::edge_type& vd_ /*While the edge is straight, it is still discretized since the part becomes narrower between the two points. As such it may need different beadings along the way.*/ - Point left_point = VoronoiUtils::getSourcePoint(*left_cell, points, segments); - Point right_point = VoronoiUtils::getSourcePoint(*right_cell, points, segments); + Point2LL left_point = VoronoiUtils::getSourcePoint(*left_cell, points, segments); + Point2LL right_point = VoronoiUtils::getSourcePoint(*right_cell, points, segments); coord_t d = vSize(right_point - left_point); - Point middle = (left_point + right_point) / 2; - Point x_axis_dir = turn90CCW(right_point - left_point); + Point2LL middle = (left_point + right_point) / 2; + Point2LL x_axis_dir = turn90CCW(right_point - left_point); coord_t x_axis_length = vSize(x_axis_dir); - const auto projected_x = [x_axis_dir, x_axis_length, middle](Point from) // Project a point on the edge. + const auto projected_x = [x_axis_dir, x_axis_length, middle](Point2LL from) // Project a point on the edge. { - Point vec = from - middle; + Point2LL vec = from - middle; coord_t x = dot(vec, x_axis_dir) / x_axis_length; return x; }; @@ -210,8 +210,8 @@ std::vector SkeletalTrapezoidation::discretize(const vd_t::edge_type& vd_ double bound = 0.5 / tan((std::numbers::pi - transitioning_angle_) * 0.5); coord_t marking_start_x = -d * bound; coord_t marking_end_x = d * bound; - Point marking_start = middle + x_axis_dir * marking_start_x / x_axis_length; - Point marking_end = middle + x_axis_dir * marking_end_x / x_axis_length; + Point2LL marking_start = middle + x_axis_dir * marking_start_x / x_axis_length; + Point2LL marking_end = middle + x_axis_dir * marking_end_x / x_axis_length; int direction = 1; if (start_x > end_x) // Oops, the Voronoi edge is the other way around. @@ -222,9 +222,9 @@ std::vector SkeletalTrapezoidation::discretize(const vd_t::edge_type& vd_ } // Start generating points along the edge. - Point a = start; - Point b = end; - std::vector ret; + Point2LL a = start; + Point2LL b = end; + std::vector ret; ret.emplace_back(a); // Introduce an extra edge at the borders of the markings? @@ -232,7 +232,7 @@ std::vector SkeletalTrapezoidation::discretize(const vd_t::edge_type& vd_ bool add_marking_end = marking_end_x * direction > start_x * direction; // The edge's length may not be divisible by the step size, so calculate an integer step count and evenly distribute the vertices among those. - Point ab = b - a; + Point2LL ab = b - a; coord_t ab_size = vSize(ab); coord_t step_count = (ab_size + discretization_step_size_ / 2) / discretization_step_size_; if (step_count % 2 == 1) @@ -241,7 +241,7 @@ std::vector SkeletalTrapezoidation::discretize(const vd_t::edge_type& vd_ } for (coord_t step = 1; step < step_count; step++) { - Point here = a + ab * step / step_count; // Now simply interpolate the coordinates to get the new vertices! + Point2LL here = a + ab * step / step_count; // Now simply interpolate the coordinates to get the new vertices! coord_t x_here = projected_x(here); // If we've surpassed the position of the extra markings, we may need to insert them first. if (add_marking_start && marking_start_x * direction < x_here * direction) { @@ -267,11 +267,11 @@ std::vector SkeletalTrapezoidation::discretize(const vd_t::edge_type& vd_ bool SkeletalTrapezoidation::computePointCellRange( vd_t::cell_type& cell, - Point& start_source_point, - Point& end_source_point, + Point2LL& start_source_point, + Point2LL& end_source_point, vd_t::edge_type*& starting_vd_edge, vd_t::edge_type*& ending_vd_edge, - const std::vector& points, + const std::vector& points, const std::vector& segments) { if (cell.incident_edge()->is_infinite()) @@ -281,9 +281,9 @@ bool SkeletalTrapezoidation::computePointCellRange( // Check if any point of the cell is inside or outside polygon // Copy whole cell into graph or not at all - const Point source_point = VoronoiUtils::getSourcePoint(cell, points, segments); + const Point2LL source_point = VoronoiUtils::getSourcePoint(cell, points, segments); const PolygonsPointIndex source_point_index = VoronoiUtils::getSourcePointIndex(cell, points, segments); - Point some_point = VoronoiUtils::p(cell.incident_edge()->vertex0()); + Point2LL some_point = VoronoiUtils::p(cell.incident_edge()->vertex0()); if (some_point == source_point) { some_point = VoronoiUtils::p(cell.incident_edge()->vertex1()); @@ -300,7 +300,7 @@ bool SkeletalTrapezoidation::computePointCellRange( do { assert(vd_edge->is_finite()); - Point p1 = VoronoiUtils::p(vd_edge->vertex1()); + Point2LL p1 = VoronoiUtils::p(vd_edge->vertex1()); if (p1 == source_point) { start_source_point = source_point; @@ -322,16 +322,16 @@ bool SkeletalTrapezoidation::computePointCellRange( void SkeletalTrapezoidation::computeSegmentCellRange( vd_t::cell_type& cell, - Point& start_source_point, - Point& end_source_point, + Point2LL& start_source_point, + Point2LL& end_source_point, vd_t::edge_type*& starting_vd_edge, vd_t::edge_type*& ending_vd_edge, - const std::vector& points, + const std::vector& points, const std::vector& segments) { const Segment& source_segment = VoronoiUtils::getSourceSegment(cell, points, segments); - Point from = source_segment.from(); - Point to = source_segment.to(); + Point2LL from = source_segment.from(); + Point2LL to = source_segment.to(); // Find starting edge // Find end edge @@ -345,8 +345,8 @@ void SkeletalTrapezoidation::computeSegmentCellRange( { continue; } - Point v0 = VoronoiUtils::p(edge->vertex0()); - Point v1 = VoronoiUtils::p(edge->vertex1()); + Point2LL v0 = VoronoiUtils::p(edge->vertex0()); + Point2LL v1 = VoronoiUtils::p(edge->vertex1()); assert(! (v0 == to && v1 == from)); if (v0 == to && ! after_start) // Use the last edge which starts in source_segment.to { @@ -400,7 +400,7 @@ void SkeletalTrapezoidation::constructFromPolygons(const Polygons& polys) vd_edge_to_he_edge_.clear(); vd_node_to_he_node_.clear(); - std::vector points; // Remains empty + std::vector points; // Remains empty std::vector segments; for (size_t poly_idx = 0; poly_idx < polys.size(); poly_idx++) @@ -421,8 +421,8 @@ void SkeletalTrapezoidation::constructFromPolygons(const Polygons& polys) { // There is no spoon continue; } - Point start_source_point; - Point end_source_point; + Point2LL start_source_point; + Point2LL end_source_point; vd_t::edge_type* starting_vonoroi_edge = nullptr; vd_t::edge_type* ending_vonoroi_edge = nullptr; // Compute and store result in above variables @@ -465,8 +465,8 @@ void SkeletalTrapezoidation::constructFromPolygons(const Polygons& polys) for (vd_t::edge_type* vd_edge = starting_vonoroi_edge->next(); vd_edge != ending_vonoroi_edge; vd_edge = vd_edge->next()) { assert(vd_edge->is_finite()); - Point v1 = VoronoiUtils::p(vd_edge->vertex0()); - Point v2 = VoronoiUtils::p(vd_edge->vertex1()); + Point2LL v1 = VoronoiUtils::p(vd_edge->vertex0()); + Point2LL v2 = VoronoiUtils::p(vd_edge->vertex1()); transferEdge(v1, v2, *vd_edge, prev_edge, start_source_point, end_source_point, points, segments); graph_.makeRib(prev_edge, start_source_point, end_source_point, vd_edge->next() == ending_vonoroi_edge); @@ -740,9 +740,9 @@ void SkeletalTrapezoidation::updateIsCentral() } else { - Point a = edge.from_->p_; - Point b = edge.to_->p_; - Point ab = b - a; + Point2LL a = edge.from_->p_; + Point2LL b = edge.to_->p_; + Point2LL ab = b - a; coord_t dR = std::abs(edge.to_->data_.distance_to_boundary_ - edge.from_->data_.distance_to_boundary_); coord_t dD = vSize(ab); edge.data_.setIsCentral(dR < dD * cap); @@ -1009,9 +1009,9 @@ void SkeletalTrapezoidation::filterTransitionMids() assert(transitions.front().lower_bead_count_ <= transitions.back().lower_bead_count_); assert(edge.from_->data_.distance_to_boundary_ <= edge.to_->data_.distance_to_boundary_); - const Point a = edge.from_->p_; - const Point b = edge.to_->p_; - Point ab = b - a; + const Point2LL a = edge.from_->p_; + const Point2LL b = edge.to_->p_; + Point2LL ab = b - a; coord_t ab_size = vSize(ab); bool going_up = true; @@ -1081,9 +1081,9 @@ std::list continue; } - Point a = edge->from_->p_; - Point b = edge->to_->p_; - Point ab = b - a; + Point2LL a = edge->from_->p_; + Point2LL b = edge->to_->p_; + Point2LL ab = b - a; coord_t ab_size = vSize(ab); bool is_aligned = edge->isUpward(); edge_t* aligned_edge = is_aligned ? edge : edge->twin_; @@ -1214,9 +1214,9 @@ void SkeletalTrapezoidation::generateAllTransitionEnds(ptr_vector_t>& edge_transition_ends) { - const Point a = edge.from_->p_; - const Point b = edge.to_->p_; - const Point ab = b - a; + const Point2LL a = edge.from_->p_; + const Point2LL b = edge.to_->p_; + const Point2LL ab = b - a; const coord_t ab_size = vSize(ab); const coord_t transition_length = beading_strategy_.getTransitioningLength(lower_bead_count); @@ -1259,9 +1259,9 @@ bool SkeletalTrapezoidation::generateTransitionEnd( coord_t lower_bead_count, ptr_vector_t>& edge_transition_ends) { - Point a = edge.from_->p_; - Point b = edge.to_->p_; - Point ab = b - a; + Point2LL a = edge.from_->p_; + Point2LL b = edge.to_->p_; + Point2LL ab = b - a; coord_t ab_size = vSize(ab); // TODO: prevent recalculation of these values assert(start_pos <= ab_size); @@ -1457,9 +1457,9 @@ void SkeletalTrapezoidation::applyTransitions(ptr_vector_tp_; - Point b = to->p_; - Point ab = b - a; + Point2LL a = from->p_; + Point2LL b = to->p_; + Point2LL ab = b - a; coord_t ab_size = vSize(ab); edge_t* last_edge_replacing_input = &edge; @@ -1474,7 +1474,7 @@ void SkeletalTrapezoidation::applyTransitions(ptr_vector_tdata_.transition_ratio_ = 0; continue; } - Point mid = a + normal(ab, end_pos); + Point2LL mid = a + normal(ab, end_pos); assert(last_edge_replacing_input->data_.isCentral()); assert(last_edge_replacing_input->data_.type_ != SkeletalTrapezoidationEdge::EdgeType::EXTRA_VD); @@ -1528,9 +1528,9 @@ void SkeletalTrapezoidation::generateExtraRibs() // Preload some variables before [edge] gets changed node_t* from = edge.from_; node_t* to = edge.to_; - Point a = from->p_; - Point b = to->p_; - Point ab = b - a; + Point2LL a = from->p_; + Point2LL b = to->p_; + Point2LL ab = b - a; coord_t ab_size = vSize(ab); coord_t a_R = edge.from_->data_.distance_to_boundary_; coord_t b_R = edge.to_->data_.distance_to_boundary_; @@ -1558,7 +1558,7 @@ void SkeletalTrapezoidation::generateExtraRibs() close_node->data_.transition_ratio_ = 0; continue; } - Point mid = a + normal(ab, end_pos); + Point2LL mid = a + normal(ab, end_pos); assert(last_edge_replacing_input->data_.isCentral()); assert(last_edge_replacing_input->data_.type_ != SkeletalTrapezoidationEdge::EdgeType::EXTRA_VD); @@ -1884,9 +1884,9 @@ void SkeletalTrapezoidation::generateJunctions(ptr_vector_t& spdlog::warn("Generated junction is beyond the center of total width."); } - Point a = edge->to_->p_; - Point b = edge->from_->p_; - Point ab = b - a; + Point2LL a = edge->to_->p_; + Point2LL b = edge->from_->p_; + Point2LL ab = b - a; const size_t num_junctions = beading->toolpath_locations.size(); size_t junction_idx; @@ -1916,7 +1916,7 @@ void SkeletalTrapezoidation::generateJunctions(ptr_vector_t& { // Junction coinciding with a node is handled by the next segment break; } - Point junction(a + ab * (bead_R - start_R) / (end_R - start_R)); + Point2LL junction(a + ab * (bead_R - start_R) / (end_R - start_R)); if (bead_R > start_R - 5) { // Snap to start node if it is really close, in order to be able to see 3-way intersection later on more robustly junction = a; @@ -2215,7 +2215,7 @@ void SkeletalTrapezoidation::generateLocalMaximaSingleBeads() for (coord_t segment = 0; segment < n_segments; segment++) { double a = 2.0 * std::numbers::pi / n_segments * segment; - line.junctions_.emplace_back(node.p_ + Point(r * cos(a), r * sin(a)), width, inset_index); + line.junctions_.emplace_back(node.p_ + Point2LL(r * cos(a), r * sin(a)), width, inset_index); } } } diff --git a/src/SkeletalTrapezoidationGraph.cpp b/src/SkeletalTrapezoidationGraph.cpp index 35dec4cd61..514277ed36 100644 --- a/src/SkeletalTrapezoidationGraph.cpp +++ b/src/SkeletalTrapezoidationGraph.cpp @@ -132,7 +132,7 @@ STHalfEdge* STHalfEdge::getNextUnconnected() return result->twin_; } -STHalfEdgeNode::STHalfEdgeNode(SkeletalTrapezoidationJoint data, Point p) +STHalfEdgeNode::STHalfEdgeNode(SkeletalTrapezoidationJoint data, Point2LL p) : HalfEdgeNode(data, p) { } @@ -329,9 +329,9 @@ void SkeletalTrapezoidationGraph::collapseSmallEdges(coord_t snap_dist) } } -void SkeletalTrapezoidationGraph::makeRib(edge_t*& prev_edge, Point start_source_point, Point end_source_point, bool is_next_to_start_or_end) +void SkeletalTrapezoidationGraph::makeRib(edge_t*& prev_edge, Point2LL start_source_point, Point2LL end_source_point, bool is_next_to_start_or_end) { - Point p = LinearAlg2D::getClosestOnLine(prev_edge->to_->p_, start_source_point, end_source_point); + Point2LL p = LinearAlg2D::getClosestOnLine(prev_edge->to_->p_, start_source_point, end_source_point); coord_t dist = vSize(prev_edge->to_->p_ - p); prev_edge->to_->data_.distance_to_boundary_ = dist; assert(dist >= 0); @@ -365,10 +365,10 @@ std::pairp_; + Point2LL p = mid_node->p_; - std::pair source_segment = getSource(edge); - Point px = LinearAlg2D::getClosestOnLineSegment(p, source_segment.first, source_segment.second); + std::pair source_segment = getSource(edge); + Point2LL px = LinearAlg2D::getClosestOnLineSegment(p, source_segment.first, source_segment.second); coord_t dist = vSize(p - px); assert(dist > 0); mid_node->data_.distance_to_boundary_ = dist; @@ -438,7 +438,7 @@ std::pair SkeletalTrapezoidationGraph::getSource(const edge_t& edge) +std::pair SkeletalTrapezoidationGraph::getSource(const edge_t& edge) { const edge_t* from_edge = &edge; while (from_edge->prev_) diff --git a/src/SkirtBrim.cpp b/src/SkirtBrim.cpp index 4567a92d6c..a2b67503ec 100644 --- a/src/SkirtBrim.cpp +++ b/src/SkirtBrim.cpp @@ -306,7 +306,7 @@ coord_t SkirtBrim::generateOffset(const Offset& offset, Polygons& covered_area, length_added = brim_lines.polyLineLength(); const coord_t max_stitch_distance = line_widths_[offset.extruder_nr_]; - PolylineStitcher::stitch(brim_lines, result.open_polylines, result.closed_polygons, max_stitch_distance); + PolylineStitcher::stitch(brim_lines, result.open_polylines, result.closed_polygons, max_stitch_distance); // clean up too small lines for (size_t line_idx = 0; line_idx < result.open_polylines.size();) diff --git a/src/TopSurface.cpp b/src/TopSurface.cpp index f3b9b8974a..acbbe94f7d 100644 --- a/src/TopSurface.cpp +++ b/src/TopSurface.cpp @@ -67,7 +67,7 @@ bool TopSurface::ironing(const SliceDataStorage& storage, const SliceMeshStorage const bool enforce_monotonic_order = mesh.settings.get("ironing_monotonic"); constexpr size_t wall_line_count = 0; const coord_t small_area_width = 0; // This shouldn't be on for ironing. - const Point infill_origin = Point(); + const Point2LL infill_origin = Point2LL(); const bool skip_line_stitching = enforce_monotonic_order; coord_t ironing_inset = -mesh.settings.get("ironing_inset"); @@ -133,12 +133,12 @@ bool TopSurface::ironing(const SliceDataStorage& storage, const SliceMeshStorage // Move to a corner of the area that is perpendicular to the ironing lines, to reduce the number of seams. const AABB bounding_box(ironed_areas); PointMatrix rotate(-direction + 90); - const Point center = bounding_box.getMiddle(); - const Point far_away = rotate.apply( - Point(0, vSize(bounding_box.max_ - center) * 100)); // Some direction very far away in the direction perpendicular to the ironing lines, relative to the centre. + const Point2LL center = bounding_box.getMiddle(); + const Point2LL far_away = rotate.apply( + Point2LL(0, vSize(bounding_box.max_ - center) * 100)); // Some direction very far away in the direction perpendicular to the ironing lines, relative to the centre. // Two options to start, both perpendicular to the ironing lines. Which is closer? - const Point front_side = PolygonUtils::findNearestVert(center + far_away, ironed_areas).p(); - const Point back_side = PolygonUtils::findNearestVert(center - far_away, ironed_areas).p(); + const Point2LL front_side = PolygonUtils::findNearestVert(center + far_away, ironed_areas).p(); + const Point2LL back_side = PolygonUtils::findNearestVert(center - far_away, ironed_areas).p(); if (vSize2(layer.getLastPlannedPositionOrStartingPosition() - front_side) < vSize2(layer.getLastPlannedPositionOrStartingPosition() - back_side)) { layer.addTravel(front_side); diff --git a/src/TreeSupport.cpp b/src/TreeSupport.cpp index fe2cc87e77..d12e14adbd 100644 --- a/src/TreeSupport.cpp +++ b/src/TreeSupport.cpp @@ -399,7 +399,7 @@ void TreeSupport::mergeHelper( // Calculate which point is closest to the point of the last merge (or tip center if no merge above it has happened) // Used at the end to estimate where to best place the branch on the bottom most layer // Could be replaced with a random point inside the new area - Point new_pos = reduced_check.first.next_position_; + Point2LL new_pos = reduced_check.first.next_position_; if (! intersect.inside(new_pos, true)) { PolygonUtils::moveInside(intersect, new_pos); @@ -1269,7 +1269,7 @@ void TreeSupport::increaseAreas( // If the bottom most point of a branch is set, later functions will assume that the position is valid, and ignore it. // But as branches connecting with the model that are to small have to be culled, the bottom most point has to be not set. // A point can be set on the top most tip layer (maybe more if it should not move for a few layers). - parent->result_on_layer_ = Point(-1, -1); + parent->result_on_layer_ = Point2LL(-1, -1); } }); } @@ -1377,7 +1377,7 @@ void TreeSupport::setPointsOnAreas(const TreeSupportElement* elem) { // Based on the branch center point of the current layer, the point on the next (further up) layer is calculated. - if (elem->result_on_layer_ == Point(-1, -1)) + if (elem->result_on_layer_ == Point2LL(-1, -1)) { spdlog::error("Uninitialized support element"); return; @@ -1386,12 +1386,12 @@ void TreeSupport::setPointsOnAreas(const TreeSupportElement* elem) for (TreeSupportElement* next_elem : elem->parents_) { if (next_elem->result_on_layer_ - != Point(-1, -1)) // If the value was set somewhere else it it kept. This happens when a branch tries not to move after being unable to create a roof. + != Point2LL(-1, -1)) // If the value was set somewhere else it it kept. This happens when a branch tries not to move after being unable to create a roof. { continue; } - Point from = elem->result_on_layer_; + Point2LL from = elem->result_on_layer_; if (! (next_elem->area_->inside(from, true))) { PolygonUtils::moveInside( @@ -1483,7 +1483,7 @@ bool TreeSupport::setToModelContact(std::vector>& } // Guess a point inside the influence area, in which the branch will be placed in. - Point best = checked[last_successfull_layer - layer_idx]->next_position_; + Point2LL best = checked[last_successfull_layer - layer_idx]->next_position_; if (! valid_place_area.inside(best, true)) { @@ -1497,7 +1497,7 @@ bool TreeSupport::setToModelContact(std::vector>& } else // can not add graceful => just place it here and hope for the best { - Point best = first_elem->next_position_; + Point2LL best = first_elem->next_position_; Polygons valid_place_area = first_elem->area_->difference(volumes_.getAvoidance(config.getCollisionRadius(first_elem), layer_idx, AvoidanceType::COLLISION, first_elem->use_min_xy_dist_)); @@ -1548,7 +1548,7 @@ void TreeSupport::createNodesFromArea(std::vector> std::unordered_set remove; for (TreeSupportElement* init : move_bounds[0]) { - Point p = init->next_position_; + Point2LL p = init->next_position_; if (! (init->area_->inside(p, true))) { PolygonUtils::moveInside(*init->area_, p, 0); @@ -1585,7 +1585,7 @@ void TreeSupport::createNodesFromArea(std::vector> for (TreeSupportElement* elem : move_bounds[layer_idx]) { bool removed = false; - if (elem->result_on_layer_ == Point(-1, -1)) // Check if the resulting center point is not yet set. + if (elem->result_on_layer_ == Point2LL(-1, -1)) // Check if the resulting center point is not yet set. { if (elem->to_buildplate_ || (! elem->to_buildplate_ && elem->distance_to_top_ < config.min_dtt_to_model && ! elem->supports_roof_)) { @@ -1604,7 +1604,7 @@ void TreeSupport::createNodesFromArea(std::vector> { // When the roof was not able to generate downwards enough, the top elements may have not moved, and have result_on_layer already set. As this branch needs // to be removed => all parents result_on_layer have to be invalidated. - parent->result_on_layer_ = Point(-1, -1); + parent->result_on_layer_ = Point2LL(-1, -1); } continue; } @@ -1647,9 +1647,9 @@ void TreeSupport::generateBranchAreas( { Polygon base_circle = TreeSupportBaseCircle::getBaseCircle(); - for (Point vertex : base_circle) + for (Point2LL vertex : base_circle) { - vertex = Point(vertex.X * config.branch_radius / TreeSupportBaseCircle::base_radius, vertex.Y * config.branch_radius / TreeSupportBaseCircle::base_radius); + vertex = Point2LL(vertex.X * config.branch_radius / TreeSupportBaseCircle::base_radius, vertex.Y * config.branch_radius / TreeSupportBaseCircle::base_radius); branch_circle.add(vertex); } } @@ -1669,24 +1669,24 @@ void TreeSupport::generateBranchAreas( TreeSupportElement* child_elem = inverse_tree_order.count(elem) ? inverse_tree_order.at(elem) : nullptr; // Calculate multiple ovalized circles, to connect with every parent and child. Also generate regular circle for the current layer. Merge all these into one area. - std::vector> movement_directions{ std::pair(Point(0, 0), radius) }; + std::vector> movement_directions{ std::pair(Point2LL(0, 0), radius) }; if (! elem->skip_ovalisation_) { if (child_elem != nullptr) { - Point movement = (child_elem->result_on_layer_ - elem->result_on_layer_); + Point2LL movement = (child_elem->result_on_layer_ - elem->result_on_layer_); movement_directions.emplace_back(movement, radius); } for (TreeSupportElement* parent : elem->parents_) { - Point movement = (parent->result_on_layer_ - elem->result_on_layer_); + Point2LL movement = (parent->result_on_layer_ - elem->result_on_layer_); movement_directions.emplace_back(movement, std::max(config.getRadius(parent), config.support_line_width)); parent_uses_min |= parent->use_min_xy_dist_; } - for (Point target : elem->additional_ovalization_targets_) + for (Point2LL target : elem->additional_ovalization_targets_) { - Point movement = (target - elem->result_on_layer_); + Point2LL movement = (target - elem->result_on_layer_); movement_directions.emplace_back(movement, std::max(radius, config.support_line_width)); } } @@ -1696,14 +1696,14 @@ void TreeSupport::generateBranchAreas( { Polygons poly; - for (std::pair movement : movement_directions) + for (std::pair movement : movement_directions) { max_speed_sqd = std::max(max_speed_sqd, vSize2(movement.first)); // Visualization: https://jsfiddle.net/0zvcq39L/2/ // Ovalizes the circle to an ellipse, that contains both old center and new target position. double used_scale = (movement.second + offset) / (1.0 * config.branch_radius); - Point center_position = elem->result_on_layer_ + movement.first / 2; + Point2LL center_position = elem->result_on_layer_ + movement.first / 2; const double moveX = movement.first.X / (used_scale * config.branch_radius); const double moveY = movement.first.Y / (used_scale * config.branch_radius); const double vsize_inv = 0.5 / (0.01 + std::sqrt(moveX * moveX + moveY * moveY)); @@ -1715,9 +1715,9 @@ void TreeSupport::generateBranchAreas( used_scale * (1 + moveY * moveY * vsize_inv), }; Polygon circle; - for (Point vertex : branch_circle) + for (Point2LL vertex : branch_circle) { - vertex = Point(matrix[0] * vertex.X + matrix[1] * vertex.Y, matrix[2] * vertex.X + matrix[3] * vertex.Y); + vertex = Point2LL(matrix[0] * vertex.X + matrix[1] * vertex.Y, matrix[2] * vertex.X + matrix[3] * vertex.Y); circle.add(center_position + vertex); } poly.add(circle.offset(0)); @@ -1762,7 +1762,7 @@ void TreeSupport::generateBranchAreas( else { // Try a fuzzy inside as sometimes the point should be on the border, but is not because of rounding errors... - Point from = elem->result_on_layer_; + Point2LL from = elem->result_on_layer_; PolygonUtils::moveInside(part, from, 0); if (vSize2(elem->result_on_layer_ - from) < (FUDGE_LENGTH * FUDGE_LENGTH) / 4) { @@ -1878,11 +1878,11 @@ void TreeSupport::smoothBranchAreas(std::vectorparents_[idx]; const coord_t max_outer_line_increase = max_radius_change_per_layer; Polygons result = layer_tree_polygons[layer_idx + 1][parent].offset(max_outer_line_increase); - const Point direction = data_pair.first->result_on_layer_ - parent->result_on_layer_; + const Point2LL direction = data_pair.first->result_on_layer_ - parent->result_on_layer_; // Move the polygons object. for (auto& outer : result) { - for (Point& p : outer) + for (Point2LL& p : outer) { p += direction; } @@ -2263,14 +2263,14 @@ void TreeSupport::drawAreas(std::vector>& move_bou // (Check if) We either come from nowhere at the final layer or we had invalid parents 2. should never happen but just to be sure: if ((layer_idx > 0 && ((! inverse_tree_order.count(elem) && elem->target_height_ == layer_idx && config.min_dtt_to_model > 0 && ! elem->to_buildplate_) - || (inverse_tree_order.count(elem) && inverse_tree_order[elem]->result_on_layer_ == Point(-1, -1))))) + || (inverse_tree_order.count(elem) && inverse_tree_order[elem]->result_on_layer_ == Point2LL(-1, -1))))) { continue; } for (TreeSupportElement* par : elem->parents_) { - if (par->result_on_layer_ == Point(-1, -1)) + if (par->result_on_layer_ == Point2LL(-1, -1)) { continue; } diff --git a/src/TreeSupportTipGenerator.cpp b/src/TreeSupportTipGenerator.cpp index 4c993cd487..5ec22f610c 100644 --- a/src/TreeSupportTipGenerator.cpp +++ b/src/TreeSupportTipGenerator.cpp @@ -117,7 +117,7 @@ std::vector TreeSupportTipGenerator::c for (const auto& line : polylines) { LineInformation res_line; - for (const Point& p : line) + for (const Point2LL& p : line) { if (config.support_rest_preference == RestPreference::BUILDPLATE && ! volumes_.getAvoidance(config.getRadius(0), layer_idx, AvoidanceType::FAST_SAFE, false, ! xy_overrides).inside(p, true)) @@ -173,9 +173,9 @@ Polygons TreeSupportTipGenerator::convertInternalToLines(std::vector)> TreeSupportTipGenerator::getEvaluatePointForNextLayerFunction(size_t current_layer) +std::function)> TreeSupportTipGenerator::getEvaluatePointForNextLayerFunction(size_t current_layer) { - std::function)> evaluatePoint = [this, current_layer](std::pair p) + std::function)> evaluatePoint = [this, current_layer](std::pair p) { if (config.support_rest_preference != RestPreference::GRACEFUL && ! volumes_ @@ -214,7 +214,7 @@ std::function)> TreeS std::pair, std::vector> TreeSupportTipGenerator::splitLines( std::vector lines, - std::function)> evaluatePoint) + std::function)> evaluatePoint) { // Assumes all Points on the current line are valid. @@ -223,11 +223,11 @@ std::pair, std::vector keep(1); std::vector set_free(1); - for (const std::vector>& line : lines) + for (const std::vector>& line : lines) { auto current = KEEPING; LineInformation resulting_line; - for (const std::pair& me : line) + for (const std::pair& me : line) { if (evaluatePoint(me) == (current == FREEING)) { @@ -246,8 +246,8 @@ std::pair, std::vector>>, - std::vector>>>(keep, set_free); + std::vector>>, + std::vector>>>(keep, set_free); } Polygons TreeSupportTipGenerator::ensureMaximumDistancePolyline(const Polygons& input, coord_t distance, size_t min_points, bool enforce_distance) const @@ -299,7 +299,7 @@ Polygons TreeSupportTipGenerator::ensureMaximumDistancePolyline(const Polygons& while (line.size() < min_points && current_distance >= coord_t(FUDGE_LENGTH * 2)) { line.clear(); - Point current_point = part[0]; + Point2LL current_point = part[0]; line.add(part[0]); bool should_add_endpoint = min_points > 1 || vSize2(part[0] - part[optimal_end_index]) > (current_distance * current_distance); @@ -328,7 +328,7 @@ Polygons TreeSupportTipGenerator::ensureMaximumDistancePolyline(const Polygons& coord_t min_distance_to_existing_point_sqd = std::numeric_limits::max(); if (enforce_distance) { - for (Point p : line) + for (Point2LL p : line) { min_distance_to_existing_point_sqd = std::min(min_distance_to_existing_point_sqd, vSize2(p - next_point.location)); } @@ -391,8 +391,8 @@ std::shared_ptr TreeSupportTipGenerator::generateCrossFi const coord_t aabb_expansion = mesh.settings.get("support_offset"); AABB3D aabb_here(mesh.bounding_box); - aabb_here.include(aabb_here.min_ - Point3(-aabb_expansion, -aabb_expansion, 0)); - aabb_here.include(aabb_here.max_ + Point3(-aabb_expansion, -aabb_expansion, 0)); + aabb_here.include(aabb_here.min_ - Point3LL(-aabb_expansion, -aabb_expansion, 0)); + aabb_here.include(aabb_here.max_ + Point3LL(-aabb_expansion, -aabb_expansion, 0)); aabb.include(aabb_here); const std::string cross_subdisivion_spec_image_file = mesh.settings.get("cross_support_density_image"); @@ -619,13 +619,13 @@ void TreeSupportTipGenerator::calculateRoofAreas(const cura::SliceMeshStorage& m void TreeSupportTipGenerator::addPointAsInfluenceArea( std::vector>& move_bounds, - std::pair p, + std::pair p, size_t dtt, LayerIndex insert_layer, size_t dont_move_until, bool roof, bool skip_ovalisation, - std::vector additional_ovalization_targets) + std::vector additional_ovalization_targets) { const bool to_bp = p.second == LineStatus::TO_BP || p.second == LineStatus::TO_BP_SAFE; const bool gracious = to_bp || p.second == LineStatus::TO_MODEL_GRACIOUS || p.second == LineStatus::TO_MODEL_GRACIOUS_SAFE; @@ -637,7 +637,7 @@ void TreeSupportTipGenerator::addPointAsInfluenceArea( } Polygon circle; Polygon base_circle = TreeSupportBaseCircle::getBaseCircle(); - for (Point corner : base_circle) + for (Point2LL corner : base_circle) { circle.add(p.first + corner); } @@ -664,7 +664,7 @@ void TreeSupportTipGenerator::addPointAsInfluenceArea( support_tree_branch_reach_limit); elem->area_ = new Polygons(area); - for (Point target : additional_ovalization_targets) + for (Point2LL target : additional_ovalization_targets) { elem->additional_ovalization_targets_.emplace_back(target); } @@ -691,10 +691,10 @@ void TreeSupportTipGenerator::addLinesAsInfluenceAreas( { for (dtt_roof_tip = 0; dtt_roof_tip < roof_tip_layers && insert_layer_idx - dtt_roof_tip >= 1; dtt_roof_tip++) { - std::function)> evaluateRoofWillGenerate = [&](std::pair p) + std::function)> evaluateRoofWillGenerate = [&](std::pair p) { Polygon roof_circle; - for (Point corner : TreeSupportBaseCircle::getBaseCircle()) + for (Point2LL corner : TreeSupportBaseCircle::getBaseCircle()) { roof_circle.add(p.first + corner * std::max(config.min_radius / TreeSupportBaseCircle::base_radius, coord_t(1))); } @@ -708,7 +708,7 @@ void TreeSupportTipGenerator::addLinesAsInfluenceAreas( for (LineInformation line : split.second) // Add all points that would not be valid. { - for (std::pair point_data : line) + for (std::pair point_data : line) { addPointAsInfluenceArea(move_bounds, point_data, 0, insert_layer_idx - dtt_roof_tip, roof_tip_layers - dtt_roof_tip, dtt_roof_tip != 0, false); } @@ -720,7 +720,7 @@ void TreeSupportTipGenerator::addLinesAsInfluenceAreas( for (LineInformation line : split.second) { - for (std::pair point_data : line) + for (std::pair point_data : line) { addPointAsInfluenceArea(move_bounds, point_data, 0, insert_layer_idx - dtt_roof_tip, roof_tip_layers - dtt_roof_tip, dtt_roof_tip != 0, false); } @@ -730,10 +730,10 @@ void TreeSupportTipGenerator::addLinesAsInfluenceAreas( Polygons added_roofs; for (LineInformation line : lines) { - for (std::pair p : line) + for (std::pair p : line) { Polygon roof_circle; - for (Point corner : TreeSupportBaseCircle::getBaseCircle()) + for (Point2LL corner : TreeSupportBaseCircle::getBaseCircle()) { roof_circle.add(p.first + corner * std::max(config.min_radius / TreeSupportBaseCircle::base_radius, coord_t(1))); } @@ -757,7 +757,7 @@ void TreeSupportTipGenerator::addLinesAsInfluenceAreas( const bool disable_ovalization = ! connect_points && config.min_radius < 3 * config.support_line_width && roof_tip_layers == 0 && dtt_roof_tip == 0; for (auto [idx, point_data] : line | ranges::views::enumerate) { - std::vector additional_ovalization_targets; + std::vector additional_ovalization_targets; if (connect_points) // If the radius is to large then the ovalization would cause the area to float in the air. { if (idx != 0) @@ -809,7 +809,7 @@ void TreeSupportTipGenerator::removeUselessAddedPoints( } else if (elem->supports_roof_) { - Point from = elem->result_on_layer_; + Point2LL from = elem->result_on_layer_; PolygonUtils::moveInside(roof_on_layer_above, from); // Remove branches should have interface above them, but dont. Should never happen. if (roof_on_layer_above.empty() @@ -992,7 +992,7 @@ void TreeSupportTipGenerator::generateTips( for (auto line : polylines) { LineInformation res_line; - for (Point p : line) + for (Point2LL p : line) { res_line.emplace_back(p, LineStatus::INVALID); } @@ -1010,7 +1010,7 @@ void TreeSupportTipGenerator::generateTips( ! xy_overrides); // It is not required to offset the forbidden area here as the points won't change: // If points here are not inside the forbidden area neither will they be later when placing these points, as these are the same points. - std::function)> evaluatePoint = [&](std::pair p) + std::function)> evaluatePoint = [&](std::pair p) { return relevant_forbidden_below.inside(p.first, true); }; @@ -1018,7 +1018,7 @@ void TreeSupportTipGenerator::generateTips( if (support_roof_layers) { // Remove all points that are for some reason part of a roof area, as the point is already supported by roof - std::function)> evaluatePartOfRoof = [&](std::pair p) + std::function)> evaluatePartOfRoof = [&](std::pair p) { return support_roof_drawn[layer_idx - lag_ctr].inside(p.first, true); }; diff --git a/src/bridge.cpp b/src/bridge.cpp index 30ed81ed9c..c5d4c25fa9 100644 --- a/src/bridge.cpp +++ b/src/bridge.cpp @@ -138,10 +138,10 @@ int bridgeAngle( double line_angle = -1; for (PolygonRef air_line : skin_perimeter_lines_over_air) { - Point p0 = air_line[0]; + Point2LL p0 = air_line[0]; for (unsigned i = 1; i < air_line.size(); ++i) { - const Point& p1(air_line[i]); + const Point2LL& p1(air_line[i]); double dist2 = vSize2(p0 - p1); if (dist2 > max_dist2) { @@ -197,8 +197,8 @@ int bridgeAngle( if (idx1 < 0 || idx2 < 0) return -1; - Point center1 = islands[idx1].centerOfMass(); - Point center2 = islands[idx2].centerOfMass(); + Point2LL center1 = islands[idx1].centerOfMass(); + Point2LL center2 = islands[idx2].centerOfMass(); return angle(center2 - center1); } diff --git a/src/communication/ArcusCommunication.cpp b/src/communication/ArcusCommunication.cpp index 7f589a1312..f715e3cfe7 100644 --- a/src/communication/ArcusCommunication.cpp +++ b/src/communication/ArcusCommunication.cpp @@ -54,7 +54,7 @@ class ArcusCommunication::PathCompiler std::vector points; //!< The points used to define the line segments, the size of this vector is D*(N+1) as each line segment is defined from one point to the next. D is //!< the dimensionality of the point. - Point last_point; + Point2LL last_point; PathCompiler(const PathCompiler&) = delete; PathCompiler& operator=(const PathCompiler&) = delete; @@ -130,7 +130,7 @@ class ArcusCommunication::PathCompiler * of the path this jump is marked as `PrintFeatureType::NoneType`. * \param from The initial point of a polygon. */ - void handleInitialPoint(const Point& initial_point) + void handleInitialPoint(const Point2LL& initial_point) { if (points.size() == 0) { @@ -188,7 +188,7 @@ class ArcusCommunication::PathCompiler /*! * \brief Move the current point of this path to \p position. */ - void setCurrentPosition(const Point& position) + void setCurrentPosition(const Point2LL& position) { handleInitialPoint(position); } @@ -204,7 +204,7 @@ class ArcusCommunication::PathCompiler * \param line_thickness The thickness (in the Z direction) of the line. * \param velocity The velocity of printing this polygon. */ - void sendLineTo(const PrintFeatureType& print_feature_type, const Point& to, const coord_t& width, const coord_t& thickness, const Velocity& feedrate) + void sendLineTo(const PrintFeatureType& print_feature_type, const Point2LL& to, const coord_t& width, const coord_t& thickness, const Velocity& feedrate) { assert(! points.empty() && "A point must already be in the buffer for sendLineTo(.) to function properly."); @@ -257,7 +257,7 @@ class ArcusCommunication::PathCompiler * Each point is represented as two consecutive floats. All members adding a * 2D point to the data should use this function. */ - void addPoint2D(const Point& point) + void addPoint2D(const Point2LL& point) { points.push_back(INT2MM(point.X)); points.push_back(INT2MM(point.Y)); @@ -276,7 +276,7 @@ class ArcusCommunication::PathCompiler * \param thickness The layer thickness of the polygon. * \param velocity How fast the polygon is printed. */ - void addLineSegment(const PrintFeatureType& print_feature_type, const Point& point, const coord_t& width, const coord_t& thickness, const Velocity& velocity) + void addLineSegment(const PrintFeatureType& print_feature_type, const Point2LL& point, const coord_t& width, const coord_t& thickness, const Velocity& velocity) { addPoint2D(point); line_types.push_back(print_feature_type); @@ -368,7 +368,7 @@ bool ArcusCommunication::hasSlice() const && private_data->slice_count < 1; // Only slice once per run of CuraEngine. See documentation of slice_count. } -void ArcusCommunication::sendCurrentPosition(const Point& position) +void ArcusCommunication::sendCurrentPosition(const Point2LL& position) { path_compiler->setCurrentPosition(position); } @@ -402,7 +402,7 @@ void ArcusCommunication::sendLayerComplete(const LayerIndex::value_type& layer_n layer->set_thickness(thickness); } -void ArcusCommunication::sendLineTo(const PrintFeatureType& type, const Point& to, const coord_t& line_width, const coord_t& line_thickness, const Velocity& velocity) +void ArcusCommunication::sendLineTo(const PrintFeatureType& type, const Point2LL& to, const coord_t& line_width, const coord_t& line_thickness, const Velocity& velocity) { path_compiler->sendLineTo(type, to, line_width, line_thickness, velocity); } @@ -443,7 +443,7 @@ void ArcusCommunication::sendPolygon( void ArcusCommunication::sendPolygons(const PrintFeatureType& type, const Polygons& polygons, const coord_t& line_width, const coord_t& line_thickness, const Velocity& velocity) { - for (const std::vector& polygon : polygons) + for (const std::vector& polygon : polygons) { path_compiler->sendPolygon(type, polygon, line_width, line_thickness, velocity); } diff --git a/src/communication/ArcusCommunicationPrivate.cpp b/src/communication/ArcusCommunicationPrivate.cpp index 9d5f3118b2..81101dc9b2 100644 --- a/src/communication/ArcusCommunicationPrivate.cpp +++ b/src/communication/ArcusCommunicationPrivate.cpp @@ -127,7 +127,7 @@ void ArcusCommunication::Private::readMeshGroupMessage(const proto::ObjectList& const std::string data = object.vertices().substr(face * bytes_per_face, bytes_per_face); const Point3F* float_vertices = reinterpret_cast(data.data()); - Point3 verts[3]; + Point3LL verts[3]; verts[0] = matrix.apply(float_vertices[0].toPoint3d()); verts[1] = matrix.apply(float_vertices[1].toPoint3d()); verts[2] = matrix.apply(float_vertices[2].toPoint3d()); diff --git a/src/communication/CommandLine.cpp b/src/communication/CommandLine.cpp index e1a7b36e37..26dcaa60c3 100644 --- a/src/communication/CommandLine.cpp +++ b/src/communication/CommandLine.cpp @@ -37,7 +37,7 @@ void CommandLine::beginGCode() void CommandLine::flushGCode() { } -void CommandLine::sendCurrentPosition(const Point&) +void CommandLine::sendCurrentPosition(const Point2LL&) { } void CommandLine::sendFinishedSlicing() const @@ -46,7 +46,7 @@ void CommandLine::sendFinishedSlicing() const void CommandLine::sendLayerComplete(const LayerIndex::value_type&, const coord_t&, const coord_t&) { } -void CommandLine::sendLineTo(const PrintFeatureType&, const Point&, const coord_t&, const coord_t&, const Velocity&) +void CommandLine::sendLineTo(const PrintFeatureType&, const Point2LL&, const coord_t&, const coord_t&, const Velocity&) { } void CommandLine::sendOptimizedLayerData() diff --git a/src/gcodeExport.cpp b/src/gcodeExport.cpp index 82e45248b3..9726c9b39c 100644 --- a/src/gcodeExport.cpp +++ b/src/gcodeExport.cpp @@ -99,11 +99,11 @@ void GCodeExport::preSetup(const size_t start_extruder) if (use_extruder_offset_to_offset_coords_) { extruder_attr_[extruder_nr].nozzle_offset_ - = Point(extruder_settings.get("machine_nozzle_offset_x"), extruder_settings.get("machine_nozzle_offset_y")); + = Point2LL(extruder_settings.get("machine_nozzle_offset_x"), extruder_settings.get("machine_nozzle_offset_y")); } else { - extruder_attr_[extruder_nr].nozzle_offset_ = Point(0, 0); + extruder_attr_[extruder_nr].nozzle_offset_ = Point2LL(0, 0); } extruder_attr_[extruder_nr].machine_firmware_retract_ = extruder_settings.get("machine_firmware_retract"); } @@ -253,8 +253,8 @@ std::string GCodeExport::getFileHeader( if (total_bounding_box_.min_.x_ > total_bounding_box_.max_.x_) // We haven't encountered any movement (yet). This probably means we're command-line slicing. { // Put some small default in there. - total_bounding_box_.min_ = Point3(0, 0, 0); - total_bounding_box_.max_ = Point3(10, 10, 10); + total_bounding_box_.min_ = Point3LL(0, 0, 0); + total_bounding_box_.max_ = Point3LL(10, 10, 10); } prefix << ";PRINT.SIZE.MIN.X:" << INT2MM(total_bounding_box_.min_.x_) << new_line_; prefix << ";PRINT.SIZE.MIN.Y:" << INT2MM(total_bounding_box_.min_.y_) << new_line_; @@ -334,9 +334,9 @@ bool GCodeExport::getExtruderIsUsed(const int extruder_nr) const return extruder_attr_[extruder_nr].is_used_; } -Point GCodeExport::getGcodePos(const coord_t x, const coord_t y, const int extruder_train) const +Point2LL GCodeExport::getGcodePos(const coord_t x, const coord_t y, const int extruder_train) const { - return Point(x, y) - extruder_attr_[extruder_train].nozzle_offset_; + return Point2LL(x, y) - extruder_attr_[extruder_train].nozzle_offset_; } void GCodeExport::setFlavor(EGCodeFlavor flavor) @@ -387,13 +387,13 @@ void GCodeExport::setFlowRateExtrusionSettings(double max_extrusion_offset, doub this->extrusion_offset_factor_ = extrusion_offset_factor; } -Point3 GCodeExport::getPosition() const +Point3LL GCodeExport::getPosition() const { return current_position_; } -Point GCodeExport::getPositionXY() const +Point2LL GCodeExport::getPositionXY() const { - return Point(current_position_.x_, current_position_.y_); + return Point2LL(current_position_.x_, current_position_.y_); } int GCodeExport::getPositionZ() const @@ -827,16 +827,16 @@ void GCodeExport::writeDelay(const Duration& time_amount) estimate_calculator_.addTime(time_amount); } -void GCodeExport::writeTravel(const Point& p, const Velocity& speed) +void GCodeExport::writeTravel(const Point2LL& p, const Velocity& speed) { - writeTravel(Point3(p.X, p.Y, current_layer_z_), speed); + writeTravel(Point3LL(p.X, p.Y, current_layer_z_), speed); } -void GCodeExport::writeExtrusion(const Point& p, const Velocity& speed, double extrusion_mm3_per_mm, PrintFeatureType feature, bool update_extrusion_offset) +void GCodeExport::writeExtrusion(const Point2LL& p, const Velocity& speed, double extrusion_mm3_per_mm, PrintFeatureType feature, bool update_extrusion_offset) { - writeExtrusion(Point3(p.X, p.Y, current_layer_z_), speed, extrusion_mm3_per_mm, feature, update_extrusion_offset); + writeExtrusion(Point3LL(p.X, p.Y, current_layer_z_), speed, extrusion_mm3_per_mm, feature, update_extrusion_offset); } -void GCodeExport::writeTravel(const Point3& p, const Velocity& speed) +void GCodeExport::writeTravel(const Point3LL& p, const Velocity& speed) { if (flavor_ == EGCodeFlavor::BFB) { @@ -846,7 +846,7 @@ void GCodeExport::writeTravel(const Point3& p, const Velocity& speed) writeTravel(p.x_, p.y_, p.z_ + is_z_hopped_, speed); } -void GCodeExport::writeExtrusion(const Point3& p, const Velocity& speed, double extrusion_mm3_per_mm, PrintFeatureType feature, bool update_extrusion_offset) +void GCodeExport::writeExtrusion(const Point3LL& p, const Velocity& speed, double extrusion_mm3_per_mm, PrintFeatureType feature, bool update_extrusion_offset) { if (flavor_ == EGCodeFlavor::BFB) { @@ -873,7 +873,7 @@ void GCodeExport::writeMoveBFB(const int x, const int y, const int z, const Velo double extrusion_per_mm = mm3ToE(extrusion_mm3_per_mm); - Point gcode_pos = getGcodePos(x, y, current_extruder_); + Point2LL gcode_pos = getGcodePos(x, y, current_extruder_); // For Bits From Bytes machines, we need to handle this completely differently. As they do not use E values but RPM values. double fspeed = speed * 60; @@ -900,7 +900,7 @@ void GCodeExport::writeMoveBFB(const int x, const int y, const int z, const Velo fspeed *= (rpm / (roundf(rpm * 100) / 100)); // Increase the extrusion amount to calculate the amount of filament used. - Point3 diff = Point3(x, y, z) - getPosition(); + Point3LL diff = Point3LL(x, y, z) - getPosition(); current_e_value_ += extrusion_per_mm * diff.vSizeMM(); } @@ -917,7 +917,7 @@ void GCodeExport::writeMoveBFB(const int x, const int y, const int z, const Velo *output_stream_ << "G1 X" << MMtoStream{ gcode_pos.X } << " Y" << MMtoStream{ gcode_pos.Y } << " Z" << MMtoStream{ z }; *output_stream_ << " F" << PrecisionedDouble{ 1, fspeed } << new_line_; - current_position_ = Point3(x, y, z); + current_position_ = Point3LL(x, y, z); estimate_calculator_.plan( TimeEstimateCalculator::Position(INT2MM(current_position_.x_), INT2MM(current_position_.y_), INT2MM(current_position_.z_), eToMm(current_e_value_)), speed, @@ -934,14 +934,14 @@ void GCodeExport::writeTravel(const coord_t x, const coord_t y, const coord_t z, #ifdef ASSERT_INSANE_OUTPUT assert(speed < 1000 && speed > 1); // normal F values occurring in UM2 gcode (this code should not be compiled for release) assert(current_position_ != no_point3); - assert(Point3(x, y, z) != no_point3); - assert((Point3(x, y, z) - current_position_).vSize() < MM2INT(1000)); // no crazy positions (this code should not be compiled for release) + assert(Point3LL(x, y, z) != no_point3); + assert((Point3LL(x, y, z) - current_position_).vSize() < MM2INT(1000)); // no crazy positions (this code should not be compiled for release) #endif // ASSERT_INSANE_OUTPUT const PrintFeatureType travel_move_type = extruder_attr_[current_extruder_].retraction_e_amount_current_ ? PrintFeatureType::MoveRetraction : PrintFeatureType::MoveCombing; const int display_width = extruder_attr_[current_extruder_].retraction_e_amount_current_ ? MM2INT(0.2) : MM2INT(0.1); const double layer_height = Application::getInstance().current_slice_->scene.current_mesh_group->settings.get("layer_height"); - Application::getInstance().communication_->sendLineTo(travel_move_type, Point(x, y), display_width, layer_height, speed); + Application::getInstance().communication_->sendLineTo(travel_move_type, Point2LL(x, y), display_width, layer_height, speed); *output_stream_ << "G0"; writeFXYZE(speed, x, y, z, current_e_value_, travel_move_type); @@ -964,8 +964,8 @@ void GCodeExport::writeExtrusion( #ifdef ASSERT_INSANE_OUTPUT assert(speed < 1000 && speed > 1); // normal F values occurring in UM2 gcode (this code should not be compiled for release) assert(current_position_ != no_point3); - assert(Point3(x, y, z) != no_point3); - assert((Point3(x, y, z) - current_position_).vSize() < MM2INT(1000)); // no crazy positions (this code should not be compiled for release) + assert(Point3LL(x, y, z) != no_point3); + assert((Point3LL(x, y, z) - current_position_).vSize() < MM2INT(1000)); // no crazy positions (this code should not be compiled for release) assert(extrusion_mm3_per_mm >= 0.0); #endif // ASSERT_INSANE_OUTPUT #ifdef DEBUG @@ -996,7 +996,7 @@ void GCodeExport::writeExtrusion( writeZhopEnd(); } - const Point3 diff = Point3(x, y, z) - current_position_; + const Point3LL diff = Point3LL(x, y, z) - current_position_; const double diff_length = diff.vSizeMM(); writeUnretractionAndPrime(); @@ -1033,8 +1033,8 @@ void GCodeExport::writeFXYZE(const Velocity& speed, const coord_t x, const coord current_speed_ = speed; } - Point gcode_pos = getGcodePos(x, y, current_extruder_); - total_bounding_box_.include(Point3(gcode_pos.X, gcode_pos.Y, z)); + Point2LL gcode_pos = getGcodePos(x, y, current_extruder_); + total_bounding_box_.include(Point3LL(gcode_pos.X, gcode_pos.Y, z)); *output_stream_ << " X" << MMtoStream{ gcode_pos.X } << " Y" << MMtoStream{ gcode_pos.Y }; if (z != current_position_.z_) @@ -1048,7 +1048,7 @@ void GCodeExport::writeFXYZE(const Velocity& speed, const coord_t x, const coord } *output_stream_ << new_line_; - current_position_ = Point3(x, y, z); + current_position_ = Point3LL(x, y, z); current_e_value_ = e; estimate_calculator_.plan(TimeEstimateCalculator::Position(INT2MM(x), INT2MM(y), INT2MM(z), eToMm(e)), speed, feature); } @@ -1357,14 +1357,14 @@ void GCodeExport::writePrimeTrain(const Velocity& travel_speed) // ideally the prime position would be respected whether we do a blob or not, // but the frontend currently doesn't support a value function of an extruder setting depending on an fdmprinter setting, // which is needed to automatically ignore the prime position for the printer when blob is disabled - Point3 prime_pos( + Point3LL prime_pos( extruder_settings.get("extruder_prime_pos_x"), extruder_settings.get("extruder_prime_pos_y"), extruder_settings.get("extruder_prime_pos_z")); if (! extruder_settings.get("extruder_prime_pos_abs")) { // currentPosition.z can be already z hopped - prime_pos += Point3(current_position_.x_, current_position_.y_, current_layer_z_); + prime_pos += Point3LL(current_position_.x_, current_position_.y_, current_layer_z_); } writeTravel(prime_pos, travel_speed); } @@ -1674,7 +1674,7 @@ void GCodeExport::ResetLastEValueAfterWipe(size_t extruder) void GCodeExport::insertWipeScript(const WipeScriptConfig& wipe_config) { - const Point3 prev_position = current_position_; + const Point3LL prev_position = current_position_; writeComment("WIPE_SCRIPT_BEGIN"); if (wipe_config.retraction_enable) @@ -1687,11 +1687,11 @@ void GCodeExport::insertWipeScript(const WipeScriptConfig& wipe_config) writeZhopStart(wipe_config.hop_amount, wipe_config.hop_speed); } - writeTravel(Point(wipe_config.brush_pos_x, current_position_.y_), wipe_config.move_speed); + writeTravel(Point2LL(wipe_config.brush_pos_x, current_position_.y_), wipe_config.move_speed); for (size_t i = 0; i < wipe_config.repeat_count; ++i) { coord_t x = current_position_.x_ + (i % 2 ? -wipe_config.move_distance : wipe_config.move_distance); - writeTravel(Point(x, current_position_.y_), wipe_config.move_speed); + writeTravel(Point2LL(x, current_position_.y_), wipe_config.move_speed); } writeTravel(prev_position, wipe_config.move_speed); diff --git a/src/infill.cpp b/src/infill.cpp index 2deda6f1b8..e746846c02 100644 --- a/src/infill.cpp +++ b/src/infill.cpp @@ -347,7 +347,7 @@ void Infill::_generate( || pattern_ == EFillMethod::ZIG_ZAG)) { // don't stich for non-zig-zagged line infill types Polygons stitched_lines; - PolylineStitcher::stitch(result_lines, stitched_lines, result_polygons, infill_line_width_); + PolylineStitcher::stitch(result_lines, stitched_lines, result_polygons, infill_line_width_); result_lines = stitched_lines; } result_lines = simplifier.polyline(result_lines); @@ -419,7 +419,7 @@ void Infill::multiplyInfill(Polygons& result_polygons, Polygons& result_lines) } Polygons polylines = inner_contour_.intersectionPolyLines(result_polygons); result_polygons.clear(); - PolylineStitcher::stitch(polylines, result_lines, result_polygons, infill_line_width_); + PolylineStitcher::stitch(polylines, result_lines, result_polygons, infill_line_width_); } } @@ -427,7 +427,7 @@ void Infill::generateGyroidInfill(Polygons& result_lines, Polygons& result_polyg { Polygons line_segments; GyroidInfill::generateTotalGyroidInfill(line_segments, zig_zaggify_, line_distance_, inner_contour_, z_); - PolylineStitcher::stitch(line_segments, result_lines, result_polygons, infill_line_width_); + PolylineStitcher::stitch(line_segments, result_lines, result_polygons, infill_line_width_); } void Infill::generateLightningInfill(const std::shared_ptr& trees, Polygons& result_lines) @@ -550,7 +550,7 @@ void Infill::generateCrossInfill(const SierpinskiFillProvider& cross_fill_provid Polygons cross_pattern_polylines; cross_pattern_polylines.add(cross_pattern_polygon); Polygons poly_lines = inner_contour_.intersectionPolyLines(cross_pattern_polylines); - PolylineStitcher::stitch(poly_lines, result_lines, result_polygons, infill_line_width_); + PolylineStitcher::stitch(poly_lines, result_lines, result_polygons, infill_line_width_); } } @@ -580,7 +580,7 @@ void Infill::addLineInfill( { // segment is too short to create infill continue; } - result.addLine(rotation_matrix.unapply(Point(x, crossings[crossing_idx])), rotation_matrix.unapply(Point(x, crossings[crossing_idx + 1]))); + result.addLine(rotation_matrix.unapply(Point2LL(x, crossings[crossing_idx])), rotation_matrix.unapply(Point2LL(x, crossings[crossing_idx + 1]))); } scanline_idx += 1; } @@ -675,11 +675,11 @@ void Infill::generateLinearBasedInfill( // Then we can later join two crossings together to form lines and still know what polygon line segments that infill line connected to. struct Crossing { - Point coordinate_; + Point2LL coordinate_; size_t polygon_index_; size_t vertex_index_; - Crossing(Point coordinate, size_t polygon_index, size_t vertex_index) + Crossing(Point2LL coordinate, size_t polygon_index, size_t vertex_index) : coordinate_(coordinate) , polygon_index_(polygon_index) , vertex_index_(vertex_index) @@ -707,12 +707,12 @@ void Infill::generateLinearBasedInfill( { crossings_on_line_[poly_idx].resize(poly.size()); // One for each line in this polygon. } - Point p0 = poly.back(); + Point2LL p0 = poly.back(); zigzag_connector_processor.registerVertex(p0); // always adds the first point to ZigzagConnectorProcessorEndPieces::first_zigzag_connector when using a zigzag infill type for (size_t point_idx = 0; point_idx < poly.size(); point_idx++) { - Point p1 = poly[point_idx]; + Point2LL p1 = poly[point_idx]; if (p1.X == p0.X) { zigzag_connector_processor.registerVertex(p1); @@ -748,7 +748,7 @@ void Infill::generateLinearBasedInfill( int y = p1.Y + (p0.Y - p1.Y) * (x - p1.X) / (p0.X - p1.X); assert(scanline_idx - scanline_min_idx >= 0 && scanline_idx - scanline_min_idx < int(cut_list.size()) && "reading infill cutlist index out of bounds!"); cut_list[scanline_idx - scanline_min_idx].push_back(y); - Point scanline_linesegment_intersection(x, y); + Point2LL scanline_linesegment_intersection(x, y); zigzag_connector_processor.registerScanlineSegmentIntersection(scanline_linesegment_intersection, scanline_idx); crossings_per_scanline[scanline_idx - min_scanline_index].emplace_back(scanline_linesegment_intersection, poly_idx, point_idx); } @@ -772,8 +772,8 @@ void Infill::generateLinearBasedInfill( const Crossing& first = crossings[crossing_index]; const Crossing& second = crossings[crossing_index + 1]; // Avoid creating zero length crossing lines - const Point unrotated_first = rotation_matrix.unapply(first.coordinate_); - const Point unrotated_second = rotation_matrix.unapply(second.coordinate_); + const Point2LL unrotated_first = rotation_matrix.unapply(first.coordinate_); + const Point2LL unrotated_second = rotation_matrix.unapply(second.coordinate_); if (unrotated_first == unrotated_second) { continue; @@ -802,7 +802,7 @@ void Infill::generateLinearBasedInfill( } } -void Infill::resolveIntersection(const coord_t at_distance, const Point& intersect, Point& connect_start, Point& connect_end, InfillLineSegment* a, InfillLineSegment* b) +void Infill::resolveIntersection(const coord_t at_distance, const Point2LL& intersect, Point2LL& connect_start, Point2LL& connect_end, InfillLineSegment* a, InfillLineSegment* b) { // Select wich ends of the line need to 'bend'. const bool forward_line_a = a->end_ == connect_start; @@ -821,7 +821,7 @@ void Infill::resolveIntersection(const coord_t at_distance, const Point& interse // Find a bisector of the intersection; specifically, the one that crosses the connection & offset it by 1/2 distance to each side. constexpr auto large_enough_vec_len = 0xFFFFFFFF; const auto bisect = LinearAlg2D::getBisectorVector(intersect, connect_start, connect_end, large_enough_vec_len); - const auto offset = ((at_distance / 2) * Point(-bisect.Y, bisect.X)) / large_enough_vec_len; + const auto offset = ((at_distance / 2) * Point2LL(-bisect.Y, bisect.X)) / large_enough_vec_len; const auto q = intersect + offset; const auto r = q + bisect; const auto s = intersect - offset; @@ -881,12 +881,12 @@ void Infill::connectLines(Polygons& result_lines) std::vector>& crossings_on_polygon = crossings_on_line_[polygon_index]; InfillLineSegment* previous_crossing = nullptr; // The crossing that we should connect to. If nullptr, we have been skipping until we find the next crossing. InfillLineSegment* previous_segment = nullptr; // The last segment we were connecting while drawing a line along the border. - Point vertex_before = inner_contour_polygon.back(); + Point2LL vertex_before = inner_contour_polygon.back(); for (size_t vertex_index = 0; vertex_index < inner_contour_polygon.size(); vertex_index++) { assert(crossings_on_polygon.size() > vertex_index && "crossings on line for the current polygon should be bigger then vertex index"); std::vector& crossings_on_polygon_segment = crossings_on_polygon[vertex_index]; - Point vertex_after = inner_contour_polygon[vertex_index]; + Point2LL vertex_after = inner_contour_polygon[vertex_index]; // Sort crossings on every line by how far they are from their initial point. std::sort( @@ -897,8 +897,8 @@ void Infill::connectLines(Polygons& result_lines) // Find the two endpoints that are relevant. const bool choose_left = (left_hand_side->start_segment_ == vertex_index && left_hand_side->start_polygon_ == polygon_index); const bool choose_right = (right_hand_side->start_segment_ == vertex_index && right_hand_side->start_polygon_ == polygon_index); - const Point left_hand_point = choose_left ? left_hand_side->start_ : left_hand_side->end_; - const Point right_hand_point = choose_right ? right_hand_side->start_ : right_hand_side->end_; + const Point2LL left_hand_point = choose_left ? left_hand_side->start_ : left_hand_side->end_; + const Point2LL right_hand_point = choose_right ? right_hand_side->start_ : right_hand_side->end_; return vSize(left_hand_point - vertex_before) < vSize(right_hand_point - vertex_before); }); @@ -925,8 +925,8 @@ void Infill::connectLines(Polygons& result_lines) // Here the InfillLineSegments function as a linked list, so that they can easily be joined. const bool previous_forward = (previous_segment->start_segment_ == vertex_index && previous_segment->start_polygon_ == polygon_index); const bool next_forward = (crossing->start_segment_ == vertex_index && crossing->start_polygon_ == polygon_index); - Point& previous_point = previous_forward ? previous_segment->start_ : previous_segment->end_; - Point& next_point = next_forward ? crossing->start_ : crossing->end_; + Point2LL& previous_point = previous_forward ? previous_segment->start_ : previous_segment->end_; + Point2LL& next_point = next_forward ? crossing->start_ : crossing->end_; InfillLineSegment* new_segment; // If the segment is near length, we avoid creating it but still want to connect the crossing with the previous segment. @@ -938,7 +938,7 @@ void Infill::connectLines(Polygons& result_lines) else { // Resolve any intersections of the fill lines close to the boundary, by inserting extra points so the lines don't create a tiny 'loop'. - Point intersect; + Point2LL intersect; if (vSize2(previous_point - next_point) < half_line_distance_squared && LinearAlg2D::lineLineIntersection(previous_segment->start_, previous_segment->end_, crossing->start_, crossing->end_, intersect) && LinearAlg2D::pointIsProjectedBeyondLine(intersect, previous_segment->start_, previous_segment->end_) == 0 @@ -1003,12 +1003,12 @@ void Infill::connectLines(Polygons& result_lines) // Find where the polyline ends by searching through previous and next lines. // Note that the "previous" and "next" lines don't necessarily match up though, because the direction while connecting infill lines was not yet known. - Point previous_vertex = infill_line->start_; // Take one side arbitrarily to start from. This variable indicates the vertex that connects to the previous line. + Point2LL previous_vertex = infill_line->start_; // Take one side arbitrarily to start from. This variable indicates the vertex that connects to the previous line. InfillLineSegment* current_infill_line = infill_line; while (current_infill_line->next_ && current_infill_line->previous_) // Until we reached an endpoint. { const bool choose_side = (previous_vertex == current_infill_line->start_); - const Point next_vertex = choose_side ? current_infill_line->end_ : current_infill_line->start_; + const Point2LL next_vertex = choose_side ? current_infill_line->end_ : current_infill_line->start_; current_infill_line = choose_side ? current_infill_line->next_ : current_infill_line->previous_; previous_vertex = next_vertex; } @@ -1031,7 +1031,7 @@ void Infill::connectLines(Polygons& result_lines) { current_infill_line->swapDirection(); } - const Point next_vertex = current_infill_line->end_; // Opposite side of the line. + const Point2LL next_vertex = current_infill_line->end_; // Opposite side of the line. constexpr bool polyline_break = false; current_infill_line->appendTo(result_line, polyline_break); current_infill_line = current_infill_line->next_; diff --git a/src/infill/GyroidInfill.cpp b/src/infill/GyroidInfill.cpp index 253cabdea9..6a95df7d54 100644 --- a/src/infill/GyroidInfill.cpp +++ b/src/infill/GyroidInfill.cpp @@ -40,7 +40,7 @@ void GyroidInfill::generateTotalGyroidInfill(Polygons& result_lines, bool zig_za std::vector odd_line_coords; std::vector even_line_coords; Polygons result; - std::vector chains[2]; // [start_points[], end_points[]] + std::vector chains[2]; // [start_points[], end_points[]] std::vector connected_to[2]; // [chain_indices[], chain_indices[]] std::vector line_numbers; // which row/column line a chain is part of if (std::abs(sin_z) <= std::abs(cos_z)) @@ -65,15 +65,15 @@ void GyroidInfill::generateTotalGyroidInfill(Polygons& result_lines, bool zig_za for (coord_t x = (std::floor(aabb.min_.X / pitch) - 2.25) * pitch; x <= aabb.max_.X + pitch / 2; x += pitch / 2) { bool is_first_point = true; - Point last; + Point2LL last; bool last_inside = false; unsigned chain_end_index = 0; - Point chain_end[2]; + Point2LL chain_end[2]; for (coord_t y = (std::floor(aabb.min_.Y / pitch) - 1) * pitch; y <= aabb.max_.Y + pitch; y += pitch) { for (unsigned i = 0; i < num_coords; ++i) { - Point current(x + ((num_columns & 1) ? odd_line_coords[i] : even_line_coords[i]) / 2 + pitch, y + (coord_t)(i * step)); + Point2LL current(x + ((num_columns & 1) ? odd_line_coords[i] : even_line_coords[i]) / 2 + pitch, y + (coord_t)(i * step)); bool current_inside = in_outline.inside(current, true); if (! is_first_point) { @@ -157,15 +157,15 @@ void GyroidInfill::generateTotalGyroidInfill(Polygons& result_lines, bool zig_za for (coord_t y = (std::floor(aabb.min_.Y / pitch) - 1) * pitch; y <= aabb.max_.Y + pitch / 2; y += pitch / 2) { bool is_first_point = true; - Point last; + Point2LL last; bool last_inside = false; unsigned chain_end_index = 0; - Point chain_end[2]; + Point2LL chain_end[2]; for (coord_t x = (std::floor(aabb.min_.X / pitch) - 1) * pitch; x <= aabb.max_.X + pitch; x += pitch) { for (unsigned i = 0; i < num_coords; ++i) { - Point current(x + (coord_t)(i * step), y + ((num_rows & 1) ? odd_line_coords[i] : even_line_coords[i]) / 2); + Point2LL current(x + (coord_t)(i * step), y + ((num_rows & 1) ? odd_line_coords[i] : even_line_coords[i]) / 2); bool current_inside = in_outline.inside(current, true); if (! is_first_point) { @@ -240,12 +240,12 @@ void GyroidInfill::generateTotalGyroidInfill(Polygons& result_lines, bool zig_za for (ConstPolygonRef outline_poly : in_outline) { - std::vector connector_points; // the points that make up a connector line + std::vector connector_points; // the points that make up a connector line // we need to remember the first chain processed and the path to it from the first outline point // so that later we can possibly connect to it from the last chain processed unsigned first_chain_chain_index = std::numeric_limits::max(); - std::vector path_to_first_chain; + std::vector path_to_first_chain; bool drawing = false; // true when a connector line is being (potentially) created @@ -253,14 +253,14 @@ void GyroidInfill::generateTotalGyroidInfill(Polygons& result_lines, bool zig_za unsigned connector_start_chain_index = std::numeric_limits::max(); unsigned connector_start_point_index = std::numeric_limits::max(); - Point cur_point; // current point of interest - either an outline point or a chain end + Point2LL cur_point; // current point of interest - either an outline point or a chain end // go round all of the region's outline and find the chain ends that meet it // quit the loop early if we have seen all the chain ends and are not currently drawing a connector for (unsigned outline_point_index = 0; (chain_ends_remaining > 0 || drawing) && outline_point_index < outline_poly.size(); ++outline_point_index) { - Point op0 = outline_poly[outline_point_index]; - Point op1 = outline_poly[(outline_point_index + 1) % outline_poly.size()]; + Point2LL op0 = outline_poly[outline_point_index]; + Point2LL op1 = outline_poly[(outline_point_index + 1) % outline_poly.size()]; std::vector points_on_outline_chain_index; std::vector points_on_outline_point_index; diff --git a/src/infill/ImageBasedDensityProvider.cpp b/src/infill/ImageBasedDensityProvider.cpp index 2835d05351..66e53fcc63 100644 --- a/src/infill/ImageBasedDensityProvider.cpp +++ b/src/infill/ImageBasedDensityProvider.cpp @@ -23,7 +23,7 @@ ImageBasedDensityProvider::ImageBasedDensityProvider(const std::string filename, int desired_channel_count = 0; // keep original amount of channels int img_x, img_y, img_z; // stbi requires pointer to int rather than to coord_t image = stbi_load(filename.c_str(), &img_x, &img_y, &img_z, desired_channel_count); - image_size = Point3(img_x, img_y, img_z); + image_size = Point3LL(img_x, img_y, img_z); if (! image) { const char* reason = "[unknown reason]"; @@ -35,12 +35,12 @@ ImageBasedDensityProvider::ImageBasedDensityProvider(const std::string filename, std::exit(-1); } { // compute aabb - Point middle = model_aabb.getMiddle(); - Point model_aabb_size = model_aabb.max_ - model_aabb.min_; - Point image_size2 = Point(image_size.x_, image_size.y_); + Point2LL middle = model_aabb.getMiddle(); + Point2LL model_aabb_size = model_aabb.max_ - model_aabb.min_; + Point2LL image_size2 = Point2LL(image_size.x_, image_size.y_); double aabb_aspect_ratio = double(model_aabb_size.X) / double(model_aabb_size.Y); double image_aspect_ratio = double(image_size.x_) / double(image_size.y_); - Point aabb_size; + Point2LL aabb_size; if (image_aspect_ratio < aabb_aspect_ratio) { aabb_size = image_size2 * model_aabb_size.X / image_size.x_; @@ -65,9 +65,9 @@ ImageBasedDensityProvider::~ImageBasedDensityProvider() double ImageBasedDensityProvider::operator()(const AABB3D& query_cube) const { - AABB query_box(Point(query_cube.min_.x_, query_cube.min_.y_), Point(query_cube.max_.x_, query_cube.max_.y_)); - Point img_min = (query_box.min_ - print_aabb.min_ - Point(1, 1)) * image_size.x_ / (print_aabb.max_.X - print_aabb.min_.X); - Point img_max = (query_box.max_ - print_aabb.min_ + Point(1, 1)) * image_size.y_ / (print_aabb.max_.Y - print_aabb.min_.Y); + AABB query_box(Point2LL(query_cube.min_.x_, query_cube.min_.y_), Point2LL(query_cube.max_.x_, query_cube.max_.y_)); + Point2LL img_min = (query_box.min_ - print_aabb.min_ - Point2LL(1, 1)) * image_size.x_ / (print_aabb.max_.X - print_aabb.min_.X); + Point2LL img_max = (query_box.max_ - print_aabb.min_ + Point2LL(1, 1)) * image_size.y_ / (print_aabb.max_.Y - print_aabb.min_.Y); long total_lightness = 0; int value_count = 0; for (int x = std::max((coord_t)0, img_min.X); x <= std::min((coord_t)image_size.x_ - 1, img_max.X); x++) @@ -83,7 +83,7 @@ double ImageBasedDensityProvider::operator()(const AABB3D& query_cube) const } if (value_count == 0) { // triangle falls outside of image or in between pixels, so we return the closest pixel - Point closest_pixel = (img_min + img_max) / 2; + Point2LL closest_pixel = (img_min + img_max) / 2; closest_pixel.X = std::max((coord_t)0, std::min((coord_t)image_size.x_ - 1, (coord_t)closest_pixel.X)); closest_pixel.Y = std::max((coord_t)0, std::min((coord_t)image_size.y_ - 1, (coord_t)closest_pixel.Y)); assert(total_lightness == 0); diff --git a/src/infill/LightningDistanceField.cpp b/src/infill/LightningDistanceField.cpp index 0c532b8ced..923eb1e8b8 100644 --- a/src/infill/LightningDistanceField.cpp +++ b/src/infill/LightningDistanceField.cpp @@ -17,7 +17,7 @@ LightningDistanceField::LightningDistanceField(const coord_t& radius, const Poly , current_outline_(current_outline) , current_overhang_(current_overhang) { - std::vector regular_dots = PolygonUtils::spreadDotsArea(current_overhang, cell_size_); + std::vector regular_dots = PolygonUtils::spreadDotsArea(current_overhang, cell_size_); for (const auto& p : regular_dots) { const ClosestPolygonPoint cpp = PolygonUtils::findClosest(p, current_outline); @@ -29,7 +29,7 @@ LightningDistanceField::LightningDistanceField(const coord_t& radius, const Poly { constexpr coord_t prime_for_hash = 191; return std::abs(b.dist_to_boundary_ - a.dist_to_boundary_) > radius ? a.dist_to_boundary_ < b.dist_to_boundary_ - : (std::hash{}(a.loc_) % prime_for_hash) < (std::hash{}(b.loc_) % prime_for_hash); + : (std::hash{}(a.loc_) % prime_for_hash) < (std::hash{}(b.loc_) % prime_for_hash); }); for (auto it = unsupported_points_.begin(); it != unsupported_points_.end(); ++it) { @@ -38,7 +38,7 @@ LightningDistanceField::LightningDistanceField(const coord_t& radius, const Poly } } -bool LightningDistanceField::tryGetNextPoint(Point* p) const +bool LightningDistanceField::tryGetNextPoint(Point2LL* p) const { if (unsupported_points_.empty()) { @@ -48,7 +48,7 @@ bool LightningDistanceField::tryGetNextPoint(Point* p) const return true; } -void LightningDistanceField::update(const Point& to_node, const Point& added_leaf) +void LightningDistanceField::update(const Point2LL& to_node, const Point2LL& added_leaf) { auto process_func = [added_leaf, this](const SquareGrid::GridPoint& grid_loc) { @@ -65,11 +65,11 @@ void LightningDistanceField::update(const Point& to_node, const Point& added_lea } return true; }; - const Point a = to_node; - const Point b = added_leaf; - Point ab = b - a; - Point ab_T = turn90CCW(ab); - Point extent = normal(ab_T, supporting_radius_); + const Point2LL a = to_node; + const Point2LL b = added_leaf; + Point2LL ab = b - a; + Point2LL ab_T = turn90CCW(ab); + Point2LL extent = normal(ab_T, supporting_radius_); // TODO: process cells only once; make use of PolygonUtils::spreadDotsArea grid_.processLineCells( std::make_pair(a + extent, a - extent), diff --git a/src/infill/LightningLayer.cpp b/src/infill/LightningLayer.cpp index 3226c0b546..cd689e1bfc 100644 --- a/src/infill/LightningLayer.cpp +++ b/src/infill/LightningLayer.cpp @@ -14,12 +14,12 @@ using namespace cura; -coord_t LightningLayer::getWeightedDistance(const Point& boundary_loc, const Point& unsupported_location) +coord_t LightningLayer::getWeightedDistance(const Point2LL& boundary_loc, const Point2LL& unsupported_location) { return vSize(boundary_loc - unsupported_location); } -Point GroundingLocation::p() const +Point2LL GroundingLocation::p() const { if (tree_node != nullptr) { @@ -61,7 +61,7 @@ void LightningLayer::generateNewTrees // Until no more points need to be added to support all: // Determine next point from tree/outline areas via distance-field - Point unsupported_location; + Point2LL unsupported_location; while (distance_field.tryGetNextPoint(&unsupported_location)) { GroundingLocation grounding_loc = @@ -91,7 +91,7 @@ void LightningLayer::generateNewTrees GroundingLocation LightningLayer::getBestGroundingLocation ( - const Point& unsupported_location, + const Point2LL& unsupported_location, const Polygons& current_outlines, const LocToLineGrid& outline_locator, const coord_t supporting_radius, @@ -101,7 +101,7 @@ GroundingLocation LightningLayer::getBestGroundingLocation ) { ClosestPolygonPoint cpp = PolygonUtils::findClosest(unsupported_location, current_outlines); - Point node_location = cpp.p(); + Point2LL node_location = cpp.p(); const coord_t within_dist = vSize(node_location - unsupported_location); PolygonsPointIndex dummy; @@ -143,7 +143,7 @@ GroundingLocation LightningLayer::getBestGroundingLocation bool LightningLayer::attach ( - const Point& unsupported_location, + const Point2LL& unsupported_location, const GroundingLocation& grounding_loc, LightningTreeNodeSPtr& new_child, LightningTreeNodeSPtr& new_root @@ -185,10 +185,10 @@ void LightningLayer::reconnectRoots if (root_ptr->getLastGroundingLocation()) { - const Point& ground_loc = root_ptr->getLastGroundingLocation().value(); + const Point2LL& ground_loc = root_ptr->getLastGroundingLocation().value(); if (ground_loc != root_ptr->getLocation()) { - Point new_root_pt; + Point2LL new_root_pt; if (PolygonUtils::lineSegmentPolygonsIntersection(root_ptr->getLocation(), ground_loc, current_outlines, outline_locator, new_root_pt, within_max_dist)) { auto new_root = LightningTreeNode::create(new_root_pt, new_root_pt); diff --git a/src/infill/LightningTreeNode.cpp b/src/infill/LightningTreeNode.cpp index 3347a2ae63..573cffb80a 100644 --- a/src/infill/LightningTreeNode.cpp +++ b/src/infill/LightningTreeNode.cpp @@ -9,7 +9,7 @@ using namespace cura; using LightningTreeNodeSPtr = std::shared_ptr; -coord_t LightningTreeNode::getWeightedDistance(const Point& unsupported_location, const coord_t& supporting_radius) const +coord_t LightningTreeNode::getWeightedDistance(const Point2LL& unsupported_location, const coord_t& supporting_radius) const { constexpr coord_t min_valence_for_boost = 0; constexpr coord_t max_valence_for_boost = 4; @@ -35,17 +35,17 @@ bool LightningTreeNode::hasOffspring(const LightningTreeNodeSPtr& to_be_checked) return false; } -const Point& LightningTreeNode::getLocation() const +const Point2LL& LightningTreeNode::getLocation() const { return p_; } -void LightningTreeNode::setLocation(const Point& loc) +void LightningTreeNode::setLocation(const Point2LL& loc) { p_ = loc; } -LightningTreeNodeSPtr LightningTreeNode::addChild(const Point& child_loc) +LightningTreeNodeSPtr LightningTreeNode::addChild(const Point2LL& child_loc) { assert(p_ != child_loc); LightningTreeNodeSPtr child = LightningTreeNode::create(child_loc); @@ -82,7 +82,7 @@ void LightningTreeNode::propagateToNextLayer( // NOTE: Depth-first, as currently implemented. // Skips the root (because that has no root itself), but all initial nodes will have the root point anyway. -void LightningTreeNode::visitBranches(const std::function& visitor) const +void LightningTreeNode::visitBranches(const std::function& visitor) const { for (const auto& node : children_) { @@ -103,7 +103,7 @@ void LightningTreeNode::visitNodes(const std::function& last_grounding_location /*= std::nullopt*/) +LightningTreeNode::LightningTreeNode(const Point2LL& p, const std::optional& last_grounding_location /*= std::nullopt*/) : is_root_(true) , p_(p) , last_grounding_location_(last_grounding_location) @@ -150,7 +150,7 @@ void LightningTreeNode::reroot(LightningTreeNodeSPtr new_parent /*= nullptr*/) } } -LightningTreeNodeSPtr LightningTreeNode::closestNode(const Point& loc) +LightningTreeNodeSPtr LightningTreeNode::closestNode(const Point2LL& loc) { LightningTreeNodeSPtr result = shared_from_this(); coord_t closest_dist2 = vSize2(p_ - loc); @@ -179,7 +179,7 @@ bool LightningTreeNode::realign(const Polygons& outlines, const LocToLineGrid& o if (outlines.inside(p_, true)) { // Only keep children that have an unbroken connection to here, realign will put the rest in rerooted parts due to recursion: - Point coll; + Point2LL coll; bool reground_me = false; const auto remove_unconnected_func{ [&](const LightningTreeNodeSPtr& child) @@ -228,7 +228,7 @@ void LightningTreeNode::straighten(const coord_t magnitude, const coord_t max_re } LightningTreeNode::RectilinearJunction - LightningTreeNode::straighten(const coord_t magnitude, const Point& junction_above, const coord_t accumulated_dist, const coord_t max_remove_colinear_dist2) + LightningTreeNode::straighten(const coord_t magnitude, const Point2LL& junction_above, const coord_t accumulated_dist, const coord_t max_remove_colinear_dist2) { constexpr coord_t junction_magnitude_factor_numerator = 3; constexpr coord_t junction_magnitude_factor_denominator = 4; @@ -240,12 +240,12 @@ LightningTreeNode::RectilinearJunction coord_t child_dist = vSize(p_ - child_p->p_); RectilinearJunction junction_below = child_p->straighten(magnitude, junction_above, accumulated_dist + child_dist, max_remove_colinear_dist2); coord_t total_dist_to_junction_below = junction_below.total_recti_dist; - Point a = junction_above; - Point b = junction_below.junction_loc; + Point2LL a = junction_above; + Point2LL b = junction_below.junction_loc; if (a != b) // should always be true! { - Point ab = b - a; - Point destination = a + ab * accumulated_dist / std::max(coord_t(1), total_dist_to_junction_below); + Point2LL ab = b - a; + Point2LL destination = a + ab * accumulated_dist / std::max(coord_t(1), total_dist_to_junction_below); if (shorterThen(destination - p_, magnitude)) { p_ = destination; @@ -279,7 +279,7 @@ LightningTreeNode::RectilinearJunction else { constexpr coord_t weight = 1000; - Point junction_moving_dir = normal(junction_above - p_, weight); + Point2LL junction_moving_dir = normal(junction_above - p_, weight); bool prevent_junction_moving = false; for (auto& child_p : children_) { @@ -292,7 +292,7 @@ LightningTreeNode::RectilinearJunction prevent_junction_moving = true; // prevent flipflopping in branches due to straightening and junctoin moving clashing } } - if (junction_moving_dir != Point(0, 0) && ! children_.empty() && ! is_root_ && ! prevent_junction_moving) + if (junction_moving_dir != Point2LL(0, 0) && ! children_.empty() && ! is_root_ && ! prevent_junction_moving) { coord_t junction_moving_dir_len = vSize(junction_moving_dir); if (junction_moving_dir_len > junction_magnitude) @@ -325,9 +325,9 @@ coord_t LightningTreeNode::prune(const coord_t& pruning_distance) } else { - const Point a = getLocation(); - const Point b = child->getLocation(); - const Point ba = a - b; + const Point2LL a = getLocation(); + const Point2LL b = child->getLocation(); + const Point2LL ba = a - b; const coord_t ab_len = vSize(ba); if (dist_pruned_child + ab_len <= pruning_distance) { // we're still in the process of pruning @@ -337,7 +337,7 @@ coord_t LightningTreeNode::prune(const coord_t& pruning_distance) } else { // pruning stops in between this node and the child - const Point n = b + normal(ba, pruning_distance - dist_pruned_child); + const Point2LL n = b + normal(ba, pruning_distance - dist_pruned_child); assert(std::abs(vSize(n - b) + dist_pruned_child - pruning_distance) < 10 && "total pruned distance must be equal to the pruning_distance"); max_distance_pruned = std::max(max_distance_pruned, pruning_distance); child->setLocation(n); @@ -349,7 +349,7 @@ coord_t LightningTreeNode::prune(const coord_t& pruning_distance) return max_distance_pruned; } -const std::optional& LightningTreeNode::getLastGroundingLocation() const +const std::optional& LightningTreeNode::getLastGroundingLocation() const { return last_grounding_location_; } @@ -399,11 +399,11 @@ void LightningTreeNode::removeJunctionOverlap(Polygons& result_lines, const coor } coord_t to_be_reduced = reduction; - Point a = polyline.back(); + Point2LL a = polyline.back(); for (int point_idx = polyline.size() - 2; point_idx >= 0; point_idx--) { - const Point b = polyline[point_idx]; - const Point ab = b - a; + const Point2LL b = polyline[point_idx]; + const Point2LL ab = b - a; const coord_t ab_len = vSize(ab); if (ab_len >= to_be_reduced) { diff --git a/src/infill/NoZigZagConnectorProcessor.cpp b/src/infill/NoZigZagConnectorProcessor.cpp index 883f9bba98..5deaa551ac 100644 --- a/src/infill/NoZigZagConnectorProcessor.cpp +++ b/src/infill/NoZigZagConnectorProcessor.cpp @@ -9,12 +9,12 @@ namespace cura { -void NoZigZagConnectorProcessor::registerVertex(const Point&) +void NoZigZagConnectorProcessor::registerVertex(const Point2LL&) { //No need to add anything. } -void NoZigZagConnectorProcessor::registerScanlineSegmentIntersection(const Point&, int) +void NoZigZagConnectorProcessor::registerScanlineSegmentIntersection(const Point2LL&, int) { //No need to add anything. } diff --git a/src/infill/SierpinskiFill.cpp b/src/infill/SierpinskiFill.cpp index b1dc6f545a..bdb4962228 100644 --- a/src/infill/SierpinskiFill.cpp +++ b/src/infill/SierpinskiFill.cpp @@ -66,8 +66,8 @@ SierpinskiFill::~SierpinskiFill() void SierpinskiFill::createTree() { - Point lt = Point(aabb_.min_.X, aabb_.max_.Y); - Point rb = Point(aabb_.max_.X, aabb_.min_.Y); + Point2LL lt = Point2LL(aabb_.min_.X, aabb_.max_.Y); + Point2LL rb = Point2LL(aabb_.max_.X, aabb_.min_.Y); bool root_straight_corner_is_left = false; int root_depth = 1; @@ -89,7 +89,7 @@ void SierpinskiFill::createTree(SierpinskiTriangle& sub_root) if (sub_root.depth_ < max_depth_) // We need to subdivide. { SierpinskiTriangle& t = sub_root; - Point middle = (t.a_ + t.b_) / 2; + Point2LL middle = (t.a_ + t.b_) / 2; // At each subdivision we divide the triangle in two. // Figure out which sort of triangle each child will be: SierpinskiTriangle::SierpinskiDirection first_dir, second_dir; @@ -119,7 +119,7 @@ void SierpinskiFill::createTree(SierpinskiTriangle& sub_root) } void SierpinskiFill::createTreeStatistics(SierpinskiTriangle& triangle) { - Point ac = triangle.straight_corner_ - triangle.a_; + Point2LL ac = triangle.straight_corner_ - triangle.a_; double area = 0.5 * INT2MM2(vSize2(ac)); double short_length = .5 * vSizeMM(ac); double long_length = .5 * vSizeMM(triangle.b_ - triangle.a_); @@ -140,7 +140,7 @@ void SierpinskiFill::createTreeRequestedLengths(SierpinskiTriangle& triangle) triangle_aabb.include(triangle.a_); triangle_aabb.include(triangle.b_); triangle_aabb.include(triangle.straight_corner_); - AABB3D triangle_aabb3d(Point3(triangle_aabb.min_.X, triangle_aabb.min_.Y, 0), Point3(triangle_aabb.max_.X, triangle_aabb.max_.Y, 1)); + AABB3D triangle_aabb3d(Point3LL(triangle_aabb.min_.X, triangle_aabb.min_.Y, 0), Point3LL(triangle_aabb.max_.X, triangle_aabb.max_.Y, 1)); double density = density_provider_(triangle_aabb3d); // The density of the square around the triangle is a rough estimate of the density of the triangle. triangle.requested_length_ = density * triangle.area_ / INT2MM(line_width_); } @@ -705,7 +705,7 @@ Polygon SierpinskiFill::generateCross() const for (SierpinskiTriangle* max_level_it : sequence_) { SierpinskiTriangle& triangle = *max_level_it; - Point edge_middle = triangle.a_ + triangle.b_ + triangle.straight_corner_; + Point2LL edge_middle = triangle.a_ + triangle.b_ + triangle.straight_corner_; switch (triangle.dir_) { case SierpinskiTriangle::SierpinskiDirection::AB_TO_BC: @@ -732,7 +732,7 @@ Polygon SierpinskiFill::generateCross(coord_t z, coord_t min_dist_to_side, coord { Polygon ret; - std::function get_edge_crossing_location = [z, min_dist_to_side](const coord_t period, const Edge e) + std::function get_edge_crossing_location = [z, min_dist_to_side](const coord_t period, const Edge e) { coord_t from_l = z % (period * 2); if (from_l > period) @@ -779,13 +779,13 @@ Polygon SierpinskiFill::generateCross(coord_t z, coord_t min_dist_to_side, coord Polygon pocketed; pocketed.reserve(ret.size() * 3 / 2); - Point p0 = ret.back(); + Point2LL p0 = ret.back(); for (size_t poly_idx = 0; poly_idx < ret.size(); poly_idx++) { - Point p1 = ret[poly_idx]; - Point p2 = ret[(poly_idx + 1) % ret.size()]; - Point v0 = p0 - p1; - Point v1 = p2 - p1; + Point2LL p1 = ret[poly_idx]; + Point2LL p2 = ret[(poly_idx + 1) % ret.size()]; + Point2LL v0 = p0 - p1; + Point2LL v1 = p2 - p1; coord_t prod = std::abs(dot(v0, v1)); bool is_straight_corner = prod < sqrt(vSize(v0) * vSize(v1)) * min_dist_to_side; // allow for rounding errors of up to min_dist_to_side diff --git a/src/infill/SierpinskiFillProvider.cpp b/src/infill/SierpinskiFillProvider.cpp index 17b27068bf..0123c42b04 100644 --- a/src/infill/SierpinskiFillProvider.cpp +++ b/src/infill/SierpinskiFillProvider.cpp @@ -65,9 +65,9 @@ SierpinskiFillProvider::~SierpinskiFillProvider() SierpinskiFillProvider::FractalConfig SierpinskiFillProvider::getFractalConfig(const AABB3D aabb_3d, coord_t min_line_distance) { AABB model_aabb = aabb_3d.flatten(); - Point model_aabb_size = model_aabb.max_ - model_aabb.min_; + Point2LL model_aabb_size = model_aabb.max_ - model_aabb.min_; coord_t max_side_length = std::max(model_aabb_size.X, model_aabb_size.Y); - Point model_middle = model_aabb.getMiddle(); + Point2LL model_middle = model_aabb.getMiddle(); int depth = 0; coord_t aabb_size = min_line_distance; @@ -83,7 +83,7 @@ SierpinskiFillProvider::FractalConfig SierpinskiFillProvider::getFractalConfig(c depth--; } - Point radius(aabb_size / 2, aabb_size / 2); + Point2LL radius(aabb_size / 2, aabb_size / 2); AABB aabb(model_middle - radius, model_middle + radius); return FractalConfig{ depth, aabb }; diff --git a/src/infill/SubDivCube.cpp b/src/infill/SubDivCube.cpp index 6f3a3873fb..f30affc602 100644 --- a/src/infill/SubDivCube.cpp +++ b/src/infill/SubDivCube.cpp @@ -23,7 +23,7 @@ coord_t SubDivCube::radius_addition_ = 0; Point3Matrix SubDivCube::rotation_matrix_; PointMatrix SubDivCube::infill_rotation_matrix_; -void SubDivCube::precomputeOctree(SliceMeshStorage& mesh, const Point& infill_origin) +void SubDivCube::precomputeOctree(SliceMeshStorage& mesh, const Point2LL& infill_origin) { radius_addition_ = mesh.settings.get("sub_div_rad_add"); @@ -51,7 +51,7 @@ void SubDivCube::precomputeOctree(SliceMeshStorage& mesh, const Point& infill_or curr_recursion_depth++; } } - Point3 center(infill_origin.X, infill_origin.Y, 0); + Point3LL center(infill_origin.X, infill_origin.Y, 0); Point3Matrix tilt; // rotation matrix to get from axis aligned cubes to cubes standing on their tip // The Z axis is transformed to go in positive Y direction @@ -114,8 +114,8 @@ void SubDivCube::generateSubdivisionLines(const coord_t z, Polygons (&directiona } if (z_diff < cube_properties.max_draw_z_diff) //!< this cube has lines that need to be drawn. { - Point relative_a, relative_b; //!< relative coordinates of line endpoints around cube center - Point a, b; //!< absolute coordinates of line endpoints + Point2LL relative_a, relative_b; //!< relative coordinates of line endpoints around cube center + Point2LL a, b; //!< absolute coordinates of line endpoints relative_a.X = (cube_properties.square_height / 2) * (cube_properties.max_draw_z_diff - z_diff) / cube_properties.max_draw_z_diff; relative_b.X = -relative_a.X; relative_a.Y = cube_properties.max_line_offset - ((z - (center_.z_ - cube_properties.max_draw_z_diff)) * ONE_OVER_SQRT_2); @@ -145,7 +145,7 @@ void SubDivCube::generateSubdivisionLines(const coord_t z, Polygons (&directiona } } -SubDivCube::SubDivCube(SliceMeshStorage& mesh, Point3& center, size_t depth) +SubDivCube::SubDivCube(SliceMeshStorage& mesh, Point3LL& center, size_t depth) : depth_(depth) , center_(center) { @@ -159,11 +159,11 @@ SubDivCube::SubDivCube(SliceMeshStorage& mesh, Point3& center, size_t depth) } CubeProperties cube_properties = cube_properties_per_recursion_step_[depth]; - Point3 child_center; + Point3LL child_center; coord_t radius = double(cube_properties.height) / 4.0 + radius_addition_; int child_nr = 0; - std::vector rel_child_centers; + std::vector rel_child_centers; rel_child_centers.emplace_back(1, 1, 1); // top rel_child_centers.emplace_back(-1, 1, 1); // top three rel_child_centers.emplace_back(1, -1, 1); @@ -172,7 +172,7 @@ SubDivCube::SubDivCube(SliceMeshStorage& mesh, Point3& center, size_t depth) rel_child_centers.emplace_back(1, -1, -1); // bottom three rel_child_centers.emplace_back(-1, 1, -1); rel_child_centers.emplace_back(-1, -1, 1); - for (Point3 rel_child_center : rel_child_centers) + for (Point3LL rel_child_center : rel_child_centers) { child_center = center + rotation_matrix_.apply(rel_child_center * int32_t(cube_properties.side_length / 4)); if (isValidSubdivision(mesh, child_center, radius)) @@ -183,7 +183,7 @@ SubDivCube::SubDivCube(SliceMeshStorage& mesh, Point3& center, size_t depth) } } -bool SubDivCube::isValidSubdivision(SliceMeshStorage& mesh, Point3& center, coord_t radius) +bool SubDivCube::isValidSubdivision(SliceMeshStorage& mesh, Point3LL& center, coord_t radius) { coord_t distance2 = 0; coord_t sphere_slice_radius2; //!< squared radius of bounding sphere slice on target layer @@ -198,7 +198,7 @@ bool SubDivCube::isValidSubdivision(SliceMeshStorage& mesh, Point3& center, coor { part_dist = Ratio{ static_cast(test_layer * layer_height - center.z_) } / radius; sphere_slice_radius2 = radius * radius * (1.0 - (part_dist * part_dist)); - Point loc(center.x_, center.y_); + Point2LL loc(center.x_, center.y_); inside = distanceFromPointToMesh(mesh, test_layer, loc, &distance2); if (inside == 1) @@ -221,7 +221,7 @@ bool SubDivCube::isValidSubdivision(SliceMeshStorage& mesh, Point3& center, coor return false; } -coord_t SubDivCube::distanceFromPointToMesh(SliceMeshStorage& mesh, const LayerIndex layer_nr, Point& location, coord_t* distance2) +coord_t SubDivCube::distanceFromPointToMesh(SliceMeshStorage& mesh, const LayerIndex layer_nr, Point2LL& location, coord_t* distance2) { if (layer_nr < 0 || (unsigned int)layer_nr >= mesh.layers.size()) //!< this layer is outside of valid range { @@ -234,10 +234,10 @@ coord_t SubDivCube::distanceFromPointToMesh(SliceMeshStorage& mesh, const LayerI collide.add(part.infill_area); } - Point centerpoint = location; + Point2LL centerpoint = location; bool inside = collide.inside(centerpoint); ClosestPolygonPoint border_point = PolygonUtils::moveInside2(collide, centerpoint); - Point diff = border_point.location_ - location; + Point2LL diff = border_point.location_ - location; *distance2 = vSize2(diff); if (inside) { @@ -247,12 +247,12 @@ coord_t SubDivCube::distanceFromPointToMesh(SliceMeshStorage& mesh, const LayerI } -void SubDivCube::rotatePointInitial(Point& target) +void SubDivCube::rotatePointInitial(Point2LL& target) { target = infill_rotation_matrix_.apply(target); } -void SubDivCube::rotatePoint120(Point& target) +void SubDivCube::rotatePoint120(Point2LL& target) { // constexpr double sqrt_three_fourths = sqrt(3.0 / 4.0); //TODO: Reactivate once MacOS is upgraded to a more modern compiler. #define sqrt_three_fourths 0.86602540378443864676372317 @@ -261,7 +261,7 @@ void SubDivCube::rotatePoint120(Point& target) target.X = x; } -void SubDivCube::addLineAndCombine(Polygons& group, Point from, Point to) +void SubDivCube::addLineAndCombine(Polygons& group, Point2LL from, Point2LL to) { int epsilon = 10; // the smallest distance of two points which are viewed as coincident (dist > 0 due to rounding errors) for (unsigned int idx = 0; idx < group.size(); idx++) diff --git a/src/infill/ZigzagConnectorProcessor.cpp b/src/infill/ZigzagConnectorProcessor.cpp index 5c579841a8..7f75b608ff 100644 --- a/src/infill/ZigzagConnectorProcessor.cpp +++ b/src/infill/ZigzagConnectorProcessor.cpp @@ -8,7 +8,7 @@ using namespace cura; -void ZigzagConnectorProcessor::registerVertex(const Point& vertex) +void ZigzagConnectorProcessor::registerVertex(const Point2LL& vertex) { if (is_first_connector_) { @@ -84,7 +84,7 @@ bool ZigzagConnectorProcessor::shouldAddCurrentConnector(int start_scanline_idx, } -void ZigzagConnectorProcessor::registerScanlineSegmentIntersection(const Point& intersection, int scanline_index) +void ZigzagConnectorProcessor::registerScanlineSegmentIntersection(const Point2LL& intersection, int scanline_index) { if (is_first_connector_) { @@ -122,7 +122,7 @@ void ZigzagConnectorProcessor::registerPolyFinished() if ((is_endpiece && use_endpieces_) || (! is_endpiece && shouldAddCurrentConnector(scanline_start_index, scanline_end_index))) { // for convenience, put every point in one vector - for (const Point& point : first_connector_) + for (const Point2LL& point : first_connector_) { current_connector_.push_back(point); } @@ -136,7 +136,7 @@ void ZigzagConnectorProcessor::registerPolyFinished() } -void ZigzagConnectorProcessor::addZagConnector(std::vector& points, bool is_endpiece) +void ZigzagConnectorProcessor::addZagConnector(std::vector& points, bool is_endpiece) { // don't include the last line yet if (points.size() < 2) diff --git a/src/layerPart.cpp b/src/layerPart.cpp index ba9507725a..2a47dd8563 100644 --- a/src/layerPart.cpp +++ b/src/layerPart.cpp @@ -28,7 +28,7 @@ namespace cura { void createLayerWithParts(const Settings& settings, SliceLayer& storageLayer, SlicerLayer* layer) { - PolylineStitcher::stitch(layer->openPolylines, storageLayer.openPolyLines, layer->polygons, settings.get("wall_line_width_0")); + PolylineStitcher::stitch(layer->openPolylines, storageLayer.openPolyLines, layer->polygons, settings.get("wall_line_width_0")); storageLayer.openPolyLines = Simplify(settings).polyline(storageLayer.openPolyLines); diff --git a/src/mesh.cpp b/src/mesh.cpp index 8224fbfc2f..740dc442c8 100644 --- a/src/mesh.cpp +++ b/src/mesh.cpp @@ -15,7 +15,7 @@ const int vertex_meld_distance = MM2INT(0.03); * returns a hash for the location, but first divides by the vertex_meld_distance, * so that any point within a box of vertex_meld_distance by vertex_meld_distance would get mapped to the same hash. */ -static inline uint32_t pointHash(const Point3& p) +static inline uint32_t pointHash(const Point3LL& p) { return ((p.x_ + vertex_meld_distance / 2) / vertex_meld_distance) ^ (((p.y_ + vertex_meld_distance / 2) / vertex_meld_distance) << 10) ^ (((p.z_ + vertex_meld_distance / 2) / vertex_meld_distance) << 20); @@ -35,7 +35,7 @@ Mesh::Mesh() { } -void Mesh::addFace(Point3& v0, Point3& v1, Point3& v2) +void Mesh::addFace(Point3LL& v0, Point3LL& v1, Point3LL& v2) { int vi0 = findIndexOfVertex(v0); int vi1 = findIndexOfVertex(v1); @@ -77,11 +77,11 @@ void Mesh::finish() } } -Point3 Mesh::min() const +Point3LL Mesh::min() const { return aabb_.min_; } -Point3 Mesh::max() const +Point3LL Mesh::max() const { return aabb_.max_; } @@ -118,7 +118,7 @@ bool Mesh::canInterlock() const return ! settings_.get("infill_mesh") && ! settings_.get("anti_overhang_mesh"); } -int Mesh::findIndexOfVertex(const Point3& v) +int Mesh::findIndexOfVertex(const Point3LL& v) { uint32_t hash = pointHash(v); diff --git a/src/multiVolumes.cpp b/src/multiVolumes.cpp index 220523c723..6852469919 100644 --- a/src/multiVolumes.cpp +++ b/src/multiVolumes.cpp @@ -174,7 +174,7 @@ void MultiVolumes::carveCuttingMeshes(std::vector& volumes, const std:: if (cutting_mesh.settings_.get("magic_mesh_surface_mode") != ESurfaceMode::NORMAL) { cutting_mesh_polylines.clear(); - PolylineStitcher::stitch(new_polylines, cutting_mesh_polylines, cutting_mesh_polygons, surface_line_width); + PolylineStitcher::stitch(new_polylines, cutting_mesh_polylines, cutting_mesh_polygons, surface_line_width); } } } diff --git a/src/pathPlanning/Comb.cpp b/src/pathPlanning/Comb.cpp index e3243a344b..be204cb197 100644 --- a/src/pathPlanning/Comb.cpp +++ b/src/pathPlanning/Comb.cpp @@ -89,8 +89,8 @@ bool Comb::calc( bool perform_z_hops, bool perform_z_hops_only_when_collides, const ExtruderTrain& train, // NOTE: USe for travel settings and 'extruder-nr' only, don't use for z-hop/retraction/wipe settings, as that should also be settable per mesh! - Point start_point, - Point end_point, + Point2LL start_point, + Point2LL end_point, CombPaths& comb_paths, bool _start_inside, bool _end_inside, @@ -101,7 +101,7 @@ bool Comb::calc( { return true; } - const Point travel_end_point_before_combing = end_point; + const Point2LL travel_end_point_before_combing = end_point; // Move start and end point inside the optimal comb boundary unsigned int start_inside_poly = NO_INDEX; const bool start_inside = moveInside(boundary_inside_optimal_, _start_inside, inside_loc_to_line_optimal_.get(), start_point, start_inside_poly); @@ -387,7 +387,7 @@ void Comb::moveCombPathInside(Polygons& boundary_inside, Polygons& boundary_insi comb_path_output.push_back(comb_path_input[0]); for (unsigned int point_idx = 1; point_idx < comb_path_input.size() - 1; point_idx++) { - Point new_point = Point(comb_path_input[point_idx]); + Point2LL new_point = Point2LL(comb_path_input[point_idx]); PolygonUtils::moveInside(boundary_inside, new_point, dist, dist2); if (boundary_inside_optimal.inside(new_point)) @@ -406,7 +406,7 @@ void Comb::moveCombPathInside(Polygons& boundary_inside, Polygons& boundary_insi } Comb::Crossing::Crossing( - const Point& dest_point, + const Point2LL& dest_point, const bool dest_is_inside, const unsigned int dest_part_idx, const unsigned int dest_part_boundary_crossing_poly_idx, @@ -425,7 +425,7 @@ Comb::Crossing::Crossing( } } -bool Comb::moveInside(Polygons& boundary_inside, bool is_inside, LocToLineGrid* inside_loc_to_line, Point& dest_point, unsigned int& inside_poly) +bool Comb::moveInside(Polygons& boundary_inside, bool is_inside, LocToLineGrid* inside_loc_to_line, Point2LL& dest_point, unsigned int& inside_poly) { if (is_inside) { @@ -444,14 +444,14 @@ bool Comb::moveInside(Polygons& boundary_inside, bool is_inside, LocToLineGrid* return false; } -void Comb::Crossing::findCrossingInOrMid(const PartsView& partsView_inside, const Point close_to) +void Comb::Crossing::findCrossingInOrMid(const PartsView& partsView_inside, const Point2LL close_to) { if (dest_is_inside_) { // in-case // find the point on the start inside-polygon closest to the endpoint, but also kind of close to the start point - Point _dest_point(dest_point_); // copy to local variable for lambda capture - std::function close_towards_start_penalty_function( - [_dest_point](Point candidate) + Point2LL _dest_point(dest_point_); // copy to local variable for lambda capture + std::function close_towards_start_penalty_function( + [_dest_point](Point2LL candidate) { return vSize2((candidate - _dest_point) / 10); }); @@ -472,7 +472,7 @@ void Comb::Crossing::findCrossingInOrMid(const PartsView& partsView_inside, cons { // we're not looking at a polygon from the dest_part return true; // a.k.a. continue; } - Point closest_here = LinearAlg2D::getClosestOnLineSegment(close_to, boundary_segment.p(), boundary_segment.next().p()); + Point2LL closest_here = LinearAlg2D::getClosestOnLineSegment(close_to, boundary_segment.p(), boundary_segment.next().p()); coord_t dist2_score_here = vSize2(close_to - closest_here) + vSize2(_dest_point - closest_here) / 10; if (dist2_score_here < dist2_score) { @@ -484,7 +484,7 @@ void Comb::Crossing::findCrossingInOrMid(const PartsView& partsView_inside, cons inside_loc_to_line_.processLine(std::make_pair(dest_point_, close_to), line_processor); } - Point result(boundary_crossing_point.p()); // the inside point of the crossing + Point2LL result(boundary_crossing_point.p()); // the inside point of the crossing if (! boundary_crossing_point.isValid()) { // no point has been found in the sparse grid result = dest_point_; @@ -514,14 +514,14 @@ void Comb::Crossing::findCrossingInOrMid(const PartsView& partsView_inside, cons } } -bool Comb::Crossing::findOutside(const ExtruderTrain& train, const Polygons& outside, const Point close_to, const bool fail_on_unavoidable_obstacles, Comb& comber) +bool Comb::Crossing::findOutside(const ExtruderTrain& train, const Polygons& outside, const Point2LL close_to, const bool fail_on_unavoidable_obstacles, Comb& comber) { out_ = in_or_mid_; if (dest_is_inside_ || outside.inside(in_or_mid_, true)) // start in_between { // move outside - Point preferred_crossing_1_out = in_or_mid_ + normal(close_to - in_or_mid_, comber.offset_from_inside_to_outside_); - std::function close_to_penalty_function( - [preferred_crossing_1_out](Point candidate) + Point2LL preferred_crossing_1_out = in_or_mid_ + normal(close_to - in_or_mid_, comber.offset_from_inside_to_outside_); + std::function close_to_penalty_function( + [preferred_crossing_1_out](Point2LL candidate) { return vSize2((candidate - preferred_crossing_1_out) / 2); }); @@ -559,8 +559,8 @@ std::shared_ptr> Comb::Cross const ExtruderTrain& train, const Polygons& outside, ConstPolygonRef from, - const Point estimated_start, - const Point estimated_end, + const Point2LL estimated_start, + const Point2LL estimated_end, Comb& comber) { ClosestPolygonPoint* best_in = nullptr; diff --git a/src/pathPlanning/LinePolygonsCrossings.cpp b/src/pathPlanning/LinePolygonsCrossings.cpp index 611aaffe4c..1391dffb7a 100644 --- a/src/pathPlanning/LinePolygonsCrossings.cpp +++ b/src/pathPlanning/LinePolygonsCrossings.cpp @@ -23,10 +23,10 @@ bool LinePolygonsCrossings::calcScanlineCrossings(bool fail_on_unavoidable_obsta for (unsigned int poly_idx = 0; poly_idx < boundary_.size(); poly_idx++) { ConstPolygonRef poly = boundary_[poly_idx]; - Point p0 = transformation_matrix_.apply(poly[poly.size() - 1]); + Point2LL p0 = transformation_matrix_.apply(poly[poly.size() - 1]); for (unsigned int point_idx = 0; point_idx < poly.size(); point_idx++) { - Point p1 = transformation_matrix_.apply(poly[point_idx]); + Point2LL p1 = transformation_matrix_.apply(poly[point_idx]); if ((p0.Y >= transformed_start_point_.Y && p1.Y <= transformed_start_point_.Y) || (p1.Y >= transformed_start_point_.Y && p0.Y <= transformed_start_point_.Y)) { // if line segment crosses the line through the transformed start and end point (aka scanline) if (p1.Y == p0.Y) // Line segment is parallel with the scanline. That means that both endpoints lie on the scanline, so they will have intersected with the adjacent @@ -68,7 +68,7 @@ bool LinePolygonsCrossings::calcScanlineCrossings(bool fail_on_unavoidable_obsta bool LinePolygonsCrossings::lineSegmentCollidesWithBoundary() { - Point diff = end_point_ - start_point_; + Point2LL diff = end_point_ - start_point_; transformation_matrix_ = PointMatrix(diff); transformed_start_point_ = transformation_matrix_.apply(start_point_); @@ -76,10 +76,10 @@ bool LinePolygonsCrossings::lineSegmentCollidesWithBoundary() for (ConstPolygonRef poly : boundary_) { - Point p0 = transformation_matrix_.apply(poly.back()); - for (Point p1_ : poly) + Point2LL p0 = transformation_matrix_.apply(poly.back()); + for (Point2LL p1_ : poly) { - Point p1 = transformation_matrix_.apply(p1_); + Point2LL p1 = transformation_matrix_.apply(p1_); // when the boundary just touches the line don't disambiguate between the boundary moving on to actually cross the line // and the boundary bouncing back, resulting in not a real collision - to keep the algorithm simple. // @@ -153,21 +153,21 @@ void LinePolygonsCrossings::generateBasicCombingPath(const Crossing& min, const // minimise the path length by measuring the length of both paths around the polygon so we can determine the shorter path ConstPolygonRef poly = boundary_[min.poly_idx_]; - combPath.push_back(transformation_matrix_.unapply(Point(min.x_ - std::abs(dist_to_move_boundary_point_outside_), transformed_start_point_.Y))); + combPath.push_back(transformation_matrix_.unapply(Point2LL(min.x_ - std::abs(dist_to_move_boundary_point_outside_), transformed_start_point_.Y))); // follow the path in the same direction as the winding order of the boundary polygon - std::vector fwd_points; - Point prev = combPath.back(); + std::vector fwd_points; + Point2LL prev = combPath.back(); coord_t fwd_len = 0; for (unsigned int point_idx = min.point_idx_; point_idx != max.point_idx_; point_idx = (point_idx < poly.size() - 1) ? (point_idx + 1) : (0)) { - const Point p = PolygonUtils::getBoundaryPointWithOffset(poly, point_idx, dist_to_move_boundary_point_outside_); + const Point2LL p = PolygonUtils::getBoundaryPointWithOffset(poly, point_idx, dist_to_move_boundary_point_outside_); fwd_points.push_back(p); fwd_len += vSize(p - prev); prev = p; } - const Point last = transformation_matrix_.unapply(Point(max.x_ + std::abs(dist_to_move_boundary_point_outside_), transformed_start_point_.Y)); + const Point2LL last = transformation_matrix_.unapply(Point2LL(max.x_ + std::abs(dist_to_move_boundary_point_outside_), transformed_start_point_.Y)); if (fwd_points.size() > 0) { @@ -175,14 +175,14 @@ void LinePolygonsCrossings::generateBasicCombingPath(const Crossing& min, const } // follow the path in the opposite direction of the winding order of the boundary polygon - std::vector rev_points; + std::vector rev_points; prev = combPath.back(); coord_t rev_len = 0; unsigned int min_idx = (min.point_idx_ == 0) ? poly.size() - 1 : min.point_idx_ - 1; unsigned int max_idx = (max.point_idx_ == 0) ? poly.size() - 1 : max.point_idx_ - 1; for (unsigned int point_idx = min_idx; point_idx != max_idx; point_idx = (point_idx > 0) ? (point_idx - 1) : (poly.size() - 1)) { - const Point p = PolygonUtils::getBoundaryPointWithOffset(poly, point_idx, dist_to_move_boundary_point_outside_); + const Point2LL p = PolygonUtils::getBoundaryPointWithOffset(poly, point_idx, dist_to_move_boundary_point_outside_); rev_points.push_back(p); rev_len += vSize(p - prev); prev = p; @@ -215,7 +215,7 @@ bool LinePolygonsCrossings::optimizePath(CombPath& comb_path, CombPath& optimize { continue; } - Point& current_point = optimized_comb_path.back(); + Point2LL& current_point = optimized_comb_path.back(); if (PolygonUtils::polygonCollidesWithLineSegment(current_point, comb_path[point_idx], loc_to_line_grid_)) { if (PolygonUtils::polygonCollidesWithLineSegment(current_point, comb_path[point_idx - 1], loc_to_line_grid_)) @@ -255,7 +255,7 @@ bool LinePolygonsCrossings::optimizePath(CombPath& comb_path, CombPath& optimize // 2----3 ... 2----3 ... // - Point p = optimized_comb_path.back(); + Point2LL p = optimized_comb_path.back(); for (double frac : { 0.9, 0.9, 0.7, 0.5 }) { // slide p towards the second point in the comb path @@ -307,7 +307,7 @@ bool LinePolygonsCrossings::optimizePath(CombPath& comb_path, CombPath& optimize for (double frac : { 0.9, 0.9, 0.7, 0.5 }) { // make a new point between the penultimate corner and the corner before that - Point p = optimized_comb_path[n - 2] + (optimized_comb_path[n - 1] - optimized_comb_path[n - 2]) * frac; + Point2LL p = optimized_comb_path[n - 2] + (optimized_comb_path[n - 1] - optimized_comb_path[n - 2]) * frac; if (! PolygonUtils::polygonCollidesWithLineSegment(p, comb_path.back(), loc_to_line_grid_)) { // using the new corner doesn't cause a conflict diff --git a/src/plugins/converters.cpp b/src/plugins/converters.cpp index 72a8166de7..c637f44c45 100644 --- a/src/plugins/converters.cpp +++ b/src/plugins/converters.cpp @@ -133,7 +133,7 @@ simplify_response::native_value_type Polygon o{}; for (const auto& point : paths.outline().path()) { - o.add(Point{ point.x(), point.y() }); + o.add(Point2LL{ point.x(), point.y() }); } poly.add(o); @@ -142,7 +142,7 @@ simplify_response::native_value_type Polygon h{}; for (const auto& point : hole.path()) { - h.add(Point{ point.x(), point.y() }); + h.add(Point2LL{ point.x(), point.y() }); } poly.add(h); } @@ -234,7 +234,7 @@ infill_generate_response::native_value_type infill_generate_response::operator() Polygon outline{}; for (auto& path_msg : polygon_msg.outline().path()) { - outline.add(Point{ path_msg.x(), path_msg.y() }); + outline.add(Point2LL{ path_msg.x(), path_msg.y() }); } polygon.add(outline); @@ -244,7 +244,7 @@ infill_generate_response::native_value_type infill_generate_response::operator() Polygon hole{}; for (auto& path_msg : hole_msg.path()) { - hole.add(Point{ path_msg.x(), path_msg.y() }); + hole.add(Point2LL{ path_msg.x(), path_msg.y() }); } polygon.add(hole); } @@ -257,7 +257,7 @@ infill_generate_response::native_value_type infill_generate_response::operator() Polygon poly_line; for (auto& p : polygon.path()) { - poly_line.emplace_back(Point{ p.x(), p.y() }); + poly_line.emplace_back(Point2LL{ p.x(), p.y() }); } result_lines.emplace_back(poly_line); } @@ -469,7 +469,7 @@ gcode_paths_modify_response::native_value_type | ranges::views::transform( [](const auto& point_msg) { - return Point{ point_msg.x(), point_msg.y() }; + return Point2LL{ point_msg.x(), point_msg.y() }; }) | ranges::to_vector; diff --git a/src/settings/ZSeamConfig.cpp b/src/settings/ZSeamConfig.cpp index ea91b0f516..2d6b9a1a05 100644 --- a/src/settings/ZSeamConfig.cpp +++ b/src/settings/ZSeamConfig.cpp @@ -6,7 +6,7 @@ namespace cura { -ZSeamConfig::ZSeamConfig(const EZSeamType type, const Point pos, const EZSeamCornerPrefType corner_pref, const coord_t simplify_curvature) +ZSeamConfig::ZSeamConfig(const EZSeamType type, const Point2LL pos, const EZSeamCornerPrefType corner_pref, const coord_t simplify_curvature) : type_(type) , pos_(pos) , corner_pref_(corner_pref) diff --git a/src/sliceDataStorage.cpp b/src/sliceDataStorage.cpp index f0e0c79a26..a60631d70b 100644 --- a/src/sliceDataStorage.cpp +++ b/src/sliceDataStorage.cpp @@ -231,13 +231,13 @@ bool SliceMeshStorage::isPrinted() const return ! settings.get("infill_mesh") && ! settings.get("cutting_mesh") && ! settings.get("anti_overhang_mesh"); } -Point SliceMeshStorage::getZSeamHint() const +Point2LL SliceMeshStorage::getZSeamHint() const { - Point pos(settings.get("z_seam_x"), settings.get("z_seam_y")); + Point2LL pos(settings.get("z_seam_x"), settings.get("z_seam_y")); if (settings.get("z_seam_relative")) { - Point3 middle = bounding_box.getMiddle(); - pos += Point(middle.x_, middle.y_); + Point3LL middle = bounding_box.getMiddle(); + pos += Point2LL(middle.x_, middle.y_); } return pos; } @@ -255,8 +255,8 @@ SliceDataStorage::SliceDataStorage() , max_print_height_second_to_last_extruder(-1) { const Settings& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; - Point3 machine_max(mesh_group_settings.get("machine_width"), mesh_group_settings.get("machine_depth"), mesh_group_settings.get("machine_height")); - Point3 machine_min(0, 0, 0); + Point3LL machine_max(mesh_group_settings.get("machine_width"), mesh_group_settings.get("machine_depth"), mesh_group_settings.get("machine_height")); + Point3LL machine_min(0, 0, 0); if (mesh_group_settings.get("machine_center_is_zero")) { machine_max /= 2; @@ -567,9 +567,9 @@ Polygons SliceDataStorage::getMachineBorder(int checking_extruder_nr) const { for (PolygonRef poly : disallowed_areas) { - for (Point& p : poly) + for (Point2LL& p : poly) { - p = Point(machine_size.max_.x_ / 2 + p.X, machine_size.max_.y_ / 2 - p.Y); + p = Point2LL(machine_size.max_.x_ / 2 + p.X, machine_size.max_.y_ / 2 - p.Y); } } } @@ -588,12 +588,12 @@ Polygons SliceDataStorage::getMachineBorder(int checking_extruder_nr) const { continue; } - Point prime_pos(extruder_settings.get("extruder_prime_pos_x"), extruder_settings.get("extruder_prime_pos_y")); - if (prime_pos == Point(0, 0)) + Point2LL prime_pos(extruder_settings.get("extruder_prime_pos_x"), extruder_settings.get("extruder_prime_pos_y")); + if (prime_pos == Point2LL(0, 0)) { continue; // Ignore extruder prime position if it is not set. } - Point translation(extruder_settings.get("machine_nozzle_offset_x"), extruder_settings.get("machine_nozzle_offset_y")); + Point2LL translation(extruder_settings.get("machine_nozzle_offset_x"), extruder_settings.get("machine_nozzle_offset_y")); prime_pos -= translation; Polygons prime_polygons; prime_polygons.emplace_back(PolygonUtils::makeCircle(prime_pos, prime_clearance, std::numbers::pi / 32)); @@ -609,7 +609,7 @@ Polygons SliceDataStorage::getMachineBorder(int checking_extruder_nr) const continue; } Settings& extruder_settings = Application::getInstance().current_slice_->scene.extruders[extruder_nr].settings_; - Point translation(extruder_settings.get("machine_nozzle_offset_x"), extruder_settings.get("machine_nozzle_offset_y")); + Point2LL translation(extruder_settings.get("machine_nozzle_offset_x"), extruder_settings.get("machine_nozzle_offset_y")); Polygons extruder_border = disallowed_areas; extruder_border.translate(translation); if (first) @@ -634,7 +634,7 @@ Polygons SliceDataStorage::getMachineBorder(int checking_extruder_nr) const continue; } Settings& extruder_settings = Application::getInstance().current_slice_->scene.extruders[extruder_nr].settings_; - Point translation(extruder_settings.get("machine_nozzle_offset_x"), extruder_settings.get("machine_nozzle_offset_y")); + Point2LL translation(extruder_settings.get("machine_nozzle_offset_x"), extruder_settings.get("machine_nozzle_offset_y")); for (size_t other_extruder_nr = 0; other_extruder_nr < extruder_is_used.size(); other_extruder_nr++) { // NOTE: the other extruder doesn't have to be used. Since the global border is the union of all extruders borders also unused extruders must be taken into account. @@ -643,7 +643,7 @@ Polygons SliceDataStorage::getMachineBorder(int checking_extruder_nr) const continue; } Settings& other_extruder_settings = Application::getInstance().current_slice_->scene.extruders[other_extruder_nr].settings_; - Point other_translation(other_extruder_settings.get("machine_nozzle_offset_x"), other_extruder_settings.get("machine_nozzle_offset_y")); + Point2LL other_translation(other_extruder_settings.get("machine_nozzle_offset_x"), other_extruder_settings.get("machine_nozzle_offset_y")); Polygons translated_border = border; translated_border.translate(translation - other_translation); border_all_extruders = border_all_extruders.intersection(translated_border); diff --git a/src/slicer.cpp b/src/slicer.cpp index ee971db3b5..22040b1480 100644 --- a/src/slicer.cpp +++ b/src/slicer.cpp @@ -71,8 +71,8 @@ int SlicerLayer::tryFaceNextSegmentIdx(const SlicerSegment& segment, const int f if (it != it_end) { const int segment_idx = (*it).second; - Point p1 = segments[segment_idx].start; - Point diff = segment.end - p1; + Point2LL p1 = segments[segment_idx].start; + Point2LL diff = segment.end - p1; if (shorterThen(diff, largest_neglected_gap_first_phase)) { if (segment_idx == static_cast(start_segment_idx)) @@ -201,12 +201,12 @@ std::priority_queue SlicerLayer::findPossibleStitch unsigned int polyline_idx; // Depending on the SparsePointGridInclusive, either the start point or the // end point of the polyline - Point polyline_term_pt; + Point2LL polyline_term_pt; }; struct StitchGridValLocator { - Point operator()(const StitchGridVal& val) const + Point2LL operator()(const StitchGridVal& val) const { return val.polyline_term_pt; } @@ -267,7 +267,7 @@ std::priority_queue SlicerLayer::findPossibleStitch nearby_ends = grid_ends.getNearby(polyline_1[0], max_dist); for (const auto& nearby_end : nearby_ends) { - Point diff = nearby_end.polyline_term_pt - polyline_1[0]; + Point2LL diff = nearby_end.polyline_term_pt - polyline_1[0]; int64_t dist2 = vSize2(diff); if (dist2 < max_dist2) { @@ -293,7 +293,7 @@ std::priority_queue SlicerLayer::findPossibleStitch continue; } - Point diff = nearby_end.polyline_term_pt - polyline_1.back(); + Point2LL diff = nearby_end.polyline_term_pt - polyline_1.back(); int64_t dist2 = vSize2(diff); if (dist2 < max_dist2) { @@ -317,7 +317,7 @@ std::priority_queue SlicerLayer::findPossibleStitch continue; } - Point diff = nearby_start.polyline_term_pt - polyline_1[0]; + Point2LL diff = nearby_start.polyline_term_pt - polyline_1[0]; int64_t dist2 = vSize2(diff); if (dist2 < max_dist2) { @@ -403,7 +403,7 @@ void SlicerLayer::joinPolylines(PolygonRef& polyline_0, PolygonRef& polyline_1, else { // append polyline_1 onto polyline_0 - for (Point& p : polyline_1) + for (Point2LL& p : polyline_1) polyline_0.add(p); } polyline_1.clear(); @@ -641,7 +641,7 @@ void SlicerLayer::stitch_extensive(Polygons& open_polylines) } } -std::optional SlicerLayer::findPolygonGapCloser(Point ip0, Point ip1) +std::optional SlicerLayer::findPolygonGapCloser(Point2LL ip0, Point2LL ip1) { std::optional c1 = findPolygonPointClosestTo(ip0); std::optional c2 = findPolygonPointClosestTo(ip1); @@ -664,11 +664,11 @@ std::optional SlicerLayer::findPolygonGapCloser(Point ip0, Poin else { // Find out if we have should go from A to B or the other way around. - Point p0 = polygons[ret.polygonIdx][ret.pointIdxA]; + Point2LL p0 = polygons[ret.polygonIdx][ret.pointIdxA]; int64_t lenA = vSize(p0 - ip0); for (unsigned int i = ret.pointIdxA; i != ret.pointIdxB; i = (i + 1) % polygons[ret.polygonIdx].size()) { - Point p1 = polygons[ret.polygonIdx][i]; + Point2LL p1 = polygons[ret.polygonIdx][i]; lenA += vSize(p0 - p1); p0 = p1; } @@ -678,7 +678,7 @@ std::optional SlicerLayer::findPolygonGapCloser(Point ip0, Poin int64_t lenB = vSize(p0 - ip1); for (unsigned int i = ret.pointIdxB; i != ret.pointIdxA; i = (i + 1) % polygons[ret.polygonIdx].size()) { - Point p1 = polygons[ret.polygonIdx][i]; + Point2LL p1 = polygons[ret.polygonIdx][i]; lenB += vSize(p0 - p1); p0 = p1; } @@ -698,24 +698,24 @@ std::optional SlicerLayer::findPolygonGapCloser(Point ip0, Poin return ret; } -std::optional SlicerLayer::findPolygonPointClosestTo(Point input) +std::optional SlicerLayer::findPolygonPointClosestTo(Point2LL input) { for (size_t n = 0; n < polygons.size(); n++) { - Point p0 = polygons[n][polygons[n].size() - 1]; + Point2LL p0 = polygons[n][polygons[n].size() - 1]; for (size_t i = 0; i < polygons[n].size(); i++) { - Point p1 = polygons[n][i]; + Point2LL p1 = polygons[n][i]; // Q = A + Normal( B - A ) * ((( B - A ) dot ( P - A )) / VSize( A - B )); - Point pDiff = p1 - p0; + Point2LL pDiff = p1 - p0; int64_t lineLength = vSize(pDiff); if (lineLength > 1) { int64_t distOnLine = dot(pDiff, input - p0) / lineLength; if (distOnLine >= 0 && distOnLine <= lineLength) { - Point q = p0 + pDiff * distOnLine / lineLength; + Point2LL q = p0 + pDiff * distOnLine / lineLength; if (shorterThen(q - input, MM2INT(0.1))) { ClosePolygonResult ret; @@ -862,9 +862,9 @@ void Slicer::buildSegments(const Mesh& mesh, const std::vector> Slicer::buildZHeightsForFaces(const Mes const MeshVertex& v2 = mesh.vertices_[face.vertex_index_[2]]; // get all vertices represented as 3D point - Point3 p0 = v0.p_; - Point3 p1 = v1.p_; - Point3 p2 = v2.p_; + Point3LL p0 = v0.p_; + Point3LL p1 = v1.p_; + Point3LL p2 = v2.p_; // find the minimum and maximum z point int32_t minZ = p0.z_; @@ -1153,7 +1153,7 @@ std::vector> Slicer::buildZHeightsForFaces(const Mes return zHeights; } -SlicerSegment Slicer::project2D(const Point3& p0, const Point3& p1, const Point3& p2, const coord_t z) +SlicerSegment Slicer::project2D(const Point3LL& p0, const Point3LL& p1, const Point3LL& p2, const coord_t z) { SlicerSegment seg; diff --git a/src/support.cpp b/src/support.cpp index 66bc59eb91..05e81fbf93 100644 --- a/src/support.cpp +++ b/src/support.cpp @@ -492,7 +492,7 @@ Polygons AreaSupport::join(const SliceDataStorage& storage, const Polygons& supp for (unsigned int i = 0; i < circle_resolution; i++) { const AngleRadians angle = TAU * i / circle_resolution; - const Point3 machine_middle = storage.machine_size.getMiddle(); + const Point3LL machine_middle = storage.machine_size.getMiddle(); const coord_t x = machine_middle.x_ + cos(angle) * width / 2; const coord_t y = machine_middle.y_ + sin(angle) * depth / 2; border_circle.emplace_back(x, y); @@ -730,8 +730,8 @@ void AreaSupport::precomputeCrossInfillTree(SliceDataStorage& storage) } const coord_t aabb_expansion = infill_settings.get("support_offset"); AABB3D aabb_here(mesh.bounding_box); - aabb_here.include(aabb_here.min_ - Point3(-aabb_expansion, -aabb_expansion, 0)); - aabb_here.include(aabb_here.max_ + Point3(-aabb_expansion, -aabb_expansion, 0)); + aabb_here.include(aabb_here.min_ - Point3LL(-aabb_expansion, -aabb_expansion, 0)); + aabb_here.include(aabb_here.max_ + Point3LL(-aabb_expansion, -aabb_expansion, 0)); aabb.include(aabb_here); } @@ -1722,13 +1722,13 @@ void AreaSupport::handleWallStruts(const Settings& settings, Polygons& supportLa // add square tower (strut) in the middle of the wall if (width < max_tower_supported_diameter) { - Point mid = (poly[best] + poly[(best + 1) % poly.size()]) / 2; + Point2LL mid = (poly[best] + poly[(best + 1) % poly.size()]) / 2; Polygons struts; PolygonRef strut = struts.newPoly(); - strut.add(mid + Point(tower_diameter / 2, tower_diameter / 2)); - strut.add(mid + Point(-tower_diameter / 2, tower_diameter / 2)); - strut.add(mid + Point(-tower_diameter / 2, -tower_diameter / 2)); - strut.add(mid + Point(tower_diameter / 2, -tower_diameter / 2)); + strut.add(mid + Point2LL(tower_diameter / 2, tower_diameter / 2)); + strut.add(mid + Point2LL(-tower_diameter / 2, tower_diameter / 2)); + strut.add(mid + Point2LL(-tower_diameter / 2, -tower_diameter / 2)); + strut.add(mid + Point2LL(tower_diameter / 2, -tower_diameter / 2)); supportLayer_this = supportLayer_this.unionPolygons(struts); } } diff --git a/src/utils/AABB.cpp b/src/utils/AABB.cpp index d31a64af21..f3a93cbf1d 100644 --- a/src/utils/AABB.cpp +++ b/src/utils/AABB.cpp @@ -18,7 +18,7 @@ AABB::AABB() { } -AABB::AABB(const Point& min, const Point& max) +AABB::AABB(const Point2LL& min, const Point2LL& max) : min_(min) , max_(max) { @@ -38,15 +38,15 @@ AABB::AABB(ConstPolygonRef poly) calculate(poly); } -Point AABB::getMiddle() const +Point2LL AABB::getMiddle() const { return (min_ + max_) / 2; } -coord_t AABB::distanceSquared(const Point& p) const +coord_t AABB::distanceSquared(const Point2LL& p) const { - const Point a = Point(max_.X, min_.Y); - const Point b = Point(min_.X, max_.Y); + const Point2LL a = Point2LL(max_.X, min_.Y); + const Point2LL b = Point2LL(min_.X, max_.Y); return (contains(p) ? -1 : 1) * std::min({ LinearAlg2D::getDist2FromLineSegment(min_, a, p), LinearAlg2D::getDist2FromLineSegment(a, max_, p), @@ -61,17 +61,17 @@ coord_t AABB::distanceSquared(const AABB& other) const other.distanceSquared(min_), distanceSquared(other.max_), other.distanceSquared(max_), - distanceSquared(Point(other.max_.X, other.min_.Y)), - other.distanceSquared(Point(max_.X, min_.Y)), - distanceSquared(Point(other.min_.X, other.max_.Y)), - other.distanceSquared(Point(min_.X, max_.Y)), + distanceSquared(Point2LL(other.max_.X, other.min_.Y)), + other.distanceSquared(Point2LL(max_.X, min_.Y)), + distanceSquared(Point2LL(other.min_.X, other.max_.Y)), + other.distanceSquared(Point2LL(min_.X, max_.Y)), }); } void AABB::calculate(const Polygons& polys) { - min_ = Point(POINT_MAX, POINT_MAX); - max_ = Point(POINT_MIN, POINT_MIN); + min_ = Point2LL(POINT_MAX, POINT_MAX); + max_ = Point2LL(POINT_MIN, POINT_MIN); for (unsigned int i = 0; i < polys.size(); i++) { for (unsigned int j = 0; j < polys[i].size(); j++) @@ -83,15 +83,15 @@ void AABB::calculate(const Polygons& polys) void AABB::calculate(ConstPolygonRef poly) { - min_ = Point(POINT_MAX, POINT_MAX); - max_ = Point(POINT_MIN, POINT_MIN); - for (const Point& p : poly) + min_ = Point2LL(POINT_MAX, POINT_MAX); + max_ = Point2LL(POINT_MIN, POINT_MIN); + for (const Point2LL& p : poly) { include(p); } } -bool AABB::contains(const Point& point) const +bool AABB::contains(const Point2LL& point) const { return point.X >= min_.X && point.X <= max_.X && point.Y >= min_.Y && point.Y <= max_.Y; } @@ -131,7 +131,7 @@ bool AABB::hit(const AABB& other) const return true; } -void AABB::include(Point point) +void AABB::include(Point2LL point) { min_.X = std::min(min_.X, point.X); min_.Y = std::min(min_.Y, point.Y); @@ -150,7 +150,7 @@ void AABB::include(const AABB other) void AABB::expand(int dist) { - if (min_ == Point(POINT_MAX, POINT_MAX) || max_ == Point(POINT_MIN, POINT_MIN)) + if (min_ == Point2LL(POINT_MAX, POINT_MAX) || max_ == Point2LL(POINT_MIN, POINT_MIN)) { return; } @@ -164,9 +164,9 @@ Polygon AABB::toPolygon() const { Polygon ret; ret.add(min_); - ret.add(Point(max_.X, min_.Y)); + ret.add(Point2LL(max_.X, min_.Y)); ret.add(max_); - ret.add(Point(min_.X, max_.Y)); + ret.add(Point2LL(min_.X, max_.Y)); return ret; } diff --git a/src/utils/AABB3D.cpp b/src/utils/AABB3D.cpp index 4ace7d4cea..698c4745b7 100644 --- a/src/utils/AABB3D.cpp +++ b/src/utils/AABB3D.cpp @@ -16,20 +16,20 @@ AABB3D::AABB3D() { } -AABB3D::AABB3D(Point3 min, Point3 max) +AABB3D::AABB3D(Point3LL min, Point3LL max) : min_(min) , max_(max) { } -Point3 AABB3D::getMiddle() const +Point3LL AABB3D::getMiddle() const { return (min_ + max_) / 2; } AABB AABB3D::flatten() const { - return AABB(Point(min_.x_, min_.y_), Point(max_.x_, max_.y_)); + return AABB(Point2LL(min_.x_, min_.y_), Point2LL(max_.x_, max_.y_)); } @@ -42,7 +42,7 @@ bool AABB3D::hit(const AABB3D& other) const return true; } -AABB3D AABB3D::include(Point3 p) +AABB3D AABB3D::include(Point3LL p) { min_.x_ = std::min(min_.x_, p.x_); min_.y_ = std::min(min_.y_, p.y_); @@ -72,14 +72,14 @@ AABB3D AABB3D::includeZ(coord_t z) return *this; } -AABB3D AABB3D::translate(Point3 offset) +AABB3D AABB3D::translate(Point3LL offset) { min_ += offset; max_ += offset; return *this; } -AABB3D AABB3D::translate(Point offset) +AABB3D AABB3D::translate(Point2LL offset) { min_ += offset; max_ += offset; @@ -88,8 +88,8 @@ AABB3D AABB3D::translate(Point offset) AABB3D AABB3D::expand(coord_t outset) { - min_ -= Point3(outset, outset, outset); - max_ += Point3(outset, outset, outset); + min_ -= Point3LL(outset, outset, outset); + max_ += Point3LL(outset, outset, outset); if (min_.x_ > max_.x_ || min_.y_ > max_.y_ || min_.z_ > max_.z_) { // make this AABB3D invalid *this = AABB3D(); @@ -99,8 +99,8 @@ AABB3D AABB3D::expand(coord_t outset) AABB3D AABB3D::expandXY(coord_t outset) { - min_ -= Point3(outset, outset, 0); - max_ += Point3(outset, outset, 0); + min_ -= Point3LL(outset, outset, 0); + max_ += Point3LL(outset, outset, 0); if (min_.x_ > max_.x_ || min_.y_ > max_.y_) { // make this AABB3D invalid *this = AABB3D(); diff --git a/src/utils/ExtrusionJunction.cpp b/src/utils/ExtrusionJunction.cpp index 4e83ad3c24..366d15dad3 100644 --- a/src/utils/ExtrusionJunction.cpp +++ b/src/utils/ExtrusionJunction.cpp @@ -11,7 +11,7 @@ bool ExtrusionJunction::operator==(const ExtrusionJunction& other) const return p_ == other.p_ && w_ == other.w_ && perimeter_index_ == other.perimeter_index_; } -ExtrusionJunction::ExtrusionJunction(const Point p, const coord_t w, const coord_t perimeter_index) +ExtrusionJunction::ExtrusionJunction(const Point2LL p, const coord_t w, const coord_t perimeter_index) : p_(p) , w_(w) , perimeter_index_(perimeter_index) diff --git a/src/utils/ExtrusionSegment.cpp b/src/utils/ExtrusionSegment.cpp index 9e6edb8c5d..71a2d59bef 100644 --- a/src/utils/ExtrusionSegment.cpp +++ b/src/utils/ExtrusionSegment.cpp @@ -18,7 +18,7 @@ Polygons ExtrusionSegment::toPolygons() Polygons ExtrusionSegment::toPolygons(bool reduced) { Polygons ret; - const Point vec = to_.p_ - from_.p_; + const Point2LL vec = to_.p_ - from_.p_; const coord_t vec_length = vSize(vec); if (vec_length <= 0) // Don't even output the endcaps. @@ -49,7 +49,7 @@ Polygons ExtrusionSegment::toPolygons(bool reduced) // Draw the endcap on the "from" vertex's end. { - poly.emplace_back(from_.p_ + Point(from_.w_ / 2 * cos(alpha + dir), from_.w_ / 2 * sin(alpha + dir))); + poly.emplace_back(from_.p_ + Point2LL(from_.w_ / 2 * cos(alpha + dir), from_.w_ / 2 * sin(alpha + dir))); double start_a = 2 * std::numbers::pi; while (start_a > alpha + dir) @@ -67,16 +67,16 @@ Polygons ExtrusionSegment::toPolygons(bool reduced) // Draw the endcap. for (double a = start_a; a <= end_a; a += a_step) { - poly.emplace_back(from_.p_ + Point(from_.w_ / 2 * cos(a), from_.w_ / 2 * sin(a))); + poly.emplace_back(from_.p_ + Point2LL(from_.w_ / 2 * cos(a), from_.w_ / 2 * sin(a))); } - poly.emplace_back(from_.p_ + Point(from_.w_ / 2 * cos(2 * std::numbers::pi - alpha + dir), from_.w_ / 2 * sin(2 * std::numbers::pi - alpha + dir))); + poly.emplace_back(from_.p_ + Point2LL(from_.w_ / 2 * cos(2 * std::numbers::pi - alpha + dir), from_.w_ / 2 * sin(2 * std::numbers::pi - alpha + dir))); } // Draw the endcap on the "to" vertex's end. { poly.emplace_back( to_.p_ - + Point( + + Point2LL( to_.w_ / 2 * cos(2 * std::numbers::pi - alpha + dir), to_.w_ / 2 * sin(2 * std::numbers::pi - alpha + dir))); // Also draws the main diagonal from the "from" vertex to the "to" vertex! @@ -109,23 +109,23 @@ Polygons ExtrusionSegment::toPolygons(bool reduced) { for (double a = end_a; a >= start_a; a -= a_step) // Go in the opposite direction. { - poly.emplace_back(to_.p_ + Point(to_.w_ / 2 * cos(a), to_.w_ / 2 * sin(a))); + poly.emplace_back(to_.p_ + Point2LL(to_.w_ / 2 * cos(a), to_.w_ / 2 * sin(a))); } } else { for (double a = end_a; a <= start_a; a += a_step) { - poly.emplace_back(to_.p_ + Point(to_.w_ / 2 * cos(a), to_.w_ / 2 * sin(a))); + poly.emplace_back(to_.p_ + Point2LL(to_.w_ / 2 * cos(a), to_.w_ / 2 * sin(a))); } } - poly.emplace_back(to_.p_ + Point(to_.w_ / 2 * cos(alpha + dir), to_.w_ / 2 * sin(alpha + dir))); + poly.emplace_back(to_.p_ + Point2LL(to_.w_ / 2 * cos(alpha + dir), to_.w_ / 2 * sin(alpha + dir))); // The other main diagonal from the "to" vertex to the "from" vertex is implicit in the closing of the polygon. } #ifdef DEBUG - for (Point p : poly) + for (Point2LL p : poly) { assert(p.X < 0x3FFFFFFFFFFFFFFFLL); assert(p.Y < 0x3FFFFFFFFFFFFFFFLL); @@ -138,9 +138,9 @@ Polygons ExtrusionSegment::toPolygons(bool reduced) std::vector ExtrusionSegment::discretize(coord_t step_size) { - Point a = from_.p_; - Point b = to_.p_; - Point ab = b - a; + Point2LL a = from_.p_; + Point2LL b = to_.p_; + Point2LL ab = b - a; coord_t ab_length = vSize(ab); coord_t step_count = std::max(static_cast(1), (ab_length + step_size / 2) / step_size); std::vector discretized; diff --git a/src/utils/LinearAlg2D.cpp b/src/utils/LinearAlg2D.cpp index 98a9b896fa..2292323251 100644 --- a/src/utils/LinearAlg2D.cpp +++ b/src/utils/LinearAlg2D.cpp @@ -7,15 +7,15 @@ #include #include // atan2 -#include "utils/IntPoint.h" // dot +#include "utils/Point2LL.h" // dot namespace cura { -double LinearAlg2D::getAngleLeft(const Point& a, const Point& b, const Point& c) +double LinearAlg2D::getAngleLeft(const Point2LL& a, const Point2LL& b, const Point2LL& c) { - const Point ba = a - b; - const Point bc = c - b; + const Point2LL ba = a - b; + const Point2LL bc = c - b; const coord_t dott = dot(ba, bc); // dot product const coord_t det = ba.X * bc.Y - ba.Y * bc.X; // determinant if (det == 0) @@ -41,7 +41,7 @@ double LinearAlg2D::getAngleLeft(const Point& a, const Point& b, const Point& c) } -bool LinearAlg2D::getPointOnLineWithDist(const Point& p, const Point& a, const Point& b, const coord_t dist, Point& result) +bool LinearAlg2D::getPointOnLineWithDist(const Point2LL& p, const Point2LL& a, const Point2LL& b, const coord_t dist, Point2LL& result) { // result // v @@ -49,9 +49,9 @@ bool LinearAlg2D::getPointOnLineWithDist(const Point& p, const Point& a, const P // '-. : // '-. : // '-.p - const Point ab = b - a; + const Point2LL ab = b - a; const coord_t ab_size = vSize(ab); - const Point ap = p - a; + const Point2LL ap = p - a; const coord_t ax_size = (ab_size < 50) ? dot(normal(ab, 1000), ap) / 1000 : dot(ab, ap) / ab_size; const coord_t ap_size2 = vSize2(ap); const coord_t px_size = sqrt(std::max(coord_t(0), ap_size2 - ax_size * ax_size)); @@ -124,15 +124,15 @@ bool LinearAlg2D::getPointOnLineWithDist(const Point& p, const Point& a, const P } -std::pair LinearAlg2D::getClosestConnection(Point a1, Point a2, Point b1, Point b2) +std::pair LinearAlg2D::getClosestConnection(Point2LL a1, Point2LL a2, Point2LL b1, Point2LL b2) { - Point b1_on_a = getClosestOnLineSegment(b1, a1, a2); + Point2LL b1_on_a = getClosestOnLineSegment(b1, a1, a2); coord_t b1_on_a_dist2 = vSize2(b1_on_a - b1); - Point b2_on_a = getClosestOnLineSegment(b2, a1, a2); + Point2LL b2_on_a = getClosestOnLineSegment(b2, a1, a2); coord_t b2_on_a_dist2 = vSize2(b2_on_a - b2); - Point a1_on_b = getClosestOnLineSegment(a1, b1, b2); + Point2LL a1_on_b = getClosestOnLineSegment(a1, b1, b2); coord_t a1_on_b_dist2 = vSize2(a1_on_b - a1); - Point a2_on_b = getClosestOnLineSegment(a1, b1, b2); + Point2LL a2_on_b = getClosestOnLineSegment(a1, b1, b2); coord_t a2_on_b_dist2 = vSize2(a2_on_b - a2); if (b1_on_a_dist2 < b2_on_a_dist2 && b1_on_a_dist2 < a1_on_b_dist2 && b1_on_a_dist2 < a2_on_b_dist2) { @@ -152,7 +152,7 @@ std::pair LinearAlg2D::getClosestConnection(Point a1, Point a2, Po } } -bool LinearAlg2D::lineSegmentsCollide(const Point& a_from_transformed, const Point& a_to_transformed, Point b_from_transformed, Point b_to_transformed) +bool LinearAlg2D::lineSegmentsCollide(const Point2LL& a_from_transformed, const Point2LL& a_to_transformed, Point2LL b_from_transformed, Point2LL b_to_transformed) { assert(std::abs(a_from_transformed.Y - a_to_transformed.Y) < 2 && "line a is supposed to be transformed to be aligned with the X axis!"); assert(a_from_transformed.X - 2 <= a_to_transformed.X && "line a is supposed to be aligned with X axis in positive direction!"); @@ -188,7 +188,7 @@ bool LinearAlg2D::lineSegmentsCollide(const Point& a_from_transformed, const Poi return false; } -coord_t LinearAlg2D::getDist2FromLine(const Point& p, const Point& a, const Point& b) +coord_t LinearAlg2D::getDist2FromLine(const Point2LL& p, const Point2LL& a, const Point2LL& b) { // NOTE: The version that tried to do a faster calulation wasn't actually that much faster, and introduced errors. // Use this for now, should we need this, we can reimplement later. @@ -196,7 +196,7 @@ coord_t LinearAlg2D::getDist2FromLine(const Point& p, const Point& a, const Poin return dist * dist; } -bool LinearAlg2D::isInsideCorner(const Point a, const Point b, const Point c, const Point query_point) +bool LinearAlg2D::isInsideCorner(const Point2LL a, const Point2LL b, const Point2LL c, const Point2LL query_point) { /* Visualisation for the algorithm below: @@ -214,10 +214,10 @@ bool LinearAlg2D::isInsideCorner(const Point a, const Point b, const Point c, co constexpr coord_t normal_length = 10000; // Create a normal vector of reasonable length in order to reduce rounding error. - const Point ba = normal(a - b, normal_length); - const Point bc = normal(c - b, normal_length); - const Point bq = query_point - b; - const Point perpendicular = turn90CCW(bq); // The query projects to this perpendicular to coordinate 0. + const Point2LL ba = normal(a - b, normal_length); + const Point2LL bc = normal(c - b, normal_length); + const Point2LL bq = query_point - b; + const Point2LL perpendicular = turn90CCW(bq); // The query projects to this perpendicular to coordinate 0. const coord_t project_a_perpendicular = dot(ba, perpendicular); // Project vertex A on the perpendicular line. const coord_t project_c_perpendicular = dot(bc, perpendicular); // Project vertex C on the perpendicular line. if ((project_a_perpendicular > 0) != (project_c_perpendicular > 0)) // Query is between A and C on the projection. @@ -236,15 +236,15 @@ bool LinearAlg2D::isInsideCorner(const Point a, const Point b, const Point c, co } } -coord_t LinearAlg2D::getDistFromLine(const Point& p, const Point& a, const Point& b) +coord_t LinearAlg2D::getDistFromLine(const Point2LL& p, const Point2LL& a, const Point2LL& b) { // x.......a------------b // : // : // p // return px_size - const Point vab = b - a; - const Point vap = p - a; + const Point2LL vab = b - a; + const Point2LL vap = p - a; const double ab_size = vSize(vab); if (ab_size == 0) // Line of 0 length. Assume it's a line perpendicular to the direction to p. { @@ -255,7 +255,7 @@ coord_t LinearAlg2D::getDistFromLine(const Point& p, const Point& a, const Point return px_size; } -Point LinearAlg2D::getBisectorVector(const Point& intersect, const Point& a, const Point& b, const coord_t vec_len) +Point2LL LinearAlg2D::getBisectorVector(const Point2LL& intersect, const Point2LL& a, const Point2LL& b, const coord_t vec_len) { const auto a0 = a - intersect; const auto b0 = b - intersect; diff --git a/src/utils/ListPolyIt.cpp b/src/utils/ListPolyIt.cpp index c640a9884e..c2c4a7cf0a 100644 --- a/src/utils/ListPolyIt.cpp +++ b/src/utils/ListPolyIt.cpp @@ -25,9 +25,9 @@ void ListPolyIt::convertPolygonsToLists(const Polygons& polys, ListPolygons& res void ListPolyIt::convertPolygonToList(ConstPolygonRef poly, ListPolygon& result) { #ifdef DEBUG - Point last = poly.back(); + Point2LL last = poly.back(); #endif // DEBUG - for (const Point& p : poly) + for (const Point2LL& p : poly) { result.push_back(p); #ifdef DEBUG @@ -52,13 +52,13 @@ void ListPolyIt::convertListPolygonsToPolygons(const ListPolygons& list_polygons void ListPolyIt::convertListPolygonToPolygon(const ListPolygon& list_polygon, PolygonRef polygon) { - for (const Point& p : list_polygon) + for (const Point2LL& p : list_polygon) { polygon.add(p); } } -ListPolyIt ListPolyIt::insertPointNonDuplicate(const ListPolyIt before, const ListPolyIt after, const Point to_insert) +ListPolyIt ListPolyIt::insertPointNonDuplicate(const ListPolyIt before, const ListPolyIt after, const Point2LL to_insert) { if (to_insert == before.p()) { diff --git a/src/utils/FMatrix4x3.cpp b/src/utils/Matrix4x3D.cpp similarity index 83% rename from src/utils/FMatrix4x3.cpp rename to src/utils/Matrix4x3D.cpp index 99d5bc0646..225be8db8a 100644 --- a/src/utils/FMatrix4x3.cpp +++ b/src/utils/Matrix4x3D.cpp @@ -2,19 +2,19 @@ // CuraEngine is released under the terms of the AGPLv3 or higher. #include "settings/types/Ratio.h" //Scale factor. -#include "utils/IntPoint.h" //Conversion directly into integer-based coordinates. +#include "utils/Point2LL.h" //Conversion directly into integer-based coordinates. #include "utils/Matrix4x3D.h" //The definitions we're implementing. #include "utils/Point3D.h" //This matrix gets applied to floating point coordinates. namespace cura { -Matrix4x3D Matrix4x3D::scale(const Ratio scale, const Point3 origin) +Matrix4x3D Matrix4x3D::scale(const Ratio scale, const Point3LL origin) { return Matrix4x3D::scale(scale, scale, scale, origin); } -Matrix4x3D Matrix4x3D::scale(const Ratio scale_x, const Ratio scale_y, const Ratio scale_z, const Point3 origin) +Matrix4x3D Matrix4x3D::scale(const Ratio scale_x, const Ratio scale_y, const Ratio scale_z, const Point3LL origin) { Matrix4x3D result; result.m[0][0] = scale_x; // X scale. @@ -45,17 +45,17 @@ Matrix4x3D::Matrix4x3D() m[3][2] = 0.0; } -Point3 Matrix4x3D::apply(const Point3D& p) const +Point3LL Matrix4x3D::apply(const Point3D& p) const { - return Point3( + return Point3LL( MM2INT(p.x_ * m[0][0] + p.y_ * m[1][0] + p.z_ * m[2][0] + m[3][0]), MM2INT(p.x_ * m[0][1] + p.y_ * m[1][1] + p.z_ * m[2][1] + m[3][1]), MM2INT(p.x_ * m[0][2] + p.y_ * m[1][2] + p.z_ * m[2][2] + m[3][2])); } -Point3 Matrix4x3D::apply(const Point3& p) const +Point3LL Matrix4x3D::apply(const Point3LL& p) const { - return Point3( + return Point3LL( m[0][0] * p.x_ + m[1][0] * p.y_ + m[2][0] * p.z_ + m[3][0], m[0][1] * p.x_ + m[1][1] * p.y_ + m[2][1] * p.z_ + m[3][1], m[0][2] * p.x_ + m[1][2] * p.y_ + m[2][2] * p.z_ + m[3][2]); diff --git a/src/utils/MinimumSpanningTree.cpp b/src/utils/MinimumSpanningTree.cpp index eff7757a01..f32b104913 100644 --- a/src/utils/MinimumSpanningTree.cpp +++ b/src/utils/MinimumSpanningTree.cpp @@ -9,12 +9,12 @@ namespace cura { -MinimumSpanningTree::MinimumSpanningTree(std::vector vertices) : adjacency_graph(prim(vertices)) +MinimumSpanningTree::MinimumSpanningTree(std::vector vertices) : adjacency_graph(prim(vertices)) { //Just copy over the fields. } -auto MinimumSpanningTree::prim(std::vector vertices) const -> AdjacencyGraph_t +auto MinimumSpanningTree::prim(std::vector vertices) const -> AdjacencyGraph_t { AdjacencyGraph_t result; if (vertices.empty()) @@ -31,10 +31,10 @@ auto MinimumSpanningTree::prim(std::vector vertices) const -> AdjacencyGr return result; } result.reserve(vertices.size()); - std::vector vertices_list(vertices.begin(), vertices.end()); + std::vector vertices_list(vertices.begin(), vertices.end()); - std::unordered_map smallest_distance; //The shortest distance to the current tree. - std::unordered_map smallest_distance_to; //Which point the shortest distance goes towards. + std::unordered_map smallest_distance; //The shortest distance to the current tree. + std::unordered_map smallest_distance_to; //Which point the shortest distance goes towards. smallest_distance.reserve(vertices_list.size()); smallest_distance_to.reserve(vertices_list.size()); for (size_t vertex_index = 1; vertex_index < vertices_list.size(); vertex_index++) @@ -50,15 +50,15 @@ auto MinimumSpanningTree::prim(std::vector vertices) const -> AdjacencyGr //This search is O(V) right now, which can be made down to O(log(V)). This reduces the overall time complexity from O(V*V) to O(V*log(E)). //However that requires an implementation of a heap that supports the decreaseKey operation, which is not in the std library. //TODO: Implement this? - using MapValue = std::pair; + using MapValue = std::pair; const auto closest = std::min_element(smallest_distance.begin(), smallest_distance.end(), [](const MapValue& a, const MapValue& b) { return a.second < b.second; }); //Add this point to the graph and remove it from the candidates. - const Point* closest_point = closest->first; - const Point other_end = *smallest_distance_to[closest_point]; + const Point2LL* closest_point = closest->first; + const Point2LL other_end = *smallest_distance_to[closest_point]; if (result.find(*closest_point) == result.end()) { result[*closest_point] = std::vector(); @@ -73,7 +73,7 @@ auto MinimumSpanningTree::prim(std::vector vertices) const -> AdjacencyGr smallest_distance_to.erase(closest_point); //Update the distances of all points that are not in the graph. - for (std::pair point_and_distance : smallest_distance) + for (std::pair point_and_distance : smallest_distance) { const coord_t new_distance = vSize2(*closest_point - *point_and_distance.first); const coord_t old_distance = point_and_distance.second; @@ -88,9 +88,9 @@ auto MinimumSpanningTree::prim(std::vector vertices) const -> AdjacencyGr return result; } -std::vector MinimumSpanningTree::adjacentNodes(Point node) const +std::vector MinimumSpanningTree::adjacentNodes(Point2LL node) const { - std::vector result; + std::vector result; AdjacencyGraph_t::const_iterator adjacency_entry = adjacency_graph.find(node); if (adjacency_entry != adjacency_graph.end()) { @@ -101,10 +101,10 @@ std::vector MinimumSpanningTree::adjacentNodes(Point node) const return result; } -std::vector MinimumSpanningTree::leaves() const +std::vector MinimumSpanningTree::leaves() const { - std::vector result; - for (std::pair> node : adjacency_graph) + std::vector result; + for (std::pair> node : adjacency_graph) { if (node.second.size() <= 1) //Leaves are nodes that have only one adjacent edge, or just the one node if the tree contains one node. { @@ -114,10 +114,10 @@ std::vector MinimumSpanningTree::leaves() const return result; } -std::vector MinimumSpanningTree::vertices() const +std::vector MinimumSpanningTree::vertices() const { - std::vector result; - using MapValue = std::pair>; + std::vector result; + using MapValue = std::pair>; std::transform(adjacency_graph.begin(), adjacency_graph.end(), std::back_inserter(result), [](const MapValue& node) { return node.first; }); return result; diff --git a/src/utils/Point3.cpp b/src/utils/Point3.cpp deleted file mode 100644 index f84d8589dd..0000000000 --- a/src/utils/Point3.cpp +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) 2022 Ultimaker B.V. -// CuraEngine is released under the terms of the AGPLv3 or higher. - -#include "utils/Point3.h" //The headers we're implementing. - -namespace cura -{ - -Point3 Point3::operator+(const Point3& p) const -{ - return Point3(x_ + p.x_, y_ + p.y_, z_ + p.z_); -} - -Point3 Point3::operator-() const -{ - return Point3(-x_, -y_, -z_); -} - -Point3 Point3::operator-(const Point3& p) const -{ - return Point3(x_ - p.x_, y_ - p.y_, z_ - p.z_); -} - -Point3 Point3::operator*(const Point3& p) const -{ - return Point3(x_ * p.x_, y_ * p.y_, z_ * p.z_); -} - -Point3 Point3::operator/(const Point3& p) const -{ - return Point3(x_ / p.x_, y_ / p.y_, z_ / p.z_); -} - -Point3& Point3::operator+=(const Point3& p) -{ - x_ += p.x_; - y_ += p.y_; - z_ += p.z_; - return *this; -} - -Point3& Point3::operator-=(const Point3& p) -{ - x_ -= p.x_; - y_ -= p.y_; - z_ -= p.z_; - return *this; -} - -Point3& Point3::operator*=(const Point3& p) -{ - x_ *= p.x_; - y_ *= p.y_; - z_ *= p.z_; - return *this; -} - -Point3& Point3::operator/=(const Point3& p) -{ - x_ /= p.x_; - y_ /= p.y_; - z_ /= p.z_; - return *this; -} - -bool Point3::operator==(const Point3& p) const -{ - return x_ == p.x_ && y_ == p.y_ && z_ == p.z_; -} - -bool Point3::operator!=(const Point3& p) const -{ - return x_ != p.x_ || y_ != p.y_ || z_ != p.z_; -} - -} // namespace cura diff --git a/src/utils/Point3LL.cpp b/src/utils/Point3LL.cpp new file mode 100644 index 0000000000..2420552fb6 --- /dev/null +++ b/src/utils/Point3LL.cpp @@ -0,0 +1,76 @@ +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. + +#include "utils/Point3LL.h" //The headers we're implementing. + +namespace cura +{ + +Point3LL Point3LL::operator+(const Point3LL& p) const +{ + return Point3LL(x_ + p.x_, y_ + p.y_, z_ + p.z_); +} + +Point3LL Point3LL::operator-() const +{ + return Point3LL(-x_, -y_, -z_); +} + +Point3LL Point3LL::operator-(const Point3LL& p) const +{ + return Point3LL(x_ - p.x_, y_ - p.y_, z_ - p.z_); +} + +Point3LL Point3LL::operator*(const Point3LL& p) const +{ + return Point3LL(x_ * p.x_, y_ * p.y_, z_ * p.z_); +} + +Point3LL Point3LL::operator/(const Point3LL& p) const +{ + return Point3LL(x_ / p.x_, y_ / p.y_, z_ / p.z_); +} + +Point3LL& Point3LL::operator+=(const Point3LL& p) +{ + x_ += p.x_; + y_ += p.y_; + z_ += p.z_; + return *this; +} + +Point3LL& Point3LL::operator-=(const Point3LL& p) +{ + x_ -= p.x_; + y_ -= p.y_; + z_ -= p.z_; + return *this; +} + +Point3LL& Point3LL::operator*=(const Point3LL& p) +{ + x_ *= p.x_; + y_ *= p.y_; + z_ *= p.z_; + return *this; +} + +Point3LL& Point3LL::operator/=(const Point3LL& p) +{ + x_ /= p.x_; + y_ /= p.y_; + z_ /= p.z_; + return *this; +} + +bool Point3LL::operator==(const Point3LL& p) const +{ + return x_ == p.x_ && y_ == p.y_ && z_ == p.z_; +} + +bool Point3LL::operator!=(const Point3LL& p) const +{ + return x_ != p.x_ || y_ != p.y_ || z_ != p.z_; +} + +} // namespace cura diff --git a/src/utils/PolygonConnector.cpp b/src/utils/PolygonConnector.cpp index 62b7b968a3..936ad69850 100644 --- a/src/utils/PolygonConnector.cpp +++ b/src/utils/PolygonConnector.cpp @@ -45,17 +45,17 @@ void PolygonConnector::connect(Polygons& output_polygons, std::vector::can } template<> -bool PolylineStitcher::canReverse(const PathsPointIndex&) +bool PolylineStitcher::canReverse(const PathsPointIndex&) { return true; } @@ -35,7 +35,7 @@ bool PolylineStitcher::can } template<> -bool PolylineStitcher::canConnect(const Polygon&, const Polygon&) +bool PolylineStitcher::canConnect(const Polygon&, const Polygon&) { return true; } @@ -47,7 +47,7 @@ bool PolylineStitcher::isO } template<> -bool PolylineStitcher::isOdd(const Polygon&) +bool PolylineStitcher::isOdd(const Polygon&) { return false; } diff --git a/src/utils/SVG.cpp b/src/utils/SVG.cpp index 497f3fe6b7..a5ee2c14b8 100644 --- a/src/utils/SVG.cpp +++ b/src/utils/SVG.cpp @@ -59,7 +59,7 @@ std::string SVG::toString(const ColorObject& color) const } -SVG::SVG(std::string filename, AABB aabb, Point canvas_size, ColorObject background) +SVG::SVG(std::string filename, AABB aabb, Point2LL canvas_size, ColorObject background) : SVG( filename, aabb, @@ -76,7 +76,7 @@ SVG::SVG(std::string filename, AABB aabb, double scale, ColorObject background) { } -SVG::SVG(std::string filename, AABB aabb, double scale, Point canvas_size, ColorObject background) +SVG::SVG(std::string filename, AABB aabb, double scale, Point2LL canvas_size, ColorObject background) : aabb_(aabb) , aabb_size_(aabb.max_ - aabb.min_) , canvas_size_(canvas_size) @@ -140,12 +140,12 @@ void SVG::nextLayer() fprintf(out_, " id=\"layer%zu\">\n", layer_nr_); } -Point SVG::transform(const Point& p) const +Point2LL SVG::transform(const Point2LL& p) const { - return Point(std::llrint(static_cast(p.X - aabb_.min_.X) * scale_), std::llrint(static_cast(p.Y - aabb_.min_.Y) * scale_)); + return Point2LL(std::llrint(static_cast(p.X - aabb_.min_.X) * scale_), std::llrint(static_cast(p.Y - aabb_.min_.Y) * scale_)); } -Point3D SVG::transformF(const Point& p) const +Point3D SVG::transformF(const Point2LL& p) const { return Point3D(static_cast(p.X - aabb_.min_.X) * scale_, static_cast(p.Y - aabb_.min_.Y) * scale_, 0.0); } @@ -164,7 +164,7 @@ void SVG::writeAreas(const Polygons& polygons, const ColorObject color, const Co for (size_t j = 0; j < part.size(); j++) { fprintf(out_, "(fp.x_), static_cast(fp.y_)); @@ -185,7 +185,7 @@ void SVG::writeAreas(ConstPolygonRef polygon, const ColorObject color, const Col toString(color).c_str(), toString(outline_color).c_str(), static_cast(stroke_width)); // The beginning of the polygon tag. - for (const Point& point : polygon) // Add every point to the list of points. + for (const Point2LL& point : polygon) // Add every point to the list of points. { Point3D transformed = transformF(point); fprintf(out_, "%f,%f ", static_cast(transformed.x_), static_cast(transformed.y_)); @@ -193,7 +193,7 @@ void SVG::writeAreas(ConstPolygonRef polygon, const ColorObject color, const Col fprintf(out_, "\" />\n"); // The end of the polygon tag. } -void SVG::writePoint(const Point& p, const bool write_coords, const double size, const ColorObject color) const +void SVG::writePoint(const Point2LL& p, const bool write_coords, const double size, const ColorObject color) const { Point3D pf = transformF(p); fprintf( @@ -212,7 +212,7 @@ void SVG::writePoint(const Point& p, const bool write_coords, const double size, void SVG::writePoints(ConstPolygonRef poly, const bool write_coords, const double size, const ColorObject color) const { - for (const Point& p : poly) + for (const Point2LL& p : poly) { writePoint(p, write_coords, size, color); } @@ -226,7 +226,7 @@ void SVG::writePoints(const Polygons& polygons, const bool write_coords, const d } } -void SVG::writeLines(const std::vector& polyline, const ColorObject color) const +void SVG::writeLines(const std::vector& polyline, const ColorObject color) const { if (polyline.size() <= 1) // Need at least 2 points. { @@ -248,7 +248,7 @@ void SVG::writeLines(const std::vector& polyline, const ColorObject color fprintf(out_, "\" />\n"); // Write the end of the tag. } -void SVG::writeLine(const Point& a, const Point& b, const ColorObject color, const double stroke_width) const +void SVG::writeLine(const Point2LL& a, const Point2LL& b, const ColorObject color, const double stroke_width) const { Point3D fa = transformF(a); Point3D fb = transformF(b); @@ -263,7 +263,7 @@ void SVG::writeLine(const Point& a, const Point& b, const ColorObject color, con static_cast(stroke_width)); } -void SVG::writeArrow(const Point& a, const Point& b, const ColorObject color, const double stroke_width, const double head_size) const +void SVG::writeArrow(const Point2LL& a, const Point2LL& b, const ColorObject color, const double stroke_width, const double head_size) const { Point3D fa = transformF(a); Point3D fb = transformF(b); @@ -290,7 +290,7 @@ void SVG::writeArrow(const Point& a, const Point& b, const ColorObject color, co static_cast(a_base.y_)); } -void SVG::writeLineRGB(const Point& from, const Point& to, const int r, const int g, const int b, const double stroke_width) const +void SVG::writeLineRGB(const Point2LL& from, const Point2LL& to, const int r, const int g, const int b, const double stroke_width) const { Point3D fa = transformF(from); Point3D fb = transformF(to); @@ -307,7 +307,7 @@ void SVG::writeLineRGB(const Point& from, const Point& to, const int r, const in static_cast(stroke_width)); } -void SVG::writeDashedLine(const Point& a, const Point& b, ColorObject color) const +void SVG::writeDashedLine(const Point2LL& a, const Point2LL& b, ColorObject color) const { Point3D fa = transformF(a); Point3D fb = transformF(b); @@ -321,7 +321,7 @@ void SVG::writeDashedLine(const Point& a, const Point& b, ColorObject color) con toString(color).c_str()); } -void SVG::writeText(const Point& p, const std::string& txt, const ColorObject color, const double font_size) const +void SVG::writeText(const Point2LL& p, const std::string& txt, const ColorObject color, const double font_size) const { Point3D pf = transformF(p); fprintf( @@ -349,9 +349,9 @@ void SVG::writePolygon(ConstPolygonRef poly, const ColorObject color, const doub return; } int size = static_cast(poly.size()); - Point p0 = poly.back(); + Point2LL p0 = poly.back(); int i = 0; - for (Point p1 : poly) + for (Point2LL p1 : poly) { if (color.color_ == Color::RAINBOW) { @@ -392,11 +392,11 @@ void SVG::writePolyline(ConstPolygonRef poly, const ColorObject color, const dou return; } const int size = static_cast(poly.size()); - Point p0 = poly[0]; + Point2LL p0 = poly[0]; int i = 0; for (size_t p_idx = 1; p_idx < poly.size(); p_idx++) { - Point p1 = poly[p_idx]; + Point2LL p1 = poly[p_idx]; if (color.color_ == Color::RAINBOW) { int g = (i * 255 * 11 / size) % (255 * 2); @@ -445,9 +445,9 @@ void SVG::writeLine(const ExtrusionLine& line, const ColorObject color, const do ExtrusionJunction end_vertex = line.junctions_[index]; // Compute the corners of the trapezoid for this variable-width line segment. - const Point direction_vector = end_vertex.p_ - start_vertex.p_; - const Point direction_left = turn90CCW(direction_vector); - const Point direction_right = -direction_left; // Opposite of left. + const Point2LL direction_vector = end_vertex.p_ - start_vertex.p_; + const Point2LL direction_left = turn90CCW(direction_vector); + const Point2LL direction_right = -direction_left; // Opposite of left. const Point3D start_left = transformF(start_vertex.p_ + normal(direction_left, std::llrint(std::max(minimum_line_width, static_cast(start_vertex.w_) * width_factor)))); const Point3D start_right @@ -480,17 +480,17 @@ void SVG::writeCoordinateGrid(const coord_t grid_size, const Color color, const for (coord_t x = min_x; x < aabb_.max_.X; x += grid_size) { - writeLine(Point(x, aabb_.min_.Y), Point(x, aabb_.max_.Y), color, stroke_width); + writeLine(Point2LL(x, aabb_.min_.Y), Point2LL(x, aabb_.max_.Y), color, stroke_width); std::stringstream ss; ss << INT2MM(x); - writeText(Point(x, std::llrint(static_cast(aabb_.min_.Y) + static_cast(aabb_.max_.Y - aabb_.min_.Y) * dist_from_edge)), ss.str(), color, font_size); + writeText(Point2LL(x, std::llrint(static_cast(aabb_.min_.Y) + static_cast(aabb_.max_.Y - aabb_.min_.Y) * dist_from_edge)), ss.str(), color, font_size); } for (coord_t y = min_y; y < aabb_.max_.Y; y += grid_size) { - writeLine(Point(aabb_.min_.X, y), Point(aabb_.max_.Y, y), color, stroke_width); + writeLine(Point2LL(aabb_.min_.X, y), Point2LL(aabb_.max_.Y, y), color, stroke_width); std::stringstream ss; ss << INT2MM(y); - writeText(Point(std::llrint(static_cast(aabb_.min_.X) + static_cast(aabb_.max_.X - aabb_.min_.X) * dist_from_edge), y), ss.str(), color, font_size); + writeText(Point2LL(std::llrint(static_cast(aabb_.min_.X) + static_cast(aabb_.max_.X - aabb_.min_.X) * dist_from_edge), y), ss.str(), color, font_size); } } diff --git a/src/utils/Simplify.cpp b/src/utils/Simplify.cpp index caefbf74de..cad210b30b 100644 --- a/src/utils/Simplify.cpp +++ b/src/utils/Simplify.cpp @@ -95,7 +95,7 @@ ExtrusionLine Simplify::createEmpty(const ExtrusionLine& original) const return result; } -void Simplify::appendVertex(Polygon& polygon, const Point& vertex) const +void Simplify::appendVertex(Polygon& polygon, const Point2LL& vertex) const { polygon.add(vertex); } @@ -105,22 +105,22 @@ void Simplify::appendVertex(ExtrusionLine& extrusion_line, const ExtrusionJuncti extrusion_line.junctions_.push_back(vertex); } -const Point& Simplify::getPosition(const Point& vertex) const +const Point2LL& Simplify::getPosition(const Point2LL& vertex) const { return vertex; } -const Point& Simplify::getPosition(const ExtrusionJunction& vertex) const +const Point2LL& Simplify::getPosition(const ExtrusionJunction& vertex) const { return vertex.p_; } -Point Simplify::createIntersection(const Point& before, const Point intersection, const Point& after) const +Point2LL Simplify::createIntersection(const Point2LL& before, const Point2LL intersection, const Point2LL& after) const { return intersection; } -ExtrusionJunction Simplify::createIntersection(const ExtrusionJunction& before, const Point intersection, const ExtrusionJunction& after) const +ExtrusionJunction Simplify::createIntersection(const ExtrusionJunction& before, const Point2LL intersection, const ExtrusionJunction& after) const { // Average the extrusion width of the line. // More correct would be to see where along the line the intersection occurs with a projection or something. @@ -128,7 +128,7 @@ ExtrusionJunction Simplify::createIntersection(const ExtrusionJunction& before, return ExtrusionJunction(intersection, (before.w_ + after.w_) / 2, before.perimeter_index_); } -coord_t Simplify::getAreaDeviation(const Point& before, const Point& vertex, const Point& after) const +coord_t Simplify::getAreaDeviation(const Point2LL& before, const Point2LL& vertex, const Point2LL& after) const { return 0; // Fixed-width polygons don't have any deviation. } diff --git a/src/utils/SquareGrid.cpp b/src/utils/SquareGrid.cpp index 29d1d9fec8..4c66c49334 100644 --- a/src/utils/SquareGrid.cpp +++ b/src/utils/SquareGrid.cpp @@ -15,9 +15,9 @@ SquareGrid::SquareGrid(coord_t cell_size) } -SquareGrid::GridPoint SquareGrid::toGridPoint(const Point& point) const +SquareGrid::GridPoint SquareGrid::toGridPoint(const Point2LL& point) const { - return Point(toGridCoord(point.X), toGridCoord(point.Y)); + return Point2LL(toGridCoord(point.X), toGridCoord(point.Y)); } @@ -33,9 +33,9 @@ SquareGrid::grid_coord_t SquareGrid::toGridCoord(const coord_t& coord) const } -cura::Point SquareGrid::toLowerCorner(const GridPoint& location) const +cura::Point2LL SquareGrid::toLowerCorner(const GridPoint& location) const { - return cura::Point(toLowerCoord(location.X), toLowerCoord(location.Y)); + return cura::Point2LL(toLowerCoord(location.X), toLowerCoord(location.Y)); } @@ -51,16 +51,16 @@ cura::coord_t SquareGrid::toLowerCoord(const grid_coord_t& grid_coord) const } -bool SquareGrid::processLineCells(const std::pair line, const std::function& process_cell_func) +bool SquareGrid::processLineCells(const std::pair line, const std::function& process_cell_func) { return static_cast(this)->processLineCells(line, process_cell_func); } -bool SquareGrid::processLineCells(const std::pair line, const std::function& process_cell_func) const +bool SquareGrid::processLineCells(const std::pair line, const std::function& process_cell_func) const { - Point start = line.first; - Point end = line.second; + Point2LL start = line.first; + Point2LL end = line.second; if (end.X < start.X) { // make sure X increases between start and end std::swap(start, end); @@ -118,10 +118,10 @@ bool SquareGrid::processLineCells(const std::pair line, const std: return false; } -bool SquareGrid::processAxisAlignedTriangle(const Point from, const Point to, bool to_the_right, const std::function& process_cell_func) const +bool SquareGrid::processAxisAlignedTriangle(const Point2LL from, const Point2LL to, bool to_the_right, const std::function& process_cell_func) const { - Point a = from; - Point b = to; + Point2LL a = from; + Point2LL b = to; if ((a.X < b.X == a.Y < b.Y) != to_the_right) { std::swap(a, b); @@ -129,7 +129,7 @@ bool SquareGrid::processAxisAlignedTriangle(const Point from, const Point to, bo return processAxisAlignedTriangle(a, b, process_cell_func); } -bool SquareGrid::processAxisAlignedTriangle(const Point from, const Point to, const std::function& process_cell_func) const +bool SquareGrid::processAxisAlignedTriangle(const Point2LL from, const Point2LL to, const std::function& process_cell_func) const { GridPoint last; GridPoint grid_to = toGridPoint(to); @@ -160,10 +160,10 @@ bool SquareGrid::processAxisAlignedTriangle(const Point from, const Point to, co }); } -bool SquareGrid::processNearby(const Point& query_pt, coord_t radius, const std::function& process_func) const +bool SquareGrid::processNearby(const Point2LL& query_pt, coord_t radius, const std::function& process_func) const { - const Point min_loc(query_pt.X - radius, query_pt.Y - radius); - const Point max_loc(query_pt.X + radius, query_pt.Y + radius); + const Point2LL min_loc(query_pt.X - radius, query_pt.Y - radius); + const Point2LL max_loc(query_pt.X + radius, query_pt.Y + radius); GridPoint min_grid = toGridPoint(min_loc); GridPoint max_grid = toGridPoint(max_loc); diff --git a/src/utils/ToolpathVisualizer.cpp b/src/utils/ToolpathVisualizer.cpp index 22b3b489f3..34526f8dca 100644 --- a/src/utils/ToolpathVisualizer.cpp +++ b/src/utils/ToolpathVisualizer.cpp @@ -65,8 +65,8 @@ void ToolpathVisualizer::width_legend(const Polygons& input, coord_t nozzle_size return ss.str(); }; AABB aabb(input); - ExtrusionJunction legend_btm(Point(aabb.max_.X + nozzle_size + max_dev, aabb.max_.Y), nozzle_size - max_dev, 0); - ExtrusionJunction legend_top(Point(aabb.max_.X + nozzle_size + max_dev, aabb.min_.Y), nozzle_size + max_dev, 0); + ExtrusionJunction legend_btm(Point2LL(aabb.max_.X + nozzle_size + max_dev, aabb.max_.Y), nozzle_size - max_dev, 0); + ExtrusionJunction legend_top(Point2LL(aabb.max_.X + nozzle_size + max_dev, aabb.min_.Y), nozzle_size + max_dev, 0); ExtrusionJunction legend_mid((legend_top.p_ + legend_btm.p_) / 2, (legend_top.w_ + legend_btm.w_) / 2, 0); legend_btm.p_ += (legend_mid.p_ - legend_btm.p_) / 4; legend_top.p_ += (legend_mid.p_ - legend_top.p_) / 4; @@ -75,7 +75,7 @@ void ToolpathVisualizer::width_legend(const Polygons& input, coord_t nozzle_size std::vector all_segments_plus; all_segments_plus.emplace_back(legend_segment); // colored - Point legend_text_offset(nozzle_size, 0); + Point2LL legend_text_offset(nozzle_size, 0); svg_.writeText(legend_top.p_ + legend_text_offset, to_string(INT2MM(legend_top.w_))); svg_.writeText(legend_btm.p_ + legend_text_offset, to_string(INT2MM(legend_btm.w_))); svg_.writeText(legend_mid.p_ + legend_text_offset, to_string(INT2MM(legend_mid.w_))); @@ -95,9 +95,9 @@ void ToolpathVisualizer::widths( bool exaggerate_widths) { // Point3 middle = rounded_visualization? Point3(255,255,255) : Point3(192,192,192); - Point3 middle(255, 255, 255); - Point3 wide(255, 0, 0); - Point3 narrow(0, 0, 255); + Point3LL middle(255, 255, 255); + Point3LL wide(255, 0, 0); + Point3LL narrow(0, 0, 255); // Polygons connecteds = PolygonUtils::connect(area_covered); // for (PolygonRef connected : connecteds) @@ -114,7 +114,7 @@ void ToolpathVisualizer::widths( for (ExtrusionSegment s : ss.discretize(MM2INT(0.1))) { coord_t avg_w = (s.from_.w_ + s.to_.w_) / 2; - Point3 clr; + Point3LL clr; double color_ratio = std::min(1.0, double(std::abs(avg_w - nozzle_size)) / max_dev); color_ratio = color_ratio * .5 + .5 * sqrt(color_ratio); if (avg_w > nozzle_size) diff --git a/src/utils/VoronoiUtils.cpp b/src/utils/VoronoiUtils.cpp index fa1d5dc6e5..564a48e99b 100644 --- a/src/utils/VoronoiUtils.cpp +++ b/src/utils/VoronoiUtils.cpp @@ -14,14 +14,14 @@ namespace cura { -Point VoronoiUtils::p(const vd_t::vertex_type* node) +Point2LL VoronoiUtils::p(const vd_t::vertex_type* node) { const double x = node->x(); const double y = node->y(); - return Point(x + 0.5 - (x < 0), y + 0.5 - (y < 0)); // Round to nearest integer coordinates. + return Point2LL(x + 0.5 - (x < 0), y + 0.5 - (y < 0)); // Round to nearest integer coordinates. } -bool VoronoiUtils::isSourcePoint(Point p, const vd_t::cell_type& cell, const std::vector& points, const std::vector& segments, coord_t snap_dist) +bool VoronoiUtils::isSourcePoint(Point2LL p, const vd_t::cell_type& cell, const std::vector& points, const std::vector& segments, coord_t snap_dist) { if (cell.contains_point()) { @@ -34,7 +34,7 @@ bool VoronoiUtils::isSourcePoint(Point p, const vd_t::cell_type& cell, const std } } -coord_t VoronoiUtils::getDistance(Point p, const vd_t::cell_type& cell, const std::vector& points, const std::vector& segments) +coord_t VoronoiUtils::getDistance(Point2LL p, const vd_t::cell_type& cell, const std::vector& points, const std::vector& segments) { if (cell.contains_point()) { @@ -47,7 +47,7 @@ coord_t VoronoiUtils::getDistance(Point p, const vd_t::cell_type& cell, const st } } -Point VoronoiUtils::getSourcePoint(const vd_t::cell_type& cell, const std::vector& points, const std::vector& segments) +Point2LL VoronoiUtils::getSourcePoint(const vd_t::cell_type& cell, const std::vector& points, const std::vector& segments) { assert(cell.contains_point()); if (! cell.contains_point()) @@ -74,7 +74,7 @@ Point VoronoiUtils::getSourcePoint(const vd_t::cell_type& cell, const std::vecto return points[cell.source_index()]; } -PolygonsPointIndex VoronoiUtils::getSourcePointIndex(const vd_t::cell_type& cell, const std::vector& points, const std::vector& segments) +PolygonsPointIndex VoronoiUtils::getSourcePointIndex(const vd_t::cell_type& cell, const std::vector& points, const std::vector& segments) { assert(cell.contains_point()); if (! cell.contains_point()) @@ -106,7 +106,7 @@ PolygonsPointIndex VoronoiUtils::getSourcePointIndex(const vd_t::cell_type& cell return ++ret; } -const VoronoiUtils::Segment& VoronoiUtils::getSourceSegment(const vd_t::cell_type& cell, const std::vector& points, const std::vector& segments) +const VoronoiUtils::Segment& VoronoiUtils::getSourceSegment(const vd_t::cell_type& cell, const std::vector& points, const std::vector& segments) { assert(cell.contains_segment()); if (! cell.contains_segment()) @@ -117,26 +117,26 @@ const VoronoiUtils::Segment& VoronoiUtils::getSourceSegment(const vd_t::cell_typ } -std::vector VoronoiUtils::discretizeParabola(const Point& p, const Segment& segment, Point s, Point e, coord_t approximate_step_size, double transitioning_angle) +std::vector VoronoiUtils::discretizeParabola(const Point2LL& p, const Segment& segment, Point2LL s, Point2LL e, coord_t approximate_step_size, double transitioning_angle) { - std::vector discretized; + std::vector discretized; // x is distance of point projected on the segment ab // xx is point projected on the segment ab - const Point a = segment.from(); - const Point b = segment.to(); - const Point ab = b - a; - const Point as = s - a; - const Point ae = e - a; + const Point2LL a = segment.from(); + const Point2LL b = segment.to(); + const Point2LL ab = b - a; + const Point2LL as = s - a; + const Point2LL ae = e - a; const coord_t ab_size = vSize(ab); const coord_t sx = dot(as, ab) / ab_size; const coord_t ex = dot(ae, ab) / ab_size; const coord_t sxex = ex - sx; - const Point ap = p - a; + const Point2LL ap = p - a; const coord_t px = dot(ap, ab) / ab_size; - const Point pxx = LinearAlg2D::getClosestOnLine(p, a, b); - const Point ppxx = pxx - p; + const Point2LL pxx = LinearAlg2D::getClosestOnLine(p, a, b); + const Point2LL ppxx = pxx - p; const coord_t d = vSize(ppxx); const PointMatrix rot = PointMatrix(turn90CCW(ppxx)); @@ -151,8 +151,8 @@ std::vector VoronoiUtils::discretizeParabola(const Point& p, const Segmen coord_t msx = -marking_bound * d; // projected marking_start coord_t mex = marking_bound * d; // projected marking_end const coord_t marking_start_end_h = msx * msx / (2 * d) + d / 2; - Point marking_start = rot.unapply(Point(msx, marking_start_end_h)) + pxx; - Point marking_end = rot.unapply(Point(mex, marking_start_end_h)) + pxx; + Point2LL marking_start = rot.unapply(Point2LL(msx, marking_start_end_h)) + pxx; + Point2LL marking_end = rot.unapply(Point2LL(mex, marking_start_end_h)) + pxx; const int dir = (sx > ex) ? -1 : 1; if (dir < 0) { @@ -163,7 +163,7 @@ std::vector VoronoiUtils::discretizeParabola(const Point& p, const Segmen bool add_marking_start = msx * dir > (sx - px) * dir && msx * dir < (ex - px) * dir; bool add_marking_end = mex * dir > (sx - px) * dir && mex * dir < (ex - px) * dir; - const Point apex = rot.unapply(Point(0, d / 2)) + pxx; + const Point2LL apex = rot.unapply(Point2LL(0, d / 2)) + pxx; // Only at the apex point if the projected start and end points // are more than 10 microns away from the projected apex bool add_apex = (sx - px) * dir < -10 && (ex - px) * dir > 10; @@ -197,7 +197,7 @@ std::vector VoronoiUtils::discretizeParabola(const Point& p, const Segmen discretized.emplace_back(marking_end); add_marking_end = false; } - const Point result = rot.unapply(Point(x, y)) + pxx; + const Point2LL result = rot.unapply(Point2LL(x, y)) + pxx; discretized.emplace_back(result); } if (add_apex) @@ -241,12 +241,12 @@ DEALINGS IN THE SOFTWARE. */ // adapted from boost::polygon::voronoi_visual_utils.cpp -void VoronoiUtils::discretize(const Point& point, const Segment& segment, const coord_t max_dist, std::vector* discretization) +void VoronoiUtils::discretize(const Point2LL& point, const Segment& segment, const coord_t max_dist, std::vector* discretization) { // Apply the linear transformation to move start point of the segment to // the point with coordinates (0, 0) and the direction of the segment to // coincide the positive direction of the x-axis. - const Point segm_vec = segment.to() - segment.from(); + const Point2LL segm_vec = segment.to() - segment.from(); const coord_t segment_length2 = vSize2(segm_vec); // Compute x-coordinates of the endpoints of the edge @@ -257,31 +257,31 @@ void VoronoiUtils::discretize(const Point& point, const Segment& segment, const // Compute parabola parameters in the transformed space. // Parabola has next representation: // f(x) = ((x-rot_x)^2 + rot_y^2) / (2.0*rot_y). - const Point point_vec = point - segment.from(); + const Point2LL point_vec = point - segment.from(); const coord_t rot_x = dot(segm_vec, point_vec); const coord_t rot_y = cross(segm_vec, point_vec); // Save the last point. - const Point last_point = (*discretization)[1]; + const Point2LL last_point = (*discretization)[1]; discretization->pop_back(); // Use stack to avoid recursion. std::stack point_stack; point_stack.push(projection_end); - Point cur(projection_start, parabolaY(projection_start, rot_x, rot_y)); + Point2LL cur(projection_start, parabolaY(projection_start, rot_x, rot_y)); // Adjust max_dist parameter in the transformed space. const coord_t max_dist_transformed = max_dist * max_dist * segment_length2; while (! point_stack.empty()) { - const Point new_(point_stack.top(), parabolaY(point_stack.top(), rot_x, rot_y)); - const Point new_vec = new_ - cur; + const Point2LL new_(point_stack.top(), parabolaY(point_stack.top(), rot_x, rot_y)); + const Point2LL new_vec = new_ - cur; // Compute coordinates of the point of the parabola that is // furthest from the current line segment. const coord_t mid_x = new_vec.Y * rot_y / new_vec.X + rot_x; const coord_t mid_y = parabolaY(mid_x, rot_x, rot_y); - Point mid_vec = Point(mid_x, mid_y) - cur; + Point2LL mid_vec = Point2LL(mid_x, mid_y) - cur; // Compute maximum distance between the given parabolic arc // and line segment that discretize it. @@ -293,7 +293,7 @@ void VoronoiUtils::discretize(const Point& point, const Segment& segment, const point_stack.pop(); const coord_t inter_x = (segm_vec.X * new_.X - segm_vec.Y * new_.Y) / segment_length2 + segment.from().X; const coord_t inter_y = (segm_vec.X * new_.Y + segm_vec.Y * new_.X) / segment_length2 + segment.from().Y; - discretization->push_back(Point(inter_x, inter_y)); + discretization->push_back(Point2LL(inter_x, inter_y)); cur = new_; } else @@ -313,10 +313,10 @@ coord_t VoronoiUtils::parabolaY(coord_t x, coord_t a, coord_t b) } // adapted from boost::polygon::voronoi_visual_utils.cpp -double VoronoiUtils::getPointProjection(const Point& point, const Segment& segment) +double VoronoiUtils::getPointProjection(const Point2LL& point, const Segment& segment) { - Point segment_vec = segment.to() - segment.from(); - Point point_vec = point - segment.from(); + Point2LL segment_vec = segment.to() - segment.from(); + Point2LL point_vec = point - segment.from(); coord_t sqr_segment_length = vSize2(segment_vec); coord_t vec_dot = dot(segment_vec, point_vec); return static_cast(vec_dot) / sqr_segment_length; diff --git a/src/utils/VoxelUtils.cpp b/src/utils/VoxelUtils.cpp index 31ecf2bf4c..b55f40c0ce 100644 --- a/src/utils/VoxelUtils.cpp +++ b/src/utils/VoxelUtils.cpp @@ -46,9 +46,9 @@ DilationKernel::DilationKernel(GridPoint3 kernel_size, DilationKernel::Type type } } -bool VoxelUtils::walkLine(Point3 start, Point3 end, const std::function& process_cell_func) const +bool VoxelUtils::walkLine(Point3LL start, Point3LL end, const std::function& process_cell_func) const { - Point3 diff = end - start; + Point3LL diff = end - start; const GridPoint3 start_cell = toGridPoint(start); const GridPoint3 end_cell = toGridPoint(end); @@ -57,7 +57,7 @@ bool VoxelUtils::walkLine(Point3 start, Point3 end, const std::function& process_cell_func) const { Polygons translated = polys; - const Point3 translation = (Point3(1, 1, 1) - kernel.kernel_size_ % 2) * cell_size_ / 2; + const Point3LL translation = (Point3LL(1, 1, 1) - kernel.kernel_size_ % 2) * cell_size_ / 2; if (translation.x_ && translation.y_) { - translated.translate(Point(translation.x_, translation.y_)); + translated.translate(Point2LL(translation.x_, translation.y_)); } return walkPolygons(translated, z + translation.z_, dilate(kernel, process_cell_func)); } @@ -127,20 +127,20 @@ bool VoxelUtils::walkDilatedPolygons(const Polygons& polys, coord_t z, const Dil bool VoxelUtils::walkAreas(const Polygons& polys, coord_t z, const std::function& process_cell_func) const { Polygons translated = polys; - const Point3 translation = -cell_size_ / 2; // offset half a cell so that the dots of spreadDotsArea are centered on the middle of the cell isntead of the lower corners. + const Point3LL translation = -cell_size_ / 2; // offset half a cell so that the dots of spreadDotsArea are centered on the middle of the cell isntead of the lower corners. if (translation.x_ && translation.y_) { - translated.translate(Point(translation.x_, translation.y_)); + translated.translate(Point2LL(translation.x_, translation.y_)); } return _walkAreas(translated, z, process_cell_func); } bool VoxelUtils::_walkAreas(const Polygons& polys, coord_t z, const std::function& process_cell_func) const { - std::vector skin_points = PolygonUtils::spreadDotsArea(polys, Point(cell_size_.x_, cell_size_.y_)); - for (Point p : skin_points) + std::vector skin_points = PolygonUtils::spreadDotsArea(polys, Point2LL(cell_size_.x_, cell_size_.y_)); + for (Point2LL p : skin_points) { - bool continue_ = process_cell_func(toGridPoint(Point3(p.X + cell_size_.x_ / 2, p.Y + cell_size_.y_ / 2, z))); + bool continue_ = process_cell_func(toGridPoint(Point3LL(p.X + cell_size_.x_ / 2, p.Y + cell_size_.y_ / 2, z))); if (! continue_) { return false; @@ -152,11 +152,11 @@ bool VoxelUtils::_walkAreas(const Polygons& polys, coord_t z, const std::functio bool VoxelUtils::walkDilatedAreas(const Polygons& polys, coord_t z, const DilationKernel& kernel, const std::function& process_cell_func) const { Polygons translated = polys; - const Point3 translation = (Point3(1, 1, 1) - kernel.kernel_size_ % 2) * cell_size_ / 2 // offset half a cell when using a n even kernel + const Point3LL translation = (Point3LL(1, 1, 1) - kernel.kernel_size_ % 2) * cell_size_ / 2 // offset half a cell when using a n even kernel - cell_size_ / 2; // offset half a cell so that the dots of spreadDotsArea are centered on the middle of the cell isntead of the lower corners. if (translation.x_ && translation.y_) { - translated.translate(Point(translation.x_, translation.y_)); + translated.translate(Point2LL(translation.x_, translation.y_)); } return _walkAreas(translated, z + translation.z_, dilate(kernel, process_cell_func)); } diff --git a/src/utils/polygon.cpp b/src/utils/polygon.cpp index d289a606ad..52708890ab 100644 --- a/src/utils/polygon.cpp +++ b/src/utils/polygon.cpp @@ -32,7 +32,7 @@ bool ConstPolygonRef::shorterThan(const coord_t check_length) const return cura::shorterThan(*this, check_length); } -bool ConstPolygonRef::_inside(Point p, bool border_result) const +bool ConstPolygonRef::_inside(Point2LL p, bool border_result) const { const ConstPolygonRef thiss = *this; if (size() < 1) @@ -41,10 +41,10 @@ bool ConstPolygonRef::_inside(Point p, bool border_result) const } int crossings = 0; - Point p0 = back(); + Point2LL p0 = back(); for (unsigned int n = 0; n < size(); n++) { - Point p1 = thiss[n]; + Point2LL p1 = thiss[n]; // no tests unless the segment p0-p1 is at least partly at, or to right of, p.X short comp = LinearAlg2D::pointLiesOnTheRightOfLine(p, p0, p1); if (comp == 1) @@ -110,7 +110,7 @@ void Polygons::makeConvex() const size_t start_index = std::min_element( poly.begin(), poly.end(), - [](Point a, Point b) + [](Point2LL a, Point2LL b) { return a.X == b.X ? a.Y < b.Y : a.X < b.X; }) @@ -119,7 +119,7 @@ void Polygons::makeConvex() for (size_t i = 1; i <= poly.size(); ++i) { - const Point& current = poly[(start_index + i) % poly.size()]; + const Point2LL& current = poly[(start_index + i) % poly.size()]; // Track backwards to make sure we haven't been in a concave pocket for multiple vertices already. while (convexified.size() >= 2 @@ -147,7 +147,7 @@ unsigned int Polygons::pointCount() const return count; } -bool Polygons::inside(Point p, bool border_result) const +bool Polygons::inside(Point2LL p, bool border_result) const { int poly_count_inside = 0; for (const ClipperLib::Path& poly : *this) @@ -162,7 +162,7 @@ bool Polygons::inside(Point p, bool border_result) const return (poly_count_inside % 2) == 1; } -bool PolygonsPart::inside(Point p, bool border_result) const +bool PolygonsPart::inside(Point2LL p, bool border_result) const { if (size() < 1) { @@ -182,7 +182,7 @@ bool PolygonsPart::inside(Point p, bool border_result) const return true; } -bool Polygons::insideOld(Point p, bool border_result) const +bool Polygons::insideOld(Point2LL p, bool border_result) const { const Polygons& thiss = *this; if (size() < 1) @@ -193,8 +193,8 @@ bool Polygons::insideOld(Point p, bool border_result) const int crossings = 0; for (const ClipperLib::Path& poly : thiss) { - Point p0 = poly.back(); - for (const Point& p1 : poly) + Point2LL p0 = poly.back(); + for (const Point2LL& p1 : poly) { short comp = LinearAlg2D::pointLiesOnTheRightOfLine(p, p0, p1); if (comp == 1) @@ -211,7 +211,7 @@ bool Polygons::insideOld(Point p, bool border_result) const return (crossings % 2) == 1; } -unsigned int Polygons::findInside(Point p, bool border_result) +unsigned int Polygons::findInside(Point2LL p, bool border_result) { Polygons& thiss = *this; if (size() < 1) @@ -226,8 +226,8 @@ unsigned int Polygons::findInside(Point p, bool border_result) for (unsigned int poly_idx = 0; poly_idx < size(); poly_idx++) { PolygonRef poly = thiss[poly_idx]; - Point p0 = poly.back(); - for (Point& p1 : poly) + Point2LL p0 = poly.back(); + for (Point2LL& p1 : poly) { short comp = LinearAlg2D::pointLiesOnTheRightOfLine(p, p0, p1); if (comp == 1) @@ -293,7 +293,7 @@ Polygons Polygons::intersectionPolyLines(const Polygons& polylines, bool restitc { Polygons result_lines, result_polygons; const coord_t snap_distance = 10_mu; - PolylineStitcher::stitch(ret, result_lines, result_polygons, max_stitch_distance, snap_distance); + PolylineStitcher::stitch(ret, result_lines, result_polygons, max_stitch_distance, snap_distance); ret = result_lines; // if polylines got stitched into polygons, split them back up into a polyline again, because the result only admits polylines for (PolygonRef poly : result_polygons) @@ -481,9 +481,9 @@ void PolygonRef::removeColinearEdges(const AngleRadians max_deviation_angle) break; } - const Point& prev = rpath[(point_idx - 1 + pathlen) % pathlen]; - const Point& pt = rpath[point_idx]; - const Point& next = rpath[(point_idx + 1) % pathlen]; + const Point2LL& prev = rpath[(point_idx - 1 + pathlen) % pathlen]; + const Point2LL& pt = rpath[point_idx]; + const Point2LL& next = rpath[(point_idx + 1) % pathlen]; double angle = LinearAlg2D::getAngleLeft(prev, pt, next); // [0 : 2 * pi] if (angle >= std::numbers::pi) @@ -721,10 +721,10 @@ void Polygons::_removeDegenerateVerts(const bool for_polyline) PolygonRef poly = thiss[poly_idx]; Polygon result; - auto isDegenerate = [](const Point& last, const Point& now, const Point& next) + auto isDegenerate = [](const Point2LL& last, const Point2LL& now, const Point2LL& next) { - Point last_line = now - last; - Point next_line = next - now; + Point2LL last_line = now - last; + Point2LL next_line = next - now; return dot(last_line, next_line) == -1 * vSize(last_line) * vSize(next_line); }; @@ -739,12 +739,12 @@ void Polygons::_removeDegenerateVerts(const bool for_polyline) bool isChanged = false; for (size_t idx = start_vertex; idx < end_vertex; idx++) { - const Point& last = (result.size() == 0) ? poly.back() : result.back(); + const Point2LL& last = (result.size() == 0) ? poly.back() : result.back(); if (idx + 1 >= poly.size() && result.size() == 0) { break; } - const Point& next = (idx + 1 >= poly.size()) ? result[0] : poly[idx + 1]; + const Point2LL& next = (idx + 1 >= poly.size()) ? result[0] : poly[idx + 1]; if (isDegenerate(last, poly[idx], next)) { // lines are in the opposite direction // don't add vert to the result @@ -787,7 +787,7 @@ Polygons Polygons::toPolygons(ClipperLib::PolyTree& poly_tree) return ret; } -bool ConstPolygonRef::smooth_corner_complex(const Point p1, ListPolyIt& p0_it, ListPolyIt& p2_it, const int64_t shortcut_length) +bool ConstPolygonRef::smooth_corner_complex(const Point2LL p1, ListPolyIt& p0_it, ListPolyIt& p2_it, const int64_t shortcut_length) { // walk away from the corner until the shortcut > shortcut_length or it would smooth a piece inward // - walk in both directions untill shortcut > shortcut_length @@ -855,7 +855,7 @@ bool ConstPolygonRef::smooth_corner_complex(const Point p1, ListPolyIt& p0_it, L } } - const Point v02 = p2_it.p() - p0_it.p(); + const Point2LL v02 = p2_it.p() - p0_it.p(); const int64_t v02_size2 = vSize2(v02); // set the following: // p0_it = start point of line @@ -879,16 +879,16 @@ bool ConstPolygonRef::smooth_corner_complex(const Point p1, ListPolyIt& p0_it, L const ListPolyIt p0_2_it = p0_it.prev(); const ListPolyIt p2_2_it = p2_it.next(); - const Point p2_2 = p2_2_it.p(); - const Point p0_2 = p0_2_it.p(); - const Point v02_2 = p0_2 - p2_2; + const Point2LL p2_2 = p2_2_it.p(); + const Point2LL p0_2 = p0_2_it.p(); + const Point2LL v02_2 = p0_2 - p2_2; const int64_t v02_2_size = vSize(v02_2); double progress = std::min(1.0, INT2MM(shortcut_length - v02_size) / INT2MM(v02_2_size - v02_size)); // account for rounding error when v02_2_size is approx equal to v02_size assert(progress >= 0.0f && progress <= 1.0f && "shortcut length must be between last length and new length"); - const Point new_p0 = p0_it.p() + (p0_2 - p0_it.p()) * progress; + const Point2LL new_p0 = p0_it.p() + (p0_2 - p0_it.p()) * progress; p0_it = ListPolyIt::insertPointNonDuplicate(p0_2_it, p0_it, new_p0); - const Point new_p2 = p2_it.p() + (p2_2 - p2_it.p()) * progress; + const Point2LL new_p2 = p2_it.p() + (p2_2 - p2_it.p()) * progress; p2_it = ListPolyIt::insertPointNonDuplicate(p2_it, p2_2_it, new_p2); } else if (! backward_is_blocked) @@ -903,10 +903,10 @@ bool ConstPolygonRef::smooth_corner_complex(const Point p1, ListPolyIt& p0_it, L // | // 0_2 const ListPolyIt p0_2_it = p0_it.prev(); - const Point p0 = p0_it.p(); - const Point p0_2 = p0_2_it.p(); - const Point p2 = p2_it.p(); - Point new_p0; + const Point2LL p0 = p0_it.p(); + const Point2LL p0_2 = p0_2_it.p(); + const Point2LL p2 = p2_it.p(); + Point2LL new_p0; bool success = LinearAlg2D::getPointOnLineWithDist(p2, p0, p0_2, shortcut_length, new_p0); // shortcut length must be possible given that last length was ok and new length is too long if (success) @@ -932,10 +932,10 @@ bool ConstPolygonRef::smooth_corner_complex(const Point p1, ListPolyIt& p0_it, L //--0.-' // a const ListPolyIt p2_2_it = p2_it.next(); - const Point p0 = p0_it.p(); - const Point p2 = p2_it.p(); - const Point p2_2 = p2_2_it.p(); - Point new_p2; + const Point2LL p0 = p0_it.p(); + const Point2LL p2 = p2_it.p(); + const Point2LL p2_2 = p2_2_it.p(); + Point2LL new_p2; bool success = LinearAlg2D::getPointOnLineWithDist(p0, p2, p2_2, shortcut_length, new_p2); // shortcut length must be possible given that last length was ok and new length is too long if (success) @@ -971,7 +971,7 @@ bool ConstPolygonRef::smooth_corner_complex(const Point p1, ListPolyIt& p0_it, L } void ConstPolygonRef::smooth_outward_step( - const Point p1, + const Point2LL p1, const int64_t shortcut_length2, ListPolyIt& p0_it, ListPolyIt& p2_it, @@ -982,15 +982,15 @@ void ConstPolygonRef::smooth_outward_step( { const bool forward_has_converged = forward_is_blocked || forward_is_too_far; const bool backward_has_converged = backward_is_blocked || backward_is_too_far; - const Point p0 = p0_it.p(); - const Point p2 = p2_it.p(); + const Point2LL p0 = p0_it.p(); + const Point2LL p2 = p2_it.p(); bool walk_forward = ! forward_has_converged && (backward_has_converged || (vSize2(p2 - p1) < vSize2(p0 - p1))); // whether to walk along the p1-p2 direction or in the p1-p0 direction if (walk_forward) { const ListPolyIt p2_2_it = p2_it.next(); - const Point p2_2 = p2_2_it.p(); + const Point2LL p2_2 = p2_2_it.p(); bool p2_is_left = LinearAlg2D::pointIsLeftOfLine(p2, p0, p2_2) >= 0; if (! p2_is_left) { @@ -998,7 +998,7 @@ void ConstPolygonRef::smooth_outward_step( return; } - const Point v02_2 = p2_2 - p0_it.p(); + const Point2LL v02_2 = p2_2 - p0_it.p(); if (vSize2(v02_2) > shortcut_length2) { forward_is_too_far = true; @@ -1013,7 +1013,7 @@ void ConstPolygonRef::smooth_outward_step( else { const ListPolyIt p0_2_it = p0_it.prev(); - const Point p0_2 = p0_2_it.p(); + const Point2LL p0_2 = p0_2_it.p(); bool p0_is_left = LinearAlg2D::pointIsLeftOfLine(p0, p0_2, p2) >= 0; if (! p0_is_left) { @@ -1021,7 +1021,7 @@ void ConstPolygonRef::smooth_outward_step( return; } - const Point v02_2 = p2_it.p() - p0_2; + const Point2LL v02_2 = p2_it.p() - p0_2; if (vSize2(v02_2) > shortcut_length2) { backward_is_too_far = true; @@ -1036,15 +1036,15 @@ void ConstPolygonRef::smooth_outward_step( } void ConstPolygonRef::smooth_corner_simple( - const Point p0, - const Point p1, - const Point p2, + const Point2LL p0, + const Point2LL p1, + const Point2LL p2, const ListPolyIt p0_it, const ListPolyIt p1_it, const ListPolyIt p2_it, - const Point v10, - const Point v12, - const Point v02, + const Point2LL v10, + const Point2LL v12, + const Point2LL v02, const int64_t shortcut_length, double cos_angle) { @@ -1079,8 +1079,8 @@ void ConstPolygonRef::smooth_corner_simple( const int64_t a1_size = shortcut_length / 2 / sin(a1m_angle); if (a1_size * a1_size < vSize2(v10) && a1_size * a1_size < vSize2(v12)) { - Point a = p1 + normal(v10, a1_size); - Point b = p1 + normal(v12, a1_size); + Point2LL a = p1 + normal(v10, a1_size); + Point2LL b = p1 + normal(v12, a1_size); #ifdef ASSERT_INSANE_OUTPUT assert(vSize(a) < 4000000); assert(vSize(b) < 4000000); @@ -1100,8 +1100,8 @@ void ConstPolygonRef::smooth_corner_simple( // |a // | // 0 - const Point& b = p2_it.p(); - Point a; + const Point2LL& b = p2_it.p(); + Point2LL a; bool success = LinearAlg2D::getPointOnLineWithDist(b, p1, p0, shortcut_length, a); // v02 has to be longer than ab! if (success) @@ -1120,8 +1120,8 @@ void ConstPolygonRef::smooth_corner_simple( // | ,-' // 0.-' // a - const Point& a = p0_it.p(); - Point b; + const Point2LL& a = p0_it.p(); + Point2LL b; bool success = LinearAlg2D::getPointOnLineWithDist(a, p1, p2, shortcut_length, b); // v02 has to be longer than ab! if (success) @@ -1176,20 +1176,20 @@ void ConstPolygonRef::smooth_outward(const AngleDegrees min_angle, int shortcut_ ListPolyIt p1_it(poly, poly.begin()); do { - const Point p1 = p1_it.p(); + const Point2LL p1 = p1_it.p(); ListPolyIt p0_it = p1_it.prev(); ListPolyIt p2_it = p1_it.next(); - const Point p0 = p0_it.p(); - const Point p2 = p2_it.p(); + const Point2LL p0 = p0_it.p(); + const Point2LL p2 = p2_it.p(); - const Point v10 = p0 - p1; - const Point v12 = p2 - p1; + const Point2LL v10 = p0 - p1; + const Point2LL v12 = p2 - p1; double cos_angle = INT2MM(INT2MM(dot(v10, v12))) / vSizeMM(v10) / vSizeMM(v12); bool is_left_angle = LinearAlg2D::pointIsLeftOfLine(p1, p0, p2) > 0; if (cos_angle > cos_min_angle && is_left_angle) { // angle is so sharp that it can be removed - Point v02 = p2_it.p() - p0_it.p(); + Point2LL v02 = p2_it.p() - p0_it.p(); if (vSize2(v02) >= shortcut_length2) { smooth_corner_simple(p0, p1, p2, p0_it, p1_it, p2_it, v10, v12, v02, shortcut_length, cos_angle); @@ -1242,10 +1242,10 @@ Polygons Polygons::smooth_outward(const AngleDegrees max_angle, int shortcut_len void ConstPolygonRef::splitPolylineIntoSegments(Polygons& result) const { - Point last = front(); + Point2LL last = front(); for (size_t idx = 1; idx < size(); idx++) { - Point p = (*this)[idx]; + Point2LL p = (*this)[idx]; result.addLine(last, p); last = p; } @@ -1318,25 +1318,25 @@ void ConstPolygonRef::smooth(int remove_length, PolygonRef result) const } return true; }; - Point v02 = thiss[2] - thiss[0]; - Point v02T = turn90CCW(v02); + Point2LL v02 = thiss[2] - thiss[0]; + Point2LL v02T = turn90CCW(v02); int64_t v02_size = vSize(v02); bool force_push = false; for (unsigned int poly_idx = 1; poly_idx < size(); poly_idx++) { - const Point& p1 = thiss[poly_idx]; - const Point& p2 = thiss[(poly_idx + 1) % size()]; - const Point& p3 = thiss[(poly_idx + 2) % size()]; + const Point2LL& p1 = thiss[poly_idx]; + const Point2LL& p2 = thiss[(poly_idx + 1) % size()]; + const Point2LL& p3 = thiss[(poly_idx + 2) % size()]; // v02 computed in last iteration // v02_size as well - const Point v12 = p2 - p1; + const Point2LL v12 = p2 - p1; const int64_t v12_size = vSize(v12); - const Point v13 = p3 - p1; + const Point2LL v13 = p3 - p1; const int64_t v13_size = vSize(v13); // v02T computed in last iteration const int64_t dot1 = dot(v02T, v12); - const Point v13T = turn90CCW(v13); + const Point2LL v13T = turn90CCW(v13); const int64_t dot2 = dot(v13T, v12); bool push_point = force_push || ! is_zigzag(v02_size, v12_size, v13_size, dot1, dot2); force_push = false; @@ -1390,9 +1390,9 @@ void ConstPolygonRef::smooth2(int remove_length, PolygonRef result) const } for (unsigned int poly_idx = 1; poly_idx < thiss.size(); poly_idx++) { - const Point& last = thiss[poly_idx - 1]; - const Point& now = thiss[poly_idx]; - const Point& next = thiss[(poly_idx + 1) % thiss.size()]; + const Point2LL& last = thiss[poly_idx - 1]; + const Point2LL& now = thiss[poly_idx]; + const Point2LL& next = thiss[(poly_idx + 1) % thiss.size()]; if (shorterThen(last - now, remove_length) && shorterThen(now - next, remove_length)) { poly_idx++; // skip the next line piece (dont escalate the removal of edges) @@ -1595,14 +1595,14 @@ void Polygons::splitIntoPartsView_processPolyTreeNode(PartsView& partsView, Poly void Polygons::ensureManifold() { const Polygons& polys = *this; - std::vector duplicate_locations; - std::unordered_set poly_locations; + std::vector duplicate_locations; + std::unordered_set poly_locations; for (size_t poly_idx = 0; poly_idx < polys.size(); poly_idx++) { ConstPolygonRef poly = polys[poly_idx]; for (size_t point_idx = 0; point_idx < poly.size(); point_idx++) { - Point p = poly[point_idx]; + Point2LL p = poly[point_idx]; if (poly_locations.find(p) != poly_locations.end()) { duplicate_locations.push_back(p); @@ -1611,13 +1611,13 @@ void Polygons::ensureManifold() } } Polygons removal_dots; - for (Point p : duplicate_locations) + for (Point2LL p : duplicate_locations) { PolygonRef dot = removal_dots.newPoly(); - dot.add(p + Point(0, 5)); - dot.add(p + Point(5, 0)); - dot.add(p + Point(0, -5)); - dot.add(p + Point(-5, 0)); + dot.add(p + Point2LL(0, 5)); + dot.add(p + Point2LL(5, 0)); + dot.add(p + Point2LL(0, -5)); + dot.add(p + Point2LL(-5, 0)); } if (! removal_dots.empty()) { diff --git a/src/utils/polygonUtils.cpp b/src/utils/polygonUtils.cpp index e314c1e5f9..42f9204a05 100644 --- a/src/utils/polygonUtils.cpp +++ b/src/utils/polygonUtils.cpp @@ -24,7 +24,7 @@ namespace cura { -const std::function PolygonUtils::no_penalty_function = [](Point) +const std::function PolygonUtils::no_penalty_function = [](Point2LL) { return 0; }; @@ -33,12 +33,12 @@ int64_t PolygonUtils::segmentLength(PolygonsPointIndex start, PolygonsPointIndex { assert(start.poly_idx_ == end.poly_idx_); int64_t segment_length = 0; - Point prev_vert = start.p(); + Point2LL prev_vert = start.p(); ConstPolygonRef poly = (*start.polygons_)[start.poly_idx_]; for (unsigned int point_idx = 1; point_idx <= poly.size(); point_idx++) { unsigned int vert_idx = (start.point_idx_ + point_idx) % poly.size(); - Point vert = poly[vert_idx]; + Point2LL vert = poly[vert_idx]; segment_length += vSize(vert - prev_vert); if (vert_idx == end.point_idx_) @@ -71,9 +71,9 @@ void PolygonUtils::spreadDots(PolygonsPointIndex start, PolygonsPointIndex end, PolygonsPointIndex vert = start; while (true) { - Point p0 = vert.p(); - Point p1 = vert.next().p(); - Point p0p1 = p1 - p0; + Point2LL p0 = vert.p(); + Point2LL p1 = vert.next().p(); + Point2LL p0p1 = p1 - p0; int64_t p0p1_length = vSize(p0p1); for (; dist_past_vert_to_insert_point < p0p1_length && n_points_generated < n_dots_in_between; dist_past_vert_to_insert_point += wipe_point_dist) @@ -92,12 +92,12 @@ void PolygonUtils::spreadDots(PolygonsPointIndex start, PolygonsPointIndex end, assert(result.size() == n_dots && "we didn't generate as many wipe locations as we asked for."); } -std::vector PolygonUtils::spreadDotsArea(const Polygons& polygons, coord_t grid_size) +std::vector PolygonUtils::spreadDotsArea(const Polygons& polygons, coord_t grid_size) { - return spreadDotsArea(polygons, Point(grid_size, grid_size)); + return spreadDotsArea(polygons, Point2LL(grid_size, grid_size)); } -std::vector PolygonUtils::spreadDotsArea(const Polygons& polygons, Point grid_size) +std::vector PolygonUtils::spreadDotsArea(const Polygons& polygons, Point2LL grid_size) { std::vector dummy_toolpaths; Settings dummy_settings; @@ -105,12 +105,12 @@ std::vector PolygonUtils::spreadDotsArea(const Polygons& polygons, Point Polygons result_polygons; Polygons result_lines; infill_gen.generate(dummy_toolpaths, result_polygons, result_lines, dummy_settings, 0, SectionType::DOTS); // FIXME: @jellespijker make sure the propper layer nr is used - std::vector result; + std::vector result; for (PolygonRef line : result_lines) { assert(line.size() == 2); - Point a = line[0]; - Point b = line[1]; + Point2LL a = line[0]; + Point2LL b = line[1]; assert(a.X == b.X); if (a.Y > b.Y) { @@ -127,19 +127,19 @@ std::vector PolygonUtils::spreadDotsArea(const Polygons& polygons, Point } bool PolygonUtils::lineSegmentPolygonsIntersection( - const Point& a, - const Point& b, + const Point2LL& a, + const Point2LL& b, const Polygons& current_outlines, const LocToLineGrid& outline_locator, - Point& result, + Point2LL& result, const coord_t within_max_dist) { const coord_t within_max_dist2 = within_max_dist * within_max_dist; - Point coll; + Point2LL coll; coord_t closest_dist2 = within_max_dist2; - const auto processOnIntersect = [&result, &closest_dist2, &a, &b, &coll](const Point& p_start, const Point& p_end) + const auto processOnIntersect = [&result, &closest_dist2, &a, &b, &coll](const Point2LL& p_start, const Point2LL& p_end) { if (LinearAlg2D::lineLineIntersection(a, b, p_start, p_end, coll) && LinearAlg2D::pointIsProjectedBeyondLine(coll, p_start, p_end) == 0 && LinearAlg2D::pointIsProjectedBeyondLine(coll, a, b) == 0) @@ -179,9 +179,9 @@ bool PolygonUtils::lineSegmentPolygonsIntersection( return closest_dist2 < within_max_dist2; } -Point PolygonUtils::getVertexInwardNormal(ConstPolygonRef poly, unsigned int point_idx) +Point2LL PolygonUtils::getVertexInwardNormal(ConstPolygonRef poly, unsigned int point_idx) { - Point p1 = poly[point_idx]; + Point2LL p1 = poly[point_idx]; int p0_idx; for (p0_idx = int(point_idx) - 1; (unsigned int)p0_idx != point_idx; p0_idx = p0_idx - 1) @@ -195,7 +195,7 @@ Point PolygonUtils::getVertexInwardNormal(ConstPolygonRef poly, unsigned int poi break; } } - Point p0 = poly[p0_idx]; + Point2LL p0 = poly[p0_idx]; unsigned int p2_idx; for (p2_idx = point_idx + 1; p2_idx != point_idx; p2_idx = p2_idx + 1) @@ -209,28 +209,28 @@ Point PolygonUtils::getVertexInwardNormal(ConstPolygonRef poly, unsigned int poi break; } } - const Point& p2 = poly[p2_idx]; + const Point2LL& p2 = poly[p2_idx]; - Point off0 = turn90CCW(normal(p1 - p0, MM2INT(10.0))); // 10.0 for some precision - Point off1 = turn90CCW(normal(p2 - p1, MM2INT(10.0))); // 10.0 for some precision - Point n = off0 + off1; + Point2LL off0 = turn90CCW(normal(p1 - p0, MM2INT(10.0))); // 10.0 for some precision + Point2LL off1 = turn90CCW(normal(p2 - p1, MM2INT(10.0))); // 10.0 for some precision + Point2LL n = off0 + off1; return n; } -Point PolygonUtils::getBoundaryPointWithOffset(ConstPolygonRef poly, unsigned int point_idx, int64_t offset) +Point2LL PolygonUtils::getBoundaryPointWithOffset(ConstPolygonRef poly, unsigned int point_idx, int64_t offset) { return poly[point_idx] + normal(getVertexInwardNormal(poly, point_idx), -offset); } -Point PolygonUtils::moveInsideDiagonally(ClosestPolygonPoint point_on_boundary, int64_t inset) +Point2LL PolygonUtils::moveInsideDiagonally(ClosestPolygonPoint point_on_boundary, int64_t inset) { if (! point_on_boundary.isValid()) { return no_point; } ConstPolygonRef poly = **point_on_boundary.poly_; - Point p0 = poly[point_on_boundary.point_idx_]; - Point p1 = poly[(point_on_boundary.point_idx_ + 1) % poly.size()]; + Point2LL p0 = poly[point_on_boundary.point_idx_]; + Point2LL p1 = poly[(point_on_boundary.point_idx_ + 1) % poly.size()]; if (vSize2(p0 - point_on_boundary.location_) < vSize2(p1 - point_on_boundary.location_)) { return point_on_boundary.location_ + normal(getVertexInwardNormal(poly, point_on_boundary.point_idx_), inset); @@ -241,19 +241,19 @@ Point PolygonUtils::moveInsideDiagonally(ClosestPolygonPoint point_on_boundary, } } -unsigned int PolygonUtils::moveOutside(const Polygons& polygons, Point& from, int distance, int64_t maxDist2) +unsigned int PolygonUtils::moveOutside(const Polygons& polygons, Point2LL& from, int distance, int64_t maxDist2) { return moveInside(polygons, from, -distance, maxDist2); } ClosestPolygonPoint PolygonUtils::moveInside2( const Polygons& polygons, - Point& from, + Point2LL& from, const int distance, const int64_t max_dist2, const Polygons* loc_to_line_polygons, const LocToLineGrid* loc_to_line_grid, - const std::function& penalty_function) + const std::function& penalty_function) { std::optional closest_polygon_point; if (loc_to_line_grid) @@ -270,11 +270,11 @@ ClosestPolygonPoint PolygonUtils::moveInside2( ClosestPolygonPoint PolygonUtils::moveInside2( const Polygons& loc_to_line_polygons, ConstPolygonRef polygon, - Point& from, + Point2LL& from, const int distance, const int64_t max_dist2, const LocToLineGrid* loc_to_line_grid, - const std::function& penalty_function) + const std::function& penalty_function) { std::optional closest_polygon_point; if (loc_to_line_grid) @@ -288,15 +288,15 @@ ClosestPolygonPoint PolygonUtils::moveInside2( return _moveInside2(*closest_polygon_point, distance, from, max_dist2); } -ClosestPolygonPoint PolygonUtils::_moveInside2(const ClosestPolygonPoint& closest_polygon_point, const int distance, Point& from, const int64_t max_dist2) +ClosestPolygonPoint PolygonUtils::_moveInside2(const ClosestPolygonPoint& closest_polygon_point, const int distance, Point2LL& from, const int64_t max_dist2) { if (! closest_polygon_point.isValid()) { return ClosestPolygonPoint(); // stub with invalid indices to signify we haven't found any } - const Point v_boundary_from = from - closest_polygon_point.location_; - Point result = moveInside(closest_polygon_point, distance); - const Point v_boundary_result = result - closest_polygon_point.location_; + const Point2LL v_boundary_from = from - closest_polygon_point.location_; + Point2LL result = moveInside(closest_polygon_point, distance); + const Point2LL v_boundary_result = result - closest_polygon_point.location_; if (dot(v_boundary_result, v_boundary_from) > 0) { // point was already on the correct side of the polygon if (vSize2(v_boundary_from) > distance * distance) @@ -327,9 +327,9 @@ ClosestPolygonPoint PolygonUtils::_moveInside2(const ClosestPolygonPoint& closes /* * Implementation assumes moving inside, but moving outside should just as well be possible. */ -unsigned int PolygonUtils::moveInside(const Polygons& polygons, Point& from, int distance, int64_t maxDist2) +unsigned int PolygonUtils::moveInside(const Polygons& polygons, Point2LL& from, int distance, int64_t maxDist2) { - Point ret = from; + Point2LL ret = from; int64_t bestDist2 = std::numeric_limits::max(); unsigned int bestPoly = NO_INDEX; bool is_already_on_correct_side_of_boundary = false; // whether [from] is already on the right side of the boundary @@ -338,21 +338,21 @@ unsigned int PolygonUtils::moveInside(const Polygons& polygons, Point& from, int ConstPolygonRef poly = polygons[poly_idx]; if (poly.size() < 2) continue; - Point p0 = poly[poly.size() - 2]; - Point p1 = poly.back(); + Point2LL p0 = poly[poly.size() - 2]; + Point2LL p1 = poly.back(); // because we compare with vSize2 here (no division by zero), we also need to compare by vSize2 inside the loop // to avoid integer rounding edge cases bool projected_p_beyond_prev_segment = dot(p1 - p0, from - p0) >= vSize2(p1 - p0); - for (const Point& p2 : poly) + for (const Point2LL& p2 : poly) { // X = A + Normal(B-A) * (((B-A) dot (P-A)) / VSize(B-A)); // = A + (B-A) * ((B-A) dot (P-A)) / VSize2(B-A); // X = P projected on AB - const Point& a = p1; - const Point& b = p2; - const Point& p = from; - Point ab = b - a; - Point ap = p - a; + const Point2LL& a = p1; + const Point2LL& b = p2; + const Point2LL& p = from; + Point2LL ab = b - a; + Point2LL ap = p - a; int64_t ab_length2 = vSize2(ab); if (ab_length2 <= 0) // A = B, i.e. the input polygon had two adjacent points on top of each other. { @@ -365,7 +365,7 @@ unsigned int PolygonUtils::moveInside(const Polygons& polygons, Point& from, int if (projected_p_beyond_prev_segment) { // case which looks like: > . projected_p_beyond_prev_segment = false; - Point& x = p1; + Point2LL& x = p1; int64_t dist2 = vSize2(x - p); if (dist2 < bestDist2) @@ -378,7 +378,7 @@ unsigned int PolygonUtils::moveInside(const Polygons& polygons, Point& from, int } else { - Point inward_dir = turn90CCW(normal(ab, MM2INT(10.0)) + normal(p1 - p0, MM2INT(10.0))); // inward direction irrespective of sign of [distance] + Point2LL inward_dir = turn90CCW(normal(ab, MM2INT(10.0)) + normal(p1 - p0, MM2INT(10.0))); // inward direction irrespective of sign of [distance] // MM2INT(10.0) to retain precision for the eventual normalization ret = x + normal(inward_dir, distance); is_already_on_correct_side_of_boundary = dot(inward_dir, p - x) * distance >= 0; @@ -403,7 +403,7 @@ unsigned int PolygonUtils::moveInside(const Polygons& polygons, Point& from, int else { // x is projected to a point properly on the line segment (not onto a vertex). The case which looks like | . projected_p_beyond_prev_segment = false; - Point x = a + ab * dot_prod / ab_length2; + Point2LL x = a + ab * dot_prod / ab_length2; int64_t dist2 = vSize2(p - x); if (dist2 < bestDist2) @@ -416,7 +416,7 @@ unsigned int PolygonUtils::moveInside(const Polygons& polygons, Point& from, int } else { - Point inward_dir = turn90CCW(normal(ab, distance)); // inward or outward depending on the sign of [distance] + Point2LL inward_dir = turn90CCW(normal(ab, distance)); // inward or outward depending on the sign of [distance] ret = x + inward_dir; is_already_on_correct_side_of_boundary = dot(inward_dir, p - x) >= 0; } @@ -447,7 +447,7 @@ unsigned int PolygonUtils::moveInside(const Polygons& polygons, Point& from, int } // Version that works on single PolygonRef. -unsigned int PolygonUtils::moveInside(const ConstPolygonRef polygon, Point& from, int distance, int64_t maxDist2) +unsigned int PolygonUtils::moveInside(const ConstPolygonRef polygon, Point2LL& from, int distance, int64_t maxDist2) { // TODO: This is copied from the moveInside of Polygons. /* @@ -456,7 +456,7 @@ unsigned int PolygonUtils::moveInside(const ConstPolygonRef polygon, Point& from is expensive. Or we need to return the distance. We need the distance there to compare with the distance to other polygons. */ - Point ret = from; + Point2LL ret = from; int64_t bestDist2 = std::numeric_limits::max(); bool is_already_on_correct_side_of_boundary = false; // whether [from] is already on the right side of the boundary @@ -464,21 +464,21 @@ unsigned int PolygonUtils::moveInside(const ConstPolygonRef polygon, Point& from { return 0; } - Point p0 = polygon[polygon.size() - 2]; - Point p1 = polygon.back(); + Point2LL p0 = polygon[polygon.size() - 2]; + Point2LL p1 = polygon.back(); // because we compare with vSize2 here (no division by zero), we also need to compare by vSize2 inside the loop // to avoid integer rounding edge cases bool projected_p_beyond_prev_segment = dot(p1 - p0, from - p0) >= vSize2(p1 - p0); - for (const Point& p2 : polygon) + for (const Point2LL& p2 : polygon) { // X = A + Normal(B-A) * (((B-A) dot (P-A)) / VSize(B-A)); // = A + (B-A) * ((B-A) dot (P-A)) / VSize2(B-A); // X = P projected on AB - const Point& a = p1; - const Point& b = p2; - const Point& p = from; - Point ab = b - a; - Point ap = p - a; + const Point2LL& a = p1; + const Point2LL& b = p2; + const Point2LL& p = from; + Point2LL ab = b - a; + Point2LL ap = p - a; int64_t ab_length2 = vSize2(ab); if (ab_length2 <= 0) // A = B, i.e. the input polygon had two adjacent points on top of each other. { @@ -491,7 +491,7 @@ unsigned int PolygonUtils::moveInside(const ConstPolygonRef polygon, Point& from if (projected_p_beyond_prev_segment) { // case which looks like: > . projected_p_beyond_prev_segment = false; - Point& x = p1; + Point2LL& x = p1; int64_t dist2 = vSize2(x - p); if (dist2 < bestDist2) @@ -503,7 +503,7 @@ unsigned int PolygonUtils::moveInside(const ConstPolygonRef polygon, Point& from } else { - Point inward_dir = turn90CCW(normal(ab, MM2INT(10.0)) + normal(p1 - p0, MM2INT(10.0))); // inward direction irrespective of sign of [distance] + Point2LL inward_dir = turn90CCW(normal(ab, MM2INT(10.0)) + normal(p1 - p0, MM2INT(10.0))); // inward direction irrespective of sign of [distance] // MM2INT(10.0) to retain precision for the eventual normalization ret = x + normal(inward_dir, distance); is_already_on_correct_side_of_boundary = dot(inward_dir, p - x) * distance >= 0; @@ -528,7 +528,7 @@ unsigned int PolygonUtils::moveInside(const ConstPolygonRef polygon, Point& from else { // x is projected to a point properly on the line segment (not onto a vertex). The case which looks like | . projected_p_beyond_prev_segment = false; - Point x = a + ab * dot_prod / ab_length2; + Point2LL x = a + ab * dot_prod / ab_length2; int64_t dist2 = vSize2(p - x); if (dist2 < bestDist2) @@ -540,7 +540,7 @@ unsigned int PolygonUtils::moveInside(const ConstPolygonRef polygon, Point& from } else { - Point inward_dir = turn90CCW(normal(ab, distance)); // inward or outward depending on the sign of [distance] + Point2LL inward_dir = turn90CCW(normal(ab, distance)); // inward or outward depending on the sign of [distance] ret = x + inward_dir; is_already_on_correct_side_of_boundary = dot(inward_dir, p - x) >= 0; } @@ -565,12 +565,12 @@ unsigned int PolygonUtils::moveInside(const ConstPolygonRef polygon, Point& from return 0; } -Point PolygonUtils::moveOutside(const ClosestPolygonPoint& cpp, const int distance) +Point2LL PolygonUtils::moveOutside(const ClosestPolygonPoint& cpp, const int distance) { return moveInside(cpp, -distance); } -Point PolygonUtils::moveInside(const ClosestPolygonPoint& cpp, const int distance) +Point2LL PolygonUtils::moveInside(const ClosestPolygonPoint& cpp, const int distance) { if (! cpp.isValid()) { @@ -582,9 +582,9 @@ Point PolygonUtils::moveInside(const ClosestPolygonPoint& cpp, const int distanc } ConstPolygonRef poly = *cpp.poly_; unsigned int point_idx = cpp.point_idx_; - const Point& on_boundary = cpp.location_; + const Point2LL& on_boundary = cpp.location_; - const Point& p1 = poly[point_idx]; + const Point2LL& p1 = poly[point_idx]; unsigned int p2_idx; for (p2_idx = point_idx + 1; p2_idx != point_idx; p2_idx = p2_idx + 1) { // find the next point different from p1 @@ -597,7 +597,7 @@ Point PolygonUtils::moveInside(const ClosestPolygonPoint& cpp, const int distanc break; } } - const Point& p2 = poly[p2_idx]; + const Point2LL& p2 = poly[p2_idx]; if (on_boundary == p1) { @@ -609,21 +609,21 @@ Point PolygonUtils::moveInside(const ClosestPolygonPoint& cpp, const int distanc } else { - const Point& x = on_boundary; // on_boundary is already projected on p1-p2 + const Point2LL& x = on_boundary; // on_boundary is already projected on p1-p2 - Point inward_dir = turn90CCW(normal(p2 - p1, distance)); + Point2LL inward_dir = turn90CCW(normal(p2 - p1, distance)); return x + inward_dir; } } ClosestPolygonPoint PolygonUtils::ensureInsideOrOutside( const Polygons& polygons, - Point& from, + Point2LL& from, int preferred_dist_inside, int64_t max_dist2, const Polygons* loc_to_line_polygons, const LocToLineGrid* loc_to_line_grid, - const std::function& penalty_function) + const std::function& penalty_function) { const ClosestPolygonPoint closest_polygon_point = moveInside2(polygons, from, preferred_dist_inside, max_dist2, loc_to_line_polygons, loc_to_line_grid, penalty_function); return ensureInsideOrOutside(polygons, from, closest_polygon_point, preferred_dist_inside, loc_to_line_polygons, loc_to_line_grid, penalty_function); @@ -631,12 +631,12 @@ ClosestPolygonPoint PolygonUtils::ensureInsideOrOutside( ClosestPolygonPoint PolygonUtils::ensureInsideOrOutside( const Polygons& polygons, - Point& from, + Point2LL& from, const ClosestPolygonPoint& closest_polygon_point, int preferred_dist_inside, const Polygons* loc_to_line_polygons, const LocToLineGrid* loc_to_line_grid, - const std::function& penalty_function) + const std::function& penalty_function) { if (! closest_polygon_point.isValid()) { @@ -783,7 +783,7 @@ void PolygonUtils::walkToNearestSmallestConnection(ClosestPolygonPoint& poly1_re auto check_neighboring_vert = [&best_distance2](ConstPolygonRef from_poly, ConstPolygonRef to_poly, ClosestPolygonPoint& from_poly_result, ClosestPolygonPoint& to_poly_result, bool vertex_after) { - const Point after_poly2_result = to_poly[(to_poly_result.point_idx_ + vertex_after) % to_poly.size()]; + const Point2LL after_poly2_result = to_poly[(to_poly_result.point_idx_ + vertex_after) % to_poly.size()]; const ClosestPolygonPoint poly1_after_poly2_result = findNearestClosest(after_poly2_result, from_poly, from_poly_result.point_idx_); const coord_t poly1_after_poly2_result_dist2 = vSize2(poly1_after_poly2_result.p() - after_poly2_result); if (poly1_after_poly2_result_dist2 < best_distance2) @@ -802,7 +802,7 @@ void PolygonUtils::walkToNearestSmallestConnection(ClosestPolygonPoint& poly1_re poly2_result.poly_idx_ = poly2_idx; } -ClosestPolygonPoint PolygonUtils::findNearestClosest(Point from, ConstPolygonRef polygon, int start_idx) +ClosestPolygonPoint PolygonUtils::findNearestClosest(Point2LL from, ConstPolygonRef polygon, int start_idx) { ClosestPolygonPoint forth = findNearestClosest(from, polygon, start_idx, 1); if (! forth.isValid()) @@ -821,14 +821,14 @@ ClosestPolygonPoint PolygonUtils::findNearestClosest(Point from, ConstPolygonRef } } -ClosestPolygonPoint PolygonUtils::findNearestClosest(Point from, ConstPolygonRef polygon, int start_idx, int direction) +ClosestPolygonPoint PolygonUtils::findNearestClosest(Point2LL from, ConstPolygonRef polygon, int start_idx, int direction) { if (polygon.size() == 0) { return ClosestPolygonPoint(polygon); } - Point aPoint = polygon[0]; - Point best = aPoint; + Point2LL aPoint = polygon[0]; + Point2LL best = aPoint; int64_t closestDist = vSize2(from - best); int bestPos = 0; @@ -838,10 +838,10 @@ ClosestPolygonPoint PolygonUtils::findNearestClosest(Point from, ConstPolygonRef { int p1_idx = (poly_size + direction * p + start_idx) % poly_size; int p2_idx = (poly_size + direction * (p + 1) + start_idx) % poly_size; - const Point& p1 = polygon[p1_idx]; - const Point& p2 = polygon[p2_idx]; + const Point2LL& p1 = polygon[p1_idx]; + const Point2LL& p2 = polygon[p2_idx]; - Point closest_here = LinearAlg2D::getClosestOnLineSegment(from, p1, p2); + Point2LL closest_here = LinearAlg2D::getClosestOnLineSegment(from, p1, p2); int64_t dist = vSize2(from - closest_here); if (dist < closestDist) { @@ -858,7 +858,7 @@ ClosestPolygonPoint PolygonUtils::findNearestClosest(Point from, ConstPolygonRef return ClosestPolygonPoint(best, bestPos, polygon); } -ClosestPolygonPoint PolygonUtils::findClosest(Point from, const Polygons& polygons, const std::function& penalty_function) +ClosestPolygonPoint PolygonUtils::findClosest(Point2LL from, const Polygons& polygons, const std::function& penalty_function) { ClosestPolygonPoint none; @@ -906,28 +906,28 @@ ClosestPolygonPoint PolygonUtils::findClosest(Point from, const Polygons& polygo return best; } -ClosestPolygonPoint PolygonUtils::findClosest(Point from, ConstPolygonRef polygon, const std::function& penalty_function) +ClosestPolygonPoint PolygonUtils::findClosest(Point2LL from, ConstPolygonRef polygon, const std::function& penalty_function) { if (polygon.size() == 0) { return ClosestPolygonPoint(polygon); } - Point aPoint = polygon[0]; - Point best = aPoint; + Point2LL aPoint = polygon[0]; + Point2LL best = aPoint; int64_t closestDist2_score = vSize2(from - best) + penalty_function(best); int bestPos = 0; for (unsigned int p = 0; p < polygon.size(); p++) { - const Point& p1 = polygon[p]; + const Point2LL& p1 = polygon[p]; unsigned int p2_idx = p + 1; if (p2_idx >= polygon.size()) p2_idx = 0; - const Point& p2 = polygon[p2_idx]; + const Point2LL& p2 = polygon[p2_idx]; - Point closest_here = LinearAlg2D::getClosestOnLineSegment(from, p1, p2); + Point2LL closest_here = LinearAlg2D::getClosestOnLineSegment(from, p1, p2); int64_t dist2_score = vSize2(from - closest_here) + penalty_function(closest_here); if (dist2_score < closestDist2_score) { @@ -940,7 +940,7 @@ ClosestPolygonPoint PolygonUtils::findClosest(Point from, ConstPolygonRef polygo return ClosestPolygonPoint(best, bestPos, polygon); } -PolygonsPointIndex PolygonUtils::findNearestVert(const Point from, const Polygons& polys) +PolygonsPointIndex PolygonUtils::findNearestVert(const Point2LL from, const Polygons& polys) { int64_t best_dist2 = std::numeric_limits::max(); PolygonsPointIndex closest_vert; @@ -960,7 +960,7 @@ PolygonsPointIndex PolygonUtils::findNearestVert(const Point from, const Polygon return closest_vert; } -unsigned int PolygonUtils::findNearestVert(const Point from, ConstPolygonRef poly) +unsigned int PolygonUtils::findNearestVert(const Point2LL from, ConstPolygonRef poly) { int64_t best_dist2 = std::numeric_limits::max(); unsigned int closest_vert_idx = -1; @@ -1005,21 +1005,21 @@ std::unique_ptr PolygonUtils::createLocToLineGrid(const Polygons& * We could skip the duplication by keeping a vector of vectors of bools. */ std::optional - PolygonUtils::findClose(Point from, const Polygons& polygons, const LocToLineGrid& loc_to_line, const std::function& penalty_function) + PolygonUtils::findClose(Point2LL from, const Polygons& polygons, const LocToLineGrid& loc_to_line, const std::function& penalty_function) { std::vector near_lines = loc_to_line.getNearby(from, loc_to_line.getCellSize()); - Point best(0, 0); + Point2LL best(0, 0); int64_t closest_dist2_score = std::numeric_limits::max(); PolygonsPointIndex best_point_poly_idx(nullptr, NO_INDEX, NO_INDEX); for (PolygonsPointIndex& point_poly_index : near_lines) { ConstPolygonRef poly = polygons[point_poly_index.poly_idx_]; - const Point& p1 = poly[point_poly_index.point_idx_]; - const Point& p2 = poly[(point_poly_index.point_idx_ + 1) % poly.size()]; + const Point2LL& p1 = poly[point_poly_index.point_idx_]; + const Point2LL& p2 = poly[(point_poly_index.point_idx_ + 1) % poly.size()]; - Point closest_here = LinearAlg2D::getClosestOnLineSegment(from, p1, p2); + Point2LL closest_here = LinearAlg2D::getClosestOnLineSegment(from, p1, p2); int64_t dist2_score = vSize2(from - closest_here) + penalty_function(closest_here); if (dist2_score < closest_dist2_score) { @@ -1039,25 +1039,25 @@ std::optional } std::vector> - PolygonUtils::findClose(ConstPolygonRef from, const Polygons& destination, const LocToLineGrid& destination_loc_to_line, const std::function& penalty_function) + PolygonUtils::findClose(ConstPolygonRef from, const Polygons& destination, const LocToLineGrid& destination_loc_to_line, const std::function& penalty_function) { std::vector> ret; int p0_idx = from.size() - 1; - Point p0(from[p0_idx]); + Point2LL p0(from[p0_idx]); int grid_size = destination_loc_to_line.getCellSize(); for (unsigned int p1_idx = 0; p1_idx < from.size(); p1_idx++) { - const Point& p1 = from[p1_idx]; + const Point2LL& p1 = from[p1_idx]; std::optional best_here = findClose(p1, destination, destination_loc_to_line, penalty_function); if (best_here) { ret.push_back(std::make_pair(ClosestPolygonPoint(p1, p1_idx, from), *best_here)); } - Point p0p1 = p1 - p0; + Point2LL p0p1 = p1 - p0; int dist_to_p1 = vSize(p0p1); for (unsigned int middle_point_nr = 1; dist_to_p1 > grid_size * 2; ++middle_point_nr) { - Point x = p0 + normal(p0p1, middle_point_nr * grid_size); + Point2LL x = p0 + normal(p0p1, middle_point_nr * grid_size); dist_to_p1 -= grid_size; best_here = findClose(x, destination, destination_loc_to_line, penalty_function); @@ -1072,14 +1072,14 @@ std::vector> return ret; } -bool PolygonUtils::getNextPointWithDistance(Point from, int64_t dist, ConstPolygonRef poly, int start_idx, int poly_start_idx, GivenDistPoint& result) +bool PolygonUtils::getNextPointWithDistance(Point2LL from, int64_t dist, ConstPolygonRef poly, int start_idx, int poly_start_idx, GivenDistPoint& result) { - Point prev_poly_point = poly[(start_idx + poly_start_idx) % poly.size()]; + Point2LL prev_poly_point = poly[(start_idx + poly_start_idx) % poly.size()]; for (unsigned int prev_idx = start_idx; prev_idx < poly.size(); prev_idx++) { int next_idx = (prev_idx + 1 + poly_start_idx) % poly.size(); // last checked segment is between last point in poly and poly[0]... - const Point& next_poly_point = poly[next_idx]; + const Point2LL& next_poly_point = poly[next_idx]; if (! shorterThen(next_poly_point - from, dist)) { /* @@ -1097,11 +1097,11 @@ bool PolygonUtils::getNextPointWithDistance(Point from, int64_t dist, ConstPolyg * r=result point at distance [dist] from f */ - Point pn = next_poly_point - prev_poly_point; + Point2LL pn = next_poly_point - prev_poly_point; if (shorterThen(pn, 100)) // when precision is limited { - Point middle = (next_poly_point + prev_poly_point) / 2; + Point2LL middle = (next_poly_point + prev_poly_point) / 2; coord_t dist_to_middle = vSize(from - middle); if (dist_to_middle - dist < 100 && dist_to_middle - dist > -100) { @@ -1116,9 +1116,9 @@ bool PolygonUtils::getNextPointWithDistance(Point from, int64_t dist, ConstPolyg } } - Point pf = from - prev_poly_point; - Point px = dot(pf, pn) / vSize(pn) * pn / vSize(pn); - Point xf = pf - px; + Point2LL pf = from - prev_poly_point; + Point2LL px = dot(pf, pn) / vSize(pn) * pn / vSize(pn); + Point2LL xf = pf - px; if (! shorterThen(xf, dist)) // line lies wholly further than pn { @@ -1134,8 +1134,8 @@ bool PolygonUtils::getNextPointWithDistance(Point from, int64_t dist, ConstPolyg continue; } - Point xr = xr_dist * pn / vSize(pn); - Point pr = px + xr; + Point2LL xr = xr_dist * pn / vSize(pn); + Point2LL pr = px + xr; result.location = prev_poly_point + pr; result.pos = prev_idx; @@ -1149,8 +1149,8 @@ bool PolygonUtils::getNextPointWithDistance(Point from, int64_t dist, ConstPolyg ClosestPolygonPoint PolygonUtils::walk(const ClosestPolygonPoint& from, coord_t distance) { ConstPolygonRef poly = *from.poly_; - Point last_vertex = from.p(); - Point next_vertex; + Point2LL last_vertex = from.p(); + Point2LL next_vertex; size_t last_point_idx = from.point_idx_; for (size_t point_idx = from.point_idx_ + 1;; point_idx++) { @@ -1165,11 +1165,11 @@ ClosestPolygonPoint PolygonUtils::walk(const ClosestPolygonPoint& from, coord_t last_vertex = next_vertex; last_point_idx = point_idx; } - Point result = next_vertex + normal(last_vertex - next_vertex, -distance); + Point2LL result = next_vertex + normal(last_vertex - next_vertex, -distance); return ClosestPolygonPoint(result, last_point_idx, poly, from.poly_idx_); } -std::optional PolygonUtils::getNextParallelIntersection(const ClosestPolygonPoint& start, const Point& line_to, const coord_t dist, const bool forward) +std::optional PolygonUtils::getNextParallelIntersection(const ClosestPolygonPoint& start, const Point2LL& line_to, const coord_t dist, const bool forward) { // <--o--t-----y----< poly 1 // : : @@ -1184,32 +1184,32 @@ std::optional PolygonUtils::getNextParallelIntersection(con // t=line_to ConstPolygonRef poly = *start.poly_; - const Point s = start.p(); - const Point t = line_to; + const Point2LL s = start.p(); + const Point2LL t = line_to; - const Point st = t - s; - const Point shift = normal(turn90CCW(st), dist); + const Point2LL st = t - s; + const Point2LL shift = normal(turn90CCW(st), dist); - Point prev_vert = s; + Point2LL prev_vert = s; coord_t prev_projected = 0; for (unsigned int next_point_nr = 0; next_point_nr < poly.size(); next_point_nr++) { const unsigned int next_point_idx = forward ? (start.point_idx_ + 1 + next_point_nr) % poly.size() : (static_cast(start.point_idx_) - next_point_nr + poly.size()) % poly.size(); // cast in order to accomodate subtracting - const Point next_vert = poly[next_point_idx]; - const Point so = next_vert - s; + const Point2LL next_vert = poly[next_point_idx]; + const Point2LL so = next_vert - s; const coord_t projected = dot(shift, so) / dist; if (std::abs(projected) > dist) { // segment crosses the line through xy (or the one on the other side of st) - const Point segment_vector = next_vert - prev_vert; + const Point2LL segment_vector = next_vert - prev_vert; const coord_t segment_length = vSize(segment_vector); const coord_t projected_segment_length = std::abs(projected - prev_projected); const int16_t sign = (projected > 0) ? 1 : -1; const coord_t projected_inter_segment_length = dist - sign * prev_projected; // add the prev_projected to dist if it is projected to the other side of the input line than where the intersection occurs. const coord_t inter_segment_length = segment_length * projected_inter_segment_length / projected_segment_length; - const Point intersection = prev_vert + normal(next_vert - prev_vert, inter_segment_length); + const Point2LL intersection = prev_vert + normal(next_vert - prev_vert, inter_segment_length); size_t vert_before_idx = next_point_idx; if (forward) @@ -1228,26 +1228,26 @@ std::optional PolygonUtils::getNextParallelIntersection(con } -bool PolygonUtils::polygonCollidesWithLineSegment(const Point from, const Point to, const LocToLineGrid& loc_to_line, PolygonsPointIndex* collision_result) +bool PolygonUtils::polygonCollidesWithLineSegment(const Point2LL from, const Point2LL to, const LocToLineGrid& loc_to_line, PolygonsPointIndex* collision_result) { bool ret = false; - Point diff = to - from; + Point2LL diff = to - from; if (vSize2(diff) < 2) { // transformation matrix would fail return false; } PointMatrix transformation_matrix = PointMatrix(diff); - Point transformed_from = transformation_matrix.apply(from); - Point transformed_to = transformation_matrix.apply(to); + Point2LL transformed_from = transformation_matrix.apply(from); + Point2LL transformed_to = transformation_matrix.apply(to); PolygonsPointIndex result; std::function process_elem_func = [transformed_from, transformed_to, &transformation_matrix, &result, &ret](const PolygonsPointIndex& line_start) { - Point p0 = transformation_matrix.apply(line_start.p()); - Point p1 = transformation_matrix.apply(line_start.next().p()); + Point2LL p0 = transformation_matrix.apply(line_start.p()); + Point2LL p1 = transformation_matrix.apply(line_start.next().p()); if (LinearAlg2D::lineSegmentsCollide(transformed_from, transformed_to, p0, p1)) { @@ -1266,12 +1266,16 @@ bool PolygonUtils::polygonCollidesWithLineSegment(const Point from, const Point return ret; } -bool PolygonUtils::polygonCollidesWithLineSegment(ConstPolygonRef poly, const Point& transformed_startPoint, const Point& transformed_endPoint, PointMatrix transformation_matrix) +bool PolygonUtils::polygonCollidesWithLineSegment( + ConstPolygonRef poly, + const Point2LL& transformed_startPoint, + const Point2LL& transformed_endPoint, + PointMatrix transformation_matrix) { - Point p0 = transformation_matrix.apply(poly.back()); - for (Point p1_ : poly) + Point2LL p0 = transformation_matrix.apply(poly.back()); + for (Point2LL p1_ : poly) { - Point p1 = transformation_matrix.apply(p1_); + Point2LL p1 = transformation_matrix.apply(p1_); if (LinearAlg2D::lineSegmentsCollide(transformed_startPoint, transformed_endPoint, p0, p1)) { return true; @@ -1281,18 +1285,22 @@ bool PolygonUtils::polygonCollidesWithLineSegment(ConstPolygonRef poly, const Po return false; } -bool PolygonUtils::polygonCollidesWithLineSegment(ConstPolygonRef poly, const Point& startPoint, const Point& endPoint) +bool PolygonUtils::polygonCollidesWithLineSegment(ConstPolygonRef poly, const Point2LL& startPoint, const Point2LL& endPoint) { - Point diff = endPoint - startPoint; + Point2LL diff = endPoint - startPoint; PointMatrix transformation_matrix = PointMatrix(diff); - Point transformed_startPoint = transformation_matrix.apply(startPoint); - Point transformed_endPoint = transformation_matrix.apply(endPoint); + Point2LL transformed_startPoint = transformation_matrix.apply(startPoint); + Point2LL transformed_endPoint = transformation_matrix.apply(endPoint); return PolygonUtils::polygonCollidesWithLineSegment(poly, transformed_startPoint, transformed_endPoint, transformation_matrix); } -bool PolygonUtils::polygonCollidesWithLineSegment(const Polygons& polys, const Point& transformed_startPoint, const Point& transformed_endPoint, PointMatrix transformation_matrix) +bool PolygonUtils::polygonCollidesWithLineSegment( + const Polygons& polys, + const Point2LL& transformed_startPoint, + const Point2LL& transformed_endPoint, + PointMatrix transformation_matrix) { for (ConstPolygonRef poly : polys) { @@ -1310,17 +1318,17 @@ bool PolygonUtils::polygonCollidesWithLineSegment(const Polygons& polys, const P } -bool PolygonUtils::polygonCollidesWithLineSegment(const Polygons& polys, const Point& startPoint, const Point& endPoint) +bool PolygonUtils::polygonCollidesWithLineSegment(const Polygons& polys, const Point2LL& startPoint, const Point2LL& endPoint) { if (endPoint == startPoint) { return false; // Zero-length line segments never collide. } - Point diff = endPoint - startPoint; + Point2LL diff = endPoint - startPoint; PointMatrix transformation_matrix = PointMatrix(diff); - Point transformed_startPoint = transformation_matrix.apply(startPoint); - Point transformed_endPoint = transformation_matrix.apply(endPoint); + Point2LL transformed_startPoint = transformation_matrix.apply(startPoint); + Point2LL transformed_endPoint = transformation_matrix.apply(endPoint); return polygonCollidesWithLineSegment(polys, transformed_startPoint, transformed_endPoint, transformation_matrix); } @@ -1338,8 +1346,8 @@ bool PolygonUtils::polygonOutlinesAdjacent(const ConstPolygonRef inner_poly, con // Heuristic check if their AABBs are near first. AABB inner_aabb(inner_poly); AABB outer_aabb(outer_poly); - inner_aabb.max_ += Point(max_gap, max_gap); // Expand one of them by way of a "distance" by checking intersection with the expanded rectangle. - inner_aabb.min_ -= Point(max_gap, max_gap); + inner_aabb.max_ += Point2LL(max_gap, max_gap); // Expand one of them by way of a "distance" by checking intersection with the expanded rectangle. + inner_aabb.min_ -= Point2LL(max_gap, max_gap); if (! inner_aabb.hit(outer_aabb)) { return false; @@ -1350,9 +1358,9 @@ bool PolygonUtils::polygonOutlinesAdjacent(const ConstPolygonRef inner_poly, con const unsigned outer_poly_size = outer_poly.size(); for (unsigned line_index = 0; line_index < outer_poly_size; ++line_index) { - const Point lp0 = outer_poly[line_index]; - const Point lp1 = outer_poly[(line_index + 1) % outer_poly_size]; - for (Point inner_poly_point : inner_poly) + const Point2LL lp0 = outer_poly[line_index]; + const Point2LL lp1 = outer_poly[(line_index + 1) % outer_poly_size]; + for (Point2LL inner_poly_point : inner_poly) { if (LinearAlg2D::getDist2FromLineSegment(lp0, inner_poly_point, lp1) < max_gap2) { @@ -1391,7 +1399,7 @@ double PolygonUtils::relativeHammingDistance(const Polygons& poly_a, const Polyg { for (const ConstPolygonRef& polygon_a : poly_a) { - for (Point point : polygon_a) + for (Point2LL point : polygon_a) { if (! poly_b.inside(point, borders_allowed)) { @@ -1401,7 +1409,7 @@ double PolygonUtils::relativeHammingDistance(const Polygons& poly_a, const Polyg } for (const ConstPolygonRef& polygon_b : poly_b) { - for (Point point : polygon_b) + for (Point2LL point : polygon_b) { if (! poly_a.inside(point, borders_allowed)) { @@ -1417,12 +1425,12 @@ double PolygonUtils::relativeHammingDistance(const Polygons& poly_a, const Polyg return hamming_distance / total_area; } -Polygon PolygonUtils::makeCircle(const Point mid, const coord_t radius, const AngleRadians a_step) +Polygon PolygonUtils::makeCircle(const Point2LL mid, const coord_t radius, const AngleRadians a_step) { Polygon circle; for (double a = 0; a < 2 * std::numbers::pi; a += a_step) { - circle.emplace_back(mid + Point(radius * cos(a), radius * sin(a))); + circle.emplace_back(mid + Point2LL(radius * cos(a), radius * sin(a))); } return circle; } @@ -1438,20 +1446,20 @@ Polygons PolygonUtils::connect(const Polygons& input) for (size_t hole_idx = 1; hole_idx < part.size(); hole_idx++) { PolygonRef hole = part[hole_idx]; - Point hole_point = hole[0]; + Point2LL hole_point = hole[0]; hole.add(hole_point); // find where the scanline passes the Y size_t best_segment_to_idx = 0; coord_t best_dist = std::numeric_limits::max(); - Point best_intersection_point = outline.back(); + Point2LL best_intersection_point = outline.back(); - Point prev = outline.back(); + Point2LL prev = outline.back(); for (size_t point_idx = 0; point_idx < outline.size(); point_idx++) { - Point here = outline[point_idx]; + Point2LL here = outline[point_idx]; if (here.Y > hole_point.Y && prev.Y <= hole_point.Y && here.Y != prev.Y) { - Point intersection_point = prev + (here - prev) * (hole_point.Y - prev.Y) / (here.Y - prev.Y); + Point2LL intersection_point = prev + (here - prev) * (hole_point.Y - prev.Y) / (here.Y - prev.Y); coord_t dist = hole_point.X - intersection_point.X; if (dist > 0 && dist < best_dist) { @@ -1496,7 +1504,7 @@ void PolygonUtils::fixSelfIntersections(const coord_t epsilon, Polygons& thiss) const size_t pathlen = thiss[poly_idx].size(); for (size_t point_idx = 0; point_idx < pathlen; ++point_idx) { - Point& pt = thiss[poly_idx][point_idx]; + Point2LL& pt = thiss[poly_idx][point_idx]; for (const auto& line : query_grid->getNearby(pt, epsilon * 2)) { const size_t line_next_idx = (line.point_idx_ + 1) % thiss[line.poly_idx_].size(); @@ -1505,13 +1513,13 @@ void PolygonUtils::fixSelfIntersections(const coord_t epsilon, Polygons& thiss) continue; } - const Point& a = thiss[line.poly_idx_][line.point_idx_]; - const Point& b = thiss[line.poly_idx_][line_next_idx]; + const Point2LL& a = thiss[line.poly_idx_][line.point_idx_]; + const Point2LL& b = thiss[line.poly_idx_][line_next_idx]; if (half_epsilon_sqrd >= vSize2(pt - LinearAlg2D::getClosestOnLineSegment(pt, a, b))) { - const Point& other = thiss[poly_idx][(point_idx + 1) % pathlen]; - const Point vec = LinearAlg2D::pointIsLeftOfLine(other, a, b) > 0 ? b - a : a - b; + const Point2LL& other = thiss[poly_idx][(point_idx + 1) % pathlen]; + const Point2LL vec = LinearAlg2D::pointIsLeftOfLine(other, a, b) > 0 ? b - a : a - b; const coord_t len = vSize(vec); pt.X += (-vec.Y * move_dist) / len; pt.Y += (vec.X * move_dist) / len; @@ -1562,7 +1570,7 @@ Polygons PolygonUtils::clipPolygonWithAABB(const Polygons& src, const AABB& aabb Bottom = 8 }; - auto sides = [aabb](const Point& p) + auto sides = [aabb](const Point2LL& p) { return int(p.X < aabb.min_.X) * int(Side::Left) + int(p.X > aabb.max_.X) * int(Side::Right) + int(p.Y < aabb.min_.Y) * int(Side::Bottom) + int(p.Y > aabb.max_.Y) * int(Side::Top); diff --git a/tests/ExtruderPlanTest.cpp b/tests/ExtruderPlanTest.cpp index d0d2772979..2aa6f6e59d 100644 --- a/tests/ExtruderPlanTest.cpp +++ b/tests/ExtruderPlanTest.cpp @@ -87,7 +87,7 @@ class ExtruderPlanTestPathCollection .spiralize = no_spiralize, .speed_factor = speed_1 } }); - square.back().points = { Point(0, 0), Point(1000, 0), Point(1000, 1000), Point(0, 1000), Point(0, 0) }; + square.back().points = { Point2LL(0, 0), Point2LL(1000, 0), Point2LL(1000, 1000), Point2LL(0, 1000), Point2LL(0, 0) }; lines.assign({ GCodePath{ .config = extrusion_config, .mesh = mesh, @@ -124,11 +124,11 @@ class ExtruderPlanTestPathCollection .width_factor = width_1, .spiralize = no_spiralize, .speed_factor = speed_1 } }); - lines[0].points = { Point(0, 0), Point(1000, 0) }; - lines[1].points = { Point(1000, 0), Point(1000, 400) }; - lines[2].points = { Point(1000, 400), Point(0, 400) }; - lines[3].points = { Point(0, 400), Point(0, 800) }; - lines[4].points = { Point(0, 800), Point(1000, 800) }; + lines[0].points = { Point2LL(0, 0), Point2LL(1000, 0) }; + lines[1].points = { Point2LL(1000, 0), Point2LL(1000, 400) }; + lines[2].points = { Point2LL(1000, 400), Point2LL(0, 400) }; + lines[3].points = { Point2LL(0, 400), Point2LL(0, 800) }; + lines[4].points = { Point2LL(0, 800), Point2LL(1000, 800) }; constexpr Ratio flow_12 = 1.2_r; constexpr Ratio flow_08 = 0.8_r; @@ -168,11 +168,11 @@ class ExtruderPlanTestPathCollection .width_factor = width_1, .spiralize = no_spiralize, .speed_factor = speed_1 } }); - decreasing_flow[0].points = { Point(0, 0), Point(1000, 0) }; - decreasing_flow[1].points = { Point(1000, 0), Point(1000, 400) }; - decreasing_flow[2].points = { Point(1000, 400), Point(0, 400) }; - decreasing_flow[3].points = { Point(0, 400), Point(0, 800) }; - decreasing_flow[4].points = { Point(0, 800), Point(1000, 800) }; + decreasing_flow[0].points = { Point2LL(0, 0), Point2LL(1000, 0) }; + decreasing_flow[1].points = { Point2LL(1000, 0), Point2LL(1000, 400) }; + decreasing_flow[2].points = { Point2LL(1000, 400), Point2LL(0, 400) }; + decreasing_flow[3].points = { Point2LL(0, 400), Point2LL(0, 800) }; + decreasing_flow[4].points = { Point2LL(0, 800), Point2LL(1000, 800) }; constexpr Ratio speed_12 = 1.2_r; constexpr Ratio speed_08 = 0.8_r; @@ -212,11 +212,11 @@ class ExtruderPlanTestPathCollection .width_factor = width_1, .spiralize = no_spiralize, .speed_factor = speed_04 } }); - decreasing_speed[0].points = { Point(0, 0), Point(1000, 0) }; - decreasing_speed[1].points = { Point(1000, 0), Point(1000, 400) }; - decreasing_speed[2].points = { Point(1000, 400), Point(0, 400) }; - decreasing_speed[3].points = { Point(0, 400), Point(0, 800) }; - decreasing_speed[4].points = { Point(0, 800), Point(1000, 800) }; + decreasing_speed[0].points = { Point2LL(0, 0), Point2LL(1000, 0) }; + decreasing_speed[1].points = { Point2LL(1000, 0), Point2LL(1000, 400) }; + decreasing_speed[2].points = { Point2LL(1000, 400), Point2LL(0, 400) }; + decreasing_speed[3].points = { Point2LL(0, 400), Point2LL(0, 800) }; + decreasing_speed[4].points = { Point2LL(0, 800), Point2LL(1000, 800) }; variable_width.assign({ GCodePath{ .config = extrusion_config, @@ -262,12 +262,12 @@ class ExtruderPlanTestPathCollection .spiralize = no_spiralize, .speed_factor = speed_1 }, }); - variable_width[0].points = { Point(0, 0), Point(1000, 0) }; - variable_width[1].points = { Point(1000, 0), Point(2000, 0) }; - variable_width[2].points = { Point(2000, 0), Point(3000, 0) }; - variable_width[3].points = { Point(3000, 0), Point(4000, 0) }; - variable_width[4].points = { Point(4000, 0), Point(5000, 0) }; - variable_width[5].points = { Point(5000, 0), Point(6000, 0) }; + variable_width[0].points = { Point2LL(0, 0), Point2LL(1000, 0) }; + variable_width[1].points = { Point2LL(1000, 0), Point2LL(2000, 0) }; + variable_width[2].points = { Point2LL(2000, 0), Point2LL(3000, 0) }; + variable_width[3].points = { Point2LL(3000, 0), Point2LL(4000, 0) }; + variable_width[4].points = { Point2LL(4000, 0), Point2LL(5000, 0) }; + variable_width[5].points = { Point2LL(5000, 0), Point2LL(6000, 0) }; } }; // NOLINTEND(misc-non-private-member-variables-in-classes) diff --git a/tests/GCodeExportTest.cpp b/tests/GCodeExportTest.cpp index 5302a02ae4..e43ba1fee9 100644 --- a/tests/GCodeExportTest.cpp +++ b/tests/GCodeExportTest.cpp @@ -46,7 +46,7 @@ class GCodeExportTest : public testing::Test gcode.output_stream_ = &output; // Since GCodeExport doesn't support copying, we have to reset everything in-place. - gcode.current_position_ = Point3(0, 0, MM2INT(20)); + gcode.current_position_ = Point3LL(0, 0, MM2INT(20)); gcode.layer_nr_ = 0; gcode.current_e_value_ = 0; gcode.current_e_offset_ = 0; @@ -207,7 +207,7 @@ class GriffinHeaderTest : public testing::TestWithParam gcode.output_stream_ = &output; // Since GCodeExport doesn't support copying, we have to reset everything in-place. - gcode.current_position_ = Point3(0, 0, MM2INT(20)); + gcode.current_position_ = Point3LL(0, 0, MM2INT(20)); gcode.layer_nr_ = 0; gcode.current_e_value_ = 0; gcode.current_extruder_ = 0; @@ -328,7 +328,7 @@ TEST_F(GCodeExportTest, HeaderUltiGCode) ExtruderTrain& train = Application::getInstance().current_slice_->scene.extruders.back(); train.settings_.add("machine_nozzle_size", "0.4"); } - gcode.total_bounding_box = AABB3D(Point3(0, 0, 0), Point3(1000, 1000, 1000)); + gcode.total_bounding_box = AABB3D(Point3LL(0, 0, 0), Point3LL(1000, 1000, 1000)); std::string result = gcode.getFileHeader(extruder_is_used, &print_time, filament_used); @@ -348,7 +348,7 @@ TEST_F(GCodeExportTest, HeaderRepRap) const std::vector extruder_is_used(num_extruders, true); constexpr Duration print_time = 1337; const std::vector filament_used = { 100, 200 }; - gcode.total_bounding_box = AABB3D(Point3(0, 0, 0), Point3(1000, 1000, 1000)); + gcode.total_bounding_box = AABB3D(Point3LL(0, 0, 0), Point3LL(1000, 1000, 1000)); std::string result = gcode.getFileHeader(extruder_is_used, &print_time, filament_used); @@ -368,7 +368,7 @@ TEST_F(GCodeExportTest, HeaderMarlin) const std::vector extruder_is_used(num_extruders, true); constexpr Duration print_time = 1337; const std::vector filament_used = { 100, 200 }; - gcode.total_bounding_box = AABB3D(Point3(0, 0, 0), Point3(1000, 1000, 1000)); + gcode.total_bounding_box = AABB3D(Point3LL(0, 0, 0), Point3LL(1000, 1000, 1000)); std::string result = gcode.getFileHeader(extruder_is_used, &print_time, filament_used); @@ -386,7 +386,7 @@ TEST_F(GCodeExportTest, HeaderMarlinVolumetric) const std::vector extruder_is_used(num_extruders, true); constexpr Duration print_time = 1337; const std::vector filament_used = { 100, 200 }; - gcode.total_bounding_box = AABB3D(Point3(0, 0, 0), Point3(1000, 1000, 1000)); + gcode.total_bounding_box = AABB3D(Point3LL(0, 0, 0), Point3LL(1000, 1000, 1000)); std::string result = gcode.getFileHeader(extruder_is_used, &print_time, filament_used); @@ -544,7 +544,7 @@ TEST_F(GCodeExportTest, WriteZHopEndCustomSpeed) TEST_F(GCodeExportTest, insertWipeScriptSingleMove) { - gcode.currentPosition = Point3(1000, 1000, 1000); + gcode.currentPosition = Point3LL(1000, 1000, 1000); gcode.current_layer_z = 1000; gcode.use_extruder_offset_to_offset_coords = false; Application::getInstance().current_slice_->scene.current_mesh_group->settings.add("layer_height", "0.2"); @@ -576,7 +576,7 @@ TEST_F(GCodeExportTest, insertWipeScriptSingleMove) TEST_F(GCodeExportTest, insertWipeScriptMultipleMoves) { - gcode.currentPosition = Point3(1000, 1000, 1000); + gcode.currentPosition = Point3LL(1000, 1000, 1000); gcode.current_layer_z = 1000; gcode.use_extruder_offset_to_offset_coords = false; Application::getInstance().current_slice_->scene.current_mesh_group->settings.add("layer_height", "0.2"); @@ -614,7 +614,7 @@ TEST_F(GCodeExportTest, insertWipeScriptMultipleMoves) TEST_F(GCodeExportTest, insertWipeScriptOptionalDelay) { - gcode.currentPosition = Point3(1000, 1000, 1000); + gcode.currentPosition = Point3LL(1000, 1000, 1000); gcode.current_layer_z = 1000; gcode.use_extruder_offset_to_offset_coords = false; Application::getInstance().current_slice_->scene.current_mesh_group->settings.add("layer_height", "0.2"); @@ -645,7 +645,7 @@ TEST_F(GCodeExportTest, insertWipeScriptOptionalDelay) TEST_F(GCodeExportTest, insertWipeScriptRetractionEnable) { - gcode.currentPosition = Point3(1000, 1000, 1000); + gcode.currentPosition = Point3LL(1000, 1000, 1000); gcode.current_layer_z = 1000; gcode.current_e_value = 100; gcode.use_extruder_offset_to_offset_coords = false; @@ -693,7 +693,7 @@ TEST_F(GCodeExportTest, insertWipeScriptRetractionEnable) TEST_F(GCodeExportTest, insertWipeScriptHopEnable) { - gcode.currentPosition = Point3(1000, 1000, 1000); + gcode.currentPosition = Point3LL(1000, 1000, 1000); gcode.current_layer_z = 1000; gcode.use_extruder_offset_to_offset_coords = false; gcode.currentSpeed = 1.0; diff --git a/tests/LayerPlanTest.cpp b/tests/LayerPlanTest.cpp index f04a22e605..455e59c82a 100644 --- a/tests/LayerPlanTest.cpp +++ b/tests/LayerPlanTest.cpp @@ -207,7 +207,7 @@ class LayerPlanTest : public testing::Test void SetUp() override { - layer_plan.addTravel_simple(Point(0, 0)); // Make sure that it appears as if we have already done things in this layer plan. Just the standard case. + layer_plan.addTravel_simple(Point2LL(0, 0)); // Make sure that it appears as if we have already done things in this layer plan. Just the standard case. } /*! @@ -310,30 +310,30 @@ class AddTravelTest : public LayerPlanTest, public testing::WithParamInterface("false", "false", "off", false, false, AddTravelTestScene::OPEN)) { - around_start_end.add(Point(-100, -100)); - around_start_end.add(Point(500100, -100)); - around_start_end.add(Point(500100, 500100)); - around_start_end.add(Point(-100, 500100)); - - around_start.add(Point(-100, -100)); - around_start.add(Point(100, -100)); - around_start.add(Point(100, 100)); - around_start.add(Point(-100, 100)); - - around_end.add(Point(249900, 249900)); - around_end.add(Point(250100, 249900)); - around_end.add(Point(250100, 250100)); - around_end.add(Point(249900, 249900)); - - between.add(Point(250000, 240000)); - between.add(Point(260000, 240000)); - between.add(Point(260000, 300000)); - between.add(Point(250000, 300000)); - - between_hole.add(Point(250000, 240000)); - between_hole.add(Point(250000, 300000)); - between_hole.add(Point(260000, 300000)); - between_hole.add(Point(260000, 240000)); + around_start_end.add(Point2LL(-100, -100)); + around_start_end.add(Point2LL(500100, -100)); + around_start_end.add(Point2LL(500100, 500100)); + around_start_end.add(Point2LL(-100, 500100)); + + around_start.add(Point2LL(-100, -100)); + around_start.add(Point2LL(100, -100)); + around_start.add(Point2LL(100, 100)); + around_start.add(Point2LL(-100, 100)); + + around_end.add(Point2LL(249900, 249900)); + around_end.add(Point2LL(250100, 249900)); + around_end.add(Point2LL(250100, 250100)); + around_end.add(Point2LL(249900, 249900)); + + between.add(Point2LL(250000, 240000)); + between.add(Point2LL(260000, 240000)); + between.add(Point2LL(260000, 300000)); + between.add(Point2LL(250000, 300000)); + + between_hole.add(Point2LL(250000, 240000)); + between_hole.add(Point2LL(250000, 300000)); + between_hole.add(Point2LL(260000, 300000)); + between_hole.add(Point2LL(260000, 240000)); } /*! @@ -401,7 +401,7 @@ class AddTravelTest : public LayerPlanTest, public testing::WithParamInterface& path) +inline Point2LL startVertex(const PathOrdering& path) { return (*path.vertices_)[path.start_vertex_]; } -inline Point endVertex(const PathOrdering& path) +inline Point2LL endVertex(const PathOrdering& path) { return (*path.vertices_)[path.vertices_->size() - (1 + path.start_vertex_)]; } -coord_t projectPathAlongAxis(const PathOrdering& path, const Point& vector) +coord_t projectPathAlongAxis(const PathOrdering& path, const Point2LL& vector) { return dot(startVertex(path), vector); } -coord_t projectEndAlongAxis(const PathOrdering& path, const Point& vector) +coord_t projectEndAlongAxis(const PathOrdering& path, const Point2LL& vector) { return dot(endVertex(path), vector); } @@ -139,11 +139,11 @@ TEST_P(PathOrderMonotonicTest, SectionsTest) Polygons polylines; ASSERT_TRUE(getInfillLines(filename, angle_radians, polylines)) << "Input test-file could not be read, check setup."; - const Point& pt_r = polylines.begin()->at(0); - const Point& pt_s = polylines.begin()->at(1); + const Point2LL& pt_r = polylines.begin()->at(0); + const Point2LL& pt_s = polylines.begin()->at(1); const double angle_from_first_line = std::atan2(pt_s.Y - pt_r.Y, pt_s.X - pt_r.X) + 0.5 * std::numbers::pi; - const Point monotonic_axis(static_cast(std::cos(angle_from_first_line)) * 1000, static_cast(std::sin(angle_from_first_line)) * 1000); - const Point perpendicular_axis{ turn90CCW(monotonic_axis) }; + const Point2LL monotonic_axis(static_cast(std::cos(angle_from_first_line)) * 1000, static_cast(std::sin(angle_from_first_line)) * 1000); + const Point2LL perpendicular_axis{ turn90CCW(monotonic_axis) }; constexpr coord_t max_adjacent_distance = line_distance + 1; PathOrderMonotonic object_under_test(angle_from_first_line, max_adjacent_distance, monotonic_axis * -1000); diff --git a/tests/PathOrderOptimizerTest.cpp b/tests/PathOrderOptimizerTest.cpp index 4c8da0924c..3b895e1360 100644 --- a/tests/PathOrderOptimizerTest.cpp +++ b/tests/PathOrderOptimizerTest.cpp @@ -21,18 +21,18 @@ class PathOrderOptimizerTest : public testing::Test */ Polygon triangle; - PathOrderOptimizerTest() : optimizer(Point(0, 0)) + PathOrderOptimizerTest() : optimizer(Point2LL(0, 0)) { } void SetUp() override { - optimizer = PathOrderOptimizer(Point(0, 0)); + optimizer = PathOrderOptimizer(Point2LL(0, 0)); triangle.clear(); - triangle.add(Point(0, 0)); - triangle.add(Point(50, 0)); - triangle.add(Point(25, 50)); + triangle.add(Point2LL(0, 0)); + triangle.add(Point2LL(50, 0)); + triangle.add(Point2LL(25, 50)); } }; // NOLINTEND(misc-non-private-member-variables-in-classes) @@ -53,11 +53,11 @@ TEST_F(PathOrderOptimizerTest, OptimizeWhileEmpty) TEST_F(PathOrderOptimizerTest, ThreeTrianglesShortestOrder) { Polygon near = triangle; // Copy, then translate. - near.translate(Point(100, 100)); + near.translate(Point2LL(100, 100)); Polygon middle = triangle; - middle.translate(Point(500, 500)); + middle.translate(Point2LL(500, 500)); Polygon far = triangle; - far.translate(Point(1000, 1000)); + far.translate(Point2LL(1000, 1000)); // Add them out of order so that it's clear that the optimization changes the order. optimizer.addPolygon(middle); @@ -66,9 +66,9 @@ TEST_F(PathOrderOptimizerTest, ThreeTrianglesShortestOrder) optimizer.optimize(); - EXPECT_EQ(optimizer.paths[0].vertices->front(), Point(100, 100)) << "Nearest triangle first."; - EXPECT_EQ(optimizer.paths[1].vertices->front(), Point(500, 500)) << "Middle triangle second."; - EXPECT_EQ(optimizer.paths[2].vertices->front(), Point(1000, 1000)) << "Far triangle last."; + EXPECT_EQ(optimizer.paths[0].vertices->front(), Point2LL(100, 100)) << "Nearest triangle first."; + EXPECT_EQ(optimizer.paths[1].vertices->front(), Point2LL(500, 500)) << "Middle triangle second."; + EXPECT_EQ(optimizer.paths[2].vertices->front(), Point2LL(1000, 1000)) << "Far triangle last."; } } // namespace cura diff --git a/tests/arcus/ArcusCommunicationTest.cpp b/tests/arcus/ArcusCommunicationTest.cpp index 6f5692fec6..7c1036166e 100644 --- a/tests/arcus/ArcusCommunicationTest.cpp +++ b/tests/arcus/ArcusCommunicationTest.cpp @@ -62,7 +62,7 @@ class ArcusCommunicationTest : public testing::Test for (double a = 0; a < 1.0; a += .05) { - test_circle.add(Point(2050, 2050) + Point(std::cos(a * 2 * std::numbers::pi) * 500, std::sin(a * 2 * std::numbers::pi) * 500)); + test_circle.add(Point2LL(2050, 2050) + Point2LL(std::cos(a * 2 * std::numbers::pi) * 500, std::sin(a * 2 * std::numbers::pi) * 500)); } test_shapes.add(test_circle); diff --git a/tests/utils/AABB3DTest.cpp b/tests/utils/AABB3DTest.cpp index 7bfb51d7db..711e20849c 100644 --- a/tests/utils/AABB3DTest.cpp +++ b/tests/utils/AABB3DTest.cpp @@ -13,7 +13,7 @@ namespace cura { inline AABB3D toBox(const coord_t& x, const coord_t& y, const coord_t& z) { - const Point3 pt(x, y, z); + const Point3LL pt(x, y, z); return { pt, pt }; } @@ -24,8 +24,8 @@ TEST(AABB3DTest, TestConstructEmpty) EXPECT_FALSE(empty_box.hit(toBox(0, 0, 0))) << "Empty box shouldn't contain anything."; EXPECT_FALSE(empty_box.hit(empty_box)) << "Empty boxes shouldn't intersect."; - empty_box.include(Point3(-10, -5, -2)); - empty_box.include(Point3(5, 10, 2)); + empty_box.include(Point3LL(-10, -5, -2)); + empty_box.include(Point3LL(5, 10, 2)); EXPECT_TRUE(empty_box.hit(toBox(0, 0, 0))) << "The previously empty box should now contain this point."; EXPECT_FALSE(empty_box.hit(toBox(11, 5, 0))) << "The previously empty box should now still not contain this point."; @@ -33,7 +33,7 @@ TEST(AABB3DTest, TestConstructEmpty) TEST(AABB3DTest, TestConstructPoint) { - AABB3D point_box(Point3(-10, -5, -2), Point3(5, 10, 2)); + AABB3D point_box(Point3LL(-10, -5, -2), Point3LL(5, 10, 2)); EXPECT_TRUE(point_box.hit(toBox(0, 0, 0))) << "Box constructed from points around the origin should contain it."; EXPECT_FALSE(point_box.hit(toBox(11, 5, 0))) << "The box shouldn't contain a point outside of it."; @@ -41,13 +41,13 @@ TEST(AABB3DTest, TestConstructPoint) TEST(AABB3DTest, TestConstructInverse) { - AABB3D inverse_box(Point3(5, 10, 2), Point3(-10, -5, -2)); + AABB3D inverse_box(Point3LL(5, 10, 2), Point3LL(-10, -5, -2)); EXPECT_FALSE(inverse_box.hit(toBox(0, 0, 0))) << "'Inverse' box shouldn't contain anything."; EXPECT_FALSE(inverse_box.hit(inverse_box)) << "'Inverse' boxes shouldn't intersect."; - inverse_box.include(Point3(-5, -2, -1)); - inverse_box.include(Point3(2, 5, 1)); + inverse_box.include(Point3LL(-5, -2, -1)); + inverse_box.include(Point3LL(2, 5, 1)); EXPECT_TRUE(inverse_box.hit(toBox(0, 0, 0))) << "The previously 'inverse' box should now contain this point."; EXPECT_FALSE(inverse_box.hit(toBox(4, 8, -1))) << "The previously 'inverse' box should now still not contain this point."; @@ -55,9 +55,9 @@ TEST(AABB3DTest, TestConstructInverse) TEST(AABB3DTest, TestHit) { - AABB3D box_a(Point3(-10, -5, -2), Point3(5, 10, 2)); - AABB3D box_b(Point3(4, 9, 0), Point3(12, 12, 12)); - AABB3D box_c(Point3(11, 11, 11), Point3(14, 14, 14)); + AABB3D box_a(Point3LL(-10, -5, -2), Point3LL(5, 10, 2)); + AABB3D box_b(Point3LL(4, 9, 0), Point3LL(12, 12, 12)); + AABB3D box_c(Point3LL(11, 11, 11), Point3LL(14, 14, 14)); EXPECT_TRUE(box_a.hit(box_a)) << "Box should overlap itself."; @@ -69,8 +69,8 @@ TEST(AABB3DTest, TestHit) EXPECT_FALSE(box_a.hit(box_c)) << "These boxes should not overlap (case AC)."; EXPECT_FALSE(box_c.hit(box_a)) << "These boxes should not overlap (case CA)."; - AABB3D box_d(Point3(3, 10, 2), Point3(12, 12, 12)); - AABB3D box_e(Point3(5, 10, 2), Point3(12, 12, 12)); + AABB3D box_d(Point3LL(3, 10, 2), Point3LL(12, 12, 12)); + AABB3D box_e(Point3LL(5, 10, 2), Point3LL(12, 12, 12)); EXPECT_TRUE(box_a.hit(box_d)) << "Overlap-check is inclusive (case AD)."; EXPECT_TRUE(box_d.hit(box_a)) << "Overlap-check is inclusive (case DA)."; @@ -80,25 +80,25 @@ TEST(AABB3DTest, TestHit) TEST(AABB3DTest, TestGetMiddle) { - AABB3D box_a(Point3(-10, -6, -5), Point3(6, 10, 3)); - AABB3D box_b(Point3(4, 10, 2), Point3(12, 12, 12)); + AABB3D box_a(Point3LL(-10, -6, -5), Point3LL(6, 10, 3)); + AABB3D box_b(Point3LL(4, 10, 2), Point3LL(12, 12, 12)); - EXPECT_EQ(box_a.getMiddle(), Point3(-2, 2, -1)) << "The middle of the AABB should be this point (case A)."; - EXPECT_EQ(box_b.getMiddle(), Point3(8, 11, 7)) << "The middle of the AABB should be this point (case B)."; + EXPECT_EQ(box_a.getMiddle(), Point3LL(-2, 2, -1)) << "The middle of the AABB should be this point (case A)."; + EXPECT_EQ(box_b.getMiddle(), Point3LL(8, 11, 7)) << "The middle of the AABB should be this point (case B)."; } TEST(AABB3DTest, TestInclude) { - AABB3D box(Point3(2, 2, 2), Point3(5, 10, 3)); + AABB3D box(Point3LL(2, 2, 2), Point3LL(5, 10, 3)); EXPECT_FALSE(box.hit(toBox(1, 1, 1))) << "The unexpanded (via include/point) box should not contain a point in the (future) expanded area."; - box.include(Point3(0, 0, 0)); + box.include(Point3LL(0, 0, 0)); EXPECT_TRUE(box.hit(toBox(1, 1, 1))) << "The expanded (via include/point) box should contain a point in the expanded area."; EXPECT_FALSE(box.hit(toBox(6, 9, -1))) << "The unexpanded (via include/other) box should not contain a point in the (future) expanded area."; - box.include(AABB3D(Point3(7, 9, -2), Point3(8, 10, 0))); + box.include(AABB3D(Point3LL(7, 9, -2), Point3LL(8, 10, 0))); EXPECT_TRUE(box.hit(toBox(6, 9, -1))) << "The expanded (via include/other) box should contain a point in the expanded area."; @@ -106,8 +106,8 @@ TEST(AABB3DTest, TestInclude) EXPECT_TRUE(box.hit(toBox(6, 9, -3))) << "The expanded (via includeZ/scalar) box should contain a point in the expanded area."; - const Point3 a(2, 2, 2); - const Point3 b(5, 10, 15); + const Point3LL a(2, 2, 2); + const Point3LL b(5, 10, 15); AABB3D box2(a, b); AABB3D empty; box2.include(empty); @@ -118,23 +118,23 @@ TEST(AABB3DTest, TestInclude) TEST(AABB3DTest, TestTranslate) { - AABB3D box(Point3(2, 2, 2), Point3(5, 10, 3)); + AABB3D box(Point3LL(2, 2, 2), Point3LL(5, 10, 3)); EXPECT_FALSE(box.hit(toBox(1, 1, 1))) << "The unexpanded (via offset-3D) box should not contain a point in the (future) expanded area."; - box.translate(Point3(-2, -2, -2)); + box.translate(Point3LL(-2, -2, -2)); EXPECT_TRUE(box.hit(toBox(1, 1, 1))) << "The expanded (via offset-3D) box should contain a point in the expanded area."; EXPECT_FALSE(box.hit(toBox(6, 9, -1))) << "The unexpanded (via offset-3D) box should not contain a point in the (future) expanded area."; - box.translate(Point(-2, -2)); + box.translate(Point2LL(-2, -2)); EXPECT_TRUE(box.hit(toBox(-1, -1, 0))) << "The expanded (via offset-2D) box should contain a point in the expanded area."; } TEST(AABB3DTest, TestExpand) { - AABB3D box(Point3(-10, -5, -2), Point3(5, 10, 2)); + AABB3D box(Point3LL(-10, -5, -2), Point3LL(5, 10, 2)); EXPECT_FALSE(box.hit(toBox(6, 11, 3))) << "Before expanding, the box shouldn't contain this point."; @@ -149,12 +149,12 @@ TEST(AABB3DTest, TestExpand) TEST(AABB3DTest, TestFlatten) { - AABB3D box(Point3(-10, -5, -2), Point3(5, 10, 2)); + AABB3D box(Point3LL(-10, -5, -2), Point3LL(5, 10, 2)); AABB flat = box.flatten(); - EXPECT_TRUE(flat.contains(Point(1, 1))) << "The flattened box should contain this point."; - EXPECT_FALSE(flat.contains(Point(-11, 3))) << "The flattened box shouldn't contain this point."; + EXPECT_TRUE(flat.contains(Point2LL(1, 1))) << "The flattened box should contain this point."; + EXPECT_FALSE(flat.contains(Point2LL(-11, 3))) << "The flattened box shouldn't contain this point."; } } // namespace cura // NOLINTEND(*-magic-numbers) diff --git a/tests/utils/AABBTest.cpp b/tests/utils/AABBTest.cpp index e09245e3bb..bb39a91b4f 100644 --- a/tests/utils/AABBTest.cpp +++ b/tests/utils/AABBTest.cpp @@ -13,23 +13,23 @@ TEST(AABBTest, TestConstructEmpty) { AABB empty_box; - EXPECT_FALSE(empty_box.contains(Point(0, 0))) << "Empty box shouldn't contain anything."; + EXPECT_FALSE(empty_box.contains(Point2LL(0, 0))) << "Empty box shouldn't contain anything."; EXPECT_FALSE(empty_box.contains(empty_box.getMiddle())) << "Empty box shouldn't contain anything, even it's own middle."; EXPECT_FALSE(empty_box.hit(empty_box)) << "Empty boxes shouldn't intersect."; - empty_box.include(Point(-10, -5)); - empty_box.include(Point(5, 10)); + empty_box.include(Point2LL(-10, -5)); + empty_box.include(Point2LL(5, 10)); - EXPECT_TRUE(empty_box.contains(Point(0, 0))) << "The previously empty box should now contain this point."; - EXPECT_FALSE(empty_box.contains(Point(11, 5))) << "The previously empty box should now still not contain this point."; + EXPECT_TRUE(empty_box.contains(Point2LL(0, 0))) << "The previously empty box should now contain this point."; + EXPECT_FALSE(empty_box.contains(Point2LL(11, 5))) << "The previously empty box should now still not contain this point."; } TEST(AABBTest, TestConstructPoint) { - AABB point_box(Point(-10, -5), Point(5, 10)); + AABB point_box(Point2LL(-10, -5), Point2LL(5, 10)); - EXPECT_TRUE(point_box.contains(Point(0, 0))) << "Box constructed from points around the origin should contain it."; - EXPECT_FALSE(point_box.contains(Point(11, 5))) << "The box shouldn't contain a point outside of it."; + EXPECT_TRUE(point_box.contains(Point2LL(0, 0))) << "Box constructed from points around the origin should contain it."; + EXPECT_FALSE(point_box.contains(Point2LL(11, 5))) << "The box shouldn't contain a point outside of it."; } TEST(AABBTest, TestConstructPolygons) @@ -37,7 +37,7 @@ TEST(AABBTest, TestConstructPolygons) Polygons empty_polygon; AABB polygons_box_a(empty_polygon); - EXPECT_FALSE(polygons_box_a.contains(Point(0, 0))) << "Box constructed from empty polygon shouldn't contain anything."; + EXPECT_FALSE(polygons_box_a.contains(Point2LL(0, 0))) << "Box constructed from empty polygon shouldn't contain anything."; Polygons polygons; polygons.add(Polygon(ClipperLib::Path({ ClipperLib::IntPoint{ -10, -10 }, ClipperLib::IntPoint{ 10, -10 }, ClipperLib::IntPoint{ -5, -5 }, ClipperLib::IntPoint{ -10, 10 } }))); @@ -46,41 +46,41 @@ TEST(AABBTest, TestConstructPolygons) AABB polygons_box_b(polygons); - EXPECT_TRUE(polygons_box_b.contains(Point(0, 0))) << "Polygon box should contain origin, even though origin is outside of the original polygons."; - EXPECT_TRUE(polygons_box_b.contains(Point(-7, -7))) << "Polygon box should contain point that was inside of the original polygons."; - EXPECT_FALSE(polygons_box_b.contains(Point(12, 12))) << "Polygon box should not contain point outside of the AABB of the polygon."; + EXPECT_TRUE(polygons_box_b.contains(Point2LL(0, 0))) << "Polygon box should contain origin, even though origin is outside of the original polygons."; + EXPECT_TRUE(polygons_box_b.contains(Point2LL(-7, -7))) << "Polygon box should contain point that was inside of the original polygons."; + EXPECT_FALSE(polygons_box_b.contains(Point2LL(12, 12))) << "Polygon box should not contain point outside of the AABB of the polygon."; } TEST(AABBTest, TestConstructInverse) { - AABB inverse_box(Point(5, 10), Point(-10, -5)); + AABB inverse_box(Point2LL(5, 10), Point2LL(-10, -5)); - EXPECT_FALSE(inverse_box.contains(Point(0, 0))) << "'Inverse' box shouldn't contain anything."; + EXPECT_FALSE(inverse_box.contains(Point2LL(0, 0))) << "'Inverse' box shouldn't contain anything."; EXPECT_FALSE(inverse_box.contains(inverse_box.getMiddle())) << "'Inverse' box shouldn't contain anything, even it's own middle."; EXPECT_FALSE(inverse_box.hit(inverse_box)) << "'Inverse' boxes shouldn't intersect."; - inverse_box.include(Point(-5, -2)); - inverse_box.include(Point(2, 5)); + inverse_box.include(Point2LL(-5, -2)); + inverse_box.include(Point2LL(2, 5)); - EXPECT_TRUE(inverse_box.contains(Point(0, 0))) << "The previously 'inverse' box should now contain this point."; - EXPECT_FALSE(inverse_box.contains(Point(4, 8))) << "The previously 'inverse' box should now still not contain this point."; + EXPECT_TRUE(inverse_box.contains(Point2LL(0, 0))) << "The previously 'inverse' box should now contain this point."; + EXPECT_FALSE(inverse_box.contains(Point2LL(4, 8))) << "The previously 'inverse' box should now still not contain this point."; } TEST(AABBTest, TestContains) { - AABB box(Point(-10, -5), Point(5, 10)); + AABB box(Point2LL(-10, -5), Point2LL(5, 10)); - EXPECT_FALSE(box.contains(Point(-16, 16))) << "Box constructed from points shouldn't contain a point outside of the box."; - EXPECT_TRUE(box.contains(Point(3, 10))) << "Box constructed from points should contain a point on its edge."; - EXPECT_TRUE(box.contains(Point(5, 10))) << "Box constructed from points should contain its edge-points."; - EXPECT_TRUE(box.contains(Point(0, 0))) << "Box constructed from points should contain the origin."; + EXPECT_FALSE(box.contains(Point2LL(-16, 16))) << "Box constructed from points shouldn't contain a point outside of the box."; + EXPECT_TRUE(box.contains(Point2LL(3, 10))) << "Box constructed from points should contain a point on its edge."; + EXPECT_TRUE(box.contains(Point2LL(5, 10))) << "Box constructed from points should contain its edge-points."; + EXPECT_TRUE(box.contains(Point2LL(0, 0))) << "Box constructed from points should contain the origin."; } TEST(AABBTest, TestHit) { - AABB box_a(Point(-10, -5), Point(5, 10)); - AABB box_b(Point(4, 9), Point(12, 12)); - AABB box_c(Point(11, 11), Point(14, 14)); + AABB box_a(Point2LL(-10, -5), Point2LL(5, 10)); + AABB box_b(Point2LL(4, 9), Point2LL(12, 12)); + AABB box_c(Point2LL(11, 11), Point2LL(14, 14)); EXPECT_TRUE(box_a.hit(box_a)) << "Box should overlap itself."; @@ -92,8 +92,8 @@ TEST(AABBTest, TestHit) EXPECT_FALSE(box_a.hit(box_c)) << "These boxes should not overlap (case AC)."; EXPECT_FALSE(box_c.hit(box_a)) << "These boxes should not overlap (case CA)."; - AABB box_d(Point(3, 10), Point(12, 12)); - AABB box_e(Point(5, 10), Point(12, 12)); + AABB box_d(Point2LL(3, 10), Point2LL(12, 12)); + AABB box_e(Point2LL(5, 10), Point2LL(12, 12)); EXPECT_TRUE(box_a.hit(box_d)) << "Overlap-check is inclusive (case AD)."; EXPECT_TRUE(box_d.hit(box_a)) << "Overlap-check is inclusive (case DA)."; @@ -103,30 +103,30 @@ TEST(AABBTest, TestHit) TEST(AABBTest, TestGetMiddle) { - AABB box_a(Point(-10, -6), Point(6, 10)); - AABB box_b(Point(4, 10), Point(12, 12)); + AABB box_a(Point2LL(-10, -6), Point2LL(6, 10)); + AABB box_b(Point2LL(4, 10), Point2LL(12, 12)); - EXPECT_EQ(box_a.getMiddle(), Point(-2, 2)) << "The middle of the AABB should be this point (case A)."; - EXPECT_EQ(box_b.getMiddle(), Point(8, 11)) << "The middle of the AABB should be this point (case B)."; + EXPECT_EQ(box_a.getMiddle(), Point2LL(-2, 2)) << "The middle of the AABB should be this point (case A)."; + EXPECT_EQ(box_b.getMiddle(), Point2LL(8, 11)) << "The middle of the AABB should be this point (case B)."; } TEST(AABBTest, TestInclude) { - AABB box(Point(2, 2), Point(5, 10)); + AABB box(Point2LL(2, 2), Point2LL(5, 10)); - EXPECT_FALSE(box.contains(Point(1, 1))) << "The unexpanded (via include/point) box should not contain a point in the (future) expanded area."; + EXPECT_FALSE(box.contains(Point2LL(1, 1))) << "The unexpanded (via include/point) box should not contain a point in the (future) expanded area."; - box.include(Point(0, 0)); + box.include(Point2LL(0, 0)); - EXPECT_TRUE(box.contains(Point(1, 1))) << "The expanded (via include/point) box should contain a point in the expanded area."; - EXPECT_FALSE(box.contains(Point(6, 9))) << "The unexpanded (via include/other) box should not contain a point in the (future) expanded area."; + EXPECT_TRUE(box.contains(Point2LL(1, 1))) << "The expanded (via include/point) box should contain a point in the expanded area."; + EXPECT_FALSE(box.contains(Point2LL(6, 9))) << "The unexpanded (via include/other) box should not contain a point in the (future) expanded area."; - box.include(AABB(Point(7, 9), Point(8, 10))); + box.include(AABB(Point2LL(7, 9), Point2LL(8, 10))); - EXPECT_TRUE(box.contains(Point(6, 9))) << "The expanded (via include/other) box should contain a point in the expanded area."; + EXPECT_TRUE(box.contains(Point2LL(6, 9))) << "The expanded (via include/other) box should contain a point in the expanded area."; - const Point a(2, 2); - const Point b(5, 10); + const Point2LL a(2, 2); + const Point2LL b(5, 10); AABB box2(a, b); AABB empty; box2.include(empty); @@ -137,22 +137,22 @@ TEST(AABBTest, TestInclude) TEST(AABBTest, TestExpand) { - AABB box(Point(-10, -5), Point(5, 10)); + AABB box(Point2LL(-10, -5), Point2LL(5, 10)); - EXPECT_FALSE(box.contains(Point(6, 11))) << "Before expanding, the box shouldn't contain this point."; + EXPECT_FALSE(box.contains(Point2LL(6, 11))) << "Before expanding, the box shouldn't contain this point."; box.expand(2); - EXPECT_TRUE(box.contains(Point(6, 11))) << "After expanding, the box should contain this point."; + EXPECT_TRUE(box.contains(Point2LL(6, 11))) << "After expanding, the box should contain this point."; box.expand(-2); - EXPECT_FALSE(box.contains(Point(6, 11))) << "After shrinking, the box shouldn't contain this point anymore."; + EXPECT_FALSE(box.contains(Point2LL(6, 11))) << "After shrinking, the box shouldn't contain this point anymore."; } TEST(AABBTest, TestToPolygon) { - AABB box(Point(-10, -5), Point(5, 10)); + AABB box(Point2LL(-10, -5), Point2LL(5, 10)); Polygon polygon = box.toPolygon(); diff --git a/tests/utils/IntPointTest.cpp b/tests/utils/IntPointTest.cpp index ee2f2bbeef..1332e1b8db 100644 --- a/tests/utils/IntPointTest.cpp +++ b/tests/utils/IntPointTest.cpp @@ -1,7 +1,7 @@ // Copyright (c) 2022 Ultimaker B.V. // CuraEngine is released under the terms of the AGPLv3 or higher. -#include "utils/IntPoint.h" +#include "utils/Point2LL.h" #include // NOLINTBEGIN(*-magic-numbers) @@ -11,21 +11,21 @@ TEST(IntPointTest, TestRotationMatrix) { PointMatrix rot2d(90); Point3Matrix rot_homogeneous(rot2d); - Point a(20, 10); - Point b(30, 20); - Point translated = Point3Matrix::translate(-a).apply(b); - Point rotated = rot_homogeneous.apply(translated); - Point rotated_in_place = Point3Matrix::translate(a).apply(rotated); + Point2LL a(20, 10); + Point2LL b(30, 20); + Point2LL translated = Point3Matrix::translate(-a).apply(b); + Point2LL rotated = rot_homogeneous.apply(translated); + Point2LL rotated_in_place = Point3Matrix::translate(a).apply(rotated); Point3Matrix all_in_one = Point3Matrix::translate(a).compose(rot_homogeneous).compose(Point3Matrix::translate(-a)); - Point rotated_in_place_2 = all_in_one.apply(b); + Point2LL rotated_in_place_2 = all_in_one.apply(b); ASSERT_EQ(rotated_in_place, rotated_in_place_2) << "Matrix composition with translate and rotate failed."; } TEST(IntPointTest, TestSize) { - ASSERT_EQ(sizeof(Point::X), sizeof(coord_t)); + ASSERT_EQ(sizeof(Point2LL::X), sizeof(coord_t)); ASSERT_LE(sizeof(coord_t), sizeof(int64_t)); } diff --git a/tests/utils/LinearAlg2DTest.cpp b/tests/utils/LinearAlg2DTest.cpp index 5d471dff36..4593c4c57c 100644 --- a/tests/utils/LinearAlg2DTest.cpp +++ b/tests/utils/LinearAlg2DTest.cpp @@ -14,13 +14,13 @@ namespace cura */ struct GetDist2FromLineSegmentParameters { - Point line_start; - Point line_end; - Point point; + Point2LL line_start; + Point2LL line_end; + Point2LL point; coord_t actual_distance2; int16_t actual_is_beyond; - GetDist2FromLineSegmentParameters(Point line_start, Point line_end, Point point, coord_t actual_distance2, int16_t actual_is_beyond) + GetDist2FromLineSegmentParameters(Point2LL line_start, Point2LL line_end, Point2LL point, coord_t actual_distance2, int16_t actual_is_beyond) : line_start(line_start) , line_end(line_end) , point(point) @@ -46,9 +46,9 @@ class GetDist2FromLineSegmentTest : public testing::TestWithParam TEST_P(GetAngleTest, GetAngle) { const GetAngleParameters parameters = GetParam(); - const Point a = parameters.a; - const Point b = parameters.b; - const Point c = parameters.c; + const Point2LL a = parameters.a; + const Point2LL b = parameters.b; + const Point2LL c = parameters.c; const double angle_degrees = parameters.angle; const double angle = angle_degrees * std::numbers::pi / 180.0; @@ -140,37 +140,37 @@ TEST_P(GetAngleTest, GetAngle) INSTANTIATE_TEST_CASE_P(GetAngleInstantiation, GetAngleTest, - testing::Values(GetAngleParameters(Point(-100, 0), Point(0, 0), Point(100, 1), 180), // Almost straight line. - GetAngleParameters(Point(-100, 0), Point(0, 0), Point(100, 0), 180), // Completely straight line. - GetAngleParameters(Point(-100, 0), Point(0, 0), Point(-100, -100), 315), //-45 degrees. - GetAngleParameters(Point(-100, 0), Point(0, 0), Point(0, -100), 270), //-90 degrees. - GetAngleParameters(Point(-100, 0), Point(0, 0), Point(0, 100), 90), // Straight angle. - GetAngleParameters(Point(-100, 0), Point(0, 0), Point(-100, 1), 0), // Almost straight back. - GetAngleParameters(Point(-100, 0), Point(0, 0), Point(-100, -1), 360), // Almost straight back but the other way around. - GetAngleParameters(Point(-100, 0), Point(0, 0), Point(-100, 0), 0) // Completely straight back. + testing::Values(GetAngleParameters(Point2LL(-100, 0)Point2LLnt2LL(0, 0), Point2LL(100, Point2LL80), // Almost straight line. + GetAngleParametersPoint2LLt(-100, 0Point2LLt2LLnt(0, 0)Point2LLnt(100Point2LL 180), // Completely straight line. + Point2LLgleParameters(Point(-100, Point2LLt2LLint(0, 0Point2LLint(-100Point2LL0), 315), //-45 degrees. + GetAngleParameters(Point(-100Point2LLnt2LLoint(0, Point2LLoint(Point2LL00), 270)Point2LL90 degrees. + GetAngleParameters(Point(-Point2LLint2LL Point(0Point2LL Point2LL(0, 100), 90Point2LL Straight angle. + GetAngleParameters(Point(Point2LLt2LL0), Point(Point2LL, Point2LL(-100, 1), Point2LL/ Almost straight back. + GetAngleParameters(PointPoint2LLt2LL 0), PointPoint2LL), Point2LL(-100, -1)Point2LL), // Almost straight back but the other way around. + GetAngleParameters(Point2LLPoint2LL, 0), Point2LL(0, 0), Point(-100, 0), 0) // Completely straight back. )); TEST(GetAngleTest, GetAngleLeftAABTest) { - LinearAlg2D::getAngleLeft(Point(0, 0), Point(0, 0), Point(100, 0)); // Any output is allowed. Just don't crash! + LinearAlg2D::getAngleLeft(Point2LL(0, 0), Point2LL(0, 0), Point2LL(100, 0)); // Any output is allowed. Just don't crash! } TEST(GetAngleTest, GetAngleLeftABBTest) { - LinearAlg2D::getAngleLeft(Point(0, 0), Point(100, 0), Point(100, 100)); // Any output is allowed. Just don't crash! + LinearAlg2D::getAngleLeft(Point2LL(0, 0), Point2LL(100, 0), Point2LL(100, 100)); // Any output is allowed. Just don't crash! } TEST(GetAngleTest, GetAngleLeftAAATest) { - LinearAlg2D::getAngleLeft(Point(0, 0), Point(0, 0), Point(0, 0)); // Any output is allowed. Just don't crash! + LinearAlg2D::getAngleLeft(Point2LL(0, 0), Point2LL(0, 0), Point2LL(0, 0)); // Any output is allowed. Just don't crash! } TEST(PointIsLeftOfLineTest, LeftOfLine) { constexpr short actual = 1; - const Point p(0, 10); // ^ - const Point a(10, 0); // . | - const Point b(10, 20); // | + const Point2LL p(0, 10); // ^ + const Point2LL a(10, 0); // . | + const Point2LL b(10, 20); // | const coord_t supposed = LinearAlg2D::pointIsLeftOfLine(p, a, b); @@ -182,9 +182,9 @@ TEST(PointIsLeftOfLineTest, LeftOfLine) TEST(PointIsLeftOfLineTest, Sharp) { constexpr short actual = -1; - const Point p(3896, 3975); // ^ - const Point a(1599, 3975); // \ . - const Point b(200, 3996); // \ . + const Point2LL p(3896, 3975); // ^ + const Point2LL a(1599, 3975); // \ . + const Point2LL b(200, 3996); // \ . const coord_t supposed = LinearAlg2D::pointIsLeftOfLine(p, a, b); // FIXME: Clean-up message with ftm when CURA-8258 is implemented or when we use C++20 @@ -195,14 +195,14 @@ TEST(PointIsLeftOfLineTest, Sharp) // NOLINTBEGIN(misc-non-private-member-variables-in-classes) struct GetPointOnLineWithDistParameters { - Point p; - Point a; - Point b; + Point2LL p; + Point2LL a; + Point2LL b; coord_t dist; - Point actual_result; + Point2LL actual_result; bool actual_returned; - GetPointOnLineWithDistParameters(Point p, Point a, Point b, coord_t dist, Point actual_result, bool actual_returned) : p(p), a(a), b(b), dist(dist), actual_result(actual_result), actual_returned(actual_returned) + GetPointOnLineWithDistParameters(Point2LL p, Point2LL a, Point2LL b, coord_t dist, Point2LL actual_result, bool actual_returned) : p(p), a(a), b(b), dist(dist), actual_result(actual_result), actual_returned(actual_returned) { } }; @@ -219,14 +219,14 @@ class GetPointOnLineWithDistTest : public testing::TestWithParam TEST_P(RotateAroundTest, RotateAround) { const RotateAroundParameters parameters = GetParam(); - const Point point = parameters.point; - const Point origin = parameters.origin; + const Point2LL point = parameters.point; + const Point2LL origin = parameters.origin; const double angle = parameters.angle; - const Point actual_result = parameters.actual_result; + const Point2LL actual_result = parameters.actual_result; const Point3Matrix mat = LinearAlg2D::rotateAround(origin, angle); - const Point supposed_result = mat.apply(point); + const Point2LL supposed_result = mat.apply(point); ASSERT_LT(vSize(supposed_result - actual_result), 2) << "LinearAlg2D::rotateAround failed: Rotating " << point << " around " << origin << " for " << angle << " degrees resulted in " << supposed_result << " instead of expected " << actual_result << "."; } INSTANTIATE_TEST_SUITE_P(RotateAroundInstantiation, RotateAroundTest, - testing::Values(RotateAroundParameters(Point(25, 30), Point(10, 17), 90, Point(-3, 32)), // 90 degrees rotation. - RotateAroundParameters(Point(25, 30), Point(10, 17), -90, Point(23, 2)), //-90 degrees rotation. - RotateAroundParameters(Point(-67, 14), Point(50, 50), 0, Point(-67, 14)), // No rotation at all. - RotateAroundParameters(Point(-67, 14), Point(50, 50), 12, Point(-57, -9)) // 12 degrees rotation. Actually ends up at [-57, -9.5]! + testing::Values(RotateAroundParameters(Point2LL(25, 30), Point2LL(10, 17), 90, Point2LL(-3, 32)), // 90 degrees rotation. + RotateAroundParameters(Point2LL(25, 30), Point2LL(10, 17), -90, Point2LL(23, 2)), //-90 degrees rotation. + RotateAroundParameters(Point2LL(-67, 14), Point2LL(50, 50), 0, Point2LL(-67, 14)), // No rotation at all. + RotateAroundParameters(Point2LL(-67, 14), Point2LL(50, 50), 12, Point2LL(-57, -9)) // 12 degrees rotation. Actually ends up at [-57, -9.5]! )); class Temp {}; @@ -304,17 +304,17 @@ TEST(Temp, LineDistTests) std::srand(987); for (int z = 0; z < 100; ++z) { - const Point p{ 500000 + (std::rand() % 4000) - 2000, 500000 + (std::rand() % 4000) - 2000 }; + const Point2LL p{ 500000 + (std::rand() % 4000) - 2000, 500000 + (std::rand() % 4000) - 2000 }; const coord_t d = (std::rand() % 2000) - 1000 /2; const double rang = std::rand() / (static_cast(RAND_MAX) / 6.29); - const Point x{ p.X + static_cast(d * std::cos(rang)), p.Y - static_cast(d * std::sin(rang)) }; + const Point2LL x{ p.X + static_cast(d * std::cos(rang)), p.Y - static_cast(d * std::sin(rang)) }; // Use positive lengths here, so line and line-segment should give the same answers. coord_t len = std::rand() % 1000; - const Point a{ x.X + static_cast(len * std::sin(rang)), x.Y + static_cast(len * std::cos(rang)) }; + const Point2LL a{ x.X + static_cast(len * std::sin(rang)), x.Y + static_cast(len * std::cos(rang)) }; len = std::rand() % 1000; - const Point b{ x.X - static_cast(len * std::sin(rang)), x.Y - static_cast(len * std::cos(rang)) }; + const Point2LL b{ x.X - static_cast(len * std::sin(rang)), x.Y - static_cast(len * std::cos(rang)) }; const coord_t abs_d = std::abs(d); ASSERT_NEAR(LinearAlg2D::getDistFromLine(p, a, b), abs_d, 5); diff --git a/tests/utils/MinimumSpanningTreeTest.cpp b/tests/utils/MinimumSpanningTreeTest.cpp index 00b22d16fa..2b4b101fc8 100644 --- a/tests/utils/MinimumSpanningTreeTest.cpp +++ b/tests/utils/MinimumSpanningTreeTest.cpp @@ -9,7 +9,7 @@ // NOLINTBEGIN(*-magic-numbers) namespace cura { -bool has(const Point& pt, const std::vector& list) +bool has(const Point2LL& pt, const std::vector& list) { return std::find(list.begin(), list.end(), pt) != list.end(); } @@ -20,9 +20,9 @@ class MinimumSpanningTreeTest : public ::testing::Test void SetUp() override { pts = { - Point(-3, -4), Point(3, -4), Point(0, -3), Point(0, 0), Point(1, 1), Point(5, 1), Point(-1, 6), Point(0, 5), Point(5, 7), Point(12, 12), Point(12, 13), + Point2LL(-3, -4), Point2LL(3, -4), Point2LL(0, -3), Point2LL(0, 0), Point2LL(1, 1), Point2LL(5, 1), Point2LL(-1, 6), Point2LL(0, 5), Point2LL(5, 7), Point2LL(12, 12), Point2LL(12, 13), }; - std::vector pts_set(pts.begin(), pts.end()); + std::vector pts_set(pts.begin(), pts.end()); p_mst = new MinimumSpanningTree(pts_set); } @@ -32,13 +32,13 @@ class MinimumSpanningTreeTest : public ::testing::Test p_mst = nullptr; } - std::vector pts; + std::vector pts; MinimumSpanningTree* p_mst; // Needs to be a pointer, because SetUp isn't a constructor and the copy function is deleted. }; TEST(SimpleMinimumSpanningTreeTest, TestConstructEmpty) { - std::vector vertices; + std::vector vertices; MinimumSpanningTree tree(vertices); ASSERT_TRUE(tree.leaves().empty()) << "Empty tree should be empty."; @@ -46,26 +46,26 @@ TEST(SimpleMinimumSpanningTreeTest, TestConstructEmpty) TEST(SimpleMinimumSpanningTreeTest, TestConstructOne) { - const Point pt_a(1, 1); - std::vector vertices = { pt_a }; + const Point2LL pt_a(1, 1); + std::vector vertices = { pt_a }; MinimumSpanningTree tree(vertices); ASSERT_FALSE(tree.leaves().empty()) << "Tree with one point shouldn't have no vertices."; - std::vector points = tree.vertices(); + std::vector points = tree.vertices(); EXPECT_EQ(points.size(), 1) << "Tree with one point should have exactly one vertex."; EXPECT_EQ(points[0], pt_a) << "Tree with one point should have that point among its vertices."; } TEST(SimpleMinimumSpanningTreeTest, TestSimpleAdjacent) { - const Point pt_a(1, 1); - const Point pt_b(2, 2); - const Point pt_c(3, 3); - const Point pt_d(4, 4); - std::vector vertices = { pt_a, pt_b, pt_c, pt_d }; + const Point2LL pt_a(1, 1); + const Point2LL pt_b(2, 2); + const Point2LL pt_c(3, 3); + const Point2LL pt_d(4, 4); + std::vector vertices = { pt_a, pt_b, pt_c, pt_d }; MinimumSpanningTree tree(vertices); - std::vector adjacent; + std::vector adjacent; adjacent = tree.adjacentNodes(pt_b); EXPECT_EQ(adjacent.size(), 2) << "2 points should be adjacent to point B (simple case)."; @@ -79,20 +79,20 @@ TEST(SimpleMinimumSpanningTreeTest, TestSimpleAdjacent) EXPECT_TRUE(has(pt_c, adjacent)) << "Point C should be adjacent to Point D (simple case)."; EXPECT_FALSE(has(pt_d, adjacent)) << "Point D should not be adjacent to itself (simple case)."; - adjacent = tree.adjacentNodes(Point(5, 5)); // point E, a non-existent node + adjacent = tree.adjacentNodes(Point2LL(5, 5)); // point E, a non-existent node EXPECT_EQ(adjacent.size(), 0) << "No points should be adjacent to point E."; } TEST(SimpleMinimumSpanningTreeTest, TestSimpleLeaves) { - const Point pt_a(1, 1); - const Point pt_b(5, 2); - const Point pt_c(2, 5); - const Point pt_d(3, 3); - std::vector vertices = { pt_a, pt_b, pt_c, pt_d }; + const Point2LL pt_a(1, 1); + const Point2LL pt_b(5, 2); + const Point2LL pt_c(2, 5); + const Point2LL pt_d(3, 3); + std::vector vertices = { pt_a, pt_b, pt_c, pt_d }; MinimumSpanningTree tree(vertices); - std::vector leaves = tree.leaves(); + std::vector leaves = tree.leaves(); EXPECT_EQ(leaves.size(), 3) << "Three out of four points should be leaves (simple case)."; EXPECT_TRUE(has(pt_a, leaves)) << "Point A should be one of the leaves (simple case)."; EXPECT_TRUE(has(pt_b, leaves)) << "Point B should be one of the leaves (simple case)."; @@ -120,7 +120,7 @@ TEST_F(MinimumSpanningTreeTest, TestLeaves) // constexpr won't work here (yet) on Win. MinimumSpanningTree& mst = *p_mst; - const std::vector leaves = mst.leaves(); + const std::vector leaves = mst.leaves(); const size_t len = pts.size(); for (size_t i_pt = 0; i_pt < len; ++i_pt) diff --git a/tests/utils/PolygonConnectorTest.cpp b/tests/utils/PolygonConnectorTest.cpp index dc7c7b832e..b423d74d31 100644 --- a/tests/utils/PolygonConnectorTest.cpp +++ b/tests/utils/PolygonConnectorTest.cpp @@ -113,8 +113,8 @@ TEST_F(PolygonConnectorTest, getBridgeClosest) ASSERT_NE(bridge, std::nullopt) << "The two polygons are adjacent and spaced closely enough to bridge along their entire side, even with the slant."; - EXPECT_EQ(bridge->b_.from_point_, Point(1000, 200)) << "The closest connection is [1000,200] -> [1100,200]. There is no space to the right of that, so bridge B should be there."; - EXPECT_EQ(bridge->b_.to_point_, Point(1100, 200)) << "The closest connection is [1000,200] -> [1100,200]. There is no space to the right of that, so bridge B should be there."; + EXPECT_EQ(bridge->b_.from_point_, Point2LL(1000, 200)) << "The closest connection is [1000,200] -> [1100,200]. There is no space to the right of that, so bridge B should be there."; + EXPECT_EQ(bridge->b_.to_point_, Point2LL(1100, 200)) << "The closest connection is [1000,200] -> [1100,200]. There is no space to the right of that, so bridge B should be there."; EXPECT_GT(LinearAlg2D::pointIsLeftOfLine(bridge->a_.from_point_, bridge->b_.from_point_, bridge->b_.to_point_), 0) << "Connection A should be to the left of connection B."; EXPECT_GT(LinearAlg2D::pointIsLeftOfLine(bridge->a_.to_point_, bridge->b_.from_point_, bridge->b_.to_point_), 0) << "Connection A should be to the left of connection B."; } diff --git a/tests/utils/PolygonTest.cpp b/tests/utils/PolygonTest.cpp index a65298bb89..bdf84466e1 100644 --- a/tests/utils/PolygonTest.cpp +++ b/tests/utils/PolygonTest.cpp @@ -79,7 +79,7 @@ class PolygonTest : public testing::Test } void twoPolygonsAreEqual(Polygons& polygon1, Polygons& polygon2) const { - auto poly_cmp = [](const ClipperLib::Path& a, const ClipperLib::Path& b) { return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end(), [](const Point& p1, const Point& p2) { return p1 < p2; }); }; + auto poly_cmp = [](const ClipperLib::Path& a, const ClipperLib::Path& b) { return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end(), [](const Point2LL& p1, const Point2LL& p2) { return p1 < p2; }); }; std::sort(polygon1.begin(), polygon1.end(), poly_cmp); std::sort(polygon2.begin(), polygon2.end(), poly_cmp); @@ -121,7 +121,7 @@ TEST_F(PolygonTest, polygonOffsetBugTest) for (const ConstPolygonRef poly : offsetted) { - for (const Point& p : poly) + for (const Point2LL& p : poly) { ASSERT_TRUE(polys.inside(p)) << "A negative offset should move the point towards the inside!"; } @@ -133,32 +133,32 @@ TEST_F(PolygonTest, isOutsideTest) Polygons test_triangle; test_triangle.add(triangle); - EXPECT_FALSE(test_triangle.inside(Point(0, 100))) << "Left point should be outside the triangle."; - EXPECT_FALSE(test_triangle.inside(Point(100, 100))) << "Middle left point should be outside the triangle."; - EXPECT_FALSE(test_triangle.inside(Point(300, 100))) << "Middle right point should be outside the triangle."; - EXPECT_FALSE(test_triangle.inside(Point(500, 100))) << "Right point should be outside the triangle."; - EXPECT_FALSE(test_triangle.inside(Point(100, 200))) << "Above point should be outside the triangle."; - EXPECT_FALSE(test_triangle.inside(Point(100, -100))) << "Below point should be outside the triangle."; + EXPECT_FALSE(test_triangle.inside(Point2LL(0, 100))) << "Left point should be outside the triangle."; + EXPECT_FALSE(test_triangle.inside(Point2LL(100, 100))) << "Middle left point should be outside the triangle."; + EXPECT_FALSE(test_triangle.inside(Point2LL(300, 100))) << "Middle right point should be outside the triangle."; + EXPECT_FALSE(test_triangle.inside(Point2LL(500, 100))) << "Right point should be outside the triangle."; + EXPECT_FALSE(test_triangle.inside(Point2LL(100, 200))) << "Above point should be outside the triangle."; + EXPECT_FALSE(test_triangle.inside(Point2LL(100, -100))) << "Below point should be outside the triangle."; } TEST_F(PolygonTest, isInsideTest) { Polygons test_polys; PolygonRef poly = test_polys.newPoly(); - poly.add(Point(82124, 98235)); - poly.add(Point(83179, 98691)); - poly.add(Point(83434, 98950)); - poly.add(Point(82751, 99026)); - poly.add(Point(82528, 99019)); - poly.add(Point(81605, 98854)); - poly.add(Point(80401, 98686)); - poly.add(Point(79191, 98595)); - poly.add(Point(78191, 98441)); - poly.add(Point(78998, 98299)); - poly.add(Point(79747, 98179)); - poly.add(Point(80960, 98095)); - - EXPECT_TRUE(test_polys.inside(Point(78315, 98440))) << "Point should be inside the polygons!"; + poly.add(Point2LL(82124, 98235)); + poly.add(Point2LL(83179, 98691)); + poly.add(Point2LL(83434, 98950)); + poly.add(Point2LL(82751, 99026)); + poly.add(Point2LL(82528, 99019)); + poly.add(Point2LL(81605, 98854)); + poly.add(Point2LL(80401, 98686)); + poly.add(Point2LL(79191, 98595)); + poly.add(Point2LL(78191, 98441)); + poly.add(Point2LL(78998, 98299)); + poly.add(Point2LL(79747, 98179)); + poly.add(Point2LL(80960, 98095)); + + EXPECT_TRUE(test_polys.inside(Point2LL(78315, 98440))) << "Point should be inside the polygons!"; } TEST_F(PolygonTest, isOnBorderTest) @@ -166,10 +166,10 @@ TEST_F(PolygonTest, isOnBorderTest) Polygons test_triangle; test_triangle.add(triangle); - EXPECT_FALSE(test_triangle.inside(Point(200, 0), false)) << "Point is on the bottom edge of the triangle."; - EXPECT_TRUE(test_triangle.inside(Point(200, 0), true)) << "Point is on the bottom edge of the triangle."; - EXPECT_FALSE(test_triangle.inside(Point(150, 50), false)) << "Point is on a diagonal side of the triangle."; - EXPECT_TRUE(test_triangle.inside(Point(150, 50), true)) << "Point is on a diagonal side of the triangle."; + EXPECT_FALSE(test_triangle.inside(Point2LL(200, 0), false)) << "Point is on the bottom edge of the triangle."; + EXPECT_TRUE(test_triangle.inside(Point2LL(200, 0), true)) << "Point is on the bottom edge of the triangle."; + EXPECT_FALSE(test_triangle.inside(Point2LL(150, 50), false)) << "Point is on a diagonal side of the triangle."; + EXPECT_TRUE(test_triangle.inside(Point2LL(150, 50), true)) << "Point is on a diagonal side of the triangle."; } TEST_F(PolygonTest, DISABLED_isInsideLineTest) // Disabled because this fails due to a bug in Clipper. @@ -177,8 +177,8 @@ TEST_F(PolygonTest, DISABLED_isInsideLineTest) // Disabled because this fails du Polygons polys; polys.add(line); - EXPECT_FALSE(polys.inside(Point(50, 0), false)) << "Should be outside since it is on the border and border is considered outside."; - EXPECT_TRUE(polys.inside(Point(50, 0), true)) << "Should be inside since it is on the border and border is considered inside."; + EXPECT_FALSE(polys.inside(Point2LL(50, 0), false)) << "Should be outside since it is on the border and border is considered outside."; + EXPECT_TRUE(polys.inside(Point2LL(50, 0), true)) << "Should be inside since it is on the border and border is considered inside."; } TEST_F(PolygonTest, splitIntoPartsWithHoleTest) @@ -207,8 +207,8 @@ TEST_F(PolygonTest, differenceClockwiseTest) for (size_t point_index = 0; point_index < outer.size(); point_index++) { const size_t next_index = (point_index + 1) % outer.size(); - const Point point = outer[point_index]; - const Point next = outer[next_index]; + const Point2LL point = outer[point_index]; + const Point2LL next = outer[next_index]; area += (next.X - point.X) * (point.Y + next.Y); } EXPECT_LT(area, 0) << "Outer polygon should be counter-clockwise."; @@ -218,8 +218,8 @@ TEST_F(PolygonTest, differenceClockwiseTest) for (size_t point_index = 0; point_index < inner.size(); point_index++) { const size_t next_index = (point_index + 1) % inner.size(); - const Point point = inner[point_index]; - const Point next = inner[next_index]; + const Point2LL point = inner[point_index]; + const Point2LL next = inner[next_index]; area += (next.X - point.X) * (point.Y + next.Y); } EXPECT_GT(area, 0) << "Inner polygon should be clockwise."; @@ -244,18 +244,18 @@ TEST_F(PolygonTest, convexTestCube) { Polygons d_polygons; PolygonRef d = d_polygons.newPoly(); - d.add(Point(0, 0)); - d.add(Point(10, 0)); - d.add(Point(10, 10)); - d.add(Point(0, 10)); + d.add(Point2LL(0, 0)); + d.add(Point2LL(10, 0)); + d.add(Point2LL(10, 10)); + d.add(Point2LL(0, 10)); d_polygons.makeConvex(); EXPECT_EQ(d.size(), 4); - EXPECT_EQ(d[0], Point(0, 0)); - EXPECT_EQ(d[1], Point(10, 0)); - EXPECT_EQ(d[2], Point(10, 10)); - EXPECT_EQ(d[3], Point(0, 10)); + EXPECT_EQ(d[0], Point2LL(0, 0)); + EXPECT_EQ(d[1], Point2LL(10, 0)); + EXPECT_EQ(d[2], Point2LL(10, 10)); + EXPECT_EQ(d[3], Point2LL(0, 10)); } /* @@ -274,11 +274,11 @@ TEST_F(PolygonTest, convexHullStar) { coord_t x_outer = -std::cos(angle_step * i) * outer_radius; coord_t y_outer = -std::sin(angle_step * i) * outer_radius; - d.add(Point(x_outer, y_outer)); + d.add(Point2LL(x_outer, y_outer)); coord_t x_inner = -std::cos(angle_step * (i + 0.5)) * inner_radius; coord_t y_inner = -std::sin(angle_step * (i + 0.5)) * inner_radius; - d.add(Point(x_inner, y_inner)); + d.add(Point2LL(x_inner, y_inner)); } d_polygons.makeConvex(); @@ -289,7 +289,7 @@ TEST_F(PolygonTest, convexHullStar) double angle = angle_step * i; coord_t x = -std::cos(angle) * outer_radius; coord_t y = -std::sin(angle) * outer_radius; - EXPECT_EQ(d[i], Point(x, y)); + EXPECT_EQ(d[i], Point2LL(x, y)); } } @@ -301,10 +301,10 @@ TEST_F(PolygonTest, convexHullMultipleMinX) { Polygons d_polygons; PolygonRef d = d_polygons.newPoly(); - d.add(Point(0, 0)); - d.add(Point(0, -10)); - d.add(Point(10, 0)); - d.add(Point(0, 10)); + d.add(Point2LL(0, 0)); + d.add(Point2LL(0, -10)); + d.add(Point2LL(10, 0)); + d.add(Point2LL(0, 10)); /* * x\ x\ @@ -327,22 +327,22 @@ TEST_F(PolygonTest, convexTestCubeColinear) { Polygons d_polygons; PolygonRef d = d_polygons.newPoly(); - d.add(Point(0, 0)); - d.add(Point(5, 0)); - d.add(Point(10, 0)); - d.add(Point(10, 5)); - d.add(Point(10, 10)); - d.add(Point(5, 10)); - d.add(Point(0, 10)); - d.add(Point(0, 5)); + d.add(Point2LL(0, 0)); + d.add(Point2LL(5, 0)); + d.add(Point2LL(10, 0)); + d.add(Point2LL(10, 5)); + d.add(Point2LL(10, 10)); + d.add(Point2LL(5, 10)); + d.add(Point2LL(0, 10)); + d.add(Point2LL(0, 5)); d_polygons.makeConvex(); EXPECT_EQ(d.size(), 4); - EXPECT_EQ(d[0], Point(0, 0)); - EXPECT_EQ(d[1], Point(10, 0)); - EXPECT_EQ(d[2], Point(10, 10)); - EXPECT_EQ(d[3], Point(0, 10)); + EXPECT_EQ(d[0], Point2LL(0, 0)); + EXPECT_EQ(d[1], Point2LL(10, 0)); + EXPECT_EQ(d[2], Point2LL(10, 10)); + EXPECT_EQ(d[3], Point2LL(0, 10)); } /* @@ -352,22 +352,22 @@ TEST_F(PolygonTest, convexHullRemoveDuplicatePoints) { Polygons d_polygons; PolygonRef d = d_polygons.newPoly(); - d.add(Point(0, 0)); - d.add(Point(0, 0)); - d.add(Point(10, 0)); - d.add(Point(10, 0)); - d.add(Point(10, 10)); - d.add(Point(10, 10)); - d.add(Point(0, 10)); - d.add(Point(0, 10)); + d.add(Point2LL(0, 0)); + d.add(Point2LL(0, 0)); + d.add(Point2LL(10, 0)); + d.add(Point2LL(10, 0)); + d.add(Point2LL(10, 10)); + d.add(Point2LL(10, 10)); + d.add(Point2LL(0, 10)); + d.add(Point2LL(0, 10)); d_polygons.makeConvex(); EXPECT_EQ(d.size(), 4); - EXPECT_EQ(d[0], Point(0, 0)); - EXPECT_EQ(d[1], Point(10, 0)); - EXPECT_EQ(d[2], Point(10, 10)); - EXPECT_EQ(d[3], Point(0, 10)); + EXPECT_EQ(d[0], Point2LL(0, 0)); + EXPECT_EQ(d[1], Point2LL(10, 0)); + EXPECT_EQ(d[2], Point2LL(10, 10)); + EXPECT_EQ(d[3], Point2LL(0, 10)); } /* @@ -378,7 +378,7 @@ TEST_F(PolygonTest, removeSmallAreas_simple) { // basic set of polygons auto test_square_2 = test_square; - test_square_2.translate(Point(0, 500)); + test_square_2.translate(Point2LL(0, 500)); auto d_polygons = Polygons{}; d_polygons.add(test_square); d_polygons.add(test_square_2); @@ -403,11 +403,11 @@ TEST_F(PolygonTest, removeSmallAreas_small_area) { // make some areas. auto small_area_1 = small_area; // Area = 100 micron^2 = 1e-4 mm^2 - small_area_1.translate(Point(350, 450)); + small_area_1.translate(Point2LL(350, 450)); auto small_area_2 = small_area; - small_area_2.translate(Point(450, 350)); + small_area_2.translate(Point2LL(450, 350)); auto triangle_1 = triangle; // area = 10000 micron^2 = 1e-2 mm^2 - triangle_1.translate(Point(50, 0)); + triangle_1.translate(Point2LL(50, 0)); // add areas to polygons auto d_polygons = Polygons{}; @@ -441,7 +441,7 @@ TEST_F(PolygonTest, removeSmallAreas_hole) // make some areas. auto small_hole_1 = small_area; // Area = 100 micron^2 = 1e-4 mm^2 small_hole_1.reverse(); - small_hole_1.translate(Point(10, 10)); + small_hole_1.translate(Point2LL(10, 10)); // add areas to polygons auto d_polygons = Polygons{}; @@ -472,14 +472,14 @@ TEST_F(PolygonTest, removeSmallAreas_hole_2) auto small_hole_1 = small_area; // Area = 100 micron^2 = 1e-4 mm^2 small_hole_1.reverse(); auto small_hole_2 = small_hole_1; - small_hole_1.translate(Point(10, 10)); - small_hole_2.translate(Point(160, 160)); + small_hole_1.translate(Point2LL(10, 10)); + small_hole_2.translate(Point2LL(160, 160)); auto med_square_1 = Polygon{}; // area = 2500 micron^2 = 2.5e-3 mm^2 - med_square_1.add(Point(0, 0)); - med_square_1.add(Point(50, 0)); - med_square_1.add(Point(50, 50)); - med_square_1.add(Point(0, 50)); - med_square_1.translate(Point(150, 150)); + med_square_1.add(Point2LL(0, 0)); + med_square_1.add(Point2LL(50, 0)); + med_square_1.add(Point2LL(50, 50)); + med_square_1.add(Point2LL(0, 50)); + med_square_1.translate(Point2LL(150, 150)); // add areas to polygons auto d_polygons = Polygons{}; @@ -516,16 +516,16 @@ TEST_F(PolygonTest, removeSmallAreas_complex) { // make some areas. auto small_area_1 = small_area; // Area = 100 micron^2 = 1e-4 mm^2 - small_area_1.translate(Point(350, 450)); + small_area_1.translate(Point2LL(350, 450)); auto small_area_2 = small_area; - small_area_2.translate(Point(450, 350)); + small_area_2.translate(Point2LL(450, 350)); auto small_hole_1 = small_area; // Area = 100 micron^2 = 1e-4 mm^2 small_hole_1.reverse(); auto small_hole_2 = small_hole_1; - small_hole_1.translate(Point(3, 3)); - small_hole_2.translate(Point(22, 50)); + small_hole_1.translate(Point2LL(3, 3)); + small_hole_2.translate(Point2LL(22, 50)); auto triangle_1 = triangle; // area = 10000 micron^2 = 1e-2 mm^2 - triangle_1.translate(Point(600, 0)); + triangle_1.translate(Point2LL(600, 0)); // add areas to polygons auto d_polygons = Polygons{}; diff --git a/tests/utils/PolygonUtilsTest.cpp b/tests/utils/PolygonUtilsTest.cpp index b8b5226910..04f668cab2 100644 --- a/tests/utils/PolygonUtilsTest.cpp +++ b/tests/utils/PolygonUtilsTest.cpp @@ -3,7 +3,7 @@ #include "utils/polygonUtils.h" // The class under test. #include "utils/Coord_t.h" -#include "utils/IntPoint.h" // Creating and testing with points. +#include "utils/Point2LL.h" // Creating and testing with points. #include "utils/polygon.h" // Creating polygons to test with. #include @@ -13,11 +13,11 @@ namespace cura struct MoveInsideParameters { - Point close_to; + Point2LL close_to; coord_t distance; - Point supposed; + Point2LL supposed; - MoveInsideParameters(Point close_to, const coord_t distance, Point supposed) : close_to(close_to), distance(distance), supposed(supposed) + MoveInsideParameters(Point2LL close_to, const coord_t distance, Point2LL supposed) : close_to(close_to), distance(distance), supposed(supposed) { } }; @@ -52,7 +52,7 @@ TEST_P(MoveInsideTest, MoveInside) { const MoveInsideParameters parameters = GetParam(); const ClosestPolygonPoint cpp = PolygonUtils::findClosest(parameters.close_to, test_square); - Point result = PolygonUtils::moveInside(cpp, parameters.distance); + Point2LL result = PolygonUtils::moveInside(cpp, parameters.distance); // FIXME: Clean-up message with ftm when CURA-8258 is implemented or when we use C++20 ASSERT_LE(vSize(result - parameters.supposed), 10) << parameters.close_to << " moved with " << parameters.distance << " micron inside to " << result << " rather than " << parameters.supposed << ".\n" @@ -65,32 +65,32 @@ TEST_P(MoveInsideTest, MoveInside2) const MoveInsideParameters parameters = GetParam(); Polygons polys; polys.add(test_square); - Point result = parameters.close_to; + Point2LL result = parameters.close_to; PolygonUtils::moveInside2(polys, result, parameters.distance); ASSERT_LE(vSize(result - parameters.supposed), 10) << parameters.close_to << " moved with " << parameters.distance << " micron inside to " << result << "rather than " << parameters.supposed << "."; } INSTANTIATE_TEST_SUITE_P(MoveInsideInstantiation, MoveInsideTest, - testing::Values(MoveInsideParameters(Point(110, 110), 28, Point(80, 80)), // Near a corner, moving inside. - MoveInsideParameters(Point(50, 110), 20, Point(50, 80)), // Near an edge, moving inside. - MoveInsideParameters(Point(110, 110), -28, Point(120, 120)), // Near a corner, moving outside. - MoveInsideParameters(Point(50, 110), -20, Point(50, 120)), // Near an edge, moving outside. - MoveInsideParameters(Point(110, 105), 28, Point(80, 80)), // Near a corner but not exactly diagonal. - MoveInsideParameters(Point(100, 50), 20, Point(80, 50)), // Starting on the border. - MoveInsideParameters(Point(80, 50), 20, Point(80, 50)), // Already inside. - MoveInsideParameters(Point(110, 50), 0, Point(100, 50)), // Not keeping any distance from the border. - MoveInsideParameters(Point(110, 50), 100000, Point(-99900, 50)) // A very far move. + testing::Values(MoveInsideParameters(Point2LL(110, 110), 28, Point2LL(80, 80)), // Near a corner, moving inside. + MoveInsideParameters(Point2LL(50, 110), 20, Point2LL(50, 80)), // Near an edge, moving inside. + MoveInsideParameters(Point2LL(110, 110), -28, Point2LL(120, 120)), // Near a corner, moving outside. + MoveInsideParameters(Point2LL(50, 110), -20, Point2LL(50, 120)), // Near an edge, moving outside. + MoveInsideParameters(Point2LL(110, 105), 28, Point2LL(80, 80)), // Near a corner but not exactly diagonal. + MoveInsideParameters(Point2LL(100, 50), 20, Point2LL(80, 50)), // Starting on the border. + MoveInsideParameters(Point2LL(80, 50), 20, Point2LL(80, 50)), // Already inside. + MoveInsideParameters(Point2LL(110, 50), 0, Point2LL(100, 50)), // Not keeping any distance from the border. + MoveInsideParameters(Point2LL(110, 50), 100000, Point2LL(-99900, 50)) // A very far move. )); TEST_F(MoveInsideTest, cornerEdgeTest) { - const Point close_to(110, 100); - const Point supposed1(80, 80); // Allow two possible values here, since the behaviour for this edge case is not specified. - const Point supposed2(72, 100); + const Point2LL close_to(110, 100); + const Point2LL supposed1(80, 80); // Allow two possible values here, since the behaviour for this edge case is not specified. + const Point2LL supposed2(72, 100); constexpr coord_t distance = 28; const ClosestPolygonPoint cpp = PolygonUtils::findClosest(close_to, test_square); - const Point result = PolygonUtils::moveInside(cpp, distance); + const Point2LL result = PolygonUtils::moveInside(cpp, distance); constexpr coord_t maximum_error = 10; @@ -103,14 +103,14 @@ TEST_F(MoveInsideTest, cornerEdgeTest) TEST_F(MoveInsideTest, middleTest) { - const Point close_to(50, 50); - const Point supposed1(80, 50); // Allow four possible values here, since the behaviour for this edge case is not specified. - const Point supposed2(50, 80); - const Point supposed3(20, 50); - const Point supposed4(50, 20); + const Point2LL close_to(50, 50); + const Point2LL supposed1(80, 50); // Allow four possible values here, since the behaviour for this edge case is not specified. + const Point2LL supposed2(50, 80); + const Point2LL supposed3(20, 50); + const Point2LL supposed4(50, 20); constexpr coord_t distance = 20; const ClosestPolygonPoint cpp = PolygonUtils::findClosest(close_to, test_square); - const Point result = PolygonUtils::moveInside(cpp, distance); + const Point2LL result = PolygonUtils::moveInside(cpp, distance); constexpr coord_t maximum_error = 10; @@ -124,12 +124,12 @@ TEST_F(MoveInsideTest, middleTest) TEST_F(MoveInsideTest, middleTestPenalty) { - const Point close_to(50, 50); - const Point supposed(80, 50); - const Point preferred_dir(120, 60); + const Point2LL close_to(50, 50); + const Point2LL supposed(80, 50); + const Point2LL preferred_dir(120, 60); constexpr coord_t distance = 20; - const ClosestPolygonPoint cpp = PolygonUtils::findClosest(close_to, test_square, [preferred_dir](Point candidate) { return vSize2(candidate - preferred_dir); }); - const Point result = PolygonUtils::moveInside(cpp, distance); + const ClosestPolygonPoint cpp = PolygonUtils::findClosest(close_to, test_square, [preferred_dir](Point2LL candidate) { return vSize2(candidate - preferred_dir); }); + const Point2LL result = PolygonUtils::moveInside(cpp, distance); // FIXME: Clean-up message with ftm when CURA-8258 is implemented or when we use C++20 ASSERT_LE(vSize(result - supposed), 10) << close_to << " moved with " << distance << " micron inside to " << result << " rather than " << supposed << ".\n" @@ -139,13 +139,13 @@ TEST_F(MoveInsideTest, middleTestPenalty) TEST_F(MoveInsideTest, cornerEdgeTest2) { - const Point close_to(110, 100); - const Point supposed1(80, 80); // Allow two possible values here, since the behaviour for this edge case is not specified. - const Point supposed2(72, 100); + const Point2LL close_to(110, 100); + const Point2LL supposed1(80, 80); // Allow two possible values here, since the behaviour for this edge case is not specified. + const Point2LL supposed2(72, 100); constexpr coord_t distance = 28; Polygons polys; polys.add(test_square); - Point result = close_to; + Point2LL result = close_to; PolygonUtils::moveInside2(polys, result, distance); constexpr coord_t maximum_error = 10; @@ -155,8 +155,8 @@ TEST_F(MoveInsideTest, cornerEdgeTest2) TEST_F(MoveInsideTest, pointyCorner) { - const Point from(55, 100); // Above pointy bit. - Point result(from); + const Point2LL from(55, 100); // Above pointy bit. + Point2LL result(from); Polygons inside; inside.add(pointy_square); ClosestPolygonPoint cpp = PolygonUtils::ensureInsideOrOutside(inside, result, 10); @@ -169,8 +169,8 @@ TEST_F(MoveInsideTest, pointyCorner) TEST_F(MoveInsideTest, pointyCornerFail) { // Should fail with normal moveInside2 (and the like). - const Point from(55, 170); // Above pointy bit. - Point result(from); + const Point2LL from(55, 170); // Above pointy bit. + Point2LL result(from); Polygons inside; inside.add(pointy_square); @@ -182,9 +182,9 @@ TEST_F(MoveInsideTest, pointyCornerFail) TEST_F(MoveInsideTest, outsidePointyCorner) { - const Point from(60, 70); // Above pointy bit. - Point result(from); - const Point supposed(50, 70); // 10 below pointy bit. + const Point2LL from(60, 70); // Above pointy bit. + Point2LL result(from); + const Point2LL supposed(50, 70); // 10 below pointy bit. Polygons inside; inside.add(pointy_square); @@ -197,9 +197,9 @@ TEST_F(MoveInsideTest, outsidePointyCorner) TEST_F(MoveInsideTest, outsidePointyCornerFail) { // Should fail with normal moveInside2 (and the like). - const Point from(60, 70); // Above pointy bit. - Point result(from); - const Point supposed(50, 70); // 10 below pointy bit. + const Point2LL from(60, 70); // Above pointy bit. + Point2LL result(from); + const Point2LL supposed(50, 70); // 10 below pointy bit. Polygons inside; inside.add(pointy_square); @@ -211,12 +211,12 @@ TEST_F(MoveInsideTest, outsidePointyCornerFail) struct FindCloseParameters { - Point close_to; - Point supposed; + Point2LL close_to; + Point2LL supposed; coord_t cell_size; std::function* penalty_function; - FindCloseParameters(const Point close_to, const Point supposed, const coord_t cell_size, std::function* penalty_function = nullptr) + FindCloseParameters(const Point2LL close_to, const Point2LL supposed, const coord_t cell_size, std::function* penalty_function = nullptr) : close_to(close_to) , supposed(supposed) , cell_size(cell_size) @@ -260,7 +260,7 @@ TEST_P(FindCloseTest, FindClose) if (cpp) { - const Point result = cpp->location; + const Point2LL result = cpp->location; ASSERT_LE(vSize(result - parameters.supposed), 10) << "Close to " << parameters.close_to << " we found " << result << " rather than " << parameters.supposed << ".\n"; } else @@ -273,16 +273,16 @@ TEST_P(FindCloseTest, FindClose) * Test penalty function to use with findClose. */ std::function testPenalty( - [](Point candidate) + [](Point2LL candidate) { - return -vSize2(candidate - Point(50, 100)); // The further from 50, 100, the lower the penalty. + return -vSize2(candidate - Point2LL(50, 100)); // The further from 50, 100, the lower the penalty. }); INSTANTIATE_TEST_SUITE_P(FindCloseInstantiation, FindCloseTest, - testing::Values(FindCloseParameters(Point(110, 110), Point(100, 100), 15), // Near a corner. - FindCloseParameters(Point(50, 110), Point(50, 100), 15), // Near a side. - FindCloseParameters(Point(50, 50), Point(50, 0), 60, &testPenalty) // Using a penalty function. + testing::Values(FindCloseParameters(Point2LL(110, 110), Point2LL(100, 100), 15), // Near a corner. + FindCloseParameters(Point2LL(50, 110), Point2LL(50, 100), 15), // Near a side. + FindCloseParameters(Point2LL(50, 50), Point2LL(50, 0), 60, &testPenalty) // Using a penalty function. )); // NOLINTBEGIN(misc-non-private-member-variables-in-classes) @@ -319,9 +319,9 @@ class PolygonUtilsTest : public testing::Test TEST_F(PolygonUtilsTest, spreadDotsSegment) { std::vector supposed; - supposed.emplace_back(Point(50, 0), 0, test_squares[0], 0); - supposed.emplace_back(Point(100, 0), 1, test_squares[0], 0); - supposed.emplace_back(Point(100, 50), 1, test_squares[0], 0); + supposed.emplace_back(Point2LL(50, 0), 0, test_squares[0], 0); + supposed.emplace_back(Point2LL(100, 0), 1, test_squares[0], 0); + supposed.emplace_back(Point2LL(100, 50), 1, test_squares[0], 0); std::vector result; PolygonUtils::spreadDots(PolygonsPointIndex(&test_squares, 0, 0), PolygonsPointIndex(&test_squares, 0, 2), 3, result); @@ -336,14 +336,14 @@ TEST_F(PolygonUtilsTest, spreadDotsSegment) TEST_F(PolygonUtilsTest, spreadDotsFull) { std::vector supposed; - supposed.emplace_back(Point(0, 0), 0, test_squares[0], 0); - supposed.emplace_back(Point(50, 0), 0, test_squares[0], 0); - supposed.emplace_back(Point(100, 0), 1, test_squares[0], 0); - supposed.emplace_back(Point(100, 50), 1, test_squares[0], 0); - supposed.emplace_back(Point(100, 100), 2, test_squares[0], 0); - supposed.emplace_back(Point(50, 100), 2, test_squares[0], 0); - supposed.emplace_back(Point(0, 100), 3, test_squares[0], 0); - supposed.emplace_back(Point(0, 50), 3, test_squares[0], 0); + supposed.emplace_back(Point2LL(0, 0), 0, test_squares[0], 0); + supposed.emplace_back(Point2LL(50, 0), 0, test_squares[0], 0); + supposed.emplace_back(Point2LL(100, 0), 1, test_squares[0], 0); + supposed.emplace_back(Point2LL(100, 50), 1, test_squares[0], 0); + supposed.emplace_back(Point2LL(100, 100), 2, test_squares[0], 0); + supposed.emplace_back(Point2LL(50, 100), 2, test_squares[0], 0); + supposed.emplace_back(Point2LL(0, 100), 3, test_squares[0], 0); + supposed.emplace_back(Point2LL(0, 50), 3, test_squares[0], 0); std::vector result; PolygonUtils::spreadDots(PolygonsPointIndex(&test_squares, 0, 0), PolygonsPointIndex(&test_squares, 0, 0), 8, result); @@ -357,13 +357,13 @@ TEST_F(PolygonUtilsTest, spreadDotsFull) struct GetNextParallelIntersectionParameters { - std::optional predicted; - Point start_point; - Point line_to; + std::optional predicted; + Point2LL start_point; + Point2LL line_to; bool forward; coord_t dist; - GetNextParallelIntersectionParameters(const std::optional predicted, const Point start_point, const Point line_to, const bool forward, const coord_t dist) + GetNextParallelIntersectionParameters(const std::optional predicted, const Point2LL start_point, const Point2LL line_to, const bool forward, const coord_t dist) : predicted(predicted) , start_point(start_point) , line_to(line_to) @@ -405,16 +405,16 @@ TEST_P(GetNextParallelIntersectionTest, GetNextParallelIntersection) INSTANTIATE_TEST_SUITE_P(GetNextParallelIntersectionInstantiation, GetNextParallelIntersectionTest, - testing::Values(GetNextParallelIntersectionParameters(Point(0, 40), Point(20, 100), Point(150, 200), true, 35), - GetNextParallelIntersectionParameters(Point(37, 100), Point(80, 100), Point(150, 200), true, 35), - GetNextParallelIntersectionParameters(Point(70, 100), Point(20, 100), Point(120, 200), false, 35), - GetNextParallelIntersectionParameters(Point(0, 0), Point(50, 100), Point(150, 200), true, 35), - GetNextParallelIntersectionParameters(Point(60, 0), Point(10, 0), Point(-90, -100), true, 35), - GetNextParallelIntersectionParameters(Point(0, 40), Point(10, 0), Point(-90, -100), false, 35), - GetNextParallelIntersectionParameters(Point(0, 75), Point(50, 100), Point(150, 100), true, 25), - GetNextParallelIntersectionParameters(Point(25, 100), Point(50, 100), Point(50, 200), true, 25), - GetNextParallelIntersectionParameters(std::optional(), Point(100, 100), Point(200, 200), true, 80), - GetNextParallelIntersectionParameters(Point(0, 45), Point(5, 100), Point(105, 200), true, 35))); + testing::Values(GetNextParallelIntersectionParameters(Point2LL(0, 40), Point2LL(20, 100), Point2LL(150, 200), true, 35), + GetNextParallelIntersectionParameters(Point2LL(37, 100), Point2LL(80, 100), Point2LL(150, 200), true, 35), + GetNextParallelIntersectionParameters(Point2LL(70, 100), Point2LL(20, 100), Point2LL(120, 200), false, 35), + GetNextParallelIntersectionParameters(Point2LL(0, 0), Point2LL(50, 100), Point2LL(150, 200), true, 35), + GetNextParallelIntersectionParameters(Point2LL(60, 0), Point2LL(10, 0), Point2LL(-90, -100), true, 35), + GetNextParallelIntersectionParameters(Point2LL(0, 40), Point2LL(10, 0), Point2LL(-90, -100), false, 35), + GetNextParallelIntersectionParameters(Point2LL(0, 75), Point2LL(50, 100), Point2LL(150, 100), true, 25), + GetNextParallelIntersectionParameters(Point2LL(25, 100), Point2LL(50, 100), Point2LL(50, 200), true, 25), + GetNextParallelIntersectionParameters(std::optional(), Point2LL(100, 100), Point2LL(200, 200), true, 80), + GetNextParallelIntersectionParameters(Point2LL(0, 45), Point2LL(5, 100), Point2LL(105, 200), true, 35))); TEST_F(PolygonUtilsTest, RelativeHammingSquaresOverlap) { @@ -424,7 +424,7 @@ TEST_F(PolygonUtilsTest, RelativeHammingSquaresOverlap) TEST_F(PolygonUtilsTest, RelativeHammingDisjunct) { Polygons shifted_polys = test_squares; // Make a copy. - shifted_polys[0].translate(Point(200, 0)); + shifted_polys[0].translate(Point2LL(200, 0)); ASSERT_EQ(PolygonUtils::relativeHammingDistance(test_squares, shifted_polys), 1.0); } @@ -432,7 +432,7 @@ TEST_F(PolygonUtilsTest, RelativeHammingDisjunct) TEST_F(PolygonUtilsTest, RelativeHammingHalfOverlap) { Polygons shifted_polys = test_squares; // Make a copy. - shifted_polys[0].translate(Point(50, 0)); + shifted_polys[0].translate(Point2LL(50, 0)); ASSERT_EQ(PolygonUtils::relativeHammingDistance(test_squares, shifted_polys), 0.5); } @@ -445,7 +445,7 @@ TEST_F(PolygonUtilsTest, RelativeHammingHalfOverlap) TEST_F(PolygonUtilsTest, RelativeHammingQuarterOverlap) { Polygons shifted_polys = test_squares; // Make a copy. - shifted_polys[0].translate(Point(50, 50)); + shifted_polys[0].translate(Point2LL(50, 50)); ASSERT_EQ(PolygonUtils::relativeHammingDistance(test_squares, shifted_polys), 0.75); } @@ -467,7 +467,7 @@ TEST_F(PolygonUtilsTest, RelativeHammingLineSquare) */ TEST_F(PolygonUtilsTest, RelativeHammingLineSquareDisjunct) { - test_line[0].translate(Point(0, 200)); + test_line[0].translate(Point2LL(0, 200)); ASSERT_EQ(PolygonUtils::relativeHammingDistance(test_squares, test_line), 1.0); } @@ -481,7 +481,7 @@ TEST_F(PolygonUtilsTest, TEST_F(PolygonUtilsTest, RelativeHammingLineLineDisjunct) { Polygons shifted_line = test_line; // Make a copy. - shifted_line[0].translate(Point(0, 1)); + shifted_line[0].translate(Point2LL(0, 1)); ASSERT_EQ(PolygonUtils::relativeHammingDistance(test_line, test_line), 1.0); } diff --git a/tests/utils/SimplifyTest.cpp b/tests/utils/SimplifyTest.cpp index 118e909644..1e45d8e9fb 100644 --- a/tests/utils/SimplifyTest.cpp +++ b/tests/utils/SimplifyTest.cpp @@ -47,7 +47,7 @@ class SimplifyTest : public testing::Test const double increment = segment_length / radius; // Segments of 990 units. for (double angle = 0; angle < tau; angle += increment) { - circle.add(Point(std::cos(angle) * radius, std::sin(angle) * radius)); + circle.add(Point2LL(std::cos(angle) * radius, std::sin(angle) * radius)); } square_collinear.clear(); @@ -63,16 +63,16 @@ class SimplifyTest : public testing::Test switch (side) { case 0: - square_collinear.add(Point(longitude, latitude)); + square_collinear.add(Point2LL(longitude, latitude)); break; case 1: - square_collinear.add(Point(width + latitude, longitude)); + square_collinear.add(Point2LL(width + latitude, longitude)); break; case 2: - square_collinear.add(Point(width - longitude, width + latitude)); + square_collinear.add(Point2LL(width - longitude, width + latitude)); break; case 3: - square_collinear.add(Point(latitude, width - longitude)); + square_collinear.add(Point2LL(latitude, width - longitude)); break; } } @@ -85,7 +85,7 @@ class SimplifyTest : public testing::Test constexpr size_t periods = 10; // How many waves of the sine to construct. for (double current_sine = 0; current_sine < std::numbers::pi * periods; current_sine += sine_step) { - sine.add(Point(std::sin(current_sine) * amplitude, y_step * sine.size())); + sine.add(Point2LL(std::sin(current_sine) * amplitude, y_step * sine.size())); } spiral.clear(); @@ -96,7 +96,7 @@ class SimplifyTest : public testing::Test radius = 0; for (size_t i = 0; i < vertex_count; ++i) { - spiral.add(Point(std::cos(angle) * radius, std::sin(angle) * radius)); + spiral.add(Point2LL(std::cos(angle) * radius, std::sin(angle) * radius)); angle += angle_step; radius += radius_step; } @@ -105,7 +105,7 @@ class SimplifyTest : public testing::Test constexpr coord_t invfreq = 30; for (size_t i = 0; i < vertex_count; ++i) { - zigzag.add(Point(-amplitude + (i % 2) * 2 * amplitude, i * invfreq)); + zigzag.add(Point2LL(-amplitude + (i % 2) * 2 * amplitude, i * invfreq)); } } }; @@ -142,17 +142,17 @@ TEST_F(SimplifyTest, CircleMaxDeviation) Polygon simplified = simplifier.polygon(circle); // Check on each vertex if it didn't deviate too much. - for (Point v : circle) + for (Point2LL v : circle) { - Point moved_point = v; + Point2LL moved_point = v; PolygonUtils::moveInside(simplified, moved_point); const coord_t deviation = vSize(moved_point - v); EXPECT_LE(deviation, simplifier.max_deviation); } // Also check the other way around, since the longest distance may also be on a vertex of the new polygon. - for (Point v : simplified) + for (Point2LL v : simplified) { - Point moved_point = v; + Point2LL moved_point = v; PolygonUtils::moveInside(circle, moved_point); const coord_t deviation = vSize(moved_point - v); EXPECT_LE(deviation, simplifier.max_deviation); @@ -221,14 +221,14 @@ TEST_F(SimplifyTest, LimitedError) // Generate a zig-zag with gradually increasing deviation. Polygon increasing_zigzag; - increasing_zigzag.add(Point(0, 0)); + increasing_zigzag.add(Point2LL(0, 0)); constexpr coord_t amplitude_step = 1; // Every 2 vertices, the amplitude increases by this much. constexpr coord_t y_step = 100; const coord_t amplitude_limit = simplifier.max_deviation * 2; // Increase amplitude up to this point. About half of the vertices should get removed. for (coord_t amplitude = 0; amplitude < amplitude_limit; amplitude += amplitude_step) { - increasing_zigzag.add(Point(amplitude, increasing_zigzag.size() * y_step)); - increasing_zigzag.add(Point(0, increasing_zigzag.size() * y_step)); + increasing_zigzag.add(Point2LL(amplitude, increasing_zigzag.size() * y_step)); + increasing_zigzag.add(Point2LL(0, increasing_zigzag.size() * y_step)); } size_t limit_vertex = 2 * simplifier.max_deviation / amplitude_step + 3; // 2 vertices per zag. Deviation/step zags. Add 3 since deviation equal to max +- epsilon is allowed. @@ -257,10 +257,10 @@ TEST_F(SimplifyTest, LimitedError) TEST_F(SimplifyTest, LongEdgesNotMoved) { Polygon polyline; - polyline.add(Point(0, 0)); - polyline.add(Point(10000, 10000)); // Long edge. - polyline.add(Point(10010, 10000)); // Short edge. - polyline.add(Point(21010, 0)); // Long edge. + polyline.add(Point2LL(0, 0)); + polyline.add(Point2LL(10000, 10000)); // Long edge. + polyline.add(Point2LL(10010, 10000)); // Short edge. + polyline.add(Point2LL(21010, 0)); // Long edge. Polygon simplified = simplifier.polyline(polyline); @@ -277,7 +277,7 @@ TEST_F(SimplifyTest, LongEdgesNotMoved) { // Both endpoints of this line segment must have a distance to the simplified polygon of 0, theoretically. // Due to rounding errors we'll allow up to 1 unit. - Point moved_point = polyline[i]; + Point2LL moved_point = polyline[i]; PolygonUtils::moveInside(simplified, moved_point); const coord_t deviation = vSize(moved_point - polyline[i]); EXPECT_LE(deviation, 1) << "The endpoints of long segments must still be in the simplified result."; @@ -294,10 +294,10 @@ TEST_F(SimplifyTest, LongEdgesNotMoved) TEST_F(SimplifyTest, LongEdgesButTooMuchDeviation) { Polygon polyline; - polyline.add(Point(0, 0)); - polyline.add(Point(0, 10000)); // Long edge. - polyline.add(Point(10, 10000)); // Short edge. - polyline.add(Point(20, 0)); // Long edge. Intersection with previous long edge is at 0,20000, which is too far. + polyline.add(Point2LL(0, 0)); + polyline.add(Point2LL(0, 10000)); // Long edge. + polyline.add(Point2LL(10, 10000)); // Short edge. + polyline.add(Point2LL(20, 0)); // Long edge. Intersection with previous long edge is at 0,20000, which is too far. Polygon simplified = simplifier.polyline(polyline); @@ -309,7 +309,7 @@ TEST_F(SimplifyTest, LongEdgesButTooMuchDeviation) } polyline.pop_back(); - polyline.add(Point(10, 0)); // Replace last vertex with one that makes the two long edges exactly parallel. + polyline.add(Point2LL(10, 0)); // Replace last vertex with one that makes the two long edges exactly parallel. simplified = simplifier.polyline(polyline); @@ -361,13 +361,13 @@ TEST_F(SimplifyTest, IdenticalVertices) switch (vertex) { case 0: - polygon.add(Point(0, 0)); + polygon.add(Point2LL(0, 0)); break; case 1: - polygon.add(Point(10000, 0)); + polygon.add(Point2LL(10000, 0)); break; case 2: - polygon.add(Point(5000, 10000)); + polygon.add(Point2LL(5000, 10000)); break; } } @@ -384,17 +384,17 @@ TEST_F(SimplifyTest, ToDegenerate) { // Create a triangle where one of the vertices could be removed. Polygon triangle; - triangle.add(Point(0, 0)); - triangle.add(Point(1100, 0)); - triangle.add(Point(550, 50)); // Deviates by 50, and both adjacent edges are just over 550 long. Could be removed. + triangle.add(Point2LL(0, 0)); + triangle.add(Point2LL(1100, 0)); + triangle.add(Point2LL(550, 50)); // Deviates by 50, and both adjacent edges are just over 550 long. Could be removed. triangle = simplifier.polygon(triangle); EXPECT_EQ(triangle.size(), 3) << "The triangle did not get simplified because that would reduce its vertices to less than 3, making it degenerate."; // Create a polyline that is shorter than the minimum resolution. Polygon segment; - segment.add(Point(0, 0)); - segment.add(Point(4, 0)); // Less than 5 micron long, so vertices would always be removed. + segment.add(Point2LL(0, 0)); + segment.add(Point2LL(4, 0)); // Less than 5 micron long, so vertices would always be removed. segment = simplifier.polyline(segment); EXPECT_EQ(segment.size(), 0) << "The segment got removed entirely, because simplification would reduce its vertices to less than 2, making it degenerate."; diff --git a/tests/utils/SmoothTest.cpp b/tests/utils/SmoothTest.cpp index 8288d605e9..1864e4b706 100644 --- a/tests/utils/SmoothTest.cpp +++ b/tests/utils/SmoothTest.cpp @@ -7,7 +7,7 @@ #include -#include "utils/IntPoint.h" +#include "utils/Point2LL.h" #include "utils/actions/smooth.h" #include "utils/polygon.h" @@ -30,10 +30,10 @@ TEST(SmoothTest, TestSmooth) * */ - auto A = cura::Point { 0, 0 }; - auto B = cura::Point { 0, 100 }; - auto C = cura::Point { 1, 100 }; - auto D = cura::Point { 1, 200 }; + auto A = cura::Point2LL { 0, 0 }; + auto B = cura::Point2LL { 0, 100 }; + auto C = cura::Point2LL { 1, 100 }; + auto D = cura::Point2LL { 1, 200 }; const auto is_smooth = smooth.isSmooth(A, B, C, D, COS_FLUID_ANGLE); EXPECT_EQ(is_smooth, false); @@ -51,10 +51,10 @@ TEST(SmoothTest, TestSmooth) * D * */ - auto A = cura::Point { 0, 0 }; - auto B = cura::Point { 100, 0 }; - auto C = cura::Point { 101, 1 }; - auto D = cura::Point { 101, 101 }; + auto A = cura::Point2LL { 0, 0 }; + auto B = cura::Point2LL { 100, 0 }; + auto C = cura::Point2LL { 101, 1 }; + auto D = cura::Point2LL { 101, 101 }; const auto is_smooth = smooth.isSmooth(A, B, C, D, COS_FLUID_ANGLE); EXPECT_EQ(is_smooth, true); @@ -66,10 +66,10 @@ TEST(SmoothTest, TestSmooth) * A ----------- B - C -------------D * */ - auto A = cura::Point { 0, 0 }; - auto B = cura::Point { 100, 0 }; - auto C = cura::Point { 101, 0 }; - auto D = cura::Point { 201, 0 }; + auto A = cura::Point2LL { 0, 0 }; + auto B = cura::Point2LL { 100, 0 }; + auto C = cura::Point2LL { 101, 0 }; + auto D = cura::Point2LL { 201, 0 }; const auto is_smooth = smooth.isSmooth(A, B, C, D, COS_FLUID_ANGLE); EXPECT_EQ(is_smooth, true); @@ -81,10 +81,10 @@ TEST(SmoothTest, TestSmooth) * D ----------- C - B -------------A * */ - auto A = cura::Point { 201, 0 }; - auto B = cura::Point { 101, 0 }; - auto C = cura::Point { 100, 0 }; - auto D = cura::Point { 0, 0 }; + auto A = cura::Point2LL { 201, 0 }; + auto B = cura::Point2LL { 101, 0 }; + auto C = cura::Point2LL { 100, 0 }; + auto D = cura::Point2LL { 0, 0 }; const auto is_smooth = smooth.isSmooth(A, B, C, D, COS_FLUID_ANGLE); EXPECT_EQ(is_smooth, true); @@ -105,10 +105,10 @@ TEST(SmoothTest, TestSmooth) * D * */ - auto A = cura::Point { 0, 0 }; - auto B = cura::Point { 100, 0 }; - auto C = cura::Point { 99, -1 }; - auto D = cura::Point { 199, 99 }; + auto A = cura::Point2LL { 0, 0 }; + auto B = cura::Point2LL { 100, 0 }; + auto C = cura::Point2LL { 99, -1 }; + auto D = cura::Point2LL { 199, 99 }; const auto is_smooth = smooth.isSmooth(A, B, C, D, COS_FLUID_ANGLE); EXPECT_EQ(is_smooth, false); @@ -127,10 +127,10 @@ TEST(SmoothTest, TestSmooth) * D * */ - auto A = cura::Point { 0, 0 }; - auto B = cura::Point { 100, 0 }; - auto C = cura::Point { 101, 1 }; - auto D = cura::Point { 201, 101 }; + auto A = cura::Point2LL { 0, 0 }; + auto B = cura::Point2LL { 100, 0 }; + auto C = cura::Point2LL { 101, 1 }; + auto D = cura::Point2LL { 201, 101 }; const auto is_smooth = smooth.isSmooth(A, B, C, D, COS_FLUID_ANGLE); EXPECT_EQ(is_smooth, true); @@ -147,10 +147,10 @@ TEST(SmoothTest, TestSmooth) * D * */ - cura::Point A = { 0, 0 }; - cura::Point B = { 100, 0 }; - cura::Point C = { 101, 0 }; - cura::Point D = { 101, 100 }; + cura::Point2LL A = { 0, 0 }; + cura::Point2LL B = { 100, 0 }; + cura::Point2LL C = { 101, 0 }; + cura::Point2LL D = { 101, 100 }; const auto is_smooth = smooth.isSmooth(A, B, C, D, COS_FLUID_ANGLE); EXPECT_EQ(is_smooth, true); @@ -158,10 +158,10 @@ TEST(SmoothTest, TestSmooth) { // real life example of a line that is clearly not smooth - auto A = cura::Point{ 148451, 162177 }; - auto B = cura::Point{ 148854, 162229 }; - auto C = cura::Point{ 148866, 162244 }; - auto D = cura::Point{ 149772, 162297 }; + auto A = cura::Point2LL{ 148451, 162177 }; + auto B = cura::Point2LL{ 148854, 162229 }; + auto C = cura::Point2LL{ 148866, 162244 }; + auto D = cura::Point2LL{ 149772, 162297 }; const auto is_smooth = smooth.isSmooth(A, B, C, D, COS_FLUID_ANGLE); EXPECT_EQ(is_smooth, false); diff --git a/tests/utils/SparseGridTest.cpp b/tests/utils/SparseGridTest.cpp index 2849a6207e..5f60ec5491 100644 --- a/tests/utils/SparseGridTest.cpp +++ b/tests/utils/SparseGridTest.cpp @@ -14,11 +14,11 @@ namespace cura struct GetNearbyParameters { - std::vector registered_points; - std::unordered_set expected_near; - std::unordered_set expected_far; + std::vector registered_points; + std::unordered_set expected_near; + std::unordered_set expected_far; - GetNearbyParameters(const std::vector registered_points, const std::unordered_set expected_near, const std::unordered_set expected_far) + GetNearbyParameters(const std::vector registered_points, const std::unordered_set expected_near, const std::unordered_set expected_far) : registered_points(registered_points) , expected_near(expected_near) , expected_far(expected_far) @@ -32,54 +32,52 @@ class GetNearbyTest : public testing::TestWithParam TEST_P(GetNearbyTest, GetNearby) { - const Point target(100, 100); + const Point2LL target(100, 100); constexpr coord_t grid_size = 10; const GetNearbyParameters parameters = GetParam(); - SparsePointGridInclusive grid(grid_size); - for (const Point point : parameters.registered_points) + SparsePointGridInclusive grid(grid_size); + for (const Point2LL point : parameters.registered_points) { grid.insert(point, point); } - const std::vector::Elem> result = grid.getNearby(target, grid_size); + const std::vector::Elem> result = grid.getNearby(target, grid_size); // Are all near points reported as near? - for (const Point point : parameters.expected_near) + for (const Point2LL point : parameters.expected_near) { - EXPECT_NE(result.end(), std::find_if(result.begin(), result.end(), [&point](const typename SparsePointGridInclusive::Elem& elem) { return elem.val == point; })) + EXPECT_NE(result.end(), std::find_if(result.begin(), result.end(), [&point](const typename SparsePointGridInclusive::Elem& elem) { return elem.val == point; })) << "Point " << point << " is near " << target << " (distance " << vSize(point - target) << "), but getNearby didn't find it. Grid size: " << grid_size; } // Are all far points NOT reported as near? - for (const Point point : parameters.expected_far) + for (const Point2LL point : parameters.expected_far) { - EXPECT_EQ(result.end(), std::find_if(result.begin(), result.end(), [&point](const typename SparsePointGridInclusive::Elem& elem) { return elem.val == point; })) + EXPECT_EQ(result.end(), std::find_if(result.begin(), result.end(), [&point](const typename SparsePointGridInclusive::Elem& elem) { return elem.val == point; })) << "Point " << point << " is far from " << target << " (distance " << vSize(point - target) << "), but getNearby thought it was near. Grid size: " << grid_size; } } INSTANTIATE_TEST_CASE_P(GetNearbyInstantiation, GetNearbyTest, - testing::Values(GetNearbyParameters({ Point(0, 100) }, std::unordered_set(), std::unordered_set({ Point(0, 100) })), // A far point. - GetNearbyParameters({ Point(95, 100) }, - std::unordered_set({ Point(95, 100) }), - std::unordered_set()), // A near point. - GetNearbyParameters({ Point(100, 100) }, - std::unordered_set({ Point(100, 100) }), - std::unordered_set()) // On top of the target. + testing::Values(Point2LLarbyParameters({ Point2LL(0, 100) }, stdPoint2LLrdered_set(), stdPoint2LLrdered_set(Point2LLnt(95, 100) }), + Point2LLunordered_setPoint2LLt>())Point2LLA near point. + GetNearbyParametersPoint2LLint(100, 100) }Point2LL std::Point2LLered_setPoint2LLt>Point2LLint(100, 100) })Point2LL std::Point2LLered_set()) // On top of the target. )); TEST_F(GetNearbyTest, getNearbyLine2) { - std::vector input; + std::vector input; for (coord_t x = 0; x < 200; x++) { input.emplace_back(x, 95); } - const Point target(99, 100); // Slightly shifted. + const Point2LL target(99, 100); // Slightly shifted. constexpr coord_t grid_size = 10; - std::unordered_set near; - std::unordered_set far; - for (const Point point : input) + std::unordered_set near; + std::unordered_set far; + for (const Point2LL point : input) { const coord_t distance = vSize(point - target); if (distance < grid_size) @@ -92,39 +90,39 @@ TEST_F(GetNearbyTest, getNearbyLine2) } } - SparsePointGridInclusive grid(grid_size); - for (const Point point : input) + SparsePointGridInclusive grid(grid_size); + for (const Point2LL point : input) { grid.insert(point, point); } - const std::vector::Elem> result = grid.getNearby(target, grid_size); + const std::vector::Elem> result = grid.getNearby(target, grid_size); // Are all near points reported as near? - for (const Point point : near) + for (const Point2LL point : near) { - EXPECT_NE(result.end(), std::find_if(result.begin(), result.end(), [&point](const typename SparsePointGridInclusive::Elem& elem) { return elem.val == point; })) + EXPECT_NE(result.end(), std::find_if(result.begin(), result.end(), [&point](const typename SparsePointGridInclusive::Elem& elem) { return elem.val == point; })) << "Point " << point << " is near " << target << " (distance " << vSize(point - target) << "), but getNearby didn't find it. Grid size: " << grid_size; } // Are all far points NOT reported as near? - for (const Point point : far) + for (const Point2LL point : far) { - EXPECT_EQ(result.end(), std::find_if(result.begin(), result.end(), [&point](const typename SparsePointGridInclusive::Elem& elem) { return elem.val == point; })) + EXPECT_EQ(result.end(), std::find_if(result.begin(), result.end(), [&point](const typename SparsePointGridInclusive::Elem& elem) { return elem.val == point; })) << "Point " << point << " is far from " << target << " (distance " << vSize(point - target) << "), but getNearby thought it was near. Grid size: " << grid_size; } } TEST_F(GetNearbyTest, getNearbyLine) { - std::vector input; + std::vector input; for (coord_t x = 0; x < 200; x++) { input.emplace_back(x, 95); } - const Point target(100, 100); + const Point2LL target(100, 100); constexpr coord_t grid_size = 10; - std::unordered_set near; - std::unordered_set far; - for (const Point point : input) + std::unordered_set near; + std::unordered_set far; + for (const Point2LL point : input) { const coord_t distance = vSize(point - target); if (distance < grid_size) @@ -137,34 +135,34 @@ TEST_F(GetNearbyTest, getNearbyLine) } } - SparsePointGridInclusive grid(grid_size); - for (const Point point : input) + SparsePointGridInclusive grid(grid_size); + for (const Point2LL point : input) { grid.insert(point, point); } - const std::vector::Elem> result = grid.getNearby(target, grid_size); + const std::vector::Elem> result = grid.getNearby(target, grid_size); // Are all near points reported as near? - for (const Point point : near) + for (const Point2LL point : near) { - EXPECT_NE(result.end(), std::find_if(result.begin(), result.end(), [&point](const typename SparsePointGridInclusive::Elem& elem) { return elem.val == point; })) + EXPECT_NE(result.end(), std::find_if(result.begin(), result.end(), [&point](const typename SparsePointGridInclusive::Elem& elem) { return elem.val == point; })) << "Point " << point << " is near " << target << " (distance " << vSize(point - target) << "), but getNearby didn't find it. Grid size: " << grid_size; } // Are all far points NOT reported as near? - for (const Point point : far) + for (const Point2LL point : far) { - EXPECT_EQ(result.end(), std::find_if(result.begin(), result.end(), [&point](const typename SparsePointGridInclusive::Elem& elem) { return elem.val == point; })) + EXPECT_EQ(result.end(), std::find_if(result.begin(), result.end(), [&point](const typename SparsePointGridInclusive::Elem& elem) { return elem.val == point; })) << "Point " << point << " is far from " << target << " (distance " << vSize(point - target) << "), but getNearby thought it was near. Grid size: " << grid_size; } } struct GetNearestParameters { - std::vector registered_points; - Point* result; + std::vector registered_points; + Point2LL* result; std::function::Elem&)> filter; - GetNearestParameters(const std::vector registered_points, Point* result, const std::function::Elem&)>& filter = SparsePointGridInclusive::no_precondition) + GetNearestParameters(const std::vector registered_points, Point2LL* result, const std::function::Elem&)>& filter = SparsePointGridInclusive::no_precondition) : registered_points(registered_points) , result(result) , filter(filter) @@ -180,15 +178,15 @@ TEST_P(GetNearestTest, GetNearest) { const GetNearestParameters parameters = GetParam(); constexpr coord_t grid_size = 10; - const Point target(100, 100); + const Point2LL target(100, 100); - SparsePointGridInclusive grid(grid_size); - for (Point point : parameters.registered_points) + SparsePointGridInclusive grid(grid_size); + for (Point2LL point : parameters.registered_points) { grid.insert(point, point); } - typename SparsePointGridInclusive::Elem result; + typename SparsePointGridInclusive::Elem result; const bool success = grid.getNearest(target, grid_size, result, parameters.filter); ASSERT_EQ(success, parameters.result != nullptr) << "getNearest returned " << success << " but should've returned " << (parameters.result != nullptr) << "."; @@ -201,33 +199,33 @@ TEST_P(GetNearestTest, GetNearest) INSTANTIATE_TEST_SUITE_P(GetNearestInstantiation, GetNearestTest, - testing::Values(GetNearestParameters(std::vector({ Point(95, 100), Point(103, 100), Point(200, 100) }), new Point(103, 100)), // Choose the nearest out of 3 points. - GetNearestParameters(std::vector({ Point(95, 100), Point(98, 100), Point(106, 100) }), - new Point(106, 100), - [](const typename SparsePointGridInclusive::Elem& elem) -> bool { return elem.point.X > 100; }), // With a filter. - GetNearestParameters(std::vector(), nullptr), // No points, no answer. - GetNearestParameters(std::vector({ Point(100, 100) }), new Point(100, 100)) // Same point as target. + testing::Values(GetNearestParameters(std::vector({ Point2LL(95, 100), Point2LL(103, 100), Point2LL(200, 100) }), new Point2LL(103, 100)), // Choose the nearest out of 3 points. + GetNearestParameters(std::vector({ Point2LL(95, 100), Point2LL(98, 100), Point2LL(106, 100) }), + new Point2LL(106, 100), + [](const typename SparsePointGridInclusive::Elem& elem) -> bool { return elem.point.X > 100; }), // With a filter. + GetNearestParameters(std::vector(), nullptr), // No points, no answer. + GetNearestParameters(std::vector({ Point2LL(100, 100) }), new Point2LL(100, 100)) // Same point as target. )); TEST_F(GetNearestTest, Equal) { - std::vector registered_points; + std::vector registered_points; registered_points.emplace_back(95, 100); registered_points.emplace_back(105, 100); - const Point target = Point(100, 100); + const Point2LL target = Point2LL(100, 100); constexpr coord_t grid_size = 10; - const Point expected1 = Point(95, 100); - const Point expected2 = Point(105, 100); + const Point2LL expected1 = Point2LL(95, 100); + const Point2LL expected2 = Point2LL(105, 100); - SparsePointGridInclusive grid(grid_size); - for (const Point point : registered_points) + SparsePointGridInclusive grid(grid_size); + for (const Point2LL point : registered_points) { grid.insert(point, point); } - typename SparsePointGridInclusive::Elem result; + typename SparsePointGridInclusive::Elem result; // The actual call to test. - const bool success = grid.getNearest(target, grid_size, result, SparsePointGridInclusive::no_precondition); + const bool success = grid.getNearest(target, grid_size, result, SparsePointGridInclusive::no_precondition); ASSERT_TRUE(success); ASSERT_TRUE(result.val == expected1 || result.val == expected2) << "getNearest reported the nearest point to be " << result.val << " (distance " << vSize(target - result.val) << "), but it should've been " << expected1 << "(distance " diff --git a/tests/utils/StringTest.cpp b/tests/utils/StringTest.cpp index 8ae5fe1f20..829c4c3da7 100644 --- a/tests/utils/StringTest.cpp +++ b/tests/utils/StringTest.cpp @@ -2,7 +2,7 @@ // CuraEngine is released under the terms of the AGPLv3 or higher. #include "utils/string.h" // The file under test. -#include "utils/IntPoint.h" +#include "utils/Point2LL.h" #include // NOLINTBEGIN(*-magic-numbers) From c74f4bbdabb8b7e2b11e824e1a42fce08d5da053 Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Wed, 22 Nov 2023 10:27:07 +0100 Subject: [PATCH 31/48] Fixed variable initialization ordering warnings --- include/PathOrderOptimizer.h | 2 +- include/TreeSupportElement.h | 8 +- include/TreeSupportTipGenerator.h | 61 ++-- src/BeadingStrategy/BeadingStrategy.cpp | 8 +- src/SkeletalTrapezoidation.cpp | 2 +- src/TreeSupportTipGenerator.cpp | 388 ++++++++++++------------ src/pathPlanning/Comb.cpp | 2 +- 7 files changed, 234 insertions(+), 237 deletions(-) diff --git a/include/PathOrderOptimizer.h b/include/PathOrderOptimizer.h index 56212693d2..4dd1e47332 100644 --- a/include/PathOrderOptimizer.h +++ b/include/PathOrderOptimizer.h @@ -116,8 +116,8 @@ class PathOrderOptimizer , combing_boundary_((combing_boundary != nullptr && ! combing_boundary->empty()) ? combing_boundary : nullptr) , detect_loops_(detect_loops) , reverse_direction_(reverse_direction) - , order_requirements_(&order_requirements) , _group_outer_walls(group_outer_walls) + , order_requirements_(&order_requirements) { } diff --git a/include/TreeSupportElement.h b/include/TreeSupportElement.h index 3fa5c3eafd..3c160b1042 100644 --- a/include/TreeSupportElement.h +++ b/include/TreeSupportElement.h @@ -117,9 +117,9 @@ struct TreeSupportElement , missing_roof_layers_(elem.missing_roof_layers_) , skip_ovalisation_(elem.skip_ovalisation_) , all_tips_(elem.all_tips_) - , influence_area_limit_area_(elem.influence_area_limit_area_) - , influence_area_limit_range_(elem.influence_area_limit_range_) , influence_area_limit_active_(elem.influence_area_limit_active_) + , influence_area_limit_range_(elem.influence_area_limit_range_) + , influence_area_limit_area_(elem.influence_area_limit_area_) { parents_.insert(parents_.begin(), elem.parents_.begin(), elem.parents_.end()); } @@ -149,9 +149,9 @@ struct TreeSupportElement , missing_roof_layers_(element_above->missing_roof_layers_) , skip_ovalisation_(false) , all_tips_(element_above->all_tips_) - , influence_area_limit_area_(element_above->influence_area_limit_area_) - , influence_area_limit_range_(element_above->influence_area_limit_range_) , influence_area_limit_active_(element_above->influence_area_limit_active_) + , influence_area_limit_range_(element_above->influence_area_limit_range_) + , influence_area_limit_area_(element_above->influence_area_limit_area_) { parents_ = { element_above }; } diff --git a/include/TreeSupportTipGenerator.h b/include/TreeSupportTipGenerator.h index eaf85c0c3d..b6ffd3d351 100644 --- a/include/TreeSupportTipGenerator.h +++ b/include/TreeSupportTipGenerator.h @@ -176,138 +176,135 @@ class TreeSupportTipGenerator */ void removeUselessAddedPoints(std::vector>& move_bounds, SliceDataStorage& storage, std::vector& additional_support_areas); + /*! + * \brief Contains config settings to avoid loading them in every function. This was done to improve readability of the code. + */ + TreeSupportSettings config_; /*! * \brief If large areas should be supported by a roof out of regular support lines. */ - bool use_fake_roof; + bool use_fake_roof_; /*! * \brief Generator for model collision, avoidance and internal guide volumes. */ TreeModelVolumes& volumes_; - /*! - * \brief Contains config settings to avoid loading them in every function. This was done to improve readability of the code. - */ - TreeSupportSettings config; - - /*! * \brief Minimum area an overhang has to have to be supported. */ - const double minimum_support_area; + const double minimum_support_area_; /*! * \brief Minimum area an overhang has to have to become a roof. */ - const double minimum_roof_area; + const double minimum_roof_area_; /*! * \brief Amount of layers of roof. Zero if roof is disabled */ - const size_t support_roof_layers; + const size_t support_roof_layers_; /*! * \brief Distance between tips, so that the tips form a lime. Is smaller than Tip Diameter. */ - const coord_t connect_length; + const coord_t connect_length_; /*! * \brief Distance between tips, if the tips support an overhang. */ - const coord_t support_tree_branch_distance; + const coord_t support_tree_branch_distance_; /*! * \brief Distance between support roof lines. Is required for generating roof patterns. */ - const coord_t support_roof_line_distance; + const coord_t support_roof_line_distance_; /*! * \brief Amount of offset to each overhang for support with regular branches (as opposed to roof). */ - const coord_t support_outset; + const coord_t support_outset_; /*! * \brief Amount of offset to each overhang for support with roof (as opposed to regular branches). */ - const coord_t roof_outset; + const coord_t roof_outset_; /*! * \brief Whether tips should be printed as roof */ - const bool force_tip_to_roof; + const bool force_tip_to_roof_; /*! * \brief Whether the maximum distance a branch should from a point they support should be limited. Can be violated if required. */ - const bool support_tree_limit_branch_reach; + const bool support_tree_limit_branch_reach_; /*! * \brief Maximum distance a branch should from a point they support (in the xy plane). Can be violated if required. */ - const coord_t support_tree_branch_reach_limit; + const coord_t support_tree_branch_reach_limit_; /*! * \brief Distance in layers from the overhang to the first layer with support. This is the z distance in layers+1 */ - const size_t z_distance_delta; + const size_t z_distance_delta_; /*! * \brief Whether the Support Distance Priority is X/Y Overrides Z */ - const bool xy_overrides; + const bool xy_overrides_; /*! * \brief Amount of layers further down than required an overhang can be supported, when Support Distance Priority is X/Y Overrides Z */ - size_t max_overhang_insert_lag; + size_t max_overhang_insert_lag_; /*! * \brief Area of a tip. */ - const double tip_roof_size; + const double tip_roof_size_; /*! * \brief Whether only support that can rest on a flat surface should be supported. */ - const bool only_gracious = SUPPORT_TREE_ONLY_GRACIOUS_TO_MODEL; + const bool only_gracious_ = SUPPORT_TREE_ONLY_GRACIOUS_TO_MODEL; /*! * \brief Whether minimum_roof_area is a hard limit. If false the roof will be combined with roof above and below, to see if a part of this roof may be part of a valid roof * further up/down. */ - const bool force_minimum_roof_area = SUPPORT_TREE_MINIMUM_ROOF_AREA_HARD_LIMIT; + const bool force_minimum_roof_area_ = SUPPORT_TREE_MINIMUM_ROOF_AREA_HARD_LIMIT; /*! * \brief Distance between branches when the branches support a support pattern */ - coord_t support_supporting_branch_distance; + coord_t support_supporting_branch_distance_; /*! * \brief Required to generate cross infill patterns */ - std::shared_ptr cross_fill_provider; + std::shared_ptr cross_fill_provider_; /*! * \brief Map that saves locations of already inserted tips. Used to prevent tips far to close together from being added. */ - std::vector> already_inserted; + std::vector> already_inserted_; /*! * \brief Areas that will be saved as support roof */ - std::vector support_roof_drawn; + std::vector support_roof_drawn_; /*! * \brief Areas that will be saved as support roof, originating from tips being replaced with roof areas. */ - std::vector roof_tips_drawn; - + std::vector roof_tips_drawn_; - std::mutex critical_move_bounds; - std::mutex critical_roof_tips; + std::mutex critical_move_bounds_; + std::mutex critical_roof_tips_; }; } // namespace cura diff --git a/src/BeadingStrategy/BeadingStrategy.cpp b/src/BeadingStrategy/BeadingStrategy.cpp index 5b3f81583f..88b295b7ad 100644 --- a/src/BeadingStrategy/BeadingStrategy.cpp +++ b/src/BeadingStrategy/BeadingStrategy.cpp @@ -14,22 +14,22 @@ BeadingStrategy::BeadingStrategy( Ratio wall_add_middle_threshold, coord_t default_transition_length, double transitioning_angle) - : optimal_width_(optimal_width) + : name_("Unknown") + , optimal_width_(optimal_width) , wall_split_middle_threshold_(wall_split_middle_threshold) , wall_add_middle_threshold_(wall_add_middle_threshold) , default_transition_length_(default_transition_length) , transitioning_angle_(transitioning_angle) { - name_ = "Unknown"; } BeadingStrategy::BeadingStrategy(const BeadingStrategy& other) - : optimal_width_(other.optimal_width_) + : name_(other.name_) + , optimal_width_(other.optimal_width_) , wall_split_middle_threshold_(other.wall_split_middle_threshold_) , wall_add_middle_threshold_(other.wall_add_middle_threshold_) , default_transition_length_(other.default_transition_length_) , transitioning_angle_(other.transitioning_angle_) - , name_(other.name_) { } diff --git a/src/SkeletalTrapezoidation.cpp b/src/SkeletalTrapezoidation.cpp index 9cd04a3cbc..3aca0644db 100644 --- a/src/SkeletalTrapezoidation.cpp +++ b/src/SkeletalTrapezoidation.cpp @@ -387,9 +387,9 @@ SkeletalTrapezoidation::SkeletalTrapezoidation( , transition_filter_dist_(transition_filter_dist) , allowed_filter_deviation_(allowed_filter_deviation) , beading_propagation_transition_dist_(beading_propagation_transition_dist) - , beading_strategy_(beading_strategy) , layer_idx_(layer_idx) , section_type_(section_type) + , beading_strategy_(beading_strategy) { scripta::log("skeletal_trapezoidation_0", polys, section_type, layer_idx); constructFromPolygons(polys); diff --git a/src/TreeSupportTipGenerator.cpp b/src/TreeSupportTipGenerator.cpp index 5ec22f610c..c5292dbf2b 100644 --- a/src/TreeSupportTipGenerator.cpp +++ b/src/TreeSupportTipGenerator.cpp @@ -29,54 +29,54 @@ namespace cura { TreeSupportTipGenerator::TreeSupportTipGenerator(const SliceDataStorage& storage, const SliceMeshStorage& mesh, TreeModelVolumes& volumes_s) - : config(mesh.settings) - , use_fake_roof(! mesh.settings.get("support_roof_enable")) - , minimum_support_area(mesh.settings.get("minimum_support_area")) - , minimum_roof_area(! use_fake_roof ? mesh.settings.get("minimum_roof_area") : std::max(SUPPORT_TREE_MINIMUM_FAKE_ROOF_AREA, minimum_support_area)) - , support_roof_layers( - mesh.settings.get("support_roof_enable") ? round_divide(mesh.settings.get("support_roof_height"), config.layer_height) - : use_fake_roof ? SUPPORT_TREE_MINIMUM_FAKE_ROOF_LAYERS + : config_(mesh.settings) + , use_fake_roof_(! mesh.settings.get("support_roof_enable")) + , volumes_(volumes_s) + , minimum_support_area_(mesh.settings.get("minimum_support_area")) + , minimum_roof_area_(! use_fake_roof_ ? mesh.settings.get("minimum_roof_area") : std::max(SUPPORT_TREE_MINIMUM_FAKE_ROOF_AREA, minimum_support_area_)) + , support_roof_layers_( + mesh.settings.get("support_roof_enable") ? round_divide(mesh.settings.get("support_roof_height"), config_.layer_height) + : use_fake_roof_ ? SUPPORT_TREE_MINIMUM_FAKE_ROOF_LAYERS : 0) - , connect_length( - (config.support_line_width * 100 / mesh.settings.get("support_tree_top_rate")) + std::max(2 * config.min_radius - 1.0 * config.support_line_width, 0.0)) - , support_tree_branch_distance((config.support_pattern == EFillMethod::TRIANGLES ? 3 : (config.support_pattern == EFillMethod::GRID ? 2 : 1)) * connect_length) - , support_roof_line_distance( - use_fake_roof ? (config.support_pattern == EFillMethod::TRIANGLES ? 3 : (config.support_pattern == EFillMethod::GRID ? 2 : 1)) - * (config.support_line_width * 100 / mesh.settings.get("support_tree_top_rate")) - : mesh.settings.get("support_roof_line_distance")) + , connect_length_( + (config_.support_line_width * 100 / mesh.settings.get("support_tree_top_rate")) + std::max(2 * config_.min_radius - 1.0 * config_.support_line_width, 0.0)) + , support_tree_branch_distance_((config_.support_pattern == EFillMethod::TRIANGLES ? 3 : (config_.support_pattern == EFillMethod::GRID ? 2 : 1)) * connect_length_) + , support_roof_line_distance_( + use_fake_roof_ ? (config_.support_pattern == EFillMethod::TRIANGLES ? 3 : (config_.support_pattern == EFillMethod::GRID ? 2 : 1)) + * (config_.support_line_width * 100 / mesh.settings.get("support_tree_top_rate")) + : mesh.settings.get("support_roof_line_distance")) , // todo propper - support_outset(0) + support_outset_(0) , // Since we disable support offset when tree support is enabled we use an offset of 0 rather than the setting value mesh.settings.get("support_offset") - roof_outset(use_fake_roof ? support_outset : mesh.settings.get("support_roof_offset")) - , force_tip_to_roof((config.min_radius * config.min_radius * std::numbers::pi > minimum_roof_area * (1000 * 1000)) && support_roof_layers && ! use_fake_roof) - , support_tree_limit_branch_reach(mesh.settings.get("support_tree_limit_branch_reach")) - , support_tree_branch_reach_limit(support_tree_limit_branch_reach ? mesh.settings.get("support_tree_branch_reach_limit") : 0) - , z_distance_delta(std::min(config.z_distance_top_layers + 1, mesh.overhang_areas.size())) - , xy_overrides(config.support_overrides == SupportDistPriority::XY_OVERRIDES_Z) - , tip_roof_size(force_tip_to_roof ? config.min_radius * config.min_radius * std::numbers::pi : 0) - , already_inserted(mesh.overhang_areas.size()) - , support_roof_drawn(mesh.overhang_areas.size(), Polygons()) - , roof_tips_drawn(mesh.overhang_areas.size(), Polygons()) - , volumes_(volumes_s) - , force_minimum_roof_area(use_fake_roof || SUPPORT_TREE_MINIMUM_ROOF_AREA_HARD_LIMIT) + roof_outset_(use_fake_roof_ ? support_outset_ : mesh.settings.get("support_roof_offset")) + , force_tip_to_roof_((config_.min_radius * config_.min_radius * std::numbers::pi > minimum_roof_area_ * (1000 * 1000)) && support_roof_layers_ && ! use_fake_roof_) + , support_tree_limit_branch_reach_(mesh.settings.get("support_tree_limit_branch_reach")) + , support_tree_branch_reach_limit_(support_tree_limit_branch_reach_ ? mesh.settings.get("support_tree_branch_reach_limit") : 0) + , z_distance_delta_(std::min(config_.z_distance_top_layers + 1, mesh.overhang_areas.size())) + , xy_overrides_(config_.support_overrides == SupportDistPriority::XY_OVERRIDES_Z) + , tip_roof_size_(force_tip_to_roof_ ? config_.min_radius * config_.min_radius * std::numbers::pi : 0) + , force_minimum_roof_area_(use_fake_roof_ || SUPPORT_TREE_MINIMUM_ROOF_AREA_HARD_LIMIT) + , already_inserted_(mesh.overhang_areas.size()) + , support_roof_drawn_(mesh.overhang_areas.size(), Polygons()) + , roof_tips_drawn_(mesh.overhang_areas.size(), Polygons()) { const double support_overhang_angle = mesh.settings.get("support_angle"); - const coord_t max_overhang_speed = (support_overhang_angle < TAU / 4) ? (coord_t)(tan(support_overhang_angle) * config.layer_height) : std::numeric_limits::max(); + const coord_t max_overhang_speed = (support_overhang_angle < TAU / 4) ? (coord_t)(tan(support_overhang_angle) * config_.layer_height) : std::numeric_limits::max(); if (max_overhang_speed == 0) { - max_overhang_insert_lag = std::numeric_limits::max(); + max_overhang_insert_lag_ = std::numeric_limits::max(); } else { - max_overhang_insert_lag = std::max((size_t)round_up_divide(config.xy_distance, max_overhang_speed / 2), 2 * config.z_distance_top_layers); + max_overhang_insert_lag_ = std::max((size_t)round_up_divide(config_.xy_distance, max_overhang_speed / 2), 2 * config_.z_distance_top_layers); // ^^^ Cap for how much layer below the overhang a new support point may be added, as other than with regular support every new inserted point may cause extra material and // time cost. // Could also be an user setting or differently calculated. Idea is that if an overhang does not turn valid in double the amount of layers a slope of support angle // would take to travel xy_distance, nothing reasonable will come from it. The 2*z_distance_delta is only a catch for when the support angle is very high. } - cross_fill_provider = generateCrossFillProvider(mesh, support_tree_branch_distance, config.support_line_width); + cross_fill_provider_ = generateCrossFillProvider(mesh, support_tree_branch_distance_, config_.support_line_width); std::vector known_z(mesh.layers.size()); @@ -84,23 +84,23 @@ TreeSupportTipGenerator::TreeSupportTipGenerator(const SliceDataStorage& storage { known_z[z] = layer.printZ; } - config.setActualZ(known_z); + config_.setActualZ(known_z); coord_t dtt_when_tips_can_merge = 1; - if (config.branch_radius * config.diameter_angle_scale_factor < 2 * config.maximum_move_distance_slow) + if (config_.branch_radius * config_.diameter_angle_scale_factor < 2 * config_.maximum_move_distance_slow) { - while ((2 * config.maximum_move_distance_slow * dtt_when_tips_can_merge - config.support_line_width) < config.getRadius(dtt_when_tips_can_merge)) + while ((2 * config_.maximum_move_distance_slow * dtt_when_tips_can_merge - config_.support_line_width) < config_.getRadius(dtt_when_tips_can_merge)) { dtt_when_tips_can_merge++; } } else { - dtt_when_tips_can_merge = config.tip_layers; // arbitrary default for when there is no guarantee that the while loop above will terminate + dtt_when_tips_can_merge = config_.tip_layers; // arbitrary default for when there is no guarantee that the while loop above will terminate } - support_supporting_branch_distance = 2 * config.getRadius(dtt_when_tips_can_merge) + config.support_line_width + FUDGE_LENGTH; + support_supporting_branch_distance_ = 2 * config_.getRadius(dtt_when_tips_can_merge) + config_.support_line_width + FUDGE_LENGTH; } @@ -119,26 +119,26 @@ std::vector TreeSupportTipGenerator::c LineInformation res_line; for (const Point2LL& p : line) { - if (config.support_rest_preference == RestPreference::BUILDPLATE - && ! volumes_.getAvoidance(config.getRadius(0), layer_idx, AvoidanceType::FAST_SAFE, false, ! xy_overrides).inside(p, true)) + if (config_.support_rest_preference == RestPreference::BUILDPLATE + && ! volumes_.getAvoidance(config_.getRadius(0), layer_idx, AvoidanceType::FAST_SAFE, false, ! xy_overrides_).inside(p, true)) { res_line.emplace_back(p, LineStatus::TO_BP_SAFE); } else if ( - config.support_rest_preference == RestPreference::BUILDPLATE - && ! volumes_.getAvoidance(config.getRadius(0), layer_idx, AvoidanceType::FAST, false, ! xy_overrides).inside(p, true)) + config_.support_rest_preference == RestPreference::BUILDPLATE + && ! volumes_.getAvoidance(config_.getRadius(0), layer_idx, AvoidanceType::FAST, false, ! xy_overrides_).inside(p, true)) { res_line.emplace_back(p, LineStatus::TO_BP); } - else if (config.support_rests_on_model && ! volumes_.getAvoidance(config.getRadius(0), layer_idx, AvoidanceType::FAST_SAFE, true, ! xy_overrides).inside(p, true)) + else if (config_.support_rests_on_model && ! volumes_.getAvoidance(config_.getRadius(0), layer_idx, AvoidanceType::FAST_SAFE, true, ! xy_overrides_).inside(p, true)) { res_line.emplace_back(p, LineStatus::TO_MODEL_GRACIOUS_SAFE); } - else if (config.support_rests_on_model && ! volumes_.getAvoidance(config.getRadius(0), layer_idx, AvoidanceType::FAST, true, ! xy_overrides).inside(p, true)) + else if (config_.support_rests_on_model && ! volumes_.getAvoidance(config_.getRadius(0), layer_idx, AvoidanceType::FAST, true, ! xy_overrides_).inside(p, true)) { res_line.emplace_back(p, LineStatus::TO_MODEL_GRACIOUS); } - else if (config.support_rests_on_model && ! volumes_.getAvoidance(config.getRadius(0), layer_idx, AvoidanceType::COLLISION, true, ! xy_overrides).inside(p, true)) + else if (config_.support_rests_on_model && ! volumes_.getAvoidance(config_.getRadius(0), layer_idx, AvoidanceType::COLLISION, true, ! xy_overrides_).inside(p, true)) { res_line.emplace_back(p, LineStatus::TO_MODEL); } @@ -177,34 +177,34 @@ std::function)> Tr { std::function)> evaluatePoint = [this, current_layer](std::pair p) { - if (config.support_rest_preference != RestPreference::GRACEFUL + if (config_.support_rest_preference != RestPreference::GRACEFUL && ! volumes_ .getAvoidance( - config.getRadius(0), + config_.getRadius(0), current_layer - 1, p.second == LineStatus::TO_BP_SAFE ? AvoidanceType::FAST_SAFE : AvoidanceType::FAST, false, - ! xy_overrides) + ! xy_overrides_) .inside(p.first, true)) { return true; } - if (config.support_rests_on_model && (p.second != LineStatus::TO_BP && p.second != LineStatus::TO_BP_SAFE)) + if (config_.support_rests_on_model && (p.second != LineStatus::TO_BP && p.second != LineStatus::TO_BP_SAFE)) { if (p.second == LineStatus::TO_MODEL_GRACIOUS || p.second == LineStatus::TO_MODEL_GRACIOUS_SAFE) { return ! volumes_ .getAvoidance( - config.getRadius(0), + config_.getRadius(0), current_layer - 1, p.second == LineStatus::TO_MODEL_GRACIOUS_SAFE ? AvoidanceType::FAST_SAFE : AvoidanceType::FAST, true, - ! xy_overrides) + ! xy_overrides_) .inside(p.first, true); } else { - return ! volumes_.getAvoidance(config.getRadius(0), current_layer - 1, AvoidanceType::COLLISION, true, ! xy_overrides).inside(p.first, true); + return ! volumes_.getAvoidance(config_.getRadius(0), current_layer - 1, AvoidanceType::COLLISION, true, ! xy_overrides_).inside(p.first, true); } } return false; @@ -380,7 +380,7 @@ Polygons TreeSupportTipGenerator::ensureMaximumDistancePolyline(const Polygons& std::shared_ptr TreeSupportTipGenerator::generateCrossFillProvider(const SliceMeshStorage& mesh, coord_t line_distance, coord_t line_width) const { - if (config.support_pattern == EFillMethod::CROSS || config.support_pattern == EFillMethod::CROSS_3D) + if (config_.support_pattern == EFillMethod::CROSS || config_.support_pattern == EFillMethod::CROSS_3D) { AABB3D aabb; if (mesh.settings.get("infill_mesh") || mesh.settings.get("anti_overhang_mesh")) @@ -413,42 +413,42 @@ void TreeSupportTipGenerator::dropOverhangAreas(const SliceMeshStorage& mesh, st // this is ugly, but as far as i can see there is not way to ensure a parallel_for loop is calculated for each iteration up to a certain point before it continues; cura::parallel_for( 1, - mesh.overhang_areas.size() - z_distance_delta, + mesh.overhang_areas.size() - z_distance_delta_, [&](const LayerIndex layer_idx) { - if (mesh.overhang_areas[layer_idx + z_distance_delta].empty() || result.size() < layer_idx) + if (mesh.overhang_areas[layer_idx + z_distance_delta_].empty() || result.size() < layer_idx) { return; // This is a continue if imagined in a loop context. } - Polygons relevant_forbidden = volumes_.getCollision(roof ? 0 : config.getRadius(0), layer_idx, ! xy_overrides); + Polygons relevant_forbidden = volumes_.getCollision(roof ? 0 : config_.getRadius(0), layer_idx, ! xy_overrides_); // ^^^ Take the least restrictive avoidance possible // Technically this also makes support blocker smaller, which is wrong as they do not have a xy_distance, but it should be good enough. - Polygons model_outline = volumes_.getCollision(0, layer_idx, ! xy_overrides).offset(-config.xy_min_distance, ClipperLib::jtRound); + Polygons model_outline = volumes_.getCollision(0, layer_idx, ! xy_overrides_).offset(-config_.xy_min_distance, ClipperLib::jtRound); Polygons overhang_regular = TreeSupportUtils::safeOffsetInc( - mesh.overhang_areas[layer_idx + z_distance_delta], - roof ? roof_outset : support_outset, + mesh.overhang_areas[layer_idx + z_distance_delta_], + roof ? roof_outset_ : support_outset_, relevant_forbidden, - config.min_radius * 1.75 + config.xy_min_distance, + config_.min_radius * 1.75 + config_.xy_min_distance, 0, 1, - config.support_line_distance / 2, - &config.simplifier); - Polygons remaining_overhang = mesh.overhang_areas[layer_idx + z_distance_delta] - .offset(roof ? roof_outset : support_outset) + config_.support_line_distance / 2, + &config_.simplifier); + Polygons remaining_overhang = mesh.overhang_areas[layer_idx + z_distance_delta_] + .offset(roof ? roof_outset_ : support_outset_) .difference(overhang_regular) .intersection(relevant_forbidden) .difference(model_outline); - for (size_t lag_ctr = 1; lag_ctr <= max_overhang_insert_lag && layer_idx - coord_t(lag_ctr) >= 1 && ! remaining_overhang.empty(); lag_ctr++) + for (size_t lag_ctr = 1; lag_ctr <= max_overhang_insert_lag_ && layer_idx - coord_t(lag_ctr) >= 1 && ! remaining_overhang.empty(); lag_ctr++) { { std::lock_guard critical_section_storage(critical); result[layer_idx - lag_ctr].add(remaining_overhang); } - Polygons relevant_forbidden_below = volumes_.getCollision(roof ? 0 : config.getRadius(0), layer_idx - lag_ctr, ! xy_overrides).offset(EPSILON); + Polygons relevant_forbidden_below = volumes_.getCollision(roof ? 0 : config_.getRadius(0), layer_idx - lag_ctr, ! xy_overrides_).offset(EPSILON); remaining_overhang = remaining_overhang.intersection(relevant_forbidden_below).unionPolygons().difference(model_outline); } }); @@ -468,17 +468,17 @@ void TreeSupportTipGenerator::calculateRoofAreas(const cura::SliceMeshStorage& m std::mutex critical_potential_support_roofs; std::vector dropped_overhangs(mesh.overhang_areas.size(), Polygons()); - if (xy_overrides) + if (xy_overrides_) { dropOverhangAreas(mesh, dropped_overhangs, true); } cura::parallel_for( 0, - mesh.overhang_areas.size() - z_distance_delta, + mesh.overhang_areas.size() - z_distance_delta_, [&](const LayerIndex layer_idx) { - if (mesh.overhang_areas[layer_idx + z_distance_delta].empty()) + if (mesh.overhang_areas[layer_idx + z_distance_delta_].empty()) { return; // This is a continue if imagined in a loop context. } @@ -487,42 +487,42 @@ void TreeSupportTipGenerator::calculateRoofAreas(const cura::SliceMeshStorage& m // -radius. This is intentional here, as support roof is still valid if only a part of the tip may reach it. Polygons forbidden_here = volumes_ .getAvoidance( - config.getRadius(0), + config_.getRadius(0), layer_idx, - (only_gracious || ! config.support_rests_on_model) ? AvoidanceType::FAST : AvoidanceType::COLLISION, - config.support_rests_on_model, - ! xy_overrides) - .offset(-config.getRadius(0), ClipperLib::jtRound); + (only_gracious_ || ! config_.support_rests_on_model) ? AvoidanceType::FAST : AvoidanceType::COLLISION, + config_.support_rests_on_model, + ! xy_overrides_) + .offset(-config_.getRadius(0), ClipperLib::jtRound); // todo Since arachnea the assumption that an area smaller then line_width is not printed is no longer true all such safeOffset should have config.support_line_width // replaced with another setting. It should still work in most cases, but it should be possible to create a situation where a overhang outset lags though a wall. I will // take a look at this later. Polygons full_overhang_area = TreeSupportUtils::safeOffsetInc( - mesh.full_overhang_areas[layer_idx + z_distance_delta].unionPolygons(dropped_overhangs[layer_idx]), - roof_outset, + mesh.full_overhang_areas[layer_idx + z_distance_delta_].unionPolygons(dropped_overhangs[layer_idx]), + roof_outset_, forbidden_here, - config.support_line_width, + config_.support_line_width, 0, 1, - config.support_line_distance / 2, - &config.simplifier); + config_.support_line_distance / 2, + &config_.simplifier); - for (LayerIndex dtt_roof = 0; dtt_roof < support_roof_layers && layer_idx - dtt_roof >= 1; dtt_roof++) + for (LayerIndex dtt_roof = 0; dtt_roof < support_roof_layers_ && layer_idx - dtt_roof >= 1; dtt_roof++) { const Polygons forbidden_next = volumes_ .getAvoidance( - config.getRadius(0), + config_.getRadius(0), layer_idx - (dtt_roof + 1), - (only_gracious || ! config.support_rests_on_model) ? AvoidanceType::FAST : AvoidanceType::COLLISION, - config.support_rests_on_model, - ! xy_overrides) - .offset(-config.getRadius(0), ClipperLib::jtRound); + (only_gracious_ || ! config_.support_rests_on_model) ? AvoidanceType::FAST : AvoidanceType::COLLISION, + config_.support_rests_on_model, + ! xy_overrides_) + .offset(-config_.getRadius(0), ClipperLib::jtRound); full_overhang_area = full_overhang_area.difference(forbidden_next); - if (force_minimum_roof_area) + if (force_minimum_roof_area_) { - full_overhang_area.removeSmallAreas(minimum_roof_area); + full_overhang_area.removeSmallAreas(minimum_roof_area_); } if (full_overhang_area.area() > EPSILON) @@ -548,9 +548,9 @@ void TreeSupportTipGenerator::calculateRoofAreas(const cura::SliceMeshStorage& m // with using the default mitered here. Could be that i just have not encountered an issue with it yet though. potential_support_roofs[layer_idx] = potential_support_roofs[layer_idx] .unionPolygons() - .offset(config.xy_min_distance) + .offset(config_.xy_min_distance) .unionPolygons() - .offset(-config.xy_min_distance) + .offset(-config_.xy_min_distance) .unionPolygons(potential_support_roofs[layer_idx]); }); @@ -567,28 +567,28 @@ void TreeSupportTipGenerator::calculateRoofAreas(const cura::SliceMeshStorage& m // -radius. This is intentional here, as support roof is still valid if only a part of the tip may reach it. Polygons forbidden_here = volumes_ .getAvoidance( - config.getRadius(0), + config_.getRadius(0), layer_idx, - (only_gracious || ! config.support_rests_on_model) ? AvoidanceType::FAST : AvoidanceType::COLLISION, - config.support_rests_on_model, - ! xy_overrides) - .offset(-(config.getRadius(0)), ClipperLib::jtRound); + (only_gracious_ || ! config_.support_rests_on_model) ? AvoidanceType::FAST : AvoidanceType::COLLISION, + config_.support_rests_on_model, + ! xy_overrides_) + .offset(-(config_.getRadius(0)), ClipperLib::jtRound); - if (! force_minimum_roof_area) + if (! force_minimum_roof_area_) { Polygons fuzzy_area = Polygons(); // the roof will be combined with roof above and below, to see if a part of this roof may be part of a valid roof further up/down. // This prevents the situation where a roof gets removed even tough its area would contribute to a (better) printable roof area further down. for (const LayerIndex layer_offset : ranges::views::iota( - -LayerIndex{ std::min(layer_idx, LayerIndex{ support_roof_layers }) }, - LayerIndex{ std::min(LayerIndex{ potential_support_roofs.size() - layer_idx }, LayerIndex{ support_roof_layers + 1 }) })) + -LayerIndex{ std::min(layer_idx, LayerIndex{ support_roof_layers_ }) }, + LayerIndex{ std::min(LayerIndex{ potential_support_roofs.size() - layer_idx }, LayerIndex{ support_roof_layers_ + 1 }) })) { - fuzzy_area.add(support_roof_drawn[layer_idx + layer_offset]); + fuzzy_area.add(support_roof_drawn_[layer_idx + layer_offset]); fuzzy_area.add(potential_support_roofs[layer_idx + layer_offset]); } fuzzy_area = fuzzy_area.unionPolygons(); - fuzzy_area.removeSmallAreas(std::max(minimum_roof_area, tip_roof_size)); + fuzzy_area.removeSmallAreas(std::max(minimum_roof_area_, tip_roof_size_)); for (Polygons potential_roof : potential_support_roofs[layer_idx].difference(forbidden_here).splitIntoParts()) { @@ -601,7 +601,7 @@ void TreeSupportTipGenerator::calculateRoofAreas(const cura::SliceMeshStorage& m else { Polygons valid_roof = potential_support_roofs[layer_idx].difference(forbidden_here); - valid_roof.removeSmallAreas(std::max(minimum_roof_area, tip_roof_size)); + valid_roof.removeSmallAreas(std::max(minimum_roof_area_, tip_roof_size_)); additional_support_roofs[layer_idx].add(valid_roof); } } @@ -612,7 +612,7 @@ void TreeSupportTipGenerator::calculateRoofAreas(const cura::SliceMeshStorage& m additional_support_roofs.size(), [&](const LayerIndex layer_idx) { - support_roof_drawn[layer_idx] = support_roof_drawn[layer_idx].unionPolygons(additional_support_roofs[layer_idx]); + support_roof_drawn_[layer_idx] = support_roof_drawn_[layer_idx].unionPolygons(additional_support_roofs[layer_idx]); }); } @@ -630,7 +630,7 @@ void TreeSupportTipGenerator::addPointAsInfluenceArea( const bool to_bp = p.second == LineStatus::TO_BP || p.second == LineStatus::TO_BP_SAFE; const bool gracious = to_bp || p.second == LineStatus::TO_MODEL_GRACIOUS || p.second == LineStatus::TO_MODEL_GRACIOUS_SAFE; const bool safe_radius = p.second == LineStatus::TO_BP_SAFE || p.second == LineStatus::TO_MODEL_GRACIOUS_SAFE; - if (! config.support_rests_on_model && ! to_bp) + if (! config_.support_rests_on_model && ! to_bp) { spdlog::warn("Tried to add an invalid support point"); return; @@ -643,25 +643,25 @@ void TreeSupportTipGenerator::addPointAsInfluenceArea( } Polygons area = circle.offset(0); { - std::lock_guard critical_section_movebounds(critical_move_bounds); - if (! already_inserted[insert_layer].count(p.first / ((config.min_radius + 1) / 10))) + std::lock_guard critical_section_movebounds(critical_move_bounds_); + if (! already_inserted_[insert_layer].count(p.first / ((config_.min_radius + 1) / 10))) { // Normalize the point a bit to also catch points which are so close that inserting it would achieve nothing. - already_inserted[insert_layer].emplace(p.first / ((config.min_radius + 1) / 10)); + already_inserted_[insert_layer].emplace(p.first / ((config_.min_radius + 1) / 10)); TreeSupportElement* elem = new TreeSupportElement( dtt, insert_layer, p.first, to_bp, gracious, - ! xy_overrides, + ! xy_overrides_, dont_move_until, roof, safe_radius, - force_tip_to_roof, + force_tip_to_roof_, skip_ovalisation, - support_tree_limit_branch_reach, - support_tree_branch_reach_limit); + support_tree_limit_branch_reach_, + support_tree_branch_reach_limit_); elem->area_ = new Polygons(area); for (Point2LL target : additional_ovalization_targets) @@ -687,7 +687,7 @@ void TreeSupportTipGenerator::addLinesAsInfluenceAreas( // Add tip area as roof (happens when minimum roof area > minimum tip area) if possible. This is required as there is no guarantee that if support_roof_wall_count == 0 that a // certain roof area will actually have lines. size_t dtt_roof_tip = 0; - if (config.support_roof_wall_count == 0) + if (config_.support_roof_wall_count == 0) { for (dtt_roof_tip = 0; dtt_roof_tip < roof_tip_layers && insert_layer_idx - dtt_roof_tip >= 1; dtt_roof_tip++) { @@ -696,10 +696,10 @@ void TreeSupportTipGenerator::addLinesAsInfluenceAreas( Polygon roof_circle; for (Point2LL corner : TreeSupportBaseCircle::getBaseCircle()) { - roof_circle.add(p.first + corner * std::max(config.min_radius / TreeSupportBaseCircle::base_radius, coord_t(1))); + roof_circle.add(p.first + corner * std::max(config_.min_radius / TreeSupportBaseCircle::base_radius, coord_t(1))); } Polygons area = roof_circle.offset(0); - return ! TreeSupportUtils::generateSupportInfillLines(area, config, true, insert_layer_idx - dtt_roof_tip, support_roof_line_distance, cross_fill_provider, true) + return ! TreeSupportUtils::generateSupportInfillLines(area, config_, true, insert_layer_idx - dtt_roof_tip, support_roof_line_distance_, cross_fill_provider_, true) .empty(); }; @@ -735,16 +735,16 @@ void TreeSupportTipGenerator::addLinesAsInfluenceAreas( Polygon roof_circle; for (Point2LL corner : TreeSupportBaseCircle::getBaseCircle()) { - roof_circle.add(p.first + corner * std::max(config.min_radius / TreeSupportBaseCircle::base_radius, coord_t(1))); + roof_circle.add(p.first + corner * std::max(config_.min_radius / TreeSupportBaseCircle::base_radius, coord_t(1))); } added_roofs.add(roof_circle); } } added_roofs = added_roofs.unionPolygons(); { - std::lock_guard critical_section_roof(critical_roof_tips); + std::lock_guard critical_section_roof(critical_roof_tips_); - roof_tips_drawn[insert_layer_idx - dtt_roof_tip].add(added_roofs); + roof_tips_drawn_[insert_layer_idx - dtt_roof_tip].add(added_roofs); } } } @@ -754,7 +754,7 @@ void TreeSupportTipGenerator::addLinesAsInfluenceAreas( // If a line consists of enough tips, the assumption is that it is not a single tip, but part of a simulated support pattern. // Ovalisation should be disabled if they may be placed close to each other to prevent tip-areas merging. If the tips has to turn into roof, the area is most likely not // large enough for this to cause issues. - const bool disable_ovalization = ! connect_points && config.min_radius < 3 * config.support_line_width && roof_tip_layers == 0 && dtt_roof_tip == 0; + const bool disable_ovalization = ! connect_points && config_.min_radius < 3 * config_.support_line_width && roof_tip_layers == 0 && dtt_roof_tip == 0; for (auto [idx, point_data] : line | ranges::views::enumerate) { std::vector additional_ovalization_targets; @@ -796,10 +796,10 @@ void TreeSupportTipGenerator::removeUselessAddedPoints( if (layer_idx + 1 < storage.support.supportLayers.size()) { std::vector to_be_removed; - Polygons roof_on_layer_above = use_fake_roof ? support_roof_drawn[layer_idx + 1] - : storage.support.supportLayers[layer_idx + 1].support_roof.unionPolygons(additional_support_areas[layer_idx + 1]); + Polygons roof_on_layer_above = use_fake_roof_ ? support_roof_drawn_[layer_idx + 1] + : storage.support.supportLayers[layer_idx + 1].support_roof.unionPolygons(additional_support_areas[layer_idx + 1]); Polygons roof_on_layer - = use_fake_roof ? support_roof_drawn[layer_idx] : storage.support.supportLayers[layer_idx].support_roof.unionPolygons(additional_support_areas[layer_idx]); + = use_fake_roof_ ? support_roof_drawn_[layer_idx] : storage.support.supportLayers[layer_idx].support_roof.unionPolygons(additional_support_areas[layer_idx]); for (TreeSupportElement* elem : move_bounds[layer_idx]) { @@ -814,7 +814,7 @@ void TreeSupportTipGenerator::removeUselessAddedPoints( // Remove branches should have interface above them, but dont. Should never happen. if (roof_on_layer_above.empty() || (! roof_on_layer_above.inside(elem->result_on_layer_) - && vSize2(from - elem->result_on_layer_) > config.getRadius(0) * config.getRadius(0) + FUDGE_LENGTH * FUDGE_LENGTH)) + && vSize2(from - elem->result_on_layer_) > config_.getRadius(0) * config_.getRadius(0) + FUDGE_LENGTH * FUDGE_LENGTH)) { to_be_removed.emplace_back(elem); spdlog::warn("Removing already placed tip that should have roof above it?"); @@ -843,37 +843,37 @@ void TreeSupportTipGenerator::generateTips( std::vector> new_tips(move_bounds.size()); const coord_t circle_length_to_half_linewidth_change - = config.min_radius < config.support_line_width ? config.min_radius / 2 : sqrt(square(config.min_radius) - square(config.min_radius - config.support_line_width / 2)); + = config_.min_radius < config_.support_line_width ? config_.min_radius / 2 : sqrt(square(config_.min_radius) - square(config_.min_radius - config_.support_line_width / 2)); // ^^^ As r*r=x*x+y*y (circle equation): If a circle with center at (0,0) the top most point is at (0,r) as in y=r. This calculates how far one has to move on the x-axis so // that y=r-support_line_width/2. // In other words how far does one need to move on the x-axis to be support_line_width/2 away from the circle line. As a circle is round this length is identical for every // axis as long as the 90� angle between both remains. - const coord_t extra_outset = std::max(coord_t(0), config.min_radius - config.support_line_width / 2) + (xy_overrides ? 0 : config.support_line_width / 2); + const coord_t extra_outset = std::max(coord_t(0), config_.min_radius - config_.support_line_width / 2) + (xy_overrides_ ? 0 : config_.support_line_width / 2); // ^^^ Extra support offset to compensate for larger tip radiis. Also outset a bit more when z overwrites xy, because supporting something with a part of a support line is // better than not supporting it at all. - if (support_roof_layers) + if (support_roof_layers_) { calculateRoofAreas(mesh); } cura::parallel_for( 1, - mesh.overhang_areas.size() - z_distance_delta, + mesh.overhang_areas.size() - z_distance_delta_, [&](const LayerIndex layer_idx) { - if (mesh.overhang_areas[layer_idx + z_distance_delta].empty() && (layer_idx + 1 >= support_roof_drawn.size() || support_roof_drawn[layer_idx + 1].empty())) + if (mesh.overhang_areas[layer_idx + z_distance_delta_].empty() && (layer_idx + 1 >= support_roof_drawn_.size() || support_roof_drawn_[layer_idx + 1].empty())) { return; // This is a continue if imagined in a loop context. } Polygons relevant_forbidden = volumes_.getAvoidance( - config.getRadius(0), + config_.getRadius(0), layer_idx, - (only_gracious || ! config.support_rests_on_model) ? AvoidanceType::FAST : AvoidanceType::COLLISION, - config.support_rests_on_model, - ! xy_overrides); + (only_gracious_ || ! config_.support_rests_on_model) ? AvoidanceType::FAST : AvoidanceType::COLLISION, + config_.support_rests_on_model, + ! xy_overrides_); // ^^^ Take the least restrictive avoidance possible relevant_forbidden = relevant_forbidden.offset(EPSILON) @@ -881,17 +881,17 @@ void TreeSupportTipGenerator::generateTips( std::function generateLines = [&](const Polygons& area, bool roof, LayerIndex generate_layer_idx) { - coord_t upper_line_distance = support_supporting_branch_distance; - coord_t line_distance = std::max(roof ? support_roof_line_distance : support_tree_branch_distance, upper_line_distance); + coord_t upper_line_distance = support_supporting_branch_distance_; + coord_t line_distance = std::max(roof ? support_roof_line_distance_ : support_tree_branch_distance_, upper_line_distance); return TreeSupportUtils::generateSupportInfillLines( area, - config, - roof && ! use_fake_roof, + config_, + roof && ! use_fake_roof_, generate_layer_idx, line_distance, - cross_fill_provider, - roof && ! use_fake_roof, + cross_fill_provider_, + roof && ! use_fake_roof_, line_distance == upper_line_distance); }; @@ -902,14 +902,14 @@ void TreeSupportTipGenerator::generateTips( // horizontal expansion and it would not have a roof if the overhang is offset by support roof horizontal expansion instead. (At least this is the current behavior // of the regular support) - Polygons core_overhang = mesh.overhang_areas[layer_idx + z_distance_delta]; + Polygons core_overhang = mesh.overhang_areas[layer_idx + z_distance_delta_]; - if (support_roof_layers && layer_idx + 1 < support_roof_drawn.size()) + if (support_roof_layers_ && layer_idx + 1 < support_roof_drawn_.size()) { - core_overhang = core_overhang.difference(support_roof_drawn[layer_idx]); - for (Polygons roof_part : support_roof_drawn[layer_idx + 1] - .difference(support_roof_drawn[layer_idx]) + core_overhang = core_overhang.difference(support_roof_drawn_[layer_idx]); + for (Polygons roof_part : support_roof_drawn_[layer_idx + 1] + .difference(support_roof_drawn_[layer_idx]) .splitIntoParts(true)) // If there is a roof, the roof will be one layer above the tips. { //^^^Technically one should also subtract the avoidance of radius 0 (similarly how calculated in calculateRoofArea), as there can be some rounding errors @@ -920,65 +920,65 @@ void TreeSupportTipGenerator::generateTips( Polygons overhang_regular = TreeSupportUtils::safeOffsetInc( core_overhang, - support_outset, + support_outset_, relevant_forbidden, - config.min_radius * 1.75 + config.xy_min_distance, + config_.min_radius * 1.75 + config_.xy_min_distance, 0, 1, - config.support_line_distance / 2, - &config.simplifier); + config_.support_line_distance / 2, + &config_.simplifier); Polygons remaining_overhang - = core_overhang.offset(support_outset).difference(overhang_regular.offset(config.support_line_width * 0.5)).intersection(relevant_forbidden); + = core_overhang.offset(support_outset_).difference(overhang_regular.offset(config_.support_line_width * 0.5)).intersection(relevant_forbidden); // Offset ensures that areas that could be supported by a part of a support line, are not considered unsupported overhang coord_t extra_total_offset_acc = 0; // Offset the area to compensate for large tip radiis. Offset happens in multiple steps to ensure the tip is as close to the original overhang as possible. - while (extra_total_offset_acc + config.support_line_width / 8 + while (extra_total_offset_acc + config_.support_line_width / 8 < extra_outset) //+mesh_config.support_line_width / 8 to avoid calculating very small (useless) offsets because of rounding errors. { - coord_t offset_current_step = extra_total_offset_acc + 2 * config.support_line_width > config.min_radius - ? std::min(config.support_line_width / 8, extra_outset - extra_total_offset_acc) + coord_t offset_current_step = extra_total_offset_acc + 2 * config_.support_line_width > config_.min_radius + ? std::min(config_.support_line_width / 8, extra_outset - extra_total_offset_acc) : std::min(circle_length_to_half_linewidth_change, extra_outset - extra_total_offset_acc); extra_total_offset_acc += offset_current_step; Polygons overhang_offset = TreeSupportUtils::safeOffsetInc( overhang_regular, 1.5 * extra_total_offset_acc, volumes_.getCollision(0, layer_idx, true), - config.xy_min_distance + config.support_line_width, + config_.xy_min_distance + config_.support_line_width, 0, 1, - config.support_line_distance / 2, - &config.simplifier); - remaining_overhang = remaining_overhang.difference(overhang_offset.unionPolygons(support_roof_drawn[layer_idx].offset(1.5 * extra_total_offset_acc))) + config_.support_line_distance / 2, + &config_.simplifier); + remaining_overhang = remaining_overhang.difference(overhang_offset.unionPolygons(support_roof_drawn_[layer_idx].offset(1.5 * extra_total_offset_acc))) .unionPolygons(); // overhang_offset is combined with roof, as all area that has a roof, is already supported by said roof. Polygons next_overhang = TreeSupportUtils::safeOffsetInc( remaining_overhang, extra_total_offset_acc, volumes_.getCollision(0, layer_idx, true), - config.xy_min_distance + config.support_line_width, + config_.xy_min_distance + config_.support_line_width, 0, 1, - config.support_line_distance / 2, - &config.simplifier); + config_.support_line_distance / 2, + &config_.simplifier); overhang_regular = overhang_regular.unionPolygons(next_overhang.difference(relevant_forbidden)); } // If the xy distance overrides the z distance, some support needs to be inserted further down. //=> Analyze which support points do not fit on this layer and check if they will fit a few layers down // (while adding them an infinite amount of layers down would technically be closer the setting description, it would not produce reasonable results. ) - if (xy_overrides) + if (xy_overrides_) { for (Polygons& remaining_overhang_part : remaining_overhang.splitIntoParts(false)) { - if (remaining_overhang_part.area() <= MM2_2INT(minimum_support_area)) + if (remaining_overhang_part.area() <= MM2_2INT(minimum_support_area_)) { continue; } std::vector overhang_lines; - Polygons polylines = ensureMaximumDistancePolyline(generateLines(remaining_overhang_part, false, layer_idx), config.min_radius, 1, false); + Polygons polylines = ensureMaximumDistancePolyline(generateLines(remaining_overhang_part, false, layer_idx), config_.min_radius, 1, false); // ^^^ Support_line_width to form a line here as otherwise most will be unsupported. // Technically this violates branch distance, but not only is this the only reasonable choice, // but it ensures consistent behavior as some infill patterns generate each line segment as its own polyline part causing a similar line forming behavior. @@ -986,7 +986,7 @@ void TreeSupportTipGenerator::generateTips( if (polylines.pointCount() <= 3) { // Add the outer wall to ensure it is correct supported instead. - polylines = ensureMaximumDistancePolyline(TreeSupportUtils::toPolylines(remaining_overhang_part), connect_length, 3, true); + polylines = ensureMaximumDistancePolyline(TreeSupportUtils::toPolylines(remaining_overhang_part), connect_length_, 3, true); } for (auto line : polylines) @@ -999,15 +999,15 @@ void TreeSupportTipGenerator::generateTips( overhang_lines.emplace_back(res_line); } - for (size_t lag_ctr = 1; lag_ctr <= max_overhang_insert_lag && ! overhang_lines.empty() && layer_idx - coord_t(lag_ctr) >= 1; lag_ctr++) + for (size_t lag_ctr = 1; lag_ctr <= max_overhang_insert_lag_ && ! overhang_lines.empty() && layer_idx - coord_t(lag_ctr) >= 1; lag_ctr++) { // get least restricted avoidance for layer_idx-lag_ctr Polygons relevant_forbidden_below = volumes_.getAvoidance( - config.getRadius(0), + config_.getRadius(0), layer_idx - lag_ctr, - (only_gracious || ! config.support_rests_on_model) ? AvoidanceType::FAST : AvoidanceType::COLLISION, - config.support_rests_on_model, - ! xy_overrides); + (only_gracious_ || ! config_.support_rests_on_model) ? AvoidanceType::FAST : AvoidanceType::COLLISION, + config_.support_rests_on_model, + ! xy_overrides_); // It is not required to offset the forbidden area here as the points won't change: // If points here are not inside the forbidden area neither will they be later when placing these points, as these are the same points. std::function)> evaluatePoint = [&](std::pair p) @@ -1015,12 +1015,12 @@ void TreeSupportTipGenerator::generateTips( return relevant_forbidden_below.inside(p.first, true); }; - if (support_roof_layers) + if (support_roof_layers_) { // Remove all points that are for some reason part of a roof area, as the point is already supported by roof std::function)> evaluatePartOfRoof = [&](std::pair p) { - return support_roof_drawn[layer_idx - lag_ctr].inside(p.first, true); + return support_roof_drawn_[layer_idx - lag_ctr].inside(p.first, true); }; overhang_lines = splitLines(overhang_lines, evaluatePartOfRoof).second; @@ -1034,16 +1034,16 @@ void TreeSupportTipGenerator::generateTips( addLinesAsInfluenceAreas( new_tips, fresh_valid_points, - (force_tip_to_roof && lag_ctr <= support_roof_layers) ? support_roof_layers : 0, + (force_tip_to_roof_ && lag_ctr <= support_roof_layers_) ? support_roof_layers_ : 0, layer_idx - lag_ctr, false, - support_roof_layers, + support_roof_layers_, false); } } } - overhang_regular.removeSmallAreas(minimum_support_area); + overhang_regular.removeSmallAreas(minimum_support_area_); for (Polygons support_part : overhang_regular.splitIntoParts(true)) { @@ -1054,7 +1054,7 @@ void TreeSupportTipGenerator::generateTips( { const bool roof_allowed_for_this_part = overhang_pair.second; Polygons overhang_outset = overhang_pair.first; - const size_t min_support_points = std::max(coord_t(1), std::min(coord_t(EPSILON), overhang_outset.polygonLength() / connect_length)); + const size_t min_support_points = std::max(coord_t(1), std::min(coord_t(EPSILON), overhang_outset.polygonLength() / connect_length_)); std::vector overhang_lines; bool only_lines = true; @@ -1063,9 +1063,9 @@ void TreeSupportTipGenerator::generateTips( // todo can cause inconsistent support density if a line exactly aligns with the model Polygons polylines = ensureMaximumDistancePolyline( generateLines(overhang_outset, roof_allowed_for_this_part, layer_idx + roof_allowed_for_this_part), - ! roof_allowed_for_this_part ? config.min_radius * 2 - : use_fake_roof ? support_supporting_branch_distance - : connect_length, + ! roof_allowed_for_this_part ? config_.min_radius * 2 + : use_fake_roof_ ? support_supporting_branch_distance_ + : connect_length_, 1, false); @@ -1080,33 +1080,33 @@ void TreeSupportTipGenerator::generateTips( only_lines = false; // Add the outer wall (of the overhang) to ensure it is correct supported instead. // Try placing the support points in a way that they fully support the outer wall, instead of just the with half of the support line width. - Polygons reduced_overhang_outset = overhang_outset.offset(-config.support_line_width / 2.2); + Polygons reduced_overhang_outset = overhang_outset.offset(-config_.support_line_width / 2.2); // ^^^ It's assumed that even small overhangs are over one line width wide, so lets try to place the support points in a way that the full support area // generated from them will support the overhang. // (If this is not done it may only be half). This WILL NOT be the case when supporting an angle of about < 60� so there is a fallback, as some support is // better than none.) if (! reduced_overhang_outset.empty() - && overhang_outset.difference(reduced_overhang_outset.offset(std::max(config.support_line_width, connect_length))).area() < 1) + && overhang_outset.difference(reduced_overhang_outset.offset(std::max(config_.support_line_width, connect_length_))).area() < 1) { - polylines = ensureMaximumDistancePolyline(TreeSupportUtils::toPolylines(reduced_overhang_outset), connect_length, min_support_points, true); + polylines = ensureMaximumDistancePolyline(TreeSupportUtils::toPolylines(reduced_overhang_outset), connect_length_, min_support_points, true); } else { - polylines = ensureMaximumDistancePolyline(TreeSupportUtils::toPolylines(overhang_outset), connect_length, min_support_points, true); + polylines = ensureMaximumDistancePolyline(TreeSupportUtils::toPolylines(overhang_outset), connect_length_, min_support_points, true); } } if (roof_allowed_for_this_part) // Some roof may only be supported by a part of a tip { - polylines = TreeSupportUtils::movePointsOutside(polylines, relevant_forbidden, config.getRadius(0) + FUDGE_LENGTH / 2); + polylines = TreeSupportUtils::movePointsOutside(polylines, relevant_forbidden, config_.getRadius(0) + FUDGE_LENGTH / 2); } overhang_lines = convertLinesToInternal(polylines, layer_idx); if (overhang_lines.empty()) // some error handling and logging { - Polygons enlarged_overhang_outset = overhang_outset.offset(config.getRadius(0) + FUDGE_LENGTH / 2, ClipperLib::jtRound).difference(relevant_forbidden); - polylines = ensureMaximumDistancePolyline(TreeSupportUtils::toPolylines(enlarged_overhang_outset), connect_length, min_support_points, true); + Polygons enlarged_overhang_outset = overhang_outset.offset(config_.getRadius(0) + FUDGE_LENGTH / 2, ClipperLib::jtRound).difference(relevant_forbidden); + polylines = ensureMaximumDistancePolyline(TreeSupportUtils::toPolylines(enlarged_overhang_outset), connect_length_, min_support_points, true); overhang_lines = convertLinesToInternal(polylines, layer_idx); if (! overhang_lines.empty()) @@ -1119,11 +1119,11 @@ void TreeSupportTipGenerator::generateTips( } } - size_t dont_move_for_layers = support_roof_layers ? (force_tip_to_roof ? support_roof_layers : (roof_allowed_for_this_part ? 0 : support_roof_layers)) : 0; + size_t dont_move_for_layers = support_roof_layers_ ? (force_tip_to_roof_ ? support_roof_layers_ : (roof_allowed_for_this_part ? 0 : support_roof_layers_)) : 0; addLinesAsInfluenceAreas( new_tips, overhang_lines, - force_tip_to_roof ? support_roof_layers : 0, + force_tip_to_roof_ ? support_roof_layers_ : 0, layer_idx, roof_allowed_for_this_part, dont_move_for_layers, @@ -1133,20 +1133,20 @@ void TreeSupportTipGenerator::generateTips( cura::parallel_for( 0, - support_roof_drawn.size(), + support_roof_drawn_.size(), [&](const LayerIndex layer_idx) { // Sometimes roofs could be empty as the pattern does not generate lines if the area is narrow enough. // If there is a roof could have zero lines in its area (as it has no wall), rand a support area would very likely be printed (because there are walls for the support // areas), replace non printable roofs with support - if (! use_fake_roof && config.support_wall_count > 0 && config.support_roof_wall_count == 0) + if (! use_fake_roof_ && config_.support_wall_count > 0 && config_.support_roof_wall_count == 0) { - for (auto roof_area : support_roof_drawn[layer_idx].unionPolygons(roof_tips_drawn[layer_idx]).splitIntoParts()) + for (auto roof_area : support_roof_drawn_[layer_idx].unionPolygons(roof_tips_drawn_[layer_idx]).splitIntoParts()) { // technically there is no guarantee that a drawn roof tip has lines, as it could be unioned with another roof area that has, but this has to be enough // hopefully. if (layer_idx < additional_support_areas.size() - && TreeSupportUtils::generateSupportInfillLines(roof_area, config, true, layer_idx, support_roof_line_distance, cross_fill_provider, false).empty()) + && TreeSupportUtils::generateSupportInfillLines(roof_area, config_, true, layer_idx, support_roof_line_distance_, cross_fill_provider_, false).empty()) { additional_support_areas[layer_idx].add(roof_area); } @@ -1161,31 +1161,31 @@ void TreeSupportTipGenerator::generateTips( } else { - if (use_fake_roof) + if (use_fake_roof_) { storage.support.supportLayers[layer_idx] - .fillInfillParts(layer_idx, support_roof_drawn, config.support_line_width, support_roof_line_distance, config.maximum_move_distance); + .fillInfillParts(layer_idx, support_roof_drawn_, config_.support_line_width, support_roof_line_distance_, config_.maximum_move_distance); placed_support_lines_support_areas[layer_idx].add(TreeSupportUtils::generateSupportInfillLines( - support_roof_drawn[layer_idx], - config, + support_roof_drawn_[layer_idx], + config_, false, layer_idx, - support_roof_line_distance, - cross_fill_provider, + support_roof_line_distance_, + cross_fill_provider_, false) - .offsetPolyLine(config.support_line_width / 2)); + .offsetPolyLine(config_.support_line_width / 2)); } else { - storage.support.supportLayers[layer_idx].support_roof.add(support_roof_drawn[layer_idx]); - storage.support.supportLayers[layer_idx].support_roof = storage.support.supportLayers[layer_idx].support_roof.unionPolygons(roof_tips_drawn[layer_idx]); + storage.support.supportLayers[layer_idx].support_roof.add(support_roof_drawn_[layer_idx]); + storage.support.supportLayers[layer_idx].support_roof = storage.support.supportLayers[layer_idx].support_roof.unionPolygons(roof_tips_drawn_[layer_idx]); } } }); cura::parallel_for( 1, - mesh.overhang_areas.size() - z_distance_delta, + mesh.overhang_areas.size() - z_distance_delta_, [&](const LayerIndex layer_idx) { if (layer_idx > 0) diff --git a/src/pathPlanning/Comb.cpp b/src/pathPlanning/Comb.cpp index be204cb197..d422f18b2e 100644 --- a/src/pathPlanning/Comb.cpp +++ b/src/pathPlanning/Comb.cpp @@ -68,6 +68,7 @@ Comb::Comb( coord_t move_inside_distance) : storage_(storage) , layer_nr_(layer_nr) + , travel_avoid_distance_(travel_avoid_distance) , offset_from_outlines_(comb_boundary_offset) // between second wall and infill / other walls , max_moveInside_distance2_(offset_from_outlines_ * offset_from_outlines_) , offset_from_inside_to_outside_(offset_from_outlines_ + travel_avoid_distance) @@ -81,7 +82,6 @@ Comb::Comb( , inside_loc_to_line_minimum_(PolygonUtils::createLocToLineGrid(boundary_inside_minimum_, comb_boundary_offset)) , inside_loc_to_line_optimal_(PolygonUtils::createLocToLineGrid(boundary_inside_optimal_, comb_boundary_offset)) , move_inside_distance_(move_inside_distance) - , travel_avoid_distance_(travel_avoid_distance) { } From 1c37545945286b5991e7eefbe6920b2c4cfba56b Mon Sep 17 00:00:00 2001 From: wawanbreton Date: Wed, 22 Nov 2023 09:28:01 +0000 Subject: [PATCH 32/48] Applied clang-format. --- include/SkeletalTrapezoidationGraph.h | 48 ++++++------ include/gcodeExport.h | 4 +- include/infill/LightningLayer.h | 8 +- include/infill/NoZigZagConnectorProcessor.h | 14 ++-- include/pathPlanning/CombPath.h | 10 +-- include/pathPlanning/LinePolygonsCrossings.h | 4 +- include/plugins/slots.h | 10 +-- include/plugins/types.h | 12 +-- include/sliceDataStorage.h | 2 +- include/utils/MinimumSpanningTree.h | 13 ++-- include/utils/PolygonsSegmentIndex.h | 8 +- include/utils/SVG.h | 2 +- include/utils/orderOptimizer.h | 28 +++---- src/LayerPlan.cpp | 4 +- src/infill/LightningDistanceField.cpp | 5 +- src/infill/LightningLayer.cpp | 81 ++++++-------------- src/infill/NoZigZagConnectorProcessor.cpp | 18 ++--- src/layerPart.cpp | 40 +++++----- src/plugins/converters.cpp | 8 +- src/utils/Matrix4x3D.cpp | 3 +- src/utils/MinimumSpanningTree.cpp | 76 ++++++++++-------- src/utils/PolygonsSegmentIndex.cpp | 18 +++-- src/utils/VoxelUtils.cpp | 2 +- 23 files changed, 211 insertions(+), 207 deletions(-) diff --git a/include/SkeletalTrapezoidationGraph.h b/include/SkeletalTrapezoidationGraph.h index ab6e589d16..01eb198f94 100644 --- a/include/SkeletalTrapezoidationGraph.h +++ b/include/SkeletalTrapezoidationGraph.h @@ -19,28 +19,29 @@ class STHalfEdge : public HalfEdge distToGoUp() const; STHalfEdge* getNextUnconnected(); @@ -50,6 +51,7 @@ class STHalfEdgeNode : public HalfEdgeNode +class SkeletalTrapezoidationGraph : public HalfEdgeGraph { using edge_t = STHalfEdge; using node_t = STHalfEdgeNode; -public: +public: /*! * If an edge is too small, collapse it and its twin and fix the surrounding edges to ensure a consistent graph. - * + * * Don't collapse support edges, unless we can collapse the whole quad. - * + * * o-, * | "-o * | | > Don't collapse this edge only. @@ -87,7 +89,7 @@ class SkeletalTrapezoidationGraph: public HalfEdgeGraph getSource(const edge_t& edge); }; -} -#endif +} // namespace cura +#endif diff --git a/include/gcodeExport.h b/include/gcodeExport.h index 29582eb649..b3b4ef6fe4 100644 --- a/include/gcodeExport.h +++ b/include/gcodeExport.h @@ -19,8 +19,8 @@ #include "sliceDataStorage.h" #include "timeEstimate.h" #include "utils/AABB3D.h" //To track the used build volume for the Griffin header. -#include "utils/Point2LL.h" #include "utils/NoCopy.h" +#include "utils/Point2LL.h" namespace cura { @@ -128,7 +128,7 @@ class GCodeExport : public NoCopy double extrusion_offset_factor_; //!< default 1 Point3LL current_position_; //!< The last build plate coordinates written to gcode (which might be different from actually written gcode coordinates when the extruder offset is - //!< encoded in the gcode) + //!< encoded in the gcode) Velocity current_speed_; //!< The current speed (F values / 60) in mm/s Acceleration current_print_acceleration_; //!< The current acceleration (in mm/s^2) used for print moves (and also for travel moves if the gcode flavor doesn't have separate //!< travel acceleration) diff --git a/include/infill/LightningLayer.h b/include/infill/LightningLayer.h index e9cd2b77c0..fe5a079e43 100644 --- a/include/infill/LightningLayer.h +++ b/include/infill/LightningLayer.h @@ -4,15 +4,15 @@ #ifndef LIGHTNING_LAYER_H #define LIGHTNING_LAYER_H -#include "../utils/SquareGrid.h" -#include "../utils/polygonUtils.h" -#include "infill/LightningTreeNode.h" - #include #include #include #include +#include "../utils/SquareGrid.h" +#include "../utils/polygonUtils.h" +#include "infill/LightningTreeNode.h" + namespace cura { using LightningTreeNodeSPtr = std::shared_ptr; diff --git a/include/infill/NoZigZagConnectorProcessor.h b/include/infill/NoZigZagConnectorProcessor.h index 82724ac95f..002fb0fb7b 100644 --- a/include/infill/NoZigZagConnectorProcessor.h +++ b/include/infill/NoZigZagConnectorProcessor.h @@ -1,5 +1,5 @@ -//Copyright (c) 2018 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2018 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef INFILL_NO_ZIGZAG_CONNECTOR_PROCESSOR_H #define INFILL_NO_ZIGZAG_CONNECTOR_PROCESSOR_H @@ -18,9 +18,13 @@ class NoZigZagConnectorProcessor : public ZigzagConnectorProcessor { public: NoZigZagConnectorProcessor(const PointMatrix& rotation_matrix, Polygons& result) - : ZigzagConnectorProcessor(rotation_matrix, result, - false, false, // settings for zig-zag end pieces, no use here - false, 0) // settings for skipping some zags, no use here + : ZigzagConnectorProcessor( + rotation_matrix, + result, + false, + false, // settings for zig-zag end pieces, no use here + false, + 0) // settings for skipping some zags, no use here { } diff --git a/include/pathPlanning/CombPath.h b/include/pathPlanning/CombPath.h index b1811352ea..6559e8c7ee 100644 --- a/include/pathPlanning/CombPath.h +++ b/include/pathPlanning/CombPath.h @@ -1,5 +1,5 @@ -//Copyright (c) 2018 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2018 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef PATH_PLANNING_COMB_PATH_H #define PATH_PLANNING_COMB_PATH_H @@ -9,12 +9,12 @@ namespace cura { -class CombPath : public std::vector //!< A single path either inside or outise the parts +class CombPath : public std::vector //!< A single path either inside or outise the parts { public: bool cross_boundary = false; //!< Whether the path crosses a boundary. }; -}//namespace cura +} // namespace cura -#endif//PATH_PLANNING_COMB_PATH_H +#endif // PATH_PLANNING_COMB_PATH_H diff --git a/include/pathPlanning/LinePolygonsCrossings.h b/include/pathPlanning/LinePolygonsCrossings.h index 551577ae2e..5fb641dd9b 100644 --- a/include/pathPlanning/LinePolygonsCrossings.h +++ b/include/pathPlanning/LinePolygonsCrossings.h @@ -57,9 +57,9 @@ class LinePolygonsCrossings PointMatrix transformation_matrix_; //!< The transformation which rotates everything such that the scanline is aligned with the x-axis. Point2LL transformed_start_point_; //!< The LinePolygonsCrossings::startPoint as transformed by Comb::transformation_matrix such that it has (roughly) the same Y as - //!< transformed_endPoint + //!< transformed_endPoint Point2LL transformed_end_point_; //!< The LinePolygonsCrossings::endPoint as transformed by Comb::transformation_matrix such that it has (roughly) the same Y as - //!< transformed_startPoint + //!< transformed_startPoint /*! diff --git a/include/plugins/slots.h b/include/plugins/slots.h index c519553114..296e3f649b 100644 --- a/include/plugins/slots.h +++ b/include/plugins/slots.h @@ -4,6 +4,11 @@ #ifndef PLUGINS_SLOTS_H #define PLUGINS_SLOTS_H +#include +#include +#include +#include + #include "WallToolPaths.h" #include "cura/plugins/slots/broadcast/v0/broadcast.grpc.pb.h" #include "cura/plugins/slots/gcode_paths/v0/modify.grpc.pb.h" @@ -21,11 +26,6 @@ #include "utils/polygon.h" #include "utils/types/char_range_literal.h" -#include -#include -#include -#include - namespace cura { namespace plugins diff --git a/include/plugins/types.h b/include/plugins/types.h index 1a9ab54d59..eb443d0b27 100644 --- a/include/plugins/types.h +++ b/include/plugins/types.h @@ -4,16 +4,16 @@ #ifndef PLUGINS_TYPES_H #define PLUGINS_TYPES_H -#include "cura/plugins/v0/slot_id.pb.h" -#include "utils/Point2LL.h" -#include "utils/polygon.h" - -#include - #include #include #include +#include + +#include "cura/plugins/v0/slot_id.pb.h" +#include "utils/Point2LL.h" +#include "utils/polygon.h" + namespace fmt { // Custom formatter for humanreadable slot_id's diff --git a/include/sliceDataStorage.h b/include/sliceDataStorage.h index 3442f0b08d..7fced685eb 100644 --- a/include/sliceDataStorage.h +++ b/include/sliceDataStorage.h @@ -18,8 +18,8 @@ #include "settings/types/LayerIndex.h" #include "utils/AABB.h" #include "utils/AABB3D.h" -#include "utils/Point2LL.h" #include "utils/NoCopy.h" +#include "utils/Point2LL.h" #include "utils/polygon.h" // libArachne diff --git a/include/utils/MinimumSpanningTree.h b/include/utils/MinimumSpanningTree.h index 9e0f53d4cf..599ab2273b 100644 --- a/include/utils/MinimumSpanningTree.h +++ b/include/utils/MinimumSpanningTree.h @@ -1,12 +1,12 @@ -//Copyright (c) 2018 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2018 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef MINIMUMSPANNINGTREE_H #define MINIMUMSPANNINGTREE_H -#include #include #include +#include #include "Point2LL.h" @@ -26,7 +26,8 @@ class MinimumSpanningTree * While edges are meant to be undirected, these do have a start and end * point. */ - struct Edge { + struct Edge + { /** * The point at which this edge starts. */ @@ -37,6 +38,7 @@ class MinimumSpanningTree */ const Point2LL end; }; + public: MinimumSpanningTree() = default; /*! @@ -76,7 +78,6 @@ class MinimumSpanningTree AdjacencyGraph_t prim(std::vector vertices) const; }; -} +} // namespace cura #endif /* MINIMUMSPANNINGTREE_H */ - diff --git a/include/utils/PolygonsSegmentIndex.h b/include/utils/PolygonsSegmentIndex.h index b5462a7a16..ab37fa2f06 100644 --- a/include/utils/PolygonsSegmentIndex.h +++ b/include/utils/PolygonsSegmentIndex.h @@ -1,5 +1,5 @@ -//Copyright (c) 2020 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2020 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef UTILS_POLYGONS_SEGMENT_INDEX_H #define UTILS_POLYGONS_SEGMENT_INDEX_H @@ -8,7 +8,7 @@ #include "PolygonsPointIndex.h" -namespace cura +namespace cura { /*! @@ -29,4 +29,4 @@ class PolygonsSegmentIndex : public PolygonsPointIndex } // namespace cura -#endif//UTILS_POLYGONS_SEGMENT_INDEX_H +#endif // UTILS_POLYGONS_SEGMENT_INDEX_H diff --git a/include/utils/SVG.h b/include/utils/SVG.h index 82646e1df6..81c5b078af 100644 --- a/include/utils/SVG.h +++ b/include/utils/SVG.h @@ -8,8 +8,8 @@ #include "AABB.h" #include "ExtrusionLine.h" //To accept variable-width paths. -#include "Point2LL.h" #include "NoCopy.h" +#include "Point2LL.h" namespace cura { diff --git a/include/utils/orderOptimizer.h b/include/utils/orderOptimizer.h index e990cecbac..cf3abaa2ba 100644 --- a/include/utils/orderOptimizer.h +++ b/include/utils/orderOptimizer.h @@ -1,25 +1,27 @@ -//Copyright (c) 2018 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2018 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef UTILS_ORDER_OPTIMIZER_H #define UTILS_ORDER_OPTIMIZER_H #include -#include #include #include // pair +#include + #include "Point2LL.h" -namespace cura { - +namespace cura +{ + /*! * Order optimization class. - * + * * Utility class for optimizing the path order by minimizing the cyclic distance traveled between several items. - * + * * The path is heuristically optimized in a way such that each node is visited and the salesman which is travelling ends up where he started. */ -template +template class OrderOptimizer { public: @@ -38,13 +40,13 @@ class OrderOptimizer std::list optimize(const Point2LL& start_position); }; -template +template void OrderOptimizer::addItem(const Point2LL location, const T item) { items.emplace_back(location, item); } -template +template std::list OrderOptimizer::optimize(const Point2LL& start_position) { // Use the nearest mesh ordering @@ -62,7 +64,7 @@ std::list OrderOptimizer::optimize(const Point2LL& start_position) } const Point2LL* last_item_position = &start_position; - while (!item_idx_list.empty()) + while (! item_idx_list.empty()) { coord_t shortest_distance = POINT_MAX; size_t shortest_distance_item_idx = -1; @@ -89,6 +91,6 @@ std::list OrderOptimizer::optimize(const Point2LL& start_position) } -}//namespace cura +} // namespace cura -#endif//UTILS_ORDER_OPTIMIZER_H +#endif // UTILS_ORDER_OPTIMIZER_H diff --git a/src/LayerPlan.cpp b/src/LayerPlan.cpp index 9ad194fb47..a9932a7116 100644 --- a/src/LayerPlan.cpp +++ b/src/LayerPlan.cpp @@ -662,8 +662,8 @@ void LayerPlan::addWallLine( { // if we are accelerating after a bridge line, the segment length is less than the whole line length Point2LL segment_end = (speed_factor == 1 || distance_to_line_end < acceleration_segment_len) - ? line_end - : cur_point + (line_end - cur_point) * acceleration_segment_len / distance_to_line_end; + ? line_end + : cur_point + (line_end - cur_point) * acceleration_segment_len / distance_to_line_end; // flow required for the next line segment - when accelerating after a bridge segment, the flow is increased in inverse proportion to the speed_factor // so the slower the feedrate, the greater the flow - the idea is to get the extruder back to normal pressure as quickly as possible diff --git a/src/infill/LightningDistanceField.cpp b/src/infill/LightningDistanceField.cpp index 923eb1e8b8..1afea87a24 100644 --- a/src/infill/LightningDistanceField.cpp +++ b/src/infill/LightningDistanceField.cpp @@ -28,8 +28,9 @@ LightningDistanceField::LightningDistanceField(const coord_t& radius, const Poly [&radius](const UnsupCell& a, const UnsupCell& b) { constexpr coord_t prime_for_hash = 191; - return std::abs(b.dist_to_boundary_ - a.dist_to_boundary_) > radius ? a.dist_to_boundary_ < b.dist_to_boundary_ - : (std::hash{}(a.loc_) % prime_for_hash) < (std::hash{}(b.loc_) % prime_for_hash); + return std::abs(b.dist_to_boundary_ - a.dist_to_boundary_) > radius + ? a.dist_to_boundary_ < b.dist_to_boundary_ + : (std::hash{}(a.loc_) % prime_for_hash) < (std::hash{}(b.loc_) % prime_for_hash); }); for (auto it = unsupported_points_.begin(); it != unsupported_points_.end(); ++it) { diff --git a/src/infill/LightningLayer.cpp b/src/infill/LightningLayer.cpp index cd689e1bfc..6cefaff8be 100644 --- a/src/infill/LightningLayer.cpp +++ b/src/infill/LightningLayer.cpp @@ -1,5 +1,5 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #include "infill/LightningLayer.h" //The class we're implementing. @@ -8,9 +8,9 @@ #include "infill/LightningDistanceField.h" #include "infill/LightningTreeNode.h" #include "sliceDataStorage.h" -#include "utils/linearAlg2D.h" #include "utils/SVG.h" #include "utils/SparsePointGridInclusive.h" +#include "utils/linearAlg2D.h" using namespace cura; @@ -34,25 +34,22 @@ Point2LL GroundingLocation::p() const void LightningLayer::fillLocator(SparseLightningTreeNodeGrid& tree_node_locator) { - std::function add_node_to_locator_func = - [&tree_node_locator](LightningTreeNodeSPtr node) - { - tree_node_locator.insert(node->getLocation(), node); - }; + std::function add_node_to_locator_func = [&tree_node_locator](LightningTreeNodeSPtr node) + { + tree_node_locator.insert(node->getLocation(), node); + }; for (auto& tree : tree_roots) { tree->visitNodes(add_node_to_locator_func); } } -void LightningLayer::generateNewTrees -( +void LightningLayer::generateNewTrees( const Polygons& current_overhang, const Polygons& current_outlines, const LocToLineGrid& outlines_locator, const coord_t supporting_radius, - const coord_t wall_supporting_radius -) + const coord_t wall_supporting_radius) { LightningDistanceField distance_field(supporting_radius, current_outlines, current_overhang); @@ -64,16 +61,8 @@ void LightningLayer::generateNewTrees Point2LL unsupported_location; while (distance_field.tryGetNextPoint(&unsupported_location)) { - GroundingLocation grounding_loc = - getBestGroundingLocation - ( - unsupported_location, - current_outlines, - outlines_locator, - supporting_radius, - wall_supporting_radius, - tree_node_locator - ); + GroundingLocation grounding_loc + = getBestGroundingLocation(unsupported_location, current_outlines, outlines_locator, supporting_radius, wall_supporting_radius, tree_node_locator); LightningTreeNodeSPtr new_parent; LightningTreeNodeSPtr new_child; @@ -89,16 +78,14 @@ void LightningLayer::generateNewTrees } } -GroundingLocation LightningLayer::getBestGroundingLocation -( +GroundingLocation LightningLayer::getBestGroundingLocation( const Point2LL& unsupported_location, const Polygons& current_outlines, const LocToLineGrid& outline_locator, const coord_t supporting_radius, const coord_t wall_supporting_radius, const SparseLightningTreeNodeGrid& tree_node_locator, - const LightningTreeNodeSPtr& exclude_tree -) + const LightningTreeNodeSPtr& exclude_tree) { ClosestPolygonPoint cpp = PolygonUtils::findClosest(unsupported_location, current_outlines); Point2LL node_location = cpp.p(); @@ -114,12 +101,8 @@ GroundingLocation LightningLayer::getBestGroundingLocation for (auto& candidate_wptr : candidate_trees) { auto candidate_sub_tree = candidate_wptr.lock(); - if - ( - (candidate_sub_tree && candidate_sub_tree != exclude_tree) && - ! (exclude_tree && exclude_tree->hasOffspring(candidate_sub_tree)) && - ! PolygonUtils::polygonCollidesWithLineSegment(unsupported_location, candidate_sub_tree->getLocation(), outline_locator, &dummy) - ) + if ((candidate_sub_tree && candidate_sub_tree != exclude_tree) && ! (exclude_tree && exclude_tree->hasOffspring(candidate_sub_tree)) + && ! PolygonUtils::polygonCollidesWithLineSegment(unsupported_location, candidate_sub_tree->getLocation(), outline_locator, &dummy)) { const coord_t candidate_dist = candidate_sub_tree->getWeightedDistance(unsupported_location, supporting_radius); if (candidate_dist < current_dist) @@ -141,13 +124,7 @@ GroundingLocation LightningLayer::getBestGroundingLocation } } -bool LightningLayer::attach -( - const Point2LL& unsupported_location, - const GroundingLocation& grounding_loc, - LightningTreeNodeSPtr& new_child, - LightningTreeNodeSPtr& new_root -) +bool LightningLayer::attach(const Point2LL& unsupported_location, const GroundingLocation& grounding_loc, LightningTreeNodeSPtr& new_child, LightningTreeNodeSPtr& new_root) { // Update trees & distance fields. if (grounding_loc.boundary_location) @@ -164,14 +141,12 @@ bool LightningLayer::attach } } -void LightningLayer::reconnectRoots -( +void LightningLayer::reconnectRoots( std::vector& to_be_reconnected_tree_roots, const Polygons& current_outlines, const LocToLineGrid& outline_locator, const coord_t supporting_radius, - const coord_t wall_supporting_radius -) + const coord_t wall_supporting_radius) { constexpr coord_t tree_connecting_ignore_offset = 100; @@ -202,18 +177,10 @@ void LightningLayer::reconnectRoots } } - const coord_t tree_connecting_ignore_width = wall_supporting_radius - tree_connecting_ignore_offset; // Ideally, the boundary size in which the valence rule is ignored would be configurable. - GroundingLocation ground = - getBestGroundingLocation - ( - root_ptr->getLocation(), - current_outlines, - outline_locator, - supporting_radius, - tree_connecting_ignore_width, - tree_node_locator, - root_ptr - ); + const coord_t tree_connecting_ignore_width + = wall_supporting_radius - tree_connecting_ignore_offset; // Ideally, the boundary size in which the valence rule is ignored would be configurable. + GroundingLocation ground + = getBestGroundingLocation(root_ptr->getLocation(), current_outlines, outline_locator, supporting_radius, tree_connecting_ignore_width, tree_node_locator, root_ptr); if (ground.boundary_location) { if (ground.boundary_location.value().p() == root_ptr->getLocation()) @@ -234,8 +201,8 @@ void LightningLayer::reconnectRoots { assert(ground.tree_node); assert(ground.tree_node != root_ptr); - assert(!root_ptr->hasOffspring(ground.tree_node)); - assert(!ground.tree_node->hasOffspring(root_ptr)); + assert(! root_ptr->hasOffspring(ground.tree_node)); + assert(! ground.tree_node->hasOffspring(root_ptr)); auto attach_ptr = root_ptr->closestNode(ground.tree_node->getLocation()); attach_ptr->reroot(); diff --git a/src/infill/NoZigZagConnectorProcessor.cpp b/src/infill/NoZigZagConnectorProcessor.cpp index 5deaa551ac..1ffa6532f4 100644 --- a/src/infill/NoZigZagConnectorProcessor.cpp +++ b/src/infill/NoZigZagConnectorProcessor.cpp @@ -1,27 +1,27 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. - -#include "utils/macros.h" +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #include "infill/NoZigZagConnectorProcessor.h" +#include "utils/macros.h" + -namespace cura +namespace cura { void NoZigZagConnectorProcessor::registerVertex(const Point2LL&) { - //No need to add anything. + // No need to add anything. } void NoZigZagConnectorProcessor::registerScanlineSegmentIntersection(const Point2LL&, int) { - //No need to add anything. + // No need to add anything. } void NoZigZagConnectorProcessor::registerPolyFinished() { - //No need to add anything. + // No need to add anything. } -} // namespace cura +} // namespace cura diff --git a/src/layerPart.cpp b/src/layerPart.cpp index 2a47dd8563..b0fb7ece93 100644 --- a/src/layerPart.cpp +++ b/src/layerPart.cpp @@ -1,16 +1,16 @@ -//Copyright (c) 2023 UltiMaker -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2023 UltiMaker +// CuraEngine is released under the terms of the AGPLv3 or higher. #include "layerPart.h" -#include "sliceDataStorage.h" -#include "slicer.h" + +#include "progress/Progress.h" #include "settings/EnumSettings.h" //For ESurfaceMode. #include "settings/Settings.h" -#include "progress/Progress.h" -#include "utils/ThreadPool.h" - +#include "sliceDataStorage.h" +#include "slicer.h" #include "utils/PolylineStitcher.h" #include "utils/Simplify.h" //Simplifying the layers after creating them. +#include "utils/ThreadPool.h" /* The layer-part creation step is the first step in creating actual useful data for 3D printing. @@ -24,7 +24,8 @@ And all every bit inside a single part can be printed without the nozzle leaving It's also the first step that stores the result in the "data storage" so all other steps can access it. */ -namespace cura { +namespace cura +{ void createLayerWithParts(const Settings& settings, SliceLayer& storageLayer, SlicerLayer* layer) { @@ -35,7 +36,7 @@ void createLayerWithParts(const Settings& settings, SliceLayer& storageLayer, Sl const bool union_all_remove_holes = settings.get("meshfix_union_all_remove_holes"); if (union_all_remove_holes) { - for(unsigned int i=0; ipolygons.size(); i++) + for (unsigned int i = 0; i < layer->polygons.size(); i++) { if (layer->polygons[i].orientation()) layer->polygons[i].reverse(); @@ -45,7 +46,7 @@ void createLayerWithParts(const Settings& settings, SliceLayer& storageLayer, Sl std::vector result; const bool union_layers = settings.get("meshfix_union_all"); const ESurfaceMode surface_only = settings.get("magic_mesh_surface_mode"); - if (surface_only == ESurfaceMode::SURFACE && !union_layers) + if (surface_only == ESurfaceMode::SURFACE && ! union_layers) { // Don't do anything with overlapping areas; no union nor xor result.reserve(layer->polygons.size()); for (const PolygonRef poly : layer->polygons) @@ -59,7 +60,7 @@ void createLayerWithParts(const Settings& settings, SliceLayer& storageLayer, Sl result = layer->polygons.splitIntoParts(union_layers || union_all_remove_holes); } - for(auto & part : result) + for (auto& part : result) { storageLayer.parts.emplace_back(); storageLayer.parts.back().outline = part; @@ -76,12 +77,15 @@ void createLayerParts(SliceMeshStorage& mesh, Slicer* slicer) const auto total_layers = slicer->layers.size(); assert(mesh.layers.size() == total_layers); - cura::parallel_for(0, total_layers, [slicer, &mesh](size_t layer_nr) - { - SliceLayer& layer_storage = mesh.layers[layer_nr]; - SlicerLayer& slice_layer = slicer->layers[layer_nr]; - createLayerWithParts(mesh.settings, layer_storage, &slice_layer); - }); + cura::parallel_for( + 0, + total_layers, + [slicer, &mesh](size_t layer_nr) + { + SliceLayer& layer_storage = mesh.layers[layer_nr]; + SlicerLayer& slice_layer = slicer->layers[layer_nr]; + createLayerWithParts(mesh.settings, layer_storage, &slice_layer); + }); for (LayerIndex layer_nr = total_layers - 1; layer_nr >= 0; layer_nr--) { @@ -94,4 +98,4 @@ void createLayerParts(SliceMeshStorage& mesh, Slicer* slicer) } } -}//namespace cura +} // namespace cura diff --git a/src/plugins/converters.cpp b/src/plugins/converters.cpp index c637f44c45..2f8eabd151 100644 --- a/src/plugins/converters.cpp +++ b/src/plugins/converters.cpp @@ -4,6 +4,10 @@ #include "plugins/converters.h" +#include +#include +#include + #include "GCodePathConfig.h" #include "WallToolPaths.h" #include "pathPlanning/GCodePath.h" @@ -12,10 +16,6 @@ #include "settings/types/LayerIndex.h" #include "utils/polygon.h" -#include -#include -#include - namespace cura::plugins { diff --git a/src/utils/Matrix4x3D.cpp b/src/utils/Matrix4x3D.cpp index 225be8db8a..43b255379f 100644 --- a/src/utils/Matrix4x3D.cpp +++ b/src/utils/Matrix4x3D.cpp @@ -1,9 +1,10 @@ // Copyright (c) 2022 Ultimaker B.V. // CuraEngine is released under the terms of the AGPLv3 or higher. +#include "utils/Matrix4x3D.h" //The definitions we're implementing. + #include "settings/types/Ratio.h" //Scale factor. #include "utils/Point2LL.h" //Conversion directly into integer-based coordinates. -#include "utils/Matrix4x3D.h" //The definitions we're implementing. #include "utils/Point3D.h" //This matrix gets applied to floating point coordinates. namespace cura diff --git a/src/utils/MinimumSpanningTree.cpp b/src/utils/MinimumSpanningTree.cpp index f32b104913..36e7c48e97 100644 --- a/src/utils/MinimumSpanningTree.cpp +++ b/src/utils/MinimumSpanningTree.cpp @@ -1,17 +1,18 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #include "utils/MinimumSpanningTree.h" -#include #include +#include namespace cura { -MinimumSpanningTree::MinimumSpanningTree(std::vector vertices) : adjacency_graph(prim(vertices)) +MinimumSpanningTree::MinimumSpanningTree(std::vector vertices) + : adjacency_graph(prim(vertices)) { - //Just copy over the fields. + // Just copy over the fields. } auto MinimumSpanningTree::prim(std::vector vertices) const -> AdjacencyGraph_t @@ -19,7 +20,7 @@ auto MinimumSpanningTree::prim(std::vector vertices) const -> Adjacenc AdjacencyGraph_t result; if (vertices.empty()) { - return result; //No vertices, so we can't create edges either. + return result; // No vertices, so we can't create edges either. } // If there's only one vertex, we can't go creating any edges so just add the point to the adjacency list with no // edges @@ -33,8 +34,8 @@ auto MinimumSpanningTree::prim(std::vector vertices) const -> Adjacenc result.reserve(vertices.size()); std::vector vertices_list(vertices.begin(), vertices.end()); - std::unordered_map smallest_distance; //The shortest distance to the current tree. - std::unordered_map smallest_distance_to; //Which point the shortest distance goes towards. + std::unordered_map smallest_distance; // The shortest distance to the current tree. + std::unordered_map smallest_distance_to; // Which point the shortest distance goes towards. smallest_distance.reserve(vertices_list.size()); smallest_distance_to.reserve(vertices_list.size()); for (size_t vertex_index = 1; vertex_index < vertices_list.size(); vertex_index++) @@ -44,40 +45,43 @@ auto MinimumSpanningTree::prim(std::vector vertices) const -> Adjacenc smallest_distance_to[&vert] = &vertices_list[0]; } - while (result.size() < vertices_list.size()) //All of the vertices need to be in the tree at the end. + while (result.size() < vertices_list.size()) // All of the vertices need to be in the tree at the end. { - //Choose the closest vertex to connect to that is not yet in the tree. - //This search is O(V) right now, which can be made down to O(log(V)). This reduces the overall time complexity from O(V*V) to O(V*log(E)). - //However that requires an implementation of a heap that supports the decreaseKey operation, which is not in the std library. - //TODO: Implement this? + // Choose the closest vertex to connect to that is not yet in the tree. + // This search is O(V) right now, which can be made down to O(log(V)). This reduces the overall time complexity from O(V*V) to O(V*log(E)). + // However that requires an implementation of a heap that supports the decreaseKey operation, which is not in the std library. + // TODO: Implement this? using MapValue = std::pair; - const auto closest = std::min_element(smallest_distance.begin(), smallest_distance.end(), - [](const MapValue& a, const MapValue& b) { - return a.second < b.second; - }); + const auto closest = std::min_element( + smallest_distance.begin(), + smallest_distance.end(), + [](const MapValue& a, const MapValue& b) + { + return a.second < b.second; + }); - //Add this point to the graph and remove it from the candidates. + // Add this point to the graph and remove it from the candidates. const Point2LL* closest_point = closest->first; const Point2LL other_end = *smallest_distance_to[closest_point]; if (result.find(*closest_point) == result.end()) { result[*closest_point] = std::vector(); } - result[*closest_point].push_back({*closest_point, other_end}); + result[*closest_point].push_back({ *closest_point, other_end }); if (result.find(other_end) == result.end()) { result[other_end] = std::vector(); } - result[other_end].push_back({other_end, *closest_point}); - smallest_distance.erase(closest_point); //Remove it so we don't check for these points again. + result[other_end].push_back({ other_end, *closest_point }); + smallest_distance.erase(closest_point); // Remove it so we don't check for these points again. smallest_distance_to.erase(closest_point); - //Update the distances of all points that are not in the graph. + // Update the distances of all points that are not in the graph. for (std::pair point_and_distance : smallest_distance) { const coord_t new_distance = vSize2(*closest_point - *point_and_distance.first); const coord_t old_distance = point_and_distance.second; - if (new_distance < old_distance) //New point is closer. + if (new_distance < old_distance) // New point is closer. { smallest_distance[point_and_distance.first] = new_distance; smallest_distance_to[point_and_distance.first] = closest_point; @@ -95,8 +99,14 @@ std::vector MinimumSpanningTree::adjacentNodes(Point2LL node) const if (adjacency_entry != adjacency_graph.end()) { const auto& edges = adjacency_entry->second; - std::transform(edges.begin(), edges.end(), std::back_inserter(result), - [&node](const Edge& e) { return (e.start == node) ? e.end : e.start; }); + std::transform( + edges.begin(), + edges.end(), + std::back_inserter(result), + [&node](const Edge& e) + { + return (e.start == node) ? e.end : e.start; + }); } return result; } @@ -106,7 +116,7 @@ std::vector MinimumSpanningTree::leaves() const std::vector result; for (std::pair> node : adjacency_graph) { - if (node.second.size() <= 1) //Leaves are nodes that have only one adjacent edge, or just the one node if the tree contains one node. + if (node.second.size() <= 1) // Leaves are nodes that have only one adjacent edge, or just the one node if the tree contains one node. { result.push_back(node.first); } @@ -117,10 +127,16 @@ std::vector MinimumSpanningTree::leaves() const std::vector MinimumSpanningTree::vertices() const { std::vector result; - using MapValue = std::pair>; - std::transform(adjacency_graph.begin(), adjacency_graph.end(), std::back_inserter(result), - [](const MapValue& node) { return node.first; }); + using MapValue = std::pair>; + std::transform( + adjacency_graph.begin(), + adjacency_graph.end(), + std::back_inserter(result), + [](const MapValue& node) + { + return node.first; + }); return result; } -} +} // namespace cura diff --git a/src/utils/PolygonsSegmentIndex.cpp b/src/utils/PolygonsSegmentIndex.cpp index 08b6238586..0b402a03f6 100644 --- a/src/utils/PolygonsSegmentIndex.cpp +++ b/src/utils/PolygonsSegmentIndex.cpp @@ -1,23 +1,29 @@ -//Copyright (c) 2022 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2022 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #include "utils/PolygonsSegmentIndex.h" namespace cura { -PolygonsSegmentIndex::PolygonsSegmentIndex() : PolygonsPointIndex() {} +PolygonsSegmentIndex::PolygonsSegmentIndex() + : PolygonsPointIndex() +{ +} -PolygonsSegmentIndex::PolygonsSegmentIndex(const Polygons* polygons, unsigned int poly_idx, unsigned int point_idx) : PolygonsPointIndex(polygons, poly_idx, point_idx) {} +PolygonsSegmentIndex::PolygonsSegmentIndex(const Polygons* polygons, unsigned int poly_idx, unsigned int point_idx) + : PolygonsPointIndex(polygons, poly_idx, point_idx) +{ +} Point2LL PolygonsSegmentIndex::from() const { return PolygonsPointIndex::p(); } - + Point2LL PolygonsSegmentIndex::to() const { return PolygonsSegmentIndex::next().p(); } -} +} // namespace cura diff --git a/src/utils/VoxelUtils.cpp b/src/utils/VoxelUtils.cpp index b55f40c0ce..ddac6713d5 100644 --- a/src/utils/VoxelUtils.cpp +++ b/src/utils/VoxelUtils.cpp @@ -153,7 +153,7 @@ bool VoxelUtils::walkDilatedAreas(const Polygons& polys, coord_t z, const Dilati { Polygons translated = polys; const Point3LL translation = (Point3LL(1, 1, 1) - kernel.kernel_size_ % 2) * cell_size_ / 2 // offset half a cell when using a n even kernel - - cell_size_ / 2; // offset half a cell so that the dots of spreadDotsArea are centered on the middle of the cell isntead of the lower corners. + - cell_size_ / 2; // offset half a cell so that the dots of spreadDotsArea are centered on the middle of the cell isntead of the lower corners. if (translation.x_ && translation.y_) { translated.translate(Point2LL(translation.x_, translation.y_)); From 511971f313f143c3562128a5b8b7fb4f72b0b636 Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Wed, 22 Nov 2023 12:07:17 +0100 Subject: [PATCH 33/48] Fixed unused variables warnings --- include/ExtruderPlan.h | 3 +-- include/FffGcodeWriter.h | 14 +++------- include/PathOrderOptimizer.h | 12 +++------ include/Preheat.h | 11 ++++---- include/SkeletalTrapezoidationGraph.h | 2 +- include/TreeSupportTipGenerator.h | 2 +- include/plugins/slots.h | 2 +- include/support.h | 13 ++++----- src/BeadingStrategy/BeadingStrategy.cpp | 2 +- src/FffGcodeWriter.cpp | 11 +++----- src/FffPolygonGenerator.cpp | 3 ++- src/InterlockingGenerator.cpp | 2 +- src/LayerPlan.cpp | 8 +++--- src/LayerPlanBuffer.cpp | 10 ++----- src/Preheat.cpp | 2 +- src/SkeletalTrapezoidation.cpp | 12 +++------ src/SkeletalTrapezoidationGraph.cpp | 2 +- src/TreeModelVolumes.cpp | 4 +-- src/TreeSupport.cpp | 2 +- src/TreeSupportTipGenerator.cpp | 2 +- src/communication/CommandLine.cpp | 2 +- src/plugins/converters.cpp | 10 ++++--- src/skin.cpp | 1 - src/support.cpp | 35 +++---------------------- src/utils/Simplify.cpp | 6 ++--- 25 files changed, 56 insertions(+), 117 deletions(-) diff --git a/include/ExtruderPlan.h b/include/ExtruderPlan.h index 17e45d0013..7f534d1ec8 100644 --- a/include/ExtruderPlan.h +++ b/include/ExtruderPlan.h @@ -93,11 +93,10 @@ class ExtruderPlan /*! * Applying fan speed changes for minimal layer times. * - * \param starting_position The position the head was before starting this extruder plan * \param minTime Maximum minimum layer time for all extruders in this layer * \param time_other_extr_plans The time spent on the other extruder plans in this layer */ - void processFanSpeedForMinimalLayerTime(Point2LL starting_position, Duration maximum_cool_min_layer_time, double time_other_extr_plans); + void processFanSpeedForMinimalLayerTime(Duration maximum_cool_min_layer_time, double time_other_extr_plans); /*! * Applying fan speed changes for the first layers. diff --git a/include/FffGcodeWriter.h b/include/FffGcodeWriter.h index 68c1cb9986..46b9657968 100644 --- a/include/FffGcodeWriter.h +++ b/include/FffGcodeWriter.h @@ -312,12 +312,11 @@ class FffGcodeWriter : public NoCopy /*! * Add a single layer from a single mesh-volume to the layer plan \p gcodeLayer in mesh surface mode. * - * \param[in] storage where the slice data is stored. * \param mesh The mesh to add to the layer plan \p gcodeLayer. * \param mesh_config the line config with which to print a print feature * \param gcodeLayer The initial planning of the gcode of the layer. */ - void addMeshLayerToGCode_meshSurfaceMode(const SliceDataStorage& storage, const SliceMeshStorage& mesh, const MeshPathConfigs& mesh_config, LayerPlan& gcodeLayer) const; + void addMeshLayerToGCode_meshSurfaceMode(const SliceMeshStorage& mesh, const MeshPathConfigs& mesh_config, LayerPlan& gcodeLayer) const; /*! * Add the open polylines from a single layer from a single mesh-volume to the layer plan \p gcodeLayer for mesh the surface modes. @@ -398,13 +397,8 @@ class FffGcodeWriter : public NoCopy * \param part The part for which to create gcode. * \return Whether this function added anything to the layer plan. */ - bool processMultiLayerInfill( - const SliceDataStorage& storage, - LayerPlan& gcodeLayer, - const SliceMeshStorage& mesh, - const size_t extruder_nr, - const MeshPathConfigs& mesh_config, - const SliceLayerPart& part) const; + bool processMultiLayerInfill(LayerPlan& gcodeLayer, const SliceMeshStorage& mesh, const size_t extruder_nr, const MeshPathConfigs& mesh_config, const SliceLayerPart& part) + const; /*! * \brief Add normal sparse infill for a given part in a layer. @@ -549,7 +543,6 @@ class FffGcodeWriter : public NoCopy * \param[in] storage where the slice data is stored. * \param gcode_layer The initial planning of the gcode of the layer. * \param mesh The mesh for which to add to the layer plan \p gcode_layer. - * \param mesh_config The mesh-config for which to add to the layer plan \p gcode_layer. * \param extruder_nr The extruder for which to print all features of the mesh which should be printed with this extruder * \param area The area to fill * \param config the line config with which to print the print feature @@ -566,7 +559,6 @@ class FffGcodeWriter : public NoCopy const SliceDataStorage& storage, LayerPlan& gcode_layer, const SliceMeshStorage& mesh, - const MeshPathConfigs& mesh_config, const size_t extruder_nr, const Polygons& area, const GCodePathConfig& config, diff --git a/include/PathOrderOptimizer.h b/include/PathOrderOptimizer.h index 4dd1e47332..94b4c74344 100644 --- a/include/PathOrderOptimizer.h +++ b/include/PathOrderOptimizer.h @@ -220,7 +220,7 @@ class PathOrderOptimizer } else { - optimized_order = getOptimizerOrderWithConstraints(line_bucket_grid, snap_radius, *order_requirements_); + optimized_order = getOptimizerOrderWithConstraints(*order_requirements_); } @@ -300,10 +300,6 @@ class PathOrderOptimizer std::unordered_map picked(paths_.size()); // Fixed size boolean flag for whether each path is already in the optimized vector. - auto isPicked = [&picked](OrderablePath* c) - { - return picked[c]; - }; auto notPicked = [&picked](OrderablePath* c) { return ! picked[c]; @@ -356,8 +352,7 @@ class PathOrderOptimizer return optimized_order; } - std::vector - getOptimizerOrderWithConstraints(SparsePointGridInclusive line_bucket_grid, size_t snap_radius, const std::unordered_multimap& order_requirements) + std::vector getOptimizerOrderWithConstraints(const std::unordered_multimap& order_requirements) { std::vector optimized_order; // To store our result in. @@ -422,7 +417,7 @@ class PathOrderOptimizer }; const std::function handle_node - = [¤t_position, &optimized_order, this](const Path current_node, const std::nullptr_t _state) + = [¤t_position, &optimized_order, this](const Path current_node, [[maybe_unused]] const std::nullptr_t state) { // We should make map from node <-> path for this stuff for (auto& path : paths_) @@ -652,7 +647,6 @@ class PathOrderOptimizer { // For most seam types, the shortest distance matters. Not for SHARPEST_CORNER though. // For SHARPEST_CORNER, use a fixed starting score of 0. - const coord_t distance = (combing_boundary_ == nullptr) ? getDirectDistance(here, target_pos) : getCombingDistance(here, target_pos); const double score_distance = (seam_config_.type_ == EZSeamType::SHARPEST_CORNER && seam_config_.corner_pref_ != EZSeamCornerPrefType::Z_SEAM_CORNER_PREF_NONE) ? MM2INT(10) : vSize2(here - target_pos); diff --git a/include/Preheat.h b/include/Preheat.h index dba5d72c08..e9ff74ac23 100644 --- a/include/Preheat.h +++ b/include/Preheat.h @@ -4,13 +4,13 @@ #ifndef PREHEAT_H #define PREHEAT_H +#include // max +#include + #include "settings/types/Duration.h" #include "settings/types/Ratio.h" #include "settings/types/Temperature.h" -#include // max -#include - namespace cura { @@ -45,11 +45,10 @@ class Preheat * or the initial layer temperature. * * \param extruder The extruder train - * \param flow The flow for which to get the optimal temperature * \param is_initial_layer Whether the initial layer temperature should be returned instead of flow-based temperature * \return The corresponding optimal temperature */ - Temperature getTemp(const size_t extruder, const Ratio& flow, const bool is_initial_layer); + Temperature getTemp(const size_t extruder, const bool is_initial_layer); /*! * Decide when to start warming up again after starting to cool down towards \p temp_mid. @@ -112,4 +111,4 @@ class Preheat } // namespace cura -#endif // PREHEAT_H \ No newline at end of file +#endif // PREHEAT_H diff --git a/include/SkeletalTrapezoidationGraph.h b/include/SkeletalTrapezoidationGraph.h index 01eb198f94..6f6bb99ebc 100644 --- a/include/SkeletalTrapezoidationGraph.h +++ b/include/SkeletalTrapezoidationGraph.h @@ -85,7 +85,7 @@ class SkeletalTrapezoidationGraph : public HalfEdgeGraph, Polygons, Polygons> operator()(auto&&... args) + std::tuple, Polygons, Polygons> operator()([[maybe_unused]] auto&&... args) { // this code is only reachable when no slot is registered while the infill type is requested to be // generated by a plugin; this should not be possible to set up in the first place. Return an empty diff --git a/include/support.h b/include/support.h index 16819c0c90..81b1218929 100644 --- a/include/support.h +++ b/include/support.h @@ -4,12 +4,12 @@ #ifndef SUPPORT_H #define SUPPORT_H -#include "settings/types/LayerIndex.h" -#include "utils/polygon.h" - #include #include +#include "settings/types/LayerIndex.h" +#include "utils/polygon.h" + namespace cura { @@ -219,11 +219,9 @@ class AreaSupport * \param storage Where to store the resulting support. * \param supportLayer_up The support areas the layer above. * \param supportLayer_this The overhang areas of the current layer at hand. - * \param smoothing_distance Maximal distance in the X/Y directions of a - * line segment which is to be smoothed out. * \return The joined support areas for this layer. */ - static Polygons join(const SliceDataStorage& storage, const Polygons& supportLayer_up, Polygons& supportLayer_this, const coord_t smoothing_distance); + static Polygons join(const SliceDataStorage& storage, const Polygons& supportLayer_up, Polygons& supportLayer_this); /*! * Move the support up from model (cut away polygons to ensure bottom z distance) @@ -322,11 +320,10 @@ class AreaSupport * generates varying xy disallowed areas for \param layer_idx where the offset distance is dependent on the wall angle * * \param storage Data storage containing the input layer data and - * \param settings The settings to use to calculate the offsets * \param layer_idx The layer for which the disallowed areas are to be calcualted * */ - static Polygons generateVaryingXYDisallowedArea(const SliceMeshStorage& storage, const Settings& infill_settings, const LayerIndex layer_idx); + static Polygons generateVaryingXYDisallowedArea(const SliceMeshStorage& storage, const LayerIndex layer_idx); }; diff --git a/src/BeadingStrategy/BeadingStrategy.cpp b/src/BeadingStrategy/BeadingStrategy.cpp index 88b295b7ad..9383d796f0 100644 --- a/src/BeadingStrategy/BeadingStrategy.cpp +++ b/src/BeadingStrategy/BeadingStrategy.cpp @@ -50,7 +50,7 @@ double BeadingStrategy::getTransitionAnchorPos(coord_t lower_bead_count) const return 1.0 - static_cast(transition_point - lower_optimum) / static_cast(upper_optimum - lower_optimum); } -std::vector BeadingStrategy::getNonlinearThicknesses(coord_t lower_bead_count) const +std::vector BeadingStrategy::getNonlinearThicknesses([[maybe_unused]] coord_t lower_bead_count) const { return std::vector(); } diff --git a/src/FffGcodeWriter.cpp b/src/FffGcodeWriter.cpp index 8c0577e3bc..4d54b3bb23 100644 --- a/src/FffGcodeWriter.cpp +++ b/src/FffGcodeWriter.cpp @@ -1092,7 +1092,7 @@ FffGcodeWriter::ProcessLayerResult FffGcodeWriter::processLayer(const SliceDataS == mesh->settings.get("wall_0_extruder_nr").extruder_nr_ // mesh surface mode should always only be printed with the outer wall extruder! ) { - addMeshLayerToGCode_meshSurfaceMode(storage, *mesh, mesh_config, gcode_layer); + addMeshLayerToGCode_meshSurfaceMode(*mesh, mesh_config, gcode_layer); } else { @@ -1476,8 +1476,7 @@ std::vector FffGcodeWriter::calculateMeshOrder(const SliceDataStorage& s return ret; } -void FffGcodeWriter::addMeshLayerToGCode_meshSurfaceMode(const SliceDataStorage& storage, const SliceMeshStorage& mesh, const MeshPathConfigs& mesh_config, LayerPlan& gcode_layer) - const +void FffGcodeWriter::addMeshLayerToGCode_meshSurfaceMode(const SliceMeshStorage& mesh, const MeshPathConfigs& mesh_config, LayerPlan& gcode_layer) const { if (gcode_layer.getLayerNr() > mesh.layer_nr_max_filled_layer) { @@ -1630,13 +1629,12 @@ bool FffGcodeWriter::processInfill( { return false; } - bool added_something = processMultiLayerInfill(storage, gcode_layer, mesh, extruder_nr, mesh_config, part); + bool added_something = processMultiLayerInfill(gcode_layer, mesh, extruder_nr, mesh_config, part); added_something = added_something | processSingleLayerInfill(storage, gcode_layer, mesh, extruder_nr, mesh_config, part); return added_something; } bool FffGcodeWriter::processMultiLayerInfill( - const SliceDataStorage& storage, LayerPlan& gcode_layer, const SliceMeshStorage& mesh, const size_t extruder_nr, @@ -2698,7 +2696,6 @@ void FffGcodeWriter::processRoofing( storage, gcode_layer, mesh, - mesh_config, extruder_nr, skin_part.roofing_fill, mesh_config.roofing_config, @@ -2879,7 +2876,6 @@ void FffGcodeWriter::processTopBottom( storage, gcode_layer, mesh, - mesh_config, extruder_nr, skin_part.skin_fill, *skin_config, @@ -2896,7 +2892,6 @@ void FffGcodeWriter::processSkinPrintFeature( const SliceDataStorage& storage, LayerPlan& gcode_layer, const SliceMeshStorage& mesh, - const MeshPathConfigs& mesh_config, const size_t extruder_nr, const Polygons& area, const GCodePathConfig& config, diff --git a/src/FffPolygonGenerator.cpp b/src/FffPolygonGenerator.cpp index fa25f1e1db..0f731b9bae 100644 --- a/src/FffPolygonGenerator.cpp +++ b/src/FffPolygonGenerator.cpp @@ -1090,7 +1090,8 @@ void FffPolygonGenerator::processFuzzyWalls(SliceMeshStorage& mesh) = (mesh.settings.get("adhesion_type") == EPlatformAdhesion::BRIM) ? 1 : 0; // don't make fuzzy skin on first layer if there's a brim auto hole_area = Polygons(); - std::function accumulate_is_in_hole = [](const bool& prev_result, const ExtrusionJunction& junction) + std::function accumulate_is_in_hole + = []([[maybe_unused]] const bool& prev_result, [[maybe_unused]] const ExtrusionJunction& junction) { return false; }; diff --git a/src/InterlockingGenerator.cpp b/src/InterlockingGenerator.cpp index ba4528eb51..6ac2efb7d1 100644 --- a/src/InterlockingGenerator.cpp +++ b/src/InterlockingGenerator.cpp @@ -78,7 +78,7 @@ std::pair InterlockingGenerator::growBorderAreasPerpendicula Polygons from_border_b = b.difference(total_shrunk); Polygons temp_a, temp_b; - for (auto _ : ranges::views::iota(0, (detect / min_line) + 2)) + for (coord_t i = 0; i < (detect / min_line) + 2; ++i) { temp_a = from_border_a.offset(min_line); temp_b = from_border_b.offset(min_line); diff --git a/src/LayerPlan.cpp b/src/LayerPlan.cpp index a9932a7116..6e5ce67341 100644 --- a/src/LayerPlan.cpp +++ b/src/LayerPlan.cpp @@ -1133,7 +1133,7 @@ void LayerPlan::addWall( void LayerPlan::addInfillWall(const ExtrusionLine& wall, const GCodePathConfig& path_config, bool force_retract) { - assert(("All empty walls should have been filtered at this stage", ! wall.empty())); + assert(! wall.empty() && "All empty walls should have been filtered at this stage"); ExtrusionJunction junction{ *wall.begin() }; addTravel(junction.p_, force_retract); @@ -1701,7 +1701,7 @@ TimeMaterialEstimates ExtruderPlan::computeNaiveTimeEstimates(Point2LL starting_ return estimates_; } -void ExtruderPlan::processFanSpeedForMinimalLayerTime(Point2LL starting_position, Duration minTime, double time_other_extr_plans) +void ExtruderPlan::processFanSpeedForMinimalLayerTime(Duration minTime, double time_other_extr_plans) { /* min layer time @@ -1778,7 +1778,6 @@ void LayerPlan::processFanSpeedAndMinimalLayerTime(Point2LL starting_position) return a.extruder_nr_ < b.extruder_nr_; }) ->extruder_nr_; - Point2LL starting_position_last_extruder; unsigned int last_extruder_idx; double other_extr_plan_time = 0.0; Duration maximum_cool_min_layer_time; @@ -1792,7 +1791,6 @@ void LayerPlan::processFanSpeedAndMinimalLayerTime(Point2LL starting_position) extruder_plan.computeNaiveTimeEstimates(starting_position); if (extruder_plan.extruder_nr_ == last_extruder_nr) { - starting_position_last_extruder = starting_position; last_extruder_idx = extr_plan_idx; } else @@ -1814,7 +1812,7 @@ void LayerPlan::processFanSpeedAndMinimalLayerTime(Point2LL starting_position) // apply minimum layer time behaviour ExtruderPlan& last_extruder_plan = extruder_plans_[last_extruder_idx]; last_extruder_plan.forceMinimalLayerTime(maximum_cool_min_layer_time, other_extr_plan_time); - last_extruder_plan.processFanSpeedForMinimalLayerTime(starting_position_last_extruder, maximum_cool_min_layer_time, other_extr_plan_time); + last_extruder_plan.processFanSpeedForMinimalLayerTime(maximum_cool_min_layer_time, other_extr_plan_time); } diff --git a/src/LayerPlanBuffer.cpp b/src/LayerPlanBuffer.cpp index 453d55f7f4..7d430b8f01 100644 --- a/src/LayerPlanBuffer.cpp +++ b/src/LayerPlanBuffer.cpp @@ -519,18 +519,12 @@ void LayerPlanBuffer::insertTempCommands() size_t extruder = extruder_plan.extruder_nr_; const Settings& extruder_settings = Application::getInstance().current_slice_->scene.extruders[extruder].settings_; Duration time = extruder_plan.estimates_.getTotalUnretractedTime(); - Ratio avg_flow; - if (time > 0.0) - { - avg_flow = extruder_plan.estimates_.material / time; - } - else + if (time <= 0.0) { assert(extruder_plan.estimates_.material == 0.0 && "No extrusion time should mean no material usage!"); - avg_flow = 0.0; } - Temperature print_temp = preheat_config_.getTemp(extruder, avg_flow, extruder_plan.is_initial_layer_); + Temperature print_temp = preheat_config_.getTemp(extruder, extruder_plan.is_initial_layer_); Temperature initial_print_temp = extruder_settings.get("material_initial_print_temperature"); if (extruder_plan.temperature_factor_ > 0) // force lower printing temperatures due to minimum layer time diff --git a/src/Preheat.cpp b/src/Preheat.cpp index d2190cb9a3..d9f24b200a 100644 --- a/src/Preheat.cpp +++ b/src/Preheat.cpp @@ -39,7 +39,7 @@ Duration Preheat::getTimeToGoFromTempToTemp(const size_t extruder, const Tempera return std::max(0.0_s, time); } -Temperature Preheat::getTemp(const size_t extruder, const Ratio& flow, const bool is_initial_layer) +Temperature Preheat::getTemp(const size_t extruder, const bool is_initial_layer) { const Settings& extruder_settings = Application::getInstance().current_slice_->scene.extruders[extruder].settings_; if (is_initial_layer && extruder_settings.get("material_print_temperature_layer_0") != 0) diff --git a/src/SkeletalTrapezoidation.cpp b/src/SkeletalTrapezoidation.cpp index 3aca0644db..887059324d 100644 --- a/src/SkeletalTrapezoidation.cpp +++ b/src/SkeletalTrapezoidation.cpp @@ -97,9 +97,7 @@ void SkeletalTrapezoidation::transferEdge( assert(twin->prev_); // Forth rib assert(twin->prev_->twin_); // Back rib assert(twin->prev_->twin_->prev_); // Prev segment along parabola - - constexpr bool is_not_next_to_start_or_end = false; // Only ribs at the end of a cell should be skipped - graph_.makeRib(prev_edge, start_source_point, end_source_point, is_not_next_to_start_or_end); + graph_.makeRib(prev_edge, start_source_point, end_source_point); } assert(prev_edge); } @@ -152,8 +150,7 @@ void SkeletalTrapezoidation::transferEdge( if (p1_idx < discretized.size() - 1) { // Rib for last segment gets introduced outside this function! - constexpr bool is_not_next_to_start_or_end = false; // Only ribs at the end of a cell should be skipped - graph_.makeRib(prev_edge, start_source_point, end_source_point, is_not_next_to_start_or_end); + graph_.makeRib(prev_edge, start_source_point, end_source_point); } } assert(prev_edge); @@ -460,8 +457,7 @@ void SkeletalTrapezoidation::constructFromPolygons(const Polygons& polys) node_t* starting_node = vd_node_to_he_node_[starting_vonoroi_edge->vertex0()]; starting_node->data_.distance_to_boundary_ = 0; - constexpr bool is_next_to_start_or_end = true; - graph_.makeRib(prev_edge, start_source_point, end_source_point, is_next_to_start_or_end); + graph_.makeRib(prev_edge, start_source_point, end_source_point); for (vd_t::edge_type* vd_edge = starting_vonoroi_edge->next(); vd_edge != ending_vonoroi_edge; vd_edge = vd_edge->next()) { assert(vd_edge->is_finite()); @@ -469,7 +465,7 @@ void SkeletalTrapezoidation::constructFromPolygons(const Polygons& polys) Point2LL v2 = VoronoiUtils::p(vd_edge->vertex1()); transferEdge(v1, v2, *vd_edge, prev_edge, start_source_point, end_source_point, points, segments); - graph_.makeRib(prev_edge, start_source_point, end_source_point, vd_edge->next() == ending_vonoroi_edge); + graph_.makeRib(prev_edge, start_source_point, end_source_point); } transferEdge(VoronoiUtils::p(ending_vonoroi_edge->vertex0()), end_source_point, *ending_vonoroi_edge, prev_edge, start_source_point, end_source_point, points, segments); diff --git a/src/SkeletalTrapezoidationGraph.cpp b/src/SkeletalTrapezoidationGraph.cpp index 514277ed36..cad3cba700 100644 --- a/src/SkeletalTrapezoidationGraph.cpp +++ b/src/SkeletalTrapezoidationGraph.cpp @@ -329,7 +329,7 @@ void SkeletalTrapezoidationGraph::collapseSmallEdges(coord_t snap_dist) } } -void SkeletalTrapezoidationGraph::makeRib(edge_t*& prev_edge, Point2LL start_source_point, Point2LL end_source_point, bool is_next_to_start_or_end) +void SkeletalTrapezoidationGraph::makeRib(edge_t*& prev_edge, Point2LL start_source_point, Point2LL end_source_point) { Point2LL p = LinearAlg2D::getClosestOnLine(prev_edge->to_->p_, start_source_point, end_source_point); coord_t dist = vSize(prev_edge->to_->p_ - p); diff --git a/src/TreeModelVolumes.cpp b/src/TreeModelVolumes.cpp index 948ef86ec0..7318061091 100644 --- a/src/TreeModelVolumes.cpp +++ b/src/TreeModelVolumes.cpp @@ -905,7 +905,7 @@ Polygons TreeModelVolumes::safeOffset(const Polygons& me, coord_t distance, Clip assert(distance * max_safe_step_distance >= 0); Polygons ret = me; - for (const auto i : ranges::views::iota(0UL, steps)) + for (size_t i = 0; i < steps; ++i) { ret = ret.offset(max_safe_step_distance, jt).unionPolygons(collision); } @@ -1254,7 +1254,7 @@ coord_t TreeModelVolumes::ceilRadius(coord_t radius) const coord_t exponential_result = SUPPORT_TREE_EXPONENTIAL_THRESHOLD * SUPPORT_TREE_EXPONENTIAL_FACTOR; const coord_t stepsize = (exponential_result - radius_0_) / (SUPPORT_TREE_PRE_EXPONENTIAL_STEPS + 1); coord_t result = radius_0_; - for (const auto step : ranges::views::iota(0UL, SUPPORT_TREE_PRE_EXPONENTIAL_STEPS)) + for (size_t i = 0; i < SUPPORT_TREE_PRE_EXPONENTIAL_STEPS; ++i) { result += stepsize; if (result >= radius && ! ignorable_radii_.count(result)) diff --git a/src/TreeSupport.cpp b/src/TreeSupport.cpp index d12e14adbd..145fc64bf3 100644 --- a/src/TreeSupport.cpp +++ b/src/TreeSupport.cpp @@ -250,7 +250,7 @@ void TreeSupport::precalculate(const SliceDataStorage& storage, std::vector>& move_bounds, SliceDataStorage& storage) { - TreeSupportTipGenerator tip_gen(storage, mesh, volumes_); + TreeSupportTipGenerator tip_gen(mesh, volumes_); tip_gen.generateTips(storage, mesh, move_bounds, additional_required_support_area, placed_support_lines_support_areas); } diff --git a/src/TreeSupportTipGenerator.cpp b/src/TreeSupportTipGenerator.cpp index c5292dbf2b..27137585b6 100644 --- a/src/TreeSupportTipGenerator.cpp +++ b/src/TreeSupportTipGenerator.cpp @@ -28,7 +28,7 @@ namespace cura { -TreeSupportTipGenerator::TreeSupportTipGenerator(const SliceDataStorage& storage, const SliceMeshStorage& mesh, TreeModelVolumes& volumes_s) +TreeSupportTipGenerator::TreeSupportTipGenerator(const SliceMeshStorage& mesh, TreeModelVolumes& volumes_s) : config_(mesh.settings) , use_fake_roof_(! mesh.settings.get("support_roof_enable")) , volumes_(volumes_s) diff --git a/src/communication/CommandLine.cpp b/src/communication/CommandLine.cpp index 26dcaa60c3..95359abae4 100644 --- a/src/communication/CommandLine.cpp +++ b/src/communication/CommandLine.cpp @@ -80,7 +80,7 @@ void CommandLine::sendGCodePrefix(const std::string&) const // TODO: Right now this is done directly in the g-code writer. For consistency it should be moved here? } -void CommandLine::sendSliceUUID(const std::string& slice_uuid) const +void CommandLine::sendSliceUUID([[maybe_unused]] const std::string& slice_uuid) const { // pass } diff --git a/src/plugins/converters.cpp b/src/plugins/converters.cpp index 2f8eabd151..40988a2f7b 100644 --- a/src/plugins/converters.cpp +++ b/src/plugins/converters.cpp @@ -85,9 +85,11 @@ handshake_response::native_value_type handshake_response::operator()(const hands .broadcast_subscriptions = std::set(message.broadcast_subscriptions().begin(), message.broadcast_subscriptions().end()) }; } -simplify_request::value_type - simplify_request::operator()(const simplify_request::native_value_type& polygons, const coord_t max_resolution, const coord_t max_deviation, const coord_t max_area_deviation) - const +simplify_request::value_type simplify_request::operator()( + const simplify_request::native_value_type& polygons, + const coord_t max_resolution, + [[maybe_unused]] const coord_t max_deviation, + [[maybe_unused]] const coord_t max_area_deviation) const { value_type message{}; if (polygons.empty()) @@ -478,4 +480,4 @@ gcode_paths_modify_response::native_value_type return paths; } -} // namespace cura::plugins \ No newline at end of file +} // namespace cura::plugins diff --git a/src/skin.cpp b/src/skin.cpp index 9f1d865dcd..e02ba1b2d1 100644 --- a/src/skin.cpp +++ b/src/skin.cpp @@ -386,7 +386,6 @@ Polygons SkinInfillAreaComputation::generateFilledAreaBelow(SliceLayerPart& part { return {}; } - constexpr size_t min_wall_line_count = 2; const int lowest_flooring_layer = layer_nr_ - flooring_layer_count; Polygons filled_area_below = getOutlineOnLayer(part, lowest_flooring_layer); diff --git a/src/support.cpp b/src/support.cpp index 05e81fbf93..6e1f398e7a 100644 --- a/src/support.cpp +++ b/src/support.cpp @@ -186,7 +186,6 @@ void AreaSupport::generateGradualSupport(SliceDataStorage& storage) const coord_t gradual_support_step_height = infill_extruder.settings_.get("gradual_support_infill_step_height"); const size_t max_density_steps = infill_extruder.settings_.get("gradual_support_infill_steps"); - const coord_t wall_count = infill_extruder.settings_.get("support_wall_count"); const coord_t wall_width = infill_extruder.settings_.get("support_line_width"); // no early-out for this function; it needs to initialize the [infill_area_per_combine_per_density] @@ -458,7 +457,7 @@ void AreaSupport::cleanup(SliceDataStorage& storage) } } -Polygons AreaSupport::join(const SliceDataStorage& storage, const Polygons& supportLayer_up, Polygons& supportLayer_this, const coord_t smoothing_distance) +Polygons AreaSupport::join(const SliceDataStorage& storage, const Polygons& supportLayer_up, Polygons& supportLayer_this) { Polygons joined; @@ -811,7 +810,7 @@ void AreaSupport::generateOverhangAreasForMesh(SliceDataStorage& storage, SliceM }); } -Polygons AreaSupport::generateVaryingXYDisallowedArea(const SliceMeshStorage& storage, const Settings& infill_settings, const LayerIndex layer_idx) +Polygons AreaSupport::generateVaryingXYDisallowedArea(const SliceMeshStorage& storage, const LayerIndex layer_idx) { const auto& mesh_group_settings = Application::getInstance().current_slice_->scene.current_mesh_group->settings; const Simplify simplify{ mesh_group_settings }; @@ -820,7 +819,6 @@ Polygons AreaSupport::generateVaryingXYDisallowedArea(const SliceMeshStorage& st const auto support_distance_bot = static_cast(mesh_group_settings.get("support_bottom_distance")); const auto overhang_angle = mesh_group_settings.get("support_angle"); const auto xy_distance = static_cast(mesh_group_settings.get("support_xy_distance")); - const auto xy_distance_overhang = infill_settings.get("support_xy_distance_overhang"); constexpr coord_t snap_radius = 10; constexpr coord_t close_dist = snap_radius + 5; // needs to be larger than the snap radius! @@ -1065,8 +1063,6 @@ void AreaSupport::generateSupportAreasForMesh( const coord_t xy_distance_overhang = infill_settings.get("support_xy_distance_overhang"); const bool use_xy_distance_overhang = infill_settings.get("support_xy_overrides_z") == SupportDistPriority::Z_OVERRIDES_XY; // whether to use a different xy distance at overhangs - const AngleRadians angle = ((mesh.settings.get("support_roof_enable")) ? roof_settings : infill_settings).get("support_angle"); - const double tan_angle = tan(angle) - 0.01; // the XY-component of the supportAngle constexpr bool no_support = false; constexpr bool no_prime_tower = false; const coord_t support_line_width = mesh_group_settings.get("support_infill_extruder_nr").settings_.get("support_line_width"); @@ -1116,7 +1112,7 @@ void AreaSupport::generateSupportAreasForMesh( // layer below that protrudes beyond the current layer's area and combine it with the current layer's overhang disallowed area Polygons minimum_xy_disallowed_areas = xy_disallowed_per_layer[layer_idx].offset(xy_distance_overhang); - Polygons varying_xy_disallowed_areas = generateVaryingXYDisallowedArea(mesh, infill_settings, layer_idx); + Polygons varying_xy_disallowed_areas = generateVaryingXYDisallowedArea(mesh, layer_idx); xy_disallowed_per_layer[layer_idx] = minimum_xy_disallowed_areas.unionPolygons(varying_xy_disallowed_areas); scripta::log("support_xy_disallowed_areas", xy_disallowed_per_layer[layer_idx], SectionType::SUPPORT, layer_idx); } @@ -1139,26 +1135,6 @@ void AreaSupport::generateSupportAreasForMesh( const coord_t max_tower_supported_diameter = infill_settings.get("support_tower_maximum_supported_diameter"); const bool use_towers = infill_settings.get("support_use_towers") && max_tower_supported_diameter > 0; - coord_t smoothing_distance; - { // compute best smoothing_distance - const ExtruderTrain& infill_train = mesh_group_settings.get("support_infill_extruder_nr"); - const coord_t infill_line_width = infill_train.settings_.get("support_line_width"); - smoothing_distance = infill_line_width; - if (mesh.settings.get("support_roof_enable")) - { - const ExtruderTrain& roof_train = mesh_group_settings.get("support_roof_extruder_nr"); - const coord_t roof_line_width = roof_train.settings_.get("support_roof_line_width"); - smoothing_distance = std::max(smoothing_distance, roof_line_width); - } - - if (mesh.settings.get("support_bottom_enable")) - { - const ExtruderTrain& bottom_train = mesh_group_settings.get("support_bottom_extruder_nr"); - const coord_t bottom_line_width = bottom_train.settings_.get("support_bottom_line_width"); - smoothing_distance = std::max(smoothing_distance, bottom_line_width); - } - } - const coord_t z_distance_bottom = ((mesh.settings.get("support_bottom_enable")) ? bottom_settings : infill_settings).get("support_bottom_distance"); const size_t bottom_empty_layer_count = round_up_divide(z_distance_bottom, layer_thickness); // number of empty layers between support and model const coord_t bottom_stair_step_height = std::max(static_cast(0), mesh.settings.get("support_bottom_stair_step_height")); @@ -1234,7 +1210,7 @@ void AreaSupport::generateSupportAreasForMesh( layer_above = ∅ layer_this = layer_this.unionPolygons(storage.support.supportLayers[layer_idx].support_mesh); } - layer_this = AreaSupport::join(storage, *layer_above, layer_this, smoothing_distance).difference(model_mesh_on_layer); + layer_this = AreaSupport::join(storage, *layer_above, layer_this).difference(model_mesh_on_layer); } // make towers for small support @@ -1548,7 +1524,6 @@ std::pair AreaSupport::computeBasicAndFullOverhang(const Sli void AreaSupport::detectOverhangPoints(const SliceDataStorage& storage, SliceMeshStorage& mesh) { - const ExtruderTrain& infill_extruder = mesh.settings.get("support_infill_extruder_nr"); const coord_t max_tower_supported_diameter = mesh.settings.get("support_tower_maximum_supported_diameter"); const coord_t max_tower_supported_area = max_tower_supported_diameter * max_tower_supported_diameter; @@ -1652,8 +1627,6 @@ void AreaSupport::handleTowers( if (tower_roof.area() < tower_diameter * tower_diameter) { - constexpr bool no_support = false; - constexpr bool no_prime_tower = false; Polygons model_outline = xy_disallowed_area; // Rather than offsetting the tower with tower_roof_expansion_distance we do this step wise to achieve two things diff --git a/src/utils/Simplify.cpp b/src/utils/Simplify.cpp index cad210b30b..8d0795da54 100644 --- a/src/utils/Simplify.cpp +++ b/src/utils/Simplify.cpp @@ -83,7 +83,7 @@ size_t Simplify::previousNotDeleted(size_t index, const std::vector& to_de return index; } -Polygon Simplify::createEmpty(const Polygon& original) const +Polygon Simplify::createEmpty([[maybe_unused]] const Polygon& original) const { return Polygon(); } @@ -115,7 +115,7 @@ const Point2LL& Simplify::getPosition(const ExtrusionJunction& vertex) const return vertex.p_; } -Point2LL Simplify::createIntersection(const Point2LL& before, const Point2LL intersection, const Point2LL& after) const +Point2LL Simplify::createIntersection([[maybe_unused]] const Point2LL& before, const Point2LL intersection, [[maybe_unused]] const Point2LL& after) const { return intersection; } @@ -128,7 +128,7 @@ ExtrusionJunction Simplify::createIntersection(const ExtrusionJunction& before, return ExtrusionJunction(intersection, (before.w_ + after.w_) / 2, before.perimeter_index_); } -coord_t Simplify::getAreaDeviation(const Point2LL& before, const Point2LL& vertex, const Point2LL& after) const +coord_t Simplify::getAreaDeviation([[maybe_unused]] const Point2LL& before, [[maybe_unused]] const Point2LL& vertex, [[maybe_unused]] const Point2LL& after) const { return 0; // Fixed-width polygons don't have any deviation. } From 46f0f974a26a9dc0ae2450c37cf2d8b336a83b79 Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Wed, 22 Nov 2023 13:25:11 +0100 Subject: [PATCH 34/48] Fixed dangling reference warnings --- include/PathOrderOptimizer.h | 13 +++++++------ include/pathPlanning/Comb.h | 2 +- include/utils/polygon.h | 33 ++++++++++++++++----------------- src/pathPlanning/Comb.cpp | 27 +++++++++++++-------------- src/utils/polygon.cpp | 32 ++++++++++++++++---------------- 5 files changed, 53 insertions(+), 54 deletions(-) diff --git a/include/PathOrderOptimizer.h b/include/PathOrderOptimizer.h index 94b4c74344..a65d3bba87 100644 --- a/include/PathOrderOptimizer.h +++ b/include/PathOrderOptimizer.h @@ -633,9 +633,10 @@ class PathOrderOptimizer // Precompute segments lengths because we are going to need them multiple times std::vector segments_sizes(path.converted_->size()); coord_t total_length = 0; - for (const auto& [i, here] : **path.converted_ | ranges::views::enumerate) + for (size_t i = 0; i < path.converted_->size(); ++i) { - const Point2LL& next = (*path.converted_)[(i + 1) % path.converted_->size()]; + const Point2LL& here = path.converted_->at(i); + const Point2LL& next = path.converted_->at((i + 1) % path.converted_->size()); const coord_t segment_size = vSize(next - here); segments_sizes[i] = segment_size; total_length += segment_size; @@ -708,7 +709,7 @@ class PathOrderOptimizer // ties are broken by favouring points with lower x-coord // if x-coord for both points are equal then break ties by // favouring points with lower y-coord - const Point2LL& best_point = (*path.converted_)[best_i]; + const Point2LL& best_point = path.converted_->at(best_i); if (std::abs(here.Y - best_point.Y) <= EPSILON ? best_point.X < here.X : best_point.Y < here.Y) { best_score = std::min(best_score, score); @@ -758,13 +759,13 @@ class PathOrderOptimizer travelled_distance += segment_size; } - const Point2LL& next_pos = (*path.converted_)[(here + actual_delta + path.converted_->size()) % path.converted_->size()]; + const Point2LL& next_pos = path.converted_->at((here + actual_delta + path.converted_->size()) % path.converted_->size()); if (travelled_distance > distance) [[likely]] { // We have overtaken the required distance, go backward on the last segment int prev = (here + actual_delta - direction + path.converted_->size()) % path.converted_->size(); - const Point2LL& prev_pos = (*path.converted_)[prev]; + const Point2LL& prev_pos = path.converted_->at(prev); const Point2LL vector = next_pos - prev_pos; const Point2LL unit_vector = (vector * 1000) / segment_size; @@ -794,7 +795,7 @@ class PathOrderOptimizer static double cornerAngle(const OrderablePath& path, int i, const std::vector& segments_sizes, coord_t total_length, const coord_t angle_query_distance = 1000) { const coord_t bounded_distance = std::min(angle_query_distance, total_length / 2); - const Point2LL& here = (*path.converted_)[i]; + const Point2LL& here = path.converted_->at(i); const Point2LL next = findNeighbourPoint(path, i, bounded_distance, segments_sizes); const Point2LL previous = findNeighbourPoint(path, i, -bounded_distance, segments_sizes); diff --git a/include/pathPlanning/Comb.h b/include/pathPlanning/Comb.h index c766bb0820..cbdd1b539a 100644 --- a/include/pathPlanning/Comb.h +++ b/include/pathPlanning/Comb.h @@ -177,7 +177,7 @@ class Comb * \param start_inside_poly[out] The polygon in which the point has been moved * \return Whether we have moved the point inside */ - bool moveInside(Polygons& boundary_inside, bool is_inside, LocToLineGrid* inside_loc_to_line, Point2LL& dest_point, unsigned int& start_inside_poly); + bool moveInside(Polygons& boundary_inside, bool is_inside, LocToLineGrid* inside_loc_to_line, Point2LL& dest_point, size_t &start_inside_poly); void moveCombPathInside(Polygons& boundary_inside, Polygons& boundary_inside_optimal, CombPath& comb_path_input, CombPath& comb_path_output); diff --git a/include/utils/polygon.h b/include/utils/polygon.h index 5b3eb781af..0cfc9af876 100644 --- a/include/utils/polygon.h +++ b/include/utils/polygon.h @@ -60,7 +60,7 @@ typedef std::list ListPolygon; //!< A polygon represented by a linked typedef std::vector ListPolygons; //!< Polygons represented by a vector of linked lists instead of a vector of vectors const static int clipper_init = (0); -#define NO_INDEX (std::numeric_limits::max()) +#define NO_INDEX (std::numeric_limits::max()) class ConstPolygonPointer; @@ -496,16 +496,15 @@ class PolygonRef : public ConstPolygonRef return *this; } - Point2LL& operator[](unsigned int index) + Point2LL& operator[](size_t index) { POLY_ASSERT(index < size()); return (*path)[index]; } - const Point2LL& operator[](unsigned int index) const + const Point2LL& operator[](size_t index) const { - POLY_ASSERT(index < size()); - return (*path)[index]; + return ConstPolygonRef::operator[](index); } ClipperLib::Path::iterator begin() @@ -549,9 +548,9 @@ class PolygonRef : public ConstPolygonRef path->emplace_back(args...); } - void remove(unsigned int index) + void remove(size_t index) { - POLY_ASSERT(index < size() && index <= static_cast(std::numeric_limits::max())); + POLY_ASSERT(index < size() && index <= static_cast(std::numeric_limits::max())); path->erase(path->begin() + index); } @@ -833,7 +832,7 @@ class Polygons */ bool empty() const; - unsigned int pointCount() const; //!< Return the amount of points in all polygons + size_t pointCount() const; //!< Return the amount of points in all polygons PolygonRef operator[](size_t index) { @@ -1173,7 +1172,7 @@ class Polygons * \param border_result Whether a point exactly on a polygon counts as inside * \return The index of the polygon inside which the point \p p resides */ - unsigned int findInside(Point2LL p, bool border_result = false); + size_t findInside(Point2LL p, bool border_result = false); /*! * Approximates the convex hull of the polygons. @@ -1501,9 +1500,9 @@ class Polygons void applyMatrix(const PointMatrix& matrix) { - for (unsigned int i = 0; i < paths.size(); i++) + for (size_t i = 0; i < paths.size(); i++) { - for (unsigned int j = 0; j < paths[i].size(); j++) + for (size_t j = 0; j < paths[i].size(); j++) { paths[i][j] = matrix.apply(paths[i][j]); } @@ -1512,9 +1511,9 @@ class Polygons void applyMatrix(const Point3Matrix& matrix) { - for (unsigned int i = 0; i < paths.size(); i++) + for (size_t i = 0; i < paths.size(); i++) { - for (unsigned int j = 0; j < paths[i].size(); j++) + for (size_t j = 0; j < paths[i].size(); j++) { paths[i][j] = matrix.apply(paths[i][j]); } @@ -1554,7 +1553,7 @@ class PolygonsPart : public Polygons * Extension of vector> which is similar to a vector of PolygonParts, except the base of the container is indices to polygons into the original Polygons, * instead of the polygons themselves */ -class PartsView : public std::vector> +class PartsView : public std::vector> { public: Polygons& polygons_; @@ -1569,7 +1568,7 @@ class PartsView : public std::vector> * \param boundary_poly_idx Optional output parameter: The index of the boundary polygon of the part in \p polygons * \return The PolygonsPart containing the polygon with index \p poly_idx */ - unsigned int getPartContaining(unsigned int poly_idx, unsigned int* boundary_poly_idx = nullptr) const; + size_t getPartContaining(size_t poly_idx, size_t* boundary_poly_idx = nullptr) const; /*! * Assemble the PolygonsPart of which the polygon with index \p poly_idx is part. * @@ -1577,14 +1576,14 @@ class PartsView : public std::vector> * \param boundary_poly_idx Optional output parameter: The index of the boundary polygon of the part in \p polygons * \return The PolygonsPart containing the polygon with index \p poly_idx */ - PolygonsPart assemblePartContaining(unsigned int poly_idx, unsigned int* boundary_poly_idx = nullptr) const; + PolygonsPart assemblePartContaining(size_t poly_idx, size_t* boundary_poly_idx = nullptr) const; /*! * Assemble the PolygonsPart of which the polygon with index \p poly_idx is part. * * \param part_idx The index of the part * \return The PolygonsPart with index \p poly_idx */ - PolygonsPart assemblePart(unsigned int part_idx) const; + PolygonsPart assemblePart(size_t part_idx) const; }; } // namespace cura diff --git a/src/pathPlanning/Comb.cpp b/src/pathPlanning/Comb.cpp index d422f18b2e..e8fbcb5919 100644 --- a/src/pathPlanning/Comb.cpp +++ b/src/pathPlanning/Comb.cpp @@ -103,16 +103,16 @@ bool Comb::calc( } const Point2LL travel_end_point_before_combing = end_point; // Move start and end point inside the optimal comb boundary - unsigned int start_inside_poly = NO_INDEX; + size_t start_inside_poly = NO_INDEX; const bool start_inside = moveInside(boundary_inside_optimal_, _start_inside, inside_loc_to_line_optimal_.get(), start_point, start_inside_poly); - unsigned int end_inside_poly = NO_INDEX; + size_t end_inside_poly = NO_INDEX; const bool end_inside = moveInside(boundary_inside_optimal_, _end_inside, inside_loc_to_line_optimal_.get(), end_point, end_inside_poly); - unsigned int start_part_boundary_poly_idx = NO_INDEX; // Added initial value to stop MSVC throwing an exception in debug mode - unsigned int end_part_boundary_poly_idx = NO_INDEX; - unsigned int start_part_idx = (start_inside_poly == NO_INDEX) ? NO_INDEX : parts_view_inside_optimal_.getPartContaining(start_inside_poly, &start_part_boundary_poly_idx); - unsigned int end_part_idx = (end_inside_poly == NO_INDEX) ? NO_INDEX : parts_view_inside_optimal_.getPartContaining(end_inside_poly, &end_part_boundary_poly_idx); + size_t start_part_boundary_poly_idx = NO_INDEX; // Added initial value to stop MSVC throwing an exception in debug mode + size_t end_part_boundary_poly_idx = NO_INDEX; + size_t start_part_idx = (start_inside_poly == NO_INDEX) ? NO_INDEX : parts_view_inside_optimal_.getPartContaining(start_inside_poly, &start_part_boundary_poly_idx); + size_t end_part_idx = (end_inside_poly == NO_INDEX) ? NO_INDEX : parts_view_inside_optimal_.getPartContaining(end_inside_poly, &end_part_boundary_poly_idx); const bool fail_on_unavoidable_obstacles = perform_z_hops && perform_z_hops_only_when_collides; @@ -137,18 +137,17 @@ bool Comb::calc( } // Move start and end point inside the minimum comb boundary - unsigned int start_inside_poly_min = NO_INDEX; + size_t start_inside_poly_min = NO_INDEX; const bool start_inside_min = moveInside(boundary_inside_minimum_, _start_inside, inside_loc_to_line_minimum_.get(), start_point, start_inside_poly_min); - unsigned int end_inside_poly_min = NO_INDEX; + size_t end_inside_poly_min = NO_INDEX; const bool end_inside_min = moveInside(boundary_inside_minimum_, _end_inside, inside_loc_to_line_minimum_.get(), end_point, end_inside_poly_min); - unsigned int start_part_boundary_poly_idx_min{}; - unsigned int end_part_boundary_poly_idx_min{}; - unsigned int start_part_idx_min + size_t start_part_boundary_poly_idx_min{}; + size_t end_part_boundary_poly_idx_min{}; + size_t start_part_idx_min = (start_inside_poly_min == NO_INDEX) ? NO_INDEX : parts_view_inside_minimum_.getPartContaining(start_inside_poly_min, &start_part_boundary_poly_idx_min); - unsigned int end_part_idx_min - = (end_inside_poly_min == NO_INDEX) ? NO_INDEX : parts_view_inside_minimum_.getPartContaining(end_inside_poly_min, &end_part_boundary_poly_idx_min); + size_t end_part_idx_min = (end_inside_poly_min == NO_INDEX) ? NO_INDEX : parts_view_inside_minimum_.getPartContaining(end_inside_poly_min, &end_part_boundary_poly_idx_min); CombPath result_path; bool comb_result; @@ -425,7 +424,7 @@ Comb::Crossing::Crossing( } } -bool Comb::moveInside(Polygons& boundary_inside, bool is_inside, LocToLineGrid* inside_loc_to_line, Point2LL& dest_point, unsigned int& inside_poly) +bool Comb::moveInside(Polygons& boundary_inside, bool is_inside, LocToLineGrid* inside_loc_to_line, Point2LL& dest_point, size_t& inside_poly) { if (is_inside) { diff --git a/src/utils/polygon.cpp b/src/utils/polygon.cpp index 52708890ab..2c6b254bc7 100644 --- a/src/utils/polygon.cpp +++ b/src/utils/polygon.cpp @@ -137,9 +137,9 @@ void Polygons::makeConvex() } } -unsigned int Polygons::pointCount() const +size_t Polygons::pointCount() const { - unsigned int count = 0; + size_t count = 0; for (const ClipperLib::Path& path : paths) { count += path.size(); @@ -211,7 +211,7 @@ bool Polygons::insideOld(Point2LL p, bool border_result) const return (crossings % 2) == 1; } -unsigned int Polygons::findInside(Point2LL p, bool border_result) +size_t Polygons::findInside(Point2LL p, bool border_result) { Polygons& thiss = *this; if (size() < 1) @@ -223,7 +223,7 @@ unsigned int Polygons::findInside(Point2LL p, bool border_result) std::vector min_x(size(), std::numeric_limits::max()); std::vector crossings(size()); - for (unsigned int poly_idx = 0; poly_idx < size(); poly_idx++) + for (size_t poly_idx = 0; poly_idx < size(); poly_idx++) { PolygonRef poly = thiss[poly_idx]; Point2LL p0 = poly.back(); @@ -256,9 +256,9 @@ unsigned int Polygons::findInside(Point2LL p, bool border_result) } int64_t min_x_uneven = std::numeric_limits::max(); - unsigned int ret = NO_INDEX; - unsigned int n_unevens = 0; - for (unsigned int array_idx = 0; array_idx < size(); array_idx++) + size_t ret = NO_INDEX; + size_t n_unevens = 0; + for (size_t array_idx = 0; array_idx < size(); array_idx++) { if (crossings[array_idx] % 2 == 1) { @@ -1508,17 +1508,17 @@ Polygons Polygons::tubeShape(const coord_t inner_offset, const coord_t outer_off return this->offset(outer_offset).difference(this->offset(-inner_offset)); } -unsigned int PartsView::getPartContaining(unsigned int poly_idx, unsigned int* boundary_poly_idx) const +size_t PartsView::getPartContaining(size_t poly_idx, size_t* boundary_poly_idx) const { const PartsView& partsView = *this; - for (unsigned int part_idx_now = 0; part_idx_now < partsView.size(); part_idx_now++) + for (size_t part_idx_now = 0; part_idx_now < partsView.size(); part_idx_now++) { - const std::vector& partView = partsView[part_idx_now]; + const std::vector& partView = partsView[part_idx_now]; if (partView.size() == 0) { continue; } - std::vector::const_iterator result = std::find(partView.begin(), partView.end(), poly_idx); + std::vector::const_iterator result = std::find(partView.begin(), partView.end(), poly_idx); if (result != partView.end()) { if (boundary_poly_idx) @@ -1531,13 +1531,13 @@ unsigned int PartsView::getPartContaining(unsigned int poly_idx, unsigned int* b return NO_INDEX; } -PolygonsPart PartsView::assemblePart(unsigned int part_idx) const +PolygonsPart PartsView::assemblePart(size_t part_idx) const { const PartsView& partsView = *this; PolygonsPart ret; if (part_idx != NO_INDEX) { - for (unsigned int poly_idx_ff : partsView[part_idx]) + for (size_t poly_idx_ff : partsView[part_idx]) { ret.add(polygons_[poly_idx_ff]); } @@ -1545,10 +1545,10 @@ PolygonsPart PartsView::assemblePart(unsigned int part_idx) const return ret; } -PolygonsPart PartsView::assemblePartContaining(unsigned int poly_idx, unsigned int* boundary_poly_idx) const +PolygonsPart PartsView::assemblePartContaining(size_t poly_idx, size_t* boundary_poly_idx) const { PolygonsPart ret; - unsigned int part_idx = getPartContaining(poly_idx, boundary_poly_idx); + size_t part_idx = getPartContaining(poly_idx, boundary_poly_idx); if (part_idx != NO_INDEX) { return assemblePart(part_idx); @@ -1580,7 +1580,7 @@ void Polygons::splitIntoPartsView_processPolyTreeNode(PartsView& partsView, Poly { ClipperLib::PolyNode* child = node->Childs[n]; partsView.emplace_back(); - unsigned int pos = partsView.size() - 1; + size_t pos = partsView.size() - 1; partsView[pos].push_back(reordered.size()); reordered.add(child->Contour); // TODO: should this steal the internal representation for speed? for (int i = 0; i < child->ChildCount(); i++) From 4749362831173ba2c03f251479dd44bfbf193006 Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Wed, 22 Nov 2023 14:56:45 +0100 Subject: [PATCH 35/48] Fixed numeric conversion warnings --- include/bridge.h | 2 +- include/pathPlanning/GCodePath.h | 2 +- include/settings/types/LayerIndex.h | 8 ++++++-- include/utils/ExtrusionLine.h | 12 +++++------- include/utils/Point2LL.h | 4 ++-- include/utils/PolygonsPointIndex.h | 6 +++--- include/utils/linearAlg2D.h | 2 +- include/utils/polygon.h | 8 ++++---- src/ConicalOverhang.cpp | 6 +++--- src/FffGcodeWriter.cpp | 2 +- src/FffPolygonGenerator.cpp | 5 +---- src/InterlockingGenerator.cpp | 22 +++++++++++----------- src/bridge.cpp | 29 +++++++++++++++-------------- src/utils/ExtrusionLine.cpp | 4 ++-- src/utils/polygon.cpp | 2 +- 15 files changed, 57 insertions(+), 57 deletions(-) diff --git a/include/bridge.h b/include/bridge.h index e7972bc17e..a4cb04233d 100644 --- a/include/bridge.h +++ b/include/bridge.h @@ -27,7 +27,7 @@ class SupportLayer; * \param supported_regions Pre-computed regions that the support layer would * support. */ -int bridgeAngle(const Settings& settings, const Polygons& skin_outline, const SliceDataStorage& storage, const unsigned layer_nr, const unsigned bridge_layer, const SupportLayer* support_layer, Polygons& supported_regions); +double bridgeAngle(const Settings& settings, const Polygons& skin_outline, const SliceDataStorage& storage, const unsigned layer_nr, const unsigned bridge_layer, const SupportLayer* support_layer, Polygons& supported_regions); }//namespace cura diff --git a/include/pathPlanning/GCodePath.h b/include/pathPlanning/GCodePath.h index e94fb8edfc..8ac4286082 100644 --- a/include/pathPlanning/GCodePath.h +++ b/include/pathPlanning/GCodePath.h @@ -45,7 +45,7 @@ struct GCodePath bool perform_z_hop{ false }; //!< Whether to perform a z_hop in this path, which is assumed to be a travel path. bool perform_prime{ false }; //!< Whether this path is preceded by a prime (blob) bool skip_agressive_merge_hint{ false }; //!< Wheter this path needs to skip merging if any travel paths are in between the extrusions. - std::vector points; //!< The points constituting this path. + std::vector points{}; //!< The points constituting this path. bool done{ false }; //!< Path is finished, no more moves should be added, and a new path should be started instead of any appending done to this one. double fan_speed{ GCodePathConfig::FAN_SPEED_DEFAULT }; //!< fan speed override for this path, value should be within range 0-100 (inclusive) and ignored otherwise TimeMaterialEstimates estimates{}; //!< Naive time and material estimates diff --git a/include/settings/types/LayerIndex.h b/include/settings/types/LayerIndex.h index 6298555dc0..9e2100da87 100644 --- a/include/settings/types/LayerIndex.h +++ b/include/settings/types/LayerIndex.h @@ -26,10 +26,14 @@ struct LayerIndex constexpr LayerIndex(LayerIndex&& other) noexcept = default; constexpr explicit LayerIndex(const utils::floating_point auto val) noexcept - : value{ static_cast(val) } {}; + : value{ static_cast(val) } + { + } constexpr LayerIndex(const utils::integral auto val) noexcept - : value{ static_cast(val) } {}; + : value{ static_cast(val) } + { + } constexpr LayerIndex& operator=(const LayerIndex& other) noexcept = default; diff --git a/include/utils/ExtrusionLine.h b/include/utils/ExtrusionLine.h index b1872da728..7c09ca4eb5 100644 --- a/include/utils/ExtrusionLine.h +++ b/include/utils/ExtrusionLine.h @@ -65,12 +65,10 @@ struct ExtrusionLine return junctions_.empty(); } - ExtrusionLine(const size_t inset_idx, const bool is_odd); - - ExtrusionLine() - : inset_idx_(-1) - , is_odd_(true) - , is_closed_(false) + ExtrusionLine(size_t inset_idx = std::numeric_limits::max(), bool is_odd = false, bool is_closed = false) + : inset_idx_(inset_idx) + , is_odd_(is_odd) + , is_closed_(is_closed) { } @@ -174,7 +172,7 @@ struct ExtrusionLine void insert(size_t index, const ExtrusionJunction& p) { - junctions_.insert(junctions_.begin() + index, p); + junctions_.insert(junctions_.begin() + static_cast(index), p); } template diff --git a/include/utils/Point2LL.h b/include/utils/Point2LL.h index 76f8df39b1..8623282fc2 100644 --- a/include/utils/Point2LL.h +++ b/include/utils/Point2LL.h @@ -183,12 +183,12 @@ INLINE coord_t cross(const Point2LL& p0, const Point2LL& p1) return p0.X * p1.Y - p0.Y * p1.X; } -INLINE int angle(const Point2LL& p) +INLINE double angle(const Point2LL& p) { double angle = std::atan2(p.X, p.Y) / std::numbers::pi * 180.0; if (angle < 0.0) angle += 360.0; - return static_cast(std::lrint(angle)); + return angle; } // Identity function, used to be able to make templated algorithms where the input is sometimes points, sometimes things that contain or can be converted to points. diff --git a/include/utils/PolygonsPointIndex.h b/include/utils/PolygonsPointIndex.h index 1b973f94da..deb722dd06 100644 --- a/include/utils/PolygonsPointIndex.h +++ b/include/utils/PolygonsPointIndex.h @@ -24,8 +24,8 @@ class PathsPointIndex * The polygons into which this index is indexing. */ const Paths* polygons_; // (pointer to const polygons) - unsigned int poly_idx_; //!< The index of the polygon in \ref PolygonsPointIndex::polygons - unsigned int point_idx_; //!< The index of the point in the polygon in \ref PolygonsPointIndex::polygons + size_t poly_idx_; //!< The index of the polygon in \ref PolygonsPointIndex::polygons + size_t point_idx_; //!< The index of the point in the polygon in \ref PolygonsPointIndex::polygons /*! * Constructs an empty point index to no polygon. @@ -157,7 +157,7 @@ struct PolygonsPointIndexSegmentLocator { ConstPolygonRef poly = (*val.polygons_)[val.poly_idx_]; Point2LL start = poly[val.point_idx_]; - unsigned int next_point_idx = (val.point_idx_ + 1) % poly.size(); + size_t next_point_idx = (val.point_idx_ + 1ul) % poly.size(); Point2LL end = poly[next_point_idx]; return std::pair(start, end); } diff --git a/include/utils/linearAlg2D.h b/include/utils/linearAlg2D.h index 42b57a16d9..5c7867e4d6 100644 --- a/include/utils/linearAlg2D.h +++ b/include/utils/linearAlg2D.h @@ -393,7 +393,7 @@ class LinearAlg2D * \param c end of second line segment * \return positive if acute, negative if obtuse, zero if 90 degree corner */ - static inline int isAcuteCorner(const Point2LL& a, const Point2LL& b, const Point2LL& c) + static inline coord_t isAcuteCorner(const Point2LL& a, const Point2LL& b, const Point2LL& c) { const Point2LL ba = a - b; const Point2LL bc = c - b; diff --git a/include/utils/polygon.h b/include/utils/polygon.h index 0cfc9af876..b1ffb4c5c1 100644 --- a/include/utils/polygon.h +++ b/include/utils/polygon.h @@ -550,13 +550,13 @@ class PolygonRef : public ConstPolygonRef void remove(size_t index) { - POLY_ASSERT(index < size() && index <= static_cast(std::numeric_limits::max())); - path->erase(path->begin() + index); + POLY_ASSERT(index < size() && index <= static_cast(std::numeric_limits::max())); + path->erase(path->begin() + static_cast(index)); } void insert(size_t index, Point2LL p) { - POLY_ASSERT(index < size() && index <= static_cast(std::numeric_limits::max())); + POLY_ASSERT(index < size() && index <= static_cast(std::numeric_limits::max())); path->insert(path->begin() + static_cast(index), p); } @@ -1099,7 +1099,7 @@ class Polygons return ret; } - Polygons offset(int distance, ClipperLib::JoinType joinType = ClipperLib::jtMiter, double miter_limit = 1.2) const; + Polygons offset(coord_t distance, ClipperLib::JoinType joinType = ClipperLib::jtMiter, double miter_limit = 1.2) const; Polygons offsetPolyLine(int distance, ClipperLib::JoinType joinType = ClipperLib::jtMiter, bool inputPolyIsClosed = false) const { diff --git a/src/ConicalOverhang.cpp b/src/ConicalOverhang.cpp index f0afc15af9..9918d8a782 100644 --- a/src/ConicalOverhang.cpp +++ b/src/ConicalOverhang.cpp @@ -19,12 +19,12 @@ void ConicalOverhang::apply(Slicer* slicer, const Mesh& mesh) const double maxHoleArea = mesh.settings_.get("conical_overhang_hole_size"); const double tan_angle = tan(angle); // the XY-component of the angle const coord_t layer_thickness = mesh.settings_.get("layer_height"); - coord_t max_dist_from_lower_layer = tan_angle * layer_thickness; // max dist which can be bridged + coord_t max_dist_from_lower_layer = std::llround(tan_angle * static_cast(layer_thickness)); // max dist which can be bridged for (LayerIndex layer_nr = slicer->layers.size() - 2; static_cast(layer_nr) >= 0; layer_nr--) { - SlicerLayer& layer = slicer->layers[layer_nr]; - SlicerLayer& layer_above = slicer->layers[layer_nr + 1]; + SlicerLayer& layer = slicer->layers[static_cast(layer_nr)]; + SlicerLayer& layer_above = slicer->layers[static_cast(layer_nr) + 1ul]; if (std::abs(max_dist_from_lower_layer) < 5) { // magically nothing happens when max_dist_from_lower_layer == 0 // below magic code solves that diff --git a/src/FffGcodeWriter.cpp b/src/FffGcodeWriter.cpp index 4d54b3bb23..76cc79db48 100644 --- a/src/FffGcodeWriter.cpp +++ b/src/FffGcodeWriter.cpp @@ -2770,7 +2770,7 @@ void FffGcodeWriter::processTopBottom( Polygons supported_skin_part_regions; - const int angle = bridgeAngle(mesh.settings, skin_part.skin_fill, storage, layer_nr, bridge_layer, support_layer, supported_skin_part_regions); + const double angle = bridgeAngle(mesh.settings, skin_part.skin_fill, storage, layer_nr, bridge_layer, support_layer, supported_skin_part_regions); if (angle > -1 || (support_threshold > 0 && (supported_skin_part_regions.area() / (skin_part.skin_fill.area() + 1) < support_threshold))) { diff --git a/src/FffPolygonGenerator.cpp b/src/FffPolygonGenerator.cpp index 0f731b9bae..16503d2839 100644 --- a/src/FffPolygonGenerator.cpp +++ b/src/FffPolygonGenerator.cpp @@ -1128,10 +1128,7 @@ void FffPolygonGenerator::processFuzzyWalls(SliceMeshStorage& mesh) continue; } - auto& result = result_lines.emplace_back(); - result.inset_idx_ = line.inset_idx_; - result.is_odd_ = line.is_odd_; - result.is_closed_ = line.is_closed_; + auto& result = result_lines.emplace_back(line.inset_idx_, line.is_odd_, line.is_closed_); // generate points in between p0 and p1 int64_t dist_left_over diff --git a/src/InterlockingGenerator.cpp b/src/InterlockingGenerator.cpp index 6ac2efb7d1..ea1849d96f 100644 --- a/src/InterlockingGenerator.cpp +++ b/src/InterlockingGenerator.cpp @@ -109,9 +109,9 @@ void InterlockingGenerator::handleThinAreas(const std::unordered_set for (const auto& cell : has_all_meshes) { const Point3LL bottom_corner = vu_.toLowerCorner(cell); - for (int layer_nr = bottom_corner.z_; layer_nr < bottom_corner.z_ + cell_size_.z_ && layer_nr < near_interlock_per_layer.size(); ++layer_nr) + for (coord_t layer_nr = bottom_corner.z_; layer_nr < bottom_corner.z_ + cell_size_.z_ && layer_nr < static_cast(near_interlock_per_layer.size()); ++layer_nr) { - near_interlock_per_layer[layer_nr].add(vu_.toPolygon(cell)); + near_interlock_per_layer[static_cast(layer_nr)].add(vu_.toPolygon(cell)); } } for (auto& near_interlock : near_interlock_per_layer) @@ -207,7 +207,7 @@ void InterlockingGenerator::addBoundaryCells(const std::vector& layers for (size_t layer_nr = 0; layer_nr < layers.size(); layer_nr++) { - const coord_t z = layer_nr; + const coord_t z = static_cast(layer_nr); vu_.walkDilatedPolygons(layers[layer_nr], z, kernel, voxel_emplacer); Polygons skin = layers[layer_nr]; if (layer_nr > 0) @@ -226,14 +226,14 @@ std::vector InterlockingGenerator::computeUnionedVolumeRegions() const for (LayerIndex layer_nr = 0; layer_nr < max_layer_count; layer_nr++) { - Polygons& layer_region = layer_regions[layer_nr]; + Polygons& layer_region = layer_regions[static_cast(layer_nr)]; for (Slicer* mesh : { &mesh_a_, &mesh_b_ }) { if (layer_nr >= mesh->layers.size()) { break; } - const SlicerLayer& layer = mesh->layers[layer_nr]; + const SlicerLayer& layer = mesh->layers[static_cast(layer_nr)]; layer_region.add(layer.polygons); } layer_region = layer_region.offset(ignored_gap_).offset(-ignored_gap_); // Morphological close to merge meshes into single volume @@ -250,7 +250,7 @@ std::vector> InterlockingGenerator::generateMicrostructure const coord_t beam_w_sum = beam_width_a_ + beam_width_b_; const coord_t middle = cell_size_.x_ * beam_width_a_ / beam_w_sum; const coord_t width[2] = { middle, cell_size_.x_ - middle }; - for (size_t mesh_idx : { 0, 1 }) + for (size_t mesh_idx : { 0ul, 1ul }) { Point2LL offset(mesh_idx ? middle : 0, 0); Point2LL area_size(width[mesh_idx], cell_size_.y_); @@ -287,7 +287,7 @@ void InterlockingGenerator::applyMicrostructureToOutlines(const std::unordered_s // Every `beam_layer_count` number of layers are combined to an interlocking beam layer // to store these we need ceil(max_layer_count / beam_layer_count) of these layers // the formula is rewritten as (max_layer_count + beam_layer_count - 1) / beam_layer_count, so it works for integer division - size_t num_interlocking_layers = (max_layer_count + beam_layer_count_ - 1) / beam_layer_count_; + size_t num_interlocking_layers = (max_layer_count + static_cast(beam_layer_count_) - 1ul) / static_cast(beam_layer_count_); structure_per_layer[0].resize(num_interlocking_layers); structure_per_layer[1].resize(num_interlocking_layers); @@ -299,9 +299,9 @@ void InterlockingGenerator::applyMicrostructureToOutlines(const std::unordered_s { for (LayerIndex layer_nr = bottom_corner.z_; layer_nr < bottom_corner.z_ + cell_size_.z_ && layer_nr < max_layer_count; layer_nr += beam_layer_count_) { - Polygons areas_here = cell_area_per_mesh_per_layer[(layer_nr / beam_layer_count_) % cell_area_per_mesh_per_layer.size()][mesh_idx]; + Polygons areas_here = cell_area_per_mesh_per_layer[static_cast(layer_nr / beam_layer_count_) % cell_area_per_mesh_per_layer.size()][mesh_idx]; areas_here.translate(Point2LL(bottom_corner.x_, bottom_corner.y_)); - structure_per_layer[mesh_idx][layer_nr / beam_layer_count_].add(areas_here); + structure_per_layer[mesh_idx][static_cast(layer_nr / beam_layer_count_)].add(areas_here); } } } @@ -329,8 +329,8 @@ void InterlockingGenerator::applyMicrostructureToOutlines(const std::unordered_s Polygons layer_outlines = layer_regions[layer_nr]; layer_outlines.applyMatrix(unapply_rotation); - const Polygons areas_here = structure_per_layer[mesh_idx][layer_nr / beam_layer_count_].intersection(layer_outlines); - const Polygons& areas_other = structure_per_layer[! mesh_idx][layer_nr / beam_layer_count_]; + const Polygons areas_here = structure_per_layer[mesh_idx][layer_nr / static_cast(beam_layer_count_)].intersection(layer_outlines); + const Polygons& areas_other = structure_per_layer[! mesh_idx][layer_nr / static_cast(beam_layer_count_)]; SlicerLayer& layer = mesh->layers[layer_nr]; layer.polygons = layer.polygons diff --git a/src/bridge.cpp b/src/bridge.cpp index c5d4c25fa9..91616a1d87 100644 --- a/src/bridge.cpp +++ b/src/bridge.cpp @@ -11,7 +11,7 @@ namespace cura { -int bridgeAngle( +double bridgeAngle( const Settings& settings, const Polygons& skin_outline, const SliceDataStorage& storage, @@ -39,7 +39,8 @@ int bridgeAngle( { const coord_t infill_line_distance = mesh.settings.get("infill_line_distance"); const coord_t infill_line_width = mesh.settings.get("infill_line_width"); - const bool part_has_sparse_infill = (infill_line_distance == 0) || ((double)infill_line_width / infill_line_distance) <= sparse_infill_max_density; + double density = static_cast(infill_line_width) / static_cast(infill_line_distance); + const bool part_has_sparse_infill = (infill_line_distance == 0) || density <= sparse_infill_max_density; for (const SliceLayerPart& prev_layer_part : mesh.layers[layer_nr - bridge_layer].parts) { @@ -117,7 +118,7 @@ int bridgeAngle( // It needs to be shrunk slightly so that the vertices of the skin polygon that would otherwise fall exactly on // the air boundary do appear to be supported - const int bb_max_dim = std::max(boundary_box.max_.X - boundary_box.min_.X, boundary_box.max_.Y - boundary_box.min_.Y); + const coord_t bb_max_dim = std::max(boundary_box.max_.X - boundary_box.min_.X, boundary_box.max_.Y - boundary_box.min_.Y); const Polygons air_below(bb_poly.offset(bb_max_dim).difference(prev_layer_outline).offset(-10)); Polygons skin_perimeter_lines; @@ -134,7 +135,7 @@ int bridgeAngle( if (skin_perimeter_lines_over_air.size()) { // one or more edges of the skin region are unsupported, determine the longest - double max_dist2 = 0; + coord_t max_dist2 = 0; double line_angle = -1; for (PolygonRef air_line : skin_perimeter_lines_over_air) { @@ -142,7 +143,7 @@ int bridgeAngle( for (unsigned i = 1; i < air_line.size(); ++i) { const Point2LL& p1(air_line[i]); - double dist2 = vSize2(p0 - p1); + coord_t dist2 = vSize2(p0 - p1); if (dist2 > max_dist2) { max_dist2 = dist2; @@ -158,20 +159,20 @@ int bridgeAngle( { // as the proportion of the skin region that is supported is >= supportThreshold, it's not // considered to be a bridge and the original bridge detection code below is skipped - return -1; + return -1.0; } if (islands.size() > 5 || islands.size() < 1) { - return -1; + return -1.0; } // Next find the 2 largest islands that we rest on. double area1 = 0; double area2 = 0; - int idx1 = -1; - int idx2 = -1; - for (unsigned int n = 0; n < islands.size(); n++) + std::optional idx1; + std::optional idx2; + for (size_t n = 0; n < islands.size(); n++) { // Skip internal holes if (! islands[n].orientation()) @@ -194,11 +195,11 @@ int bridgeAngle( } } - if (idx1 < 0 || idx2 < 0) - return -1; + if (! idx1 || ! idx2) + return -1.0; - Point2LL center1 = islands[idx1].centerOfMass(); - Point2LL center2 = islands[idx2].centerOfMass(); + Point2LL center1 = islands[*idx1].centerOfMass(); + Point2LL center2 = islands[*idx2].centerOfMass(); return angle(center2 - center1); } diff --git a/src/utils/ExtrusionLine.cpp b/src/utils/ExtrusionLine.cpp index b16a247f63..7d0ef20561 100644 --- a/src/utils/ExtrusionLine.cpp +++ b/src/utils/ExtrusionLine.cpp @@ -11,12 +11,12 @@ namespace cura { -ExtrusionLine::ExtrusionLine(const size_t inset_idx, const bool is_odd) +/*ExtrusionLine::ExtrusionLine(const size_t inset_idx, const bool is_odd) : inset_idx_(inset_idx) , is_odd_(is_odd) , is_closed_(false) { -} +}*/ coord_t ExtrusionLine::getLength() const { diff --git a/src/utils/polygon.cpp b/src/utils/polygon.cpp index 2c6b254bc7..c7554f08bd 100644 --- a/src/utils/polygon.cpp +++ b/src/utils/polygon.cpp @@ -359,7 +359,7 @@ coord_t Polygons::polyLineLength() const return length; } -Polygons Polygons::offset(int distance, ClipperLib::JoinType join_type, double miter_limit) const +Polygons Polygons::offset(coord_t distance, ClipperLib::JoinType join_type, double miter_limit) const { if (distance == 0) { From fda3e1bb8e712fc83a8e2f17d96881ad6d4a42c9 Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Wed, 22 Nov 2023 15:39:51 +0100 Subject: [PATCH 36/48] Fixed unit tests build --- include/PathOrderOptimizer.h | 12 +- include/utils/Simplify.h | 35 ++-- tests/ExtruderPlanTest.cpp | 49 +++-- tests/GCodeExportTest.cpp | 128 ++++++------ tests/PathOrderOptimizerTest.cpp | 12 +- tests/arcus/ArcusCommunicationPrivateTest.cpp | 28 +-- tests/arcus/MockCommunication.h | 34 ++-- tests/integration/SlicePhaseTest.cpp | 4 +- tests/settings/SettingsTest.cpp | 22 ++- tests/utils/LinearAlg2DTest.cpp | 184 ++++++++++-------- tests/utils/PolygonUtilsTest.cpp | 150 ++++++++------ tests/utils/SimplifyTest.cpp | 35 ++-- tests/utils/SparseGridTest.cpp | 133 +++++++++---- 13 files changed, 479 insertions(+), 347 deletions(-) diff --git a/include/PathOrderOptimizer.h b/include/PathOrderOptimizer.h index a65d3bba87..9bd8288a95 100644 --- a/include/PathOrderOptimizer.h +++ b/include/PathOrderOptimizer.h @@ -80,12 +80,12 @@ class PathOrderOptimizer * The location where the nozzle is assumed to start from before printing * these parts. */ - const Point2LL start_point_; + Point2LL start_point_; /*! * Seam settings. */ - const ZSeamConfig seam_config_; + ZSeamConfig seam_config_; static const std::unordered_multimap no_order_requirements_; @@ -104,7 +104,7 @@ class PathOrderOptimizer * \param combing_boundary Boundary to avoid when making travel moves. */ PathOrderOptimizer( - const Point2LL start_point, + const Point2LL& start_point, const ZSeamConfig seam_config = ZSeamConfig(), const bool detect_loops = false, const Polygons* combing_boundary = nullptr, @@ -268,7 +268,7 @@ class PathOrderOptimizer * polygons. This then allows the optimizer to decide on a seam location * that is not one of the endpoints of the polyline. */ - const bool detect_loops_; + bool detect_loops_; /*! * Whether to reverse the ordering completely. @@ -276,7 +276,7 @@ class PathOrderOptimizer * This reverses the order in which parts are printed, and inverts the * direction of each path as well. */ - const bool reverse_direction_; + bool reverse_direction_; /* * Whether to print all outer walls in a group, one after another. @@ -284,7 +284,7 @@ class PathOrderOptimizer * If this is enabled outer walls will be printed first and then all other * walls will be printed. If reversed they will be printed last. */ - const bool _group_outer_walls; + bool _group_outer_walls; /*! * Order requirements on the paths. diff --git a/include/utils/Simplify.h b/include/utils/Simplify.h index 91c0eeca61..3ca5b0009d 100644 --- a/include/utils/Simplify.h +++ b/include/utils/Simplify.h @@ -40,6 +40,23 @@ namespace cura class Simplify { public: + /*! + * Line segments shorter than this size should be considered for removal. + */ + coord_t max_resolution_; + + /*! + * If removing a vertex causes a deviation further than this, it may not be + * removed. + */ + coord_t max_deviation_; + + /*! + * If removing a vertex causes the covered area of the line segments to + * change by more than this, it may not be removed. + */ + coord_t max_area_deviation_; + /*! * Construct a simplifier, storing the simplification parameters in the * instance (as a factory pattern). @@ -471,24 +488,6 @@ class Simplify * \return The area deviation that would be caused by removing the vertex. */ coord_t getAreaDeviation(const ExtrusionJunction& before, const ExtrusionJunction& vertex, const ExtrusionJunction& after) const; - -private: - /*! - * Line segments shorter than this size should be considered for removal. - */ - coord_t max_resolution_; - - /*! - * If removing a vertex causes a deviation further than this, it may not be - * removed. - */ - coord_t max_deviation_; - - /*! - * If removing a vertex causes the covered area of the line segments to - * change by more than this, it may not be removed. - */ - coord_t max_area_deviation_; }; } // namespace cura diff --git a/tests/ExtruderPlanTest.cpp b/tests/ExtruderPlanTest.cpp index 2aa6f6e59d..ed15fc4a9f 100644 --- a/tests/ExtruderPlanTest.cpp +++ b/tests/ExtruderPlanTest.cpp @@ -1,11 +1,12 @@ // Copyright (c) 2023 UltiMaker // CuraEngine is released under the terms of the AGPLv3 or higher -#include "LayerPlan.h" //Code under test. -#include "pathPlanning/SpeedDerivatives.h" +#include //For calculating averages. #include -#include //For calculating averages. + +#include "LayerPlan.h" //Code under test. +#include "pathPlanning/SpeedDerivatives.h" // NOLINTBEGIN(*-magic-numbers) namespace cura @@ -71,8 +72,16 @@ class ExtruderPlanTestPathCollection GCodePathConfig travel_config; ExtruderPlanTestPathCollection() - : extrusion_config(GCodePathConfig{ .type = PrintFeatureType::OuterWall, .line_width = 400, .layer_thickness = 100, .flow = 1.0_r, .speed_derivatives = SpeedDerivatives { .speed = 50.0, .acceleration = 1000.0, .jerk = 10.0 } }) - , travel_config(GCodePathConfig{ .type = PrintFeatureType::MoveCombing, .line_width = 0, .layer_thickness = 100, .flow = 0.0_r, .speed_derivatives = SpeedDerivatives { .speed = 120.0, .acceleration = 5000.0, .jerk = 30.0 } }) + : extrusion_config(GCodePathConfig{ .type = PrintFeatureType::OuterWall, + .line_width = 400, + .layer_thickness = 100, + .flow = 1.0_r, + .speed_derivatives = SpeedDerivatives{ .speed = 50.0, .acceleration = 1000.0, .jerk = 10.0 } }) + , travel_config(GCodePathConfig{ .type = PrintFeatureType::MoveCombing, + .line_width = 0, + .layer_thickness = 100, + .flow = 0.0_r, + .speed_derivatives = SpeedDerivatives{ .speed = 120.0, .acceleration = 5000.0, .jerk = 30.0 } }) { std::shared_ptr mesh = nullptr; constexpr Ratio flow_1 = 1.0_r; @@ -363,10 +372,10 @@ class ExtruderPlanTest : public testing::Test */ TEST_P(ExtruderPlanPathsParameterizedTest, BackPressureCompensationZeroIsUncompensated) { - extruder_plan.paths = GetParam(); + extruder_plan.paths_ = GetParam(); std::vector original_widths; std::vector original_speeds; - for (const GCodePath& path : extruder_plan.paths) + for (const GCodePath& path : extruder_plan.paths_) { original_widths.push_back(path.width_factor); original_speeds.push_back(path.speed_factor); @@ -374,11 +383,11 @@ TEST_P(ExtruderPlanPathsParameterizedTest, BackPressureCompensationZeroIsUncompe extruder_plan.applyBackPressureCompensation(0.0_r); - ASSERT_EQ(extruder_plan.paths.size(), original_widths.size()) << "Number of paths may not have changed."; - for (size_t i = 0; i < extruder_plan.paths.size(); ++i) + ASSERT_EQ(extruder_plan.paths_.size(), original_widths.size()) << "Number of paths may not have changed."; + for (size_t i = 0; i < extruder_plan.paths_.size(); ++i) { - EXPECT_NEAR(original_widths[i], extruder_plan.paths[i].width_factor, error_margin) << "The width did not change. Back pressure compensation doesn't adjust line width."; - EXPECT_NEAR(original_speeds[i], extruder_plan.paths[i].speed_factor, error_margin) << "The speed factor did not change, since the compensation factor was 0."; + EXPECT_NEAR(original_widths[i], extruder_plan.paths_[i].width_factor, error_margin) << "The width did not change. Back pressure compensation doesn't adjust line width."; + EXPECT_NEAR(original_speeds[i], extruder_plan.paths_[i].speed_factor, error_margin) << "The speed factor did not change, since the compensation factor was 0."; } } @@ -388,24 +397,24 @@ TEST_P(ExtruderPlanPathsParameterizedTest, BackPressureCompensationZeroIsUncompe */ TEST_P(ExtruderPlanPathsParameterizedTest, BackPressureCompensationFull) { - extruder_plan.paths = GetParam(); + extruder_plan.paths_ = GetParam(); extruder_plan.applyBackPressureCompensation(1.0_r); auto first_extrusion = std::find_if( - extruder_plan.paths.begin(), - extruder_plan.paths.end(), + extruder_plan.paths_.begin(), + extruder_plan.paths_.end(), [&](GCodePath& path) { return shouldCountPath(path); }); - if (first_extrusion == extruder_plan.paths.end()) // Only travel moves in this plan. + if (first_extrusion == extruder_plan.paths_.end()) // Only travel moves in this plan. { return; } // All flow rates must be equal to this one. const double first_flow_mm3_per_sec = calculatePathWidth(*first_extrusion); - for (GCodePath& path : extruder_plan.paths) + for (GCodePath& path : extruder_plan.paths_) { if (! shouldCountPath(path)) { @@ -422,11 +431,11 @@ TEST_P(ExtruderPlanPathsParameterizedTest, BackPressureCompensationFull) */ TEST_P(ExtruderPlanPathsParameterizedTest, BackPressureCompensationHalf) { - extruder_plan.paths = GetParam(); + extruder_plan.paths_ = GetParam(); // Calculate what the flow rates were originally. std::vector original_flows; - for (GCodePath& path : extruder_plan.paths) + for (GCodePath& path : extruder_plan.paths_) { if (! shouldCountPath(path)) { @@ -441,7 +450,7 @@ TEST_P(ExtruderPlanPathsParameterizedTest, BackPressureCompensationHalf) // Calculate the new flow rates. std::vector new_flows; - for (GCodePath& path : extruder_plan.paths) + for (GCodePath& path : extruder_plan.paths_) { if (! shouldCountPath(path)) { @@ -471,7 +480,7 @@ TEST_F(ExtruderPlanTest, BackPressureCompensationEmptyPlan) // The extruder plan starts off empty. So immediately try applying back-pressure compensation. extruder_plan.applyBackPressureCompensation(0.5_r); - EXPECT_TRUE(extruder_plan.paths.empty()) << "The paths in the extruder plan should remain empty. Also it shouldn't crash."; + EXPECT_TRUE(extruder_plan.paths_.empty()) << "The paths in the extruder plan should remain empty. Also it shouldn't crash."; } } // namespace cura // NOLINTEND(*-magic-numbers) diff --git a/tests/GCodeExportTest.cpp b/tests/GCodeExportTest.cpp index e43ba1fee9..b8ae6bb7ca 100644 --- a/tests/GCodeExportTest.cpp +++ b/tests/GCodeExportTest.cpp @@ -241,7 +241,7 @@ class GriffinHeaderTest : public testing::TestWithParam TEST_P(GriffinHeaderTest, HeaderGriffinFormat) { const size_t num_extruders = GetParam(); - gcode.flavor = EGCodeFlavor::GRIFFIN; + gcode.flavor_ = EGCodeFlavor::GRIFFIN; for (size_t extruder_index = 0; extruder_index < num_extruders; extruder_index++) { Application::getInstance().current_slice_->scene.extruders.emplace_back(extruder_index, nullptr); @@ -270,7 +270,7 @@ TEST_P(GriffinHeaderTest, HeaderGriffinFormat) EXPECT_EQ(Date::getDate().toStringDashed(), token.substr(22)); std::getline(result, token, '\n'); EXPECT_EQ(std::string(";TARGET_MACHINE.NAME:"), token.substr(0, 21)); - EXPECT_EQ(gcode.machine_name, token.substr(21)); + EXPECT_EQ(gcode.machine_name_, token.substr(21)); for (size_t extruder_nr = 0; extruder_nr < num_extruders; extruder_nr++) { @@ -317,7 +317,7 @@ INSTANTIATE_TEST_SUITE_P(GriffinHeaderTestInstantiation, GriffinHeaderTest, test */ TEST_F(GCodeExportTest, HeaderUltiGCode) { - gcode.flavor = EGCodeFlavor::ULTIGCODE; + gcode.flavor_ = EGCodeFlavor::ULTIGCODE; constexpr size_t num_extruders = 2; const std::vector extruder_is_used(num_extruders, true); constexpr Duration print_time = 1337; @@ -328,7 +328,7 @@ TEST_F(GCodeExportTest, HeaderUltiGCode) ExtruderTrain& train = Application::getInstance().current_slice_->scene.extruders.back(); train.settings_.add("machine_nozzle_size", "0.4"); } - gcode.total_bounding_box = AABB3D(Point3LL(0, 0, 0), Point3LL(1000, 1000, 1000)); + gcode.total_bounding_box_ = AABB3D(Point3LL(0, 0, 0), Point3LL(1000, 1000, 1000)); std::string result = gcode.getFileHeader(extruder_is_used, &print_time, filament_used); @@ -341,14 +341,14 @@ TEST_F(GCodeExportTest, HeaderUltiGCode) TEST_F(GCodeExportTest, HeaderRepRap) { Application::getInstance().current_slice_->scene.current_mesh_group->settings.add("layer_height", "0.123"); - gcode.flavor = EGCodeFlavor::REPRAP; - gcode.extruder_attr[0].filament_area = 5.0; - gcode.extruder_attr[1].filament_area = 4.0; + gcode.flavor_ = EGCodeFlavor::REPRAP; + gcode.extruder_attr_[0].filament_area_ = 5.0; + gcode.extruder_attr_[1].filament_area_ = 4.0; constexpr size_t num_extruders = 2; const std::vector extruder_is_used(num_extruders, true); constexpr Duration print_time = 1337; const std::vector filament_used = { 100, 200 }; - gcode.total_bounding_box = AABB3D(Point3LL(0, 0, 0), Point3LL(1000, 1000, 1000)); + gcode.total_bounding_box_ = AABB3D(Point3LL(0, 0, 0), Point3LL(1000, 1000, 1000)); std::string result = gcode.getFileHeader(extruder_is_used, &print_time, filament_used); @@ -361,14 +361,14 @@ TEST_F(GCodeExportTest, HeaderRepRap) TEST_F(GCodeExportTest, HeaderMarlin) { Application::getInstance().current_slice_->scene.current_mesh_group->settings.add("layer_height", "0.123"); - gcode.flavor = EGCodeFlavor::MARLIN; - gcode.extruder_attr[0].filament_area = 5.0; - gcode.extruder_attr[1].filament_area = 4.0; + gcode.flavor_ = EGCodeFlavor::MARLIN; + gcode.extruder_attr_[0].filament_area_ = 5.0; + gcode.extruder_attr_[1].filament_area_ = 4.0; constexpr size_t num_extruders = 2; const std::vector extruder_is_used(num_extruders, true); constexpr Duration print_time = 1337; const std::vector filament_used = { 100, 200 }; - gcode.total_bounding_box = AABB3D(Point3LL(0, 0, 0), Point3LL(1000, 1000, 1000)); + gcode.total_bounding_box_ = AABB3D(Point3LL(0, 0, 0), Point3LL(1000, 1000, 1000)); std::string result = gcode.getFileHeader(extruder_is_used, &print_time, filament_used); @@ -381,12 +381,12 @@ TEST_F(GCodeExportTest, HeaderMarlin) TEST_F(GCodeExportTest, HeaderMarlinVolumetric) { Application::getInstance().current_slice_->scene.current_mesh_group->settings.add("layer_height", "0.123"); - gcode.flavor = EGCodeFlavor::MARLIN_VOLUMATRIC; + gcode.flavor_ = EGCodeFlavor::MARLIN_VOLUMATRIC; constexpr size_t num_extruders = 2; const std::vector extruder_is_used(num_extruders, true); constexpr Duration print_time = 1337; const std::vector filament_used = { 100, 200 }; - gcode.total_bounding_box = AABB3D(Point3LL(0, 0, 0), Point3LL(1000, 1000, 1000)); + gcode.total_bounding_box_ = AABB3D(Point3LL(0, 0, 0), Point3LL(1000, 1000, 1000)); std::string result = gcode.getFileHeader(extruder_is_used, &print_time, filament_used); @@ -403,8 +403,8 @@ TEST_F(GCodeExportTest, HeaderMarlinVolumetric) TEST_F(GCodeExportTest, EVsMmVolumetric) { constexpr double filament_area = 10.0; - gcode.extruder_attr[0].filament_area = filament_area; - gcode.is_volumetric = true; + gcode.extruder_attr_[0].filament_area_ = filament_area; + gcode.is_volumetric_ = true; constexpr double mm3_input = 15.0; EXPECT_EQ(gcode.mm3ToE(mm3_input), mm3_input) << "Since the E is volumetric and the input mm3 is also volumetric, the output needs to be the same."; @@ -428,8 +428,8 @@ TEST_F(GCodeExportTest, EVsMmVolumetric) TEST_F(GCodeExportTest, EVsMmLinear) { constexpr double filament_area = 10.0; - gcode.extruder_attr[0].filament_area = filament_area; - gcode.is_volumetric = false; + gcode.extruder_attr_[0].filament_area_ = filament_area; + gcode.is_volumetric_ = false; EXPECT_EQ(gcode.mmToE(15.0), 15.0) << "Since the E is linear and the input mm is also linear, the output needs to be the same."; EXPECT_EQ(gcode.eToMm(15.0), 15.0) << "Since the E is linear and the output mm is also linear, the output needs to be the same."; @@ -460,22 +460,22 @@ TEST_F(GCodeExportTest, SwitchExtruderSimple) scene.extruders.emplace_back(0, nullptr); ExtruderTrain& train1 = scene.extruders.back(); - train1.settings.add("machine_extruder_start_code", ";FIRST EXTRUDER START G-CODE!"); - train1.settings.add("machine_extruder_end_code", ";FIRST EXTRUDER END G-CODE!"); - train1.settings.add("machine_extruder_start_code_duration", "0.0"); - train1.settings.add("machine_extruder_end_code_duration", "0.0"); - train1.settings.add("machine_firmware_retract", "True"); - train1.settings.add("retraction_enable", "True"); + train1.settings_.add("machine_extruder_start_code", ";FIRST EXTRUDER START G-CODE!"); + train1.settings_.add("machine_extruder_end_code", ";FIRST EXTRUDER END G-CODE!"); + train1.settings_.add("machine_extruder_start_code_duration", "0.0"); + train1.settings_.add("machine_extruder_end_code_duration", "0.0"); + train1.settings_.add("machine_firmware_retract", "True"); + train1.settings_.add("retraction_enable", "True"); scene.extruders.emplace_back(1, nullptr); ExtruderTrain& train2 = scene.extruders.back(); - train2.settings.add("machine_extruder_start_code", ";SECOND EXTRUDER START G-CODE!"); - train2.settings.add("machine_extruder_end_code", ";SECOND EXTRUDER END G-CODE!"); - train2.settings.add("machine_extruder_start_code_duration", "0.0"); - train2.settings.add("machine_extruder_end_code_duration", "0.0"); - train2.settings.add("machine_firmware_retract", "True"); - train2.settings.add("retraction_enable", "True"); + train2.settings_.add("machine_extruder_start_code", ";SECOND EXTRUDER START G-CODE!"); + train2.settings_.add("machine_extruder_end_code", ";SECOND EXTRUDER END G-CODE!"); + train2.settings_.add("machine_extruder_start_code_duration", "0.0"); + train2.settings_.add("machine_extruder_end_code_duration", "0.0"); + train2.settings_.add("machine_firmware_retract", "True"); + train2.settings_.add("retraction_enable", "True"); RetractionConfig no_retraction; no_retraction.distance = 0; @@ -496,8 +496,8 @@ TEST_F(GCodeExportTest, WriteZHopStartZero) TEST_F(GCodeExportTest, WriteZHopStartDefaultSpeed) { Application::getInstance().current_slice_->scene.extruders.emplace_back(0, nullptr); - Application::getInstance().current_slice_->scene.extruders[gcode.current_extruder].settings_.add("speed_z_hop", "1"); // 60mm/min. - gcode.current_layer_z = 2000; + Application::getInstance().current_slice_->scene.extruders[gcode.current_extruder_].settings_.add("speed_z_hop", "1"); // 60mm/min. + gcode.current_layer_z_ = 2000; constexpr coord_t hop_height = 3000; gcode.writeZhopStart(hop_height); EXPECT_EQ(std::string("G1 F60 Z5\n"), output.str()); @@ -506,8 +506,8 @@ TEST_F(GCodeExportTest, WriteZHopStartDefaultSpeed) TEST_F(GCodeExportTest, WriteZHopStartCustomSpeed) { Application::getInstance().current_slice_->scene.extruders.emplace_back(0, nullptr); - Application::getInstance().current_slice_->scene.extruders[gcode.current_extruder].settings_.add("speed_z_hop", "1"); // 60mm/min. - gcode.current_layer_z = 2000; + Application::getInstance().current_slice_->scene.extruders[gcode.current_extruder_].settings_.add("speed_z_hop", "1"); // 60mm/min. + gcode.current_layer_z_ = 2000; constexpr coord_t hop_height = 3000; constexpr Velocity speed{ 4.0 }; // 240 mm/min. gcode.writeZhopStart(hop_height, speed); @@ -516,7 +516,7 @@ TEST_F(GCodeExportTest, WriteZHopStartCustomSpeed) TEST_F(GCodeExportTest, WriteZHopEndZero) { - gcode.is_z_hopped = 0; + gcode.is_z_hopped_ = 0; gcode.writeZhopEnd(); EXPECT_EQ(std::string(""), output.str()) << "Zero length z hop shouldn't affect gcode output."; } @@ -524,9 +524,9 @@ TEST_F(GCodeExportTest, WriteZHopEndZero) TEST_F(GCodeExportTest, WriteZHopEndDefaultSpeed) { Application::getInstance().current_slice_->scene.extruders.emplace_back(0, nullptr); - Application::getInstance().current_slice_->scene.extruders[gcode.current_extruder].settings_.add("speed_z_hop", "1"); // 60mm/min. - gcode.current_layer_z = 2000; - gcode.is_z_hopped = 3000; + Application::getInstance().current_slice_->scene.extruders[gcode.current_extruder_].settings_.add("speed_z_hop", "1"); // 60mm/min. + gcode.current_layer_z_ = 2000; + gcode.is_z_hopped_ = 3000; gcode.writeZhopEnd(); EXPECT_EQ(std::string("G1 F60 Z2\n"), output.str()); } @@ -534,9 +534,9 @@ TEST_F(GCodeExportTest, WriteZHopEndDefaultSpeed) TEST_F(GCodeExportTest, WriteZHopEndCustomSpeed) { Application::getInstance().current_slice_->scene.extruders.emplace_back(0, nullptr); - Application::getInstance().current_slice_->scene.extruders[gcode.current_extruder].settings_.add("speed_z_hop", "1"); - gcode.current_layer_z = 2000; - gcode.is_z_hopped = 3000; + Application::getInstance().current_slice_->scene.extruders[gcode.current_extruder_].settings_.add("speed_z_hop", "1"); + gcode.current_layer_z_ = 2000; + gcode.is_z_hopped_ = 3000; constexpr Velocity speed{ 4.0 }; // 240 mm/min. gcode.writeZhopEnd(speed); EXPECT_EQ(std::string("G1 F240 Z2\n"), output.str()) << "Custom provided speed should be used."; @@ -544,9 +544,9 @@ TEST_F(GCodeExportTest, WriteZHopEndCustomSpeed) TEST_F(GCodeExportTest, insertWipeScriptSingleMove) { - gcode.currentPosition = Point3LL(1000, 1000, 1000); - gcode.current_layer_z = 1000; - gcode.use_extruder_offset_to_offset_coords = false; + gcode.current_position_ = Point3LL(1000, 1000, 1000); + gcode.current_layer_z_ = 1000; + gcode.use_extruder_offset_to_offset_coords_ = false; Application::getInstance().current_slice_->scene.current_mesh_group->settings.add("layer_height", "0.2"); WipeScriptConfig config; @@ -576,9 +576,9 @@ TEST_F(GCodeExportTest, insertWipeScriptSingleMove) TEST_F(GCodeExportTest, insertWipeScriptMultipleMoves) { - gcode.currentPosition = Point3LL(1000, 1000, 1000); - gcode.current_layer_z = 1000; - gcode.use_extruder_offset_to_offset_coords = false; + gcode.current_position_ = Point3LL(1000, 1000, 1000); + gcode.current_layer_z_ = 1000; + gcode.use_extruder_offset_to_offset_coords_ = false; Application::getInstance().current_slice_->scene.current_mesh_group->settings.add("layer_height", "0.2"); WipeScriptConfig config; @@ -614,9 +614,9 @@ TEST_F(GCodeExportTest, insertWipeScriptMultipleMoves) TEST_F(GCodeExportTest, insertWipeScriptOptionalDelay) { - gcode.currentPosition = Point3LL(1000, 1000, 1000); - gcode.current_layer_z = 1000; - gcode.use_extruder_offset_to_offset_coords = false; + gcode.current_position_ = Point3LL(1000, 1000, 1000); + gcode.current_layer_z_ = 1000; + gcode.use_extruder_offset_to_offset_coords_ = false; Application::getInstance().current_slice_->scene.current_mesh_group->settings.add("layer_height", "0.2"); WipeScriptConfig config; @@ -645,15 +645,15 @@ TEST_F(GCodeExportTest, insertWipeScriptOptionalDelay) TEST_F(GCodeExportTest, insertWipeScriptRetractionEnable) { - gcode.currentPosition = Point3LL(1000, 1000, 1000); - gcode.current_layer_z = 1000; - gcode.current_e_value = 100; - gcode.use_extruder_offset_to_offset_coords = false; - gcode.is_volumetric = false; - gcode.current_extruder = 0; - gcode.extruder_attr[0].filament_area = 10.0; - gcode.relative_extrusion = false; - gcode.currentSpeed = 1.0; + gcode.current_position_ = Point3LL(1000, 1000, 1000); + gcode.current_layer_z_ = 1000; + gcode.current_e_value_ = 100; + gcode.use_extruder_offset_to_offset_coords_ = false; + gcode.is_volumetric_ = false; + gcode.current_extruder_ = 0; + gcode.extruder_attr_[0].filament_area_ = 10.0; + gcode.relative_extrusion_ = false; + gcode.current_speed_ = 1.0; Application::getInstance().current_slice_->scene.current_mesh_group->settings.add("layer_height", "0.2"); Application::getInstance().current_slice_->scene.extruders.emplace_back(0, &Application::getInstance().current_slice_->scene.current_mesh_group->settings); Application::getInstance().current_slice_->scene.extruders.back().settings_.add("machine_firmware_retract", "false"); @@ -663,7 +663,7 @@ TEST_F(GCodeExportTest, insertWipeScriptRetractionEnable) config.retraction_config.distance = 1; config.retraction_config.speed = 2.0; // 120 mm/min. config.retraction_config.primeSpeed = 3.0; // 180 mm/min. - config.retraction_config.prime_volume = gcode.extruder_attr[0].filament_area * 4; // 4mm in linear dimensions + config.retraction_config.prime_volume = gcode.extruder_attr_[0].filament_area_ * 4; // 4mm in linear dimensions config.retraction_config.retraction_count_max = 100; // Practically no limit. config.retraction_config.retraction_extrusion_window = 1; config.retraction_config.retraction_min_travel_distance = 0; // Don't limit retractions for being too short. @@ -693,10 +693,10 @@ TEST_F(GCodeExportTest, insertWipeScriptRetractionEnable) TEST_F(GCodeExportTest, insertWipeScriptHopEnable) { - gcode.currentPosition = Point3LL(1000, 1000, 1000); - gcode.current_layer_z = 1000; - gcode.use_extruder_offset_to_offset_coords = false; - gcode.currentSpeed = 1.0; + gcode.current_position_ = Point3LL(1000, 1000, 1000); + gcode.current_layer_z_ = 1000; + gcode.use_extruder_offset_to_offset_coords_ = false; + gcode.current_speed_ = 1.0; Application::getInstance().current_slice_->scene.current_mesh_group->settings.add("layer_height", "0.2"); WipeScriptConfig config; diff --git a/tests/PathOrderOptimizerTest.cpp b/tests/PathOrderOptimizerTest.cpp index 3b895e1360..b4d4a32ee1 100644 --- a/tests/PathOrderOptimizerTest.cpp +++ b/tests/PathOrderOptimizerTest.cpp @@ -2,6 +2,7 @@ // CuraEngine is released under the terms of the AGPLv3 or higher. #include "PathOrderOptimizer.h" //The code under test. + #include //To run the tests. // NOLINTBEGIN(*-magic-numbers) @@ -21,7 +22,8 @@ class PathOrderOptimizerTest : public testing::Test */ Polygon triangle; - PathOrderOptimizerTest() : optimizer(Point2LL(0, 0)) + PathOrderOptimizerTest() + : optimizer(Point2LL(0, 0)) { } @@ -43,7 +45,7 @@ class PathOrderOptimizerTest : public testing::Test TEST_F(PathOrderOptimizerTest, OptimizeWhileEmpty) { optimizer.optimize(); // Don't crash. - EXPECT_EQ(optimizer.paths.size(), 0) << "Still empty!"; + EXPECT_EQ(optimizer.paths_.size(), 0) << "Still empty!"; } /*! @@ -66,9 +68,9 @@ TEST_F(PathOrderOptimizerTest, ThreeTrianglesShortestOrder) optimizer.optimize(); - EXPECT_EQ(optimizer.paths[0].vertices->front(), Point2LL(100, 100)) << "Nearest triangle first."; - EXPECT_EQ(optimizer.paths[1].vertices->front(), Point2LL(500, 500)) << "Middle triangle second."; - EXPECT_EQ(optimizer.paths[2].vertices->front(), Point2LL(1000, 1000)) << "Far triangle last."; + EXPECT_EQ(optimizer.paths_[0].vertices_->front(), Point2LL(100, 100)) << "Nearest triangle first."; + EXPECT_EQ(optimizer.paths_[1].vertices_->front(), Point2LL(500, 500)) << "Middle triangle second."; + EXPECT_EQ(optimizer.paths_[2].vertices_->front(), Point2LL(1000, 1000)) << "Far triangle last."; } } // namespace cura diff --git a/tests/arcus/ArcusCommunicationPrivateTest.cpp b/tests/arcus/ArcusCommunicationPrivateTest.cpp index 29d33d94c0..12652958ca 100644 --- a/tests/arcus/ArcusCommunicationPrivateTest.cpp +++ b/tests/arcus/ArcusCommunicationPrivateTest.cpp @@ -2,17 +2,20 @@ // CuraEngine is released under the terms of the AGPLv3 or higher. #include "communication/ArcusCommunicationPrivate.h" //The class we're testing. -#include "Application.h" -#include "ExtruderTrain.h" -#include "MockSocket.h" -#include "Slice.h" -#include "utils/Coord_t.h" + #include #include #include #include + #include +#include "Application.h" +#include "ExtruderTrain.h" +#include "MockSocket.h" +#include "Slice.h" +#include "utils/Coord_t.h" + // NOLINTBEGIN(*-magic-numbers) namespace cura { @@ -193,7 +196,8 @@ TEST_F(ArcusCommunicationPrivateTest, ReadMeshGroupMessage) // - - Add settings to the mesh: std::map mesh_settings = { - { "extruder_nr", "0" }, { "center_object", "1" }, { "mesh_position_x", "0" }, { "mesh_position_y", "0" }, { "mesh_position_z", "0" }, { "infill_mesh", "0" }, { "cutting_mesh", "0" }, { "anti_overhang_mesh", "0" }, + { "extruder_nr", "0" }, { "center_object", "1" }, { "mesh_position_x", "0" }, { "mesh_position_y", "0" }, + { "mesh_position_z", "0" }, { "infill_mesh", "0" }, { "cutting_mesh", "0" }, { "anti_overhang_mesh", "0" }, }; for (std::pair key_value : mesh_settings) { @@ -234,12 +238,12 @@ TEST_F(ArcusCommunicationPrivateTest, ReadMeshGroupMessage) std::array max_coords = { std::numeric_limits::min(), std::numeric_limits::min(), std::numeric_limits::min() }; for (const auto& vertex : vertices) { - min_coords[0] = std::min(vertex.p_.x, min_coords[0]); - min_coords[1] = std::min(vertex.p_.y, min_coords[1]); - min_coords[2] = std::min(vertex.p_.z, min_coords[2]); - max_coords[0] = std::max(vertex.p_.x, max_coords[0]); - max_coords[1] = std::max(vertex.p_.y, max_coords[1]); - max_coords[2] = std::max(vertex.p_.z, max_coords[2]); + min_coords[0] = std::min(vertex.p_.x_, min_coords[0]); + min_coords[1] = std::min(vertex.p_.y_, min_coords[1]); + min_coords[2] = std::min(vertex.p_.z_, min_coords[2]); + max_coords[0] = std::max(vertex.p_.x_, max_coords[0]); + max_coords[1] = std::max(vertex.p_.y_, max_coords[1]); + max_coords[2] = std::max(vertex.p_.z_, max_coords[2]); } // - Then, just compare: diff --git a/tests/arcus/MockCommunication.h b/tests/arcus/MockCommunication.h index 1db835ffb7..f2401025fd 100644 --- a/tests/arcus/MockCommunication.h +++ b/tests/arcus/MockCommunication.h @@ -4,11 +4,12 @@ #ifndef MOCKCOMMUNICATION_H #define MOCKCOMMUNICATION_H +#include + #include "communication/Communication.h" //The interface we're implementing. +#include "settings/types/LayerIndex.h" #include "utils/Coord_t.h" #include "utils/polygon.h" //In the signature of Communication. -#include -#include "settings/types/LayerIndex.h" namespace cura { @@ -21,27 +22,14 @@ class MockCommunication : public Communication public: MOCK_CONST_METHOD0(hasSlice, bool()); MOCK_CONST_METHOD0(isSequential, bool()); - MOCK_CONST_METHOD1(sendProgress, void(const float& progress)); + MOCK_CONST_METHOD1(sendProgress, void(double progress)); MOCK_METHOD3(sendLayerComplete, void(const LayerIndex::value_type& layer_nr, const coord_t& z, const coord_t& thickness)); - MOCK_METHOD5(sendPolygons, - void(const PrintFeatureType& type, - const Polygons& polygons, - const coord_t& line_width, - const coord_t& line_thickness, - const Velocity& velocity)); - MOCK_METHOD5(sendPolygon, - void(const PrintFeatureType& type, - const ConstPolygonRef& polygon, - const coord_t& line_width, - const coord_t& line_thickness, - const Velocity& velocity)); - MOCK_METHOD5(sendLineTo, - void(const PrintFeatureType& type, - const Point& to, - const coord_t& line_width, - const coord_t& line_thickness, - const Velocity& velocity)); - MOCK_METHOD1(sendCurrentPosition, void(const Point& position)); + MOCK_METHOD5(sendPolygons, void(const PrintFeatureType& type, const Polygons& polygons, const coord_t& line_width, const coord_t& line_thickness, const Velocity& velocity)); + MOCK_METHOD5( + sendPolygon, + void(const PrintFeatureType& type, const ConstPolygonRef& polygon, const coord_t& line_width, const coord_t& line_thickness, const Velocity& velocity)); + MOCK_METHOD5(sendLineTo, void(const PrintFeatureType& type, const Point2LL& to, const coord_t& line_width, const coord_t& line_thickness, const Velocity& velocity)); + MOCK_METHOD1(sendCurrentPosition, void(const Point2LL& position)); MOCK_METHOD1(setExtruderForSend, void(const ExtruderTrain& extruder)); MOCK_METHOD1(setLayerForSend, void(const LayerIndex::value_type& layer_nr)); MOCK_METHOD0(sendOptimizedLayerData, void()); @@ -56,4 +44,4 @@ class MockCommunication : public Communication } // namespace cura -#endif // MOCKCOMMUNICATION_H \ No newline at end of file +#endif // MOCKCOMMUNICATION_H diff --git a/tests/integration/SlicePhaseTest.cpp b/tests/integration/SlicePhaseTest.cpp index 291c2acd15..95fd638fa1 100644 --- a/tests/integration/SlicePhaseTest.cpp +++ b/tests/integration/SlicePhaseTest.cpp @@ -79,7 +79,7 @@ TEST_F(SlicePhaseTest, Cube) const auto initial_layer_thickness = scene.settings.get("layer_height_0"); constexpr bool variable_layer_height = false; constexpr std::vector* variable_layer_height_values = nullptr; - const size_t num_layers = (cube_mesh.getAABB().max_.z - initial_layer_thickness) / layer_thickness + 1; + const size_t num_layers = (cube_mesh.getAABB().max_.z_ - initial_layer_thickness) / layer_thickness + 1; Slicer slicer(&cube_mesh, layer_thickness, num_layers, variable_layer_height, variable_layer_height_values); ASSERT_EQ(slicer.layers.size(), num_layers) << "The number of layers in the output must equal the requested number of layers."; @@ -140,7 +140,7 @@ TEST_F(SlicePhaseTest, Cylinder1000) const auto initial_layer_thickness = scene.settings.get("layer_height_0"); constexpr bool variable_layer_height = false; constexpr std::vector* variable_layer_height_values = nullptr; - const size_t num_layers = (cylinder_mesh.getAABB().max_.z - initial_layer_thickness) / layer_thickness + 1; + const size_t num_layers = (cylinder_mesh.getAABB().max_.z_ - initial_layer_thickness) / layer_thickness + 1; Slicer slicer(&cylinder_mesh, layer_thickness, num_layers, variable_layer_height, variable_layer_height_values); ASSERT_EQ(slicer.layers.size(), num_layers) << "The number of layers in the output must equal the requested number of layers."; diff --git a/tests/settings/SettingsTest.cpp b/tests/settings/SettingsTest.cpp index 8486ce2292..c8f7814db8 100644 --- a/tests/settings/SettingsTest.cpp +++ b/tests/settings/SettingsTest.cpp @@ -3,6 +3,11 @@ #include "settings/Settings.h" //The class under test. +#include //For std::numbers::pi. +#include //For shared_ptr. + +#include + #include "Application.h" //To test extruder train settings. #include "ExtruderTrain.h" #include "Slice.h" @@ -17,10 +22,6 @@ #include "utils/Coord_t.h" #include "utils/Matrix4x3D.h" //Testing matrix transformation settings. -#include //For std::numbers::pi. -#include -#include //For shared_ptr. - // NOLINTBEGIN(*-magic-numbers) namespace cura { @@ -124,7 +125,8 @@ TEST_F(SettingsTest, AddSettingAngleRadians) EXPECT_DOUBLE_EQ(AngleRadians(std::numbers::pi), settings.get("test_setting")) << "180 degrees is 1 pi radians."; settings.add("test_setting", "810"); - EXPECT_NEAR(AngleRadians(std::numbers::pi / 2.0), settings.get("test_setting"), 0.00000001) << "810 degrees in clock arithmetic is 90 degrees, which is 0.5 pi radians."; + EXPECT_NEAR(AngleRadians(std::numbers::pi / 2.0), settings.get("test_setting"), 0.00000001) + << "810 degrees in clock arithmetic is 90 degrees, which is 0.5 pi radians."; } TEST_F(SettingsTest, AddSettingAngleDegrees) @@ -142,7 +144,7 @@ TEST_F(SettingsTest, AddSettingTemperature) TEST_F(SettingsTest, AddSettingVelocity) { settings.add("test_setting", "12.345"); - EXPECT_DOUBLE_EQ(Velocity { 12.345 }, settings.get("test_setting")); + EXPECT_DOUBLE_EQ(Velocity{ 12.345 }, settings.get("test_setting")); settings.add("test_setting", "-78"); EXPECT_DOUBLE_EQ(Velocity{ -78.0 }, settings.get("test_setting")); @@ -151,16 +153,16 @@ TEST_F(SettingsTest, AddSettingVelocity) TEST_F(SettingsTest, AddSettingRatio) { settings.add("test_setting", "1.618"); - EXPECT_DOUBLE_EQ(Ratio { 0.01618 }, settings.get("test_setting")) << "With ratios, the input is interpreted in percentages."; + EXPECT_DOUBLE_EQ(Ratio{ 0.01618 }, settings.get("test_setting")) << "With ratios, the input is interpreted in percentages."; } TEST_F(SettingsTest, AddSettingDuration) { settings.add("test_setting", "1234.5678"); - EXPECT_DOUBLE_EQ(Duration { 1234.5678 }, settings.get("test_setting")); + EXPECT_DOUBLE_EQ(Duration{ 1234.5678 }, settings.get("test_setting")); settings.add("test_setting", "-1234.5678"); - EXPECT_DOUBLE_EQ(Duration { 0 }, settings.get("test_setting")) << "Negative duration doesn't exist, so it gets rounded to 0."; + EXPECT_DOUBLE_EQ(Duration{ 0 }, settings.get("test_setting")) << "Negative duration doesn't exist, so it gets rounded to 0."; } TEST_F(SettingsTest, AddSettingFlowTempGraph) @@ -244,7 +246,7 @@ TEST_F(SettingsTest, LimitToExtruder) // Add a setting to the extruder this is limiting to. const std::string limit_extruder_value = "I was gonna tell a time travelling joke but you didn't like it."; - current_slice->scene.extruders[2].settings.add("test_setting", limit_extruder_value); + current_slice->scene.extruders[2].settings_.add("test_setting", limit_extruder_value); current_slice->scene.limit_to_extruder.emplace("test_setting", ¤t_slice->scene.extruders[2]); // Add a decoy setting to the main scene to make sure that we aren't getting the global setting instead. diff --git a/tests/utils/LinearAlg2DTest.cpp b/tests/utils/LinearAlg2DTest.cpp index 4593c4c57c..b9e4f41bb0 100644 --- a/tests/utils/LinearAlg2DTest.cpp +++ b/tests/utils/LinearAlg2DTest.cpp @@ -2,7 +2,9 @@ // CuraEngine is released under the terms of the AGPLv3 or higher. #include "utils/linearAlg2D.h" + #include + #include // NOLINTBEGIN(*-magic-numbers) @@ -61,43 +63,47 @@ TEST_P(GetDist2FromLineSegmentTest, GetDist2FromLineSegment) const coord_t supposed_distance = LinearAlg2D::getDist2FromLineSegment(line_start, point, line_end, &supposed_is_beyond); // FIXME: Clean-up message with ftm when CURA-8258 is implemented or when we use C++20 - ASSERT_LE(std::fabs(sqrt(double(supposed_distance)) - sqrt(double(actual_distance2))), maximum_error) << "Line [" << line_start.X << ", " << line_start.Y << "] -- [" << line_end.X << ", " << line_end.Y << "], point [" << point.X << ", " - << point.Y << "], squared distance was " << supposed_distance << " rather than " << actual_distance2 << "."; - ASSERT_EQ(supposed_is_beyond, actual_is_beyond) << "Line [" << line_start.X << ", " << line_start.Y << "] -- [" << line_end.X << ", " << line_end.Y << "], point [" << point.X << ", " << point.Y << "], check whether it is beyond was " - << static_cast(supposed_is_beyond) << " rather than " << static_cast(actual_is_beyond) << "."; + ASSERT_LE(std::fabs(sqrt(double(supposed_distance)) - sqrt(double(actual_distance2))), maximum_error) + << "Line [" << line_start.X << ", " << line_start.Y << "] -- [" << line_end.X << ", " << line_end.Y << "], point [" << point.X << ", " << point.Y + << "], squared distance was " << supposed_distance << " rather than " << actual_distance2 << "."; + ASSERT_EQ(supposed_is_beyond, actual_is_beyond) << "Line [" << line_start.X << ", " << line_start.Y << "] -- [" << line_end.X << ", " << line_end.Y << "], point [" << point.X + << ", " << point.Y << "], check whether it is beyond was " << static_cast(supposed_is_beyond) << " rather than " + << static_cast(actual_is_beyond) << "."; } -INSTANTIATE_TEST_CASE_P(GetDist2FromLineSegmentInstantiation, - GetDist2FromLineSegmentTest, - testing::Values(GetDist2FromLineSegmentParameters(Point2LL(0, 0), Point2LL(100, 0), Point2LL(25, 3), 9, 0), // Nearby a horizontal line. - GetDist2FromLineSegmentParametersPoint2LLt(0, 0)Point2LLnt(100, 0)Point2LLnt(25, 0), 0, 0), // On a horizontal line. - Point2LLst2FromLineSegmentParameters(Point(0, 0Point2LLint(100, 0Point2LLint(200, 0), 10000, 1), // Beyond a horizontal line. - GetDist2FromLineSegmentParametersPoint2LLt(0, PointPoint2LLnt(100, PointPoint2LLnt(-100, 0), 10000, -1)Point2LLBefore a horizontal line. - GetDist2FromLineSegmentParametersPoint2LLt(0Point2LPoint2LLnt(100Point2LPoint2LLnt(-1, -1), 2, -1Point2LL In a corner near a horizontal line. - GetDist2FromLineSegmentParameters(Point(Point2LL, Point(Point2LL0), Point(0, 3), 9, Point2LL/ Perpendicular to a horizontal line. - GetDist2FromLineSegmentParameters(PointPoint2LL), PointPoint2LL00), Point(5, 25), 25Point2LL // Nearby a vertical line. - GetDist2FromLineSegmentParameters(Point2LL(0, 0), Point2LL(0, 100), Point(0, 25), Point2LL, // On a vertical line. - GetDist2FromLineSegmentParametersPoint2LLt(0, 0)Point2LLnt(0, 100), Point(0, 200)Point2LL00Point2LL // Beyond a vertical line. - Point2LLst2FromLineSegmentParameters(Point2LL(0, 0Point2Point2LL(0, 100), Point(0, -100)Point2LL00, Point2LL// Before a vertical line. - GetDist2FromLineSegmentParameters(Point2LL(0, Point2LPoint2LL(0, 100), Point(-1, -1Point2LL -1)Point2LLIn a corner near a vertical line. - GetDist2FromLineSegmentParameters(Point(0Point2LL Point(0, 100), Point(3Point2LL 9, 0Point2LL Perpendicular to a vertical line. - GetDist2FromLineSegmentParameters(Point(Point2LL, Point(100, 100), Point(Point2LL0), 50, Point2LL/ Nearby a diagonal line. - GetDist2FromLineSegmentParameters(PointPoint2LL), Point(100, 100), PointPoint2LL25), 0Point2LL // On a diagonal line. - GetDist2FromLineSegmentParameters(Point2LL(0, 0), Point(100, 100), Point2LL(200Point2LL), Point2LL, 1Point2LL Beyond a diagonal line. - GetDist2FromLineSegmentParametersPoint2LLt(Point2LL, Point(100, 100), Point(Point2LPoint2LL0), Point2LL, Point2LL// Before a diagonal line. - Point2LLst2FromLineSegmentParameters(Point2LL(0, 0), Point(100, 100), Point2LLPoint2LL0)PointPoint2LL), // In a corner near a diagonal line. - Point2LLst2FromLineSegmentParameters(Point(0, 0), Point(100, 100Point2LLint(3, -Point2LL, 0)Point2LLPerpendicular to a diagonal line. - GetDist2FromLineSegmentParameters(Point(0, 0), Point(100Point2LL, Point(20Point2LL, 320, 0Point2LL Nearby a diagonal line. - GetDist2FromLineSegmentParameters(Point(0, 0), Point(Point2LL50), Point(Point2LL0), 0, Point2LL/ On a diagonal line. - GetDist2FromLineSegmentParameters(Point(0, 0), PointPoint2LL 50), PointPoint2LL), 0Point2LL // On one of the vertices of the diagonal line. - GetDist2FromLineSegmentParameters(Point(0, 0), Point2LL(100Point2LL, Point2LL(200Point2LL), Point2LL, 1Point2LL Beyond a diagonal line. - GetDist2FromLineSegmentParameters(Point(0, 0), Point(Point2LLPoint2LLPoint(Point2LPoint2LL), Point2LL, Point2LL// Before a diagonal line. - GetDist2FromLineSegmentParameters(Point(0, 0), Point2LLPoint2LL 50), Point2LLPoint2LL0)PointPoint2LL), // In a corner near a diagonal line. - GetDist2FromLineSegmentParameters(Point(0, 0Point2LLint(100, 50Point2LLint(-2, Point2LL0, 0), // Perpendicular to a diagonal line. - GetDist2FromLineSegmentParameters(Point(0Point2LL Point(10000Point2LL0), Point(2000Point2LL0), 3200000, 0), // Longer distances. - GetDist2FromLineSegmentParameters(Point(Point2LL, Point(Point2LL, Point(Point2LL), 400, 0), // Near a line of length 0. - GetDist2FromLineSegmentParameters(Point(0, 0), Point(0, 0), Point(0, 0), 0, 0) // On a line of length 0. - )); +INSTANTIATE_TEST_CASE_P( + GetDist2FromLineSegmentInstantiation, + GetDist2FromLineSegmentTest, + testing::Values( + GetDist2FromLineSegmentParameters(Point2LL(0, 0), Point2LL(100, 0), Point2LL(25, 3), 9, 0), // Nearby a horizontal line. + GetDist2FromLineSegmentParameters(Point2LL(0, 0), Point2LL(100, 0), Point2LL(25, 0), 0, 0), // On a horizontal line. + GetDist2FromLineSegmentParameters(Point2LL(0, 0), Point2LL(100, 0), Point2LL(200, 0), 10000, 1), // Beyond a horizontal line. + GetDist2FromLineSegmentParameters(Point2LL(0, 0), Point2LL(100, 0), Point2LL(-100, 0), 10000, -1), // Before a horizontal line. + GetDist2FromLineSegmentParameters(Point2LL(0, 0), Point2LL(100, 0), Point2LL(-1, -1), 2, -1), // In a corner near a horizontal line. + GetDist2FromLineSegmentParameters(Point2LL(0, 0), Point2LL(100, 0), Point2LL(0, 3), 9, 0), // Perpendicular to a horizontal line. + GetDist2FromLineSegmentParameters(Point2LL(0, 0), Point2LL(0, 100), Point2LL(5, 25), 25, 0), // Nearby a vertical line. + GetDist2FromLineSegmentParameters(Point2LL(0, 0), Point2LL(0, 100), Point2LL(0, 25), 0, 0), // On a vertical line. + GetDist2FromLineSegmentParameters(Point2LL(0, 0), Point2LL(0, 100), Point2LL(0, 200), 10000, 1), // Beyond a vertical line. + GetDist2FromLineSegmentParameters(Point2LL(0, 0), Point2LL(0, 100), Point2LL(0, -100), 10000, -1), // Before a vertical line. + GetDist2FromLineSegmentParameters(Point2LL(0, 0), Point2LL(0, 100), Point2LL(-1, -1), 2, -1), // In a corner near a vertical line. + GetDist2FromLineSegmentParameters(Point2LL(0, 0), Point2LL(0, 100), Point2LL(3, 0), 9, 0), // Perpendicular to a vertical line. + GetDist2FromLineSegmentParameters(Point2LL(0, 0), Point2LL(100, 100), Point2LL(30, 20), 50, 0), // Nearby a diagonal line. + GetDist2FromLineSegmentParameters(Point2LL(0, 0), Point2LL(100, 100), Point2LL(25, 25), 0, 0), // On a diagonal line. + GetDist2FromLineSegmentParameters(Point2LL(0, 0), Point2LL(100, 100), Point2LL(200, 200), 20000, 1), // Beyond a diagonal line. + GetDist2FromLineSegmentParameters(Point2LL(0, 0), Point2LL(100, 100), Point2LL(-100, -100), 20000, -1), // Before a diagonal line. + GetDist2FromLineSegmentParameters(Point2LL(0, 0), Point2LL(100, 100), Point2LL(-3, 0), 9, -1), // In a corner near a diagonal line. + GetDist2FromLineSegmentParameters(Point2LL(0, 0), Point2LL(100, 100), Point2LL(3, -3), 9, 0), // Perpendicular to a diagonal line. + GetDist2FromLineSegmentParameters(Point2LL(0, 0), Point2LL(100, 50), Point2LL(20, 30), 320, 0), // Nearby a diagonal line. + GetDist2FromLineSegmentParameters(Point2LL(0, 0), Point2LL(100, 50), Point2LL(40, 20), 0, 0), // On a diagonal line. + GetDist2FromLineSegmentParameters(Point2LL(0, 0), Point2LL(100, 50), Point2LL(0, 0), 0, 0), // On one of the vertices of the diagonal line. + GetDist2FromLineSegmentParameters(Point2LL(0, 0), Point2LL(100, 50), Point2LL(200, 100), 12500, 1), // Beyond a diagonal line. + GetDist2FromLineSegmentParameters(Point2LL(0, 0), Point2LL(100, 50), Point2LL(-100, -50), 12500, -1), // Before a diagonal line. + GetDist2FromLineSegmentParameters(Point2LL(0, 0), Point2LL(100, 50), Point2LL(-3, 0), 9, -1), // In a corner near a diagonal line. + GetDist2FromLineSegmentParameters(Point2LL(0, 0), Point2LL(100, 50), Point2LL(-2, 4), 20, 0), // Perpendicular to a diagonal line. + GetDist2FromLineSegmentParameters(Point2LL(0, 0), Point2LL(10000, 5000), Point2LL(2000, 3000), 3200000, 0), // Longer distances. + GetDist2FromLineSegmentParameters(Point2LL(0, 0), Point2LL(0, 0), Point2LL(20, 0), 400, 0), // Near a line of length 0. + GetDist2FromLineSegmentParameters(Point2LL(0, 0), Point2LL(0, 0), Point2LL(0, 0), 0, 0) // On a line of length 0. + )); // NOLINTBEGIN(misc-non-private-member-variables-in-classes) struct GetAngleParameters @@ -107,7 +113,11 @@ struct GetAngleParameters Point2LL c; double angle; // In degrees. - GetAngleParameters(Point2LL a, Point2LL b, Point2LL c, double angle) : a(a), b(b), c(c), angle(angle) + GetAngleParameters(Point2LL a, Point2LL b, Point2LL c, double angle) + : a(a) + , b(b) + , c(c) + , angle(angle) { } }; @@ -135,20 +145,23 @@ TEST_P(GetAngleTest, GetAngle) const double angle = angle_degrees * std::numbers::pi / 180.0; const double supposed_angle = LinearAlg2D::getAngleLeft(a, b, c); - ASSERT_LE(std::fabs(angle - supposed_angle), maximum_error) << "Corner in " << a << " - " << b << " - " << c << " was computed to have an angle of " << supposed_angle << " instead of " << angle << "."; + ASSERT_LE(std::fabs(angle - supposed_angle), maximum_error) + << "Corner in " << a << " - " << b << " - " << c << " was computed to have an angle of " << supposed_angle << " instead of " << angle << "."; } -INSTANTIATE_TEST_CASE_P(GetAngleInstantiation, - GetAngleTest, - testing::Values(GetAngleParameters(Point2LL(-100, 0)Point2LLnt2LL(0, 0), Point2LL(100, Point2LL80), // Almost straight line. - GetAngleParametersPoint2LLt(-100, 0Point2LLt2LLnt(0, 0)Point2LLnt(100Point2LL 180), // Completely straight line. - Point2LLgleParameters(Point(-100, Point2LLt2LLint(0, 0Point2LLint(-100Point2LL0), 315), //-45 degrees. - GetAngleParameters(Point(-100Point2LLnt2LLoint(0, Point2LLoint(Point2LL00), 270)Point2LL90 degrees. - GetAngleParameters(Point(-Point2LLint2LL Point(0Point2LL Point2LL(0, 100), 90Point2LL Straight angle. - GetAngleParameters(Point(Point2LLt2LL0), Point(Point2LL, Point2LL(-100, 1), Point2LL/ Almost straight back. - GetAngleParameters(PointPoint2LLt2LL 0), PointPoint2LL), Point2LL(-100, -1)Point2LL), // Almost straight back but the other way around. - GetAngleParameters(Point2LLPoint2LL, 0), Point2LL(0, 0), Point(-100, 0), 0) // Completely straight back. - )); +INSTANTIATE_TEST_CASE_P( + GetAngleInstantiation, + GetAngleTest, + testing::Values( + GetAngleParameters(Point2LL(-100, 0), Point2LL(0, 0), Point2LL(100, 1), 180), // Almost straight line. + GetAngleParameters(Point2LL(-100, 0), Point2LL(0, 0), Point2LL(100, 0), 180), // Completely straight line. + GetAngleParameters(Point2LL(-100, 0), Point2LL(0, 0), Point2LL(-100, -100), 315), //-45 degrees. + GetAngleParameters(Point2LL(-100, 0), Point2LL(0, 0), Point2LL(0, -100), 270), //-90 degrees. + GetAngleParameters(Point2LL(-100, 0), Point2LL(0, 0), Point2LL(0, 100), 90), // Straight angle. + GetAngleParameters(Point2LL(-100, 0), Point2LL(0, 0), Point2LL(-100, 1), 0), // Almost straight back. + GetAngleParameters(Point2LL(-100, 0), Point2LL(0, 0), Point2LL(-100, -1), 360), // Almost straight back but the other way around. + GetAngleParameters(Point2LL(-100, 0), Point2LL(0, 0), Point2LL(-100, 0), 0) // Completely straight back. + )); TEST(GetAngleTest, GetAngleLeftAABTest) { @@ -175,8 +188,9 @@ TEST(PointIsLeftOfLineTest, LeftOfLine) const coord_t supposed = LinearAlg2D::pointIsLeftOfLine(p, a, b); // FIXME: Clean-up message with ftm when CURA-8258 is implemented or when we use C++20 - ASSERT_TRUE(actual * supposed > 0 || (actual == 0 && supposed == 0)) << "Point " << p << " was computed as lying " << ((supposed == 0) ? "on" : ((supposed < 0) ? "left" : "right")) << " the line from " << a << " to " << b - << ", instead of " << ((actual == 0) ? "on" : ((actual < 0) ? "left" : "right")); + ASSERT_TRUE(actual * supposed > 0 || (actual == 0 && supposed == 0)) + << "Point " << p << " was computed as lying " << ((supposed == 0) ? "on" : ((supposed < 0) ? "left" : "right")) << " the line from " << a << " to " << b << ", instead of " + << ((actual == 0) ? "on" : ((actual < 0) ? "left" : "right")); } TEST(PointIsLeftOfLineTest, Sharp) @@ -188,8 +202,9 @@ TEST(PointIsLeftOfLineTest, Sharp) const coord_t supposed = LinearAlg2D::pointIsLeftOfLine(p, a, b); // FIXME: Clean-up message with ftm when CURA-8258 is implemented or when we use C++20 - ASSERT_TRUE(actual * supposed > 0 || (actual == 0 && supposed == 0)) << "Point " << p << " was computed as lying " << ((supposed == 0) ? "on" : ((supposed < 0) ? "left" : "right")) << " the line from " << a << " to " << b - << ", instead of " << ((actual == 0) ? "on" : ((actual < 0) ? "left" : "right")); + ASSERT_TRUE(actual * supposed > 0 || (actual == 0 && supposed == 0)) + << "Point " << p << " was computed as lying " << ((supposed == 0) ? "on" : ((supposed < 0) ? "left" : "right")) << " the line from " << a << " to " << b << ", instead of " + << ((actual == 0) ? "on" : ((actual < 0) ? "left" : "right")); } // NOLINTBEGIN(misc-non-private-member-variables-in-classes) @@ -202,7 +217,13 @@ struct GetPointOnLineWithDistParameters Point2LL actual_result; bool actual_returned; - GetPointOnLineWithDistParameters(Point2LL p, Point2LL a, Point2LL b, coord_t dist, Point2LL actual_result, bool actual_returned) : p(p), a(a), b(b), dist(dist), actual_result(actual_result), actual_returned(actual_returned) + GetPointOnLineWithDistParameters(Point2LL p, Point2LL a, Point2LL b, coord_t dist, Point2LL actual_result, bool actual_returned) + : p(p) + , a(a) + , b(b) + , dist(dist) + , actual_result(actual_result) + , actual_returned(actual_returned) { } }; @@ -233,7 +254,8 @@ TEST_P(GetPointOnLineWithDistTest, GetPointOnLineWithDist) if (actual_returned) { EXPECT_TRUE(supposed_returned) << "Point " << p << " wasn't projected on (" << a << " - " << b << ") instead of projecting to " << actual_result << "."; - EXPECT_LT(vSize2(actual_result - supposed_result), 10 * 10) << "Point " << p << " was projected on (" << a << " - " << b << ") to " << supposed_result << " instead of " << actual_result << "."; + EXPECT_LT(vSize2(actual_result - supposed_result), 10 * 10) + << "Point " << p << " was projected on (" << a << " - " << b << ") to " << supposed_result << " instead of " << actual_result << "."; EXPECT_LT(std::abs(supposed_dist - dist), 10) << "Projection distance of " << p << " onto (" << a << " - " << b << ") was " << supposed_dist << " instead of " << dist << "."; // FIXME: Clean-up message with ftm when CURA-8258 is implemented or when we use C++20 } @@ -243,15 +265,17 @@ TEST_P(GetPointOnLineWithDistTest, GetPointOnLineWithDist) } } -INSTANTIATE_TEST_CASE_P(GetPointOnLineWithDistInstantiation, - GetPointOnLineWithDistTest, - testing::Values(GetPointOnLineWithDistParameters(Point2LL(110, 30), Point2LL(0, 0), Point2LL(100, 0), 50, Point2LL(70, 0), true), - GetPointOnLineWithDistParameters(Point2LL(90, 30), Point2LL(0, 0), Point2LL(100, 0), 50, Point2LL(50, 0), true), - GetPointOnLineWithDistParameters(Point2LL(10, 30), Point2LL(0, 0), Point2LL(100, 0), 50, Point2LL(50, 0), true), - GetPointOnLineWithDistParameters(Point2LL(-10, 30), Point2LL(0, 0), Point2LL(100, 0), 50, Point2LL(30, 0), true), - GetPointOnLineWithDistParameters(Point2LL(50, 30), Point2LL(0, 0), Point2LL(100, 0), 50, Point2LL(10, 0), true), - GetPointOnLineWithDistParameters(Point2LL(210, 30), Point2LL(0, 0), Point2LL(100, 0), 50, Point2LL(70, 0), false), - GetPointOnLineWithDistParameters(Point2LL(110, 130), Point2LL(0, 0), Point2LL(100, 0), 50, Point2LL(70, 0), false))); +INSTANTIATE_TEST_CASE_P( + GetPointOnLineWithDistInstantiation, + GetPointOnLineWithDistTest, + testing::Values( + GetPointOnLineWithDistParameters(Point2LL(110, 30), Point2LL(0, 0), Point2LL(100, 0), 50, Point2LL(70, 0), true), + GetPointOnLineWithDistParameters(Point2LL(90, 30), Point2LL(0, 0), Point2LL(100, 0), 50, Point2LL(50, 0), true), + GetPointOnLineWithDistParameters(Point2LL(10, 30), Point2LL(0, 0), Point2LL(100, 0), 50, Point2LL(50, 0), true), + GetPointOnLineWithDistParameters(Point2LL(-10, 30), Point2LL(0, 0), Point2LL(100, 0), 50, Point2LL(30, 0), true), + GetPointOnLineWithDistParameters(Point2LL(50, 30), Point2LL(0, 0), Point2LL(100, 0), 50, Point2LL(10, 0), true), + GetPointOnLineWithDistParameters(Point2LL(210, 30), Point2LL(0, 0), Point2LL(100, 0), 50, Point2LL(70, 0), false), + GetPointOnLineWithDistParameters(Point2LL(110, 130), Point2LL(0, 0), Point2LL(100, 0), 50, Point2LL(70, 0), false))); // NOLINTBEGIN(misc-non-private-member-variables-in-classes) struct RotateAroundParameters @@ -261,7 +285,11 @@ struct RotateAroundParameters double angle; Point2LL actual_result; - RotateAroundParameters(Point2LL point, Point2LL origin, double angle, Point2LL actual_result) : point(point), origin(origin), angle(angle), actual_result(actual_result) + RotateAroundParameters(Point2LL point, Point2LL origin, double angle, Point2LL actual_result) + : point(point) + , origin(origin) + , angle(angle) + , actual_result(actual_result) { } }; @@ -285,19 +313,23 @@ TEST_P(RotateAroundTest, RotateAround) const Point3Matrix mat = LinearAlg2D::rotateAround(origin, angle); const Point2LL supposed_result = mat.apply(point); - ASSERT_LT(vSize(supposed_result - actual_result), 2) << "LinearAlg2D::rotateAround failed: Rotating " << point << " around " << origin << " for " << angle << " degrees resulted in " << supposed_result << " instead of expected " - << actual_result << "."; + ASSERT_LT(vSize(supposed_result - actual_result), 2) << "LinearAlg2D::rotateAround failed: Rotating " << point << " around " << origin << " for " << angle + << " degrees resulted in " << supposed_result << " instead of expected " << actual_result << "."; } -INSTANTIATE_TEST_SUITE_P(RotateAroundInstantiation, - RotateAroundTest, - testing::Values(RotateAroundParameters(Point2LL(25, 30), Point2LL(10, 17), 90, Point2LL(-3, 32)), // 90 degrees rotation. - RotateAroundParameters(Point2LL(25, 30), Point2LL(10, 17), -90, Point2LL(23, 2)), //-90 degrees rotation. - RotateAroundParameters(Point2LL(-67, 14), Point2LL(50, 50), 0, Point2LL(-67, 14)), // No rotation at all. - RotateAroundParameters(Point2LL(-67, 14), Point2LL(50, 50), 12, Point2LL(-57, -9)) // 12 degrees rotation. Actually ends up at [-57, -9.5]! - )); - -class Temp {}; +INSTANTIATE_TEST_SUITE_P( + RotateAroundInstantiation, + RotateAroundTest, + testing::Values( + RotateAroundParameters(Point2LL(25, 30), Point2LL(10, 17), 90, Point2LL(-3, 32)), // 90 degrees rotation. + RotateAroundParameters(Point2LL(25, 30), Point2LL(10, 17), -90, Point2LL(23, 2)), //-90 degrees rotation. + RotateAroundParameters(Point2LL(-67, 14), Point2LL(50, 50), 0, Point2LL(-67, 14)), // No rotation at all. + RotateAroundParameters(Point2LL(-67, 14), Point2LL(50, 50), 12, Point2LL(-57, -9)) // 12 degrees rotation. Actually ends up at [-57, -9.5]! + )); + +class Temp +{ +}; TEST(Temp, LineDistTests) { @@ -306,7 +338,7 @@ TEST(Temp, LineDistTests) { const Point2LL p{ 500000 + (std::rand() % 4000) - 2000, 500000 + (std::rand() % 4000) - 2000 }; - const coord_t d = (std::rand() % 2000) - 1000 /2; + const coord_t d = (std::rand() % 2000) - 1000 / 2; const double rang = std::rand() / (static_cast(RAND_MAX) / 6.29); const Point2LL x{ p.X + static_cast(d * std::cos(rang)), p.Y - static_cast(d * std::sin(rang)) }; diff --git a/tests/utils/PolygonUtilsTest.cpp b/tests/utils/PolygonUtilsTest.cpp index 04f668cab2..f859a48c08 100644 --- a/tests/utils/PolygonUtilsTest.cpp +++ b/tests/utils/PolygonUtilsTest.cpp @@ -2,10 +2,12 @@ // CuraEngine is released under the terms of the AGPLv3 or higher. #include "utils/polygonUtils.h" // The class under test. + +#include + #include "utils/Coord_t.h" #include "utils/Point2LL.h" // Creating and testing with points. #include "utils/polygon.h" // Creating polygons to test with. -#include // NOLINTBEGIN(*-magic-numbers) namespace cura @@ -17,7 +19,10 @@ struct MoveInsideParameters coord_t distance; Point2LL supposed; - MoveInsideParameters(Point2LL close_to, const coord_t distance, Point2LL supposed) : close_to(close_to), distance(distance), supposed(supposed) + MoveInsideParameters(Point2LL close_to, const coord_t distance, Point2LL supposed) + : close_to(close_to) + , distance(distance) + , supposed(supposed) { } }; @@ -55,9 +60,11 @@ TEST_P(MoveInsideTest, MoveInside) Point2LL result = PolygonUtils::moveInside(cpp, parameters.distance); // FIXME: Clean-up message with ftm when CURA-8258 is implemented or when we use C++20 - ASSERT_LE(vSize(result - parameters.supposed), 10) << parameters.close_to << " moved with " << parameters.distance << " micron inside to " << result << " rather than " << parameters.supposed << ".\n" - << "\tPS: dist to boundary computed = " << vSize(cpp.location - result) << "; vs supposed = " << vSize(cpp.location - parameters.supposed) << ".\n" - << "\tclosest_point = " << cpp.location << " at index " << cpp.point_idx << "."; + ASSERT_LE(vSize(result - parameters.supposed), 10) << parameters.close_to << " moved with " << parameters.distance << " micron inside to " << result << " rather than " + << parameters.supposed << ".\n" + << "\tPS: dist to boundary computed = " << vSize(cpp.location_ - result) + << "; vs supposed = " << vSize(cpp.location_ - parameters.supposed) << ".\n" + << "\tclosest_point = " << cpp.location_ << " at index " << cpp.point_idx_ << "."; } TEST_P(MoveInsideTest, MoveInside2) @@ -67,21 +74,24 @@ TEST_P(MoveInsideTest, MoveInside2) polys.add(test_square); Point2LL result = parameters.close_to; PolygonUtils::moveInside2(polys, result, parameters.distance); - ASSERT_LE(vSize(result - parameters.supposed), 10) << parameters.close_to << " moved with " << parameters.distance << " micron inside to " << result << "rather than " << parameters.supposed << "."; + ASSERT_LE(vSize(result - parameters.supposed), 10) << parameters.close_to << " moved with " << parameters.distance << " micron inside to " << result << "rather than " + << parameters.supposed << "."; } -INSTANTIATE_TEST_SUITE_P(MoveInsideInstantiation, - MoveInsideTest, - testing::Values(MoveInsideParameters(Point2LL(110, 110), 28, Point2LL(80, 80)), // Near a corner, moving inside. - MoveInsideParameters(Point2LL(50, 110), 20, Point2LL(50, 80)), // Near an edge, moving inside. - MoveInsideParameters(Point2LL(110, 110), -28, Point2LL(120, 120)), // Near a corner, moving outside. - MoveInsideParameters(Point2LL(50, 110), -20, Point2LL(50, 120)), // Near an edge, moving outside. - MoveInsideParameters(Point2LL(110, 105), 28, Point2LL(80, 80)), // Near a corner but not exactly diagonal. - MoveInsideParameters(Point2LL(100, 50), 20, Point2LL(80, 50)), // Starting on the border. - MoveInsideParameters(Point2LL(80, 50), 20, Point2LL(80, 50)), // Already inside. - MoveInsideParameters(Point2LL(110, 50), 0, Point2LL(100, 50)), // Not keeping any distance from the border. - MoveInsideParameters(Point2LL(110, 50), 100000, Point2LL(-99900, 50)) // A very far move. - )); +INSTANTIATE_TEST_SUITE_P( + MoveInsideInstantiation, + MoveInsideTest, + testing::Values( + MoveInsideParameters(Point2LL(110, 110), 28, Point2LL(80, 80)), // Near a corner, moving inside. + MoveInsideParameters(Point2LL(50, 110), 20, Point2LL(50, 80)), // Near an edge, moving inside. + MoveInsideParameters(Point2LL(110, 110), -28, Point2LL(120, 120)), // Near a corner, moving outside. + MoveInsideParameters(Point2LL(50, 110), -20, Point2LL(50, 120)), // Near an edge, moving outside. + MoveInsideParameters(Point2LL(110, 105), 28, Point2LL(80, 80)), // Near a corner but not exactly diagonal. + MoveInsideParameters(Point2LL(100, 50), 20, Point2LL(80, 50)), // Starting on the border. + MoveInsideParameters(Point2LL(80, 50), 20, Point2LL(80, 50)), // Already inside. + MoveInsideParameters(Point2LL(110, 50), 0, Point2LL(100, 50)), // Not keeping any distance from the border. + MoveInsideParameters(Point2LL(110, 50), 100000, Point2LL(-99900, 50)) // A very far move. + )); TEST_F(MoveInsideTest, cornerEdgeTest) { @@ -97,8 +107,9 @@ TEST_F(MoveInsideTest, cornerEdgeTest) // FIXME: Clean-up message with ftm when CURA-8258 is implemented or when we use C++20 ASSERT_TRUE(vSize(result - supposed1) <= maximum_error || vSize(result - supposed2) <= maximum_error) << close_to << " moved with " << distance << " micron inside to " << result << " rather than " << supposed1 << " or " << supposed2 << ".\n" - << "\tPS: dist to boundary computed = " << vSize(cpp.location - result) << "; vs supposed = " << vSize(cpp.location - supposed1) << " or " << vSize(cpp.location - supposed2) << ".\n" - << "\tclosest point = " << cpp.location << " at index " << cpp.point_idx << "."; + << "\tPS: dist to boundary computed = " << vSize(cpp.location_ - result) << "; vs supposed = " << vSize(cpp.location_ - supposed1) << " or " + << vSize(cpp.location_ - supposed2) << ".\n" + << "\tclosest point = " << cpp.location_ << " at index " << cpp.point_idx_ << "."; } TEST_F(MoveInsideTest, middleTest) @@ -115,11 +126,14 @@ TEST_F(MoveInsideTest, middleTest) constexpr coord_t maximum_error = 10; // FIXME: Clean-up message with ftm when CURA-8258 is implemented or when we use C++20 - ASSERT_TRUE(vSize(result - supposed1) <= maximum_error || vSize(result - supposed2) <= maximum_error || vSize(result - supposed3) <= maximum_error || vSize(result - supposed4) <= maximum_error) - << close_to << " moved with " << distance << " micron inside to " << result << " rather than " << supposed1 << ", " << supposed2 << ", " << supposed3 << " or " << supposed4 << ".\n" - << "\tPS: dist to boundary computed = " << vSize(cpp.location - result) << "; vs supposed = " << vSize(cpp.location - supposed1) << ", " << vSize(cpp.location - supposed2) << ", " << vSize(cpp.location - supposed3) << " or " - << vSize(cpp.location - supposed4) << ".\n" - << "\tclosest point = " << cpp.location << " at index " << cpp.point_idx << "."; + ASSERT_TRUE( + vSize(result - supposed1) <= maximum_error || vSize(result - supposed2) <= maximum_error || vSize(result - supposed3) <= maximum_error + || vSize(result - supposed4) <= maximum_error) + << close_to << " moved with " << distance << " micron inside to " << result << " rather than " << supposed1 << ", " << supposed2 << ", " << supposed3 << " or " << supposed4 + << ".\n" + << "\tPS: dist to boundary computed = " << vSize(cpp.location_ - result) << "; vs supposed = " << vSize(cpp.location_ - supposed1) << ", " + << vSize(cpp.location_ - supposed2) << ", " << vSize(cpp.location_ - supposed3) << " or " << vSize(cpp.location_ - supposed4) << ".\n" + << "\tclosest point = " << cpp.location_ << " at index " << cpp.point_idx_ << "."; } TEST_F(MoveInsideTest, middleTestPenalty) @@ -128,13 +142,20 @@ TEST_F(MoveInsideTest, middleTestPenalty) const Point2LL supposed(80, 50); const Point2LL preferred_dir(120, 60); constexpr coord_t distance = 20; - const ClosestPolygonPoint cpp = PolygonUtils::findClosest(close_to, test_square, [preferred_dir](Point2LL candidate) { return vSize2(candidate - preferred_dir); }); + const ClosestPolygonPoint cpp = PolygonUtils::findClosest( + close_to, + test_square, + [preferred_dir](Point2LL candidate) + { + return vSize2(candidate - preferred_dir); + }); const Point2LL result = PolygonUtils::moveInside(cpp, distance); // FIXME: Clean-up message with ftm when CURA-8258 is implemented or when we use C++20 ASSERT_LE(vSize(result - supposed), 10) << close_to << " moved with " << distance << " micron inside to " << result << " rather than " << supposed << ".\n" - << "\tPS: dist to boundary computed = " << vSize(cpp.location - result) << "; vs supposed = " << vSize(cpp.location - supposed) << ".\n" - << "\tclosest point = " << cpp.location << " at index " << cpp.point_idx << "."; + << "\tPS: dist to boundary computed = " << vSize(cpp.location_ - result) << "; vs supposed = " << vSize(cpp.location_ - supposed) + << ".\n" + << "\tclosest point = " << cpp.location_ << " at index " << cpp.point_idx_ << "."; } TEST_F(MoveInsideTest, cornerEdgeTest2) @@ -161,8 +182,8 @@ TEST_F(MoveInsideTest, pointyCorner) inside.add(pointy_square); ClosestPolygonPoint cpp = PolygonUtils::ensureInsideOrOutside(inside, result, 10); - ASSERT_NE(cpp.point_idx, NO_INDEX) << "Couldn't ensure point inside close to " << from << "."; - ASSERT_NE(cpp.poly_idx, NO_INDEX) << "Couldn't ensure point inside close to " << from << "."; + ASSERT_NE(cpp.point_idx_, NO_INDEX) << "Couldn't ensure point inside close to " << from << "."; + ASSERT_NE(cpp.poly_idx_, NO_INDEX) << "Couldn't ensure point inside close to " << from << "."; ASSERT_TRUE(inside.inside(result)) << from << " couldn't be moved inside."; } @@ -175,8 +196,8 @@ TEST_F(MoveInsideTest, pointyCornerFail) inside.add(pointy_square); ClosestPolygonPoint cpp = PolygonUtils::moveInside2(inside, result, 10); - ASSERT_NE(cpp.point_idx, NO_INDEX) << "Couldn't ensure point inside close to " << from << "."; - ASSERT_NE(cpp.poly_idx, NO_INDEX) << "Couldn't ensure point inside close to " << from << "."; + ASSERT_NE(cpp.point_idx_, NO_INDEX) << "Couldn't ensure point inside close to " << from << "."; + ASSERT_NE(cpp.poly_idx_, NO_INDEX) << "Couldn't ensure point inside close to " << from << "."; ASSERT_FALSE(inside.inside(result)) << from << " could be moved inside, while it was designed to fail."; } @@ -189,8 +210,8 @@ TEST_F(MoveInsideTest, outsidePointyCorner) inside.add(pointy_square); const ClosestPolygonPoint cpp = PolygonUtils::ensureInsideOrOutside(inside, result, -10); - ASSERT_NE(cpp.point_idx, NO_INDEX) << "Couldn't ensure point inside close to " << from << "."; - ASSERT_NE(cpp.poly_idx, NO_INDEX) << "Couldn't ensure point inside close to " << from << "."; + ASSERT_NE(cpp.point_idx_, NO_INDEX) << "Couldn't ensure point inside close to " << from << "."; + ASSERT_NE(cpp.poly_idx_, NO_INDEX) << "Couldn't ensure point inside close to " << from << "."; ASSERT_TRUE(! inside.inside(result)) << from << " couldn't be moved outside."; } @@ -204,8 +225,8 @@ TEST_F(MoveInsideTest, outsidePointyCornerFail) inside.add(pointy_square); const ClosestPolygonPoint cpp = PolygonUtils::moveInside2(inside, result, -10); - ASSERT_NE(cpp.point_idx, NO_INDEX) << "Couldn't ensure point inside close to " << from << "."; - ASSERT_NE(cpp.poly_idx, NO_INDEX) << "Couldn't ensure point inside close to " << from << "."; + ASSERT_NE(cpp.point_idx_, NO_INDEX) << "Couldn't ensure point inside close to " << from << "."; + ASSERT_NE(cpp.poly_idx_, NO_INDEX) << "Couldn't ensure point inside close to " << from << "."; ASSERT_FALSE(! inside.inside(result)) << from << " could be moved outside to " << result << ", while it was designed to fail."; } @@ -214,9 +235,9 @@ struct FindCloseParameters Point2LL close_to; Point2LL supposed; coord_t cell_size; - std::function* penalty_function; + std::function* penalty_function; - FindCloseParameters(const Point2LL close_to, const Point2LL supposed, const coord_t cell_size, std::function* penalty_function = nullptr) + FindCloseParameters(const Point2LL close_to, const Point2LL supposed, const coord_t cell_size, std::function* penalty_function = nullptr) : close_to(close_to) , supposed(supposed) , cell_size(cell_size) @@ -260,7 +281,7 @@ TEST_P(FindCloseTest, FindClose) if (cpp) { - const Point2LL result = cpp->location; + const Point2LL result = cpp->location_; ASSERT_LE(vSize(result - parameters.supposed), 10) << "Close to " << parameters.close_to << " we found " << result << " rather than " << parameters.supposed << ".\n"; } else @@ -272,18 +293,20 @@ TEST_P(FindCloseTest, FindClose) /* * Test penalty function to use with findClose. */ -std::function testPenalty( +std::function testPenalty( [](Point2LL candidate) { return -vSize2(candidate - Point2LL(50, 100)); // The further from 50, 100, the lower the penalty. }); -INSTANTIATE_TEST_SUITE_P(FindCloseInstantiation, - FindCloseTest, - testing::Values(FindCloseParameters(Point2LL(110, 110), Point2LL(100, 100), 15), // Near a corner. - FindCloseParameters(Point2LL(50, 110), Point2LL(50, 100), 15), // Near a side. - FindCloseParameters(Point2LL(50, 50), Point2LL(50, 0), 60, &testPenalty) // Using a penalty function. - )); +INSTANTIATE_TEST_SUITE_P( + FindCloseInstantiation, + FindCloseTest, + testing::Values( + FindCloseParameters(Point2LL(110, 110), Point2LL(100, 100), 15), // Near a corner. + FindCloseParameters(Point2LL(50, 110), Point2LL(50, 100), 15), // Near a side. + FindCloseParameters(Point2LL(50, 50), Point2LL(50, 0), 60, &testPenalty) // Using a penalty function. + )); // NOLINTBEGIN(misc-non-private-member-variables-in-classes) class PolygonUtilsTest : public testing::Test @@ -403,18 +426,20 @@ TEST_P(GetNextParallelIntersectionTest, GetNextParallelIntersection) } } -INSTANTIATE_TEST_SUITE_P(GetNextParallelIntersectionInstantiation, - GetNextParallelIntersectionTest, - testing::Values(GetNextParallelIntersectionParameters(Point2LL(0, 40), Point2LL(20, 100), Point2LL(150, 200), true, 35), - GetNextParallelIntersectionParameters(Point2LL(37, 100), Point2LL(80, 100), Point2LL(150, 200), true, 35), - GetNextParallelIntersectionParameters(Point2LL(70, 100), Point2LL(20, 100), Point2LL(120, 200), false, 35), - GetNextParallelIntersectionParameters(Point2LL(0, 0), Point2LL(50, 100), Point2LL(150, 200), true, 35), - GetNextParallelIntersectionParameters(Point2LL(60, 0), Point2LL(10, 0), Point2LL(-90, -100), true, 35), - GetNextParallelIntersectionParameters(Point2LL(0, 40), Point2LL(10, 0), Point2LL(-90, -100), false, 35), - GetNextParallelIntersectionParameters(Point2LL(0, 75), Point2LL(50, 100), Point2LL(150, 100), true, 25), - GetNextParallelIntersectionParameters(Point2LL(25, 100), Point2LL(50, 100), Point2LL(50, 200), true, 25), - GetNextParallelIntersectionParameters(std::optional(), Point2LL(100, 100), Point2LL(200, 200), true, 80), - GetNextParallelIntersectionParameters(Point2LL(0, 45), Point2LL(5, 100), Point2LL(105, 200), true, 35))); +INSTANTIATE_TEST_SUITE_P( + GetNextParallelIntersectionInstantiation, + GetNextParallelIntersectionTest, + testing::Values( + GetNextParallelIntersectionParameters(Point2LL(0, 40), Point2LL(20, 100), Point2LL(150, 200), true, 35), + GetNextParallelIntersectionParameters(Point2LL(37, 100), Point2LL(80, 100), Point2LL(150, 200), true, 35), + GetNextParallelIntersectionParameters(Point2LL(70, 100), Point2LL(20, 100), Point2LL(120, 200), false, 35), + GetNextParallelIntersectionParameters(Point2LL(0, 0), Point2LL(50, 100), Point2LL(150, 200), true, 35), + GetNextParallelIntersectionParameters(Point2LL(60, 0), Point2LL(10, 0), Point2LL(-90, -100), true, 35), + GetNextParallelIntersectionParameters(Point2LL(0, 40), Point2LL(10, 0), Point2LL(-90, -100), false, 35), + GetNextParallelIntersectionParameters(Point2LL(0, 75), Point2LL(50, 100), Point2LL(150, 100), true, 25), + GetNextParallelIntersectionParameters(Point2LL(25, 100), Point2LL(50, 100), Point2LL(50, 200), true, 25), + GetNextParallelIntersectionParameters(std::optional(), Point2LL(100, 100), Point2LL(200, 200), true, 80), + GetNextParallelIntersectionParameters(Point2LL(0, 45), Point2LL(5, 100), Point2LL(105, 200), true, 35))); TEST_F(PolygonUtilsTest, RelativeHammingSquaresOverlap) { @@ -456,9 +481,10 @@ TEST_F(PolygonUtilsTest, RelativeHammingQuarterOverlap) */ TEST_F(PolygonUtilsTest, RelativeHammingLineSquare) { - ASSERT_EQ(PolygonUtils::relativeHammingDistance(test_squares, test_line), 1.0) << "The difference between the polygons is 100% because the area of the difference encompasses the area of the one polygon that " - "has " - "area."; + ASSERT_EQ(PolygonUtils::relativeHammingDistance(test_squares, test_line), 1.0) + << "The difference between the polygons is 100% because the area of the difference encompasses the area of the one polygon that " + "has " + "area."; } /* @@ -493,4 +519,4 @@ TEST_F(PolygonUtilsTest, DISABLED_RelativeHammingLineLineDifferentVerts) // Disa } } // namespace cura -// NOLINTEND(*-magic-numbers) \ No newline at end of file +// NOLINTEND(*-magic-numbers) diff --git a/tests/utils/SimplifyTest.cpp b/tests/utils/SimplifyTest.cpp index 1e45d8e9fb..3b80885267 100644 --- a/tests/utils/SimplifyTest.cpp +++ b/tests/utils/SimplifyTest.cpp @@ -2,9 +2,11 @@ // CuraEngine is released under the terms of the AGPLv3 or higher. #include "utils/Simplify.h" // The unit under test. + +#include + #include "utils/Coord_t.h" #include "utils/polygonUtils.h" // Helper functions for testing deviation. -#include // NOLINTBEGIN(*-magic-numbers) namespace cura @@ -32,7 +34,8 @@ class SimplifyTest : public testing::Test Polygon spiral; // A spiral with gradually increasing segment length. Polygon zigzag; // Sawtooth zig-zag pattern. - SimplifyTest() : simplifier(MAX_RESOLUTION, MAX_DEVIATION, MAX_AREA_DEVIATION) + SimplifyTest() + : simplifier(MAX_RESOLUTION, MAX_DEVIATION, MAX_AREA_DEVIATION) { } @@ -119,7 +122,7 @@ class SimplifyTest : public testing::Test */ TEST_F(SimplifyTest, CircleMaxResolution) { - simplifier.max_deviation = 999999; // For this test, the maximum deviation should not be an issue. + simplifier.max_deviation_ = 999999; // For this test, the maximum deviation should not be an issue. circle = simplifier.polygon(circle); for (size_t point_index = 1; point_index + 1 < circle.size(); point_index++) // Don't check the last vertex. Due to odd-numbered vertices it has to be shorter than the minimum. @@ -138,7 +141,7 @@ TEST_F(SimplifyTest, CircleMaxResolution) */ TEST_F(SimplifyTest, CircleMaxDeviation) { - simplifier.max_resolution = 999999; // For this test, the maximum resolution should not be an issue. + simplifier.max_resolution_ = 999999; // For this test, the maximum resolution should not be an issue. Polygon simplified = simplifier.polygon(circle); // Check on each vertex if it didn't deviate too much. @@ -147,7 +150,7 @@ TEST_F(SimplifyTest, CircleMaxDeviation) Point2LL moved_point = v; PolygonUtils::moveInside(simplified, moved_point); const coord_t deviation = vSize(moved_point - v); - EXPECT_LE(deviation, simplifier.max_deviation); + EXPECT_LE(deviation, simplifier.max_deviation_); } // Also check the other way around, since the longest distance may also be on a vertex of the new polygon. for (Point2LL v : simplified) @@ -155,7 +158,7 @@ TEST_F(SimplifyTest, CircleMaxDeviation) Point2LL moved_point = v; PolygonUtils::moveInside(circle, moved_point); const coord_t deviation = vSize(moved_point - v); - EXPECT_LE(deviation, simplifier.max_deviation); + EXPECT_LE(deviation, simplifier.max_deviation_); } } @@ -168,7 +171,7 @@ TEST_F(SimplifyTest, CircleMaxDeviation) */ TEST_F(SimplifyTest, Zigzag) { - simplifier.max_resolution = 9999999; + simplifier.max_resolution_ = 9999999; Polygon simplified = simplifier.polyline(zigzag); EXPECT_EQ(simplified.size(), 2) << "All zigzagged lines can be erased because they deviate less than the maximum deviation, leaving only the endpoints."; } @@ -182,12 +185,12 @@ TEST_F(SimplifyTest, Zigzag) */ TEST_F(SimplifyTest, LimitedLength) { - simplifier.max_deviation = 999999; // Maximum deviation should have no effect. + simplifier.max_deviation_ = 999999; // Maximum deviation should have no effect. // Find from where on the segments become longer than the maximum resolution. size_t limit_vertex; for (limit_vertex = 1; limit_vertex < spiral.size(); ++limit_vertex) { - if (vSize2(spiral[limit_vertex] - spiral[limit_vertex - 1]) > simplifier.max_resolution * simplifier.max_resolution) + if (vSize2(spiral[limit_vertex] - spiral[limit_vertex - 1]) > simplifier.max_resolution_ * simplifier.max_resolution_) { limit_vertex--; break; @@ -217,21 +220,21 @@ TEST_F(SimplifyTest, LimitedLength) */ TEST_F(SimplifyTest, LimitedError) { - simplifier.max_resolution = 9999999; + simplifier.max_resolution_ = 9999999; // Generate a zig-zag with gradually increasing deviation. Polygon increasing_zigzag; increasing_zigzag.add(Point2LL(0, 0)); constexpr coord_t amplitude_step = 1; // Every 2 vertices, the amplitude increases by this much. constexpr coord_t y_step = 100; - const coord_t amplitude_limit = simplifier.max_deviation * 2; // Increase amplitude up to this point. About half of the vertices should get removed. + const coord_t amplitude_limit = simplifier.max_deviation_ * 2; // Increase amplitude up to this point. About half of the vertices should get removed. for (coord_t amplitude = 0; amplitude < amplitude_limit; amplitude += amplitude_step) { increasing_zigzag.add(Point2LL(amplitude, increasing_zigzag.size() * y_step)); increasing_zigzag.add(Point2LL(0, increasing_zigzag.size() * y_step)); } - size_t limit_vertex = 2 * simplifier.max_deviation / amplitude_step + 3; // 2 vertices per zag. Deviation/step zags. Add 3 since deviation equal to max +- epsilon is allowed. + size_t limit_vertex = 2 * simplifier.max_deviation_ / amplitude_step + 3; // 2 vertices per zag. Deviation/step zags. Add 3 since deviation equal to max +- epsilon is allowed. Polygon simplified = simplifier.polyline(increasing_zigzag); @@ -267,13 +270,13 @@ TEST_F(SimplifyTest, LongEdgesNotMoved) // Verify that all small segments are removed. for (size_t i = 1; i < simplified.size(); ++i) { - EXPECT_GE(vSize(simplified[i] - simplified[i - 1]), simplifier.max_resolution) << "There may not be any segment smaller than max resolution."; + EXPECT_GE(vSize(simplified[i] - simplified[i - 1]), simplifier.max_resolution_) << "There may not be any segment smaller than max resolution."; } // Verify that all long segments are still present. for (size_t i = 0; i < polyline.size() - 1; ++i) { - if (vSize(polyline[i] - polyline[i + 1]) > simplifier.max_resolution) + if (vSize(polyline[i] - polyline[i + 1]) > simplifier.max_resolution_) { // Both endpoints of this line segment must have a distance to the simplified polygon of 0, theoretically. // Due to rounding errors we'll allow up to 1 unit. @@ -331,7 +334,7 @@ TEST_F(SimplifyTest, LongEdgesButTooMuchDeviation) */ TEST_F(SimplifyTest, Sine) { - simplifier.max_resolution = 9999999; + simplifier.max_resolution_ = 9999999; Polygon simplified = simplifier.polyline(sine); EXPECT_EQ(simplified.size(), 2) << "All zigzagged lines can be erased because they deviate less than the maximum deviation, leaving only the endpoints."; @@ -401,4 +404,4 @@ TEST_F(SimplifyTest, ToDegenerate) } } // namespace cura -// NOLINTEND(*-magic-numbers) \ No newline at end of file +// NOLINTEND(*-magic-numbers) diff --git a/tests/utils/SparseGridTest.cpp b/tests/utils/SparseGridTest.cpp index 5f60ec5491..00f013ed61 100644 --- a/tests/utils/SparseGridTest.cpp +++ b/tests/utils/SparseGridTest.cpp @@ -2,13 +2,16 @@ // CuraEngine is released under the terms of the AGPLv3 or higher. #include "utils/SparseGrid.h" -#include "utils/Coord_t.h" -#include "utils/SparsePointGridInclusive.h" + #include -#include #include #include +#include + +#include "utils/Coord_t.h" +#include "utils/SparsePointGridInclusive.h" + namespace cura { @@ -46,25 +49,47 @@ TEST_P(GetNearbyTest, GetNearby) // Are all near points reported as near? for (const Point2LL point : parameters.expected_near) { - EXPECT_NE(result.end(), std::find_if(result.begin(), result.end(), [&point](const typename SparsePointGridInclusive::Elem& elem) { return elem.val == point; })) + EXPECT_NE( + result.end(), + std::find_if( + result.begin(), + result.end(), + [&point](const typename SparsePointGridInclusive::Elem& elem) + { + return elem.val == point; + })) << "Point " << point << " is near " << target << " (distance " << vSize(point - target) << "), but getNearby didn't find it. Grid size: " << grid_size; } // Are all far points NOT reported as near? for (const Point2LL point : parameters.expected_far) { - EXPECT_EQ(result.end(), std::find_if(result.begin(), result.end(), [&point](const typename SparsePointGridInclusive::Elem& elem) { return elem.val == point; })) + EXPECT_EQ( + result.end(), + std::find_if( + result.begin(), + result.end(), + [&point](const typename SparsePointGridInclusive::Elem& elem) + { + return elem.val == point; + })) << "Point " << point << " is far from " << target << " (distance " << vSize(point - target) << "), but getNearby thought it was near. Grid size: " << grid_size; } } -INSTANTIATE_TEST_CASE_P(GetNearbyInstantiation, - GetNearbyTest, - testing::Values(Point2LLarbyParameters({ Point2LL(0, 100) }, stdPoint2LLrdered_set(), stdPoint2LLrdered_set(Point2LLnt(95, 100) }), - Point2LLunordered_setPoint2LLt>())Point2LLA near point. - GetNearbyParametersPoint2LLint(100, 100) }Point2LL std::Point2LLered_setPoint2LLt>Point2LLint(100, 100) })Point2LL std::Point2LLered_set()) // On top of the target. - )); +INSTANTIATE_TEST_CASE_P( + GetNearbyInstantiation, + GetNearbyTest, + testing::Values( + GetNearbyParameters({ Point2LL(0, 100) }, std::unordered_set(), std::unordered_set({ Point2LL(0, 100) })), // A far point. + GetNearbyParameters( + { Point2LL(95, 100) }, + std::unordered_set({ Point2LL(95, 100) }), + std::unordered_set()), // A near point. + GetNearbyParameters( + { Point2LL(100, 100) }, + std::unordered_set({ Point2LL(100, 100) }), + std::unordered_set()) // On top of the target. + )); TEST_F(GetNearbyTest, getNearbyLine2) { @@ -100,13 +125,29 @@ TEST_F(GetNearbyTest, getNearbyLine2) // Are all near points reported as near? for (const Point2LL point : near) { - EXPECT_NE(result.end(), std::find_if(result.begin(), result.end(), [&point](const typename SparsePointGridInclusive::Elem& elem) { return elem.val == point; })) + EXPECT_NE( + result.end(), + std::find_if( + result.begin(), + result.end(), + [&point](const typename SparsePointGridInclusive::Elem& elem) + { + return elem.val == point; + })) << "Point " << point << " is near " << target << " (distance " << vSize(point - target) << "), but getNearby didn't find it. Grid size: " << grid_size; } // Are all far points NOT reported as near? for (const Point2LL point : far) { - EXPECT_EQ(result.end(), std::find_if(result.begin(), result.end(), [&point](const typename SparsePointGridInclusive::Elem& elem) { return elem.val == point; })) + EXPECT_EQ( + result.end(), + std::find_if( + result.begin(), + result.end(), + [&point](const typename SparsePointGridInclusive::Elem& elem) + { + return elem.val == point; + })) << "Point " << point << " is far from " << target << " (distance " << vSize(point - target) << "), but getNearby thought it was near. Grid size: " << grid_size; } } @@ -145,13 +186,29 @@ TEST_F(GetNearbyTest, getNearbyLine) // Are all near points reported as near? for (const Point2LL point : near) { - EXPECT_NE(result.end(), std::find_if(result.begin(), result.end(), [&point](const typename SparsePointGridInclusive::Elem& elem) { return elem.val == point; })) + EXPECT_NE( + result.end(), + std::find_if( + result.begin(), + result.end(), + [&point](const typename SparsePointGridInclusive::Elem& elem) + { + return elem.val == point; + })) << "Point " << point << " is near " << target << " (distance " << vSize(point - target) << "), but getNearby didn't find it. Grid size: " << grid_size; } // Are all far points NOT reported as near? for (const Point2LL point : far) { - EXPECT_EQ(result.end(), std::find_if(result.begin(), result.end(), [&point](const typename SparsePointGridInclusive::Elem& elem) { return elem.val == point; })) + EXPECT_EQ( + result.end(), + std::find_if( + result.begin(), + result.end(), + [&point](const typename SparsePointGridInclusive::Elem& elem) + { + return elem.val == point; + })) << "Point " << point << " is far from " << target << " (distance " << vSize(point - target) << "), but getNearby thought it was near. Grid size: " << grid_size; } } @@ -160,9 +217,12 @@ struct GetNearestParameters { std::vector registered_points; Point2LL* result; - std::function::Elem&)> filter; + std::function::Elem&)> filter; - GetNearestParameters(const std::vector registered_points, Point2LL* result, const std::function::Elem&)>& filter = SparsePointGridInclusive::no_precondition) + GetNearestParameters( + const std::vector registered_points, + Point2LL* result, + const std::function::Elem&)>& filter = SparsePointGridInclusive::no_precondition) : registered_points(registered_points) , result(result) , filter(filter) @@ -192,20 +252,26 @@ TEST_P(GetNearestTest, GetNearest) ASSERT_EQ(success, parameters.result != nullptr) << "getNearest returned " << success << " but should've returned " << (parameters.result != nullptr) << "."; if (parameters.result) { - ASSERT_EQ(result.val, *parameters.result) << "getNearest reported the nearest point to be " << result.val << " (distance " << vSize(target - result.val) << "), but it was " << *parameters.result << " (distance " - << vSize(target - *parameters.result) << ")."; + ASSERT_EQ(result.val, *parameters.result) << "getNearest reported the nearest point to be " << result.val << " (distance " << vSize(target - result.val) << "), but it was " + << *parameters.result << " (distance " << vSize(target - *parameters.result) << ")."; } } -INSTANTIATE_TEST_SUITE_P(GetNearestInstantiation, - GetNearestTest, - testing::Values(GetNearestParameters(std::vector({ Point2LL(95, 100), Point2LL(103, 100), Point2LL(200, 100) }), new Point2LL(103, 100)), // Choose the nearest out of 3 points. - GetNearestParameters(std::vector({ Point2LL(95, 100), Point2LL(98, 100), Point2LL(106, 100) }), - new Point2LL(106, 100), - [](const typename SparsePointGridInclusive::Elem& elem) -> bool { return elem.point.X > 100; }), // With a filter. - GetNearestParameters(std::vector(), nullptr), // No points, no answer. - GetNearestParameters(std::vector({ Point2LL(100, 100) }), new Point2LL(100, 100)) // Same point as target. - )); +INSTANTIATE_TEST_SUITE_P( + GetNearestInstantiation, + GetNearestTest, + testing::Values( + GetNearestParameters(std::vector({ Point2LL(95, 100), Point2LL(103, 100), Point2LL(200, 100) }), new Point2LL(103, 100)), // Choose the nearest out of 3 points. + GetNearestParameters( + std::vector({ Point2LL(95, 100), Point2LL(98, 100), Point2LL(106, 100) }), + new Point2LL(106, 100), + [](const typename SparsePointGridInclusive::Elem& elem) -> bool + { + return elem.point.X > 100; + }), // With a filter. + GetNearestParameters(std::vector(), nullptr), // No points, no answer. + GetNearestParameters(std::vector({ Point2LL(100, 100) }), new Point2LL(100, 100)) // Same point as target. + )); TEST_F(GetNearestTest, Equal) { @@ -228,9 +294,10 @@ TEST_F(GetNearestTest, Equal) const bool success = grid.getNearest(target, grid_size, result, SparsePointGridInclusive::no_precondition); ASSERT_TRUE(success); - ASSERT_TRUE(result.val == expected1 || result.val == expected2) << "getNearest reported the nearest point to be " << result.val << " (distance " << vSize(target - result.val) << "), but it should've been " << expected1 << "(distance " - << vSize(expected1 - target) << ") or " << expected2 << " (distance " << vSize(expected2 - target) - << ")."; // FIXME: simplify once fmt or we use C++20 is added as a dependency + ASSERT_TRUE(result.val == expected1 || result.val == expected2) + << "getNearest reported the nearest point to be " << result.val << " (distance " << vSize(target - result.val) << "), but it should've been " << expected1 << "(distance " + << vSize(expected1 - target) << ") or " << expected2 << " (distance " << vSize(expected2 - target) + << ")."; // FIXME: simplify once fmt or we use C++20 is added as a dependency } } // namespace cura From fd3b4dcfd366d8cfdb0bd4b05eb000442b6afb89 Mon Sep 17 00:00:00 2001 From: wawanbreton Date: Wed, 22 Nov 2023 14:40:37 +0000 Subject: [PATCH 37/48] Applied clang-format. --- include/bridge.h | 17 ++++++++++++----- include/pathPlanning/Comb.h | 2 +- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/include/bridge.h b/include/bridge.h index a4cb04233d..a95e3a0fe7 100644 --- a/include/bridge.h +++ b/include/bridge.h @@ -1,5 +1,5 @@ -//Copyright (c) 2019 Ultimaker B.V. -//CuraEngine is released under the terms of the AGPLv3 or higher. +// Copyright (c) 2019 Ultimaker B.V. +// CuraEngine is released under the terms of the AGPLv3 or higher. #ifndef BRIDGE_H #define BRIDGE_H @@ -27,8 +27,15 @@ class SupportLayer; * \param supported_regions Pre-computed regions that the support layer would * support. */ -double bridgeAngle(const Settings& settings, const Polygons& skin_outline, const SliceDataStorage& storage, const unsigned layer_nr, const unsigned bridge_layer, const SupportLayer* support_layer, Polygons& supported_regions); +double bridgeAngle( + const Settings& settings, + const Polygons& skin_outline, + const SliceDataStorage& storage, + const unsigned layer_nr, + const unsigned bridge_layer, + const SupportLayer* support_layer, + Polygons& supported_regions); -}//namespace cura +} // namespace cura -#endif//BRIDGE_H +#endif // BRIDGE_H diff --git a/include/pathPlanning/Comb.h b/include/pathPlanning/Comb.h index cbdd1b539a..289a5a1f5d 100644 --- a/include/pathPlanning/Comb.h +++ b/include/pathPlanning/Comb.h @@ -177,7 +177,7 @@ class Comb * \param start_inside_poly[out] The polygon in which the point has been moved * \return Whether we have moved the point inside */ - bool moveInside(Polygons& boundary_inside, bool is_inside, LocToLineGrid* inside_loc_to_line, Point2LL& dest_point, size_t &start_inside_poly); + bool moveInside(Polygons& boundary_inside, bool is_inside, LocToLineGrid* inside_loc_to_line, Point2LL& dest_point, size_t& start_inside_poly); void moveCombPathInside(Polygons& boundary_inside, Polygons& boundary_inside_optimal, CombPath& comb_path_input, CombPath& comb_path_output); From f08aadfa6bb62bdae753d86d56542af74d2f6c66 Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Wed, 22 Nov 2023 15:46:13 +0100 Subject: [PATCH 38/48] Fixed conversion warning, with potential side-effects on combing --- src/LayerPlan.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/LayerPlan.cpp b/src/LayerPlan.cpp index 6e5ce67341..441e0faebd 100644 --- a/src/LayerPlan.cpp +++ b/src/LayerPlan.cpp @@ -175,7 +175,7 @@ Polygons LayerPlan::computeCombBoundary(const CombBoundary boundary_type) switch (boundary_type) { case CombBoundary::MINIMUM: - offset = -mesh.settings.get("machine_nozzle_size") / 2 - 0.1 - mesh.settings.get("wall_line_width_0") / 2; + offset = -mesh.settings.get("machine_nozzle_size") / 2 - mesh.settings.get("wall_line_width_0") / 2; break; case CombBoundary::PREFERRED: offset = -mesh.settings.get("machine_nozzle_size") * 3 / 2 - mesh.settings.get("wall_line_width_0") / 2; From cdca811ffc8652eea2b2df13ba7ec8d2040c34ae Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Wed, 22 Nov 2023 15:54:24 +0100 Subject: [PATCH 39/48] Fixed crash --- include/utils/PolygonsPointIndex.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/utils/PolygonsPointIndex.h b/include/utils/PolygonsPointIndex.h index deb722dd06..c4ce020105 100644 --- a/include/utils/PolygonsPointIndex.h +++ b/include/utils/PolygonsPointIndex.h @@ -47,7 +47,7 @@ class PathsPointIndex * \param poly_idx The index of the sub-polygon to point to. * \param point_idx The index of the vertex in the sub-polygon. */ - PathsPointIndex(const Paths* polygons, unsigned int poly_idx, unsigned int point_idx) + PathsPointIndex(const Paths* polygons, size_t poly_idx, size_t point_idx) : polygons_(polygons) , poly_idx_(poly_idx) , point_idx_(point_idx) From b7776f4272fff230a161f31e27cb1a5813f75afe Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Wed, 22 Nov 2023 16:36:00 +0100 Subject: [PATCH 40/48] Upload unit-test report for Github action --- .github/workflows/unit-test.yml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.github/workflows/unit-test.yml b/.github/workflows/unit-test.yml index 04e325df79..ff529730fc 100644 --- a/.github/workflows/unit-test.yml +++ b/.github/workflows/unit-test.yml @@ -141,5 +141,13 @@ jobs: files: | **/*.xml + - name: Upload the detailed tests report + uses: actions/upload-artifact@v3 + with: + name: LastTest.log + path: | + /home/runner/work/CuraEngine/CuraEngine/build/Release/Testing/Temporary/LastTest.log + retention-days: 5 + - name: Conclusion run: echo "Conclusion is ${{ fromJSON( steps.test-results.outputs.json ).conclusion }}" From 7625e4fd8b542ce71efb8cd516db520e2a74c2f9 Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Wed, 22 Nov 2023 16:52:18 +0100 Subject: [PATCH 41/48] Upload detailed test report only on Linux --- .github/workflows/unit-test.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/unit-test.yml b/.github/workflows/unit-test.yml index ff529730fc..59c3e7320b 100644 --- a/.github/workflows/unit-test.yml +++ b/.github/workflows/unit-test.yml @@ -143,10 +143,11 @@ jobs: - name: Upload the detailed tests report uses: actions/upload-artifact@v3 + if: ${{ runner.os == 'Linux' }} with: name: LastTest.log path: | - /home/runner/work/CuraEngine/CuraEngine/build/Release/Testing/Temporary/LastTest.log + build/Release/Testing/Temporary/LastTest.log retention-days: 5 - name: Conclusion From 50366ad0c5e2070eee6a553c03dde2fa775cc5e1 Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Wed, 22 Nov 2023 17:14:36 +0100 Subject: [PATCH 42/48] Force unit test report publishing --- .github/workflows/unit-test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/unit-test.yml b/.github/workflows/unit-test.yml index 59c3e7320b..94f0ed77cb 100644 --- a/.github/workflows/unit-test.yml +++ b/.github/workflows/unit-test.yml @@ -143,7 +143,7 @@ jobs: - name: Upload the detailed tests report uses: actions/upload-artifact@v3 - if: ${{ runner.os == 'Linux' }} + if: ${{ always() }} with: name: LastTest.log path: | From 332b2f36023b3a63a3d3b43cbbc8f450da917fb6 Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Wed, 22 Nov 2023 17:41:40 +0100 Subject: [PATCH 43/48] Fixed GCodeExport unit test --- tests/GCodeExportTest.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/GCodeExportTest.cpp b/tests/GCodeExportTest.cpp index b8ae6bb7ca..4435285791 100644 --- a/tests/GCodeExportTest.cpp +++ b/tests/GCodeExportTest.cpp @@ -652,11 +652,10 @@ TEST_F(GCodeExportTest, insertWipeScriptRetractionEnable) gcode.is_volumetric_ = false; gcode.current_extruder_ = 0; gcode.extruder_attr_[0].filament_area_ = 10.0; + gcode.extruder_attr_[0].machine_firmware_retract_ = false; gcode.relative_extrusion_ = false; gcode.current_speed_ = 1.0; Application::getInstance().current_slice_->scene.current_mesh_group->settings.add("layer_height", "0.2"); - Application::getInstance().current_slice_->scene.extruders.emplace_back(0, &Application::getInstance().current_slice_->scene.current_mesh_group->settings); - Application::getInstance().current_slice_->scene.extruders.back().settings_.add("machine_firmware_retract", "false"); WipeScriptConfig config; config.retraction_enable = true; From a336b225b92367cc4f6a608db71e17659205bb34 Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Wed, 22 Nov 2023 17:42:02 +0100 Subject: [PATCH 44/48] Fixed some numeric conversion warnings --- include/TreeSupportSettings.h | 6 +++--- include/timeEstimate.h | 20 ++++++++++---------- include/utils/ExtrusionLine.h | 4 ++-- include/utils/string.h | 6 +++--- src/FffPolygonGenerator.cpp | 2 +- src/MeshGroup.cpp | 2 +- src/gcodeExport.cpp | 4 ++-- src/skin.cpp | 2 +- 8 files changed, 23 insertions(+), 23 deletions(-) diff --git a/include/TreeSupportSettings.h b/include/TreeSupportSettings.h index a550bb530b..78be092694 100644 --- a/include/TreeSupportSettings.h +++ b/include/TreeSupportSettings.h @@ -32,8 +32,8 @@ struct TreeSupportSettings , min_radius(mesh_group_settings.get("support_tree_tip_diameter") / 2) , // The actual radius is 50 microns larger as the resulting branches will be increased by 50 microns to avoid rounding errors effectively increasing the xydistance max_radius(mesh_group_settings.get("support_tree_max_diameter") / 2) - , maximum_move_distance((angle < TAU / 4) ? (coord_t)(tan(angle) * layer_height) : std::numeric_limits::max()) - , maximum_move_distance_slow((angle_slow < TAU / 4) ? (coord_t)(tan(angle_slow) * layer_height) : std::numeric_limits::max()) + , maximum_move_distance((angle < TAU / 4) ? std::llround(tan(angle) * layer_height) : std::numeric_limits::max()) + , maximum_move_distance_slow((angle_slow < TAU / 4) ? std::llround(tan(angle_slow) * layer_height) : std::numeric_limits::max()) , support_bottom_layers(mesh_group_settings.get("support_bottom_enable") ? round_divide(mesh_group_settings.get("support_bottom_height"), layer_height) : 0) , tip_layers(std::max((branch_radius - min_radius) / (support_line_width / 3), branch_radius / layer_height)) , // Ensure lines always stack nicely even if layer height is large @@ -50,7 +50,7 @@ struct TreeSupportSettings : RestPreference::BUILDPLATE) , xy_distance(mesh_group_settings.get("support_xy_distance")) , bp_radius(mesh_group_settings.get("support_tree_bp_diameter") / 2) - , diameter_scale_bp_radius(std::min(sin(0.7) * layer_height / branch_radius, 1.0 / (branch_radius / (support_line_width / 2.0)))) + , diameter_scale_bp_radius(std::min(sin(0.7) * static_cast(layer_height / branch_radius), 1.0 / (branch_radius / (support_line_width / 2.0)))) , // Either 40° or as much as possible so that 2 lines will overlap by at least 50%, whichever is smaller. support_overrides(mesh_group_settings.get("support_xy_overrides_z")) , xy_min_distance(support_overrides == SupportDistPriority::Z_OVERRIDES_XY ? mesh_group_settings.get("support_xy_distance_overhang") : xy_distance) diff --git a/include/timeEstimate.h b/include/timeEstimate.h index 4ce741a6ba..b78b136aea 100644 --- a/include/timeEstimate.h +++ b/include/timeEstimate.h @@ -4,15 +4,15 @@ #ifndef TIME_ESTIMATE_H #define TIME_ESTIMATE_H +#include +#include +#include + #include "PrintFeature.h" #include "settings/types/Duration.h" //Print time estimates. #include "settings/types/Ratio.h" #include "settings/types/Velocity.h" //Speeds and accelerations at which we print. -#include -#include -#include - namespace cura { @@ -26,11 +26,11 @@ class Settings; class TimeEstimateCalculator { public: - constexpr static unsigned int NUM_AXIS = 4; - constexpr static unsigned int X_AXIS = 0; - constexpr static unsigned int Y_AXIS = 1; - constexpr static unsigned int Z_AXIS = 2; - constexpr static unsigned int E_AXIS = 3; + constexpr static size_t NUM_AXIS = 4; + constexpr static size_t X_AXIS = 0; + constexpr static size_t Y_AXIS = 1; + constexpr static size_t Z_AXIS = 2; + constexpr static size_t E_AXIS = 3; class Position @@ -50,7 +50,7 @@ class TimeEstimateCalculator } double axis[NUM_AXIS]; - double& operator[](const int n) + double& operator[](const size_t n) { return axis[n]; } diff --git a/include/utils/ExtrusionLine.h b/include/utils/ExtrusionLine.h index 7c09ca4eb5..e1f2437666 100644 --- a/include/utils/ExtrusionLine.h +++ b/include/utils/ExtrusionLine.h @@ -129,12 +129,12 @@ struct ExtrusionLine return junctions_.back(); } - const ExtrusionJunction& operator[](unsigned int index) const + const ExtrusionJunction& operator[](size_t index) const { return junctions_[index]; } - ExtrusionJunction& operator[](unsigned int index) + ExtrusionJunction& operator[](size_t index) { return junctions_[index]; } diff --git a/include/utils/string.h b/include/utils/string.h index 7ca857c191..90ddc318fd 100644 --- a/include/utils/string.h +++ b/include/utils/string.h @@ -121,10 +121,10 @@ struct MMtoStream * \param coord double to output * \param ss The output stream to write the string to */ -static inline void writeDoubleToStream(const unsigned int precision, const double coord, std::ostream& ss) +static inline void writeDoubleToStream(const uint8_t precision, const double coord, std::ostream& ss) { char format[5] = "%.xF"; // write a float with [x] digits after the dot - format[2] = '0' + precision; // set [x] + format[2] = '0' + static_cast(precision); // set [x] constexpr size_t buffer_size = 400; char buffer[buffer_size]; int char_count = sprintf(buffer, format, coord); @@ -166,7 +166,7 @@ static inline void writeDoubleToStream(const unsigned int precision, const doubl */ struct PrecisionedDouble { - unsigned int precision; //!< Number of digits after the decimal mark with which to convert to string + uint8_t precision; //!< Number of digits after the decimal mark with which to convert to string double value; //!< The double value friend inline std::ostream& operator<<(std::ostream& out, const PrecisionedDouble precision_and_input) diff --git a/src/FffPolygonGenerator.cpp b/src/FffPolygonGenerator.cpp index 16503d2839..384093794c 100644 --- a/src/FffPolygonGenerator.cpp +++ b/src/FffPolygonGenerator.cpp @@ -827,7 +827,7 @@ void FffPolygonGenerator::processSkinsAndInfill(SliceMeshStorage& mesh, const La SkinInfillAreaComputation skin_infill_area_computation(layer_nr, mesh, process_infill); skin_infill_area_computation.generateSkinsAndInfill(); - if (mesh.settings.get("ironing_enabled") && (! mesh.settings.get("ironing_only_highest_layer") || mesh.layer_nr_max_filled_layer == layer_nr) + if (((mesh.settings.get("ironing_enabled") && (! mesh.settings.get("ironing_only_highest_layer"))) || mesh.layer_nr_max_filled_layer == layer_nr) || ! mesh.settings.get("small_skin_on_surface")) { // Generate the top surface to iron over. diff --git a/src/MeshGroup.cpp b/src/MeshGroup.cpp index c31623cee6..f71b2f7bd5 100644 --- a/src/MeshGroup.cpp +++ b/src/MeshGroup.cpp @@ -210,7 +210,7 @@ bool loadMeshSTL_binary(Mesh* mesh, const char* filename, const Matrix4x3D& matr fclose(f); return false; } - float* v = ((float*)buffer) + 3; + float* v = reinterpret_cast(buffer) + 3; Point3LL v0 = matrix.apply(Point3F(v[0], v[1], v[2]).toPoint3d()); Point3LL v1 = matrix.apply(Point3F(v[3], v[4], v[5]).toPoint3d()); diff --git a/src/gcodeExport.cpp b/src/gcodeExport.cpp index 9726c9b39c..8372ba1656 100644 --- a/src/gcodeExport.cpp +++ b/src/gcodeExport.cpp @@ -31,7 +31,7 @@ std::string transliterate(const std::string& text) std::ostringstream stream; for (const char& c : text) { - stream << static_cast((c >= 0) ? c : '?'); + stream << ((c >= 0) ? c : '?'); } return stream.str(); } @@ -1165,7 +1165,7 @@ void GCodeExport::writeRetraction(const RetractionConfig& config, bool force, bo } } - if (extruder_attr_[current_extruder_].machine_firmware_retract_) + if (extr_attr.machine_firmware_retract_) { if (extruder_switch && extr_attr.retraction_e_amount_current_) { diff --git a/src/skin.cpp b/src/skin.cpp index e02ba1b2d1..1f36864698 100644 --- a/src/skin.cpp +++ b/src/skin.cpp @@ -535,7 +535,7 @@ void SkinInfillAreaComputation::generateGradualInfill(SliceMeshStorage& mesh) void SkinInfillAreaComputation::combineInfillLayers(SliceMeshStorage& mesh) { - if (mesh.layers.empty() || mesh.layers.size() - 1 < static_cast(mesh.settings.get("top_layers")) + if (mesh.layers.empty() || mesh.layers.size() - 1 < mesh.settings.get("top_layers") || mesh.settings.get("infill_line_distance") == 0) // No infill is even generated. { return; From 65f0d9b9661c3d0f45ca8b0fb8e467485273637f Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Thu, 23 Nov 2023 09:51:19 +0100 Subject: [PATCH 45/48] Fixed minimum layer time application regression --- include/ExtruderPlan.h | 2 +- src/LayerPlan.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/include/ExtruderPlan.h b/include/ExtruderPlan.h index 7f534d1ec8..e5fc1dd11d 100644 --- a/include/ExtruderPlan.h +++ b/include/ExtruderPlan.h @@ -44,7 +44,7 @@ class ExtruderPlan FRIEND_TEST(ExtruderPlanTest, BackPressureCompensationEmptyPlan); #endif public: - size_t extruder_nr_; //!< The extruder used for this paths in the current plan. + size_t extruder_nr_{ 0 }; //!< The extruder used for this paths in the current plan. ExtruderPlan() noexcept = default; diff --git a/src/LayerPlan.cpp b/src/LayerPlan.cpp index 441e0faebd..6077daa44d 100644 --- a/src/LayerPlan.cpp +++ b/src/LayerPlan.cpp @@ -1592,7 +1592,7 @@ void ExtruderPlan::forceMinimalLayerTime(double minTime, double time_other_extr_ // Slowing down to the slowest_speed is sufficient to respect the minimum layer time. // Linear interpolate between extrudeTime and total_extrude_time_at_slowest_speed const double factor = (1 / total_extrude_time_at_slowest_speed - 1 / minExtrudeTime) / (1 / total_extrude_time_at_slowest_speed - 1 / extrudeTime); - slow_down_func = [&slowest_path_speed = slowest_path_speed_, &factor](const GCodePath& path) + slow_down_func = [&slowest_path_speed = slowest_path_speed_, factor](const GCodePath& path) { const double actual_target_speed = slowest_path_speed * (1.0 - factor) + (path.config.getSpeed() * path.speed_factor) * factor; return std::min(actual_target_speed / (path.config.getSpeed() * path.speed_factor), 1.0); From 1884fbcea08fc2af15841985a175876f7c096389 Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Thu, 30 Nov 2023 15:21:26 +0100 Subject: [PATCH 46/48] Update src/utils/PolygonsPointIndex.cpp Use at() instead or brackets Co-authored-by: Casper Lamboo --- src/utils/PolygonsPointIndex.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/PolygonsPointIndex.cpp b/src/utils/PolygonsPointIndex.cpp index d41092baba..7084831e0a 100644 --- a/src/utils/PolygonsPointIndex.cpp +++ b/src/utils/PolygonsPointIndex.cpp @@ -9,7 +9,7 @@ namespace cura template<> ConstPolygonRef PathsPointIndex::getPolygon() const { - return (*polygons_)[poly_idx_]; + return polygons_->at(poly_idx_); } } // namespace cura From 4d203599b08143a2725112a24f4eed66562a68ec Mon Sep 17 00:00:00 2001 From: Erwan MATHIEU Date: Thu, 30 Nov 2023 15:24:34 +0100 Subject: [PATCH 47/48] Update src/utils/ExtrusionLine.cpp Remove useless code Co-authored-by: Casper Lamboo --- src/utils/ExtrusionLine.cpp | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/utils/ExtrusionLine.cpp b/src/utils/ExtrusionLine.cpp index 7d0ef20561..5183aab67b 100644 --- a/src/utils/ExtrusionLine.cpp +++ b/src/utils/ExtrusionLine.cpp @@ -11,12 +11,6 @@ namespace cura { -/*ExtrusionLine::ExtrusionLine(const size_t inset_idx, const bool is_odd) - : inset_idx_(inset_idx) - , is_odd_(is_odd) - , is_closed_(false) -{ -}*/ coord_t ExtrusionLine::getLength() const { From a33ad67da1285111b4c8d2592540617e54edf377 Mon Sep 17 00:00:00 2001 From: Casper Lamboo Date: Fri, 1 Dec 2023 10:57:21 +0100 Subject: [PATCH 48/48] Use explicit `std::optional` utility functions CURA-11359 --- src/bridge.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/bridge.cpp b/src/bridge.cpp index 91616a1d87..aeae8aeb9e 100644 --- a/src/bridge.cpp +++ b/src/bridge.cpp @@ -195,11 +195,11 @@ double bridgeAngle( } } - if (! idx1 || ! idx2) + if (! idx1.hasValue() || ! idx2.hasValue()) return -1.0; - Point2LL center1 = islands[*idx1].centerOfMass(); - Point2LL center2 = islands[*idx2].centerOfMass(); + Point2LL center1 = islands[idx1.value()].centerOfMass(); + Point2LL center2 = islands[idx2.value()].centerOfMass(); return angle(center2 - center1); }