diff --git a/CMakeLists.txt b/CMakeLists.txt
index a3c2eca12..bc0c80869 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -72,6 +72,9 @@ if (MSVC)
# error C3859: virtual memory range for PCH exceeded; please recompile with a command line option of '-Zm90' or greater
# Generate symbols at every build target, even for the release.
add_compile_options(-bigobj -Zm520 /Zi)
+ # Disable STL4007: Many result_type typedefs and all argument_type, first_argument_type, and second_argument_type typedefs are deprecated in C++17.
+ #FIXME Remove this line after eigen library adapts to the new C++17 adaptor rules.
+ add_compile_options(-D_SILENCE_CXX17_ADAPTOR_TYPEDEFS_DEPRECATION_WARNING)
endif ()
if (MINGW)
diff --git a/deps/MPFR/MPFR.cmake b/deps/MPFR/MPFR.cmake
index 17ac283ea..cda7eeea9 100644
--- a/deps/MPFR/MPFR.cmake
+++ b/deps/MPFR/MPFR.cmake
@@ -21,7 +21,7 @@ else ()
ExternalProject_Add(dep_MPFR
URL http://ftp.vim.org/ftp/gnu/mpfr/mpfr-3.1.6.tar.bz2 https://www.mpfr.org/mpfr-3.1.6/mpfr-3.1.6.tar.bz2 # mirrors are allowed
BUILD_IN_SOURCE ON
- CONFIGURE_COMMAND ./configure --prefix=${DESTDIR}/usr/local --with-gmp=${DESTDIR}/usr/local --with-pic
+ CONFIGURE_COMMAND ./configure --prefix=${DESTDIR}/usr/local --enable-shared=no --enable-static=yes --with-gmp=${DESTDIR}/usr/local --with-pic
BUILD_COMMAND make -j
INSTALL_COMMAND make install
DEPENDS dep_GMP
diff --git a/resources/icons/error_tick.svg b/resources/icons/error_tick.svg
new file mode 100644
index 000000000..6467d29fb
--- /dev/null
+++ b/resources/icons/error_tick.svg
@@ -0,0 +1,12 @@
+
+
+
diff --git a/resources/localization/PrusaSlicer.pot b/resources/localization/PrusaSlicer.pot
index 13f55f7bb..c5bcaa3bd 100644
--- a/resources/localization/PrusaSlicer.pot
+++ b/resources/localization/PrusaSlicer.pot
@@ -3622,8 +3622,7 @@ msgstr ""
#: src/slic3r/GUI/Plater.cpp:2315
msgid ""
-"You can't load SLA project if there is at least one multi-part object on the "
-"bed"
+"You cannot load SLA project with a multi-part object on the bed"
msgstr ""
#: src/slic3r/GUI/Plater.cpp:2316 src/slic3r/GUI/Tab.cpp:2915
diff --git a/resources/localization/pt_br/PrusaSlicer_pt_br.po b/resources/localization/pt_br/PrusaSlicer_pt_br.po
index e54f17ec3..30c0687a5 100644
--- a/resources/localization/pt_br/PrusaSlicer_pt_br.po
+++ b/resources/localization/pt_br/PrusaSlicer_pt_br.po
@@ -8,7 +8,7 @@ msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2019-09-09 16:39+0200\n"
-"PO-Revision-Date: 2019-11-18 16:39-0300\n"
+"PO-Revision-Date: 2019-12-21 19:55-0300\n"
"Language-Team: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
@@ -1432,7 +1432,7 @@ msgid ""
"You will lose content of the plater."
msgstr ""
"Alterar a linguagem fará com que o aplicativo reinicie.\n"
-"Você irá perder conteúdo no prato."
+"Você irá perder conteúdo na bandeja."
#: src/slic3r/GUI/GUI_App.cpp:877
msgid "Do you want to proceed?"
@@ -2302,7 +2302,7 @@ msgstr "(Re)fatiar"
#: src/slic3r/GUI/KBShortcutsDialog.cpp:116
msgid "Select Plater Tab"
-msgstr "Selecione a guia de prato"
+msgstr "Selecione a guia de bandeja"
#: src/slic3r/GUI/KBShortcutsDialog.cpp:118
msgid "Select Print Settings Tab"
@@ -2466,7 +2466,7 @@ msgstr "Desmarcar Gizmo/limpar seleção"
#: src/slic3r/GUI/KBShortcutsDialog.cpp:166
msgid "Plater Shortcuts"
-msgstr "Atalhos do prato"
+msgstr "Atalhos da bandeja"
#: src/slic3r/GUI/KBShortcutsDialog.cpp:181
#: src/slic3r/GUI/KBShortcutsDialog.cpp:193
@@ -2546,7 +2546,7 @@ msgstr "baseado no Slic3r"
#: src/slic3r/GUI/MainFrame.cpp:189
msgid "Plater"
-msgstr "Prato"
+msgstr "Bandeja"
#: src/slic3r/GUI/MainFrame.cpp:400
msgid "&New Project"
@@ -2635,7 +2635,7 @@ msgstr "Exportar &G-code"
#: src/slic3r/GUI/MainFrame.cpp:469
msgid "Export current plate as G-code"
-msgstr "Exporte o prato atual como o G-code"
+msgstr "Exporte a bandeja atual como o G-code"
#: src/slic3r/GUI/MainFrame.cpp:473 src/slic3r/GUI/MainFrame.cpp:720
msgid "S&end G-code"
@@ -2643,31 +2643,31 @@ msgstr "E&nviar G-code"
#: src/slic3r/GUI/MainFrame.cpp:473
msgid "Send to print current plate as G-code"
-msgstr "Enviar para imprimir prato atual como G-code"
+msgstr "Enviar para imprimir a bandeja atual como G-code"
#: src/slic3r/GUI/MainFrame.cpp:478
msgid "Export plate as &STL"
-msgstr "Exportar prato como &STL"
+msgstr "Exportar bandeja como &STL"
#: src/slic3r/GUI/MainFrame.cpp:478
msgid "Export current plate as STL"
-msgstr "Exporte o prato atual como STL"
+msgstr "Exporte a bandeja atual como STL"
#: src/slic3r/GUI/MainFrame.cpp:481
msgid "Export plate as STL &including supports"
-msgstr "Exportar prato como STL &incluindo suportes"
+msgstr "Exportar bandeja como STL &incluindo suportes"
#: src/slic3r/GUI/MainFrame.cpp:481
msgid "Export current plate as STL including supports"
-msgstr "Exporte o prato atual como o STL que inclui suportes"
+msgstr "Exporte a bandeja atual como o STL que inclui suportes"
#: src/slic3r/GUI/MainFrame.cpp:484
msgid "Export plate as &AMF"
-msgstr "Exportar prato como &AMF"
+msgstr "Exportar bandeja como &AMF"
#: src/slic3r/GUI/MainFrame.cpp:484
msgid "Export current plate as AMF"
-msgstr "Exporte o prato atual como o AMF"
+msgstr "Exporte a bandeja atual como o AMF"
#: src/slic3r/GUI/MainFrame.cpp:488
msgid "Export &toolpaths as OBJ"
@@ -2804,11 +2804,11 @@ msgstr "Colar área de transferência"
#: src/slic3r/GUI/MainFrame.cpp:590
msgid "&Plater Tab"
-msgstr "&Prato"
+msgstr "&Bandeja"
#: src/slic3r/GUI/MainFrame.cpp:590
msgid "Show the plater"
-msgstr "Mostrar o prato"
+msgstr "Mostrar a bandeja"
#: src/slic3r/GUI/MainFrame.cpp:597
msgid "P&rint Settings Tab"
@@ -6198,7 +6198,7 @@ msgstr "Distância entre cópias"
#: src/libslic3r/PrintConfig.cpp:352
msgid "Distance used for the auto-arrange feature of the plater."
-msgstr "Distância usada para o recurso de organizar automaticamente o prato."
+msgstr "Distância usada para o recurso de organizar automaticamente a bandeja."
#: src/libslic3r/PrintConfig.cpp:359
msgid "Elephant foot compensation"
@@ -6395,8 +6395,8 @@ msgid ""
msgstr ""
"Defina isso para o raio de folga em torno de sua extrusora. Se a extrusora "
"não estiver centralizada, escolha o maior valor para a segurança. Essa "
-"config. é usada para verificar colisões e exibir a visualização gráfica no "
-"prato."
+"config. é usada para verificar colisões e exibir a visualização gráfica na "
+"bandeja."
#: src/libslic3r/PrintConfig.cpp:505
msgid "Extruder Color"
diff --git a/resources/profiles/Creality.ini b/resources/profiles/Creality.ini
index 4ebf99d32..181bb4f4e 100644
--- a/resources/profiles/Creality.ini
+++ b/resources/profiles/Creality.ini
@@ -18,6 +18,9 @@ config_update_url = http://files.prusa3d.com/wp-content/uploads/repository/Prusa
name = Creality Ender-3
variants = 0.4
technology = FFF
+bed_model = ender3_bed.stl
+bed_texture = ender3.svg
+default_materials = Creality PLA @ENDER3; Prusament PLA @ENDER3
# All presets starting with asterisk, for example *common*, are intermediate and they will
# not make it into the user interface.
diff --git a/resources/icons/bed/ender3.svg b/resources/profiles/Creality/ender3.svg
similarity index 100%
rename from resources/icons/bed/ender3.svg
rename to resources/profiles/Creality/ender3.svg
diff --git a/resources/models/ender3_bed.stl b/resources/profiles/Creality/ender3_bed.stl
similarity index 100%
rename from resources/models/ender3_bed.stl
rename to resources/profiles/Creality/ender3_bed.stl
diff --git a/resources/profiles/PrusaResearch.ini b/resources/profiles/PrusaResearch.ini
index 746aaf966..4f5c0482b 100644
--- a/resources/profiles/PrusaResearch.ini
+++ b/resources/profiles/PrusaResearch.ini
@@ -22,72 +22,108 @@ name = Original Prusa MINI
variants = 0.4; 0.25; 0.6
technology = FFF
family = MINI
+bed_model = mini_bed.stl
+bed_texture = mini.svg
+default_materials = Prusament PLA; Prusament PETG @MINI
[printer_model:MK3S]
name = Original Prusa i3 MK3S
variants = 0.4; 0.25; 0.6
technology = FFF
family = MK3
+bed_model = mk3_bed.stl
+bed_texture = mk3.svg
+default_materials = Prusament PLA; Prusament PETG
[printer_model:MK3]
name = Original Prusa i3 MK3
variants = 0.4; 0.25; 0.6
technology = FFF
family = MK3
+bed_model = mk3_bed.stl
+bed_texture = mk3.svg
+default_materials = Prusament PLA; Prusament PETG
[printer_model:MK3SMMU2S]
name = Original Prusa i3 MK3S MMU2S
variants = 0.4; 0.25; 0.6
technology = FFF
family = MK3
+bed_model = mk3_bed.stl
+bed_texture = mk3.svg
+default_materials = Prusament PLA @MMU2; Prusament PETG @MMU2
[printer_model:MK3MMU2]
name = Original Prusa i3 MK3 MMU2
variants = 0.4; 0.25; 0.6
technology = FFF
family = MK3
+bed_model = mk3_bed.stl
+bed_texture = mk3.svg
+default_materials = Prusament PLA @MMU2; Prusament PETG @MMU2
[printer_model:MK2.5S]
name = Original Prusa i3 MK2.5S
variants = 0.4; 0.25; 0.6
technology = FFF
family = MK2.5
+bed_model = mk3_bed.stl
+bed_texture = mk3.svg
+default_materials = Prusament PLA; Prusament PETG
[printer_model:MK2.5]
name = Original Prusa i3 MK2.5
variants = 0.4; 0.25; 0.6
technology = FFF
family = MK2.5
+bed_model = mk3_bed.stl
+bed_texture = mk3.svg
+default_materials = Prusament PLA; Prusament PETG
[printer_model:MK2.5SMMU2S]
name = Original Prusa i3 MK2.5S MMU2S
variants = 0.4; 0.25; 0.6
technology = FFF
family = MK2.5
+bed_model = mk3_bed.stl
+bed_texture = mk3.svg
+default_materials = Prusament PLA @MMU2; Prusament PETG @MMU2
[printer_model:MK2.5MMU2]
name = Original Prusa i3 MK2.5 MMU2
variants = 0.4; 0.25; 0.6
technology = FFF
family = MK2.5
+bed_model = mk3_bed.stl
+bed_texture = mk3.svg
+default_materials = Prusament PLA @MMU2; Prusament PETG @MMU2
[printer_model:MK2S]
name = Original Prusa i3 MK2S
variants = 0.4; 0.25; 0.6
technology = FFF
family = MK2
+bed_model = mk2_bed.stl
+bed_texture = mk2.svg
+default_materials = Prusament PLA; Prusament PETG
[printer_model:MK2SMM]
name = Original Prusa i3 MK2S MMU1
variants = 0.4; 0.6
technology = FFF
family = MK2
+bed_model = mk2_bed.stl
+bed_texture = mk2.svg
+default_materials = Prusament PLA; Prusament PETG @MMU1
[printer_model:SL1]
name = Original Prusa SL1
variants = default
technology = SLA
family = SL1
+bed_model = sl1_bed.stl
+bed_texture = sl1.svg
+default_materials = Prusa Transparent Tough @0.05
# All presets starting with asterisk, for example *common*, are intermediate and they will
# not make it into the user interface.
diff --git a/resources/icons/bed/mini.svg b/resources/profiles/PrusaResearch/mini.svg
similarity index 100%
rename from resources/icons/bed/mini.svg
rename to resources/profiles/PrusaResearch/mini.svg
diff --git a/resources/models/mini_bed.stl b/resources/profiles/PrusaResearch/mini_bed.stl
similarity index 100%
rename from resources/models/mini_bed.stl
rename to resources/profiles/PrusaResearch/mini_bed.stl
diff --git a/resources/icons/bed/mk2.svg b/resources/profiles/PrusaResearch/mk2.svg
similarity index 100%
rename from resources/icons/bed/mk2.svg
rename to resources/profiles/PrusaResearch/mk2.svg
diff --git a/resources/models/mk2_bed.stl b/resources/profiles/PrusaResearch/mk2_bed.stl
similarity index 100%
rename from resources/models/mk2_bed.stl
rename to resources/profiles/PrusaResearch/mk2_bed.stl
diff --git a/resources/icons/bed/mk3.svg b/resources/profiles/PrusaResearch/mk3.svg
similarity index 100%
rename from resources/icons/bed/mk3.svg
rename to resources/profiles/PrusaResearch/mk3.svg
diff --git a/resources/models/mk3_bed.stl b/resources/profiles/PrusaResearch/mk3_bed.stl
similarity index 100%
rename from resources/models/mk3_bed.stl
rename to resources/profiles/PrusaResearch/mk3_bed.stl
diff --git a/resources/icons/bed/sl1.svg b/resources/profiles/PrusaResearch/sl1.svg
similarity index 100%
rename from resources/icons/bed/sl1.svg
rename to resources/profiles/PrusaResearch/sl1.svg
diff --git a/resources/models/sl1_bed.stl b/resources/profiles/PrusaResearch/sl1_bed.stl
similarity index 100%
rename from resources/models/sl1_bed.stl
rename to resources/profiles/PrusaResearch/sl1_bed.stl
diff --git a/src/PrusaSlicer.cpp b/src/PrusaSlicer.cpp
index d755f0b2e..28aadc045 100644
--- a/src/PrusaSlicer.cpp
+++ b/src/PrusaSlicer.cpp
@@ -641,10 +641,18 @@ bool CLI::export_models(IO::ExportFormat format)
const std::string path = this->output_filepath(model, format);
bool success = false;
switch (format) {
+#if ENABLE_CONFIGURABLE_PATHS_EXPORT_TO_3MF_AND_AMF
+ case IO::AMF: success = Slic3r::store_amf(path.c_str(), &model, nullptr, false); break;
+#else
case IO::AMF: success = Slic3r::store_amf(path.c_str(), &model, nullptr); break;
+#endif // ENABLE_CONFIGURABLE_PATHS_EXPORT_TO_3MF_AND_AMF
case IO::OBJ: success = Slic3r::store_obj(path.c_str(), &model); break;
case IO::STL: success = Slic3r::store_stl(path.c_str(), &model, true); break;
+#if ENABLE_CONFIGURABLE_PATHS_EXPORT_TO_3MF_AND_AMF
+ case IO::TMF: success = Slic3r::store_3mf(path.c_str(), &model, nullptr, false); break;
+#else
case IO::TMF: success = Slic3r::store_3mf(path.c_str(), &model, nullptr); break;
+#endif // ENABLE_CONFIGURABLE_PATHS_EXPORT_TO_3MF_AND_AMF
default: assert(false); break;
}
if (success)
diff --git a/src/libnest2d/CMakeLists.txt b/src/libnest2d/CMakeLists.txt
index 6484da3d0..592ab069c 100644
--- a/src/libnest2d/CMakeLists.txt
+++ b/src/libnest2d/CMakeLists.txt
@@ -24,7 +24,7 @@ set(LIBNEST2D_SRCFILES
src/libnest2d.cpp
)
-add_library(libnest2d ${LIBNEST2D_SRCFILES})
+add_library(libnest2d STATIC ${LIBNEST2D_SRCFILES})
target_include_directories(libnest2d PUBLIC ${CMAKE_CURRENT_LIST_DIR}/include)
target_link_libraries(libnest2d PUBLIC clipper NLopt::nlopt TBB::tbb Boost::boost)
diff --git a/src/libnest2d/include/libnest2d/placers/nfpplacer.hpp b/src/libnest2d/include/libnest2d/placers/nfpplacer.hpp
index 003028758..e44e1dae1 100644
--- a/src/libnest2d/include/libnest2d/placers/nfpplacer.hpp
+++ b/src/libnest2d/include/libnest2d/placers/nfpplacer.hpp
@@ -1116,12 +1116,8 @@ private:
for(Item& item : items_) item.translate(d);
}
- void setInitialPosition(Item& item) {
- auto sh = item.rawShape();
- sl::translate(sh, item.translation());
- sl::rotate(sh, item.rotation());
-
- Box bb = sl::boundingBox(sh);
+ void setInitialPosition(Item& item) {
+ Box bb = item.boundingBox();
Vertex ci, cb;
auto bbin = sl::boundingBox(bin_);
diff --git a/src/libslic3r/Config.hpp b/src/libslic3r/Config.hpp
index 87a79d93f..9b04ae026 100644
--- a/src/libslic3r/Config.hpp
+++ b/src/libslic3r/Config.hpp
@@ -289,13 +289,13 @@ public:
throw std::runtime_error("ConfigOptionVector::set_at(): Assigning an incompatible type");
}
- T& get_at(size_t i)
+ const T& get_at(size_t i) const
{
assert(! this->values.empty());
return (i < this->values.size()) ? this->values[i] : this->values.front();
}
- const T& get_at(size_t i) const { return const_cast*>(this)->get_at(i); }
+ T& get_at(size_t i) { return const_cast(std::as_const(*this).get_at(i)); }
// Resize this vector by duplicating the /*last*/first value.
// If the current vector is empty, the default value is used instead.
@@ -500,7 +500,7 @@ public:
if (NULLABLE)
this->values.push_back(nil_value());
else
- std::runtime_error("Deserializing nil into a non-nullable object");
+ throw std::runtime_error("Deserializing nil into a non-nullable object");
} else {
std::istringstream iss(item_str);
double value;
@@ -525,9 +525,9 @@ protected:
if (NULLABLE)
ss << "nil";
else
- std::runtime_error("Serializing NaN");
+ throw std::runtime_error("Serializing NaN");
} else
- std::runtime_error("Serializing invalid number");
+ throw std::runtime_error("Serializing invalid number");
}
static bool vectors_equal(const std::vector &v1, const std::vector &v2) {
if (NULLABLE) {
@@ -646,7 +646,7 @@ public:
if (NULLABLE)
this->values.push_back(nil_value());
else
- std::runtime_error("Deserializing nil into a non-nullable object");
+ throw std::runtime_error("Deserializing nil into a non-nullable object");
} else {
std::istringstream iss(item_str);
int value;
@@ -663,7 +663,7 @@ private:
if (NULLABLE)
ss << "nil";
else
- std::runtime_error("Serializing NaN");
+ throw std::runtime_error("Serializing NaN");
} else
ss << v;
}
@@ -1126,7 +1126,7 @@ public:
if (NULLABLE)
this->values.push_back(nil_value());
else
- std::runtime_error("Deserializing nil into a non-nullable object");
+ throw std::runtime_error("Deserializing nil into a non-nullable object");
} else
this->values.push_back(item_str.compare("1") == 0);
}
@@ -1139,7 +1139,7 @@ protected:
if (NULLABLE)
ss << "nil";
else
- std::runtime_error("Serializing NaN");
+ throw std::runtime_error("Serializing NaN");
} else
ss << (v ? "1" : "0");
}
@@ -1638,7 +1638,7 @@ class DynamicConfig : public virtual ConfigBase
public:
DynamicConfig() {}
DynamicConfig(const DynamicConfig &rhs) { *this = rhs; }
- DynamicConfig(DynamicConfig &&rhs) : options(std::move(rhs.options)) { rhs.options.clear(); }
+ DynamicConfig(DynamicConfig &&rhs) noexcept : options(std::move(rhs.options)) { rhs.options.clear(); }
explicit DynamicConfig(const ConfigBase &rhs, const t_config_option_keys &keys);
explicit DynamicConfig(const ConfigBase& rhs) : DynamicConfig(rhs, rhs.keys()) {}
virtual ~DynamicConfig() override { clear(); }
@@ -1656,7 +1656,7 @@ public:
// Move a content of one DynamicConfig to another DynamicConfig.
// If rhs.def() is not null, then it has to be equal to this->def().
- DynamicConfig& operator=(DynamicConfig &&rhs)
+ DynamicConfig& operator=(DynamicConfig &&rhs) noexcept
{
assert(this->def() == nullptr || this->def() == rhs.def());
this->clear();
diff --git a/src/libslic3r/ExPolygon.hpp b/src/libslic3r/ExPolygon.hpp
index 4ee8974f4..7c0dfcce5 100644
--- a/src/libslic3r/ExPolygon.hpp
+++ b/src/libslic3r/ExPolygon.hpp
@@ -19,7 +19,7 @@ class ExPolygon
public:
ExPolygon() {}
ExPolygon(const ExPolygon &other) : contour(other.contour), holes(other.holes) {}
- ExPolygon(ExPolygon &&other) : contour(std::move(other.contour)), holes(std::move(other.holes)) {}
+ ExPolygon(ExPolygon &&other) noexcept : contour(std::move(other.contour)), holes(std::move(other.holes)) {}
explicit ExPolygon(const Polygon &contour) : contour(contour) {}
explicit ExPolygon(Polygon &&contour) : contour(std::move(contour)) {}
explicit ExPolygon(const Points &contour) : contour(contour) {}
@@ -32,7 +32,7 @@ public:
ExPolygon(std::initializer_list contour, std::initializer_list hole) : contour(contour), holes({ hole }) {}
ExPolygon& operator=(const ExPolygon &other) { contour = other.contour; holes = other.holes; return *this; }
- ExPolygon& operator=(ExPolygon &&other) { contour = std::move(other.contour); holes = std::move(other.holes); return *this; }
+ ExPolygon& operator=(ExPolygon &&other) noexcept { contour = std::move(other.contour); holes = std::move(other.holes); return *this; }
Polygon contour;
Polygons holes;
diff --git a/src/libslic3r/Extruder.hpp b/src/libslic3r/Extruder.hpp
index df92bf84b..066a5f56d 100644
--- a/src/libslic3r/Extruder.hpp
+++ b/src/libslic3r/Extruder.hpp
@@ -48,9 +48,6 @@ public:
double retract_length_toolchange() const;
double retract_restart_extra_toolchange() const;
- // Constructor for a key object, to be used by the stdlib search functions.
- static Extruder key(unsigned int id) { return Extruder(id); }
-
private:
// Private constructor to create a key for a search in std::set.
Extruder(unsigned int id) : m_id(id) {}
diff --git a/src/libslic3r/ExtrusionEntityCollection.cpp b/src/libslic3r/ExtrusionEntityCollection.cpp
index e1a9709d1..147a60d95 100644
--- a/src/libslic3r/ExtrusionEntityCollection.cpp
+++ b/src/libslic3r/ExtrusionEntityCollection.cpp
@@ -6,6 +6,26 @@
namespace Slic3r {
+void filter_by_extrusion_role_in_place(ExtrusionEntitiesPtr &extrusion_entities, ExtrusionRole role)
+{
+ if (role != erMixed) {
+ auto first = extrusion_entities.begin();
+ auto last = extrusion_entities.end();
+ auto result = first;
+ while (first != last) {
+ // The caller wants only paths with a specific extrusion role.
+ auto role2 = (*first)->role();
+ if (role != role2) {
+ // This extrusion entity does not match the role asked.
+ assert(role2 != erMixed);
+ *result = *first;
+ ++ result;
+ }
+ ++ first;
+ }
+ }
+}
+
ExtrusionEntityCollection::ExtrusionEntityCollection(const ExtrusionPaths &paths)
: no_sort(false)
{
@@ -74,31 +94,16 @@ void ExtrusionEntityCollection::remove(size_t i)
this->entities.erase(this->entities.begin() + i);
}
-ExtrusionEntityCollection ExtrusionEntityCollection::chained_path_from(const Point &start_near, ExtrusionRole role) const
+ExtrusionEntityCollection ExtrusionEntityCollection::chained_path_from(const ExtrusionEntitiesPtr& extrusion_entities, const Point &start_near, ExtrusionRole role)
{
- ExtrusionEntityCollection out;
- if (this->no_sort) {
- out = *this;
- } else {
- if (role == erMixed)
- out = *this;
- else {
- for (const ExtrusionEntity *ee : this->entities) {
- if (role != erMixed) {
- // The caller wants only paths with a specific extrusion role.
- auto role2 = ee->role();
- if (role != role2) {
- // This extrusion entity does not match the role asked.
- assert(role2 != erMixed);
- continue;
- }
- }
- out.entities.emplace_back(ee->clone());
- }
- }
- chain_and_reorder_extrusion_entities(out.entities, &start_near);
- }
- return out;
+ // Return a filtered copy of the collection.
+ ExtrusionEntityCollection out;
+ out.entities = filter_by_extrusion_role(extrusion_entities, role);
+ // Clone the extrusion entities.
+ for (auto &ptr : out.entities)
+ ptr = ptr->clone();
+ chain_and_reorder_extrusion_entities(out.entities, &start_near);
+ return out;
}
void ExtrusionEntityCollection::polygons_covered_by_width(Polygons &out, const float scaled_epsilon) const
diff --git a/src/libslic3r/ExtrusionEntityCollection.hpp b/src/libslic3r/ExtrusionEntityCollection.hpp
index 3084e5741..8aacb4d46 100644
--- a/src/libslic3r/ExtrusionEntityCollection.hpp
+++ b/src/libslic3r/ExtrusionEntityCollection.hpp
@@ -6,6 +6,21 @@
namespace Slic3r {
+// Remove those items from extrusion_entities, that do not match role.
+// Do nothing if role is mixed.
+// Removed elements are NOT being deleted.
+void filter_by_extrusion_role_in_place(ExtrusionEntitiesPtr &extrusion_entities, ExtrusionRole role);
+
+// Return new vector of ExtrusionEntities* with only those items from input extrusion_entities, that match role.
+// Return all extrusion entities if role is mixed.
+// Returned extrusion entities are shared with the source vector, they are NOT cloned, they are considered to be owned by extrusion_entities.
+inline ExtrusionEntitiesPtr filter_by_extrusion_role(const ExtrusionEntitiesPtr &extrusion_entities, ExtrusionRole role)
+{
+ ExtrusionEntitiesPtr out { extrusion_entities };
+ filter_by_extrusion_role_in_place(out, role);
+ return out;
+}
+
class ExtrusionEntityCollection : public ExtrusionEntity
{
public:
@@ -65,7 +80,9 @@ public:
}
void replace(size_t i, const ExtrusionEntity &entity);
void remove(size_t i);
- ExtrusionEntityCollection chained_path_from(const Point &start_near, ExtrusionRole role = erMixed) const;
+ static ExtrusionEntityCollection chained_path_from(const ExtrusionEntitiesPtr &extrusion_entities, const Point &start_near, ExtrusionRole role = erMixed);
+ ExtrusionEntityCollection chained_path_from(const Point &start_near, ExtrusionRole role = erMixed) const
+ { return this->no_sort ? *this : chained_path_from(this->entities, start_near, role); }
void reverse();
const Point& first_point() const { return this->entities.front()->first_point(); }
const Point& last_point() const { return this->entities.back()->last_point(); }
@@ -105,6 +122,6 @@ public:
}
};
-}
+} // namespace Slic3r
#endif
diff --git a/src/libslic3r/Flow.cpp b/src/libslic3r/Flow.cpp
index 6069677a1..2c5c64fe7 100644
--- a/src/libslic3r/Flow.cpp
+++ b/src/libslic3r/Flow.cpp
@@ -107,9 +107,9 @@ double Flow::mm3_per_mm() const
{
float res = this->bridge ?
// Area of a circle with dmr of this->width.
- (this->width * this->width) * 0.25 * PI :
+ float((this->width * this->width) * 0.25 * PI) :
// Rectangle with semicircles at the ends. ~ h (w - 0.215 h)
- this->height * (this->width - this->height * (1. - 0.25 * PI));
+ float(this->height * (this->width - this->height * (1. - 0.25 * PI)));
//assert(res > 0.);
if (res <= 0.)
throw std::runtime_error("Flow::mm3_per_mm() produced negative flow. Did you set some extrusion width too small?");
diff --git a/src/libslic3r/Format/3mf.cpp b/src/libslic3r/Format/3mf.cpp
index b3ccc44b9..de7b26f04 100644
--- a/src/libslic3r/Format/3mf.cpp
+++ b/src/libslic3r/Format/3mf.cpp
@@ -1187,7 +1187,7 @@ namespace Slic3r {
return;
pt::ptree code_tree = main_tree.front().second;
- m_model->custom_gcode_per_print_z.clear();
+ m_model->custom_gcode_per_print_z.gcodes.clear();
for (const auto& code : code_tree)
{
@@ -1199,7 +1199,7 @@ namespace Slic3r {
int extruder = tree.get (".extruder" );
std::string color = tree.get (".color" );
- m_model->custom_gcode_per_print_z.push_back(Model::CustomGCode{print_z, gcode, extruder, color}) ;
+ m_model->custom_gcode_per_print_z.gcodes.push_back(Model::CustomGCode{print_z, gcode, extruder, color}) ;
}
}
}
@@ -1816,9 +1816,6 @@ namespace Slic3r {
break;
}
}
-#if !ENABLE_KEEP_LOADED_VOLUME_TRANSFORM_AS_STAND_ALONE
- Transform3d inv_matrix = volume_matrix_to_object.inverse();
-#endif // !ENABLE_KEEP_LOADED_VOLUME_TRANSFORM_AS_STAND_ALONE
// splits volume out of imported geometry
TriangleMesh triangle_mesh;
@@ -1838,15 +1835,7 @@ namespace Slic3r {
for (unsigned int v = 0; v < 3; ++v)
{
unsigned int tri_id = geometry.triangles[src_start_id + ii + v] * 3;
-#if ENABLE_KEEP_LOADED_VOLUME_TRANSFORM_AS_STAND_ALONE
facet.vertex[v] = Vec3f(geometry.vertices[tri_id + 0], geometry.vertices[tri_id + 1], geometry.vertices[tri_id + 2]);
-#else
- Vec3f vertex(geometry.vertices[tri_id + 0], geometry.vertices[tri_id + 1], geometry.vertices[tri_id + 2]);
- facet.vertex[v] = has_transform ?
- // revert the vertices to the original mesh reference system
- (inv_matrix * vertex.cast()).cast() :
- vertex;
-#endif // ENABLE_KEEP_LOADED_VOLUME_TRANSFORM_AS_STAND_ALONE
}
}
@@ -1854,15 +1843,9 @@ namespace Slic3r {
triangle_mesh.repair();
ModelVolume* volume = object.add_volume(std::move(triangle_mesh));
-#if ENABLE_KEEP_LOADED_VOLUME_TRANSFORM_AS_STAND_ALONE
// stores the volume matrix taken from the metadata, if present
if (has_transform)
volume->source.transform = Slic3r::Geometry::Transformation(volume_matrix_to_object);
-#else
- // apply the volume matrix taken from the metadata, if present
- if (has_transform)
- volume->set_transformation(Slic3r::Geometry::Transformation(volume_matrix_to_object));
-#endif //ENABLE_KEEP_LOADED_VOLUME_TRANSFORM_AS_STAND_ALONE
volume->calculate_convex_hull();
// apply the remaining volume's metadata
@@ -1975,12 +1958,24 @@ namespace Slic3r {
typedef std::vector BuildItemsList;
typedef std::map IdToObjectDataMap;
+#if ENABLE_CONFIGURABLE_PATHS_EXPORT_TO_3MF_AND_AMF
+ bool m_fullpath_sources{ true };
+#endif // ENABLE_CONFIGURABLE_PATHS_EXPORT_TO_3MF_AND_AMF
+
public:
+#if ENABLE_CONFIGURABLE_PATHS_EXPORT_TO_3MF_AND_AMF
+#if ENABLE_THUMBNAIL_GENERATOR
+ bool save_model_to_file(const std::string& filename, Model& model, const DynamicPrintConfig* config, bool fullpath_sources, const ThumbnailData* thumbnail_data = nullptr);
+#else
+ bool save_model_to_file(const std::string& filename, Model& model, const DynamicPrintConfig* config, bool fullpath_sources);
+#endif // ENABLE_THUMBNAIL_GENERATOR
+#else
#if ENABLE_THUMBNAIL_GENERATOR
bool save_model_to_file(const std::string& filename, Model& model, const DynamicPrintConfig* config, const ThumbnailData* thumbnail_data = nullptr);
#else
bool save_model_to_file(const std::string& filename, Model& model, const DynamicPrintConfig* config);
#endif // ENABLE_THUMBNAIL_GENERATOR
+#endif // ENABLE_CONFIGURABLE_PATHS_EXPORT_TO_3MF_AND_AMF
private:
#if ENABLE_THUMBNAIL_GENERATOR
@@ -2006,6 +2001,22 @@ namespace Slic3r {
bool _add_custom_gcode_per_print_z_file_to_archive(mz_zip_archive& archive, Model& model);
};
+#if ENABLE_CONFIGURABLE_PATHS_EXPORT_TO_3MF_AND_AMF
+#if ENABLE_THUMBNAIL_GENERATOR
+ bool _3MF_Exporter::save_model_to_file(const std::string& filename, Model& model, const DynamicPrintConfig* config, bool fullpath_sources, const ThumbnailData* thumbnail_data)
+ {
+ clear_errors();
+ m_fullpath_sources = fullpath_sources;
+ return _save_model_to_file(filename, model, config, thumbnail_data);
+ }
+#else
+ bool _3MF_Exporter::save_model_to_file(const std::string& filename, Model& model, const DynamicPrintConfig* config, bool fullpath_sources)
+ {
+ clear_errors();
+ return _save_model_to_file(filename, model, config);
+ }
+#endif // ENABLE_THUMBNAIL_GENERATOR
+#else
#if ENABLE_THUMBNAIL_GENERATOR
bool _3MF_Exporter::save_model_to_file(const std::string& filename, Model& model, const DynamicPrintConfig* config, const ThumbnailData* thumbnail_data)
{
@@ -2019,6 +2030,7 @@ namespace Slic3r {
return _save_model_to_file(filename, model, config);
}
#endif // ENABLE_THUMBNAIL_GENERATOR
+#endif // ENABLE_CONFIGURABLE_PATHS_EXPORT_TO_3MF_AND_AMF
#if ENABLE_THUMBNAIL_GENERATOR
bool _3MF_Exporter::_save_model_to_file(const std::string& filename, Model& model, const DynamicPrintConfig* config, const ThumbnailData* thumbnail_data)
@@ -2690,11 +2702,7 @@ namespace Slic3r {
// stores volume's local matrix
stream << " <" << METADATA_TAG << " " << TYPE_ATTR << "=\"" << VOLUME_TYPE << "\" " << KEY_ATTR << "=\"" << MATRIX_KEY << "\" " << VALUE_ATTR << "=\"";
-#if ENABLE_KEEP_LOADED_VOLUME_TRANSFORM_AS_STAND_ALONE
Transform3d matrix = volume->get_matrix() * volume->source.transform.get_matrix();
-#else
- const Transform3d& matrix = volume->get_matrix();
-#endif // ENABLE_KEEP_LOADED_VOLUME_TRANSFORM_AS_STAND_ALONE
for (int r = 0; r < 4; ++r)
{
for (int c = 0; c < 4; ++c)
@@ -2709,7 +2717,12 @@ namespace Slic3r {
// stores volume's source data
if (!volume->source.input_file.empty())
{
+#if ENABLE_CONFIGURABLE_PATHS_EXPORT_TO_3MF_AND_AMF
+ std::string input_file = xml_escape(m_fullpath_sources ? volume->source.input_file : boost::filesystem::path(volume->source.input_file).filename().string());
+ stream << " <" << METADATA_TAG << " " << TYPE_ATTR << "=\"" << VOLUME_TYPE << "\" " << KEY_ATTR << "=\"" << SOURCE_FILE_KEY << "\" " << VALUE_ATTR << "=\"" << input_file << "\"/>\n";
+#else
stream << " <" << METADATA_TAG << " " << TYPE_ATTR << "=\"" << VOLUME_TYPE << "\" " << KEY_ATTR << "=\"" << SOURCE_FILE_KEY << "\" " << VALUE_ATTR << "=\"" << xml_escape(volume->source.input_file) << "\"/>\n";
+#endif // ENABLE_CONFIGURABLE_PATHS_EXPORT_TO_3MF_AND_AMF
stream << " <" << METADATA_TAG << " " << TYPE_ATTR << "=\"" << VOLUME_TYPE << "\" " << KEY_ATTR << "=\"" << SOURCE_OBJECT_ID_KEY << "\" " << VALUE_ATTR << "=\"" << volume->source.object_idx << "\"/>\n";
stream << " <" << METADATA_TAG << " " << TYPE_ATTR << "=\"" << VOLUME_TYPE << "\" " << KEY_ATTR << "=\"" << SOURCE_VOLUME_ID_KEY << "\" " << VALUE_ATTR << "=\"" << volume->source.volume_idx << "\"/>\n";
stream << " <" << METADATA_TAG << " " << TYPE_ATTR << "=\"" << VOLUME_TYPE << "\" " << KEY_ATTR << "=\"" << SOURCE_OFFSET_X_KEY << "\" " << VALUE_ATTR << "=\"" << volume->source.mesh_offset(0) << "\"/>\n";
@@ -2749,12 +2762,12 @@ bool _3MF_Exporter::_add_custom_gcode_per_print_z_file_to_archive( mz_zip_archiv
{
std::string out = "";
- if (!model.custom_gcode_per_print_z.empty())
+ if (!model.custom_gcode_per_print_z.gcodes.empty())
{
pt::ptree tree;
pt::ptree& main_tree = tree.add("custom_gcodes_per_print_z", "");
- for (const Model::CustomGCode& code : model.custom_gcode_per_print_z)
+ for (const Model::CustomGCode& code : model.custom_gcode_per_print_z.gcodes)
{
pt::ptree& code_tree = main_tree.add("code", "");
// store minX and maxZ
@@ -2798,21 +2811,37 @@ bool load_3mf(const char* path, DynamicPrintConfig* config, Model* model, bool c
return res;
}
+#if ENABLE_CONFIGURABLE_PATHS_EXPORT_TO_3MF_AND_AMF
+#if ENABLE_THUMBNAIL_GENERATOR
+bool store_3mf(const char* path, Model* model, const DynamicPrintConfig* config, bool fullpath_sources, const ThumbnailData* thumbnail_data)
+#else
+bool store_3mf(const char* path, Model* model, const DynamicPrintConfig* config, bool fullpath_sources)
+#endif // ENABLE_THUMBNAIL_GENERATOR
+#else
#if ENABLE_THUMBNAIL_GENERATOR
bool store_3mf(const char* path, Model* model, const DynamicPrintConfig* config, const ThumbnailData* thumbnail_data)
#else
bool store_3mf(const char* path, Model* model, const DynamicPrintConfig* config)
#endif // ENABLE_THUMBNAIL_GENERATOR
+#endif // ENABLE_CONFIGURABLE_PATHS_EXPORT_TO_3MF_AND_AMF
{
if ((path == nullptr) || (model == nullptr))
return false;
_3MF_Exporter exporter;
+#if ENABLE_CONFIGURABLE_PATHS_EXPORT_TO_3MF_AND_AMF
+#if ENABLE_THUMBNAIL_GENERATOR
+ bool res = exporter.save_model_to_file(path, *model, config, fullpath_sources, thumbnail_data);
+#else
+ bool res = exporter.save_model_to_file(path, *model, config, fullpath_sources);
+#endif // ENABLE_THUMBNAIL_GENERATOR
+#else
#if ENABLE_THUMBNAIL_GENERATOR
bool res = exporter.save_model_to_file(path, *model, config, thumbnail_data);
#else
bool res = exporter.save_model_to_file(path, *model, config);
#endif // ENABLE_THUMBNAIL_GENERATOR
+#endif // ENABLE_CONFIGURABLE_PATHS_EXPORT_TO_3MF_AND_AMF
if (!res)
exporter.log_errors();
diff --git a/src/libslic3r/Format/3mf.hpp b/src/libslic3r/Format/3mf.hpp
index 7da0ce7fc..79ac61a23 100644
--- a/src/libslic3r/Format/3mf.hpp
+++ b/src/libslic3r/Format/3mf.hpp
@@ -35,11 +35,19 @@ namespace Slic3r {
// Save the given model and the config data contained in the given Print into a 3mf file.
// The model could be modified during the export process if meshes are not repaired or have no shared vertices
+#if ENABLE_CONFIGURABLE_PATHS_EXPORT_TO_3MF_AND_AMF
+#if ENABLE_THUMBNAIL_GENERATOR
+ extern bool store_3mf(const char* path, Model* model, const DynamicPrintConfig* config, bool fullpath_sources, const ThumbnailData* thumbnail_data = nullptr);
+#else
+ extern bool store_3mf(const char* path, Model* model, const DynamicPrintConfig* config, bool fullpath_sources);
+#endif // ENABLE_THUMBNAIL_GENERATOR
+#else
#if ENABLE_THUMBNAIL_GENERATOR
extern bool store_3mf(const char* path, Model* model, const DynamicPrintConfig* config, const ThumbnailData* thumbnail_data = nullptr);
#else
extern bool store_3mf(const char* path, Model* model, const DynamicPrintConfig* config);
#endif // ENABLE_THUMBNAIL_GENERATOR
+#endif // ENABLE_CONFIGURABLE_PATHS_EXPORT_TO_3MF_AND_AMF
}; // namespace Slic3r
diff --git a/src/libslic3r/Format/AMF.cpp b/src/libslic3r/Format/AMF.cpp
index 5b65d8fa2..7041956ba 100644
--- a/src/libslic3r/Format/AMF.cpp
+++ b/src/libslic3r/Format/AMF.cpp
@@ -585,36 +585,20 @@ void AMFParserContext::endElement(const char * /* name */)
stl_allocate(&stl);
bool has_transform = ! m_volume_transform.isApprox(Transform3d::Identity(), 1e-10);
-#if !ENABLE_KEEP_LOADED_VOLUME_TRANSFORM_AS_STAND_ALONE
- Transform3d inv_matrix = m_volume_transform.inverse();
-#endif // !ENABLE_KEEP_LOADED_VOLUME_TRANSFORM_AS_STAND_ALONE
for (size_t i = 0; i < m_volume_facets.size();) {
stl_facet &facet = stl.facet_start[i/3];
for (unsigned int v = 0; v < 3; ++v)
{
unsigned int tri_id = m_volume_facets[i++] * 3;
-#if ENABLE_KEEP_LOADED_VOLUME_TRANSFORM_AS_STAND_ALONE
facet.vertex[v] = Vec3f(m_object_vertices[tri_id + 0], m_object_vertices[tri_id + 1], m_object_vertices[tri_id + 2]);
-#else
- Vec3f vertex(m_object_vertices[tri_id + 0], m_object_vertices[tri_id + 1], m_object_vertices[tri_id + 2]);
- facet.vertex[v] = has_transform ?
- // revert the vertices to the original mesh reference system
- (inv_matrix * vertex.cast()).cast() :
- vertex;
-#endif // ENABLE_KEEP_LOADED_VOLUME_TRANSFORM_AS_STAND_ALONE
}
}
stl_get_size(&stl);
mesh.repair();
m_volume->set_mesh(std::move(mesh));
-#if ENABLE_KEEP_LOADED_VOLUME_TRANSFORM_AS_STAND_ALONE
// stores the volume matrix taken from the metadata, if present
if (has_transform)
m_volume->source.transform = Slic3r::Geometry::Transformation(m_volume_transform);
-#else
- if (has_transform)
- m_volume->set_transformation(m_volume_transform);
-#endif // ENABLE_KEEP_LOADED_VOLUME_TRANSFORM_AS_STAND_ALONE
if (m_volume->source.input_file.empty() && (m_volume->type() == ModelVolumeType::MODEL_PART))
{
m_volume->source.object_idx = (int)m_model.objects.size() - 1;
@@ -653,7 +637,7 @@ void AMFParserContext::endElement(const char * /* name */)
int extruder = atoi(m_value[2].c_str());
const std::string& color = m_value[3];
- m_model.custom_gcode_per_print_z.push_back(Model::CustomGCode{height, gcode, extruder, color});
+ m_model.custom_gcode_per_print_z.gcodes.push_back(Model::CustomGCode{height, gcode, extruder, color});
for (std::string& val: m_value)
val.clear();
@@ -1019,7 +1003,11 @@ bool load_amf(const char* path, DynamicPrintConfig* config, Model* model, bool c
return false;
}
+#if ENABLE_CONFIGURABLE_PATHS_EXPORT_TO_3MF_AND_AMF
+bool store_amf(const char* path, Model* model, const DynamicPrintConfig* config, bool fullpath_sources)
+#else
bool store_amf(const char *path, Model *model, const DynamicPrintConfig *config)
+#endif // ENABLE_CONFIGURABLE_PATHS_EXPORT_TO_3MF_AND_AMF
{
if ((path == nullptr) || (model == nullptr))
return false;
@@ -1159,11 +1147,7 @@ bool store_amf(const char *path, Model *model, const DynamicPrintConfig *config)
stream << " 1\n";
stream << " " << ModelVolume::type_to_string(volume->type()) << "\n";
stream << " ";
-#if ENABLE_KEEP_LOADED_VOLUME_TRANSFORM_AS_STAND_ALONE
const Transform3d& matrix = volume->get_matrix() * volume->source.transform.get_matrix();
-#else
- const Transform3d& matrix = volume->get_matrix();
-#endif // ENABLE_KEEP_LOADED_VOLUME_TRANSFORM_AS_STAND_ALONE
stream << std::setprecision(std::numeric_limits::max_digits10);
for (int r = 0; r < 4; ++r)
{
@@ -1177,7 +1161,12 @@ bool store_amf(const char *path, Model *model, const DynamicPrintConfig *config)
stream << "\n";
if (!volume->source.input_file.empty())
{
+#if ENABLE_CONFIGURABLE_PATHS_EXPORT_TO_3MF_AND_AMF
+ std::string input_file = xml_escape(fullpath_sources ? volume->source.input_file : boost::filesystem::path(volume->source.input_file).filename().string());
+ stream << " " << input_file << "\n";
+#else
stream << " " << xml_escape(volume->source.input_file) << "\n";
+#endif // ENABLE_CONFIGURABLE_PATHS_EXPORT_TO_3MF_AND_AMF
stream << " " << volume->source.object_idx << "\n";
stream << " " << volume->source.volume_idx << "\n";
stream << " " << volume->source.mesh_offset(0) << "\n";
@@ -1241,14 +1230,14 @@ bool store_amf(const char *path, Model *model, const DynamicPrintConfig *config)
stream << " \n";
}
- if (!model->custom_gcode_per_print_z.empty())
+ if (!model->custom_gcode_per_print_z.gcodes.empty())
{
std::string out = "";
pt::ptree tree;
pt::ptree& main_tree = tree.add("custom_gcodes_per_height", "");
- for (const Model::CustomGCode& code : model->custom_gcode_per_print_z)
+ for (const Model::CustomGCode& code : model->custom_gcode_per_print_z.gcodes)
{
pt::ptree& code_tree = main_tree.add("code", "");
// store minX and maxZ
diff --git a/src/libslic3r/Format/AMF.hpp b/src/libslic3r/Format/AMF.hpp
index 1206d60d0..7404e1e90 100644
--- a/src/libslic3r/Format/AMF.hpp
+++ b/src/libslic3r/Format/AMF.hpp
@@ -11,7 +11,11 @@ extern bool load_amf(const char* path, DynamicPrintConfig* config, Model* model,
// Save the given model and the config data into an amf file.
// The model could be modified during the export process if meshes are not repaired or have no shared vertices
+#if ENABLE_CONFIGURABLE_PATHS_EXPORT_TO_3MF_AND_AMF
+extern bool store_amf(const char* path, Model* model, const DynamicPrintConfig* config, bool fullpath_sources);
+#else
extern bool store_amf(const char *path, Model *model, const DynamicPrintConfig *config);
+#endif // ENABLE_CONFIGURABLE_PATHS_EXPORT_TO_3MF_AND_AMF
}; // namespace Slic3r
diff --git a/src/libslic3r/GCode.cpp b/src/libslic3r/GCode.cpp
index 40ca7b074..517b5281b 100644
--- a/src/libslic3r/GCode.cpp
+++ b/src/libslic3r/GCode.cpp
@@ -12,6 +12,7 @@
#include
#include
#include
+#include
#include
#include
@@ -34,6 +35,8 @@
#include "miniz_extension.hpp"
+using namespace std::literals::string_view_literals;
+
#if 0
// Enable debugging and asserts, even in the release build.
#define DEBUG
@@ -792,6 +795,297 @@ void GCode::do_export(Print *print, const char *path, GCodePreviewData *preview_
PROFILE_OUTPUT(debug_out_path("gcode-export-profile.txt").c_str());
}
+// free functions called by GCode::_do_export()
+namespace DoExport {
+ static void init_time_estimators(const PrintConfig &config, GCodeTimeEstimator &normal_time_estimator, GCodeTimeEstimator &silent_time_estimator, bool &silent_time_estimator_enabled)
+ {
+ // resets time estimators
+ normal_time_estimator.reset();
+ normal_time_estimator.set_dialect(config.gcode_flavor);
+ normal_time_estimator.set_extrusion_axis(config.get_extrusion_axis()[0]);
+ silent_time_estimator_enabled = (config.gcode_flavor == gcfMarlin) && config.silent_mode;
+
+ // Until we have a UI support for the other firmwares than the Marlin, use the hardcoded default values
+ // and let the user to enter the G-code limits into the start G-code.
+ // If the following block is enabled for other firmwares than the Marlin, then the function
+ // this->print_machine_envelope(file, print);
+ // shall be adjusted as well to produce a G-code block compatible with the particular firmware flavor.
+ if (config.gcode_flavor.value == gcfMarlin) {
+ normal_time_estimator.set_max_acceleration((float)config.machine_max_acceleration_extruding.values[0]);
+ normal_time_estimator.set_retract_acceleration((float)config.machine_max_acceleration_retracting.values[0]);
+ normal_time_estimator.set_minimum_feedrate((float)config.machine_min_extruding_rate.values[0]);
+ normal_time_estimator.set_minimum_travel_feedrate((float)config.machine_min_travel_rate.values[0]);
+ normal_time_estimator.set_axis_max_acceleration(GCodeTimeEstimator::X, (float)config.machine_max_acceleration_x.values[0]);
+ normal_time_estimator.set_axis_max_acceleration(GCodeTimeEstimator::Y, (float)config.machine_max_acceleration_y.values[0]);
+ normal_time_estimator.set_axis_max_acceleration(GCodeTimeEstimator::Z, (float)config.machine_max_acceleration_z.values[0]);
+ normal_time_estimator.set_axis_max_acceleration(GCodeTimeEstimator::E, (float)config.machine_max_acceleration_e.values[0]);
+ normal_time_estimator.set_axis_max_feedrate(GCodeTimeEstimator::X, (float)config.machine_max_feedrate_x.values[0]);
+ normal_time_estimator.set_axis_max_feedrate(GCodeTimeEstimator::Y, (float)config.machine_max_feedrate_y.values[0]);
+ normal_time_estimator.set_axis_max_feedrate(GCodeTimeEstimator::Z, (float)config.machine_max_feedrate_z.values[0]);
+ normal_time_estimator.set_axis_max_feedrate(GCodeTimeEstimator::E, (float)config.machine_max_feedrate_e.values[0]);
+ normal_time_estimator.set_axis_max_jerk(GCodeTimeEstimator::X, (float)config.machine_max_jerk_x.values[0]);
+ normal_time_estimator.set_axis_max_jerk(GCodeTimeEstimator::Y, (float)config.machine_max_jerk_y.values[0]);
+ normal_time_estimator.set_axis_max_jerk(GCodeTimeEstimator::Z, (float)config.machine_max_jerk_z.values[0]);
+ normal_time_estimator.set_axis_max_jerk(GCodeTimeEstimator::E, (float)config.machine_max_jerk_e.values[0]);
+
+ if (silent_time_estimator_enabled)
+ {
+ silent_time_estimator.reset();
+ silent_time_estimator.set_dialect(config.gcode_flavor);
+ silent_time_estimator.set_extrusion_axis(config.get_extrusion_axis()[0]);
+ /* "Stealth mode" values can be just a copy of "normal mode" values
+ * (when they aren't input for a printer preset).
+ * Thus, use back value from values, instead of second one, which could be absent
+ */
+ silent_time_estimator.set_max_acceleration((float)config.machine_max_acceleration_extruding.values.back());
+ silent_time_estimator.set_retract_acceleration((float)config.machine_max_acceleration_retracting.values.back());
+ silent_time_estimator.set_minimum_feedrate((float)config.machine_min_extruding_rate.values.back());
+ silent_time_estimator.set_minimum_travel_feedrate((float)config.machine_min_travel_rate.values.back());
+ silent_time_estimator.set_axis_max_acceleration(GCodeTimeEstimator::X, (float)config.machine_max_acceleration_x.values.back());
+ silent_time_estimator.set_axis_max_acceleration(GCodeTimeEstimator::Y, (float)config.machine_max_acceleration_y.values.back());
+ silent_time_estimator.set_axis_max_acceleration(GCodeTimeEstimator::Z, (float)config.machine_max_acceleration_z.values.back());
+ silent_time_estimator.set_axis_max_acceleration(GCodeTimeEstimator::E, (float)config.machine_max_acceleration_e.values.back());
+ silent_time_estimator.set_axis_max_feedrate(GCodeTimeEstimator::X, (float)config.machine_max_feedrate_x.values.back());
+ silent_time_estimator.set_axis_max_feedrate(GCodeTimeEstimator::Y, (float)config.machine_max_feedrate_y.values.back());
+ silent_time_estimator.set_axis_max_feedrate(GCodeTimeEstimator::Z, (float)config.machine_max_feedrate_z.values.back());
+ silent_time_estimator.set_axis_max_feedrate(GCodeTimeEstimator::E, (float)config.machine_max_feedrate_e.values.back());
+ silent_time_estimator.set_axis_max_jerk(GCodeTimeEstimator::X, (float)config.machine_max_jerk_x.values.back());
+ silent_time_estimator.set_axis_max_jerk(GCodeTimeEstimator::Y, (float)config.machine_max_jerk_y.values.back());
+ silent_time_estimator.set_axis_max_jerk(GCodeTimeEstimator::Z, (float)config.machine_max_jerk_z.values.back());
+ silent_time_estimator.set_axis_max_jerk(GCodeTimeEstimator::E, (float)config.machine_max_jerk_e.values.back());
+ if (config.single_extruder_multi_material) {
+ // As of now the fields are shown at the UI dialog in the same combo box as the ramming values, so they
+ // are considered to be active for the single extruder multi-material printers only.
+ silent_time_estimator.set_filament_load_times(config.filament_load_time.values);
+ silent_time_estimator.set_filament_unload_times(config.filament_unload_time.values);
+ }
+ }
+ }
+ // Filament load / unload times are not specific to a firmware flavor. Let anybody use it if they find it useful.
+ if (config.single_extruder_multi_material) {
+ // As of now the fields are shown at the UI dialog in the same combo box as the ramming values, so they
+ // are considered to be active for the single extruder multi-material printers only.
+ normal_time_estimator.set_filament_load_times(config.filament_load_time.values);
+ normal_time_estimator.set_filament_unload_times(config.filament_unload_time.values);
+ }
+ }
+
+ static void init_gcode_analyzer(const PrintConfig &config, GCodeAnalyzer &analyzer)
+ {
+ // resets analyzer
+ analyzer.reset();
+
+ // send extruder offset data to analyzer
+ GCodeAnalyzer::ExtruderOffsetsMap extruder_offsets;
+ unsigned int num_extruders = static_cast(config.nozzle_diameter.values.size());
+ for (unsigned int extruder_id = 0; extruder_id < num_extruders; ++ extruder_id)
+ {
+ Vec2d offset = config.extruder_offset.get_at(extruder_id);
+ if (!offset.isApprox(Vec2d::Zero()))
+ extruder_offsets[extruder_id] = offset;
+ }
+ analyzer.set_extruder_offsets(extruder_offsets);
+
+ // tell analyzer about the extrusion axis
+ analyzer.set_extrusion_axis(config.get_extrusion_axis()[0]);
+
+ // send extruders count to analyzer to allow it to detect invalid extruder idxs
+ analyzer.set_extruders_count(num_extruders);
+
+ // tell analyzer about the gcode flavor
+ analyzer.set_gcode_flavor(config.gcode_flavor);
+ }
+
+ static double autospeed_volumetric_limit(const Print &print)
+ {
+ // get the minimum cross-section used in the print
+ std::vector mm3_per_mm;
+ for (auto object : print.objects()) {
+ for (size_t region_id = 0; region_id < object->region_volumes.size(); ++ region_id) {
+ const PrintRegion* region = print.regions()[region_id];
+ for (auto layer : object->layers()) {
+ const LayerRegion* layerm = layer->regions()[region_id];
+ if (region->config().get_abs_value("perimeter_speed") == 0 ||
+ region->config().get_abs_value("small_perimeter_speed") == 0 ||
+ region->config().get_abs_value("external_perimeter_speed") == 0 ||
+ region->config().get_abs_value("bridge_speed") == 0)
+ mm3_per_mm.push_back(layerm->perimeters.min_mm3_per_mm());
+ if (region->config().get_abs_value("infill_speed") == 0 ||
+ region->config().get_abs_value("solid_infill_speed") == 0 ||
+ region->config().get_abs_value("top_solid_infill_speed") == 0 ||
+ region->config().get_abs_value("bridge_speed") == 0)
+ mm3_per_mm.push_back(layerm->fills.min_mm3_per_mm());
+ }
+ }
+ if (object->config().get_abs_value("support_material_speed") == 0 ||
+ object->config().get_abs_value("support_material_interface_speed") == 0)
+ for (auto layer : object->support_layers())
+ mm3_per_mm.push_back(layer->support_fills.min_mm3_per_mm());
+ }
+ // filter out 0-width segments
+ mm3_per_mm.erase(std::remove_if(mm3_per_mm.begin(), mm3_per_mm.end(), [](double v) { return v < 0.000001; }), mm3_per_mm.end());
+ double volumetric_speed = 0.;
+ if (! mm3_per_mm.empty()) {
+ // In order to honor max_print_speed we need to find a target volumetric
+ // speed that we can use throughout the print. So we define this target
+ // volumetric speed as the volumetric speed produced by printing the
+ // smallest cross-section at the maximum speed: any larger cross-section
+ // will need slower feedrates.
+ volumetric_speed = *std::min_element(mm3_per_mm.begin(), mm3_per_mm.end()) * print.config().max_print_speed.value;
+ // limit such volumetric speed with max_volumetric_speed if set
+ if (print.config().max_volumetric_speed.value > 0)
+ volumetric_speed = std::min(volumetric_speed, print.config().max_volumetric_speed.value);
+ }
+ return volumetric_speed;
+ }
+
+ static void init_ooze_prevention(const Print &print, OozePrevention &ooze_prevention)
+ {
+ // Calculate wiping points if needed
+ if (print.config().ooze_prevention.value && ! print.config().single_extruder_multi_material) {
+ Points skirt_points;
+ for (const ExtrusionEntity *ee : print.skirt().entities)
+ for (const ExtrusionPath &path : dynamic_cast(ee)->paths)
+ append(skirt_points, path.polyline.points);
+ if (! skirt_points.empty()) {
+ Polygon outer_skirt = Slic3r::Geometry::convex_hull(skirt_points);
+ Polygons skirts;
+ for (unsigned int extruder_id : print.extruders()) {
+ const Vec2d &extruder_offset = print.config().extruder_offset.get_at(extruder_id);
+ Polygon s(outer_skirt);
+ s.translate(Point::new_scale(-extruder_offset(0), -extruder_offset(1)));
+ skirts.emplace_back(std::move(s));
+ }
+ ooze_prevention.enable = true;
+ ooze_prevention.standby_points = offset(Slic3r::Geometry::convex_hull(skirts), scale_(3.f)).front().equally_spaced_points(scale_(10.));
+ #if 0
+ require "Slic3r/SVG.pm";
+ Slic3r::SVG::output(
+ "ooze_prevention.svg",
+ red_polygons => \@skirts,
+ polygons => [$outer_skirt],
+ points => $gcodegen->ooze_prevention->standby_points,
+ );
+ #endif
+ }
+ }
+ }
+
+ #if ENABLE_THUMBNAIL_GENERATOR
+ template
+ static void export_thumbnails_to_file(ThumbnailsGeneratorCallback &thumbnail_cb, const std::vector &sizes, WriteToOutput output, ThrowIfCanceledCallback throw_if_canceled)
+ {
+ // Write thumbnails using base64 encoding
+ if (thumbnail_cb != nullptr)
+ {
+ const size_t max_row_length = 78;
+ ThumbnailsList thumbnails;
+ thumbnail_cb(thumbnails, sizes, true, true, true, true);
+ for (const ThumbnailData& data : thumbnails)
+ {
+ if (data.is_valid())
+ {
+ size_t png_size = 0;
+ void* png_data = tdefl_write_image_to_png_file_in_memory_ex((const void*)data.pixels.data(), data.width, data.height, 4, &png_size, MZ_DEFAULT_LEVEL, 1);
+ if (png_data != nullptr)
+ {
+ std::string encoded;
+ encoded.resize(boost::beast::detail::base64::encoded_size(png_size));
+ encoded.resize(boost::beast::detail::base64::encode((void*)&encoded[0], (const void*)png_data, png_size));
+
+ output((boost::format("\n;\n; thumbnail begin %dx%d %d\n") % data.width % data.height % encoded.size()).str().c_str());
+
+ unsigned int row_count = 0;
+ while (encoded.size() > max_row_length)
+ {
+ output((boost::format("; %s\n") % encoded.substr(0, max_row_length)).str().c_str());
+ encoded = encoded.substr(max_row_length);
+ ++row_count;
+ }
+
+ if (encoded.size() > 0)
+ output((boost::format("; %s\n") % encoded).str().c_str());
+
+ output("; thumbnail end\n;\n");
+
+ mz_free(png_data);
+ }
+ }
+ throw_if_canceled();
+ }
+ }
+ }
+ #endif // ENABLE_THUMBNAIL_GENERATOR
+
+ // Fill in print_statistics and return formatted string containing filament statistics to be inserted into G-code comment section.
+ static std::string update_print_stats_and_format_filament_stats(
+ const GCodeTimeEstimator &normal_time_estimator,
+ const GCodeTimeEstimator &silent_time_estimator,
+ const bool silent_time_estimator_enabled,
+ const bool has_wipe_tower,
+ const WipeTowerData &wipe_tower_data,
+ const std::vector &extruders,
+ PrintStatistics &print_statistics)
+ {
+ std::string filament_stats_string_out;
+
+ print_statistics.clear();
+ print_statistics.estimated_normal_print_time = normal_time_estimator.get_time_dhms();
+ print_statistics.estimated_silent_print_time = silent_time_estimator_enabled ? silent_time_estimator.get_time_dhms() : "N/A";
+ print_statistics.estimated_normal_color_print_times = normal_time_estimator.get_color_times_dhms(true);
+ if (silent_time_estimator_enabled)
+ print_statistics.estimated_silent_color_print_times = silent_time_estimator.get_color_times_dhms(true);
+ print_statistics.total_toolchanges = std::max(0, wipe_tower_data.number_of_toolchanges);
+ if (! extruders.empty()) {
+ std::pair out_filament_used_mm ("; filament used [mm] = ", 0);
+ std::pair out_filament_used_cm3("; filament used [cm3] = ", 0);
+ std::pair out_filament_used_g ("; filament used [g] = ", 0);
+ std::pair out_filament_cost ("; filament cost = ", 0);
+ for (const Extruder &extruder : extruders) {
+ double used_filament = extruder.used_filament() + (has_wipe_tower ? wipe_tower_data.used_filament[extruder.id()] : 0.f);
+ double extruded_volume = extruder.extruded_volume() + (has_wipe_tower ? wipe_tower_data.used_filament[extruder.id()] * 2.4052f : 0.f); // assumes 1.75mm filament diameter
+ double filament_weight = extruded_volume * extruder.filament_density() * 0.001;
+ double filament_cost = filament_weight * extruder.filament_cost() * 0.001;
+ auto append = [&extruder, &extruders](std::pair &dst, const char *tmpl, double value) {
+ while (dst.second < extruder.id()) {
+ // Fill in the non-printing extruders with zeros.
+ dst.first += (dst.second > 0) ? ", 0" : "0";
+ ++ dst.second;
+ }
+ if (dst.second > 0)
+ dst.first += ", ";
+ char buf[64];
+ sprintf(buf, tmpl, value);
+ dst.first += buf;
+ ++ dst.second;
+ };
+ print_statistics.filament_stats.insert(std::pair{extruder.id(), (float)used_filament});
+ append(out_filament_used_mm, "%.1lf", used_filament);
+ append(out_filament_used_cm3, "%.1lf", extruded_volume * 0.001);
+ if (filament_weight > 0.) {
+ print_statistics.total_weight = print_statistics.total_weight + filament_weight;
+ append(out_filament_used_g, "%.1lf", filament_weight);
+ if (filament_cost > 0.) {
+ print_statistics.total_cost = print_statistics.total_cost + filament_cost;
+ append(out_filament_cost, "%.1lf", filament_cost);
+ }
+ }
+ print_statistics.total_used_filament += used_filament;
+ print_statistics.total_extruded_volume += extruded_volume;
+ print_statistics.total_wipe_tower_filament += has_wipe_tower ? used_filament - extruder.used_filament() : 0.;
+ print_statistics.total_wipe_tower_cost += has_wipe_tower ? (extruded_volume - extruder.extruded_volume())* extruder.filament_density() * 0.001 * extruder.filament_cost() * 0.001 : 0.;
+ }
+ filament_stats_string_out += out_filament_used_mm.first;
+ filament_stats_string_out += out_filament_used_cm3.first;
+ if (out_filament_used_g.second)
+ filament_stats_string_out += out_filament_used_g.first;
+ if (out_filament_cost.second)
+ filament_stats_string_out += out_filament_cost.first;
+ }
+ return filament_stats_string_out;
+ }
+}
+
#if ENABLE_THUMBNAIL_GENERATOR
void GCode::_do_export(Print& print, FILE* file, ThumbnailsGeneratorCallback thumbnail_cb)
#else
@@ -800,99 +1094,10 @@ void GCode::_do_export(Print& print, FILE* file)
{
PROFILE_FUNC();
- // resets time estimators
- m_normal_time_estimator.reset();
- m_normal_time_estimator.set_dialect(print.config().gcode_flavor);
- m_normal_time_estimator.set_extrusion_axis(print.config().get_extrusion_axis()[0]);
- m_silent_time_estimator_enabled = (print.config().gcode_flavor == gcfMarlin) && print.config().silent_mode;
-
- // Until we have a UI support for the other firmwares than the Marlin, use the hardcoded default values
- // and let the user to enter the G-code limits into the start G-code.
- // If the following block is enabled for other firmwares than the Marlin, then the function
- // this->print_machine_envelope(file, print);
- // shall be adjusted as well to produce a G-code block compatible with the particular firmware flavor.
- if (print.config().gcode_flavor.value == gcfMarlin) {
- m_normal_time_estimator.set_max_acceleration((float)print.config().machine_max_acceleration_extruding.values[0]);
- m_normal_time_estimator.set_retract_acceleration((float)print.config().machine_max_acceleration_retracting.values[0]);
- m_normal_time_estimator.set_minimum_feedrate((float)print.config().machine_min_extruding_rate.values[0]);
- m_normal_time_estimator.set_minimum_travel_feedrate((float)print.config().machine_min_travel_rate.values[0]);
- m_normal_time_estimator.set_axis_max_acceleration(GCodeTimeEstimator::X, (float)print.config().machine_max_acceleration_x.values[0]);
- m_normal_time_estimator.set_axis_max_acceleration(GCodeTimeEstimator::Y, (float)print.config().machine_max_acceleration_y.values[0]);
- m_normal_time_estimator.set_axis_max_acceleration(GCodeTimeEstimator::Z, (float)print.config().machine_max_acceleration_z.values[0]);
- m_normal_time_estimator.set_axis_max_acceleration(GCodeTimeEstimator::E, (float)print.config().machine_max_acceleration_e.values[0]);
- m_normal_time_estimator.set_axis_max_feedrate(GCodeTimeEstimator::X, (float)print.config().machine_max_feedrate_x.values[0]);
- m_normal_time_estimator.set_axis_max_feedrate(GCodeTimeEstimator::Y, (float)print.config().machine_max_feedrate_y.values[0]);
- m_normal_time_estimator.set_axis_max_feedrate(GCodeTimeEstimator::Z, (float)print.config().machine_max_feedrate_z.values[0]);
- m_normal_time_estimator.set_axis_max_feedrate(GCodeTimeEstimator::E, (float)print.config().machine_max_feedrate_e.values[0]);
- m_normal_time_estimator.set_axis_max_jerk(GCodeTimeEstimator::X, (float)print.config().machine_max_jerk_x.values[0]);
- m_normal_time_estimator.set_axis_max_jerk(GCodeTimeEstimator::Y, (float)print.config().machine_max_jerk_y.values[0]);
- m_normal_time_estimator.set_axis_max_jerk(GCodeTimeEstimator::Z, (float)print.config().machine_max_jerk_z.values[0]);
- m_normal_time_estimator.set_axis_max_jerk(GCodeTimeEstimator::E, (float)print.config().machine_max_jerk_e.values[0]);
-
- if (m_silent_time_estimator_enabled)
- {
- m_silent_time_estimator.reset();
- m_silent_time_estimator.set_dialect(print.config().gcode_flavor);
- m_silent_time_estimator.set_extrusion_axis(print.config().get_extrusion_axis()[0]);
- /* "Stealth mode" values can be just a copy of "normal mode" values
- * (when they aren't input for a printer preset).
- * Thus, use back value from values, instead of second one, which could be absent
- */
- m_silent_time_estimator.set_max_acceleration((float)print.config().machine_max_acceleration_extruding.values.back());
- m_silent_time_estimator.set_retract_acceleration((float)print.config().machine_max_acceleration_retracting.values.back());
- m_silent_time_estimator.set_minimum_feedrate((float)print.config().machine_min_extruding_rate.values.back());
- m_silent_time_estimator.set_minimum_travel_feedrate((float)print.config().machine_min_travel_rate.values.back());
- m_silent_time_estimator.set_axis_max_acceleration(GCodeTimeEstimator::X, (float)print.config().machine_max_acceleration_x.values.back());
- m_silent_time_estimator.set_axis_max_acceleration(GCodeTimeEstimator::Y, (float)print.config().machine_max_acceleration_y.values.back());
- m_silent_time_estimator.set_axis_max_acceleration(GCodeTimeEstimator::Z, (float)print.config().machine_max_acceleration_z.values.back());
- m_silent_time_estimator.set_axis_max_acceleration(GCodeTimeEstimator::E, (float)print.config().machine_max_acceleration_e.values.back());
- m_silent_time_estimator.set_axis_max_feedrate(GCodeTimeEstimator::X, (float)print.config().machine_max_feedrate_x.values.back());
- m_silent_time_estimator.set_axis_max_feedrate(GCodeTimeEstimator::Y, (float)print.config().machine_max_feedrate_y.values.back());
- m_silent_time_estimator.set_axis_max_feedrate(GCodeTimeEstimator::Z, (float)print.config().machine_max_feedrate_z.values.back());
- m_silent_time_estimator.set_axis_max_feedrate(GCodeTimeEstimator::E, (float)print.config().machine_max_feedrate_e.values.back());
- m_silent_time_estimator.set_axis_max_jerk(GCodeTimeEstimator::X, (float)print.config().machine_max_jerk_x.values.back());
- m_silent_time_estimator.set_axis_max_jerk(GCodeTimeEstimator::Y, (float)print.config().machine_max_jerk_y.values.back());
- m_silent_time_estimator.set_axis_max_jerk(GCodeTimeEstimator::Z, (float)print.config().machine_max_jerk_z.values.back());
- m_silent_time_estimator.set_axis_max_jerk(GCodeTimeEstimator::E, (float)print.config().machine_max_jerk_e.values.back());
- if (print.config().single_extruder_multi_material) {
- // As of now the fields are shown at the UI dialog in the same combo box as the ramming values, so they
- // are considered to be active for the single extruder multi-material printers only.
- m_silent_time_estimator.set_filament_load_times(print.config().filament_load_time.values);
- m_silent_time_estimator.set_filament_unload_times(print.config().filament_unload_time.values);
- }
- }
- }
- // Filament load / unload times are not specific to a firmware flavor. Let anybody use it if they find it useful.
- if (print.config().single_extruder_multi_material) {
- // As of now the fields are shown at the UI dialog in the same combo box as the ramming values, so they
- // are considered to be active for the single extruder multi-material printers only.
- m_normal_time_estimator.set_filament_load_times(print.config().filament_load_time.values);
- m_normal_time_estimator.set_filament_unload_times(print.config().filament_unload_time.values);
- }
-
- // resets analyzer
- m_analyzer.reset();
-
- // send extruder offset data to analyzer
- GCodeAnalyzer::ExtruderOffsetsMap extruder_offsets;
- for (unsigned int extruder_id : print.extruders())
- {
- Vec2d offset = print.config().extruder_offset.get_at(extruder_id);
- if (!offset.isApprox(Vec2d::Zero()))
- extruder_offsets[extruder_id] = offset;
- }
- m_analyzer.set_extruder_offsets(extruder_offsets);
-
- // tell analyzer about the extrusion axis
- m_analyzer.set_extrusion_axis(print.config().get_extrusion_axis()[0]);
-
- // send extruders count to analyzer to allow it to detect invalid extruder idxs
- const ConfigOptionStrings* extruders_opt = dynamic_cast(print.config().option("extruder_colour"));
- const ConfigOptionStrings* filamemts_opt = dynamic_cast(print.config().option("filament_colour"));
- m_analyzer.set_extruders_count(std::max((unsigned int)extruders_opt->values.size(), (unsigned int)filamemts_opt->values.size()));
-
- // tell analyzer about the gcode flavor
- m_analyzer.set_gcode_flavor(print.config().gcode_flavor);
+ DoExport::init_time_estimators(print.config(),
+ // modifies the following:
+ m_normal_time_estimator, m_silent_time_estimator, m_silent_time_estimator_enabled);
+ DoExport::init_gcode_analyzer(print.config(), m_analyzer);
// resets analyzer's tracking data
m_last_mm3_per_mm = GCodeAnalyzer::Default_mm3_per_mm;
@@ -914,8 +1119,7 @@ void GCode::_do_export(Print& print, FILE* file)
std::sort(zs.begin(), zs.end());
m_layer_count += (unsigned int)(object->copies().size() * (std::unique(zs.begin(), zs.end()) - zs.begin()));
}
- }
- else {
+ } else {
// Print all objects with the same print_z together.
std::vector zs;
for (auto object : print.objects()) {
@@ -932,53 +1136,8 @@ void GCode::_do_export(Print& print, FILE* file)
m_enable_cooling_markers = true;
this->apply_print_config(print.config());
- this->set_extruders(print.extruders());
- // Initialize custom gcode
- Model* model = print.get_object(0)->model_object()->get_model();
- m_custom_gcode_per_print_z = model->custom_gcode_per_print_z;
-
- // Initialize autospeed.
- {
- // get the minimum cross-section used in the print
- std::vector mm3_per_mm;
- for (auto object : print.objects()) {
- for (size_t region_id = 0; region_id < object->region_volumes.size(); ++region_id) {
- const PrintRegion* region = print.regions()[region_id];
- for (auto layer : object->layers()) {
- const LayerRegion* layerm = layer->regions()[region_id];
- if (region->config().get_abs_value("perimeter_speed") == 0 ||
- region->config().get_abs_value("small_perimeter_speed") == 0 ||
- region->config().get_abs_value("external_perimeter_speed") == 0 ||
- region->config().get_abs_value("bridge_speed") == 0)
- mm3_per_mm.push_back(layerm->perimeters.min_mm3_per_mm());
- if (region->config().get_abs_value("infill_speed") == 0 ||
- region->config().get_abs_value("solid_infill_speed") == 0 ||
- region->config().get_abs_value("top_solid_infill_speed") == 0 ||
- region->config().get_abs_value("bridge_speed") == 0)
- mm3_per_mm.push_back(layerm->fills.min_mm3_per_mm());
- }
- }
- if (object->config().get_abs_value("support_material_speed") == 0 ||
- object->config().get_abs_value("support_material_interface_speed") == 0)
- for (auto layer : object->support_layers())
- mm3_per_mm.push_back(layer->support_fills.min_mm3_per_mm());
- }
- print.throw_if_canceled();
- // filter out 0-width segments
- mm3_per_mm.erase(std::remove_if(mm3_per_mm.begin(), mm3_per_mm.end(), [](double v) { return v < 0.000001; }), mm3_per_mm.end());
- if (!mm3_per_mm.empty()) {
- // In order to honor max_print_speed we need to find a target volumetric
- // speed that we can use throughout the print. So we define this target
- // volumetric speed as the volumetric speed produced by printing the
- // smallest cross-section at the maximum speed: any larger cross-section
- // will need slower feedrates.
- m_volumetric_speed = *std::min_element(mm3_per_mm.begin(), mm3_per_mm.end()) * print.config().max_print_speed.value;
- // limit such volumetric speed with max_volumetric_speed if set
- if (print.config().max_volumetric_speed.value > 0)
- m_volumetric_speed = std::min(m_volumetric_speed, print.config().max_volumetric_speed.value);
- }
- }
+ m_volumetric_speed = DoExport::autospeed_volumetric_limit(print);
print.throw_if_canceled();
m_cooling_buffer = make_unique(*this);
@@ -996,47 +1155,9 @@ void GCode::_do_export(Print& print, FILE* file)
// Write information on the generator.
_write_format(file, "; %s\n\n", Slic3r::header_slic3r_generated().c_str());
-#if ENABLE_THUMBNAIL_GENERATOR
- // Write thumbnails using base64 encoding
- if (thumbnail_cb != nullptr)
- {
- const size_t max_row_length = 78;
- ThumbnailsList thumbnails;
- thumbnail_cb(thumbnails, print.full_print_config().option("thumbnails")->values, true, true, true, true);
- for (const ThumbnailData& data : thumbnails)
- {
- if (data.is_valid())
- {
- size_t png_size = 0;
- void* png_data = tdefl_write_image_to_png_file_in_memory_ex((const void*)data.pixels.data(), data.width, data.height, 4, &png_size, MZ_DEFAULT_LEVEL, 1);
- if (png_data != nullptr)
- {
- std::string encoded;
- encoded.resize(boost::beast::detail::base64::encoded_size(png_size));
- encoded.resize(boost::beast::detail::base64::encode((void*)&encoded[0], (const void*)png_data, png_size));
-
- _write_format(file, "\n;\n; thumbnail begin %dx%d %d\n", data.width, data.height, encoded.size());
-
- unsigned int row_count = 0;
- while (encoded.size() > max_row_length)
- {
- _write_format(file, "; %s\n", encoded.substr(0, max_row_length).c_str());
- encoded = encoded.substr(max_row_length);
- ++row_count;
- }
-
- if (encoded.size() > 0)
- _write_format(file, "; %s\n", encoded.c_str());
-
- _write(file, "; thumbnail end\n;\n");
-
- mz_free(png_data);
- }
- }
- print.throw_if_canceled();
- }
- }
-#endif // ENABLE_THUMBNAIL_GENERATOR
+ DoExport::export_thumbnails_to_file(thumbnail_cb, print.full_print_config().option("thumbnails")->values,
+ [this, file](const char* sz) { this->_write(file, sz); },
+ [&print]() { print.throw_if_canceled(); });
// Write notes (content of the Print Settings tab -> Notes)
{
@@ -1079,9 +1200,6 @@ void GCode::_do_export(Print& print, FILE* file)
_writeln(file, GCodeTimeEstimator::Silent_First_M73_Output_Placeholder_Tag);
}
- // Hold total number of print toolchanges. Check for negative toolchanges (single extruder mode) and set to 0 (no tool change).
- int total_toolchanges = std::max(0, print.wipe_tower_data().number_of_toolchanges);
-
// Prepare the helper object for replacing placeholders in custom G-code and output filename.
m_placeholder_parser = print.placeholder_parser();
m_placeholder_parser.update_timestamp();
@@ -1101,18 +1219,23 @@ void GCode::_do_export(Print& print, FILE* file)
if ((initial_extruder_id = tool_ordering.first_extruder()) != (unsigned int)-1)
break;
}
+ // We don't allow switching of extruders per layer by Model::custom_gcode_per_print_z in sequential mode.
+ // Use the extruder IDs collected from Regions.
+ this->set_extruders(print.extruders());
} else {
// Find tool ordering for all the objects at once, and the initial extruder ID.
// If the tool ordering has been pre-calculated by Print class for wipe tower already, reuse it.
- tool_ordering = print.wipe_tower_data().tool_ordering.empty() ?
- ToolOrdering(print, initial_extruder_id) :
- print.wipe_tower_data().tool_ordering;
+ tool_ordering = print.tool_ordering();
+ tool_ordering.assign_custom_gcodes(print);
has_wipe_tower = print.has_wipe_tower() && tool_ordering.has_wipe_tower();
- initial_extruder_id = (has_wipe_tower && ! print.config().single_extruder_multi_material_priming) ?
+ initial_extruder_id = (has_wipe_tower && ! print.config().single_extruder_multi_material_priming) ?
// The priming towers will be skipped.
tool_ordering.all_extruders().back() :
- // Don't skip the priming towers.
+ // Don't skip the priming towers.
tool_ordering.first_extruder();
+ // In non-sequential print, the printing extruders may have been modified by the extruder switches stored in Model::custom_gcode_per_print_z.
+ // Therefore initialize the printing extruders from there.
+ this->set_extruders(tool_ordering.all_extruders());
}
if (initial_extruder_id == (unsigned int)-1) {
// Nothing to print!
@@ -1124,49 +1247,6 @@ void GCode::_do_export(Print& print, FILE* file)
}
print.throw_if_canceled();
-// #ys_FIXME_no_exported_codes
- /*
- /* To avoid change filament for non-used extruder for Multi-material,
- * check model->custom_gcode_per_print_z using tool_ordering values
- * /
- if (!m_custom_gcode_per_print_z. empty())
- {
- bool delete_executed = false;
- auto it = m_custom_gcode_per_print_z.end();
- while (it != m_custom_gcode_per_print_z.begin())
- {
- --it;
- if (it->gcode != ColorChangeCode)
- continue;
-
- auto it_layer_tools = std::lower_bound(tool_ordering.begin(), tool_ordering.end(), LayerTools(it->print_z));
-
- bool used_extruder = false;
- for (; it_layer_tools != tool_ordering.end(); it_layer_tools++)
- {
- const std::vector& extruders = it_layer_tools->extruders;
- if (std::find(extruders.begin(), extruders.end(), (unsigned)(it->extruder-1)) != extruders.end())
- {
- used_extruder = true;
- break;
- }
- }
- if (used_extruder)
- continue;
-
- /* If we are there, current extruder wouldn't be used,
- * so this color change is a redundant move.
- * Delete this item from m_custom_gcode_per_print_z
- * /
- it = m_custom_gcode_per_print_z.erase(it);
- delete_executed = true;
- }
-
- if (delete_executed)
- model->custom_gcode_per_print_z = m_custom_gcode_per_print_z;
- }
-*/
-
m_cooling_buffer->set_current_extruder(initial_extruder_id);
// Emit machine envelope limits for the Marlin firmware.
@@ -1187,7 +1267,8 @@ void GCode::_do_export(Print& print, FILE* file)
// For the start / end G-code to do the priming and final filament pull in case there is no wipe tower provided.
m_placeholder_parser.set("has_wipe_tower", has_wipe_tower);
m_placeholder_parser.set("has_single_extruder_multi_material_priming", has_wipe_tower && print.config().single_extruder_multi_material_priming);
- m_placeholder_parser.set("total_toolchanges", total_toolchanges);
+ m_placeholder_parser.set("total_toolchanges", std::max(0, print.wipe_tower_data().number_of_toolchanges)); // Check for negative toolchanges (single extruder mode) and set to 0 (no tool change).
+
std::string start_gcode = this->placeholder_parser_process("start_gcode", print.config().start_gcode.value, initial_extruder_id);
// Set bed temperature if the start G-code does not contain any bed temp control G-codes.
this->_print_first_layer_bed_temperature(file, print, start_gcode, initial_extruder_id, true);
@@ -1195,12 +1276,8 @@ void GCode::_do_export(Print& print, FILE* file)
this->_print_first_layer_extruder_temperatures(file, print, start_gcode, initial_extruder_id, false);
if (m_enable_analyzer)
- {
// adds tag for analyzer
- char buf[32];
- sprintf(buf, ";%s%d\n", GCodeAnalyzer::Extrusion_Role_Tag.c_str(), erCustom);
- _writeln(file, buf);
- }
+ _write_format(file, ";%s%d\n", GCodeAnalyzer::Extrusion_Role_Tag.c_str(), erCustom);
// Write the custom start G-code
_writeln(file, start_gcode);
@@ -1228,35 +1305,8 @@ void GCode::_do_export(Print& print, FILE* file)
}
// Calculate wiping points if needed
- if (print.config().ooze_prevention.value && ! print.config().single_extruder_multi_material) {
- Points skirt_points;
- for (const ExtrusionEntity *ee : print.skirt().entities)
- for (const ExtrusionPath &path : dynamic_cast(ee)->paths)
- append(skirt_points, path.polyline.points);
- if (! skirt_points.empty()) {
- Polygon outer_skirt = Slic3r::Geometry::convex_hull(skirt_points);
- Polygons skirts;
- for (unsigned int extruder_id : print.extruders()) {
- const Vec2d &extruder_offset = print.config().extruder_offset.get_at(extruder_id);
- Polygon s(outer_skirt);
- s.translate(Point::new_scale(-extruder_offset(0), -extruder_offset(1)));
- skirts.emplace_back(std::move(s));
- }
- m_ooze_prevention.enable = true;
- m_ooze_prevention.standby_points =
- offset(Slic3r::Geometry::convex_hull(skirts), scale_(3.f)).front().equally_spaced_points(scale_(10.));
-#if 0
- require "Slic3r/SVG.pm";
- Slic3r::SVG::output(
- "ooze_prevention.svg",
- red_polygons => \@skirts,
- polygons => [$outer_skirt],
- points => $gcodegen->ooze_prevention->standby_points,
- );
-#endif
- }
- print.throw_if_canceled();
- }
+ DoExport::init_ooze_prevention(print, m_ooze_prevention);
+ print.throw_if_canceled();
if (! (has_wipe_tower && print.config().single_extruder_multi_material_priming)) {
// Set initial extruder only after custom start G-code.
@@ -1387,12 +1437,8 @@ void GCode::_do_export(Print& print, FILE* file)
_write(file, m_writer.set_fan(false));
if (m_enable_analyzer)
- {
// adds tag for analyzer
- char buf[32];
- sprintf(buf, ";%s%d\n", GCodeAnalyzer::Extrusion_Role_Tag.c_str(), erCustom);
- _writeln(file, buf);
- }
+ _write_format(file, ";%s%d\n", GCodeAnalyzer::Extrusion_Role_Tag.c_str(), erCustom);
// Process filament-specific gcode in extruder order.
{
@@ -1432,60 +1478,13 @@ void GCode::_do_export(Print& print, FILE* file)
m_silent_time_estimator.calculate_time(false);
// Get filament stats.
- print.m_print_statistics.clear();
- print.m_print_statistics.estimated_normal_print_time = m_normal_time_estimator.get_time_dhms();
- print.m_print_statistics.estimated_silent_print_time = m_silent_time_estimator_enabled ? m_silent_time_estimator.get_time_dhms() : "N/A";
- print.m_print_statistics.estimated_normal_color_print_times = m_normal_time_estimator.get_color_times_dhms(true);
- if (m_silent_time_estimator_enabled)
- print.m_print_statistics.estimated_silent_color_print_times = m_silent_time_estimator.get_color_times_dhms(true);
- print.m_print_statistics.total_toolchanges = total_toolchanges;
- std::vector extruders = m_writer.extruders();
- if (! extruders.empty()) {
- std::pair out_filament_used_mm ("; filament used [mm] = ", 0);
- std::pair out_filament_used_cm3("; filament used [cm3] = ", 0);
- std::pair out_filament_used_g ("; filament used [g] = ", 0);
- std::pair out_filament_cost ("; filament cost = ", 0);
- for (const Extruder &extruder : extruders) {
- double used_filament = extruder.used_filament() + (has_wipe_tower ? print.wipe_tower_data().used_filament[extruder.id()] : 0.f);
- double extruded_volume = extruder.extruded_volume() + (has_wipe_tower ? print.wipe_tower_data().used_filament[extruder.id()] * 2.4052f : 0.f); // assumes 1.75mm filament diameter
- double filament_weight = extruded_volume * extruder.filament_density() * 0.001;
- double filament_cost = filament_weight * extruder.filament_cost() * 0.001;
- auto append = [&extruder, &extruders](std::pair &dst, const char *tmpl, double value) {
- while (dst.second < extruder.id()) {
- // Fill in the non-printing extruders with zeros.
- dst.first += (dst.second > 0) ? ", 0" : "0";
- ++ dst.second;
- }
- if (dst.second > 0)
- dst.first += ", ";
- char buf[64];
- sprintf(buf, tmpl, value);
- dst.first += buf;
- ++ dst.second;
- };
- print.m_print_statistics.filament_stats.insert(std::pair{extruder.id(), (float)used_filament});
- append(out_filament_used_mm, "%.1lf", used_filament);
- append(out_filament_used_cm3, "%.1lf", extruded_volume * 0.001);
- if (filament_weight > 0.) {
- print.m_print_statistics.total_weight = print.m_print_statistics.total_weight + filament_weight;
- append(out_filament_used_g, "%.1lf", filament_weight);
- if (filament_cost > 0.) {
- print.m_print_statistics.total_cost = print.m_print_statistics.total_cost + filament_cost;
- append(out_filament_cost, "%.1lf", filament_cost);
- }
- }
- print.m_print_statistics.total_used_filament += used_filament;
- print.m_print_statistics.total_extruded_volume += extruded_volume;
- print.m_print_statistics.total_wipe_tower_filament += has_wipe_tower ? used_filament - extruder.used_filament() : 0.;
- print.m_print_statistics.total_wipe_tower_cost += has_wipe_tower ? (extruded_volume - extruder.extruded_volume())* extruder.filament_density() * 0.001 * extruder.filament_cost() * 0.001 : 0.;
- }
- _writeln(file, out_filament_used_mm.first);
- _writeln(file, out_filament_used_cm3.first);
- if (out_filament_used_g.second)
- _writeln(file, out_filament_used_g.first);
- if (out_filament_cost.second)
- _writeln(file, out_filament_cost.first);
- }
+ _write(file, DoExport::update_print_stats_and_format_filament_stats(
+ // Const inputs
+ m_normal_time_estimator, m_silent_time_estimator, m_silent_time_estimator_enabled,
+ has_wipe_tower, print.wipe_tower_data(),
+ m_writer.extruders(),
+ // Modifies
+ print.m_print_statistics));
_write_format(file, "; total filament used [g] = %.1lf\n", print.m_print_statistics.total_weight);
_write_format(file, "; total filament cost = %.1lf\n", print.m_print_statistics.total_cost);
if (print.m_print_statistics.total_toolchanges > 0)
@@ -1729,6 +1728,136 @@ std::vector GCode::sort_print_object_instances(
return out;
}
+namespace ProcessLayer
+{
+
+ static std::string emit_custom_gcode_per_print_z(
+ const Model::CustomGCode *custom_gcode,
+ // ID of the first extruder printing this layer.
+ unsigned int first_extruder_id,
+ bool single_material_print)
+ {
+ std::string gcode;
+
+ if (custom_gcode != nullptr) {
+ // Extruder switches are processed by LayerTools, they should be filtered out.
+ assert(custom_gcode->gcode != ToolChangeCode);
+
+ const std::string &custom_code = custom_gcode->gcode;
+ std::string pause_print_msg;
+ int m600_extruder_before_layer = -1;
+ if (custom_code == ColorChangeCode && custom_gcode->extruder > 0)
+ m600_extruder_before_layer = custom_gcode->extruder - 1;
+ else if (custom_code == PausePrintCode)
+ pause_print_msg = custom_gcode->color;
+
+ // we should add or not colorprint_change in respect to nozzle_diameter count instead of really used extruders count
+ if (custom_code == ColorChangeCode) // color change
+ {
+ // add tag for analyzer
+ gcode += "; " + GCodeAnalyzer::Color_Change_Tag + ",T" + std::to_string(m600_extruder_before_layer) + "\n";
+ // add tag for time estimator
+ gcode += "; " + GCodeTimeEstimator::Color_Change_Tag + "\n";
+
+ if (!single_material_print && m600_extruder_before_layer >= 0 && first_extruder_id != m600_extruder_before_layer
+ // && !MMU1
+ ) {
+ //! FIXME_in_fw show message during print pause
+ gcode += "M601\n"; // pause print
+ gcode += "M117 Change filament for Extruder " + std::to_string(m600_extruder_before_layer) + "\n";
+ }
+ else
+ gcode += custom_code + "\n";
+ }
+ else
+ {
+ if (custom_code == PausePrintCode) // Pause print
+ {
+ // add tag for analyzer
+ gcode += "; " + GCodeAnalyzer::Pause_Print_Tag + "\n";
+ //! FIXME_in_fw show message during print pause
+ if (!pause_print_msg.empty())
+ gcode += "M117 " + pause_print_msg + "\n";
+ // add tag for time estimator
+ //gcode += "; " + GCodeTimeEstimator::Pause_Print_Tag + "\n";
+ }
+ else // custom Gcode
+ {
+ // add tag for analyzer
+ gcode += "; " + GCodeAnalyzer::Custom_Code_Tag + "\n";
+ // add tag for time estimator
+ //gcode += "; " + GCodeTimeEstimator::Custom_Code_Tag + "\n";
+ }
+ gcode += custom_code + "\n";
+ }
+ }
+
+ return gcode;
+ }
+} // namespace ProcessLayer
+
+namespace Skirt {
+ static void skirt_loops_per_extruder_all_printing(const Print &print, const LayerTools &layer_tools, std::map> &skirt_loops_per_extruder_out)
+ {
+ // Prime all extruders printing over the 1st layer over the skirt lines.
+ size_t n_loops = print.skirt().entities.size();
+ size_t n_tools = layer_tools.extruders.size();
+ size_t lines_per_extruder = (n_loops + n_tools - 1) / n_tools;
+ for (size_t i = 0; i < n_loops; i += lines_per_extruder)
+ skirt_loops_per_extruder_out[layer_tools.extruders[i / lines_per_extruder]] = std::pair(i, std::min(i + lines_per_extruder, n_loops));
+ }
+
+ static std::map> make_skirt_loops_per_extruder_1st_layer(
+ const Print &print,
+ const std::vector & /*layers */,
+ const LayerTools &layer_tools,
+ // Heights (print_z) at which the skirt has already been extruded.
+ std::vector &skirt_done)
+ {
+ // Extrude skirt at the print_z of the raft layers and normal object layers
+ // not at the print_z of the interlaced support material layers.
+ std::map> skirt_loops_per_extruder_out;
+ if (skirt_done.empty() && print.has_skirt() && ! print.skirt().entities.empty()) {
+ skirt_loops_per_extruder_all_printing(print, layer_tools, skirt_loops_per_extruder_out);
+ skirt_done.emplace_back(layer_tools.print_z);
+ }
+ return skirt_loops_per_extruder_out;
+ }
+
+ static std::map> make_skirt_loops_per_extruder_other_layers(
+ const Print &print,
+ const std::vector &layers,
+ const LayerTools &layer_tools,
+ // Heights (print_z) at which the skirt has already been extruded.
+ std::vector &skirt_done)
+ {
+ // Extrude skirt at the print_z of the raft layers and normal object layers
+ // not at the print_z of the interlaced support material layers.
+ std::map> skirt_loops_per_extruder_out;
+ if (print.has_skirt() && ! print.skirt().entities.empty() &&
+ // Not enough skirt layers printed yet.
+ //FIXME infinite or high skirt does not make sense for sequential print!
+ (skirt_done.size() < (size_t)print.config().skirt_height.value || print.has_infinite_skirt()) &&
+ // This print_z has not been extruded yet (sequential print)
+ skirt_done.back() < layer_tools.print_z - EPSILON &&
+ // and this layer is an object layer, or it is a raft layer.
+ (layer_tools.has_object || layers.front().support_layer->id() < (size_t)layers.front().support_layer->object()->config().raft_layers.value)) {
+#if 0
+ // Prime just the first printing extruder. This is original Slic3r's implementation.
+ skirt_loops_per_extruder_out[layer_tools.extruders.front()] = std::pair(0, print.config().skirts.value);
+#else
+ // Prime all extruders planned for this layer, see
+ // https://github.com/prusa3d/PrusaSlicer/issues/469#issuecomment-322450619
+ skirt_loops_per_extruder_all_printing(print, layer_tools, skirt_loops_per_extruder_out);
+#endif
+ assert(!skirt_done.empty());
+ skirt_done.emplace_back(layer_tools.print_z);
+ }
+ return skirt_loops_per_extruder_out;
+ }
+
+} // namespace Skirt
+
// In sequential mode, process_layer is called once per each object and its copy,
// therefore layers will contain a single entry and single_object_instance_idx will point to the copy of the object.
// In non-sequential mode, process_layer is called per each print_z height with all object and support layers accumulated.
@@ -1765,7 +1894,7 @@ void GCode::process_layer(
if (l.support_layer != nullptr && support_layer == nullptr)
support_layer = l.support_layer;
}
- const Layer &layer = (object_layer != nullptr) ? *object_layer : *support_layer;
+ const Layer &layer = (object_layer != nullptr) ? *object_layer : *support_layer;
coordf_t print_z = layer.print_z;
bool first_layer = layer.id() == 0;
unsigned int first_extruder_id = layer_tools.extruders.front();
@@ -1829,124 +1958,22 @@ void GCode::process_layer(
m_second_layer_things_done = true;
}
- // Let's issue a filament change command if requested at this layer.
- // In case there are more toolchange requests that weren't done yet and should happen simultaneously, erase them all.
- // (Layers can be close to each other, model could have been resliced with bigger layer height, ...).
- bool colorprint_change = false;
+ // Map from extruder ID to index of skirt loops to be extruded with that extruder.
+ std::map> skirt_loops_per_extruder;
- std::string custom_code = "";
- std::string pause_print_msg = "";
- int m600_before_extruder = -1;
- while (!m_custom_gcode_per_print_z.empty() && m_custom_gcode_per_print_z.front().print_z - EPSILON < layer.print_z) {
- custom_code = m_custom_gcode_per_print_z.front().gcode;
-
- if (custom_code == ColorChangeCode && m_custom_gcode_per_print_z.front().extruder > 0)
- m600_before_extruder = m_custom_gcode_per_print_z.front().extruder - 1;
- if (custom_code == PausePrintCode)
- pause_print_msg = m_custom_gcode_per_print_z.front().color;
-
- m_custom_gcode_per_print_z.erase(m_custom_gcode_per_print_z.begin());
- colorprint_change = true;
+ if (single_object_instance_idx == size_t(-1)) {
+ // Normal (non-sequential) print.
+ gcode += ProcessLayer::emit_custom_gcode_per_print_z(layer_tools.custom_gcode, first_extruder_id, print.config().nozzle_diameter.size() == 1);
}
-
- // we should add or not colorprint_change in respect to nozzle_diameter count instead of really used extruders count
-
- // don't save "tool_change"(ExtruderChangeCode) code to GCode
- if (colorprint_change && custom_code != ExtruderChangeCode) {
- const bool single_material_print = print.config().nozzle_diameter.size() == 1;
-
- if (custom_code == ColorChangeCode) // color change
- {
- // add tag for analyzer
- gcode += "; " + GCodeAnalyzer::Color_Change_Tag + ",T" + std::to_string(m600_before_extruder) + "\n";
- // add tag for time estimator
- gcode += "; " + GCodeTimeEstimator::Color_Change_Tag + "\n";
-
- if (!single_material_print && m600_before_extruder >= 0 && first_extruder_id != m600_before_extruder
- // && !MMU1
- ) {
- //! FIXME_in_fw show message during print pause
- gcode += "M601\n"; // pause print
- gcode += "M117 Change filament for Extruder " + std::to_string(m600_before_extruder) + "\n";
- }
- else
- gcode += custom_code + "\n";
- }
- else
- {
- if (custom_code == PausePrintCode) // Pause print
- {
- // add tag for analyzer
- gcode += "; " + GCodeAnalyzer::Pause_Print_Tag + "\n";
- //! FIXME_in_fw show message during print pause
- if (!pause_print_msg.empty())
- gcode += "M117 " + pause_print_msg + "\n";
- // add tag for time estimator
- //gcode += "; " + GCodeTimeEstimator::Pause_Print_Tag + "\n";
- }
- else // custom Gcode
- {
- // add tag for analyzer
- gcode += "; " + GCodeAnalyzer::Custom_Code_Tag + "\n";
- // add tag for time estimator
- //gcode += "; " + GCodeTimeEstimator::Custom_Code_Tag + "\n";
- }
- gcode += custom_code + "\n";
- }
- }
-
-
// Extrude skirt at the print_z of the raft layers and normal object layers
// not at the print_z of the interlaced support material layers.
- bool extrude_skirt =
- ! print.skirt().entities.empty() &&
- // Not enough skirt layers printed yet.
- (m_skirt_done.size() < (size_t)print.config().skirt_height.value || print.has_infinite_skirt()) &&
- // This print_z has not been extruded yet
- (m_skirt_done.empty() ? 0. : m_skirt_done.back()) < print_z - EPSILON &&
- // and this layer is the 1st layer, or it is an object layer, or it is a raft layer.
- (first_layer || object_layer != nullptr || support_layer->id() < (size_t)m_config.raft_layers.value);
- std::map> skirt_loops_per_extruder;
- coordf_t skirt_height = 0.;
- if (extrude_skirt) {
- // Fill in skirt_loops_per_extruder.
- skirt_height = print_z - (m_skirt_done.empty() ? 0. : m_skirt_done.back());
- m_skirt_done.push_back(print_z);
- if (first_layer) {
- // Prime the extruders over the skirt lines.
- std::vector extruder_ids = m_writer.extruder_ids();
- // Reorder the extruders, so that the last used extruder is at the front.
- for (size_t i = 1; i < extruder_ids.size(); ++ i)
- if (extruder_ids[i] == first_extruder_id) {
- // Move the last extruder to the front.
- memmove(extruder_ids.data() + 1, extruder_ids.data(), i * sizeof(unsigned int));
- extruder_ids.front() = first_extruder_id;
- break;
- }
- size_t n_loops = print.skirt().entities.size();
- if (n_loops <= extruder_ids.size()) {
- for (size_t i = 0; i < n_loops; ++i)
- skirt_loops_per_extruder[extruder_ids[i]] = std::pair(i, i + 1);
- } else {
- // Assign skirt loops to the extruders.
- std::vector extruder_loops(extruder_ids.size(), 1);
- n_loops -= extruder_loops.size();
- while (n_loops > 0) {
- for (size_t i = 0; i < extruder_ids.size() && n_loops > 0; ++ i, -- n_loops)
- ++ extruder_loops[i];
- }
- for (size_t i = 0; i < extruder_ids.size(); ++ i)
- skirt_loops_per_extruder[extruder_ids[i]] = std::make_pair(
- (i == 0) ? 0 : extruder_loops[i - 1],
- ((i == 0) ? 0 : extruder_loops[i - 1]) + extruder_loops[i]);
- }
- } else
- // Extrude all skirts with the current extruder.
- skirt_loops_per_extruder[first_extruder_id] = std::pair(0, print.config().skirts.value);
- }
+ skirt_loops_per_extruder = first_layer ?
+ Skirt::make_skirt_loops_per_extruder_1st_layer(print, layers, layer_tools, m_skirt_done) :
+ Skirt::make_skirt_loops_per_extruder_other_layers(print, layers, layer_tools, m_skirt_done);
// Group extrusions by an extruder, then by an object, an island and a region.
std::map> by_extruder;
+ bool is_anything_overridden = const_cast(layer_tools).wiping_extrusions().is_anything_overridden();
for (const LayerToPrint &layer_to_print : layers) {
if (layer_to_print.support_layer != nullptr) {
const SupportLayer &support_layer = *layer_to_print.support_layer;
@@ -2014,7 +2041,7 @@ void GCode::process_layer(
slices_test_order.reserve(n_slices);
for (size_t i = 0; i < n_slices; ++ i)
slices_test_order.emplace_back(i);
- std::sort(slices_test_order.begin(), slices_test_order.end(), [&layer_surface_bboxes](int i, int j) {
+ std::sort(slices_test_order.begin(), slices_test_order.end(), [&layer_surface_bboxes](size_t i, size_t j) {
const Vec2d s1 = layer_surface_bboxes[i].size().cast();
const Vec2d s2 = layer_surface_bboxes[j].size().cast();
return s1.x() * s1.y() < s2.x() * s2.y();
@@ -2026,58 +2053,71 @@ void GCode::process_layer(
layer.lslices[i].contour.contains(point);
};
- for (size_t region_id = 0; region_id < print.regions().size(); ++ region_id) {
- const LayerRegion *layerm = (region_id < layer.regions().size()) ? layer.regions()[region_id] : nullptr;
+ for (size_t region_id = 0; region_id < layer.regions().size(); ++ region_id) {
+ const LayerRegion *layerm = layer.regions()[region_id];
if (layerm == nullptr)
continue;
const PrintRegion ®ion = *print.regions()[region_id];
-
// Now we must process perimeters and infills and create islands of extrusions in by_region std::map.
// It is also necessary to save which extrusions are part of MM wiping and which are not.
// The process is almost the same for perimeters and infills - we will do it in a cycle that repeats twice:
- for (std::string entity_type("infills") ; entity_type != "done" ; entity_type = entity_type=="infills" ? "perimeters" : "done") {
-
- const ExtrusionEntitiesPtr& source_entities = entity_type=="infills" ? layerm->fills.entities : layerm->perimeters.entities;
-
- for (const ExtrusionEntity *ee : source_entities) {
- // fill represents infill extrusions of a single island.
- const auto *fill = dynamic_cast(ee);
- if (fill->entities.empty()) // This shouldn't happen but first_point() would fail.
+ std::vector printing_extruders;
+ for (const ObjectByExtruder::Island::Region::Type entity_type : { ObjectByExtruder::Island::Region::INFILL, ObjectByExtruder::Island::Region::PERIMETERS }) {
+ for (const ExtrusionEntity *ee : (entity_type == ObjectByExtruder::Island::Region::INFILL) ? layerm->fills.entities : layerm->perimeters.entities) {
+ // extrusions represents infill or perimeter extrusions of a single island.
+ assert(dynamic_cast(ee) != nullptr);
+ const auto *extrusions = static_cast(ee);
+ if (extrusions->entities.empty()) // This shouldn't happen but first_point() would fail.
continue;
// This extrusion is part of certain Region, which tells us which extruder should be used for it:
- int correct_extruder_id = Print::get_extruder(*fill, region);
+ int correct_extruder_id = layer_tools.extruder(*extrusions, region);
// Let's recover vector of extruder overrides:
- const ExtruderPerCopy* entity_overrides = const_cast(layer_tools).wiping_extrusions().get_extruder_overrides(fill, correct_extruder_id, layer_to_print.object()->copies().size());
+ const WipingExtrusions::ExtruderPerCopy *entity_overrides = nullptr;
+ if (is_anything_overridden) {
+ printing_extruders.clear();
+ if (! layer_tools.has_extruder(correct_extruder_id)) {
+ // this entity is not overridden, but its extruder is not in layer_tools - we'll print it
+ // by last extruder on this layer (could happen e.g. when a wiping object is taller than others - dontcare extruders are eradicated from layer_tools)
+ correct_extruder_id = layer_tools.extruders.back();
+ }
+ entity_overrides = const_cast(layer_tools).wiping_extrusions().get_extruder_overrides(extrusions, correct_extruder_id, layer_to_print.object()->copies().size());
+ if (entity_overrides == nullptr) {
+ printing_extruders.emplace_back(correct_extruder_id);
+ } else {
+ printing_extruders.reserve(entity_overrides->size());
+ for (int extruder : *entity_overrides)
+ printing_extruders.emplace_back(extruder >= 0 ?
+ // at least one copy is overridden to use this extruder
+ extruder :
+ // at least one copy would normally be printed with this extruder (see get_extruder_overrides function for explanation)
+ static_cast(- extruder - 1));
+ }
+ Slic3r::sort_remove_duplicates(printing_extruders);
+ } else
+ printing_extruders = { (unsigned int)correct_extruder_id };
// Now we must add this extrusion into the by_extruder map, once for each extruder that will print it:
- for (unsigned int extruder : layer_tools.extruders)
+ for (unsigned int extruder : printing_extruders)
{
- // Init by_extruder item only if we actually use the extruder:
- if (std::find(entity_overrides->begin(), entity_overrides->end(), extruder) != entity_overrides->end() || // at least one copy is overridden to use this extruder
- std::find(entity_overrides->begin(), entity_overrides->end(), -extruder-1) != entity_overrides->end() || // at least one copy would normally be printed with this extruder (see get_extruder_overrides function for explanation)
- (std::find(layer_tools.extruders.begin(), layer_tools.extruders.end(), correct_extruder_id) == layer_tools.extruders.end() && extruder == layer_tools.extruders.back())) // this entity is not overridden, but its extruder is not in layer_tools - we'll print it
- //by last extruder on this layer (could happen e.g. when a wiping object is taller than others - dontcare extruders are eradicated from layer_tools)
- {
- std::vector &islands = object_islands_by_extruder(
- by_extruder,
- extruder,
- &layer_to_print - layers.data(),
- layers.size(), n_slices+1);
- for (size_t i = 0; i <= n_slices; ++ i) {
- bool last = i == n_slices;
- size_t island_idx = last ? n_slices : slices_test_order[i];
- if (// fill->first_point does not fit inside any slice
- last ||
- // fill->first_point fits inside ith slice
- point_inside_surface(island_idx, fill->first_point())) {
- if (islands[island_idx].by_region.empty())
- islands[island_idx].by_region.assign(print.regions().size(), ObjectByExtruder::Island::Region());
- islands[island_idx].by_region[region_id].append(entity_type, fill, entity_overrides, layer_to_print.object()->copies().size());
- break;
- }
+ std::vector &islands = object_islands_by_extruder(
+ by_extruder,
+ extruder,
+ &layer_to_print - layers.data(),
+ layers.size(), n_slices+1);
+ for (size_t i = 0; i <= n_slices; ++ i) {
+ bool last = i == n_slices;
+ size_t island_idx = last ? n_slices : slices_test_order[i];
+ if (// extrusions->first_point does not fit inside any slice
+ last ||
+ // extrusions->first_point fits inside ith slice
+ point_inside_surface(island_idx, extrusions->first_point())) {
+ if (islands[island_idx].by_region.empty())
+ islands[island_idx].by_region.assign(print.regions().size(), ObjectByExtruder::Island::Region());
+ islands[island_idx].by_region[region_id].append(entity_type, extrusions, entity_overrides);
+ break;
}
}
}
@@ -2099,30 +2139,27 @@ void GCode::process_layer(
if (m_enable_analyzer && layer_tools.has_wipe_tower && m_wipe_tower)
m_last_analyzer_extrusion_role = erWipeTower;
- if (extrude_skirt) {
- auto loops_it = skirt_loops_per_extruder.find(extruder_id);
- if (loops_it != skirt_loops_per_extruder.end()) {
- const std::pair loops = loops_it->second;
- this->set_origin(0.,0.);
- m_avoid_crossing_perimeters.use_external_mp = true;
- Flow skirt_flow = print.skirt_flow();
- for (size_t i = loops.first; i < loops.second; ++ i) {
- // Adjust flow according to this layer's layer height.
- ExtrusionLoop loop = *dynamic_cast(print.skirt().entities[i]);
- Flow layer_skirt_flow(skirt_flow);
- layer_skirt_flow.height = (float)skirt_height;
- double mm3_per_mm = layer_skirt_flow.mm3_per_mm();
- for (ExtrusionPath &path : loop.paths) {
- path.height = (float)layer.height;
- path.mm3_per_mm = mm3_per_mm;
- }
- gcode += this->extrude_loop(loop, "skirt", m_config.support_material_speed.value);
+ if (auto loops_it = skirt_loops_per_extruder.find(extruder_id); loops_it != skirt_loops_per_extruder.end()) {
+ const std::pair loops = loops_it->second;
+ this->set_origin(0., 0.);
+ m_avoid_crossing_perimeters.use_external_mp = true;
+ Flow layer_skirt_flow(print.skirt_flow());
+ layer_skirt_flow.height = float(m_skirt_done.back() - (m_skirt_done.size() == 1 ? 0. : m_skirt_done[m_skirt_done.size() - 2]));
+ double mm3_per_mm = layer_skirt_flow.mm3_per_mm();
+ for (size_t i = loops.first; i < loops.second; ++i) {
+ // Adjust flow according to this layer's layer height.
+ ExtrusionLoop loop = *dynamic_cast(print.skirt().entities[i]);
+ for (ExtrusionPath &path : loop.paths) {
+ path.height = layer_skirt_flow.height;
+ path.mm3_per_mm = mm3_per_mm;
}
- m_avoid_crossing_perimeters.use_external_mp = false;
- // Allow a straight travel move to the first object point if this is the first layer (but don't in next layers).
- if (first_layer && loops.first == 0)
- m_avoid_crossing_perimeters.disable_once = true;
+ //FIXME using the support_material_speed of the 1st object printed.
+ gcode += this->extrude_loop(loop, "skirt", m_config.support_material_speed.value);
}
+ m_avoid_crossing_perimeters.use_external_mp = false;
+ // Allow a straight travel move to the first object point if this is the first layer (but don't in next layers).
+ if (first_layer && loops.first == 0)
+ m_avoid_crossing_perimeters.disable_once = true;
}
// Extrude brim with the extruder of the 1st region.
@@ -2146,7 +2183,7 @@ void GCode::process_layer(
std::vector instances_to_print = sort_print_object_instances(objects_by_extruder_it->second, layers, ordering, single_object_instance_idx);
// We are almost ready to print. However, we must go through all the objects twice to print the the overridden extrusions first (infill/perimeter wiping feature):
- bool is_anything_overridden = const_cast(layer_tools).wiping_extrusions().is_anything_overridden();
+ std::vector by_region_per_copy_cache;
for (int print_wipe_extrusions = is_anything_overridden; print_wipe_extrusions>=0; --print_wipe_extrusions) {
if (is_anything_overridden && print_wipe_extrusions == 0)
gcode+="; PURGING FINISHED\n";
@@ -2174,8 +2211,8 @@ void GCode::process_layer(
m_layer = layers[instance_to_print.layer_id].layer();
}
for (ObjectByExtruder::Island &island : instance_to_print.object_by_extruder.islands) {
- const auto& by_region_specific = is_anything_overridden ? island.by_region_per_copy(instance_to_print.instance_id, extruder_id, print_wipe_extrusions) : island.by_region;
-
+ const auto& by_region_specific = is_anything_overridden ? island.by_region_per_copy(by_region_per_copy_cache, static_cast(instance_to_print.instance_id), extruder_id, print_wipe_extrusions != 0) : island.by_region;
+ //FIXME the following code prints regions in the order they are defined, the path is not optimized in any way.
if (print.config().infill_first) {
gcode += this->extrude_infill(print, by_region_specific);
gcode += this->extrude_perimeters(print, by_region_specific, lower_layer_edge_grids[instance_to_print.layer_id]);
@@ -2234,8 +2271,20 @@ void GCode::apply_print_config(const PrintConfig &print_config)
void GCode::append_full_config(const Print &print, std::string &str)
{
const DynamicPrintConfig &cfg = print.full_print_config();
+ // Sorted list of config keys, which shall not be stored into the G-code. Initializer list.
+ static constexpr auto banned_keys = {
+ "compatible_printers"sv,
+ "compatible_prints"sv,
+ "print_host"sv,
+ "printhost_apikey"sv,
+ "printhost_cafile"sv
+ };
+ assert(std::is_sorted(banned_keys.begin(), banned_keys.end()));
+ auto is_banned = [](const std::string &key) {
+ return std::binary_search(banned_keys.begin(), banned_keys.end(), key);
+ };
for (const std::string &key : cfg.keys())
- if (key != "compatible_prints" && key != "compatible_printers" && ! cfg.option(key)->is_nil())
+ if (! is_banned(key) && ! cfg.option(key)->is_nil())
str += "; " + key + " = " + cfg.opt_serialize(key) + "\n";
}
@@ -2783,7 +2832,7 @@ std::string GCode::extrude_perimeters(const Print &print, const std::vectorconfig());
- for (ExtrusionEntity *ee : region.perimeters.entities)
+ for (const ExtrusionEntity *ee : region.perimeters)
gcode += this->extrude_entity(*ee, "perimeter", -1., &lower_layer_edge_grid);
}
return gcode;
@@ -2795,8 +2844,10 @@ std::string GCode::extrude_infill(const Print &print, const std::vectorconfig());
- for (ExtrusionEntity *fill : region.infills.chained_path_from(m_last_pos).entities) {
- auto *eec = dynamic_cast(fill);
+ ExtrusionEntitiesPtr extrusions { region.infills };
+ chain_and_reorder_extrusion_entities(extrusions, &m_last_pos);
+ for (const ExtrusionEntity *fill : extrusions) {
+ auto *eec = dynamic_cast(fill);
if (eec) {
for (ExtrusionEntity *ee : eec->chained_path_from(m_last_pos).entities)
gcode += this->extrude_entity(*ee, "infill");
@@ -3260,59 +3311,96 @@ Point GCode::gcode_to_point(const Vec2d &point) const
// Goes through by_region std::vector and returns reference to a subvector of entities, that are to be printed
// during infill/perimeter wiping, or normally (depends on wiping_entities parameter)
-// Returns a reference to member to avoid copying.
-const std::vector& GCode::ObjectByExtruder::Island::by_region_per_copy(unsigned int copy, int extruder, bool wiping_entities)
+// Fills in by_region_per_copy_cache and returns its reference.
+const std::vector& GCode::ObjectByExtruder::Island::by_region_per_copy(std::vector &by_region_per_copy_cache, unsigned int copy, unsigned int extruder, bool wiping_entities) const
{
+ bool has_overrides = false;
+ for (const auto& reg : by_region)
+ if (! reg.infills_overrides.empty() || ! reg.perimeters_overrides.empty()) {
+ has_overrides = true;
+ break;
+ }
+ if (! has_overrides)
+ // Simple case. No need to copy the regions.
+ return this->by_region;
+
+ // Complex case. Some of the extrusions of some object instances are to be printed first - those are the wiping extrusions.
+ // Some of the extrusions of some object instances are printed later - those are the clean print extrusions.
+ // Filter out the extrusions based on the infill_overrides / perimeter_overrides:
+
+ // Data is cleared, but the memory is not.
by_region_per_copy_cache.clear();
for (const auto& reg : by_region) {
- by_region_per_copy_cache.push_back(ObjectByExtruder::Island::Region()); // creates a region in the newly created Island
+ by_region_per_copy_cache.emplace_back(); // creates a region in the newly created Island
// Now we are going to iterate through perimeters and infills and pick ones that are supposed to be printed
// References are used so that we don't have to repeat the same code
for (int iter = 0; iter < 2; ++iter) {
- const ExtrusionEntitiesPtr& entities = (iter ? reg.infills.entities : reg.perimeters.entities);
- ExtrusionEntityCollection& target_eec = (iter ? by_region_per_copy_cache.back().infills : by_region_per_copy_cache.back().perimeters);
- const std::vector& overrides = (iter ? reg.infills_overrides : reg.perimeters_overrides);
+ const ExtrusionEntitiesPtr& entities = (iter ? reg.infills : reg.perimeters);
+ ExtrusionEntitiesPtr& target_eec = (iter ? by_region_per_copy_cache.back().infills : by_region_per_copy_cache.back().perimeters);
+ const std::vector& overrides = (iter ? reg.infills_overrides : reg.perimeters_overrides);
// Now the most important thing - which extrusion should we print.
// See function ToolOrdering::get_extruder_overrides for details about the negative numbers hack.
- int this_extruder_mark = wiping_entities ? extruder : -extruder-1;
-
- for (unsigned int i=0;iat(copy) == this_extruder_mark) // this copy should be printed with this extruder
- target_eec.append((*entities[i]));
+ if (wiping_entities) {
+ // Apply overrides for this region.
+ for (unsigned int i = 0; i < overrides.size(); ++ i) {
+ const WipingExtrusions::ExtruderPerCopy *this_override = overrides[i];
+ // This copy (aka object instance) should be printed with this extruder, which overrides the default one.
+ if (this_override != nullptr && (*this_override)[copy] == int(extruder))
+ target_eec.emplace_back(entities[i]);
+ }
+ } else {
+ // Apply normal extrusions (non-overrides) for this region.
+ unsigned int i = 0;
+ for (; i < overrides.size(); ++ i) {
+ const WipingExtrusions::ExtruderPerCopy *this_override = overrides[i];
+ // This copy (aka object instance) should be printed with this extruder, which shall be equal to the default one.
+ if (this_override == nullptr || (*this_override)[copy] == -int(extruder)-1)
+ target_eec.emplace_back(entities[i]);
+ }
+ for (; i < overrides.size(); ++ i)
+ target_eec.emplace_back(entities[i]);
+ }
}
}
return by_region_per_copy_cache;
}
-
-
// This function takes the eec and appends its entities to either perimeters or infills of this Region (depending on the first parameter)
// It also saves pointer to ExtruderPerCopy struct (for each entity), that holds information about which extruders should be used for which copy.
-void GCode::ObjectByExtruder::Island::Region::append(const std::string& type, const ExtrusionEntityCollection* eec, const ExtruderPerCopy* copies_extruder, size_t object_copies_num)
+void GCode::ObjectByExtruder::Island::Region::append(const Type type, const ExtrusionEntityCollection* eec, const WipingExtrusions::ExtruderPerCopy* copies_extruder)
{
// We are going to manipulate either perimeters or infills, exactly in the same way. Let's create pointers to the proper structure to not repeat ourselves:
- ExtrusionEntityCollection* perimeters_or_infills = &infills;
- std::vector* perimeters_or_infills_overrides = &infills_overrides;
+ ExtrusionEntitiesPtr* perimeters_or_infills;
+ std::vector* perimeters_or_infills_overrides;
- if (type == "perimeters") {
- perimeters_or_infills = &perimeters;
- perimeters_or_infills_overrides = &perimeters_overrides;
+ switch (type) {
+ case PERIMETERS:
+ perimeters_or_infills = &perimeters;
+ perimeters_or_infills_overrides = &perimeters_overrides;
+ break;
+ case INFILL:
+ perimeters_or_infills = &infills;
+ perimeters_or_infills_overrides = &infills_overrides;
+ break;
+ default:
+ throw std::invalid_argument("Unknown parameter!");
}
- else
- if (type != "infills") {
- throw std::invalid_argument("Unknown parameter!");
- return;
- }
-
// First we append the entities, there are eec->entities.size() of them:
- perimeters_or_infills->append(eec->entities);
+ size_t old_size = perimeters_or_infills->size();
+ perimeters_or_infills->reserve(perimeters_or_infills->size() + eec->entities.size());
+ for (auto* ee : eec->entities)
+ perimeters_or_infills->emplace_back(ee);
- for (unsigned int i=0;ientities.size();++i)
- perimeters_or_infills_overrides->push_back(copies_extruder);
+ if (copies_extruder != nullptr) {
+ perimeters_or_infills_overrides->reserve(old_size + eec->entities.size());
+ perimeters_or_infills_overrides->resize(old_size, nullptr);
+ for (unsigned int i = 0; i < eec->entities.size(); ++ i)
+ perimeters_or_infills_overrides->emplace_back(copies_extruder);
+ }
}
} // namespace Slic3r
diff --git a/src/libslic3r/GCode.hpp b/src/libslic3r/GCode.hpp
index 497dc8c71..0344924a1 100644
--- a/src/libslic3r/GCode.hpp
+++ b/src/libslic3r/GCode.hpp
@@ -197,23 +197,25 @@ public:
// append full config to the given string
static void append_full_config(const Print& print, std::string& str);
-protected:
+ // Object and support extrusions of the same PrintObject at the same print_z.
+ // public, so that it could be accessed by free helper functions from GCode.cpp
+ struct LayerToPrint
+ {
+ LayerToPrint() : object_layer(nullptr), support_layer(nullptr) {}
+ const Layer* object_layer;
+ const SupportLayer* support_layer;
+ const Layer* layer() const { return (object_layer != nullptr) ? object_layer : support_layer; }
+ const PrintObject* object() const { return (this->layer() != nullptr) ? this->layer()->object() : nullptr; }
+ coordf_t print_z() const { return (object_layer != nullptr && support_layer != nullptr) ? 0.5 * (object_layer->print_z + support_layer->print_z) : this->layer()->print_z; }
+ };
+
+private:
#if ENABLE_THUMBNAIL_GENERATOR
- void _do_export(Print& print, FILE* file, ThumbnailsGeneratorCallback thumbnail_cb);
+ void _do_export(Print &print, FILE *file, ThumbnailsGeneratorCallback thumbnail_cb);
#else
void _do_export(Print &print, FILE *file);
#endif //ENABLE_THUMBNAIL_GENERATOR
- // Object and support extrusions of the same PrintObject at the same print_z.
- struct LayerToPrint
- {
- LayerToPrint() : object_layer(nullptr), support_layer(nullptr) {}
- const Layer *object_layer;
- const SupportLayer *support_layer;
- const Layer* layer() const { return (object_layer != nullptr) ? object_layer : support_layer; }
- const PrintObject* object() const { return (this->layer() != nullptr) ? this->layer()->object() : nullptr; }
- coordf_t print_z() const { return (object_layer != nullptr && support_layer != nullptr) ? 0.5 * (object_layer->print_z + support_layer->print_z) : this->layer()->print_z; }
- };
static std::vector collect_layers_to_print(const PrintObject &object);
static std::vector>> collect_layers_to_print(const Print &print);
void process_layer(
@@ -239,7 +241,6 @@ protected:
std::string extrude_multi_path(ExtrusionMultiPath multipath, std::string description = "", double speed = -1.);
std::string extrude_path(ExtrusionPath path, std::string description = "", double speed = -1.);
- typedef std::vector ExtruderPerCopy;
// Extruding multiple objects with soluble / non-soluble / combined supports
// on a multi-material printer, trying to minimize tool switches.
// Following structures sort extrusions by the extruder ID, by an order of objects and object islands.
@@ -253,21 +254,29 @@ protected:
struct Island
{
struct Region {
- ExtrusionEntityCollection perimeters;
- ExtrusionEntityCollection infills;
+ // Non-owned references to LayerRegion::perimeters::entities
+ // std::vector would be better here, but there is no way in C++ to convert from std::vector std::vector without copying.
+ ExtrusionEntitiesPtr perimeters;
+ // Non-owned references to LayerRegion::fills::entities
+ ExtrusionEntitiesPtr infills;
- std::vector infills_overrides;
- std::vector perimeters_overrides;
+ std::vector infills_overrides;
+ std::vector perimeters_overrides;
+
+ enum Type {
+ PERIMETERS,
+ INFILL,
+ };
// Appends perimeter/infill entities and writes don't indices of those that are not to be extruder as part of perimeter/infill wiping
- void append(const std::string& type, const ExtrusionEntityCollection* eec, const ExtruderPerCopy* copy_extruders, size_t object_copies_num);
+ void append(const Type type, const ExtrusionEntityCollection* eec, const WipingExtrusions::ExtruderPerCopy* copy_extruders);
};
- std::vector by_region; // all extrusions for this island, grouped by regions
- const std::vector& by_region_per_copy(unsigned int copy, int extruder, bool wiping_entities = false); // returns reference to subvector of by_region
- private:
- std::vector by_region_per_copy_cache; // caches vector generated by function above to avoid copying and recalculating
+ std::vector by_region; // all extrusions for this island, grouped by regions
+
+ // Fills in by_region_per_copy_cache and returns its reference.
+ const std::vector& by_region_per_copy(std::vector &by_region_per_copy_cache, unsigned int copy, unsigned int extruder, bool wiping_entities = false) const;
};
std::vector islands;
};
@@ -277,7 +286,9 @@ protected:
InstanceToPrint(ObjectByExtruder &object_by_extruder, size_t layer_id, const PrintObject &print_object, size_t instance_id) :
object_by_extruder(object_by_extruder), layer_id(layer_id), print_object(print_object), instance_id(instance_id) {}
- ObjectByExtruder &object_by_extruder;
+ // Repository
+ ObjectByExtruder &object_by_extruder;
+ // Index into std::vector, which contains Object and Support layers for the current print_z, collected for a single object, or for possibly multiple objects with multiple instances.
const size_t layer_id;
const PrintObject &print_object;
// Instance idx of the copy of a print object.
@@ -285,7 +296,8 @@ protected:
};
std::vector sort_print_object_instances(
- std::vector &objects_by_extruder,
+ std::vector &objects_by_extruder,
+ // Object and Support layers for the current print_z, collected for a single object, or for possibly multiple objects with multiple instances.
const std::vector &layers,
// Ordering must be defined for normal (non-sequential print).
const std::vector> *ordering,
@@ -354,7 +366,7 @@ protected:
#endif /* HAS_PRESSURE_EQUALIZER */
std::unique_ptr m_wipe_tower;
- // Heights at which the skirt has already been extruded.
+ // Heights (print_z) at which the skirt has already been extruded.
std::vector m_skirt_done;
// Has the brim been extruded already? Brim is being extruded only for the first object of a multi-object print.
bool m_brim_done;
@@ -362,11 +374,6 @@ protected:
bool m_second_layer_things_done;
// Index of a last object copy extruded.
std::pair m_last_obj_copy;
- // Extensions for colorprint - now it's not a just color_print_heights,
- // there can be some custom gcode.
- // Updated before the export and erased during the process,
- // so no toolchange occurs twice.
- std::vector m_custom_gcode_per_print_z;
// Time estimators
GCodeTimeEstimator m_normal_time_estimator;
diff --git a/src/libslic3r/GCode/Analyzer.cpp b/src/libslic3r/GCode/Analyzer.cpp
index 7b8004ab0..ec5de71b1 100644
--- a/src/libslic3r/GCode/Analyzer.cpp
+++ b/src/libslic3r/GCode/Analyzer.cpp
@@ -311,24 +311,22 @@ void GCodeAnalyzer::_processG1(const GCodeReader::GCodeLine& line)
{
auto axis_absolute_position = [this](GCodeAnalyzer::EAxis axis, const GCodeReader::GCodeLine& lineG1) -> float
{
- float current_absolute_position = _get_axis_position(axis);
- float current_origin = _get_axis_origin(axis);
- float lengthsScaleFactor = (_get_units() == GCodeAnalyzer::Inches) ? INCHES_TO_MM : 1.0f;
-
bool is_relative = (_get_global_positioning_type() == Relative);
if (axis == E)
is_relative |= (_get_e_local_positioning_type() == Relative);
if (lineG1.has(Slic3r::Axis(axis)))
{
+ float lengthsScaleFactor = (_get_units() == GCodeAnalyzer::Inches) ? INCHES_TO_MM : 1.0f;
float ret = lineG1.value(Slic3r::Axis(axis)) * lengthsScaleFactor;
- return is_relative ? current_absolute_position + ret : ret + current_origin;
+ return is_relative ? _get_axis_position(axis) + ret : _get_axis_origin(axis) + ret;
}
else
- return current_absolute_position;
+ return _get_axis_position(axis);
};
// updates axes positions from line
+
float new_pos[Num_Axis];
for (unsigned char a = X; a < Num_Axis; ++a)
{
@@ -352,7 +350,7 @@ void GCodeAnalyzer::_processG1(const GCodeReader::GCodeLine& line)
if (delta_pos[E] < 0.0f)
{
if ((delta_pos[X] != 0.0f) || (delta_pos[Y] != 0.0f) || (delta_pos[Z] != 0.0f))
- type = GCodeMove::Move;
+ type = GCodeMove::Move;
else
type = GCodeMove::Retract;
}
@@ -440,7 +438,9 @@ void GCodeAnalyzer::_processG92(const GCodeReader::GCodeLine& line)
if (line.has_e())
{
- _set_axis_origin(E, _get_axis_position(E) - line.e() * lengthsScaleFactor);
+ // extruder coordinate can grow to the point where its float representation does not allow for proper addition with small increments,
+ // we set the value taken from the G92 line as the new current position for it
+ _set_axis_position(E, line.e() * lengthsScaleFactor);
anyFound = true;
}
@@ -956,7 +956,7 @@ void GCodeAnalyzer::_calc_gcode_preview_extrusion_layers(GCodePreviewData& previ
GCodePreviewData::Extrusion::Path &path = paths.back();
path.polyline = polyline;
path.extrusion_role = data.extrusion_role;
- path.mm3_per_mm = data.mm3_per_mm;
+ path.mm3_per_mm = float(data.mm3_per_mm);
path.width = data.width;
path.height = data.height;
path.feedrate = data.feedrate;
@@ -978,7 +978,7 @@ void GCodeAnalyzer::_calc_gcode_preview_extrusion_layers(GCodePreviewData& previ
float volumetric_rate = FLT_MAX;
GCodePreviewData::Range height_range;
GCodePreviewData::Range width_range;
- GCodePreviewData::Range feedrate_range;
+ GCodePreviewData::MultiRange feedrate_range;
GCodePreviewData::Range volumetric_rate_range;
GCodePreviewData::Range fan_speed_range;
@@ -1013,7 +1013,7 @@ void GCodeAnalyzer::_calc_gcode_preview_extrusion_layers(GCodePreviewData& previ
volumetric_rate = move.data.feedrate * (float)move.data.mm3_per_mm;
height_range.update_from(move.data.height);
width_range.update_from(move.data.width);
- feedrate_range.update_from(move.data.feedrate);
+ feedrate_range.update_from(move.data.feedrate, GCodePreviewData::FeedrateKind::EXTRUSION);
volumetric_rate_range.update_from(volumetric_rate);
fan_speed_range.update_from(move.data.fan_speed);
}
@@ -1066,7 +1066,7 @@ void GCodeAnalyzer::_calc_gcode_preview_travel(GCodePreviewData& preview_data, s
GCodePreviewData::Range height_range;
GCodePreviewData::Range width_range;
- GCodePreviewData::Range feedrate_range;
+ GCodePreviewData::MultiRange feedrate_range;
// to avoid to call the callback too often
unsigned int cancel_callback_threshold = (unsigned int)std::max((int)travel_moves->second.size() / 25, 1);
@@ -1106,7 +1106,7 @@ void GCodeAnalyzer::_calc_gcode_preview_travel(GCodePreviewData& preview_data, s
extruder_id = move.data.extruder_id;
height_range.update_from(move.data.height);
width_range.update_from(move.data.width);
- feedrate_range.update_from(move.data.feedrate);
+ feedrate_range.update_from(move.data.feedrate, GCodePreviewData::FeedrateKind::TRAVEL);
}
// store last polyline
diff --git a/src/libslic3r/GCode/CoolingBuffer.cpp b/src/libslic3r/GCode/CoolingBuffer.cpp
index b00bc73eb..6815ea73a 100644
--- a/src/libslic3r/GCode/CoolingBuffer.cpp
+++ b/src/libslic3r/GCode/CoolingBuffer.cpp
@@ -303,8 +303,8 @@ std::vector CoolingBuffer::parse_layer_gcode(const std::
unsigned int extruder_id = extruders[i].id();
adj.extruder_id = extruder_id;
adj.cooling_slow_down_enabled = config.cooling.get_at(extruder_id);
- adj.slowdown_below_layer_time = config.slowdown_below_layer_time.get_at(extruder_id);
- adj.min_print_speed = config.min_print_speed.get_at(extruder_id);
+ adj.slowdown_below_layer_time = float(config.slowdown_below_layer_time.get_at(extruder_id));
+ adj.min_print_speed = float(config.min_print_speed.get_at(extruder_id));
map_extruder_to_per_extruder_adjustment[extruder_id] = i;
}
diff --git a/src/libslic3r/GCode/PreviewData.cpp b/src/libslic3r/GCode/PreviewData.cpp
index e7475089a..eecabe718 100644
--- a/src/libslic3r/GCode/PreviewData.cpp
+++ b/src/libslic3r/GCode/PreviewData.cpp
@@ -1,6 +1,5 @@
#include "Analyzer.hpp"
#include "PreviewData.hpp"
-#include
#include
#include "Utils.hpp"
@@ -11,9 +10,7 @@
namespace Slic3r {
-const GCodePreviewData::Color GCodePreviewData::Color::Dummy(0.0f, 0.0f, 0.0f, 0.0f);
-
-std::vector GCodePreviewData::Color::as_bytes() const
+std::vector Color::as_bytes() const
{
std::vector ret;
for (unsigned int i = 0; i < 4; ++i)
@@ -38,20 +35,6 @@ GCodePreviewData::Travel::Polyline::Polyline(EType type, EDirection direction, f
{
}
-const GCodePreviewData::Color GCodePreviewData::Range::Default_Colors[Colors_Count] =
-{
- Color(0.043f, 0.173f, 0.478f, 1.0f),
- Color(0.075f, 0.349f, 0.522f, 1.0f),
- Color(0.110f, 0.533f, 0.569f, 1.0f),
- Color(0.016f, 0.839f, 0.059f, 1.0f),
- Color(0.667f, 0.949f, 0.000f, 1.0f),
- Color(0.988f, 0.975f, 0.012f, 1.0f),
- Color(0.961f, 0.808f, 0.039f, 1.0f),
- Color(0.890f, 0.533f, 0.125f, 1.0f),
- Color(0.820f, 0.408f, 0.188f, 1.0f),
- Color(0.761f, 0.322f, 0.235f, 1.0f)
-};
-
GCodePreviewData::Range::Range()
{
reset();
@@ -59,69 +42,73 @@ GCodePreviewData::Range::Range()
void GCodePreviewData::Range::reset()
{
- min = FLT_MAX;
- max = -FLT_MAX;
+ min_val = FLT_MAX;
+ max_val = -FLT_MAX;
}
bool GCodePreviewData::Range::empty() const
{
- return min == max;
+ return min_val >= max_val;
}
void GCodePreviewData::Range::update_from(float value)
{
- min = std::min(min, value);
- max = std::max(max, value);
+ min_val = std::min(min_val, value);
+ max_val = std::max(max_val, value);
}
-void GCodePreviewData::Range::update_from(const Range& other)
+void GCodePreviewData::Range::update_from(const RangeBase& other)
{
- min = std::min(min, other.min);
- max = std::max(max, other.max);
+ min_val = std::min(min_val, other.min());
+ max_val = std::max(max_val, other.max());
}
-void GCodePreviewData::Range::set_from(const Range& other)
+float GCodePreviewData::RangeBase::step_size() const
{
- min = other.min;
- max = other.max;
+ return (max() - min()) / static_cast(range_rainbow_colors.size() - 1);
}
-float GCodePreviewData::Range::step_size() const
+Color GCodePreviewData::RangeBase::get_color_at(float value) const
{
- return (max - min) / (float)(Colors_Count - 1);
-}
+ // Input value scaled to the color range
+ float step = step_size();
+ const float global_t = (step != 0.0f) ? std::max(0.0f, value - min()) / step_size() : 0.0f; // lower limit of 0.0f
-GCodePreviewData::Color GCodePreviewData::Range::get_color_at(float value) const
-{
- if (empty())
- return Color::Dummy;
+ constexpr std::size_t color_max_idx = range_rainbow_colors.size() - 1;
- float global_t = (value - min) / step_size();
+ // Compute the two colors just below (low) and above (high) the input value
+ const std::size_t color_low_idx = std::clamp(static_cast(global_t), std::size_t{ 0 }, color_max_idx);
+ const std::size_t color_high_idx = std::clamp(color_low_idx + 1, std::size_t{ 0 }, color_max_idx);
- unsigned int low = (unsigned int)global_t;
- unsigned int high = clamp((unsigned int)0, Colors_Count - 1, low + 1);
+ // Compute how far the value is between the low and high colors so that they can be interpolated
+ const float local_t = std::min(global_t - static_cast(color_low_idx), 1.0f); // upper limit of 1.0f
- Color color_low = colors[low];
- Color color_high = colors[high];
-
- float local_t = global_t - (float)low;
-
- // interpolate in RGB space
+ // Interpolate between the low and high colors in RGB space to find exactly which color the input value should get
Color ret;
for (unsigned int i = 0; i < 4; ++i)
{
- ret.rgba[i] = lerp(color_low.rgba[i], color_high.rgba[i], local_t);
+ ret.rgba[i] = lerp(range_rainbow_colors[color_low_idx].rgba[i], range_rainbow_colors[color_high_idx].rgba[i], local_t);
}
return ret;
}
-GCodePreviewData::LegendItem::LegendItem(const std::string& text, const GCodePreviewData::Color& color)
+float GCodePreviewData::Range::min() const
+{
+ return min_val;
+}
+
+float GCodePreviewData::Range::max() const
+{
+ return max_val;
+}
+
+GCodePreviewData::LegendItem::LegendItem(const std::string& text, const Color& color)
: text(text)
, color(color)
{
}
-const GCodePreviewData::Color GCodePreviewData::Extrusion::Default_Extrusion_Role_Colors[erCount] =
+const Color GCodePreviewData::Extrusion::Default_Extrusion_Role_Colors[erCount] =
{
Color(0.0f, 0.0f, 0.0f, 1.0f), // erNone
Color(1.0f, 0.0f, 0.0f, 1.0f), // erPerimeter
@@ -180,7 +167,7 @@ size_t GCodePreviewData::Extrusion::memory_used() const
const float GCodePreviewData::Travel::Default_Width = 0.075f;
const float GCodePreviewData::Travel::Default_Height = 0.075f;
-const GCodePreviewData::Color GCodePreviewData::Travel::Default_Type_Colors[Num_Types] =
+const Color GCodePreviewData::Travel::Default_Type_Colors[Num_Types] =
{
Color(0.0f, 0.0f, 0.75f, 1.0f), // Move
Color(0.0f, 0.75f, 0.0f, 1.0f), // Extrude
@@ -206,7 +193,7 @@ size_t GCodePreviewData::Travel::memory_used() const
return out;
}
-const GCodePreviewData::Color GCodePreviewData::Retraction::Default_Color = GCodePreviewData::Color(1.0f, 1.0f, 1.0f, 1.0f);
+const Color GCodePreviewData::Retraction::Default_Color = Color(1.0f, 1.0f, 1.0f, 1.0f);
GCodePreviewData::Retraction::Position::Position(const Vec3crd& position, float width, float height)
: position(position)
@@ -238,17 +225,15 @@ GCodePreviewData::GCodePreviewData()
void GCodePreviewData::set_default()
{
- ::memcpy((void*)ranges.height.colors, (const void*)Range::Default_Colors, Range::Colors_Count * sizeof(Color));
- ::memcpy((void*)ranges.width.colors, (const void*)Range::Default_Colors, Range::Colors_Count * sizeof(Color));
- ::memcpy((void*)ranges.feedrate.colors, (const void*)Range::Default_Colors, Range::Colors_Count * sizeof(Color));
- ::memcpy((void*)ranges.fan_speed.colors, (const void*)Range::Default_Colors, Range::Colors_Count * sizeof(Color));
- ::memcpy((void*)ranges.volumetric_rate.colors, (const void*)Range::Default_Colors, Range::Colors_Count * sizeof(Color));
-
extrusion.set_default();
travel.set_default();
retraction.set_default();
unretraction.set_default();
shell.set_default();
+
+ // Configure the color range for feedrate to match the default for travels and to enable extrusions since they are always visible
+ ranges.feedrate.set_mode(FeedrateKind::TRAVEL, travel.is_visible);
+ ranges.feedrate.set_mode(FeedrateKind::EXTRUSION, true);
}
void GCodePreviewData::reset()
@@ -268,32 +253,32 @@ bool GCodePreviewData::empty() const
return extrusion.layers.empty() && travel.polylines.empty() && retraction.positions.empty() && unretraction.positions.empty();
}
-GCodePreviewData::Color GCodePreviewData::get_extrusion_role_color(ExtrusionRole role) const
+Color GCodePreviewData::get_extrusion_role_color(ExtrusionRole role) const
{
return extrusion.role_colors[role];
}
-GCodePreviewData::Color GCodePreviewData::get_height_color(float height) const
+Color GCodePreviewData::get_height_color(float height) const
{
return ranges.height.get_color_at(height);
}
-GCodePreviewData::Color GCodePreviewData::get_width_color(float width) const
+Color GCodePreviewData::get_width_color(float width) const
{
return ranges.width.get_color_at(width);
}
-GCodePreviewData::Color GCodePreviewData::get_feedrate_color(float feedrate) const
+Color GCodePreviewData::get_feedrate_color(float feedrate) const
{
return ranges.feedrate.get_color_at(feedrate);
}
-GCodePreviewData::Color GCodePreviewData::get_fan_speed_color(float fan_speed) const
+Color GCodePreviewData::get_fan_speed_color(float fan_speed) const
{
return ranges.fan_speed.get_color_at(fan_speed);
}
-GCodePreviewData::Color GCodePreviewData::get_volumetric_rate_color(float rate) const
+Color GCodePreviewData::get_volumetric_rate_color(float rate) const
{
return ranges.volumetric_rate.get_color_at(rate);
}
@@ -384,16 +369,25 @@ GCodePreviewData::LegendItemsList GCodePreviewData::get_legend_items(const std::
{
struct Helper
{
- static void FillListFromRange(LegendItemsList& list, const Range& range, unsigned int decimals, float scale_factor)
+ static void FillListFromRange(LegendItemsList& list, const RangeBase& range, unsigned int decimals, float scale_factor)
{
- list.reserve(Range::Colors_Count);
+ list.reserve(range_rainbow_colors.size());
float step = range.step_size();
- for (int i = Range::Colors_Count - 1; i >= 0; --i)
+ if (step == 0.0f)
{
char buf[1024];
- sprintf(buf, "%.*f", decimals, scale_factor * (range.min + (float)i * step));
- list.emplace_back(buf, range.colors[i]);
+ sprintf(buf, "%.*f", decimals, scale_factor * range.min());
+ list.emplace_back(buf, range_rainbow_colors[0]);
+ }
+ else
+ {
+ for (int i = static_cast(range_rainbow_colors.size()) - 1; i >= 0; --i)
+ {
+ char buf[1024];
+ sprintf(buf, "%.*f", decimals, scale_factor * (range.min() + (float)i * step));
+ list.emplace_back(buf, range_rainbow_colors[i]);
+ }
}
}
};
@@ -446,8 +440,8 @@ GCodePreviewData::LegendItemsList GCodePreviewData::get_legend_items(const std::
items.reserve(tools_colors_count);
for (unsigned int i = 0; i < tools_colors_count; ++i)
{
- GCodePreviewData::Color color;
- ::memcpy((void*)color.rgba, (const void*)(tool_colors.data() + i * 4), 4 * sizeof(float));
+ Color color;
+ ::memcpy((void*)color.rgba.data(), (const void*)(tool_colors.data() + i * 4), 4 * sizeof(float));
items.emplace_back((boost::format(Slic3r::I18N::translate(L("Extruder %d"))) % (i + 1)).str(), color);
}
@@ -460,7 +454,7 @@ GCodePreviewData::LegendItemsList GCodePreviewData::get_legend_items(const std::
if (color_print_cnt == 1) // means "Default print color"
{
Color color;
- ::memcpy((void*)color.rgba, (const void*)(tool_colors.data()), 4 * sizeof(float));
+ ::memcpy((void*)color.rgba.data(), (const void*)(tool_colors.data()), 4 * sizeof(float));
items.emplace_back(cp_items[0], color);
break;
@@ -472,7 +466,7 @@ GCodePreviewData::LegendItemsList GCodePreviewData::get_legend_items(const std::
for (int i = 0 ; i < color_print_cnt; ++i)
{
Color color;
- ::memcpy((void*)color.rgba, (const void*)(tool_colors.data() + i * 4), 4 * sizeof(float));
+ ::memcpy((void*)color.rgba.data(), (const void*)(tool_colors.data() + i * 4), 4 * sizeof(float));
items.emplace_back(cp_items[i], color);
}
@@ -502,20 +496,20 @@ const std::vector& GCodePreviewData::ColorPrintColors()
return color_print;
}
-GCodePreviewData::Color operator + (const GCodePreviewData::Color& c1, const GCodePreviewData::Color& c2)
+Color operator + (const Color& c1, const Color& c2)
{
- return GCodePreviewData::Color(clamp(0.0f, 1.0f, c1.rgba[0] + c2.rgba[0]),
- clamp(0.0f, 1.0f, c1.rgba[1] + c2.rgba[1]),
- clamp(0.0f, 1.0f, c1.rgba[2] + c2.rgba[2]),
- clamp(0.0f, 1.0f, c1.rgba[3] + c2.rgba[3]));
+ return Color(std::clamp(c1.rgba[0] + c2.rgba[0], 0.0f, 1.0f),
+ std::clamp(c1.rgba[1] + c2.rgba[1], 0.0f, 1.0f),
+ std::clamp(c1.rgba[2] + c2.rgba[2], 0.0f, 1.0f),
+ std::clamp(c1.rgba[3] + c2.rgba[3], 0.0f, 1.0f));
}
-GCodePreviewData::Color operator * (float f, const GCodePreviewData::Color& color)
+Color operator * (float f, const Color& color)
{
- return GCodePreviewData::Color(clamp(0.0f, 1.0f, f * color.rgba[0]),
- clamp(0.0f, 1.0f, f * color.rgba[1]),
- clamp(0.0f, 1.0f, f * color.rgba[2]),
- clamp(0.0f, 1.0f, f * color.rgba[3]));
+ return Color(std::clamp(f * color.rgba[0], 0.0f, 1.0f),
+ std::clamp(f * color.rgba[1], 0.0f, 1.0f),
+ std::clamp(f * color.rgba[2], 0.0f, 1.0f),
+ std::clamp(f * color.rgba[3], 0.0f, 1.0f));
}
} // namespace Slic3r
diff --git a/src/libslic3r/GCode/PreviewData.hpp b/src/libslic3r/GCode/PreviewData.hpp
index 725c0258d..35bbfa50a 100644
--- a/src/libslic3r/GCode/PreviewData.hpp
+++ b/src/libslic3r/GCode/PreviewData.hpp
@@ -5,43 +5,190 @@
#include "../ExtrusionEntity.hpp"
#include "../Point.hpp"
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include
+
namespace Slic3r {
+// Represents an RGBA color
+struct Color
+{
+ std::array rgba;
+
+ Color(const float *argba)
+ {
+ memcpy(this->rgba.data(), argba, sizeof(float) * 4);
+ }
+ constexpr Color(float r = 1.f, float g = 1.f, float b = 1.f, float a = 1.f) : rgba{r,g,b,a}
+ {
+ // Intentionally empty
+ }
+
+ std::vector as_bytes() const;
+};
+Color operator + (const Color& c1, const Color& c2);
+Color operator * (float f, const Color& color);
+
+// Default colors for Ranges
+constexpr std::array range_rainbow_colors{
+ Color{0.043f, 0.173f, 0.478f, 1.0f},
+ Color{0.075f, 0.349f, 0.522f, 1.0f},
+ Color{0.110f, 0.533f, 0.569f, 1.0f},
+ Color{0.016f, 0.839f, 0.059f, 1.0f},
+ Color{0.667f, 0.949f, 0.000f, 1.0f},
+ Color{0.988f, 0.975f, 0.012f, 1.0f},
+ Color{0.961f, 0.808f, 0.039f, 1.0f},
+ Color{0.890f, 0.533f, 0.125f, 1.0f},
+ Color{0.820f, 0.408f, 0.188f, 1.0f},
+ Color{0.761f, 0.322f, 0.235f, 1.0f}};
+
class GCodePreviewData
{
public:
- struct Color
+
+ // Color mapping to convert a float into a smooth rainbow of 10 colors.
+ class RangeBase
{
- float rgba[4];
+ public:
- Color(const float *argba) { memcpy(this->rgba, argba, sizeof(float) * 4); }
- Color(float r = 1.f, float g = 1.f, float b = 1.f, float a = 1.f) { rgba[0] = r; rgba[1] = g; rgba[2] = b; rgba[3] = a; }
-
- std::vector as_bytes() const;
-
- static const Color Dummy;
+ virtual void reset() = 0;
+ virtual bool empty() const = 0;
+ virtual float min() const = 0;
+ virtual float max() const = 0;
+
+ // Gets the step size using min(), max() and colors
+ float step_size() const;
+
+ // Gets the color at a value using colors, min(), and max()
+ Color get_color_at(float value) const;
};
-
- // Color mapping from a range into a smooth rainbow of 10 colors.
- struct Range
+
+ // Color mapping converting a float in a range between a min and a max into a smooth rainbow of 10 colors.
+ class Range : public RangeBase
{
- static const unsigned int Colors_Count = 10;
- static const Color Default_Colors[Colors_Count];
-
- Color colors[Colors_Count];
- float min;
- float max;
-
+ public:
Range();
- void reset();
- bool empty() const;
+ // RangeBase Overrides
+ void reset() override;
+ bool empty() const override;
+ float min() const override;
+ float max() const override;
+
+ // Range-specific methods
void update_from(float value);
- void update_from(const Range& other);
- void set_from(const Range& other);
- float step_size() const;
+ void update_from(const RangeBase& other);
- Color get_color_at(float value) const;
+ private:
+ float min_val;
+ float max_val;
+ };
+
+ // Like Range, but stores multiple ranges internally that are used depending on mode.
+ // Template param EnumRangeType must be an enum with values for each type of range that needs to be tracked in this MultiRange.
+ // The last enum value should be num_values. The numerical values of all enum values should range from 0 to num_values.
+ template
+ class MultiRange : public RangeBase
+ {
+ public:
+
+ void reset() override
+ {
+ bounds = decltype(bounds){};
+ }
+
+ bool empty() const override
+ {
+ for (std::size_t i = 0; i < bounds.size(); ++i)
+ {
+ if (bounds[i].min != bounds[i].max)
+ return false;
+ }
+ return true;
+ }
+
+ float min() const override
+ {
+ float min = FLT_MAX;
+ for (std::size_t i = 0; i < bounds.size(); ++i)
+ {
+ // Only use bounds[i] if the current mode includes it
+ if (mode.test(i))
+ {
+ min = std::min(min, bounds[i].min);
+ }
+ }
+ return min;
+ }
+
+ float max() const override
+ {
+ float max = -FLT_MAX;
+ for (std::size_t i = 0; i < bounds.size(); ++i)
+ {
+ // Only use bounds[i] if the current mode includes it
+ if (mode.test(i))
+ {
+ max = std::max(max, bounds[i].max);
+ }
+ }
+ return max;
+ }
+
+ void update_from(const float value, EnumRangeType range_type_value)
+ {
+ bounds[static_cast(range_type_value)].update_from(value);
+ }
+
+ void update_from(const MultiRange& other)
+ {
+ for (std::size_t i = 0; i < bounds.size(); ++i)
+ {
+ bounds[i].update_from(other.bounds[i]);
+ }
+ }
+
+ void set_mode(const EnumRangeType range_type_value, const bool enable)
+ {
+ mode.set(static_cast(range_type_value), enable);
+ }
+
+ private:
+
+ // Interval bounds
+ struct Bounds
+ {
+ float min{FLT_MAX};
+ float max{-FLT_MAX};
+ void update_from(const float value)
+ {
+ min = std::min(min, value);
+ max = std::max(max, value);
+ }
+ void update_from(const Bounds other_bounds)
+ {
+ min = std::min(min, other_bounds.min);
+ max = std::max(max, other_bounds.max);
+ }
+ };
+
+ std::array(EnumRangeType::num_values)> bounds;
+ std::bitset(EnumRangeType::num_values)> mode;
+ };
+
+ // Enum distinguishing different kinds of feedrate data
+ enum class FeedrateKind
+ {
+ EXTRUSION = 0, // values must go from 0 up to num_values
+ TRAVEL,
+ num_values //must be last in the list of values
};
struct Ranges
@@ -51,7 +198,7 @@ public:
// Color mapping by extrusion width.
Range width;
// Color mapping by feedrate.
- Range feedrate;
+ MultiRange feedrate;
// Color mapping by fan speed.
Range fan_speed;
// Color mapping by volumetric extrusion rate.
@@ -245,9 +392,6 @@ public:
static const std::vector& ColorPrintColors();
};
-GCodePreviewData::Color operator + (const GCodePreviewData::Color& c1, const GCodePreviewData::Color& c2);
-GCodePreviewData::Color operator * (float f, const GCodePreviewData::Color& color);
-
} // namespace Slic3r
#endif /* slic3r_GCode_PreviewData_hpp_ */
diff --git a/src/libslic3r/GCode/PrintExtents.cpp b/src/libslic3r/GCode/PrintExtents.cpp
index d44ef1aad..1fedcf3f0 100644
--- a/src/libslic3r/GCode/PrintExtents.cpp
+++ b/src/libslic3r/GCode/PrintExtents.cpp
@@ -29,7 +29,7 @@ static inline BoundingBox extrusion_polyline_extents(const Polyline &polyline, c
static inline BoundingBoxf extrusionentity_extents(const ExtrusionPath &extrusion_path)
{
- BoundingBox bbox = extrusion_polyline_extents(extrusion_path.polyline, scale_(0.5 * extrusion_path.width));
+ BoundingBox bbox = extrusion_polyline_extents(extrusion_path.polyline, coord_t(scale_(0.5 * extrusion_path.width)));
BoundingBoxf bboxf;
if (! empty(bbox)) {
bboxf.min = unscale(bbox.min);
@@ -43,7 +43,7 @@ static inline BoundingBoxf extrusionentity_extents(const ExtrusionLoop &extrusio
{
BoundingBox bbox;
for (const ExtrusionPath &extrusion_path : extrusion_loop.paths)
- bbox.merge(extrusion_polyline_extents(extrusion_path.polyline, scale_(0.5 * extrusion_path.width)));
+ bbox.merge(extrusion_polyline_extents(extrusion_path.polyline, coord_t(scale_(0.5 * extrusion_path.width))));
BoundingBoxf bboxf;
if (! empty(bbox)) {
bboxf.min = unscale(bbox.min);
@@ -57,7 +57,7 @@ static inline BoundingBoxf extrusionentity_extents(const ExtrusionMultiPath &ext
{
BoundingBox bbox;
for (const ExtrusionPath &extrusion_path : extrusion_multi_path.paths)
- bbox.merge(extrusion_polyline_extents(extrusion_path.polyline, scale_(0.5 * extrusion_path.width)));
+ bbox.merge(extrusion_polyline_extents(extrusion_path.polyline, coord_t(scale_(0.5 * extrusion_path.width))));
BoundingBoxf bboxf;
if (! empty(bbox)) {
bboxf.min = unscale(bbox.min);
diff --git a/src/libslic3r/GCode/ToolOrdering.cpp b/src/libslic3r/GCode/ToolOrdering.cpp
index b7d1d57df..3e01e2594 100644
--- a/src/libslic3r/GCode/ToolOrdering.cpp
+++ b/src/libslic3r/GCode/ToolOrdering.cpp
@@ -13,13 +13,17 @@
#include
#include
+#include
+
+#include "../GCodeWriter.hpp"
+
namespace Slic3r {
// Returns true in case that extruder a comes before b (b does not have to be present). False otherwise.
bool LayerTools::is_extruder_order(unsigned int a, unsigned int b) const
{
- if (a==b)
+ if (a == b)
return false;
for (auto extruder : extruders) {
@@ -32,6 +36,39 @@ bool LayerTools::is_extruder_order(unsigned int a, unsigned int b) const
return false;
}
+// Return a zero based extruder from the region, or extruder_override if overriden.
+unsigned int LayerTools::perimeter_extruder(const PrintRegion ®ion) const
+{
+ assert(region.config().perimeter_extruder.value > 0);
+ return ((this->extruder_override == 0) ? region.config().perimeter_extruder.value : this->extruder_override) - 1;
+}
+
+unsigned int LayerTools::infill_extruder(const PrintRegion ®ion) const
+{
+ assert(region.config().infill_extruder.value > 0);
+ return ((this->extruder_override == 0) ? region.config().infill_extruder.value : this->extruder_override) - 1;
+}
+
+unsigned int LayerTools::solid_infill_extruder(const PrintRegion ®ion) const
+{
+ assert(region.config().solid_infill_extruder.value > 0);
+ return ((this->extruder_override == 0) ? region.config().solid_infill_extruder.value : this->extruder_override) - 1;
+}
+
+// Returns a zero based extruder this eec should be printed with, according to PrintRegion config or extruder_override if overriden.
+unsigned int LayerTools::extruder(const ExtrusionEntityCollection &extrusions, const PrintRegion ®ion) const
+{
+ assert(region.config().perimeter_extruder.value > 0);
+ assert(region.config().infill_extruder.value > 0);
+ assert(region.config().solid_infill_extruder.value > 0);
+ // 1 based extruder ID.
+ unsigned int extruder = ((this->extruder_override == 0) ?
+ (is_infill(extrusions.role()) ?
+ (is_solid_infill(extrusions.entities.front()->role()) ? region.config().solid_infill_extruder : region.config().infill_extruder) :
+ region.config().perimeter_extruder.value) :
+ this->extruder_override);
+ return (extruder == 0) ? 0 : extruder - 1;
+}
// For the use case when each object is printed separately
// (print.config().complete_objects is true).
@@ -52,7 +89,7 @@ ToolOrdering::ToolOrdering(const PrintObject &object, unsigned int first_extrude
}
// Collect extruders reuqired to print the layers.
- this->collect_extruders(object);
+ this->collect_extruders(object, std::vector>());
// Reorder the extruders to minimize tool switches.
this->reorder_extruders(first_extruder);
@@ -89,9 +126,19 @@ ToolOrdering::ToolOrdering(const Print &print, unsigned int first_extruder, bool
this->initialize_layers(zs);
}
+ // Use the extruder switches from Model::custom_gcode_per_print_z to override the extruder to print the object.
+ // Do it only if all the objects were configured to be printed with a single extruder.
+ std::vector> per_layer_extruder_switches;
+ if (auto num_extruders = unsigned(print.config().nozzle_diameter.size());
+ num_extruders > 1 && print.object_extruders().size() == 1) {
+ // Printing a single extruder platter on a printer with more than 1 extruder (or single-extruder multi-material).
+ // There may be custom per-layer tool changes available at the model.
+ per_layer_extruder_switches = custom_tool_changes(print.model(), num_extruders);
+ }
+
// Collect extruders reuqired to print the layers.
for (auto object : print.objects())
- this->collect_extruders(*object);
+ this->collect_extruders(*object, per_layer_extruder_switches);
// Reorder the extruders to minimize tool switches.
this->reorder_extruders(first_extruder);
@@ -111,13 +158,13 @@ void ToolOrdering::initialize_layers(std::vector &zs)
coordf_t zmax = zs[i] + EPSILON;
for (; j < zs.size() && zs[j] <= zmax; ++ j) ;
// Assign an average print_z to the set of layers with nearly equal print_z.
- m_layer_tools.emplace_back(LayerTools(0.5 * (zs[i] + zs[j-1]), m_print_config_ptr));
+ m_layer_tools.emplace_back(LayerTools(0.5 * (zs[i] + zs[j-1])));
i = j;
}
}
// Collect extruders reuqired to print layers.
-void ToolOrdering::collect_extruders(const PrintObject &object)
+void ToolOrdering::collect_extruders(const PrintObject &object, const std::vector> &per_layer_extruder_switches)
{
// Collect the support extruders.
for (auto support_layer : object.support_layers()) {
@@ -134,9 +181,23 @@ void ToolOrdering::collect_extruders(const PrintObject &object)
if (has_support || has_interface)
layer_tools.has_support = true;
}
+
+ // Extruder overrides are ordered by print_z.
+ std::vector>::const_iterator it_per_layer_extruder_override;
+ it_per_layer_extruder_override = per_layer_extruder_switches.begin();
+ unsigned int extruder_override = 0;
+
// Collect the object extruders.
for (auto layer : object.layers()) {
LayerTools &layer_tools = this->tools_for_layer(layer->print_z);
+
+ // Override extruder with the next
+ for (; it_per_layer_extruder_override != per_layer_extruder_switches.end() && it_per_layer_extruder_override->first < layer->print_z + EPSILON; ++ it_per_layer_extruder_override)
+ extruder_override = (int)it_per_layer_extruder_override->second;
+
+ // Store the current extruder override (set to zero if no overriden), so that layer_tools.wiping_extrusions().is_overridable_and_mark() will use it.
+ layer_tools.extruder_override = extruder_override;
+
// What extruders are required to print this object layer?
for (size_t region_id = 0; region_id < object.region_volumes.size(); ++ region_id) {
const LayerRegion *layerm = (region_id < layer->regions().size()) ? layer->regions()[region_id] : nullptr;
@@ -150,19 +211,18 @@ void ToolOrdering::collect_extruders(const PrintObject &object)
if (m_print_config_ptr) { // in this case complete_objects is false (see ToolOrdering constructors)
something_nonoverriddable = false;
for (const auto& eec : layerm->perimeters.entities) // let's check if there are nonoverriddable entities
- if (!layer_tools.wiping_extrusions().is_overriddable(dynamic_cast(*eec), *m_print_config_ptr, object, region)) {
+ if (!layer_tools.wiping_extrusions().is_overriddable_and_mark(dynamic_cast(*eec), *m_print_config_ptr, object, region)) {
something_nonoverriddable = true;
break;
}
}
if (something_nonoverriddable)
- layer_tools.extruders.push_back(region.config().perimeter_extruder.value);
+ layer_tools.extruders.emplace_back((extruder_override == 0) ? region.config().perimeter_extruder.value : extruder_override);
layer_tools.has_object = true;
}
-
bool has_infill = false;
bool has_solid_infill = false;
bool something_nonoverriddable = false;
@@ -176,17 +236,19 @@ void ToolOrdering::collect_extruders(const PrintObject &object)
has_infill = true;
if (m_print_config_ptr) {
- if (!something_nonoverriddable && !layer_tools.wiping_extrusions().is_overriddable(*fill, *m_print_config_ptr, object, region))
+ if (!something_nonoverriddable && !layer_tools.wiping_extrusions().is_overriddable_and_mark(*fill, *m_print_config_ptr, object, region))
something_nonoverriddable = true;
}
}
- if (something_nonoverriddable || !m_print_config_ptr)
- {
- if (has_solid_infill)
- layer_tools.extruders.push_back(region.config().solid_infill_extruder);
- if (has_infill)
- layer_tools.extruders.push_back(region.config().infill_extruder);
+ if (something_nonoverriddable || !m_print_config_ptr) {
+ if (extruder_override == 0) {
+ if (has_solid_infill)
+ layer_tools.extruders.emplace_back(region.config().solid_infill_extruder);
+ if (has_infill)
+ layer_tools.extruders.emplace_back(region.config().infill_extruder);
+ } else if (has_solid_infill || has_infill)
+ layer_tools.extruders.emplace_back(extruder_override);
}
if (has_solid_infill || has_infill)
layer_tools.has_object = true;
@@ -199,7 +261,7 @@ void ToolOrdering::collect_extruders(const PrintObject &object)
// make sure that there are some tools for each object layer (e.g. tall wiping object will result in empty extruders vector)
if (layer.extruders.empty() && layer.has_object)
- layer.extruders.push_back(0); // 0="dontcare" extruder - it will be taken care of in reorder_extruders
+ layer.extruders.emplace_back(0); // 0="dontcare" extruder - it will be taken care of in reorder_extruders
}
}
@@ -254,11 +316,9 @@ void ToolOrdering::reorder_extruders(unsigned int last_extruder_id)
for (unsigned int &extruder_id : lt.extruders) {
assert(extruder_id > 0);
-- extruder_id;
- }
+ }
}
-
-
void ToolOrdering::fill_wipe_tower_partitions(const PrintConfig &config, coordf_t object_bottom_z)
{
if (m_layer_tools.empty())
@@ -394,17 +454,76 @@ void ToolOrdering::collect_extruder_statistics(bool prime_multi_material)
}
}
+// Assign a pointer to a custom G-code to the respective ToolOrdering::LayerTools.
+// Ignore color changes, which are performed on a layer and for such an extruder, that the extruder will not be printing above that layer.
+// If multiple events are planned over a span of a single layer, use the last one.
+void ToolOrdering::assign_custom_gcodes(const Print &print)
+{
+ // Only valid for non-sequential print.
+ assert(! print.config().complete_objects.value);
+ const Model::CustomGCodeInfo &custom_gcode_per_print_z = print.model().custom_gcode_per_print_z;
+ if (custom_gcode_per_print_z.gcodes.empty())
+ return;
+
+ unsigned int num_extruders = *std::max_element(m_all_printing_extruders.begin(), m_all_printing_extruders.end()) + 1;
+ std::vector extruder_printing_above(num_extruders, false);
+ auto custom_gcode_it = custom_gcode_per_print_z.gcodes.rbegin();
+ // If printing on a single extruder machine, make the tool changes trigger color change (M600) events.
+ bool tool_changes_as_color_changes = num_extruders == 1;
+ // From the last layer to the first one:
+ for (auto it_lt = m_layer_tools.rbegin(); it_lt != m_layer_tools.rend(); ++ it_lt) {
+ LayerTools < = *it_lt;
+ // Add the extruders of the current layer to the set of extruders printing at and above this print_z.
+ for (unsigned int i : lt.extruders)
+ extruder_printing_above[i] = true;
+ // Skip all custom G-codes above this layer and skip all extruder switches.
+ for (; custom_gcode_it != custom_gcode_per_print_z.gcodes.rend() && (custom_gcode_it->print_z > lt.print_z + EPSILON || custom_gcode_it->gcode == ToolChangeCode); ++ custom_gcode_it);
+ if (custom_gcode_it == custom_gcode_per_print_z.gcodes.rend())
+ // Custom G-codes were processed.
+ break;
+ // Some custom G-code is configured for this layer or a layer below.
+ const Model::CustomGCode &custom_gcode = *custom_gcode_it;
+ // print_z of the layer below the current layer.
+ coordf_t print_z_below = 0.;
+ if (auto it_lt_below = it_lt; ++ it_lt_below != m_layer_tools.rend())
+ print_z_below = it_lt_below->print_z;
+ if (custom_gcode.print_z > print_z_below + 0.5 * EPSILON) {
+ // The custom G-code applies to the current layer.
+ if ( tool_changes_as_color_changes || custom_gcode.gcode != ColorChangeCode ||
+ (custom_gcode.extruder <= num_extruders && extruder_printing_above[unsigned(custom_gcode.extruder - 1)]))
+ // If it is color change, it will actually be useful as the exturder above will print.
+ lt.custom_gcode = &custom_gcode;
+ // Consume that custom G-code event.
+ ++ custom_gcode_it;
+ }
+ }
+}
+
+const LayerTools& ToolOrdering::tools_for_layer(coordf_t print_z) const
+{
+ auto it_layer_tools = std::lower_bound(m_layer_tools.begin(), m_layer_tools.end(), LayerTools(print_z - EPSILON));
+ assert(it_layer_tools != m_layer_tools.end());
+ coordf_t dist_min = std::abs(it_layer_tools->print_z - print_z);
+ for (++ it_layer_tools; it_layer_tools != m_layer_tools.end(); ++ it_layer_tools) {
+ coordf_t d = std::abs(it_layer_tools->print_z - print_z);
+ if (d >= dist_min)
+ break;
+ dist_min = d;
+ }
+ -- it_layer_tools;
+ assert(dist_min < EPSILON);
+ return *it_layer_tools;
+}
// This function is called from Print::mark_wiping_extrusions and sets extruder this entity should be printed with (-1 .. as usual)
-void WipingExtrusions::set_extruder_override(const ExtrusionEntity* entity, unsigned int copy_id, int extruder, unsigned int num_of_copies)
+void WipingExtrusions::set_extruder_override(const ExtrusionEntity* entity, size_t copy_id, int extruder, size_t num_of_copies)
{
something_overridden = true;
- auto entity_map_it = (entity_map.insert(std::make_pair(entity, std::vector()))).first; // (add and) return iterator
- auto& copies_vector = entity_map_it->second;
- if (copies_vector.size() < num_of_copies)
- copies_vector.resize(num_of_copies, -1);
+ auto entity_map_it = (entity_map.emplace(entity, ExtruderPerCopy())).first; // (add and) return iterator
+ ExtruderPerCopy& copies_vector = entity_map_it->second;
+ copies_vector.resize(num_of_copies, -1);
if (copies_vector[copy_id] != -1)
std::cout << "ERROR: Entity extruder overriden multiple times!!!\n"; // A debugging message - this must never happen.
@@ -412,7 +531,6 @@ void WipingExtrusions::set_extruder_override(const ExtrusionEntity* entity, unsi
copies_vector[copy_id] = extruder;
}
-
// Finds first non-soluble extruder on the layer
int WipingExtrusions::first_nonsoluble_extruder_on_layer(const PrintConfig& print_config) const
{
@@ -435,11 +553,10 @@ int WipingExtrusions::last_nonsoluble_extruder_on_layer(const PrintConfig& print
return (-1);
}
-
// Decides whether this entity could be overridden
bool WipingExtrusions::is_overriddable(const ExtrusionEntityCollection& eec, const PrintConfig& print_config, const PrintObject& object, const PrintRegion& region) const
{
- if (print_config.filament_soluble.get_at(Print::get_extruder(eec, region)))
+ if (print_config.filament_soluble.get_at(m_layer_tools->extruder(eec, region)))
return false;
if (object.config().wipe_into_objects)
@@ -451,7 +568,6 @@ bool WipingExtrusions::is_overriddable(const ExtrusionEntityCollection& eec, con
return true;
}
-
// Following function iterates through all extrusions on the layer, remembers those that could be used for wiping after toolchange
// and returns volume that is left to be wiped on the wipe tower.
float WipingExtrusions::mark_wiping_extrusions(const Print& print, unsigned int old_extruder, unsigned int new_extruder, float volume_to_wipe)
@@ -459,8 +575,8 @@ float WipingExtrusions::mark_wiping_extrusions(const Print& print, unsigned int
const LayerTools& lt = *m_layer_tools;
const float min_infill_volume = 0.f; // ignore infill with smaller volume than this
- if (print.config().filament_soluble.get_at(old_extruder) || print.config().filament_soluble.get_at(new_extruder))
- return volume_to_wipe; // Soluble filament cannot be wiped in a random infill, neither the filament after it
+ if (! this->something_overridable || volume_to_wipe <= 0. || print.config().filament_soluble.get_at(old_extruder) || print.config().filament_soluble.get_at(new_extruder))
+ return std::max(0.f, volume_to_wipe); // Soluble filament cannot be wiped in a random infill, neither the filament after it
// we will sort objects so that dedicated for wiping are at the beginning:
PrintObjectPtrs object_list = print.objects();
@@ -483,13 +599,13 @@ float WipingExtrusions::mark_wiping_extrusions(const Print& print, unsigned int
const PrintObject* object = object_list[i];
// Finds this layer:
- auto this_layer_it = std::find_if(object->layers().begin(), object->layers().end(), [<](const Layer* lay) { return std::abs(lt.print_z - lay->print_z)layers().end())
- continue;
- const Layer* this_layer = *this_layer_it;
+ const Layer* this_layer = object->get_layer_at_printz(lt.print_z, EPSILON);
+ if (this_layer == nullptr)
+ continue;
size_t num_of_copies = object->copies().size();
- for (unsigned int copy = 0; copy < num_of_copies; ++copy) { // iterate through copies first, so that we mark neighbouring infills to minimize travel moves
+ // iterate through copies (aka PrintObject instances) first, so that we mark neighbouring infills to minimize travel moves
+ for (unsigned int copy = 0; copy < num_of_copies; ++copy) {
for (size_t region_id = 0; region_id < object->region_volumes.size(); ++ region_id) {
const auto& region = *object->print()->regions()[region_id];
@@ -497,51 +613,48 @@ float WipingExtrusions::mark_wiping_extrusions(const Print& print, unsigned int
if (!region.config().wipe_into_infill && !object->config().wipe_into_objects)
continue;
-
- if ((!print.config().infill_first ? perimeters_done : !perimeters_done) || (!object->config().wipe_into_objects && region.config().wipe_into_infill)) {
+ bool wipe_into_infill_only = ! object->config().wipe_into_objects && region.config().wipe_into_infill;
+ if (print.config().infill_first != perimeters_done || wipe_into_infill_only) {
for (const ExtrusionEntity* ee : this_layer->regions()[region_id]->fills.entities) { // iterate through all infill Collections
auto* fill = dynamic_cast(ee);
if (!is_overriddable(*fill, print.config(), *object, region))
continue;
- if (volume_to_wipe<=0)
- continue;
-
- if (!object->config().wipe_into_objects && !print.config().infill_first && region.config().wipe_into_infill)
+ if (wipe_into_infill_only && ! print.config().infill_first)
// In this case we must check that the original extruder is used on this layer before the one we are overridding
// (and the perimeters will be finished before the infill is printed):
- if (!lt.is_extruder_order(region.config().perimeter_extruder - 1, new_extruder))
+ if (!lt.is_extruder_order(lt.perimeter_extruder(region), new_extruder))
continue;
if ((!is_entity_overridden(fill, copy) && fill->total_volume() > min_infill_volume)) { // this infill will be used to wipe this extruder
set_extruder_override(fill, copy, new_extruder, num_of_copies);
- volume_to_wipe -= float(fill->total_volume());
+ if ((volume_to_wipe -= float(fill->total_volume())) <= 0.f)
+ // More material was purged already than asked for.
+ return 0.f;
}
}
}
// Now the same for perimeters - see comments above for explanation:
- if (object->config().wipe_into_objects && (print.config().infill_first ? perimeters_done : !perimeters_done))
+ if (object->config().wipe_into_objects && print.config().infill_first == perimeters_done)
{
for (const ExtrusionEntity* ee : this_layer->regions()[region_id]->perimeters.entities) {
auto* fill = dynamic_cast(ee);
- if (!is_overriddable(*fill, print.config(), *object, region))
- continue;
-
- if (volume_to_wipe<=0)
- continue;
-
- if ((!is_entity_overridden(fill, copy) && fill->total_volume() > min_infill_volume)) {
+ if (is_overriddable(*fill, print.config(), *object, region) && !is_entity_overridden(fill, copy) && fill->total_volume() > min_infill_volume) {
set_extruder_override(fill, copy, new_extruder, num_of_copies);
- volume_to_wipe -= float(fill->total_volume());
+ if ((volume_to_wipe -= float(fill->total_volume())) <= 0.f)
+ // More material was purged already than asked for.
+ return 0.f;
}
}
}
}
}
}
- return std::max(0.f, volume_to_wipe);
+ // Some purge remains to be done on the Wipe Tower.
+ assert(volume_to_wipe > 0.);
+ return volume_to_wipe;
}
@@ -552,16 +665,18 @@ float WipingExtrusions::mark_wiping_extrusions(const Print& print, unsigned int
// them again and make sure we override it.
void WipingExtrusions::ensure_perimeters_infills_order(const Print& print)
{
+ if (! this->something_overridable)
+ return;
+
const LayerTools& lt = *m_layer_tools;
unsigned int first_nonsoluble_extruder = first_nonsoluble_extruder_on_layer(print.config());
unsigned int last_nonsoluble_extruder = last_nonsoluble_extruder_on_layer(print.config());
for (const PrintObject* object : print.objects()) {
// Finds this layer:
- auto this_layer_it = std::find_if(object->layers().begin(), object->layers().end(), [<](const Layer* lay) { return std::abs(lt.print_z - lay->print_z)layers().end())
- continue;
- const Layer* this_layer = *this_layer_it;
+ const Layer* this_layer = object->get_layer_at_printz(lt.print_z, EPSILON);
+ if (this_layer == nullptr)
+ continue;
size_t num_of_copies = object->copies().size();
for (size_t copy = 0; copy < num_of_copies; ++copy) { // iterate through copies first, so that we mark neighbouring infills to minimize travel moves
@@ -584,9 +699,8 @@ void WipingExtrusions::ensure_perimeters_infills_order(const Print& print)
// Either way, we will now force-override it with something suitable:
if (print.config().infill_first
|| object->config().wipe_into_objects // in this case the perimeter is overridden, so we can override by the last one safely
- || lt.is_extruder_order(region.config().perimeter_extruder - 1, last_nonsoluble_extruder // !infill_first, but perimeter is already printed when last extruder prints
- || std::find(lt.extruders.begin(), lt.extruders.end(), region.config().infill_extruder - 1) == lt.extruders.end()) // we have to force override - this could violate infill_first (FIXME)
- )
+ || lt.is_extruder_order(lt.perimeter_extruder(region), last_nonsoluble_extruder // !infill_first, but perimeter is already printed when last extruder prints
+ || ! lt.has_extruder(lt.infill_extruder(region)))) // we have to force override - this could violate infill_first (FIXME)
set_extruder_override(fill, copy, (print.config().infill_first ? first_nonsoluble_extruder : last_nonsoluble_extruder), num_of_copies);
else {
// In this case we can (and should) leave it to be printed normally.
@@ -597,42 +711,31 @@ void WipingExtrusions::ensure_perimeters_infills_order(const Print& print)
// Now the same for perimeters - see comments above for explanation:
for (const ExtrusionEntity* ee : this_layer->regions()[region_id]->perimeters.entities) { // iterate through all perimeter Collections
auto* fill = dynamic_cast(ee);
- if (!is_overriddable(*fill, print.config(), *object, region)
- || is_entity_overridden(fill, copy) )
- continue;
-
- set_extruder_override(fill, copy, (print.config().infill_first ? last_nonsoluble_extruder : first_nonsoluble_extruder), num_of_copies);
+ if (is_overriddable(*fill, print.config(), *object, region) && ! is_entity_overridden(fill, copy))
+ set_extruder_override(fill, copy, (print.config().infill_first ? last_nonsoluble_extruder : first_nonsoluble_extruder), num_of_copies);
}
}
}
}
}
-
-
-
-
-
-
-// Following function is called from process_layer and returns pointer to vector with information about which extruders should be used for given copy of this entity.
-// It first makes sure the pointer is valid (creates the vector if it does not exist) and contains a record for each copy
-// It also modifies the vector in place and changes all -1 to correct_extruder_id (at the time the overrides were created, correct extruders were not known,
-// so -1 was used as "print as usual".
-// The resulting vector has to keep track of which extrusions are the ones that were overridden and which were not. In the extruder is used as overridden,
-// its number is saved as it is (zero-based index). Usual extrusions are saved as -number-1 (unfortunately there is no negative zero).
-const std::vector* WipingExtrusions::get_extruder_overrides(const ExtrusionEntity* entity, int correct_extruder_id, size_t num_of_copies)
+// Following function is called from GCode::process_layer and returns pointer to vector with information about which extruders should be used for given copy of this entity.
+// If this extrusion does not have any override, nullptr is returned.
+// Otherwise it modifies the vector in place and changes all -1 to correct_extruder_id (at the time the overrides were created, correct extruders were not known,
+// so -1 was used as "print as usual").
+// The resulting vector therefore keeps track of which extrusions are the ones that were overridden and which were not. If the extruder used is overridden,
+// its number is saved as is (zero-based index). Regular extrusions are saved as -number-1 (unfortunately there is no negative zero).
+const WipingExtrusions::ExtruderPerCopy* WipingExtrusions::get_extruder_overrides(const ExtrusionEntity* entity, int correct_extruder_id, size_t num_of_copies)
{
+ ExtruderPerCopy *overrides = nullptr;
auto entity_map_it = entity_map.find(entity);
- if (entity_map_it == entity_map.end())
- entity_map_it = (entity_map.insert(std::make_pair(entity, std::vector()))).first;
-
- // Now the entity_map_it should be valid, let's make sure the vector is long enough:
- entity_map_it->second.resize(num_of_copies, -1);
-
- // Each -1 now means "print as usual" - we will replace it with actual extruder id (shifted it so we don't lose that information):
- std::replace(entity_map_it->second.begin(), entity_map_it->second.end(), -1, -correct_extruder_id-1);
-
- return &(entity_map_it->second);
+ if (entity_map_it != entity_map.end()) {
+ overrides = &entity_map_it->second;
+ overrides->resize(num_of_copies, -1);
+ // Each -1 now means "print as usual" - we will replace it with actual extruder id (shifted it so we don't lose that information):
+ std::replace(overrides->begin(), overrides->end(), -1, -correct_extruder_id-1);
+ }
+ return overrides;
}
diff --git a/src/libslic3r/GCode/ToolOrdering.hpp b/src/libslic3r/GCode/ToolOrdering.hpp
index 0d4b83ecb..08dd72656 100644
--- a/src/libslic3r/GCode/ToolOrdering.hpp
+++ b/src/libslic3r/GCode/ToolOrdering.hpp
@@ -5,6 +5,10 @@
#include "../libslic3r.h"
+#include
+
+#include
+
namespace Slic3r {
class Print;
@@ -23,8 +27,19 @@ public:
return something_overridden;
}
+ // When allocating extruder overrides of an object's ExtrusionEntity, overrides for maximum 3 copies are allocated in place.
+ typedef boost::container::small_vector ExtruderPerCopy;
+
+ class ExtruderOverrides
+ {
+ public:
+ ExtruderOverrides(const ExtruderPerCopy *overrides, const int correct_extruder_id) : m_overrides(overrides) {}
+ private:
+ const ExtruderPerCopy *m_overrides;
+ };
+
// This is called from GCode::process_layer - see implementation for further comments:
- const std::vector* get_extruder_overrides(const ExtrusionEntity* entity, int correct_extruder_id, size_t num_of_copies);
+ const ExtruderPerCopy* get_extruder_overrides(const ExtrusionEntity* entity, int correct_extruder_id, size_t num_of_copies);
// This function goes through all infill entities, decides which ones will be used for wiping and
// marks them by the extruder id. Returns volume that remains to be wiped on the wipe tower:
@@ -33,6 +48,11 @@ public:
void ensure_perimeters_infills_order(const Print& print);
bool is_overriddable(const ExtrusionEntityCollection& ee, const PrintConfig& print_config, const PrintObject& object, const PrintRegion& region) const;
+ bool is_overriddable_and_mark(const ExtrusionEntityCollection& ee, const PrintConfig& print_config, const PrintObject& object, const PrintRegion& region) {
+ bool out = this->is_overriddable(ee, print_config, object, region);
+ this->something_overridable |= out;
+ return out;
+ }
void set_layer_tools_ptr(const LayerTools* lt) { m_layer_tools = lt; }
@@ -41,14 +61,16 @@ private:
int last_nonsoluble_extruder_on_layer(const PrintConfig& print_config) const;
// This function is called from mark_wiping_extrusions and sets extruder that it should be printed with (-1 .. as usual)
- void set_extruder_override(const ExtrusionEntity* entity, unsigned int copy_id, int extruder, unsigned int num_of_copies);
+ void set_extruder_override(const ExtrusionEntity* entity, size_t copy_id, int extruder, size_t num_of_copies);
// Returns true in case that entity is not printed with its usual extruder for a given copy:
bool is_entity_overridden(const ExtrusionEntity* entity, size_t copy_id) const {
- return (entity_map.find(entity) == entity_map.end() ? false : entity_map.at(entity).at(copy_id) != -1);
+ auto it = entity_map.find(entity);
+ return it == entity_map.end() ? false : it->second[copy_id] != -1;
}
- std::map> entity_map; // to keep track of who prints what
+ std::map entity_map; // to keep track of who prints what
+ bool something_overridable = false;
bool something_overridden = false;
const LayerTools* m_layer_tools; // so we know which LayerTools object this belongs to
};
@@ -58,13 +80,7 @@ private:
class LayerTools
{
public:
- LayerTools(const coordf_t z, const PrintConfig* print_config_ptr = nullptr) :
- print_z(z),
- has_object(false),
- has_support(false),
- has_wipe_tower(false),
- wipe_tower_partitions(0),
- wipe_tower_layer_height(0.) {}
+ LayerTools(const coordf_t z) : print_z(z) {}
// Changing these operators to epsilon version can make a problem in cases where support and object layers get close to each other.
// In case someone tries to do it, make sure you know what you're doing and test it properly (slice multiple objects at once with supports).
@@ -72,20 +88,33 @@ public:
bool operator==(const LayerTools &rhs) const { return print_z == rhs.print_z; }
bool is_extruder_order(unsigned int a, unsigned int b) const;
+ bool has_extruder(unsigned int extruder) const { return std::find(this->extruders.begin(), this->extruders.end(), extruder) != this->extruders.end(); }
- coordf_t print_z;
- bool has_object;
- bool has_support;
+ // Return a zero based extruder from the region, or extruder_override if overriden.
+ unsigned int perimeter_extruder(const PrintRegion ®ion) const;
+ unsigned int infill_extruder(const PrintRegion ®ion) const;
+ unsigned int solid_infill_extruder(const PrintRegion ®ion) const;
+ // Returns a zero based extruder this eec should be printed with, according to PrintRegion config or extruder_override if overriden.
+ unsigned int extruder(const ExtrusionEntityCollection &extrusions, const PrintRegion ®ion) const;
+
+ coordf_t print_z = 0.;
+ bool has_object = false;
+ bool has_support = false;
// Zero based extruder IDs, ordered to minimize tool switches.
std::vector extruders;
+ // If per layer extruder switches are inserted by the G-code preview slider, this value contains the new (1 based) extruder, with which the whole object layer is being printed with.
+ // If not overriden, it is set to 0.
+ unsigned int extruder_override = 0;
// Will there be anything extruded on this layer for the wipe tower?
// Due to the support layers possibly interleaving the object layers,
// wipe tower will be disabled for some support only layers.
- bool has_wipe_tower;
+ bool has_wipe_tower = false;
// Number of wipe tower partitions to support the required number of tool switches
// and to support the wipe tower partitions above this one.
- size_t wipe_tower_partitions;
- coordf_t wipe_tower_layer_height;
+ size_t wipe_tower_partitions = 0;
+ coordf_t wipe_tower_layer_height = 0.;
+ // Custom G-code (color change, extruder switch, pause) to be performed before this layer starts to print.
+ const Model::CustomGCode *custom_gcode = nullptr;
WipingExtrusions& wiping_extrusions() {
m_wiping_extrusions.set_layer_tools_ptr(this);
@@ -106,14 +135,20 @@ public:
// For the use case when each object is printed separately
// (print.config.complete_objects is true).
- ToolOrdering(const PrintObject &object, unsigned int first_extruder = (unsigned int)-1, bool prime_multi_material = false);
+ ToolOrdering(const PrintObject &object, unsigned int first_extruder, bool prime_multi_material = false);
// For the use case when all objects are printed at once.
// (print.config.complete_objects is false).
- ToolOrdering(const Print &print, unsigned int first_extruder = (unsigned int)-1, bool prime_multi_material = false);
+ ToolOrdering(const Print &print, unsigned int first_extruder, bool prime_multi_material = false);
void clear() { m_layer_tools.clear(); }
+ // Only valid for non-sequential print:
+ // Assign a pointer to a custom G-code to the respective ToolOrdering::LayerTools.
+ // Ignore color changes, which are performed on a layer and for such an extruder, that the extruder will not be printing above that layer.
+ // If multiple events are planned over a span of a single layer, use the last one.
+ void assign_custom_gcodes(const Print &print);
+
// Get the first extruder printing, including the extruder priming areas, returns -1 if there is no layer printed.
unsigned int first_extruder() const { return m_first_printing_extruder; }
@@ -123,25 +158,9 @@ public:
// For a multi-material print, the printing extruders are ordered in the order they shall be primed.
const std::vector& all_extruders() const { return m_all_printing_extruders; }
- template static auto tools_for_layer(Self& self, coordf_t print_z) -> decltype (*self.m_layer_tools.begin())
- {
- auto it_layer_tools = std::lower_bound(self.m_layer_tools.begin(), self.m_layer_tools.end(), LayerTools(print_z - EPSILON));
- assert(it_layer_tools != self.m_layer_tools.end());
- coordf_t dist_min = std::abs(it_layer_tools->print_z - print_z);
- for (++ it_layer_tools; it_layer_tools != self.m_layer_tools.end(); ++it_layer_tools) {
- coordf_t d = std::abs(it_layer_tools->print_z - print_z);
- if (d >= dist_min)
- break;
- dist_min = d;
- }
- -- it_layer_tools;
- assert(dist_min < EPSILON);
- return *it_layer_tools;
- }
-
// Find LayerTools with the closest print_z.
- LayerTools& tools_for_layer(coordf_t print_z) { return tools_for_layer(*this, print_z); }
- const LayerTools& tools_for_layer(coordf_t print_z) const { return tools_for_layer(*this, print_z); }
+ const LayerTools& tools_for_layer(coordf_t print_z) const;
+ LayerTools& tools_for_layer(coordf_t print_z) { return const_cast(std::as_const(*this).tools_for_layer(print_z)); }
const LayerTools& front() const { return m_layer_tools.front(); }
const LayerTools& back() const { return m_layer_tools.back(); }
@@ -153,7 +172,7 @@ public:
private:
void initialize_layers(std::vector &zs);
- void collect_extruders(const PrintObject &object);
+ void collect_extruders(const PrintObject &object, const std::vector> &per_layer_extruder_switches);
void reorder_extruders(unsigned int last_extruder_id);
void fill_wipe_tower_partitions(const PrintConfig &config, coordf_t object_bottom_z);
void collect_extruder_statistics(bool prime_multi_material);
@@ -166,7 +185,6 @@ private:
// All extruders, which extrude some material over m_layer_tools.
std::vector m_all_printing_extruders;
-
const PrintConfig* m_print_config_ptr = nullptr;
};
diff --git a/src/libslic3r/GCodeTimeEstimator.cpp b/src/libslic3r/GCodeTimeEstimator.cpp
index c624c0fce..36127cad7 100644
--- a/src/libslic3r/GCodeTimeEstimator.cpp
+++ b/src/libslic3r/GCodeTimeEstimator.cpp
@@ -1261,7 +1261,9 @@ namespace Slic3r {
if (line.has_e())
{
- set_axis_origin(E, get_axis_position(E) - line.e() * lengthsScaleFactor);
+ // extruder coordinate can grow to the point where its float representation does not allow for proper addition with small increments,
+ // we set the value taken from the G92 line as the new current position for it
+ set_axis_position(E, line.e() * lengthsScaleFactor);
anyFound = true;
}
else
diff --git a/src/libslic3r/GCodeWriter.cpp b/src/libslic3r/GCodeWriter.cpp
index 364ba12ae..4c53048dc 100644
--- a/src/libslic3r/GCodeWriter.cpp
+++ b/src/libslic3r/GCodeWriter.cpp
@@ -19,12 +19,13 @@ void GCodeWriter::apply_print_config(const PrintConfig &print_config)
this->config.apply(print_config, true);
m_extrusion_axis = this->config.get_extrusion_axis();
m_single_extruder_multi_material = print_config.single_extruder_multi_material.value;
- m_max_acceleration = (print_config.gcode_flavor.value == gcfMarlin) ?
- print_config.machine_max_acceleration_extruding.values.front() : 0;
+ m_max_acceleration = std::lrint((print_config.gcode_flavor.value == gcfMarlin) ?
+ print_config.machine_max_acceleration_extruding.values.front() : 0);
}
-void GCodeWriter::set_extruders(const std::vector &extruder_ids)
+void GCodeWriter::set_extruders(std::vector extruder_ids)
{
+ std::sort(extruder_ids.begin(), extruder_ids.end());
m_extruders.clear();
m_extruders.reserve(extruder_ids.size());
for (unsigned int extruder_id : extruder_ids)
@@ -247,9 +248,9 @@ std::string GCodeWriter::toolchange_prefix() const
std::string GCodeWriter::toolchange(unsigned int extruder_id)
{
// set the new extruder
- auto it_extruder = std::lower_bound(m_extruders.begin(), m_extruders.end(), Extruder::key(extruder_id));
- assert(it_extruder != m_extruders.end());
- m_extruder = const_cast(&*it_extruder);
+ auto it_extruder = Slic3r::lower_bound_by_predicate(m_extruders.begin(), m_extruders.end(), [extruder_id](const Extruder &e) { return e.id() < extruder_id; });
+ assert(it_extruder != m_extruders.end() && it_extruder->id() == extruder_id);
+ m_extruder = &*it_extruder;
// return the toolchange command
// if we are running a single-extruder setup, just set the extruder and return nothing
diff --git a/src/libslic3r/GCodeWriter.hpp b/src/libslic3r/GCodeWriter.hpp
index 98abdda28..abeaf0024 100644
--- a/src/libslic3r/GCodeWriter.hpp
+++ b/src/libslic3r/GCodeWriter.hpp
@@ -13,7 +13,7 @@ namespace Slic3r {
// Additional Codes which can be set by user using DoubleSlider
static constexpr char ColorChangeCode[] = "M600";
static constexpr char PausePrintCode[] = "M601";
-static constexpr char ExtruderChangeCode[] = "tool_change";
+static constexpr char ToolChangeCode[] = "tool_change";
class GCodeWriter {
public:
@@ -33,7 +33,7 @@ public:
std::string extrusion_axis() const { return m_extrusion_axis; }
void apply_print_config(const PrintConfig &print_config);
// Extruders are expected to be sorted in an increasing order.
- void set_extruders(const std::vector &extruder_ids);
+ void set_extruders(std::vector extruder_ids);
const std::vector& extruders() const { return m_extruders; }
std::vector extruder_ids() const {
std::vector out;
@@ -74,7 +74,8 @@ public:
Vec3d get_position() const { return m_pos; }
private:
- std::vector m_extruders;
+ // Extruders are sorted by their ID, so that binary search is possible.
+ std::vector m_extruders;
std::string m_extrusion_axis;
bool m_single_extruder_multi_material;
Extruder* m_extruder;
diff --git a/src/libslic3r/Model.cpp b/src/libslic3r/Model.cpp
index 5f5199efb..0513653a2 100644
--- a/src/libslic3r/Model.cpp
+++ b/src/libslic3r/Model.cpp
@@ -126,7 +126,7 @@ Model Model::read_from_file(const std::string& input_file, DynamicPrintConfig* c
if (add_default_instances)
model.add_default_instances();
- update_custom_gcode_per_print_z_from_config(model.custom_gcode_per_print_z, config);
+ update_custom_gcode_per_print_z_from_config(model.custom_gcode_per_print_z.gcodes, config);
return model;
}
@@ -163,7 +163,7 @@ Model Model::read_from_archive(const std::string& input_file, DynamicPrintConfig
if (add_default_instances)
model.add_default_instances();
- update_custom_gcode_per_print_z_from_config(model.custom_gcode_per_print_z, config);
+ update_custom_gcode_per_print_z_from_config(model.custom_gcode_per_print_z.gcodes, config);
return model;
}
@@ -598,21 +598,6 @@ std::string Model::propose_export_file_name_and_path(const std::string &new_exte
return boost::filesystem::path(this->propose_export_file_name_and_path()).replace_extension(new_extension).string();
}
-std::vector> Model::get_custom_tool_changes(double default_layer_height, size_t num_extruders) const
-{
- std::vector> custom_tool_changes;
- for (const CustomGCode& custom_gcode : custom_gcode_per_print_z)
- if (custom_gcode.gcode == ExtruderChangeCode) {
- DynamicPrintConfig config;
- // If extruder count in PrinterSettings was changed, use default (0) extruder for extruders, more than num_extruders
- config.set_key_value("extruder", new ConfigOptionInt(custom_gcode.extruder > num_extruders ? 0 : custom_gcode.extruder));
- // For correct extruders(tools) changing, we should decrease custom_gcode.height value by one default layer height
- custom_tool_changes.push_back({ custom_gcode.print_z - default_layer_height, config });
- }
-
- return custom_tool_changes;
-}
-
ModelObject::~ModelObject()
{
this->clear_volumes();
@@ -860,7 +845,7 @@ TriangleMesh ModelObject::mesh() const
}
// Non-transformed (non-rotated, non-scaled, non-translated) sum of non-modifier object volumes.
-// Currently used by ModelObject::mesh(), to calculate the 2D envelope for 2D platter
+// Currently used by ModelObject::mesh(), to calculate the 2D envelope for 2D plater
// and to display the object statistics at ModelObject::print_info().
TriangleMesh ModelObject::raw_mesh() const
{
@@ -1863,6 +1848,19 @@ arrangement::ArrangePolygon ModelInstance::get_arrange_polygon() const
return ret;
}
+// Return pairs of sorted by increasing print_z from custom_gcode_per_print_z.
+// print_z corresponds to the first layer printed with the new extruder.
+std::vector> custom_tool_changes(const Model &model, size_t num_extruders)
+{
+ std::vector> custom_tool_changes;
+ for (const Model::CustomGCode &custom_gcode : model.custom_gcode_per_print_z.gcodes)
+ if (custom_gcode.gcode == ToolChangeCode) {
+ // If extruder count in PrinterSettings was changed, use default (0) extruder for extruders, more than num_extruders
+ custom_tool_changes.emplace_back(custom_gcode.print_z, static_cast(custom_gcode.extruder > num_extruders ? 1 : custom_gcode.extruder));
+ }
+ return custom_tool_changes;
+}
+
// Test whether the two models contain the same number of ModelObjects with the same set of IDs
// ordered in the same order. In that case it is not necessary to kill the background processing.
bool model_object_list_equal(const Model &model_old, const Model &model_new)
diff --git a/src/libslic3r/Model.hpp b/src/libslic3r/Model.hpp
index 934eea94f..5f07acc6a 100644
--- a/src/libslic3r/Model.hpp
+++ b/src/libslic3r/Model.hpp
@@ -240,7 +240,7 @@ public:
// A mesh containing all transformed instances of this object.
TriangleMesh mesh() const;
// Non-transformed (non-rotated, non-scaled, non-translated) sum of non-modifier object volumes.
- // Currently used by ModelObject::mesh() and to calculate the 2D envelope for 2D platter.
+ // Currently used by ModelObject::mesh() and to calculate the 2D envelope for 2D plater.
TriangleMesh raw_mesh() const;
// Non-transformed (non-rotated, non-scaled, non-translated) sum of all object volumes.
TriangleMesh full_raw_mesh() const;
@@ -403,13 +403,9 @@ public:
int object_idx{ -1 };
int volume_idx{ -1 };
Vec3d mesh_offset{ Vec3d::Zero() };
-#if ENABLE_KEEP_LOADED_VOLUME_TRANSFORM_AS_STAND_ALONE
Geometry::Transformation transform;
template void serialize(Archive& ar) { ar(input_file, object_idx, volume_idx, mesh_offset, transform); }
-#else
- template void serialize(Archive& ar) { ar(input_file, object_idx, volume_idx, mesh_offset); }
-#endif // ENABLE_KEEP_LOADED_VOLUME_TRANSFORM_AS_STAND_ALONE
};
Source source;
@@ -771,12 +767,34 @@ public:
double print_z;
std::string gcode;
- int extruder; // 0 - "gcode" will be applied for whole print
- // else - "gcode" will be applied only for "extruder" print
+ int extruder; // Informative value for ColorChangeCode and ToolChangeCode
+ // "gcode" == ColorChangeCode => M600 will be applied for "extruder" extruder
+ // "gcode" == ToolChangeCode => for whole print tool will be switched to "extruder" extruder
std::string color; // if gcode is equal to PausePrintCode,
// this field is used for save a short message shown on Printer display
};
- std::vector custom_gcode_per_print_z;
+
+ struct CustomGCodeInfo
+ {
+ enum MODE
+ {
+ SingleExtruder, // single extruder printer preset is selected
+ MultiAsSingle, // multiple extruder printer preset is selected, but
+ // this mode works just for Single extruder print
+ // (For all print from objects settings is used just one extruder)
+ MultiExtruder // multiple extruder printer preset is selected
+ } mode;
+
+ std::vector gcodes;
+
+ bool operator==(const CustomGCodeInfo& rhs) const
+ {
+ return (rhs.mode == this->mode ) &&
+ (rhs.gcodes == this->gcodes );
+ }
+ bool operator!=(const CustomGCodeInfo& rhs) const { return !(*this == rhs); }
+ }
+ custom_gcode_per_print_z;
// Default constructor assigns a new ID to the model.
Model() { assert(this->id().valid()); }
@@ -842,9 +860,6 @@ public:
// Propose an output path, replace extension. The new_extension shall contain the initial dot.
std::string propose_export_file_name_and_path(const std::string &new_extension) const;
- // from custom_gcode_per_print_z get just tool_change codes
- std::vector> get_custom_tool_changes(double default_layer_height, size_t num_extruders) const;
-
private:
explicit Model(int) : ObjectBase(-1) { assert(this->id().invalid()); };
void assign_new_unique_ids_recursive();
@@ -861,6 +876,10 @@ private:
#undef OBJECTBASE_DERIVED_COPY_MOVE_CLONE
#undef OBJECTBASE_DERIVED_PRIVATE_COPY_MOVE
+// Return pairs of sorted by increasing print_z from custom_gcode_per_print_z.
+// print_z corresponds to the first layer printed with the new extruder.
+extern std::vector> custom_tool_changes(const Model &model, size_t num_extruders);
+
// Test whether the two models contain the same number of ModelObjects with the same set of IDs
// ordered in the same order. In that case it is not necessary to kill the background processing.
extern bool model_object_list_equal(const Model &model_old, const Model &model_new);
diff --git a/src/libslic3r/PlaceholderParser.cpp b/src/libslic3r/PlaceholderParser.cpp
index 0cfd97415..bbf32a141 100644
--- a/src/libslic3r/PlaceholderParser.cpp
+++ b/src/libslic3r/PlaceholderParser.cpp
@@ -332,6 +332,21 @@ namespace client
return expr();
}
+ expr unary_integer(const Iterator start_pos) const
+ {
+ switch (this->type) {
+ case TYPE_INT :
+ return expr(this->i(), start_pos, this->it_range.end());
+ case TYPE_DOUBLE:
+ return expr((int)(this->d()), start_pos, this->it_range.end());
+ default:
+ this->throw_exception("Cannot convert to integer.");
+ }
+ assert(false);
+ // Suppress compiler warnings.
+ return expr();
+ }
+
expr unary_not(const Iterator start_pos) const
{
switch (this->type) {
@@ -415,6 +430,22 @@ namespace client
return *this;
}
+ expr &operator%=(const expr &rhs)
+ {
+ this->throw_if_not_numeric("Cannot divide a non-numeric type.");
+ rhs.throw_if_not_numeric("Cannot divide with a non-numeric type.");
+ if ((this->type == TYPE_INT) ? (rhs.i() == 0) : (rhs.d() == 0.))
+ rhs.throw_exception("Division by zero");
+ if (this->type == TYPE_DOUBLE || rhs.type == TYPE_DOUBLE) {
+ double d = std::fmod(this->as_d(), rhs.as_d());
+ this->data.d = d;
+ this->type = TYPE_DOUBLE;
+ } else
+ this->data.i %= rhs.i();
+ this->it_range = boost::iterator_range(this->it_range.begin(), rhs.it_range.end());
+ return *this;
+ }
+
static void to_string2(expr &self, std::string &out)
{
out = self.to_string();
@@ -1087,6 +1118,7 @@ namespace client
unary_expression(_r1) [_val = _1]
>> *( (lit('*') > unary_expression(_r1) ) [_val *= _1]
| (lit('/') > unary_expression(_r1) ) [_val /= _1]
+ | (lit('%') > unary_expression(_r1) ) [_val %= _1]
);
multiplicative_expression.name("multiplicative_expression");
@@ -1107,6 +1139,8 @@ namespace client
{ out = value.unary_minus(out.it_range.begin()); }
static void not_(expr &value, expr &out)
{ out = value.unary_not(out.it_range.begin()); }
+ static void to_int(expr &value, expr &out)
+ { out = value.unary_integer(out.it_range.begin()); }
};
unary_expression = iter_pos[px::bind(&FactorActions::set_start_pos, _1, _val)] >> (
scalar_variable_reference(_r1) [ _val = _1 ]
@@ -1118,6 +1152,8 @@ namespace client
[ px::bind(&expr::min, _val, _2) ]
| (kw["max"] > '(' > conditional_expression(_r1) [_val = _1] > ',' > conditional_expression(_r1) > ')')
[ px::bind(&expr::max, _val, _2) ]
+ //FIXME this is likley not correct
+ | (kw["int"] > '(' > unary_expression(_r1) /* > ')' */ ) [ px::bind(&FactorActions::to_int, _1, _val) ]
| (strict_double > iter_pos) [ px::bind(&FactorActions::double_, _1, _2, _val) ]
| (int_ > iter_pos) [ px::bind(&FactorActions::int_, _1, _2, _val) ]
| (kw[bool_] > iter_pos) [ px::bind(&FactorActions::bool_, _1, _2, _val) ]
diff --git a/src/libslic3r/PlaceholderParser.hpp b/src/libslic3r/PlaceholderParser.hpp
index 14fdc5c28..d744dba22 100644
--- a/src/libslic3r/PlaceholderParser.hpp
+++ b/src/libslic3r/PlaceholderParser.hpp
@@ -41,7 +41,7 @@ public:
// Fill in the template using a macro processing language.
// Throws std::runtime_error on syntax or runtime error.
- std::string process(const std::string &templ, unsigned int current_extruder_id, const DynamicConfig *config_override = nullptr) const;
+ std::string process(const std::string &templ, unsigned int current_extruder_id = 0, const DynamicConfig *config_override = nullptr) const;
// Evaluate a boolean expression using the full expressive power of the PlaceholderParser boolean expression syntax.
// Throws std::runtime_error on syntax or runtime error.
diff --git a/src/libslic3r/Print.cpp b/src/libslic3r/Print.cpp
index 02d9da784..1cb16b4de 100644
--- a/src/libslic3r/Print.cpp
+++ b/src/libslic3r/Print.cpp
@@ -478,7 +478,7 @@ static std::vector print_objects_from_model_object(const ModelOb
// Compare just the layer ranges and their layer heights, not the associated configs.
// Ignore the layer heights if check_layer_heights is false.
-bool layer_height_ranges_equal(const t_layer_config_ranges &lr1, const t_layer_config_ranges &lr2, bool check_layer_height)
+static bool layer_height_ranges_equal(const t_layer_config_ranges &lr1, const t_layer_config_ranges &lr2, bool check_layer_height)
{
if (lr1.size() != lr2.size())
return false;
@@ -493,6 +493,37 @@ bool layer_height_ranges_equal(const t_layer_config_ranges &lr1, const t_layer_c
return true;
}
+// Returns true if va == vb when all CustomGCode items that are not ToolChangeCode are ignored.
+static bool custom_per_printz_gcodes_tool_changes_differ(const std::vector &va, const std::vector &vb)
+{
+ auto it_a = va.begin();
+ auto it_b = vb.begin();
+ while (it_a != va.end() && it_b != vb.end()) {
+ if (it_a != va.end() && it_a->gcode != ToolChangeCode) {
+ // Skip any CustomGCode items, which are not tool changes.
+ ++ it_a;
+ continue;
+ }
+ if (it_b != vb.end() && it_b->gcode != ToolChangeCode) {
+ // Skip any CustomGCode items, which are not tool changes.
+ ++ it_b;
+ continue;
+ }
+ if (it_a == va.end() || it_b == vb.end())
+ // va or vb contains more Tool Changes than the other.
+ return true;
+ assert(it_a->gcode == ToolChangeCode);
+ assert(it_b->gcode == ToolChangeCode);
+ if (*it_a != *it_b)
+ // The two Tool Changes differ.
+ return true;
+ ++ it_a;
+ ++ it_b;
+ }
+ // There is no change in custom Tool Changes.
+ return false;
+}
+
// Collect diffs of configuration values at various containers,
// resolve the filament rectract overrides of extruder retract values.
void Print::config_diffs(
@@ -638,48 +669,6 @@ Print::ApplyStatus Print::apply(const Model &model, DynamicPrintConfig new_full_
m_ranges.emplace_back(t_layer_height_range(m_ranges.back().first.second, DBL_MAX), nullptr);
}
- // Convert input config ranges into continuous non-overlapping sorted vector of intervals and their configs,
- // considering custom_tool_change values
- void assign(const t_layer_config_ranges &in, const std::vector> &custom_tool_changes) {
- m_ranges.clear();
- m_ranges.reserve(in.size());
- // Input ranges are sorted lexicographically. First range trims the other ranges.
- coordf_t last_z = 0;
- for (const std::pair &range : in)
- if (range.first.second > last_z) {
- coordf_t min_z = std::max(range.first.first, 0.);
- if (min_z > last_z + EPSILON) {
- m_ranges.emplace_back(t_layer_height_range(last_z, min_z), nullptr);
- last_z = min_z;
- }
- if (range.first.second > last_z + EPSILON) {
- const DynamicPrintConfig* cfg = &range.second;
- m_ranges.emplace_back(t_layer_height_range(last_z, range.first.second), cfg);
- last_z = range.first.second;
- }
- }
-
- // add ranges for extruder changes from custom_tool_changes
- for (size_t i = 0; i < custom_tool_changes.size(); i++) {
- const DynamicPrintConfig* cfg = &custom_tool_changes[i].second;
- coordf_t cur_Z = custom_tool_changes[i].first;
- coordf_t next_Z = i == custom_tool_changes.size()-1 ? DBL_MAX : custom_tool_changes[i+1].first;
- if (cur_Z > last_z + EPSILON) {
- if (i==0)
- m_ranges.emplace_back(t_layer_height_range(last_z, cur_Z), nullptr);
- m_ranges.emplace_back(t_layer_height_range(cur_Z, next_Z), cfg);
- }
- else if (next_Z > last_z + EPSILON)
- m_ranges.emplace_back(t_layer_height_range(last_z, next_Z), cfg);
- }
-
- if (m_ranges.empty())
- m_ranges.emplace_back(t_layer_height_range(0, DBL_MAX), nullptr);
- else if (m_ranges.back().second == nullptr)
- m_ranges.back().first.second = DBL_MAX;
- else if (m_ranges.back().first.second != DBL_MAX)
- m_ranges.emplace_back(t_layer_height_range(m_ranges.back().first.second, DBL_MAX), nullptr);
- }
const DynamicPrintConfig* config(const t_layer_height_range &range) const {
auto it = std::lower_bound(m_ranges.begin(), m_ranges.end(), std::make_pair< t_layer_height_range, const DynamicPrintConfig*>(t_layer_height_range(range.first - EPSILON, range.second - EPSILON), nullptr));
// #ys_FIXME_COLOR
@@ -733,17 +722,18 @@ Print::ApplyStatus Print::apply(const Model &model, DynamicPrintConfig new_full_
for (const ModelObject *model_object : m_model.objects)
model_object_status.emplace(model_object->id(), ModelObjectStatus::New);
} else {
+ if (m_model.custom_gcode_per_print_z != model.custom_gcode_per_print_z) {
+ update_apply_status(custom_per_printz_gcodes_tool_changes_differ(m_model.custom_gcode_per_print_z.gcodes, model.custom_gcode_per_print_z.gcodes) ?
+ // The Tool Ordering and the Wipe Tower are no more valid.
+ this->invalidate_steps({ psWipeTower, psGCodeExport }) :
+ // There is no change in Tool Changes stored in custom_gcode_per_print_z, therefore there is no need to update Tool Ordering.
+ this->invalidate_step(psGCodeExport));
+ m_model.custom_gcode_per_print_z = model.custom_gcode_per_print_z;
+ }
if (model_object_list_equal(m_model, model)) {
// The object list did not change.
for (const ModelObject *model_object : m_model.objects)
model_object_status.emplace(model_object->id(), ModelObjectStatus::Old);
-
- // But if custom gcode per layer height was changed
- if (m_model.custom_gcode_per_print_z != model.custom_gcode_per_print_z) {
- // we should stop background processing
- update_apply_status(this->invalidate_step(psGCodeExport));
- m_model.custom_gcode_per_print_z = model.custom_gcode_per_print_z;
- }
} else if (model_object_list_extended(m_model, model)) {
// Add new objects. Their volumes and configs will be synchronized later.
update_apply_status(this->invalidate_step(psGCodeExport));
@@ -835,9 +825,6 @@ Print::ApplyStatus Print::apply(const Model &model, DynamicPrintConfig new_full_
for (PrintObject *print_object : m_objects)
print_object_status.emplace(PrintObjectStatus(print_object));
- std::vector> custom_tool_changes =
- m_model.get_custom_tool_changes(m_default_object_config.layer_height, num_extruders);
-
// 3) Synchronize ModelObjects & PrintObjects.
for (size_t idx_model_object = 0; idx_model_object < model.objects.size(); ++ idx_model_object) {
ModelObject &model_object = *m_model.objects[idx_model_object];
@@ -845,9 +832,7 @@ Print::ApplyStatus Print::apply(const Model &model, DynamicPrintConfig new_full_
assert(it_status != model_object_status.end());
assert(it_status->status != ModelObjectStatus::Deleted);
const ModelObject& model_object_new = *model.objects[idx_model_object];
- // ys_FIXME_COLOR
- // const_cast(*it_status).layer_ranges.assign(model_object_new.layer_config_ranges);
- const_cast(*it_status).layer_ranges.assign(model_object_new.layer_config_ranges, custom_tool_changes);
+ const_cast(*it_status).layer_ranges.assign(model_object_new.layer_config_ranges);
if (it_status->status == ModelObjectStatus::New)
// PrintObject instances will be added in the next loop.
continue;
@@ -1015,8 +1000,6 @@ Print::ApplyStatus Print::apply(const Model &model, DynamicPrintConfig new_full_
PrintRegionConfig this_region_config;
bool this_region_config_set = false;
for (PrintObject *print_object : m_objects) {
- if(m_force_update_print_regions && !custom_tool_changes.empty())
- goto print_object_end;
const LayerRanges *layer_ranges;
{
auto it_status = model_object_status.find(ModelObjectStatus(print_object->model_object()->id()));
@@ -1572,9 +1555,13 @@ void Print::process()
obj->generate_support_material();
if (this->set_started(psWipeTower)) {
m_wipe_tower_data.clear();
+ m_tool_ordering.clear();
if (this->has_wipe_tower()) {
//this->set_status(95, L("Generating wipe tower"));
this->_make_wipe_tower();
+ } else if (! this->config().complete_objects.value) {
+ // Initialize the tool ordering, so it could be used by the G-code preview slider for planning tool changes and filament switches.
+ m_tool_ordering = ToolOrdering(*this, -1, false);
}
this->set_done(psWipeTower);
}
@@ -1963,8 +1950,8 @@ const WipeTowerData& Print::wipe_tower_data(size_t extruders_cnt, double first_l
// If the wipe tower wasn't created yet, make sure the depth and brim_width members are set to default.
if (! is_step_done(psWipeTower) && extruders_cnt !=0) {
- float width = m_config.wipe_tower_width;
- float brim_spacing = nozzle_diameter * 1.25f - first_layer_height * (1. - M_PI_4);
+ float width = float(m_config.wipe_tower_width);
+ float brim_spacing = float(nozzle_diameter * 1.25f - first_layer_height * (1. - M_PI_4));
const_cast(this)->m_wipe_tower_data.depth = (900.f/width) * float(extruders_cnt - 1);
const_cast(this)->m_wipe_tower_data.brim_width = 4.5f * brim_spacing;
@@ -1990,6 +1977,7 @@ void Print::_make_wipe_tower()
// Let the ToolOrdering class know there will be initial priming extrusions at the start of the print.
m_wipe_tower_data.tool_ordering = ToolOrdering(*this, (unsigned int)-1, true);
+
if (! m_wipe_tower_data.tool_ordering.has_wipe_tower())
// Don't generate any wipe tower.
return;
@@ -2107,13 +2095,6 @@ void Print::_make_wipe_tower()
m_wipe_tower_data.number_of_toolchanges = wipe_tower.get_number_of_toolchanges();
}
-// Returns extruder this eec should be printed with, according to PrintRegion config
-int Print::get_extruder(const ExtrusionEntityCollection& fill, const PrintRegion ®ion)
-{
- return is_infill(fill.role()) ? std::max(0, (is_solid_infill(fill.entities.front()->role()) ? region.config().solid_infill_extruder : region.config().infill_extruder) - 1) :
- std::max(region.config().perimeter_extruder.value - 1, 0);
-}
-
// Generate a recommended G-code output file name based on the format template, default extension, and template parameters
// (timestamps, object placeholders derived from the model, current placeholder prameters and print statistics.
// Use the final print statistics if available, or just keep the print statistics placeholders if not available yet (before G-code is finalized).
diff --git a/src/libslic3r/Print.hpp b/src/libslic3r/Print.hpp
index 95c7b656a..53a6f97b9 100644
--- a/src/libslic3r/Print.hpp
+++ b/src/libslic3r/Print.hpp
@@ -15,6 +15,8 @@
#include "GCode/ThumbnailData.hpp"
#endif // ENABLE_THUMBNAIL_GENERATOR
+#include "libslic3r.h"
+
namespace Slic3r {
class Print;
@@ -25,8 +27,19 @@ class GCodePreviewData;
// Print step IDs for keeping track of the print state.
enum PrintStep {
- psSkirt, psBrim, psWipeTower, psGCodeExport, psCount,
+ psSkirt,
+ psBrim,
+ // Synonym for the last step before the Wipe Tower / Tool Ordering, for the G-code preview slider to understand that
+ // all the extrusions are there for the layer slider to add color changes etc.
+ psExtrusionPaths = psBrim,
+ psWipeTower,
+ // psToolOrdering is a synonym to psWipeTower, as the Wipe Tower calculates and modifies the ToolOrdering,
+ // while if printing without the Wipe Tower, the ToolOrdering is calculated as well.
+ psToolOrdering = psWipeTower,
+ psGCodeExport,
+ psCount,
};
+
enum PrintObjectStep {
posSlice, posPerimeters, posPrepareInfill,
posInfill, posSupportMaterial, posCount,
@@ -50,7 +63,7 @@ public:
// Average diameter of nozzles participating on extruding this region.
coordf_t bridging_height_avg(const PrintConfig &print_config) const;
- // Collect extruder indices used to print this region's object.
+ // Collect 0-based extruder indices used to print this region's object.
void collect_object_printing_extruders(std::vector &object_extruders) const;
static void collect_object_printing_extruders(const PrintConfig &print_config, const PrintRegionConfig ®ion_config, std::vector &object_extruders);
@@ -116,8 +129,21 @@ public:
size_t total_layer_count() const { return this->layer_count() + this->support_layer_count(); }
size_t layer_count() const { return m_layers.size(); }
void clear_layers();
- Layer* get_layer(int idx) { return m_layers[idx]; }
- const Layer* get_layer(int idx) const { return m_layers[idx]; }
+ const Layer* get_layer(int idx) const { return m_layers[idx]; }
+ Layer* get_layer(int idx) { return m_layers[idx]; }
+ // Get a layer exactly at print_z.
+ const Layer* get_layer_at_printz(coordf_t print_z) const {
+ auto it = Slic3r::lower_bound_by_predicate(m_layers.begin(), m_layers.end(), [print_z](const Layer *layer) { return layer->print_z < print_z; });
+ return (it == m_layers.end() || (*it)->print_z != print_z) ? nullptr : *it;
+ }
+ Layer* get_layer_at_printz(coordf_t print_z) { return const_cast(std::as_const(*this).get_layer_at_printz(print_z)); }
+ // Get a layer approximately at print_z.
+ const Layer* get_layer_at_printz(coordf_t print_z, coordf_t epsilon) const {
+ coordf_t limit = print_z + epsilon;
+ auto it = Slic3r::lower_bound_by_predicate(m_layers.begin(), m_layers.end(), [limit](const Layer *layer) { return layer->print_z < limit; });
+ return (it == m_layers.end() || (*it)->print_z < print_z - epsilon) ? nullptr : *it;
+ }
+ Layer* get_layer_at_printz(coordf_t print_z, coordf_t epsilon) { return const_cast(std::as_const(*this).get_layer_at_printz(print_z, epsilon)); }
// print_z: top of the layer; slice_z: center of the layer.
Layer* add_layer(int id, coordf_t height, coordf_t print_z, coordf_t slice_z);
@@ -219,7 +245,7 @@ struct WipeTowerData
// Following section will be consumed by the GCodeGenerator.
// Tool ordering of a non-sequential print has to be known to calculate the wipe tower.
// Cache it here, so it does not need to be recalculated during the G-code generation.
- ToolOrdering tool_ordering;
+ ToolOrdering &tool_ordering;
// Cache of tool changes per print layer.
std::unique_ptr> priming;
std::vector> tool_changes;
@@ -232,7 +258,6 @@ struct WipeTowerData
float brim_width;
void clear() {
- tool_ordering.clear();
priming.reset(nullptr);
tool_changes.clear();
final_purge.reset(nullptr);
@@ -241,6 +266,14 @@ struct WipeTowerData
depth = 0.f;
brim_width = 0.f;
}
+
+private:
+ // Only allow the WipeTowerData to be instantiated internally by Print,
+ // as this WipeTowerData shares reference to Print::m_tool_ordering.
+ friend class Print;
+ WipeTowerData(ToolOrdering &tool_ordering) : tool_ordering(tool_ordering) { clear(); }
+ WipeTowerData(const WipeTowerData & /* rhs */) = delete;
+ WipeTowerData &operator=(const WipeTowerData & /* rhs */) = delete;
};
struct PrintStatistics
@@ -345,6 +378,7 @@ public:
const PrintConfig& config() const { return m_config; }
const PrintObjectConfig& default_object_config() const { return m_default_object_config; }
const PrintRegionConfig& default_region_config() const { return m_default_region_config; }
+ //FIXME returning const vector to non-const PrintObject*, caller could modify PrintObjects!
const PrintObjectPtrs& objects() const { return m_objects; }
PrintObject* get_object(size_t idx) { return m_objects[idx]; }
const PrintObject* get_object(size_t idx) const { return m_objects[idx]; }
@@ -353,9 +387,6 @@ public:
// If zero, then the print is empty and the print shall not be executed.
unsigned int num_object_instances() const;
- // Returns extruder this eec should be printed with, according to PrintRegion config:
- static int get_extruder(const ExtrusionEntityCollection& fill, const PrintRegion ®ion);
-
const ExtrusionEntityCollection& skirt() const { return m_skirt; }
const ExtrusionEntityCollection& brim() const { return m_brim; }
@@ -364,14 +395,13 @@ public:
// Wipe tower support.
bool has_wipe_tower() const;
const WipeTowerData& wipe_tower_data(size_t extruders_cnt = 0, double first_layer_height = 0., double nozzle_diameter = 0.) const;
+ const ToolOrdering& tool_ordering() const { return m_tool_ordering; }
std::string output_filename(const std::string &filename_base = std::string()) const override;
// Accessed by SupportMaterial
const PrintRegion* get_region(size_t idx) const { return m_regions[idx]; }
-
- // force update of PrintRegions, when custom_tool_change is not empty and (Re)Slicing is started
- void set_force_update_print_regions(bool force_update_print_regions) { m_force_update_print_regions = force_update_print_regions; }
+ const ToolOrdering& get_tool_ordering() const { return m_wipe_tower_data.tool_ordering; } // #ys_FIXME just for testing
protected:
// methods for handling regions
@@ -410,14 +440,12 @@ private:
ExtrusionEntityCollection m_brim;
// Following section will be consumed by the GCodeGenerator.
- WipeTowerData m_wipe_tower_data;
+ ToolOrdering m_tool_ordering;
+ WipeTowerData m_wipe_tower_data {m_tool_ordering};
// Estimated print time, filament consumed.
PrintStatistics m_print_statistics;
- // flag used
- bool m_force_update_print_regions = false;
-
// To allow GCode to set the Print's GCodeExport step status.
friend class GCode;
// Allow PrintObject to access m_mutex and m_cancel_callback.
diff --git a/src/libslic3r/PrintBase.cpp b/src/libslic3r/PrintBase.cpp
index fdee67f2e..55e24178d 100644
--- a/src/libslic3r/PrintBase.cpp
+++ b/src/libslic3r/PrintBase.cpp
@@ -37,7 +37,7 @@ void PrintBase::update_object_placeholders(DynamicConfig &config, const std::str
}
}
- config.set_key_value("year", new ConfigOptionStrings(v_scale));
+ config.set_key_value("scale", new ConfigOptionStrings(v_scale));
if (! input_file.empty()) {
// get basename with and without suffix
const std::string input_filename = boost::filesystem::path(input_file).filename().string();
diff --git a/src/libslic3r/PrintConfig.cpp b/src/libslic3r/PrintConfig.cpp
index 00c33dcfb..47a72b829 100644
--- a/src/libslic3r/PrintConfig.cpp
+++ b/src/libslic3r/PrintConfig.cpp
@@ -1337,7 +1337,7 @@ void PrintConfigDef::init_fff_params()
def->enum_labels.push_back("OctoPrint");
def->enum_labels.push_back("Duet");
def->enum_labels.push_back("FlashAir");
- def->enum_values.push_back("AstroBox");
+ def->enum_labels.push_back("AstroBox");
def->mode = comAdvanced;
def->set_default_value(new ConfigOptionEnum(htOctoPrint));
diff --git a/src/libslic3r/Slicing.cpp b/src/libslic3r/Slicing.cpp
index 8199bde03..2a32ba5ef 100644
--- a/src/libslic3r/Slicing.cpp
+++ b/src/libslic3r/Slicing.cpp
@@ -300,26 +300,14 @@ std::vector layer_height_profile_adaptive(const SlicingParameters& slici
layer_height_profile.push_back(print_z);
layer_height_profile.push_back(height);
print_z += height;
-#if !ENABLE_ADAPTIVE_LAYER_HEIGHT_PROFILE
- layer_height_profile.push_back(print_z);
- layer_height_profile.push_back(height);
-#endif // !ENABLE_ADAPTIVE_LAYER_HEIGHT_PROFILE
}
-#if ENABLE_ADAPTIVE_LAYER_HEIGHT_PROFILE
double z_gap = slicing_params.object_print_z_height() - layer_height_profile[layer_height_profile.size() - 2];
if (z_gap > 0.0)
{
layer_height_profile.push_back(slicing_params.object_print_z_height());
layer_height_profile.push_back(clamp(slicing_params.min_layer_height, slicing_params.max_layer_height, z_gap));
}
-#else
- double last = std::max(slicing_params.first_object_layer_height, layer_height_profile[layer_height_profile.size() - 2]);
- layer_height_profile.push_back(last);
- layer_height_profile.push_back(slicing_params.first_object_layer_height);
- layer_height_profile.push_back(slicing_params.object_print_z_height());
- layer_height_profile.push_back(slicing_params.first_object_layer_height);
-#endif // ENABLE_ADAPTIVE_LAYER_HEIGHT_PROFILE
return layer_height_profile;
}
diff --git a/src/libslic3r/Technologies.hpp b/src/libslic3r/Technologies.hpp
index 64c5ce953..727200ca8 100644
--- a/src/libslic3r/Technologies.hpp
+++ b/src/libslic3r/Technologies.hpp
@@ -41,24 +41,6 @@
#define ENABLE_THUMBNAIL_GENERATOR (1 && ENABLE_2_2_0_ALPHA1)
#define ENABLE_THUMBNAIL_GENERATOR_DEBUG (0 && ENABLE_THUMBNAIL_GENERATOR)
-// Enable adaptive layer height profile
-#define ENABLE_ADAPTIVE_LAYER_HEIGHT_PROFILE (1 && ENABLE_2_2_0_ALPHA1)
-
-// Enable grayed variant for gizmos icons in non activable state
-#define ENABLE_GIZMO_ICONS_NON_ACTIVABLE_STATE (1 && ENABLE_2_2_0_ALPHA1)
-
-// Enable fix for view toolbar background not showing up on Mac with dark mode
-#define ENABLE_VIEW_TOOLBAR_BACKGROUND_FIX (1 && ENABLE_2_2_0_ALPHA1)
-
-// Enable selection for missing files in reload from disk command
-#define ENABLE_RELOAD_FROM_DISK_MISSING_SELECTION (1 && ENABLE_2_2_0_ALPHA1)
-
-// Enable closing 3Dconnextion imgui settings dialog by clicking on [X] and [Close] buttons
-#define ENABLE_3DCONNEXION_DEVICES_CLOSE_SETTING_DIALOG (1 && ENABLE_2_2_0_ALPHA1)
-
-// Enable not applying volume transformation during 3mf and amf loading, but keeping it as a ModelVolume member
-#define ENABLE_KEEP_LOADED_VOLUME_TRANSFORM_AS_STAND_ALONE (1 && ENABLE_2_2_0_ALPHA1)
-
//==================
// 2.2.0.beta1 techs
@@ -68,4 +50,13 @@
// Enable using Y axis of 3Dconnexion devices as zoom
#define ENABLE_3DCONNEXION_Y_AS_ZOOM (1 && ENABLE_2_2_0_BETA1)
+// Enable a modified version of the toolbar textures where all the icons are separated by 1 pixel
+#define ENABLE_MODIFIED_TOOLBAR_TEXTURES (1 && ENABLE_2_2_0_BETA1)
+
+// Enable configurable paths export (fullpath or not) to 3mf and amf
+#define ENABLE_CONFIGURABLE_PATHS_EXPORT_TO_3MF_AND_AMF (1 && ENABLE_2_2_0_BETA1)
+
+// Enable 6 degrees of freedom camera
+#define ENABLE_6DOF_CAMERA (1 && ENABLE_2_2_0_BETA1)
+
#endif // _technologies_h_
diff --git a/src/libslic3r/libslic3r.h b/src/libslic3r/libslic3r.h
index f2dd00114..0454644bb 100644
--- a/src/libslic3r/libslic3r.h
+++ b/src/libslic3r/libslic3r.h
@@ -158,6 +158,53 @@ inline std::unique_ptr make_unique(Args&&... args) {
return std::unique_ptr(new T(std::forward(args)...));
}
+// Variant of std::lower_bound() with compare predicate, but without the key.
+// This variant is very useful in case that the T type is large or it does not even have a public constructor.
+template
+ForwardIt lower_bound_by_predicate(ForwardIt first, ForwardIt last, LowerThanKeyPredicate lower_thank_key)
+{
+ ForwardIt it;
+ typename std::iterator_traits::difference_type count, step;
+ count = std::distance(first, last);
+
+ while (count > 0) {
+ it = first;
+ step = count / 2;
+ std::advance(it, step);
+ if (lower_thank_key(*it)) {
+ first = ++it;
+ count -= step + 1;
+ }
+ else
+ count = step;
+ }
+ return first;
+}
+
+// from https://en.cppreference.com/w/cpp/algorithm/lower_bound
+template