diff --git a/docs/HLSD/layer-cooling-time.md b/docs/HLSD/layer-cooling-time.md new file mode 100644 index 0000000000..707400ad8b --- /dev/null +++ b/docs/HLSD/layer-cooling-time.md @@ -0,0 +1,82 @@ +# Layer cooling time — High Level Design + +## Purpose and scope + +Two filament cooling settings depend on how long a layer takes. The slowdown for better layer cooling slows a +layer that is shorter than `slow_down_layer_time`. The part cooling fan interpolates its speed between +`fan_cooling_layer_time` and `slow_down_layer_time`. Both thresholds are in seconds, and users read the layer +times off the Preview, so `CoolingBuffer` measures a layer with the same estimate as the Preview. +`GCodeProcessor` provides it, with acceleration, cornering and the printer's motion limits. + +The time at the feed rates, the length of each move over its speed, is much shorter on a printer whose moves +spend a large part of their time accelerating. On fast printers with moderate acceleration, the Preview time is +often 1.3 to 2 times the time at the feed rates. The slowdown itself still works in the time at the feed rates. +The estimate sets the targets it aims at, and the time the fan goes by. + +## What is timed + +A layer is timed whole, from its layer change to its end, as in the Preview. A layer whose first extrusion comes +after a filament change is timed from that extrusion instead: a long filament change before the printing would +otherwise hide a layer whose printing is quick. The time at the feed rates covers the same part of the layer. + +The estimate leaves out the time the printer spends loading, unloading or changing a filament +(`machine_load_filament_time`, `machine_unload_filament_time`, `machine_tool_change_time`). The time at the feed +rates never counted it either. The moves of a filament change, such as the purge and the prime tower, count. + +## The timer + +The export runs its own `GCodeProcessor` on the G-code as it is written, in a later stage of the export pipeline +than the cooling. That processor has not seen a layer when the cooling decides on it, so `CoolingBuffer` owns a +second one. Before each estimate it resets that processor and applies the print config, with the filament change +times set to zero. + +The layer is timed from a standstill. The G-code timed is preceded by lines that put the processor in the +machine state where the timed part starts: + +- the extruder, as a `T` command; +- the extrusion mode, `M82` or `M83`; +- the last line of each kind that sets an acceleration or another motion limit, seen so far, in the order the + lines came; +- the position, as a `G92`. + +A line kind is its command and its parameter names, for example `M204 P T` or +`SET_VELOCITY_LIMIT ACCEL ACCEL_TO_DECEL`, so a later line overrides only what it sets. The commands followed are +`M201`, `M203`, `M204`, `M205`, `M221`, `M566` and `SET_VELOCITY_LIMIT`. Most of the G-code reaches the cooling +layer by layer. `GCode` passes it the G-code that users write and that goes straight to the file before the first +layer: the start G-code, the IDEX or IQEX mode G-code, and the first filament's start G-code on Bambu Lab +printers. The machine limits Orca writes at the top of the file come from the config, which the processor has +already. The first layer starts where the start G-code left the print head, which the export's processor knows by +then, as it reads everything written before the first layer as it is written. A `G4 P0` at the end makes the +planner finish the last moves. + +## Slowdown + +The slowdown lowers the fastest extrusions first, to a common speed cap, in the time at the feed rates. Its +targets, the minimum layer times, are multiplied by a scale, and the scale is searched for so that the estimate +of the slowed layer reaches the longest minimum layer time among its filaments: + +1. A layer whose estimate already reaches the target is not slowed down. +2. The first scale is the ratio of the layer's time at the feed rates to its estimate. +3. Until a slowed layer reaches the target, the next scale comes from a model of the slowed layer. With the + moves slowed to one speed, acceleration adds about `k / t` to a layer that takes `t` at its feed rates. Where + that has no solution, because the moves never reach their speed, the time is taken as proportional to the + scale. +4. Once a slowed layer reaches the target, false position between the last layer short of it and the shortest + one past it. + +A layer from 0.2% short of the target to 1% past it is accepted, as a slightly longer layer only cools more. The +search stops after six estimates. If it ends short of the target with a longer candidate found, the layer takes +that candidate. It also stops when the minimum print speed caps the slowdown, which the time at the feed rates +shows when it no longer grows. + +## Fan + +The fan interpolates on the estimate of the layer as it is printed, after the slowdown. + +## Cost + +Acceleration only makes a layer longer, so a layer that takes more than every fan and slowdown threshold at its +feed rates, by a 10% margin, is not timed: it gets the minimum fan and no slowdown either way. Those are the large +layers, which hold most of the G-code. Any other layer is timed once, and a slowed layer about three times more. +The cooling runs in its own stage of the export pipeline. On the 51 MB fan calibration cone of issue 11751, whose +65 s fan threshold has every layer timed, the slicing takes about 2% more processor time. diff --git a/src/libslic3r/GCode.cpp b/src/libslic3r/GCode.cpp index 9435dacaee..b5864701e9 100644 --- a/src/libslic3r/GCode.cpp +++ b/src/libslic3r/GCode.cpp @@ -4402,11 +4402,14 @@ void GCode::_do_export(Print& print, GCodeOutputStream &file, ThumbnailsGenerato } // Write IMEX mode G-code first (processed above), then machine_start_gcode. - if (!imex_processed_gcode.empty()) + if (!imex_processed_gcode.empty()) { file.writeln(imex_processed_gcode); + m_cooling_buffer->remember_motion_settings(imex_processed_gcode); + } // Write the custom start G-code file.writeln(machine_start_gcode); + m_cooling_buffer->remember_motion_settings(machine_start_gcode); // Mark the end of the machine start g-code so the GCodeProcessor usage-block builder knows where user // g-code ends and can start attributing filament/extruder usage. Gated on enable_pre_heating: only the // injector fleet (H2D/X2D/H2D-Pro/H2C) emits it; the byte-frozen fleet (X1/P1/A1/H2S, flag false) never @@ -4435,6 +4438,7 @@ void GCode::_do_export(Print& print, GCodeOutputStream &file, ThumbnailsGenerato config.set_key_value("max_layer_z", new ConfigOptionFloat(m_max_layer_z)); std::string filament_start_gcode = this->placeholder_parser_process("filament_start_gcode", print.config().filament_start_gcode.get_at(initial_non_support_extruder_id), initial_non_support_extruder_id,&config); file.writeln(filament_start_gcode); + m_cooling_buffer->remember_motion_settings(filament_start_gcode); // Mark the first filament used in print. Multi-nozzle printers (H2C) get ";VT%d H%d" where // H = dynamic ? nozzle_id : -1; existing single-nozzle printers keep the bare ";VT%d" so their // g-code stays byte-identical. @@ -4573,6 +4577,9 @@ void GCode::_do_export(Print& print, GCodeOutputStream &file, ThumbnailsGenerato // so that first travel can be planned from the position the G-code actually // left the machine at rather than the default last_pos value. GCodeProcessor::PositionState startup_position = m_processor.get_current_position(); + // ORCA: The layer cooling times the first layer from there too. + if (startup_position.has_known_xy()) + m_cooling_buffer->reset(startup_position.position); const Vec2f plate_offset = m_writer.get_xy_offset(); startup_position.position.x() += plate_offset.x(); startup_position.position.y() += plate_offset.y(); diff --git a/src/libslic3r/GCode/CoolingBuffer.cpp b/src/libslic3r/GCode/CoolingBuffer.cpp index c3a4103964..6e2942aac1 100644 --- a/src/libslic3r/GCode/CoolingBuffer.cpp +++ b/src/libslic3r/GCode/CoolingBuffer.cpp @@ -5,7 +5,9 @@ #include "libslic3r/libslic3r.h" #include "libslic3r/Circle.hpp" #include "CoolingBuffer.hpp" +#include "GCodeProcessor.hpp" #include +#include #include #include #include @@ -16,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -37,8 +40,12 @@ namespace Slic3r { -CoolingBuffer::CoolingBuffer(GCode &gcodegen) : m_config(gcodegen.config()), m_gcodegen(gcodegen), m_toolchange_prefix(gcodegen.writer().toolchange_prefix()), m_current_extruder(0), m_current_nozzle(0) +CoolingBuffer::CoolingBuffer(GCode &gcodegen) : m_config(gcodegen.config()), m_gcodegen(gcodegen), m_toolchange_prefix(gcodegen.writer().toolchange_prefix()), m_current_extruder(0), m_current_nozzle(0), + m_layer_timer_config(gcodegen.config()) { + m_layer_timer_config.machine_load_filament_time.value = 0.; + m_layer_timer_config.machine_unload_filament_time.value = 0.; + m_layer_timer_config.machine_tool_change_time.value = 0.; this->reset(gcodegen.writer().get_position()); const std::vector &extruders = gcodegen.writer().extruders(); @@ -350,16 +357,76 @@ std::string CoolingBuffer::process_layer(std::string &&gcode, size_t layer_id, b // This is either an object layer or the very last print layer. Calculate cool down over the collected support layers // and one object layer. std::vector per_extruder_adjustments = this->parse_layer_gcode(m_gcode, m_current_pos); - float layer_time_stretched = this->calculate_layer_slowdown(per_extruder_adjustments); + float layer_time_stretched = this->slow_down_layer(m_gcode, per_extruder_adjustments); out = this->apply_layer_cooldown(m_gcode, layer_id, layer_time_stretched, per_extruder_adjustments); m_gcode.clear(); } return out; } +// The kind of a line that sets a limit the time estimate follows, such as "M204 P T" or "SET_VELOCITY_LIMIT ACCEL", +// from its command and parameter names; empty for any other line. +static std::string motion_setting_kind(const std::string &line) +{ + const size_t start = line.empty() || (line.front() != ' ' && line.front() != '\t') ? 0 : line.find_first_not_of(" \t"); + if (start >= line.size() || (line[start] != 'M' && line[start] != 'S')) + return {}; + static constexpr std::array commands{ "M201", "M203", "M204", "M205", "M221", "M566", "SET_VELOCITY_LIMIT" }; + const size_t end = std::min(line.find(';'), line.size()); + const std::string_view command = std::string_view(line).substr(start, std::min(line.find_first_of(" \t", start), end) - start); + if (std::find(commands.begin(), commands.end(), command) == commands.end()) + return {}; + std::vector names; + for (size_t word = start + command.size(); word < end;) { + word = line.find_first_not_of(" \t", word); + if (word >= end) + break; + const size_t word_end = std::min(line.find_first_of(" \t", word), end); + const size_t equals = line.find('=', word); + names.emplace_back(std::string_view(line).substr(word, equals < word_end ? equals - word : 1)); + word = word_end; + } + std::sort(names.begin(), names.end()); + std::string kind(command); + for (const std::string_view name : names) + (kind += ' ') += name; + return kind; +} + +void CoolingBuffer::remember_motion_setting(const std::string &line) +{ + if (std::string kind = motion_setting_kind(line); ! kind.empty()) + m_motion_settings[std::move(kind)] = { m_motion_settings_count ++, line }; +} + +void CoolingBuffer::remember_motion_settings(const std::string &gcode) +{ + for (size_t begin = 0; begin < gcode.size();) { + const size_t end = std::min(gcode.find('\n', begin), gcode.size()); + const size_t line_end = end > begin && gcode[end - 1] == '\r' ? end - 1 : end; + this->remember_motion_setting(gcode.substr(begin, line_end - begin)); + begin = end + 1; + } +} + +std::string CoolingBuffer::timer_setup(unsigned int extruder, const std::vector &position) const +{ + std::string setup = "T" + std::to_string(extruder) + '\n'; + setup += m_config.use_relative_e_distances.value ? "M83\n" : "M82\n"; + std::vector *> settings; + for (const auto &[kind, setting] : m_motion_settings) + settings.emplace_back(&setting); + std::sort(settings.begin(), settings.end(), [](const auto *a, const auto *b) { return a->first < b->first; }); + for (const auto *setting : settings) + (setup += setting->second) += '\n'; + return setup + "G92 X" + float_to_string_decimal_point(position[0]) + " Y" + float_to_string_decimal_point(position[1]) + " Z" + + float_to_string_decimal_point(position[2]) + " E" + + float_to_string_decimal_point(m_config.use_relative_e_distances.value ? 0. : position[3]) + '\n'; +} + // Parse the layer G-code for the moves, which could be adjusted. // Return the list of parsed lines, bucketed by an extruder. -std::vector CoolingBuffer::parse_layer_gcode(const std::string &gcode, std::vector ¤t_pos) const +std::vector CoolingBuffer::parse_layer_gcode(const std::string &gcode, std::vector ¤t_pos) { std::vector per_extruder_adjustments(m_extruder_ids.size()); std::vector map_extruder_to_per_extruder_adjustment(m_num_extruders, 0); @@ -384,8 +451,12 @@ std::vector CoolingBuffer::parse_layer_gcode(const std:: size_t active_speed_modifier = size_t(-1); // Orca: Whether we had our first extrusion in this layer. - // Time of any other movements before the first extrusion will be excluded from the layer time. bool layer_had_extrusion = false; + // ORCA: A filament change before the first extrusion leaves the time before that extrusion out of the layer time, + // so the change cannot make a quick layer look long enough. + bool changed_filament = false; + std::string layer_start_setup = this->timer_setup(current_extruder, current_pos); + m_timed_from = std::string::npos; for (; *line_start != 0; line_start = line_end) { @@ -397,6 +468,7 @@ std::vector CoolingBuffer::parse_layer_gcode(const std:: if (*line_end == '\n') ++ line_end; CoolingLine line(0, line_start - gcode.c_str(), line_end - gcode.c_str()); + this->remember_motion_setting(sline); if (boost::starts_with(sline, "G0 ")) line.type = CoolingLine::TYPE_G0; else if (boost::starts_with(sline, "G1 ")) @@ -449,9 +521,19 @@ std::vector CoolingBuffer::parse_layer_gcode(const std:: if (wipe) line.type |= CoolingLine::TYPE_WIPE; - // Orca: only slow down movements since the first extrusion - if (boost::contains(sline, ";_EXTRUDE_SET_SPEED")) + if (! layer_had_extrusion && boost::contains(sline, ";_EXTRUDE_SET_SPEED")) { layer_had_extrusion = true; + if (changed_filament) { + m_timed_from = line.line_start; + m_timer_setup = this->timer_setup(current_extruder, current_pos); + for (PerExtruderAdjustments &adj : per_extruder_adjustments) + for (CoolingLine &earlier : adj.lines) + earlier.time = earlier.time_max = 0; + } else { + m_timed_from = 0; + m_timer_setup = std::move(layer_start_setup); + } + } // ORCA: Dont slowdown external perimeters for layer time feature // use the adjustment pointer to ensure the value for the current extruder (filament) is used. @@ -532,6 +614,7 @@ std::vector CoolingBuffer::parse_layer_gcode(const std:: line.type = CoolingLine::TYPE_SET_TOOL; current_extruder = new_extruder; adjustment = &per_extruder_adjustments[map_extruder_to_per_extruder_adjustment[current_extruder]]; + changed_filament |= ! layer_had_extrusion; } } else { // Only log the error in case of MM printer. Single extruder printers likely ignore any T anyway. @@ -571,16 +654,16 @@ std::vector CoolingBuffer::parse_layer_gcode(const std:: line.type = CoolingLine::TYPE_FORCE_RESUME_FAN; } - // Orca: For any movements before this layer's first ever extrusion, we exclude them from the layer time calculation. - if (!layer_had_extrusion) { - assert((line.type & CoolingLine::TYPE_ADJUSTABLE) == 0); - line.time = line.time_max = 0; - } - if (line.type != 0) adjustment->lines.emplace_back(std::move(line)); } + // A layer without extrusion is not timed. + if (! layer_had_extrusion) + for (PerExtruderAdjustments &adj : per_extruder_adjustments) + for (CoolingLine &line : adj.lines) + line.time = line.time_max = 0; + return per_extruder_adjustments; } @@ -663,7 +746,7 @@ static inline void extruder_range_slow_down_non_proportional( } // Calculate slow down for all the extruders. -float CoolingBuffer::calculate_layer_slowdown(std::vector &per_extruder_adjustments) +float CoolingBuffer::calculate_layer_slowdown(std::vector &per_extruder_adjustments, float time_scale) { // Sort the extruders by an increasing slow_down_layer_time. // The layers with a lower slow_down_layer_time are slowed down @@ -696,7 +779,7 @@ float CoolingBuffer::calculate_layer_slowdown(std::vectortime_total; - float slow_down_layer_time = adj.slow_down_layer_time * 1.001f; + float slow_down_layer_time = adj.slow_down_layer_time * time_scale * 1.001f; if (total > slow_down_layer_time) { // The current total time is above the minimum threshold of the rest of the extruders, don't adjust anything. } else { @@ -719,6 +802,106 @@ float CoolingBuffer::calculate_layer_slowdown(std::vector &per_extruder_adjustments) +{ + if (m_timed_from == std::string::npos) + return 0.f; + std::vector slowed; + for (const PerExtruderAdjustments &adj : per_extruder_adjustments) + for (const CoolingLine &line : adj.lines) + if (line.slowdown && line.line_start >= m_timed_from) + slowed.emplace_back(&line); + std::sort(slowed.begin(), slowed.end(), [](const CoolingLine *l1, const CoolingLine *l2) { return l1->line_start < l2->line_start; }); + + std::string timed = m_timer_setup; + size_t from = m_timed_from; + for (const CoolingLine *line : slowed) { + // A slowed line only sets the feed rate. + timed.append(gcode, from, line->line_start - from); + timed += "G1 F" + std::to_string(int(std::floor(60. * line->feedrate + 0.5))) + '\n'; + from = line->line_end; + } + timed.append(gcode, from, std::string::npos); + // Plans the last moves to a stop. + timed += "\nG4 P0\n"; + + m_layer_timer.reset(); + m_layer_timer.initialize_result_moves(); + m_layer_timer.apply_config(m_layer_timer_config); + m_layer_timer.process_buffer(timed); + return float(m_layer_timer.get_time(PrintEstimatedStatistics::ETimeMode::Normal)); +} + +float CoolingBuffer::slow_down_layer(const std::string &gcode, std::vector &per_extruder_adjustments) +{ + float time_at_feed_rates = 0.f; + float longest_minimum = 0.f; + for (const PerExtruderAdjustments &adj : per_extruder_adjustments) { + time_at_feed_rates += adj.elapsed_time_total(); + if (adj.cooling_slow_down_enabled && ! adj.lines.empty()) + longest_minimum = std::max(longest_minimum, adj.slow_down_layer_time); + } + // Acceleration only lengthens a layer, so one past every cooling threshold at its feed rates needs no estimate. + float longest_threshold = 0.f; + for (const unsigned int extruder_id : m_extruder_ids) + longest_threshold = std::max({ longest_threshold, float(m_config.fan_cooling_layer_time.get_at(extruder_id)), + float(m_config.slow_down_layer_time.get_at(extruder_id)) }); + if (time_at_feed_rates > 1.1f * longest_threshold) + return time_at_feed_rates; + + const float time = this->estimate_layer_time(gcode, per_extruder_adjustments); + if (time <= 0.f || time_at_feed_rates <= 0.f) + return this->calculate_layer_slowdown(per_extruder_adjustments, 1.f); + const float target = longest_minimum * 1.001f; + if (time >= target) + return time; + + // The slowdown works in the time at the feed rates, which is shorter than the estimate, so its targets are scaled. + // The scale is searched for until a slowed layer reaches the target, then by false position between the two. + const std::vector unslowed = per_extruder_adjustments; + const auto slow_down = [&](float scale) { + per_extruder_adjustments = unslowed; + return this->calculate_layer_slowdown(per_extruder_adjustments, scale); + }; + float lo_scale = time_at_feed_rates / target, lo_time = time, hi_scale = 0.f, hi_time = 0.f; + float scale = time_at_feed_rates / time, slowed_time = time, at_feed_rates = time_at_feed_rates; + for (int i = 0; i < 6; ++ i) { + const float prev_at_feed_rates = at_feed_rates; + at_feed_rates = slow_down(scale); + slowed_time = this->estimate_layer_time(gcode, per_extruder_adjustments); + // A little longer than the target only cools the layer more. + if (slowed_time >= 0.998f * target && slowed_time <= 1.01f * target) + return slowed_time; + if (slowed_time >= target) { + hi_scale = scale; + hi_time = slowed_time; + } else { + // The moves are at the minimum print speed already. + if (hi_scale == 0.f && at_feed_rates <= prev_at_feed_rates * 1.0001f) + return slowed_time; + lo_scale = scale; + lo_time = slowed_time; + } + if (hi_scale > 0.f) { + scale = std::clamp(lo_scale + (target - lo_time) * (hi_scale - lo_scale) / (hi_time - lo_time), + lo_scale + 0.1f * (hi_scale - lo_scale), hi_scale - 0.1f * (hi_scale - lo_scale)); + } else { + // Slowed to one speed, the moves spend about k / t accelerating in a layer taking t at its feed rates. + // Where they never reach their speed, slowing barely lengthens the layer, and the time is taken as proportional. + const float k = (slowed_time - at_feed_rates) * at_feed_rates; + const float discriminant = target * target - 4.f * k; + const float proportional = scale * target / slowed_time; + scale = std::min(std::max(discriminant > 0.f ? 0.5f * (target + std::sqrt(discriminant)) / target : proportional, proportional), 1.2f); + } + } + // Rather the layer slowed down past the target than short of it. + if (slowed_time < target && hi_scale > 0.f) { + slow_down(hi_scale); + return hi_time; + } + return slowed_time; +} + // Apply slow down over G-code lines stored in per_extruder_adjustments, enable fan if needed. // Returns the adjusted G-code. std::string CoolingBuffer::apply_layer_cooldown( diff --git a/src/libslic3r/GCode/CoolingBuffer.hpp b/src/libslic3r/GCode/CoolingBuffer.hpp index 7c54d2f5ec..0428a5adab 100644 --- a/src/libslic3r/GCode/CoolingBuffer.hpp +++ b/src/libslic3r/GCode/CoolingBuffer.hpp @@ -2,17 +2,19 @@ #define slic3r_CoolingBuffer_hpp_ #include "../Point.hpp" +#include "../PrintConfig.hpp" +#include "GCodeProcessor.hpp" #include #include #include #include +#include #include namespace Slic3r { class GCode; class Layer; -class PrintConfig; struct PerExtruderAdjustments; // A standalone G-code filter, to control cooling of the print. @@ -30,11 +32,21 @@ public: void reset(const Vec3d &position); void set_current_extruder(unsigned int extruder_id, unsigned int nozzle_id) { m_current_extruder = extruder_id; m_current_nozzle = nozzle_id; } std::string process_layer(std::string &&gcode, size_t layer_id, bool flush); + // ORCA: Remembers the motion limits that G-code outside the layers sets, such as the start G-code, to time the layers. + void remember_motion_settings(const std::string &gcode); private: CoolingBuffer& operator=(const CoolingBuffer&) = delete; - std::vector parse_layer_gcode(const std::string &gcode, std::vector ¤t_pos) const; - float calculate_layer_slowdown(std::vector &per_extruder_adjustments); + std::vector parse_layer_gcode(const std::string &gcode, std::vector ¤t_pos); + // The slowdown aims at time_scale times each minimum layer time, in the time at the feed rates. + float calculate_layer_slowdown(std::vector &per_extruder_adjustments, float time_scale); + // ORCA: Slows the layer down to the minimum layer time as the time estimate gives it, and returns that time. + float slow_down_layer(const std::string &gcode, std::vector &per_extruder_adjustments); + // ORCA: The time of the layer's timed part, with acceleration, as the preview estimates it. + float estimate_layer_time(const std::string &gcode, const std::vector &per_extruder_adjustments); + void remember_motion_setting(const std::string &line); + // ORCA: The G-code that puts the layer timer in the machine state with this extruder at this position. + std::string timer_setup(unsigned int extruder, const std::vector &position) const; // Apply slow down over G-code lines stored in per_extruder_adjustments, enable fan if needed. // Returns the adjusted G-code. std::string apply_layer_cooldown(const std::string &gcode, size_t layer_id, float layer_time, std::vector &per_extruder_adjustments); @@ -66,6 +78,17 @@ private: // Belt printers: the extrusion being processed lies in the first-layer band above the // belt (between a ";_BELT_BAND_START" and a ";_BELT_BAND_END"). Kept across layers. bool m_belt_band_active = false; + + // ORCA: Times the layers. Its config leaves out filament changes, which the layer time does not count. + GCodeProcessor m_layer_timer; + PrintConfig m_layer_timer_config; + // The last line of each kind that sets an acceleration or another motion limit, and its order. + std::map> m_motion_settings; + size_t m_motion_settings_count { 0 }; + // Where the layer's timed part starts in its G-code, and the G-code that sets the timer up for it. The whole layer is + // timed, unless a filament change comes before its first extrusion: then it is timed from that extrusion. + size_t m_timed_from { std::string::npos }; + std::string m_timer_setup; }; } diff --git a/src/libslic3r/GCode/GCodeProcessor.cpp b/src/libslic3r/GCode/GCodeProcessor.cpp index 97fba7c27f..c49a20efa3 100644 --- a/src/libslic3r/GCode/GCodeProcessor.cpp +++ b/src/libslic3r/GCode/GCodeProcessor.cpp @@ -57,6 +57,7 @@ #include #include #include +#include #include #include #include @@ -2770,6 +2771,14 @@ const std::vector> GCodeProces unsigned int GCodeProcessor::s_result_id = 0; +// Results can be reset on several threads at once, as the layer cooling resets its own processor during an export. +static unsigned int next_result_id(unsigned int &last_id) +{ + static std::mutex mutex; + std::lock_guard lock(mutex); + return ++ last_id; +} + bool GCodeProcessor::contains_reserved_tag(const std::string& gcode, std::string& found_tag) { bool ret = false; @@ -3826,7 +3835,7 @@ void GCodeProcessor::reset() m_used_filaments.reset(); m_result.reset(); - m_result.id = ++s_result_id; + m_result.id = next_result_id(s_result_id); m_last_default_color_id = 0; @@ -3925,7 +3934,7 @@ void GCodeProcessor::process_file(const std::string& filename, std::function #include +#include #include #include #include "test_helpers.hpp" @@ -10,7 +11,10 @@ #include #include "libslic3r/PrintConfig.hpp" #include "libslic3r/Config.hpp" +#include "libslic3r/GCode/GCodeProcessor.hpp" #include "libslic3r/GCodeReader.hpp" +#include "libslic3r/Model.hpp" +#include "libslic3r/Print.hpp" #include "libslic3r/TriangleMesh.hpp" #include "libslic3r/libslic3r.h" #include @@ -202,3 +206,112 @@ TEST_CASE("Layer cooling slowdown does not depend on relative extrusion distance // Feed rates are written in whole mm/min. CHECK_THAT(largest_difference, Catch::Matchers::WithinAbs(0., 1. / MM_PER_MIN)); } + +// Per layer: its time as the G-code preview estimates it, with acceleration, and the part cooling fan speed of its first +// extrusion, in percent. +struct EstimatedLayer +{ + double time = 0.; + float fan = -1.f; +}; + +static std::vector estimated_layers(const TriangleMesh &mesh, const DynamicPrintConfig &config) +{ + Print print; + Model model; + init_print({ mesh }, print, model, config); + GCodeProcessorResult result; + gcode(print, &result); + std::vector layers; + for (const GCodeProcessorResult::MoveVertex &move : result.moves) { + if (move.layer_id >= layers.size()) + layers.resize(move.layer_id + 1); + EstimatedLayer &layer = layers[move.layer_id]; + layer.time += move.time[static_cast(PrintEstimatedStatistics::ETimeMode::Normal)]; + if (layer.fan < 0.f && move.type == EMoveType::Extrude) + layer.fan = move.fan_speed; + } + return layers; +} + +// Print speeds that a low acceleration never reaches on a small part, so its layers take several times their time at the feed rates. +static DynamicPrintConfig slowly_accelerating_config() +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_deserialize_strict({ + { "filament_max_volumetric_speed", 100 }, + { "initial_layer_print_height", 0.3 }, + { "inner_wall_speed", 200 }, + { "internal_solid_infill_speed", 200 }, + { "layer_height", 0.3 }, + { "machine_max_acceleration_extruding", "300,300" }, + { "outer_wall_speed", 200 }, + { "sparse_infill_speed", 200 }, + { "top_surface_speed", 200 }, + }); + return config; +} + +TEST_CASE("Layer cooling slowdown reaches the minimum layer time with acceleration", "[Cooling]") +{ + // A little longer than most layers of the cube take, so they slow down just a little and still accelerate a lot. + constexpr double minimum_layer_time = 8.; + DynamicPrintConfig config = slowly_accelerating_config(); + config.set_deserialize_strict({ + { "slow_down_for_layer_cooling", false }, + { "slow_down_layer_time", minimum_layer_time }, + { "slow_down_min_speed", 1 }, + }); + const std::vector unslowed = estimated_layers(cube(10), config); + config.set_deserialize_strict({ { "slow_down_for_layer_cooling", true } }); + const std::vector slowed = estimated_layers(cube(10), config); + REQUIRE(slowed.size() == unslowed.size()); + + // Layer 0 holds the start G-code, and the last layer the end G-code. + const size_t quick = std::count_if(unslowed.begin() + 1, unslowed.end() - 1, + [](const EstimatedLayer &layer) { return layer.time < minimum_layer_time; }); + REQUIRE(quick > 10); + for (size_t i = 1; i + 1 < slowed.size(); ++i) { + if (unslowed[i].time < minimum_layer_time) { + CHECK(slowed[i].time > 0.99 * minimum_layer_time); + CHECK(slowed[i].time < 1.03 * minimum_layer_time); + } else + CHECK_THAT(slowed[i].time, Catch::Matchers::WithinRel(unslowed[i].time, 0.001)); + } +} + +TEST_CASE("Fan speed follows the layer time with acceleration", "[Cooling]") +{ + constexpr double full_fan_time = 2.; + constexpr double minimum_fan_time = 100.; + constexpr double full_fan = 100.; + constexpr double minimum_fan = 20.; + DynamicPrintConfig config = slowly_accelerating_config(); + config.set_deserialize_strict({ + { "close_fan_the_first_x_layers", 0 }, + { "fan_cooling_layer_time", minimum_fan_time }, + { "fan_max_speed", full_fan }, + { "fan_min_speed", minimum_fan }, + { "full_fan_speed_layer", 0 }, + // A pause before the first extrusion of each layer, which counts as in the Preview. + { "layer_change_gcode", "G4 S3" }, + { "slow_down_for_layer_cooling", false }, + { "slow_down_layer_time", full_fan_time }, + }); + // The low acceleration is the machine limit, or the one the start G-code sets when the layers set none of their own. + if (GENERATE(false, true)) + config.set_deserialize_strict({ + { "default_acceleration", 0 }, + { "machine_max_acceleration_extruding", "20000,20000" }, + { "machine_start_gcode", "G90\n M204 S300 ; indented\nG92 E0" }, + }); + const std::vector layers = estimated_layers(cube(20), config); + REQUIRE(layers.size() > 4); + for (size_t i = 1; i + 1 < layers.size(); ++i) { + REQUIRE(layers[i].time > full_fan_time); + REQUIRE(layers[i].time < minimum_fan_time); + const double t = (layers[i].time - full_fan_time) / (minimum_fan_time - full_fan_time); + // The cooling rounds the speed down to a whole percent, and M106 takes it in 1/255 steps. + CHECK_THAT(layers[i].fan, Catch::Matchers::WithinAbs(t * minimum_fan + (1. - t) * full_fan, 1.5)); + } +}