From 3bfabc9831622fad0785c41625b4f9a62b63ac21 Mon Sep 17 00:00:00 2001 From: Antoine <15737031+MinDBreaK@users.noreply.github.com> Date: Sat, 14 Nov 2026 18:15:28 +0100 Subject: [PATCH 01/60] Fix Ankermake M5/M5C printing time (#17548) The Anker file header wrote `;TIME:{print_time_sec}s`. print_time_sec is only the seconds part of the estimate (0 to 59), so the M5, M5 All-Metal and M5C were told every print takes under a minute. Use print_time_total_sec, the whole estimate in seconds, and drop the `s`. --- resources/profiles/Anker.json | 2 +- resources/profiles/Anker/machine/fdm_marlin_common.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/resources/profiles/Anker.json b/resources/profiles/Anker.json index a902697e8c..7711db67e4 100644 --- a/resources/profiles/Anker.json +++ b/resources/profiles/Anker.json @@ -1,6 +1,6 @@ { "name": "Anker", - "version": "02.04.00.07", + "version": "02.04.00.08", "force_update": "0", "description": "Anker configurations", "machine_model_list": [ diff --git a/resources/profiles/Anker/machine/fdm_marlin_common.json b/resources/profiles/Anker/machine/fdm_marlin_common.json index 4f17be404f..044a9b2ca7 100644 --- a/resources/profiles/Anker/machine/fdm_marlin_common.json +++ b/resources/profiles/Anker/machine/fdm_marlin_common.json @@ -6,7 +6,7 @@ "instantiation": "false", "gcode_flavor": "marlin2", "before_layer_change_gcode": ";BEFORE_LAYER_CHANGE\nG92 E0.0\n;[layer_z]\n\n", - "file_start_gcode": ";TIME:{print_time_sec}s\n;Filament weight: {total_weight}g\n;Filament used: {used_filament}m\n;Layer height: {layer_height}\n;material_print_temperature_layer_0: {first_layer_temperature[0]}", + "file_start_gcode": ";TIME:{print_time_total_sec}\n;Filament weight: {total_weight}g\n;Filament used: {used_filament}m\n;Layer height: {layer_height}\n;material_print_temperature_layer_0: {first_layer_temperature[0]}", "machine_start_gcode": "M4899 T3 ; Enable v3 jerk and S-curve acceleration \nM104 S150 ; Set hotend temp to 150 degrees to prevent ooze\nM190 S{first_layer_bed_temperature[0]} ; set and wait for bed temp to stabilize\nM109 S{first_layer_temperature[0]} ; set final nozzle temp to stabilize\nG28 ;Home\n;LAYER_COUNT:{total_layer_count}", "machine_end_gcode": "M104 S0\nM140 S0\n;Retract the filament\nG92 E1\nG1 E-1 F300\nG28 X0 Y0\nM18", "change_filament_gcode": "M600", From 8a1cef365e47aa3c5a8b6ab18ffe71558cf716ab Mon Sep 17 00:00:00 2001 From: Ian Bassi Date: Sun, 15 Nov 2026 10:47:57 -0300 Subject: [PATCH 02/60] Time Layer Cooling With Acceleration, as the Preview Does (#17540) --- docs/HLSD/layer-cooling-time.md | 82 ++++++++++ src/libslic3r/GCode.cpp | 9 +- src/libslic3r/GCode/CoolingBuffer.cpp | 211 +++++++++++++++++++++++-- src/libslic3r/GCode/CoolingBuffer.hpp | 29 +++- src/libslic3r/GCode/GCodeProcessor.cpp | 15 +- tests/fff_print/test_cooling.cpp | 113 +++++++++++++ 6 files changed, 438 insertions(+), 21 deletions(-) create mode 100644 docs/HLSD/layer-cooling-time.md 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)); + } +} From ebfce227c6b0ead0c9f78c484969d2000e20412b Mon Sep 17 00:00:00 2001 From: Ian Bassi Date: Sun, 15 Nov 2026 11:07:56 -0300 Subject: [PATCH 03/60] Copy the Python runtime only when it changes, and use thin archives with clang-cl (#17511) --- CMakeLists.txt | 5 ++++ cmake/modules/StagePythonRuntime.cmake | 32 ++++++++++++++++++++++++++ scripts/run_unit_tests.sh | 2 +- src/CMakeLists.txt | 8 ++++--- tests/slic3rutils/CMakeLists.txt | 6 +++-- 5 files changed, 47 insertions(+), 6 deletions(-) create mode 100644 cmake/modules/StagePythonRuntime.cmake diff --git a/CMakeLists.txt b/CMakeLists.txt index a34fd2a9cd..a31ea9237e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -373,6 +373,11 @@ if (MSVC AND CMAKE_CXX_COMPILER_ID STREQUAL Clang) # clang-cl can interpret SYSTEM header paths if -imsvc is used set(CMAKE_INCLUDE_SYSTEM_FLAG_CXX "-imsvc") + + # Thin archives reference the objects instead of copying them; only lld-link reads them. + if (NOT CMAKE_GENERATOR MATCHES "Visual Studio" AND CMAKE_AR MATCHES "llvm-lib" AND CMAKE_LINKER MATCHES "lld-link") + string(APPEND CMAKE_STATIC_LINKER_FLAGS " /llvmlibthin") + endif () else () set(IS_CLANG_CL FALSE) endif () diff --git a/cmake/modules/StagePythonRuntime.cmake b/cmake/modules/StagePythonRuntime.cmake new file mode 100644 index 0000000000..b48ef9a600 --- /dev/null +++ b/cmake/modules/StagePythonRuntime.cmake @@ -0,0 +1,32 @@ +# cmake -DSOURCE= -DDESTINATION= -DSTAMP= -P StagePythonRuntime.cmake +# Copies only when SOURCE's files or their times changed since the copy STAMP records. +foreach (_var SOURCE DESTINATION STAMP) + if (NOT DEFINED ${_var}) + message(FATAL_ERROR "StagePythonRuntime.cmake: ${_var} is not set") + endif () +endforeach () + +file(GLOB_RECURSE _files LIST_DIRECTORIES false RELATIVE "${SOURCE}" "${SOURCE}/*") +list(SORT _files) +set(_signature "${SOURCE}\n") +foreach (_file IN LISTS _files) + file(TIMESTAMP "${SOURCE}/${_file}" _time "%Y%m%d%H%M%S" UTC) + string(APPEND _signature "${_file} ${_time}\n") +endforeach () +string(SHA256 _signature "${_signature}") + +if (IS_DIRECTORY "${DESTINATION}" AND EXISTS "${STAMP}") + file(READ "${STAMP}" _copied) + if (_copied STREQUAL _signature) + return() + endif () +endif () + +file(REMOVE "${STAMP}") +file(REMOVE_RECURSE "${DESTINATION}") +execute_process(COMMAND "${CMAKE_COMMAND}" -E copy_directory "${SOURCE}" "${DESTINATION}" + RESULT_VARIABLE _result) +if (NOT _result EQUAL 0) + message(FATAL_ERROR "Copying ${SOURCE} to ${DESTINATION} failed") +endif () +file(WRITE "${STAMP}" "${_signature}") diff --git a/scripts/run_unit_tests.sh b/scripts/run_unit_tests.sh index 5d2bd2b31d..1ad6c13c50 100755 --- a/scripts/run_unit_tests.sh +++ b/scripts/run_unit_tests.sh @@ -24,7 +24,7 @@ BUILD_CONFIG="${2:-}" # Install it with the uv staged beside that runtime -- the tool the app installs plugin # dependencies with -- straight into the interpreter's own site-packages: no pip needed # in the runtime, no PYTHONPATH. Re-checked every run because a rebuild of the test -# target re-copies the runtime; needs network whenever it installs. Pinned so a numpy +# target can re-copy the runtime; needs network whenever it installs. Pinned so a numpy # release cannot change results on its own. NUMPY_VERSION="2.5.3" diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index c8d882f291..b5d866304e 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -282,9 +282,11 @@ if (WIN32) endif () # copy libpython to the bin folder for Windows add_custom_command(TARGET OrcaSlicer POST_BUILD - COMMAND ${CMAKE_COMMAND} -E rm -rf "$/python" - COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_PREFIX_PATH}/libpython" "$/python" - COMMENT "Copying Python runtime into the build tree" + COMMAND ${CMAKE_COMMAND} "-DSOURCE=${CMAKE_PREFIX_PATH}/libpython" + "-DDESTINATION=$/python" + "-DSTAMP=${CMAKE_CURRENT_BINARY_DIR}/python_runtime_$.stamp" + -P "${CMAKE_SOURCE_DIR}/cmake/modules/StagePythonRuntime.cmake" + COMMENT "Updating the Python runtime in the build tree" VERBATIM) if (CMAKE_CONFIGURATION_TYPES) diff --git a/tests/slic3rutils/CMakeLists.txt b/tests/slic3rutils/CMakeLists.txt index 5765cc8207..18eec0f42d 100644 --- a/tests/slic3rutils/CMakeLists.txt +++ b/tests/slic3rutils/CMakeLists.txt @@ -90,8 +90,10 @@ orcaslicer_copy_test_dlls(${_TEST_NAME}_tests) if (WIN32) add_custom_command(TARGET ${_TEST_NAME}_tests POST_BUILD - COMMAND ${CMAKE_COMMAND} -E make_directory "$/python" - COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_PREFIX_PATH}/libpython" "$/python" + COMMAND ${CMAKE_COMMAND} "-DSOURCE=${CMAKE_PREFIX_PATH}/libpython" + "-DDESTINATION=$/python" + "-DSTAMP=${CMAKE_CURRENT_BINARY_DIR}/python_runtime_$.stamp" + -P "${CMAKE_SOURCE_DIR}/cmake/modules/StagePythonRuntime.cmake" COMMAND ${CMAKE_COMMAND} -E copy_if_different "${CMAKE_PREFIX_PATH}/libpython/python${_bundled_python_abi}.dll" "${CMAKE_PREFIX_PATH}/libpython/vcruntime140.dll" From 8b8d573a85c58b524bd2c943a05f6c17542ef606 Mon Sep 17 00:00:00 2001 From: Ian Bassi Date: Sun, 15 Nov 2026 11:29:03 -0300 Subject: [PATCH 04/60] Keep Outer Walls Out of the Resonance Avoidance Range in the Layer Cooling Slowdown (#17534) --- docs/HLSD/resonance-avoidance.md | 82 +++++++++++++++++++++++++ src/libslic3r/GCode/CoolingBuffer.cpp | 69 +++++++++++++++++++-- tests/fff_print/test_cooling.cpp | 86 ++++++++++++++++++++++++++- 3 files changed, 229 insertions(+), 8 deletions(-) create mode 100644 docs/HLSD/resonance-avoidance.md diff --git a/docs/HLSD/resonance-avoidance.md b/docs/HLSD/resonance-avoidance.md new file mode 100644 index 0000000000..a6ec873d55 --- /dev/null +++ b/docs/HLSD/resonance-avoidance.md @@ -0,0 +1,82 @@ +# Resonance avoidance — High Level Design + +## Purpose and scope + +Many printers ring or show vertical fine artifacts (VFAs) on the surface when +the toolhead moves within a certain speed range. Resonance avoidance keeps outer +walls out of that range. Only outer walls are covered, because they form the +visible surface. Inner walls, infill and the other features keep their speeds. + +The range is a property of the printer, so the settings are printer settings, in +Motion ability: `resonance_avoidance` (off by default), +`min_resonance_avoidance_speed` and `max_resonance_avoidance_speed`. The VFA +calibration measures the range. The calibrations that test speeds or motion turn +the option off, so it cannot hide what they measure: pressure advance, flow +rate, temperature, max volumetric speed, retraction, VFA, input shaping and +cornering. + +An outer wall can get its speed in two places: when the G-code is generated, and +later in the layer cooling slowdown. The range is enforced in both. + +## Speed of each path + +`GCode::_extrude()` resolves the speed of an outer wall path first. This covers +the outer wall speed, the small perimeter speed, the scarf seam speed, the first +layer speeds and their ramp over the following layers, and the cap from the +filament's max volumetric speed. When the result falls inside the range, it +moves to the nearer half's end: a speed in the lower half goes down to the +minimum, and a speed in the upper half goes up to the maximum. Speeds above the +range, and speeds below it, are left alone. + +## Layer cooling slowdown + +When a layer prints faster than the filament's minimum layer time, +`CoolingBuffer` slows the layer down, as [layer-cooling-time.md](layer-cooling-time.md) +describes. It lowers the fastest moves first, so most features end at one shared +speed. Without resonance avoidance, that speed can +fall anywhere, including inside the range. + +`CoolingBuffer::process_layer()` handles this in up to three passes of that +slowdown over the parsed layer: + +1. The normal slowdown runs. If no outer wall ends inside the range, its result + is used as is. +2. Otherwise the slowdown runs again from the unslowed layer. This time the outer + walls whose speed was at or above the maximum are fixed at the maximum and + are not adjustable. The other features must take the remaining time. This is + the same mechanism that "Don't slow down outer walls" uses to exclude outer + walls. +3. The second result is used if its estimated layer time reaches the time of + the first pass or the minimum layer time, whichever is shorter, within the + 0.2% the slowdown accepts short of its target. If not, the other features + cannot slow down enough, and the outer walls are fixed at the minimum of the + range instead. + +Holding at the maximum comes first for two reasons. The path speeds of outer +walls are already outside the range, so the walls held here had a speed above +it, and the maximum is the allowed speed closest to their own. It also keeps the wall speed smooth from layer to layer: as +the layers get shorter, the slowed speed drops towards the maximum and then +stays there. The minimum layer time is a cooling requirement, so it is never +traded for the range. The minimum of the range only adds time, so the fallback +always keeps the layer as long as the first pass made it. The fallback makes a +step in wall speed, from the maximum to the minimum, at the first layer that +needs it. + +Only the extruders whose outer walls landed inside the range are held. Holding +the walls of every extruder would slow filaments that the slowdown did not +touch, such as a filament with the slowdown turned off, or one whose own +minimum layer time the layer already meets. + +The layer is only copied when resonance avoidance is on, and the extra passes +run only on layers where an outer wall landed inside the range. With "Don't +slow down outer walls" on, the walls are never slowed, so these passes never +run. The cooling stage needs a minimum above zero, because holding a wall at +zero speed has no meaning. + +## Not covered + +Overhang speeds are set for each point of a path, after the path speed above. +They can put parts of an outer wall inside the range. Those speeds are set by +the user for overhang quality, so resonance avoidance leaves them as they are. +The cooling stage does not hold them either: it only holds outer walls whose +speed was at or above the maximum. diff --git a/src/libslic3r/GCode/CoolingBuffer.cpp b/src/libslic3r/GCode/CoolingBuffer.cpp index 6e2942aac1..d6bff1b1fc 100644 --- a/src/libslic3r/GCode/CoolingBuffer.cpp +++ b/src/libslic3r/GCode/CoolingBuffer.cpp @@ -344,6 +344,43 @@ finished: return new_feedrate; } +static bool outer_wall_slowed_into_range(const PerExtruderAdjustments &adj, float min_speed, float max_speed) +{ + return std::any_of(adj.lines.begin(), adj.lines.end(), [min_speed, max_speed](const CoolingLine &line) { + return line.slowdown && (line.type & CoolingLine::TYPE_EXTERNAL_PERIMETER) && line.feedrate > min_speed + EPSILON && + line.feedrate < max_speed - EPSILON; + }); +} + +// Fixes the outer walls printed at or above max_speed at speed, for the extruders whose walls the slowdown brought into the range. +static void hold_outer_walls(std::vector &unslowed, + const std::vector &slowed, + float min_speed, + float max_speed, + float speed) +{ + for (size_t i = 0; i < unslowed.size(); ++i) + if (outer_wall_slowed_into_range(slowed[i], min_speed, max_speed)) + for (CoolingLine &line : unslowed[i].lines) + if ((line.type & CoolingLine::TYPE_ADJUSTABLE) && (line.type & CoolingLine::TYPE_EXTERNAL_PERIMETER) && + line.feedrate > max_speed - EPSILON) { + line.type &= ~size_t(CoolingLine::TYPE_ADJUSTABLE); + line.feedrate = speed; + line.time = line.length / speed; + line.slowdown = true; + } +} + +// The longest minimum layer time among the filaments whose layer may slow down. +static float longest_minimum_layer_time(const std::vector &per_extruder_adjustments) +{ + float longest = 0.f; + for (const PerExtruderAdjustments &adj : per_extruder_adjustments) + if (adj.cooling_slow_down_enabled && ! adj.lines.empty()) + longest = std::max(longest, adj.slow_down_layer_time); + return longest; +} + std::string CoolingBuffer::process_layer(std::string &&gcode, size_t layer_id, bool flush) { // Cache the input G-code. @@ -357,7 +394,31 @@ 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); + const float ra_min = float(m_config.min_resonance_avoidance_speed.value); + const float ra_max = float(m_config.max_resonance_avoidance_speed.value); + const bool avoid_resonance = m_config.resonance_avoidance.value && ra_min > 0.f; + std::vector unslowed; + if (avoid_resonance) + unslowed = per_extruder_adjustments; float layer_time_stretched = this->slow_down_layer(m_gcode, per_extruder_adjustments); + if (avoid_resonance && std::any_of(per_extruder_adjustments.begin(), per_extruder_adjustments.end(), + [ra_min, ra_max](const PerExtruderAdjustments &adj) { + return outer_wall_slowed_into_range(adj, ra_min, ra_max); + })) { + // ORCA: Hold those outer walls at the top of the resonance range and slow the rest of the layer more, + // or at the bottom of the range when that cannot reach the layer time. + std::vector held = unslowed; + hold_outer_walls(held, per_extruder_adjustments, ra_min, ra_max, ra_max); + float held_time = this->slow_down_layer(m_gcode, held); + // The slowdown accepts a layer up to 0.2% short of its target. + if (held_time < 0.998f * std::min(layer_time_stretched, longest_minimum_layer_time(unslowed))) { + held = std::move(unslowed); + hold_outer_walls(held, per_extruder_adjustments, ra_min, ra_max, ra_min); + held_time = this->slow_down_layer(m_gcode, held); + } + per_extruder_adjustments = std::move(held); + layer_time_stretched = held_time; + } out = this->apply_layer_cooldown(m_gcode, layer_id, layer_time_stretched, per_extruder_adjustments); m_gcode.clear(); } @@ -835,12 +896,8 @@ float CoolingBuffer::estimate_layer_time(const std::string &gcode, const std::ve 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) { + 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) @@ -852,7 +909,7 @@ float CoolingBuffer::slow_down_layer(const std::string &gcode, std::vectorestimate_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; + const float target = longest_minimum_layer_time(per_extruder_adjustments) * 1.001f; if (time >= target) return time; diff --git a/tests/fff_print/test_cooling.cpp b/tests/fff_print/test_cooling.cpp index 01b8d6fabc..0e2d6a0210 100644 --- a/tests/fff_print/test_cooling.cpp +++ b/tests/fff_print/test_cooling.cpp @@ -19,6 +19,7 @@ #include "libslic3r/libslic3r.h" #include #include +#include #include #include @@ -215,13 +216,16 @@ struct EstimatedLayer float fan = -1.f; }; -static std::vector estimated_layers(const TriangleMesh &mesh, const DynamicPrintConfig &config) +static std::vector estimated_layers(const TriangleMesh &mesh, const DynamicPrintConfig &config, + std::string *gcode_text = nullptr) { Print print; Model model; init_print({ mesh }, print, model, config); GCodeProcessorResult result; - gcode(print, &result); + std::string text = gcode(print, &result); + if (gcode_text) + *gcode_text = std::move(text); std::vector layers; for (const GCodeProcessorResult::MoveVertex &move : result.moves) { if (move.layer_id >= layers.size()) @@ -315,3 +319,81 @@ TEST_CASE("Fan speed follows the layer time with acceleration", "[Cooling]") CHECK_THAT(layers[i].fan, Catch::Matchers::WithinAbs(t * minimum_fan + (1. - t) * full_fan, 1.5)); } } + +// The speeds of the outer wall extrusions, in mm/s. +static std::vector outer_wall_speeds(const std::string &gcode, const DynamicPrintConfig &config) +{ + std::vector speeds; + bool outer_wall = false; + GCodeReader parser; + parser.apply_config(config); + parser.parse_buffer(gcode, [&speeds, &outer_wall](GCodeReader &self, const GCodeReader::GCodeLine &line) { + const std::string_view comment = line.comment(); + if (comment.rfind("TYPE:", 0) == 0) + outer_wall = comment == "TYPE:Outer wall"; + if (outer_wall && line.extruding(self) && line.dist_XY(self) > 0.) + speeds.push_back(line.new_F(self) / MM_PER_MIN); + }); + return speeds; +} + +TEST_CASE("Layer cooling slowdown keeps outer walls out of the resonance avoidance range", "[Cooling]") +{ + constexpr double min_speed = 40.; + constexpr double max_speed = 90.; + // With inner walls and infill to slow down instead, the outer walls stay at the top of the range. A lone outer + // wall cannot pass its time on, so it drops to the bottom; its layers are quick, hence the shorter layer time. + const bool lone_wall = GENERATE(false, true); + const double held_speed = lone_wall ? min_speed : max_speed; + const double minimum_layer_time = lone_wall ? 2. : 10.; + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_deserialize_strict({ + { "bottom_shell_layers", lone_wall ? 0 : 3 }, + { "dont_slow_down_outer_wall", false }, + { "enable_arc_fitting", "disabled" }, + { "enable_overhang_speed", false }, + { "filament_max_volumetric_speed", 100 }, + { "initial_layer_print_height", 0.3 }, + // Below the range, so resonance avoidance leaves it alone. + { "initial_layer_speed", 30 }, + { "layer_height", 0.3 }, + { "max_resonance_avoidance_speed", max_speed }, + { "min_resonance_avoidance_speed", min_speed }, + { "outer_wall_speed", 200 }, + { "slow_down_for_layer_cooling", true }, + { "slow_down_layer_time", minimum_layer_time }, + { "slow_down_layers", 0 }, + { "slow_down_min_speed", 10 }, + { "sparse_infill_density", lone_wall ? "0%" : "15%" }, + { "top_shell_layers", lone_wall ? 0 : 3 }, + { "wall_loops", lone_wall ? 1 : 3 }, + }); + + // A cone's layers shrink upwards, so the slowdown deepens through the range. + std::string without_gcode; + std::string with_gcode; + config.set_deserialize_strict({ { "resonance_avoidance", false } }); + const std::vector without = estimated_layers(make_cone(15., 15.), config, &without_gcode); + config.set_deserialize_strict({ { "resonance_avoidance", true } }); + const std::vector with = estimated_layers(make_cone(15., 15.), config, &with_gcode); + + std::vector without_in_range; + std::vector with_in_range; + bool held = false; + for (double speed : outer_wall_speeds(without_gcode, config)) + if (speed > min_speed + 0.5 && speed < max_speed - 0.5) + without_in_range.push_back(speed); + for (double speed : outer_wall_speeds(with_gcode, config)) { + if (speed > min_speed + 0.5 && speed < max_speed - 0.5) + with_in_range.push_back(speed); + held |= std::abs(speed - held_speed) < 0.1; + } + REQUIRE_FALSE(without_in_range.empty()); + CHECK(with_in_range.empty()); + CHECK(held); + + // No layer gets shorter than the slowdown made it without resonance avoidance, within the slowdown's tolerance. + REQUIRE(with.size() == without.size()); + for (size_t i = 0; i < with.size(); ++i) + CHECK(with[i].time > 0.99 * std::min(without[i].time, minimum_layer_time)); +} From 0e8e95d516a302b6ea432f45392abf7559b4e3bb Mon Sep 17 00:00:00 2001 From: Rodrigo Faselli <162915171+RF47@users.noreply.github.com> Date: Sun, 15 Nov 2026 11:51:10 -0300 Subject: [PATCH 05/60] Fix Crash (access violation) instead of the "empty first layer" (#17565) --- src/libslic3r/GCode/WipeTower2.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/libslic3r/GCode/WipeTower2.cpp b/src/libslic3r/GCode/WipeTower2.cpp index 681a03e883..ccd3d78e92 100644 --- a/src/libslic3r/GCode/WipeTower2.cpp +++ b/src/libslic3r/GCode/WipeTower2.cpp @@ -1286,7 +1286,8 @@ std::vector WipeTower2::prime( toolchange_Load(writer, cleaning_box); // Prime the tool. if (idx_tool + 1 == tools.size()) { // Last tool should not be unloaded, but it should be wiped enough to become of a pure color. - toolchange_Wipe(writer, cleaning_box, wipe_volumes[tools[idx_tool-1]][tool], false, true); + const float wipe_volume = idx_tool == 0 ? 0.f : wipe_volumes[tools[idx_tool - 1]][tool]; + toolchange_Wipe(writer, cleaning_box, wipe_volume, false, true); } else { // Ram the hot material out of the melt zone, retract the filament into the cooling tubes and let it cool. //writer.travel(writer.x(), writer.y() + m_perimeter_width, 7200); From b4a9565deec5b2801d4da9fed36fd194a2a16da8 Mon Sep 17 00:00:00 2001 From: Noisyfox Date: Sun, 15 Nov 2026 22:52:27 +0800 Subject: [PATCH 06/60] Round mixed filament row corners (#17561) --- src/slic3r/GUI/Plater.cpp | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/src/slic3r/GUI/Plater.cpp b/src/slic3r/GUI/Plater.cpp index 14df7f21a6..4ff37b6157 100644 --- a/src/slic3r/GUI/Plater.cpp +++ b/src/slic3r/GUI/Plater.cpp @@ -82,6 +82,7 @@ #include "slic3r/GUI/Printer/PrinterFileSystem.h" #include "slic3r/GUI/GUI_Geometry.hpp" #include "slic3r/GUI/Widgets/DialogButtons.hpp" +#include "slic3r/GUI/Widgets/StaticBox.hpp" #include "slic3r/GUI/PrintOptionsDialog.hpp" #include "slic3r/GUI/CalibrationPanel.hpp" #include "slic3r/GUI/CalibrationWizard.hpp" @@ -117,6 +118,7 @@ #include #include #include +#include #include #include #include @@ -4624,9 +4626,19 @@ void Sidebar::update_mixed_filament_list() wxBufferedPaintDC dc(content_panel); wxSize sz = content_panel->GetClientSize(); - dc.SetBrush(wxBrush(mc_bg)); - dc.SetPen(wxPen(mc_border, 1)); - dc.DrawRectangle(0, 0, sz.GetWidth(), sz.GetHeight()); + dc.SetBackground(wxBrush(StaticBox::GetParentBackgroundColor(content_panel->GetParent()))); + dc.Clear(); + if (sz.GetWidth() < 2 || sz.GetHeight() < 2) + return; + { + wxGCDC gdc(dc); + wxDC* border_dc = gdc.IsOk() ? static_cast(&gdc) : &dc; + const int border_width = 1; + border_dc->SetBrush(wxBrush(mc_bg)); + border_dc->SetPen(wxPen(mc_border, border_width)); + border_dc->DrawRoundedRectangle(0, 0, sz.GetWidth(), sz.GetHeight(), + content_panel->FromDIP(StaticBox::InputCornerRadius) - border_width); + } dc.SetFont(::Label::Body_13); int x = cp_pad; From 87fb98766832852737d83e64e93da3e289394e5a Mon Sep 17 00:00:00 2001 From: Kiss Lorand <50251547+kisslorand@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:52:34 +0200 Subject: [PATCH 07/60] Fix part deformation in Assembly Parallel operation (#17552) --- src/slic3r/GUI/Gizmos/GLGizmoMeasure.cpp | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/slic3r/GUI/Gizmos/GLGizmoMeasure.cpp b/src/slic3r/GUI/Gizmos/GLGizmoMeasure.cpp index 41a764ea44..9d74e11bf1 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoMeasure.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoMeasure.cpp @@ -2572,12 +2572,13 @@ void GLGizmoMeasure::set_to_parallel(bool same_model_object, bool take_shot, boo v->set_instance_rotation(rotation); selection->rotate(v->object_idx(), v->instance_idx(), v->get_instance_transformation().get_matrix()); } else { - Geometry::Transformation world_tran(v->world_matrix()); - auto new_tran = r_m * world_tran.get_rotation_matrix(); - Transform3d volume_rotation_tran = v->get_instance_transformation().get_rotation_matrix().inverse() * new_tran; - Vec3d rotation = Geometry::extract_euler_angles(volume_rotation_tran); - v->set_volume_rotation(rotation); - selection->rotate(v->object_idx(), v->instance_idx(), v->volume_idx(), v->get_volume_transformation().get_matrix()); + const Transform3d &instance = v->get_instance_transformation().get_matrix(); + Transform3d rotated_world = instance * v->get_volume_transformation().get_matrix(); + // Rotate about the part origin while retaining its position and full affine transform. + rotated_world.linear() = rotation_matrix * rotated_world.linear().eval(); + const Transform3d volume_tran = instance.inverse() * rotated_world; + v->set_volume_transformation(volume_tran); + selection->rotate(v->object_idx(), v->instance_idx(), v->volume_idx(), volume_tran); } wxGetApp().plater()->canvas3D()->do_rotate(""); register_single_mesh_pick(); From f5305fa5426e48939689354ad832058328da6f19 Mon Sep 17 00:00:00 2001 From: yw4z Date: Mon, 16 Nov 2026 01:12:49 +0300 Subject: [PATCH 08/60] Remove the unused NanoSVG deps recipe (#17583) --- deps/NanoSVG/NanoSVG.cmake | 10 ---------- 1 file changed, 10 deletions(-) delete mode 100644 deps/NanoSVG/NanoSVG.cmake diff --git a/deps/NanoSVG/NanoSVG.cmake b/deps/NanoSVG/NanoSVG.cmake deleted file mode 100644 index 5c833e3249..0000000000 --- a/deps/NanoSVG/NanoSVG.cmake +++ /dev/null @@ -1,10 +0,0 @@ -# In PrusaSlicer 2.6.0 we switched from https://github.com/memononen/nanosvg to its fork https://github.com/fltk/nanosvg -# because this last implements the new function nsvgRasterizeXY() which we now use in GLTexture::load_from_svg() -# for rasterizing svg files from their original size to a squared power of two texture on Windows systems using -# AMD Radeon graphics cards - -orcaslicer_add_cmake_project(NanoSVG - DEPENDS dep_Boost - URL https://github.com/SoftFever/nanosvg/archive/863f6aa97ef62028126fa2c19bd4350394c2e15e.zip - URL_HASH SHA256=8d9c1624ad6518dd6dfa31e4f8dc7da9ec243d88bae595c7a037450617fec851 -) \ No newline at end of file From ff93256eff8e6fb3fc274c6c483f69db9367a0c9 Mon Sep 17 00:00:00 2001 From: yw4z Date: Mon, 16 Nov 2026 06:24:56 +0300 Subject: [PATCH 09/60] LabeledCheckBox class (#15761) * init * extend feature set * update * fix tidy * fix tidy * Update calib_dlg.cpp * simplify class * update * align labels with RadioGroup * replace ImportCheckBox * Update LabeledCheckBox.cpp * apply to more dialog * add to ai skills * update * fix Tooltip only reaches the children on the first call * fix Label can stay grey after a theme switch * Update release dialog * change focus target for all platforms --------- Co-authored-by: Noisyfox --- .claude/skills/orca-wxwidgets/SKILL.md | 14 +- .../references/controls-dataview.md | 13 +- .../orca-wxwidgets/references/events.md | 4 + .../orca-wxwidgets/references/orca-widgets.md | 125 ++++++- .../references/sizers-layout.md | 4 +- src/slic3r/CMakeLists.txt | 4 +- src/slic3r/GUI/GeometryImportDialog.cpp | 92 ++---- src/slic3r/GUI/GeometryImportDialog.hpp | 19 +- src/slic3r/GUI/MixedFilamentDialog.cpp | 25 +- src/slic3r/GUI/MixedFilamentDialog.hpp | 8 +- src/slic3r/GUI/MsgDialog.cpp | 44 +-- src/slic3r/GUI/MsgDialog.hpp | 4 +- src/slic3r/GUI/PrimitiveSizeDialog.cpp | 17 +- src/slic3r/GUI/PrimitiveSizeDialog.hpp | 10 +- src/slic3r/GUI/ReleaseNote.cpp | 20 +- src/slic3r/GUI/ReleaseNote.hpp | 8 +- src/slic3r/GUI/SavePresetDialog.cpp | 35 +- src/slic3r/GUI/StepMeshDialog.cpp | 45 ++- src/slic3r/GUI/StepMeshDialog.hpp | 13 +- src/slic3r/GUI/Tab.cpp | 26 +- src/slic3r/GUI/Tab.hpp | 4 +- src/slic3r/GUI/TextureImportDialog.cpp | 5 +- src/slic3r/GUI/TextureImportDialog.hpp | 4 +- src/slic3r/GUI/UVEditorCanvas.cpp | 28 +- src/slic3r/GUI/UVEditorCanvas.hpp | 4 +- src/slic3r/GUI/UnsavedChangesDialog.cpp | 20 +- src/slic3r/GUI/UnsavedChangesDialog.hpp | 5 +- src/slic3r/GUI/Widgets/LabeledCheckBox.cpp | 307 ++++++++++++++++++ src/slic3r/GUI/Widgets/LabeledCheckBox.hpp | 74 +++++ src/slic3r/GUI/calib_dlg.cpp | 20 +- src/slic3r/GUI/calib_dlg.hpp | 7 +- 31 files changed, 671 insertions(+), 337 deletions(-) create mode 100644 src/slic3r/GUI/Widgets/LabeledCheckBox.cpp create mode 100644 src/slic3r/GUI/Widgets/LabeledCheckBox.hpp diff --git a/.claude/skills/orca-wxwidgets/SKILL.md b/.claude/skills/orca-wxwidgets/SKILL.md index 0e39ce9d24..9bd352039e 100644 --- a/.claude/skills/orca-wxwidgets/SKILL.md +++ b/.claude/skills/orca-wxwidgets/SKILL.md @@ -56,11 +56,12 @@ the source is what runs — the references mark such facts **[source]**. Orca-si ## Golden rules -1. **Interactive controls are Orca widgets** (`Button` + `SetStyle(...)`, `::CheckBox`, `::ComboBox`, - `::TextInput`, `SpinInput`, `SwitchButton`, `RadioGroup`, `TabCtrl`); the bottom row of every dialog is - `DialogButtons`. Never `wxButton`, `wxSpinCtrl`, `wxCheckBox`, `wxChoice` or a single-line `wxTextCtrl` - in new code; multi-line text is a raw `wxTextCtrl`. Inside `Slic3r::GUI` write `::CheckBox` etc. — - `Field.hpp` has classes with the same names. → `orca-widgets.md` +1. **Interactive controls are Orca widgets** (`Button` + `SetStyle(...)`, `::CheckBox`, `LabeledCheckBox`, + `::ComboBox`, `::TextInput`, `SpinInput`, `SwitchButton`, `RadioGroup`, `TabCtrl`); the bottom row of every + dialog is `DialogButtons`. Never `wxButton`, `wxSpinCtrl`, `wxCheckBox`, `wxChoice` or a single-line + `wxTextCtrl` in new code; multi-line text is a raw `wxTextCtrl`. When the label is on the right side of the + check box and belongs to it, use a `LabeledCheckBox`, not a `::CheckBox` paired with a label by hand. Inside + `Slic3r::GUI` write `::CheckBox` etc. — `Field.hpp` has classes with the same names. → `orca-widgets.md` 2. **DPI.** Layout pixel values go through `FromDIP(n)` (or `n * em_unit()`); `wxBitmap` constructor sizes, image-list sizes and GL viewports are physical and are not `FromDIP`'d (icon heights passed to `create_scaled_bitmap`/`ScalableBitmap`/`Button` are DIP). Top-level windows are `DPIDialog`/ @@ -171,7 +172,8 @@ if (dlg.ShowModal() == wxID_OK) { /* read results */ } | Orca widget (`src/slic3r/GUI/Widgets/`) | Instead of | Must know | |---|---|---| | `Button` | `wxButton` | ctor `(parent, text, icon_name, style, iconSize, id)` — id is last; style with `SetStyle(ButtonStyle::…, ButtonType::…)`; emits `wxEVT_BUTTON`; not a `wxButton` (no dialog default/escape emulation) | -| `::CheckBox` | `wxCheckBox` | no label parameter — pair with a `wxStaticText`/`Label`; emits `wxEVT_TOGGLEBUTTON` (never `wxEVT_CHECKBOX`), and a handler bound on it must `Skip()` or the bitmap is not refreshed | +| `::CheckBox` | `wxCheckBox` without a label | no label parameter — when the label is on the right side of the check box and belongs to it, use `LabeledCheckBox`; emits `wxEVT_TOGGLEBUTTON` (never `wxEVT_CHECKBOX`), and a handler bound on it must `Skip()` or the bitmap is not refreshed | +| `LabeledCheckBox` | `wxCheckBox` with a label, a `::CheckBox` hand-paired with its own label on the right side | ctor `(parent, label, id)`; a click on the check or the label sends `wxEVT_CHECKBOX` **and** `wxEVT_TOGGLEBUTTON` from the control — bind one; `SetValue` silent; label, font, `Wrap(width)`/`AutoWrap()` and `Enable()` go through the control, not its children | | `::ComboBox` (+ `DropDown`) | `wxComboBox`/`wxChoice` | `wxCB_READONLY` for choices; `SelectAndNotify(n)` fires the event; ignores the ctor id; `void*` client data only | | `::TextInput` | single-line `wxTextCtrl` | text via `GetTextCtrl()`; bind `wxEVT_TEXT_ENTER`/`wxEVT_KILL_FOCUS` on the widget, never on a parent | | `SpinInput` | `wxSpinCtrl` | non-negative integers only (`-` cannot be typed); commits on Enter, kill-focus and arrow steps with `wxEVT_SPINCTRL`, a plain `wxCommandEvent` — bind a `wxCommandEvent&` handler and read `GetValue()` | diff --git a/.claude/skills/orca-wxwidgets/references/controls-dataview.md b/.claude/skills/orca-wxwidgets/references/controls-dataview.md index 3671e05991..a6721f5237 100644 --- a/.claude/skills/orca-wxwidgets/references/controls-dataview.md +++ b/.claude/skills/orca-wxwidgets/references/controls-dataview.md @@ -73,6 +73,7 @@ Contents: [Rules](#rules) · [Native vs generic](#native-vs-generic-and-silent-a constructor, so bind on the combo (or `SetId()` after construction if an id filter is unavoidable). → [Orca widgets](#orca-replacement-widgets-event-contracts) 26. `::CheckBox`/`SwitchButton` emit `wxEVT_TOGGLEBUTTON`, and a handler bound on the widget itself must `Skip()`; + `LabeledCheckBox` sends `wxEVT_CHECKBOX` and `wxEVT_TOGGLEBUTTON` from itself — bind one; `RadioGroup::SetSelection` always emits; `SpinInput`'s `wxEVT_SPINCTRL` is a plain `wxCommandEvent`. → [Orca widgets](#orca-replacement-widgets-event-contracts) 27. Expect Orca's colours on every generic data view and `RenderText` on MSW: `ObjectList` installs a @@ -300,8 +301,8 @@ Contract: - `wxRadioBox::SetSelection(n)` needs a valid `n`, never `wxNOT_FOUND` (`interface/wx/radiobox.h:292-295`), and sends no event. -OrcaSlicer: interactive check boxes are `::CheckBox`/`SwitchButton`, radio rows are `::RadioGroup`; their event -contracts differ from these ([below](#checkbox-and-switchbutton)). +OrcaSlicer: interactive check boxes are `::CheckBox`/`LabeledCheckBox`/`SwitchButton`, radio rows are +`::RadioGroup`; their event contracts differ from these ([below](#checkbox-and-switchbutton)). Pitfalls: - **Rule:** Put `wxRB_GROUP` on the first button of *every* group. @@ -751,6 +752,7 @@ Bind column means an ancestor bound by event type; binding an ancestor by the wi | `::ComboBox` | `wxComboBox`/`wxChoice` | `wxEVT_COMBOBOX` (int = index, string = text); DROPDOWN/CLOSEUP | COMBOBOX: combo's auto-generated id (the ctor `id` is ignored) and object; DROPDOWN/CLOSEUP: id 0, no object | `SetSelection`/`SetValue` → `wxEVT_TEXT` when the text ctrl is shown or `CB_NO_TEXT`; `SelectAndNotify` → `wxEVT_COMBOBOX` | COMBOBOX on the combo (or an ancestor); DROPDOWN/CLOSEUP on the combo without id | | `::SpinInput` | `wxSpinCtrl` | `wxEVT_SPINCTRL` (a `wxCommandEvent`); `EVT_SPINCTRL_TEXT` per parsable keystroke; inner `wxEVT_TEXT` | SPINCTRL / SPINCTRL_TEXT: spinner id/object | `SetValue(int)` → `EVT_SPINCTRL_TEXT` + `wxEVT_TEXT`, no `wxEVT_SPINCTRL` | SPINCTRL on the spinner or an ancestor, handler takes `wxCommandEvent&` | | `::CheckBox`, `SwitchButton` | `wxCheckBox` | `wxEVT_TOGGLEBUTTON` | native | `SetValue` silent | on the widget (with `Skip()`) or an ancestor; never `wxEVT_CHECKBOX` | +| `LabeledCheckBox` | `wxCheckBox` with its own label on the right side | `wxEVT_CHECKBOX`, then `wxEVT_TOGGLEBUTTON` | control id/object | `SetValue` silent | on the control or an ancestor, **one** of the two | | `::RadioGroup` | `wxRadioBox` | `wxEVT_COMMAND_RADIOBOX_SELECTED` | group id, no object | **every** `SetSelection` emits | on the group or an ancestor | | `::TabCtrl` | tab bar | `wxEVT_TAB_SEL_CHANGING` then `wxEVT_TAB_SEL_CHANGED` (plain `wxCommandEvent`) | tab ctrl id/object; CHANGING carries the old index | `SelectItem(i)` emits both when `i` changes | on the ctrl or an ancestor; cannot veto | | `Button` | `wxButton` | `wxEVT_BUTTON` | button id/object | — | on the button or an ancestor | @@ -815,9 +817,10 @@ two arrow `Button`s with key-repeat; `SetValue/GetValue/SetRange/SetStep`. ### CheckBox and SwitchButton -`::CheckBox` (ctor `CheckBox(parent, id = wxID_ANY)`, no label — pair it with a `wxStaticText`/`Label`, as -`CloneDialog` does) and `SwitchButton` are `wxBitmapToggleButton`s. They emit `wxEVT_TOGGLEBUTTON`, never -`wxEVT_CHECKBOX`; `SetValue` sends nothing. The half state is drawn only (`SetHalfChecked`/`IsHalfChecked`); any click +`::CheckBox` (ctor `CheckBox(parent, id = wxID_ANY)`, no label — when the label is on the right side of the check +box and belongs to it, use `LabeledCheckBox`, `references/orca-widgets.md §LabeledCheckBox`) and `SwitchButton` are +`wxBitmapToggleButton`s. They emit `wxEVT_TOGGLEBUTTON`, never `wxEVT_CHECKBOX`; `SetValue` sends nothing. The half +state is drawn only (`SetHalfChecked`/`IsHalfChecked`); any click clears it via the widget's own `wxEVT_TOGGLEBUTTON` handler (bound in the constructor), which also swaps the on/off bitmap. Handlers bound later on the same widget run first, so they must `Skip()`, or the bitmap keeps showing the old state and the half state is never cleared (`PreferencesDialog::create_item_bambu_cloud` marks this with "let diff --git a/.claude/skills/orca-wxwidgets/references/events.md b/.claude/skills/orca-wxwidgets/references/events.md index 98944c9646..f98c21220e 100644 --- a/.claude/skills/orca-wxwidgets/references/events.md +++ b/.claude/skills/orca-wxwidgets/references/events.md @@ -941,6 +941,10 @@ The per-widget table (event types, ids and event objects, which setters emit, wh constructor (clears the half state, refreshes the bitmap, Skips); `TextInput`'s handlers on the inner control run `OnEdit` and the re-dispatch. A user handler bound on the widget (or on `GetTextCtrl()`) for those events must `Skip()`. Capture-lost handling: `references/mouse-keyboard-focus.md`. +- **`LabeledCheckBox` re-emits.** It consumes its inner check's `wxEVT_TOGGLEBUTTON` and sends `wxEVT_CHECKBOX`, then + `wxEVT_TOGGLEBUTTON`, from itself (own id and object), for label clicks too. It has no handler of its own for the + two, so a handler bound on it needs no `Skip()` — but one bound to both runs twice + (`references/orca-widgets.md §LabeledCheckBox`). - **`EVT_ENABLE_CHANGED`** (`StateHandler.hpp`, a `wxCommandEvent` with id 0) comes from the `Enable` overrides of `Button`, `SpinInput`, `RadioGroup` and the other `StateHandler` widgets. `StateHandler` Skips it, so it propagates to ancestors like any command event. diff --git a/.claude/skills/orca-wxwidgets/references/orca-widgets.md b/.claude/skills/orca-wxwidgets/references/orca-widgets.md index 0efc91fb0a..b52cf90a3d 100644 --- a/.claude/skills/orca-wxwidgets/references/orca-widgets.md +++ b/.claude/skills/orca-wxwidgets/references/orca-widgets.md @@ -12,7 +12,8 @@ Contents: [Rules](#rules) · [Why the library exists](#why-the-library-exists) [Namespaces](#namespaces-and-the-checkbox-clash) · [Catalog](#catalog) · [Event semantics](#event-semantics) · [Custom vs raw](#custom-vs-raw) · [Shared lifecycle rules](#shared-lifecycle-rules) · [Button](#button) · [DialogButtons](#dialogbuttons) · [Label and HyperLink](#label-and-hyperlink) · [CheckBox](#checkbox-and-radiobox) · -[SwitchButton family](#switchbutton-family) · [RadioGroup](#radiogroup) · [TextInput](#textinput) · +[LabeledCheckBox](#labeledcheckbox) · [SwitchButton family](#switchbutton-family) · [RadioGroup](#radiogroup) · +[TextInput](#textinput) · [ComboBox and DropDown](#combobox-and-dropdown) · [SpinInput](#spininput-and-tempinput) · [Tab systems](#tab-systems) · [StaticBox, LabeledStaticBox, StaticLine](#staticbox-labeledstaticbox-staticline) · [ProgressBar](#progressbar) · [ScrolledWindow](#scrolledwindow) · [PopupWindow](#popupwindow) · @@ -21,9 +22,9 @@ Contents: [Rules](#rules) · [Why the library exists](#why-the-library-exists) ## Rules -1. Interactive controls in new or modified UI are Orca widgets (`Button`, `::CheckBox`, `::ComboBox`, `::TextInput`, - `SpinInput`, `SwitchButton`, `RadioGroup`, `TabCtrl`); never `wxButton`, `wxSpinCtrl`, `wxCheckBox`, `wxChoice` or - a single-line `wxTextCtrl` in new code. → §Custom vs raw +1. Interactive controls in new or modified UI are Orca widgets (`Button`, `::CheckBox`, `LabeledCheckBox`, + `::ComboBox`, `::TextInput`, `SpinInput`, `SwitchButton`, `RadioGroup`, `TabCtrl`); never `wxButton`, `wxSpinCtrl`, + `wxCheckBox`, `wxChoice` or a single-line `wxTextCtrl` in new code. → §Custom vs raw 2. Every dialog's bottom button row is `DialogButtons`. → §DialogButtons 3. Inside `namespace Slic3r::GUI` write `::CheckBox`, `::TextInput`, `::ComboBox` (also in `dynamic_cast` and forward declarations, which go at global scope). → §Namespaces @@ -38,7 +39,8 @@ Contents: [Rules](#rules) · [Why the library exists](#why-the-library-exists) 7. Know which setters emit: `RadioGroup::SetSelection`, `MultiSwitchButton::SetSelection`, `TabCtrl::SelectItem`, `Notebook::SetSelection`, an editable `ComboBox::SetSelection` (as `wxEVT_TEXT`) and `SpinInput::SetValue` (as `wxEVT_TEXT` + `EVT_SPINCTRL_TEXT`) do. → §Event semantics -8. `::CheckBox` and `SwitchButton` emit `wxEVT_TOGGLEBUTTON`, never `wxEVT_CHECKBOX`. → §CheckBox and RadioBox +8. `::CheckBox` and `SwitchButton` emit `wxEVT_TOGGLEBUTTON`, never `wxEVT_CHECKBOX`; `LabeledCheckBox` sends both + from itself. → §CheckBox and RadioBox, §LabeledCheckBox 9. Set a container's background colour before creating widgets in it. → §Shared lifecycle rules 10. Enable/disable custom widgets individually; disabling an ancestor leaves them painted enabled (`::CheckBox`, a native button, greys with it). → §Shared lifecycle rules @@ -61,6 +63,9 @@ Contents: [Rules](#rules) · [Why the library exists](#why-the-library-exists) → §StaticBox, LabeledStaticBox, StaticLine 21. Links are `HyperLink`, or a `Label` given `LB_HYPERLINK` through `SetWindowStyleFlag` (the constructor ignores it). → §Label and HyperLink +22. When the label is on the right side of the check box and belongs to it, use a `LabeledCheckBox`, not a + `::CheckBox` paired with a label by hand. Bind **one** of its two events; change its label, font and wrap through + the control; read its enabled state through a `LabeledCheckBox*`. → §LabeledCheckBox ## Why the library exists @@ -134,6 +139,7 @@ class, which is not a `wxWindow`. `TextCtrl` also names the MSW `wxTextCtrl` sub | `Label` | `wxStaticText` | `wxStaticText` | `Label(parent, text = "", style = 0, size)` (font `Body_14`), `Label(parent, font, text, style, size)` | `LB_AUTO_WRAP`, `LB_PROPAGATE_MOUSE_EVENT`, `LB_HYPERLINK` (via `SetWindowStyleFlag`); hosts the font table. §Label | | `HyperLink` (`Slic3r::GUI`) | `wxHyperlinkCtrl` | `wxStaticText` | `HyperLink(parent, label = "", url = "", style = 0)` | opens `url` with `wxLaunchDefaultBrowser` on left-down. §Label | | `::CheckBox` | `wxCheckBox` | `wxBitmapToggleButton` | `CheckBox(parent, id = wxID_ANY)` — **no label** | emits `wxEVT_TOGGLEBUTTON`; `SetHalfChecked`; `Rescale()`. §CheckBox | +| `LabeledCheckBox` | `wxCheckBox` with a label, a `::CheckBox` paired with its own label on the right side | `wxPanel` | `LabeledCheckBox(parent, label = "", id = wxID_ANY)` | clickable label with focus frame; emits `wxEVT_CHECKBOX` **and** `wxEVT_TOGGLEBUTTON`; `Wrap(width)`/`AutoWrap()`; `GetLabelCtrl()`; `Rescale()`. §LabeledCheckBox | | `SwitchButton` | on/off `wxCheckBox`, `wxToggleButton` | `wxBitmapToggleButton` | `SwitchButton(parent = nullptr, id = wxID_ANY)` | `SetLabels(on, off)`; track/thumb/text `StateColor`s; emits `wxEVT_TOGGLEBUTTON`. §SwitchButton family | | `MultiSwitchButton` | segmented `wxRadioBox` | `StaticBox` | `MultiSwitchButton(parent, id, pos, size, style)` | emits `wxCUSTOMEVT_MULTISWITCH_SELECTION`, also from `SetSelection`. §SwitchButton family | | `RadioGroup` | `wxRadioBox`, `wxRadioButton` rows | `wxPanel` | `RadioGroup(parent, std::vector labels, wxHORIZONTAL/wxVERTICAL, row_col_limit = -1)` | emits `wxEVT_RADIOBOX` from **every** `SetSelection`. §RadioGroup | @@ -164,6 +170,7 @@ Field classes (`Field.cpp`) build their editors from these widgets (`TextCtrl` |---|---|---|---|---| | `Button` | `wxEVT_BUTTON` (on release inside, Space/Enter) | button id / button | `SetValue(bool)` (Checked look) silent | on the button (Rule 6) | | `::CheckBox`, `SwitchButton` | `wxEVT_TOGGLEBUTTON` | native id / widget | `SetValue`, `SetHalfChecked` silent (`interface/wx/tglbtn.h:98`) | on the widget; never `wxEVT_CHECKBOX` | +| `LabeledCheckBox` | `wxEVT_CHECKBOX`, then `wxEVT_TOGGLEBUTTON` (int = new value), also from a label click | control id / control | `SetValue`, `SetHalfChecked` silent | on the control, **one** of the two; no `Skip()` needed for the bitmap | | `::ComboBox` | `wxEVT_COMBOBOX` (int = index, string = text) from popup pick, arrow keys (read-only combo), `SelectAndNotify`; `wxEVT_COMBOBOX_DROPDOWN`/`_CLOSEUP` | COMBOBOX: combo's auto id / combo; DROPDOWN/CLOSEUP: **id 0, no object** | `SetSelection`, `SetValue` silent for COMBOBOX; editable or `CB_NO_TEXT`: they send `wxEVT_TEXT` | on the combo | | `::TextInput` | inner `wxEVT_TEXT` (propagates); `wxEVT_TEXT_ENTER`, `wxEVT_KILL_FOCUS` re-sent to the wrapper only | TEXT: **inner** id/object; ENTER/KILL_FOCUS: wrapper id, inner object | `GetTextCtrl()->SetValue` sends `wxEVT_TEXT`; `ChangeValue` silent | TEXT: wrapper, inner, or ancestor by type; ENTER/KILL_FOCUS: wrapper or inner | | `SpinInput` | `wxEVT_SPINCTRL` (a plain `wxCommandEvent`, no int) on commit; `EVT_SPINCTRL_TEXT` (int + string) per parseable keystroke; inner `wxEVT_TEXT` | spinner id / spinner | `SetValue` sends `EVT_SPINCTRL_TEXT` + `wxEVT_TEXT`, no `wxEVT_SPINCTRL` | on the spinner; handler takes `wxCommandEvent&` | @@ -221,7 +228,9 @@ No Orca replacement exists — use raw wx (`references/controls-dataview.md`) fo **Background snapshot.** `StaticBox::Create`, `Label`, `SwitchButton` (through `StaticBox::GetParentBackgroundColor`: a parent `StaticBox`'s default fill — the midpoint for a gradient — else `parent->GetBackgroundColour()`), and -`::CheckBox`, `RadioGroup` (`parent->GetBackgroundColour()`) copy the parent's background colour at construction; +`::CheckBox`, `RadioGroup` (`parent->GetBackgroundColour()`) copy the parent's background colour at construction, and +so does `LabeledCheckBox` (`GetParentBackground` in `LabeledCheckBox.cpp`: the parent's colour, or under a scrolled +window the colour of that window's child on the parent chain); wx itself never inherits a background colour ([source] `src/common/wincmn.cpp:1543-1552`). - **Rule:** Set the container's background before creating widgets in it. ```cpp @@ -242,7 +251,8 @@ its disabled bitmap (`src/msw/window.cpp:576-593`, `src/msw/anybutton.cpp:846-87 button image draws a greyed copy of the current bitmap while `!IsEnabled()` (`src/gtk/image_gtk.cpp:37-42`), though the disabled bitmap itself needs `IsThisEnabled()` false (`src/gtk/anybutton.cpp:140-146`); macOS sends `setEnabled:NO` (`src/osx/cocoa/window.mm:3784-3791`) and AppKit dims the image (`NSButtonCell` -`imageDimsWhenDisabled`, default YES). +`imageDimsWhenDisabled`, default YES). A `LabeledCheckBox` is half of each: its inner check greys with the parent, its +label keeps the enabled colour, which only `LabeledCheckBox::Enable` changes. - **Rule:** Enable/disable each custom widget directly (`RadioGroup::Enable` does this for its own buttons). ```cpp m_options_panel->Enable(on); // Wrong: widgets keep the enabled look @@ -251,8 +261,8 @@ the disabled bitmap itself needs `IsThisEnabled()` false (`src/gtk/anybutton.cpp ``` **DPI.** Widgets size themselves from `FromDIP` values and cached bitmaps; after a DPI change the owning -`DPIDialog::on_dpi_changed` must call `Rescale()` on each (`Button`, `::CheckBox`, `::TextInput`, `::ComboBox` -(also rescales its `DropDown`), `SpinInput`, `SwitchButton`, `MultiSwitchButton`, `TabCtrl`, `StaticLine`, +`DPIDialog::on_dpi_changed` must call `Rescale()` on each (`Button`, `::CheckBox`, `LabeledCheckBox`, `::TextInput`, +`::ComboBox` (also rescales its `DropDown`), `SpinInput`, `SwitchButton`, `MultiSwitchButton`, `TabCtrl`, `StaticLine`, `ModeSwitchButton`). Exceptions: `RadioGroup`, `Label`, `HyperLink` and `LabeledStaticBox` (its scale is fixed in `Create()`) have no `Rescale()`; `ProgressBar::Rescale()` is empty; `DialogButtons` rescales itself. Pass sizes through `FromDIP` (`references/dpi-bitmaps-fonts.md`). @@ -276,7 +286,8 @@ it re-reads colours, e.g. `SwitchButton`), and keep `UpdateDlgDarkUI(this)` as t a label, font, icon, style or DPI changes, and the bitmap toggles (`::CheckBox`, `SwitchButton`) size themselves to their bitmap in `Rescale()`. Nothing re-lays out the parent: call `Layout()` on the container after changing a widget's content at runtime -(`references/sizers-layout.md`). +(`references/sizers-layout.md`). `LabeledCheckBox` is the exception: its setters re-fit it and send the parent a size +event (§LabeledCheckBox). **Mouse capture.** `Button`, `DropDown`, `SpinInput`'s arrows, `ModeSwitchButton`, `MyScrollbar`, `StepCtrl` and the device-page `SideButton`, `ImageSwitchButton` and `AxisCtrlButton` capture the mouse while pressed; a capture leak @@ -461,8 +472,10 @@ Pitfalls: ## CheckBox and RadioBox `::CheckBox` (`Widgets/CheckBox.cpp`) is a `wxBitmapToggleButton` (`wxBORDER_NONE`) showing 18 px SVGs -`check_{on,half,off}`, `…_disabled`, `…_focused`. It has **no label**: pair it with a `wxStaticText`/`Label` -(as `CloneDialog::CloneDialog` does). `GetValue()` is a 2-state `bool`. +`check_{on,half,off}`, `…_disabled`, `…_focused`. It has **no label**: when the label is on the right side of the +check box and belongs to it, use a `LabeledCheckBox` (§LabeledCheckBox); pair a bare `::CheckBox` with a +`wxStaticText`/`Label` only where the label sits elsewhere, such as on the left side in the label column of a form +row (as `CloneDialog::CloneDialog` does). `GetValue()` is a 2-state `bool`. - Emits `wxEVT_TOGGLEBUTTON` on click (native). `SetValue` emits nothing (`interface/wx/tglbtn.h:98`). - `SetHalfChecked(true)` is a drawn-only third state (`IsHalfChecked()` exists for the inspector only); the widget's own toggle handler clears it on any click. `SetValue` does **not** clear it — call `SetHalfChecked(false)` before showing a definite @@ -488,6 +501,94 @@ Pitfalls: cb->Bind(wxEVT_TOGGLEBUTTON, [this](wxCommandEvent& e) { e.Skip(); apply(); }); // Right ``` +## LabeledCheckBox + +`LabeledCheckBox` (`Widgets/LabeledCheckBox.cpp`, global namespace) is the check box with its own label on the +right side: a `wxPanel` holding a `::CheckBox` and, to its right, a `StaticBox` frame around a `Label`. The label +must belong to the check box, that is, name the option the box switches. Other text that only shares the row (a +value, a unit, a link, the label of the next control) is not its label, however close it sits, and stays a separate +window. The control has no other label position: a label on the left side or in a separate column stays a +`::CheckBox` paired with a label (§CheckBox and RadioBox). Constructor +`LabeledCheckBox(parent, label = "", id = wxID_ANY)`; font `Body_14`, label colour `#363636` (dark-mapped at +construction). An empty label hides the frame and leaves the bare check. + +- **Value.** `SetValue(bool)`, `GetValue()`/`IsChecked()`, `SetHalfChecked(bool = true)`. The half state is + `::CheckBox`'s: drawn only, cleared by any user toggle, not by `SetValue`. No setter emits. +- **Events.** A user toggle — a click on the check, Space on the focused check, a left click on the label or its + frame — sends `wxEVT_CHECKBOX` and then `wxEVT_TOGGLEBUTTON` from the control (`LabeledCheckBox::OnToggled`): the + control's current id (so `SetId()` after construction works), the control as event object, `IsChecked()`/`GetInt()` + = the new value. A double click on the label toggles twice (its second click arrives as `wxEVT_LEFT_DCLICK`). The + inner check's own `wxEVT_TOGGLEBUTTON` is consumed, so an ancestor bound by type gets one event of each type per + toggle. The control has no handler of its own for the two events: a handler bound on it needs no `Skip()` to keep + the bitmap right; `Skip()` only lets ancestors see the event. For a label click both events are sent from inside + the label's `wxEVT_LEFT_DOWN` handler, so a handler that opens a modal dialog defers it with `CallAfter` + (`references/windows-dialogs.md` rule 19). +- **Focus.** The inner check holds the keyboard focus; frame and label never take it, and a label click moves the + focus to the check. `HasFocus()` reports the check's focus. The frame's border is the focus indicator + (`LabeledCheckBox::ShowFocus`): `#009688` when focused, the background colour otherwise. +- **Hover.** While the pointer is on the label or its frame, the check shows its hover bitmap + (`LabeledCheckBox::ShowHover`). +- **Enable.** `Enable(bool)` disables the inner check and greys the label (`#6B6A6A`, dark-mapped); the panel itself + stays enabled. `IsEnabled()` is a non-virtual shadow that returns the check's state. A disabled control ignores + label clicks. +- **Setters go through the control.** `SetLabel`, `SetFont`, `Wrap`, `AutoWrap` and `Rescale` update the label, + re-fit the control (`Fit()`) and send the parent a size event (`LabeledCheckBox::Relayout`), so a sizer-managed + parent lays out again; a top-level window is not re-fitted. `SetForegroundColour` sets the enabled label colour, + `SetBackgroundColour` reaches check, frame and label, and a tooltip set on the control is copied to all three + (`DoSetToolTip`). `GetLabelCtrl()` returns the inner `Label`. +- **Wrapping** is `Label::Wrap` on the stored text. `Wrap(width)` wraps the text to `width` px minus the check and + the padding, so the whole control fits `width`; `width <= 0` unwraps. `AutoWrap(true)` re-wraps to the width the + control is given on every `wxEVT_SIZE`, so it needs a sizer item that gives it a width (`wxEXPAND` in a vertical + sizer, or a proportion) inside a container whose width comes from elsewhere: until the first layout the control + reports its unwrapped width. Each of the two calls cancels the other mode. With a wrapped label the check stays + centred on the first text line. +- **Metrics.** The padding around the text is `FromDIP(wxSize(5, 2))`, the padding of `RadioGroup`'s label buttons + (`RadioGroup::Create`), and both icons are 18 px: a `LabeledCheckBox` and a `RadioGroup` added with the same left + border line up icon under icon and text under text. Unlike `RadioGroup`, which puts `FromDIP(4)` above and below + each row, the control adds no outer margin; row spacing is the sizer's. +- **DPI.** `Rescale()` rescales the check and re-fits; call it from `on_dpi_changed`. +- **[source] Bitmap states on MSW.** Setting the normal bitmap of a bitmap button (`SetBitmapLabel`) deletes the + button's image data, so the bitmaps set for the other states are gone and their getters (`GetBitmapCurrent()`, …) + return a null bitmap until they are set again (`src/msw/anybutton.cpp:770-783`, `:785-796`); a null normal bitmap + then removes the image without a refresh (`:797-812`). wxGTK keeps one bitmap per state + (`src/gtk/anybutton.cpp:198-201`, `:391`). `LabeledCheckBox::ShowHover` shows the hover art by copying the check's + hover bitmap into its normal state, and therefore lets `::CheckBox` set all its bitmaps again first. + +Pitfalls: +- **Rule:** When the label is on the right side of the check box and belongs to it, use one `LabeledCheckBox`; + don't pair a `::CheckBox` with a `wxStaticText`/`Label` and forward the label's clicks by hand. + **Why:** the hand-made pair needs its own sizer, label styling, click and double-click forwarding, disabled + colour and tooltip on both windows, and still shows no focus frame on the label. + ```cpp + auto* cb = new ::CheckBox(this); // Wrong: two windows wired by hand + auto* lbl = new wxStaticText(this, wxID_ANY, _L("Don't show again")); + lbl->Bind(wxEVT_LEFT_DOWN, [cb](wxMouseEvent&) { cb->SetValue(!cb->GetValue()); /* + send the event */ }); + auto* cb = new LabeledCheckBox(this, _L("Don't show again")); // Right + ``` +- **Rule:** Bind **one** of the two events. + **Why:** both are sent for every toggle, so that a handler written for a `wxCheckBox` (`wxEVT_CHECKBOX`) or for a + `::CheckBox` (`wxEVT_TOGGLEBUTTON`) keeps working when the control replaces either; a handler bound to both runs + twice. + ```cpp + cb->Bind(wxEVT_CHECKBOX, h); cb->Bind(wxEVT_TOGGLEBUTTON, h); // Wrong: h runs twice + cb->Bind(wxEVT_CHECKBOX, [this](wxCommandEvent& e) { apply(e.IsChecked()); e.Skip(); }); // Right + ``` +- **Rule:** Change the label, font and wrap through the control, not through `GetLabelCtrl()`. + **Why:** only the control's own setters re-wrap, re-fit and notify the parent. + ```cpp + cb->GetLabelCtrl()->SetLabel(text); // Wrong: the control keeps its old size and wrap + cb->SetLabel(text); // Right + ``` +- **Rule:** Read the enabled state through a `LabeledCheckBox*`. + **Why:** `Enable()` is virtual and works through any pointer, but `IsEnabled()` is not: through a `wxWindow*` it + reports the panel, which stays enabled (`src/common/wincmn.cpp:1142-1145`). The rule of §Shared lifecycle rules + holds too: disabling an ancestor greys the inner check but not the label — call the control's `Enable()`. + ```cpp + wxWindow* w = cb; cb->Enable(false); + if (w->IsEnabled()) { /* Wrong: still true */ } + if (cb->IsEnabled()) { /* Right: false */ } + ``` + ## SwitchButton family All in `Widgets/SwitchButton.hpp/.cpp`: diff --git a/.claude/skills/orca-wxwidgets/references/sizers-layout.md b/.claude/skills/orca-wxwidgets/references/sizers-layout.md index 8f58cac3c8..16b68a3ddf 100644 --- a/.claude/skills/orca-wxwidgets/references/sizers-layout.md +++ b/.claude/skills/orca-wxwidgets/references/sizers-layout.md @@ -636,7 +636,9 @@ single-line `wxST_ELLIPSIZE_END` labels; other modes are generic (`src/msw/statt - the label needs a real width: a ctor size `wxSize(FromDIP(w), -1)`, min = max width, or `wxEXPAND` in a vertical sizer whose container width is fixed; - `Label::split_lines(dc, width, text, out, max_count)` exposes the same wrapper for owner-drawn text. -Orca's wrapping is preferred over `wxST_WRAP` for CJK text. +Orca's wrapping is preferred over `wxST_WRAP` for CJK text. A check box label wraps through +`LabeledCheckBox::Wrap(width)`/`AutoWrap()`, which also re-fit the control (`references/orca-widgets.md +§LabeledCheckBox`). **Pitfalls** - **Rule:** Re-wrapping after `SetLabel` must defeat the wrap cache. diff --git a/src/slic3r/CMakeLists.txt b/src/slic3r/CMakeLists.txt index 268b48c664..ef017ffb41 100644 --- a/src/slic3r/CMakeLists.txt +++ b/src/slic3r/CMakeLists.txt @@ -628,9 +628,11 @@ set(SLIC3R_GUI_SOURCES GUI/Widgets/ImageSwitchButton.cpp GUI/Widgets/ImageSwitchButton.hpp GUI/Widgets/Label.cpp + GUI/Widgets/Label.hpp GUI/Widgets/LabeledStaticBox.cpp GUI/Widgets/LabeledStaticBox.hpp - GUI/Widgets/Label.hpp + GUI/Widgets/LabeledCheckBox.cpp + GUI/Widgets/LabeledCheckBox.hpp GUI/Widgets/PopupWindow.cpp GUI/Widgets/PopupWindow.hpp GUI/Widgets/ProgressBar.cpp diff --git a/src/slic3r/GUI/GeometryImportDialog.cpp b/src/slic3r/GUI/GeometryImportDialog.cpp index 0f276e7028..01be417d51 100644 --- a/src/slic3r/GUI/GeometryImportDialog.cpp +++ b/src/slic3r/GUI/GeometryImportDialog.cpp @@ -19,7 +19,6 @@ #include #include #include -#include #include #include @@ -30,9 +29,9 @@ #include "MsgDialog.hpp" #include "slic3r/GUI/format.hpp" #include "Widgets/Button.hpp" -#include "Widgets/CheckBox.hpp" #include "Widgets/DialogButtons.hpp" #include "Widgets/Label.hpp" +#include "Widgets/LabeledCheckBox.hpp" #include "Widgets/RadioGroup.hpp" #include "Widgets/RoundedRectangle.hpp" #include "Widgets/StateColor.hpp" @@ -95,7 +94,7 @@ void add_tip(DPIDialog& dialog, wxBoxSizer& sizer, const wxString& text, int wra sizer.Add(frame, 0, wxEXPAND | wxLEFT | wxRIGHT | wxTOP, dialog.FromDIP(12)); } -ImportCheckBox add_checkbox(DPIDialog& dialog, wxBoxSizer& sizer, const wxString& label, bool value) +LabeledCheckBox* add_checkbox(DPIDialog& dialog, wxBoxSizer& sizer, const wxString& label, bool value) { return add_import_checkbox(&dialog, sizer, label, value, wxLEFT | wxRIGHT | wxTOP, dialog.FromDIP(12)); } @@ -221,55 +220,20 @@ GeometryImportNamePolicy geometry_import_name_policy(const AppConfig& config) return policy; } -bool ImportCheckBox::GetValue() const { return box->GetValue(); } - -void ImportCheckBox::SetValue(bool value) const { box->SetValue(value); } - -void ImportCheckBox::Enable(bool enable) const +LabeledCheckBox* add_import_checkbox(wxWindow* parent, wxSizer& sizer, const wxString& text, bool value, int flags, int border) { - box->Enable(enable); - label->Enable(enable); - // Same disabled text color as RadioGroup. - label->SetForegroundColour(enable ? StateColor::darkModeColorFor(wxColour("#363636")) : wxColour("#6B6A6A")); - label->Refresh(); -} - -void ImportCheckBox::SetToolTip(const wxString& tip) const -{ - box->SetToolTip(tip); - label->SetToolTip(tip); -} - -ImportCheckBox add_import_checkbox(wxWindow* parent, wxSizer& sizer, const wxString& text, bool value, int flags, int border) -{ - ImportCheckBox checkbox{new ::CheckBox(parent), new wxStaticText(parent, wxID_ANY, text)}; - apply_label_style(checkbox.label); - checkbox.box->SetValue(value); - ::CheckBox* box = checkbox.box; - auto toggle = [box]() { - if (!box->IsEnabled()) - return; - box->SetValue(!box->GetValue()); - wxCommandEvent event(wxEVT_TOGGLEBUTTON, box->GetId()); - event.SetEventObject(box); - box->GetEventHandler()->ProcessEvent(event); - }; - // A double click arrives as one down and one double-click event, so each toggles once. - checkbox.label->Bind(wxEVT_LEFT_DOWN, [toggle](wxMouseEvent&) { toggle(); }); - checkbox.label->Bind(wxEVT_LEFT_DCLICK, [toggle](wxMouseEvent&) { toggle(); }); - auto* row = new wxBoxSizer(wxHORIZONTAL); - row->Add(checkbox.box, 0, wxALIGN_CENTER_VERTICAL); - row->Add(checkbox.label, 0, wxALIGN_CENTER_VERTICAL | wxLEFT, parent->FromDIP(5)); - sizer.Add(row, 0, flags, border); + auto* checkbox = new LabeledCheckBox(parent, text); + checkbox->SetValue(value); + sizer.Add(checkbox, 0, flags, border); return checkbox; } // Sorting only makes sense for original names; while Keep is off it is disabled but keeps its remembered value. -void link_sort_to_keep(const ImportCheckBox& keep, const ImportCheckBox& sort) +void link_sort_to_keep(LabeledCheckBox* keep, LabeledCheckBox* sort) { - sort.Enable(keep.GetValue()); - keep.box->Bind(wxEVT_TOGGLEBUTTON, [keep, sort](wxCommandEvent& event) { - sort.Enable(keep.GetValue()); + sort->Enable(keep->GetValue()); + keep->Bind(wxEVT_CHECKBOX, [keep, sort](wxCommandEvent& event) { + sort->Enable(keep->GetValue()); event.Skip(); }); } @@ -300,15 +264,15 @@ bool show_geometry_import_options(wxWindow* parent, const std::string& format, G load_mode->SetRadioTooltip(2, _L("The original bodies and names are kept inside the object. Use Split to parts to show them as separate parts.")); sizer->Add(load_mode, 0, wxLEFT | wxRIGHT | wxTOP, dialog.FromDIP(12)); } - const auto keep = add_checkbox(dialog, *sizer, _L("Keep original names"), options.keep_names); - keep.SetToolTip(_L("Use the body names stored in the file, when there are any. When disabled, the usual OrcaSlicer names are used; existing project names are kept.")); - const auto sort = add_checkbox(dialog, *sizer, _L("Sort parts by name"), options.sort_names); - sort.SetToolTip(_L("Sort the parts inside each imported assembly in the object list. This does not change the order used for slicing. Available when Keep original names is on.")); + auto* keep = add_checkbox(dialog, *sizer, _L("Keep original names"), options.keep_names); + keep->SetToolTip(_L("Use the body names stored in the file, when there are any. When disabled, the usual OrcaSlicer names are used; existing project names are kept.")); + auto* sort = add_checkbox(dialog, *sizer, _L("Sort parts by name"), options.sort_names); + sort->SetToolTip(_L("Sort the parts inside each imported assembly in the object list. This does not change the order used for slicing. Available when Keep original names is on.")); link_sort_to_keep(keep, sort); - const auto remember = add_checkbox(dialog, *sizer, _L("Remember my choice"), false); - remember.SetToolTip(_L("Use these choices as defaults next time. The dialog still opens.")); - const auto dont_ask = add_checkbox(dialog, *sizer, _L("Don't ask again"), false); - dont_ask.SetToolTip(_L("Save these choices and apply them without asking next time. You can show this dialog again in Preferences.")); + auto* remember = add_checkbox(dialog, *sizer, _L("Remember my choice"), false); + remember->SetToolTip(_L("Use these choices as defaults next time. The dialog still opens.")); + auto* dont_ask = add_checkbox(dialog, *sizer, _L("Don't ask again"), false); + dont_ask->SetToolTip(_L("Save these choices and apply them without asking next time. You can show this dialog again in Preferences.")); auto* buttons = new DialogButtons(&dialog, {"OK", "Cancel"}); buttons->GetOK()->Bind(wxEVT_BUTTON, [&](wxCommandEvent&) { dialog.EndModal(wxID_OK); }); @@ -321,16 +285,16 @@ bool show_geometry_import_options(wxWindow* parent, const std::string& format, G if (dialog.ShowModal() != wxID_OK) return false; - options.keep_names = keep.GetValue(); - options.sort_names = sort.GetValue(); + options.keep_names = keep->GetValue(); + options.sort_names = sort->GetValue(); if (load_mode != nullptr) { options.separate_objects = load_mode->GetSelection() == 0; // Separate objects leave the remembered assembly choice as it was. if (!options.separate_objects) options.load_as_assembly = load_mode->GetSelection() == 1; } - options.remember = remember.GetValue(); - options.dont_ask = dont_ask.GetValue(); + options.remember = remember->GetValue(); + options.dont_ask = dont_ask->GetValue(); return true; } @@ -375,10 +339,10 @@ bool prepare_geometry_import_names(wxWindow* parent, const std::vector& wxTE_MULTILINE | wxTE_READONLY | wxTE_DONTWRAP); apply_label_style(preview); sizer->Add(preview, 1, wxEXPAND | wxALL, dialog.FromDIP(12)); - const auto remember = add_checkbox(dialog, *sizer, _L("Remember my choice"), false); - remember.SetToolTip(_L("Use this rule as the default next time. The dialog still opens.")); - const auto dont_ask = add_checkbox(dialog, *sizer, _L("Don't ask again"), false); - dont_ask.SetToolTip(_L("Save this rule and apply it without asking next time. You can show this dialog again in Preferences.")); + auto* remember = add_checkbox(dialog, *sizer, _L("Remember my choice"), false); + remember->SetToolTip(_L("Use this rule as the default next time. The dialog still opens.")); + auto* dont_ask = add_checkbox(dialog, *sizer, _L("Don't ask again"), false); + dont_ask->SetToolTip(_L("Save this rule and apply it without asking next time. You can show this dialog again in Preferences.")); auto* buttons = new DialogButtons(&dialog, {"OK", "Cancel"}); auto update_preview = [&]() { @@ -415,8 +379,8 @@ bool prepare_geometry_import_names(wxWindow* parent, const std::vector& return false; policy.remove = rule->GetSelection() == 0; policy.replacement = into_u8(replacement->GetTextCtrl()->GetValue()); - policy.remember = remember.GetValue(); - policy.dont_ask = dont_ask.GetValue(); + policy.remember = remember->GetValue(); + policy.dont_ask = dont_ask->GetValue(); } const auto results = cleaned_groups(groups, policy.remove ? std::string() : policy.replacement); diff --git a/src/slic3r/GUI/GeometryImportDialog.hpp b/src/slic3r/GUI/GeometryImportDialog.hpp index 7623e7e981..be0d96b713 100644 --- a/src/slic3r/GUI/GeometryImportDialog.hpp +++ b/src/slic3r/GUI/GeometryImportDialog.hpp @@ -3,9 +3,8 @@ #include #include -class CheckBox; +class LabeledCheckBox; class wxSizer; -class wxStaticText; class wxString; class wxWindow; @@ -49,20 +48,10 @@ bool is_geometry_only_3mf(const std::string& path); GeometryImportOptions geometry_import_options(const AppConfig& config, const std::string& format); GeometryImportNamePolicy geometry_import_name_policy(const AppConfig& config); bool show_geometry_import_options(wxWindow* parent, const std::string& format, GeometryImportOptions& options); -// App-styled check box with its label, shared by the import dialogs. -struct ImportCheckBox { - ::CheckBox* box = nullptr; - wxStaticText* label = nullptr; - bool GetValue() const; - void SetValue(bool value) const; - // Greys the label too and stops it toggling the box. - void Enable(bool enable) const; - void SetToolTip(const wxString& tip) const; -}; -// A click on the label toggles the box and sends its wxEVT_TOGGLEBUTTON, as a click on the box does. -ImportCheckBox add_import_checkbox(wxWindow* parent, wxSizer& sizer, const wxString& text, bool value, int flags, int border); +// Check box with its label, shared by the import dialogs. +LabeledCheckBox* add_import_checkbox(wxWindow* parent, wxSizer& sizer, const wxString& text, bool value, int flags, int border); // Sorting is offered only together with Keep original names; shared by the STEP dialog. -void link_sort_to_keep(const ImportCheckBox& keep, const ImportCheckBox& sort); +void link_sort_to_keep(LabeledCheckBox* keep, LabeledCheckBox* sort); bool prepare_geometry_import_names(wxWindow* parent, const std::vector& models, GeometryImportNamePolicy& policy); void save_geometry_import_options(AppConfig& config, const std::string& format, const GeometryImportOptions& options); void save_geometry_import_name_policy(AppConfig& config, const GeometryImportNamePolicy& policy); diff --git a/src/slic3r/GUI/MixedFilamentDialog.cpp b/src/slic3r/GUI/MixedFilamentDialog.cpp index d15d14c74d..eb0421ad5e 100644 --- a/src/slic3r/GUI/MixedFilamentDialog.cpp +++ b/src/slic3r/GUI/MixedFilamentDialog.cpp @@ -32,7 +32,6 @@ #include #include #include -#include #include #include @@ -45,7 +44,7 @@ #include "FilamentBitmapUtils.hpp" #include "wxExtensions.hpp" #include "Widgets/Button.hpp" -#include "Widgets/CheckBox.hpp" +#include "Widgets/LabeledCheckBox.hpp" #include "Widgets/ComboBox.hpp" #include "Widgets/DropDown.hpp" #include "Widgets/Label.hpp" @@ -1070,14 +1069,10 @@ wxBoxSizer* MixedFilamentDialog::create_gradient_section() { m_gradient_sizer = new wxBoxSizer(wxHORIZONTAL); - m_chk_gradient = new ::CheckBox(this); + m_chk_gradient = new LabeledCheckBox(this, _L("Gradient Effect")); m_chk_gradient->SetValue(m_result.gradient_enabled); - m_chk_gradient->Bind(wxEVT_TOGGLEBUTTON, [this](wxCommandEvent& e) { e.Skip(); on_gradient_toggled(); }); - m_gradient_sizer->Add(m_chk_gradient, 0, wxALIGN_CENTER_VERTICAL | wxTOP | wxBOTTOM, FromDIP(4)); - - m_label_gradient = new wxStaticText(this, wxID_ANY, _L("Gradient Effect")); - m_label_gradient->SetFont(::Label::Body_13); - m_gradient_sizer->Add(m_label_gradient, 0, wxALIGN_CENTER_VERTICAL | wxLEFT, FromDIP(8)); + m_chk_gradient->Bind(wxEVT_CHECKBOX, [this](wxCommandEvent& e) { e.Skip(); on_gradient_toggled(); }); + m_gradient_sizer->Add(m_chk_gradient, 0, wxALIGN_CENTER_VERTICAL | wxTOP | wxBOTTOM, FromDIP(2)); m_combo_gradient_dir = new ComboBox(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(FromDIP(152), FromDIP(24)), 0, nullptr, wxCB_READONLY); @@ -1111,17 +1106,12 @@ wxBoxSizer* MixedFilamentDialog::create_gradient_section() // Per-part gradient toggle sits BELOW the curve editor. m_per_part_gradient_sizer = new wxBoxSizer(wxHORIZONTAL); - m_chk_per_part_gradient = new ::CheckBox(this); + m_chk_per_part_gradient = new LabeledCheckBox(this, _L("Enable per-part gradient effect")); m_chk_per_part_gradient->SetValue(m_result.per_part_gradient); - m_chk_per_part_gradient->Bind(wxEVT_TOGGLEBUTTON, + m_chk_per_part_gradient->Bind(wxEVT_CHECKBOX, [this](wxCommandEvent& e) { e.Skip(); on_per_part_gradient_toggled(); }); m_per_part_gradient_sizer->Add(m_chk_per_part_gradient, 0, - wxALIGN_CENTER_VERTICAL | wxTOP | wxBOTTOM, FromDIP(4)); - - m_label_per_part_gradient = new wxStaticText(this, wxID_ANY, _L("Enable per-part gradient effect")); - m_label_per_part_gradient->SetFont(::Label::Body_13); - m_per_part_gradient_sizer->Add(m_label_per_part_gradient, 0, - wxALIGN_CENTER_VERTICAL | wxLEFT, FromDIP(8)); + wxALIGN_CENTER_VERTICAL | wxTOP | wxBOTTOM, FromDIP(2)); outer->Add(m_per_part_gradient_sizer, 0, wxEXPAND | wxTOP, FromDIP(2)); m_per_part_gradient_sizer->ShowItems(m_result.gradient_enabled); @@ -1803,7 +1793,6 @@ void MixedFilamentDialog::update_component_count_ui() if (m_gradient_sizer) { bool show_gradient = is_two; m_chk_gradient->Show(show_gradient); - if (m_label_gradient) m_label_gradient->Show(show_gradient); m_combo_gradient_dir->Show(show_gradient && m_result.gradient_enabled); if (m_per_part_gradient_sizer) m_per_part_gradient_sizer->ShowItems(show_gradient && m_result.gradient_enabled); diff --git a/src/slic3r/GUI/MixedFilamentDialog.hpp b/src/slic3r/GUI/MixedFilamentDialog.hpp index 7d275a5c74..1e60b7c663 100644 --- a/src/slic3r/GUI/MixedFilamentDialog.hpp +++ b/src/slic3r/GUI/MixedFilamentDialog.hpp @@ -20,7 +20,7 @@ #include "libslic3r/FilamentMixer.hpp" class Button; -class CheckBox; +class LabeledCheckBox; class ComboBox; class wxMouseEvent; class wxScrolledWindow; @@ -142,14 +142,12 @@ private: RatioLabelPanel* m_label_ratio_b{nullptr}; wxPanel* m_ratio_editor_panel{nullptr}; wxTextCtrl* m_ratio_editor{nullptr}; - CheckBox* m_chk_gradient{nullptr}; - wxStaticText* m_label_gradient{nullptr}; + LabeledCheckBox* m_chk_gradient{nullptr}; ComboBox* m_combo_gradient_dir{nullptr}; wxBoxSizer* m_gradient_sizer{nullptr}; GradientCurveEditor* m_curve_editor{nullptr}; wxBoxSizer* m_curve_sizer{nullptr}; - CheckBox* m_chk_per_part_gradient{nullptr}; - wxStaticText* m_label_per_part_gradient{nullptr}; + LabeledCheckBox* m_chk_per_part_gradient{nullptr}; wxBoxSizer* m_per_part_gradient_sizer{nullptr}; Button* m_btn_add_material{nullptr}; Button* m_btn_remove_material{nullptr}; diff --git a/src/slic3r/GUI/MsgDialog.cpp b/src/slic3r/GUI/MsgDialog.cpp index db41c7adec..34e0983402 100644 --- a/src/slic3r/GUI/MsgDialog.cpp +++ b/src/slic3r/GUI/MsgDialog.cpp @@ -5,7 +5,7 @@ #include #include #include -#include "slic3r/GUI/Widgets/CheckBox.hpp" +#include "slic3r/GUI/Widgets/LabeledCheckBox.hpp" #include "slic3r/GUI/ReleaseNote.hpp" #include "slic3r/GUI/Widgets/StateColor.hpp" #include "slic3r/GUI/Widgets/Button.hpp" @@ -40,7 +40,6 @@ #include #include #include -#include #include #include @@ -110,30 +109,18 @@ MsgDialog::MsgDialog(wxWindow *parent, const wxString &title, const wxString &he void MsgDialog::show_dsa_button(wxString const &title) { - m_checkbox_dsa = new CheckBox(this); - m_dsa_sizer->Add(m_checkbox_dsa, 0, wxALIGN_CENTER); - m_checkbox_dsa->Bind(wxEVT_TOGGLEBUTTON, [this](wxCommandEvent& e) { + m_checkbox_dsa = new LabeledCheckBox(this, title.IsEmpty() ? _L("Don't show again") : title); + m_checkbox_dsa->SetFont(::Label::Body_13); + m_checkbox_dsa->SetForegroundColour(StateColor::darkModeColorFor(wxColour("#323A3D"))); + m_checkbox_dsa->Bind(wxEVT_CHECKBOX, [this](wxCommandEvent& e) { auto event = wxCommandEvent(EVT_CHECKBOX_CHANGE); - event.SetInt(m_checkbox_dsa->GetValue()?1:0); + event.SetInt(e.IsChecked() ? 1 : 0); event.SetEventObject(this); wxPostEvent(this, event); e.Skip(); }); - - auto m_text_dsa = new wxStaticText(this, wxID_ANY, title.IsEmpty() ? _L("Don't show again") : title, wxDefaultPosition, wxDefaultSize, 0); - auto on_toggle = [this]() { - m_checkbox_dsa->SetValue(!m_checkbox_dsa->GetValue()); - wxCommandEvent ev(wxEVT_TOGGLEBUTTON, m_checkbox_dsa->GetId()); - ev.SetEventObject(m_checkbox_dsa); - m_checkbox_dsa->GetEventHandler()->ProcessEvent(ev); - }; - m_text_dsa->Bind(wxEVT_LEFT_DOWN, [on_toggle](wxMouseEvent& e) {if(!e.LeftDClick()) on_toggle();}); - m_text_dsa->Bind(wxEVT_LEFT_DCLICK, [on_toggle](wxMouseEvent& e) {on_toggle();}); - - m_dsa_sizer->Add(m_text_dsa, 0, wxALL | wxALIGN_CENTER, FromDIP(2)); + m_dsa_sizer->Add(m_checkbox_dsa, 0, wxALIGN_CENTER); m_dsa_sizer->AddSpacer(FromDIP(10)); // spacing after checkbox - m_text_dsa->SetFont(::Label::Body_13); - m_text_dsa->SetForegroundColour(StateColor::darkModeColorFor(wxColour("#323A3D"))); btn_sizer->Layout(); Fit(); } @@ -830,17 +817,9 @@ NetworkErrorDialog::NetworkErrorDialog(wxWindow* parent) wxBoxSizer* sizer_button = new wxBoxSizer(wxHORIZONTAL); /*dont show again*/ - auto checkbox = new ::CheckBox(this); - checkbox->SetValue(false); - - - auto checkbox_title = new Label(this, _L("Don't show this dialog again")); - checkbox_title->SetForegroundColour(0x323A3C); - checkbox_title->SetFont(::Label::Body_14); - checkbox_title->Wrap(-1); - - checkbox->Bind(wxEVT_TOGGLEBUTTON, [this, checkbox](wxCommandEvent &e) { - m_show_again = checkbox->GetValue(); + auto checkbox = new LabeledCheckBox(this, _L("Don't show this dialog again")); + checkbox->Bind(wxEVT_CHECKBOX, [this](wxCommandEvent &e) { + m_show_again = e.IsChecked(); e.Skip(); }); @@ -848,8 +827,7 @@ NetworkErrorDialog::NetworkErrorDialog(wxWindow* parent) m_button_confirm->SetStyle(ButtonStyle::Confirm, ButtonType::Choice); m_button_confirm->Bind(wxEVT_LEFT_DOWN, [this](auto& e) {EndModal(wxCLOSE);}); - sizer_button->Add(checkbox, 0, wxALL, 5); - sizer_button->Add(checkbox_title, 0, wxALL, 5); + sizer_button->Add(checkbox, 0, wxALL | wxALIGN_CENTER_VERTICAL, 5); sizer_button->Add(0, 0, 1, wxEXPAND, 5); sizer_button->Add(m_button_confirm, 0, wxALL, FromDIP(ButtonProps::ChoiceButtonGap())); diff --git a/src/slic3r/GUI/MsgDialog.hpp b/src/slic3r/GUI/MsgDialog.hpp index 21ad283d0a..63c08ad2de 100644 --- a/src/slic3r/GUI/MsgDialog.hpp +++ b/src/slic3r/GUI/MsgDialog.hpp @@ -21,7 +21,7 @@ #include #include #include "Widgets/Button.hpp" -#include "Widgets/CheckBox.hpp" +#include "Widgets/LabeledCheckBox.hpp" #include "Widgets/TextInput.hpp" #include "Widgets/HyperLink.hpp" #include "BBLStatusBar.hpp" @@ -106,7 +106,7 @@ protected: wxBoxSizer *m_dsa_sizer; wxStaticBitmap *logo; MsgButtonsHash m_buttons; - CheckBox* m_checkbox_dsa{nullptr}; + LabeledCheckBox* m_checkbox_dsa{nullptr}; wxString m_forward_str; }; diff --git a/src/slic3r/GUI/PrimitiveSizeDialog.cpp b/src/slic3r/GUI/PrimitiveSizeDialog.cpp index fbd19cc81d..0827fd7d15 100644 --- a/src/slic3r/GUI/PrimitiveSizeDialog.cpp +++ b/src/slic3r/GUI/PrimitiveSizeDialog.cpp @@ -7,9 +7,9 @@ #include "MainFrame.hpp" #include "MsgDialog.hpp" #include "Widgets/Button.hpp" -#include "Widgets/CheckBox.hpp" #include "Widgets/DialogButtons.hpp" #include "Widgets/Label.hpp" +#include "Widgets/LabeledCheckBox.hpp" #include "Widgets/TextInput.hpp" #include "libslic3r/LocalesUtils.hpp" @@ -99,20 +99,11 @@ bool PrimitiveSizeDialog::save_as_default() const { return m_save_default->GetVa bool PrimitiveSizeDialog::dont_show_again() const { return m_dont_show->GetValue(); } -::CheckBox* PrimitiveSizeDialog::add_checkbox(wxSizer* sizer, const wxString& label, const wxString& tooltip) +LabeledCheckBox* PrimitiveSizeDialog::add_checkbox(wxSizer* sizer, const wxString& label, const wxString& tooltip) { - auto checkbox = new ::CheckBox(this); - auto text = new wxStaticText(this, wxID_ANY, label); + auto checkbox = new LabeledCheckBox(this, label); checkbox->SetToolTip(tooltip); - text->SetToolTip(tooltip); - auto toggle = [checkbox](wxMouseEvent&) { checkbox->SetValue(!checkbox->GetValue()); }; - text->Bind(wxEVT_LEFT_DOWN, toggle); - text->Bind(wxEVT_LEFT_DCLICK, toggle); - - auto row = new wxBoxSizer(wxHORIZONTAL); - row->Add(checkbox, 0, wxALIGN_CENTER_VERTICAL); - row->Add(text, 0, wxALIGN_CENTER_VERTICAL | wxLEFT, FromDIP(5)); - sizer->Add(row, 0, wxLEFT | wxRIGHT | wxBOTTOM, FromDIP(10)); + sizer->Add(checkbox, 0, wxLEFT | wxRIGHT | wxBOTTOM, FromDIP(10)); return checkbox; } diff --git a/src/slic3r/GUI/PrimitiveSizeDialog.hpp b/src/slic3r/GUI/PrimitiveSizeDialog.hpp index 8d41a80e4a..a685f5decb 100644 --- a/src/slic3r/GUI/PrimitiveSizeDialog.hpp +++ b/src/slic3r/GUI/PrimitiveSizeDialog.hpp @@ -7,7 +7,7 @@ #include #include -class CheckBox; +class LabeledCheckBox; class TextInput; class wxSizer; class wxWindow; @@ -34,16 +34,16 @@ protected: void on_dpi_changed(const wxRect& suggested_rect) override; private: - ::CheckBox* add_checkbox(wxSizer* sizer, const wxString& label, const wxString& tooltip); + LabeledCheckBox* add_checkbox(wxSizer* sizer, const wxString& label, const wxString& tooltip); void on_input_changed(size_t idx); bool read_values(); std::vector<::TextInput*> m_inputs; // The last valid value of each input, which uniform scaling multiplies. std::vector m_last_values; - ::CheckBox* m_uniform_scale{nullptr}; - ::CheckBox* m_save_default{nullptr}; - ::CheckBox* m_dont_show{nullptr}; + LabeledCheckBox* m_uniform_scale{nullptr}; + LabeledCheckBox* m_save_default{nullptr}; + LabeledCheckBox* m_dont_show{nullptr}; std::vector m_values; }; diff --git a/src/slic3r/GUI/ReleaseNote.cpp b/src/slic3r/GUI/ReleaseNote.cpp index f8845443a2..98ed958a26 100644 --- a/src/slic3r/GUI/ReleaseNote.cpp +++ b/src/slic3r/GUI/ReleaseNote.cpp @@ -23,7 +23,7 @@ #include #include #include "slic3r/GUI/Widgets/HyperLink.hpp" -#include "slic3r/GUI/Widgets/CheckBox.hpp" +#include "slic3r/GUI/Widgets/LabeledCheckBox.hpp" #include #include #include @@ -54,7 +54,6 @@ #include #include #include -#include #include #include #include "Plater.hpp" @@ -382,16 +381,14 @@ UpdateVersionDialog::UpdateVersionDialog(wxWindow *parent) EndModal(wxID_NO); }); - m_cb_stable_only = new CheckBox(this); + m_cb_stable_only = new LabeledCheckBox(this, _L("Check for stable updates only")); + m_cb_stable_only->SetFont(Label::Body_12); m_cb_stable_only->SetValue(wxGetApp().app_config->get_bool("check_stable_update_only")); - m_cb_stable_only->Bind(wxEVT_TOGGLEBUTTON, [this](wxCommandEvent& e) { + m_cb_stable_only->Bind(wxEVT_CHECKBOX, [this](wxCommandEvent& e) { wxGetApp().app_config->set_bool("check_stable_update_only", m_cb_stable_only->GetValue()); e.Skip(); }); - auto stable_only_label = new Label(this, _L("Check for stable updates only")); - stable_only_label->SetFont(Label::Body_12); - m_button_cancel = new Button(this, _L("Cancel")); m_button_cancel->SetStyle(ButtonStyle::Regular, ButtonType::Choice); @@ -402,7 +399,6 @@ UpdateVersionDialog::UpdateVersionDialog(wxWindow *parent) //sizer_button->Add(m_remind_choice, 0, wxALL | wxEXPAND, FromDIP(5)); sizer_button->Add(m_cb_stable_only , 0, wxALIGN_CENTER); - sizer_button->Add(stable_only_label , 0, wxALIGN_CENTER | wxLEFT, FromDIP(5)); sizer_button->AddStretchSpacer(); sizer_button->Add(m_button_download , 0, wxLEFT, FromDIP(10)); sizer_button->Add(m_button_skip_version, 0, wxLEFT, FromDIP(10)); @@ -600,8 +596,8 @@ SecondaryCheckDialog::SecondaryCheckDialog(wxWindow* parent, wxWindowID id, cons if (not_show_again_check) { auto checkbox_sizer = new wxBoxSizer(wxHORIZONTAL); - m_show_again_checkbox = new wxCheckBox(this, wxID_ANY, _L("Don't show again"), wxDefaultPosition, wxDefaultSize, 0); - m_show_again_checkbox->Bind(wxEVT_COMMAND_CHECKBOX_CLICKED, [this](wxCommandEvent& e) { + m_show_again_checkbox = new LabeledCheckBox(this, _L("Don't show again")); + m_show_again_checkbox->Bind(wxEVT_CHECKBOX, [this](wxCommandEvent& e) { not_show_again = !not_show_again; m_show_again_checkbox->SetValue(not_show_again); }); @@ -1184,8 +1180,8 @@ ConfirmBeforeSendDialog::ConfirmBeforeSendDialog(wxWindow* parent, wxWindowID id if (not_show_again_check) { auto checkbox_sizer = new wxBoxSizer(wxHORIZONTAL); - m_show_again_checkbox = new wxCheckBox(this, wxID_ANY, _L("Don't show again"), wxDefaultPosition, wxDefaultSize, 0); - m_show_again_checkbox->Bind(wxEVT_COMMAND_CHECKBOX_CLICKED, [this](wxCommandEvent& e) { + m_show_again_checkbox = new LabeledCheckBox(this, _L("Don't show again")); + m_show_again_checkbox->Bind(wxEVT_CHECKBOX, [this](wxCommandEvent& e) { not_show_again = !not_show_again; m_show_again_checkbox->SetValue(not_show_again); }); diff --git a/src/slic3r/GUI/ReleaseNote.hpp b/src/slic3r/GUI/ReleaseNote.hpp index 71159feada..f78bcc274a 100644 --- a/src/slic3r/GUI/ReleaseNote.hpp +++ b/src/slic3r/GUI/ReleaseNote.hpp @@ -41,7 +41,7 @@ #include "DeviceManager.hpp" #include "Widgets/Label.hpp" #include "Widgets/Button.hpp" -#include "Widgets/CheckBox.hpp" +#include "Widgets/LabeledCheckBox.hpp" #include "Widgets/ComboBox.hpp" #include "Widgets/ScrolledWindow.hpp" #include "Widgets/HyperLink.hpp" @@ -113,7 +113,7 @@ public: Label * m_staticText_release_note{nullptr}; wxStaticBitmap* m_bitmap_open_in_browser; Button* m_button_skip_version; - CheckBox* m_cb_stable_only; + LabeledCheckBox* m_cb_stable_only; Button* m_button_download; Button* m_button_cancel; std::string url_line; @@ -166,7 +166,7 @@ public: Button* m_button_cancel { nullptr }; Button* m_button_fn { nullptr }; Button* m_button_resume { nullptr }; - wxCheckBox* m_show_again_checkbox; + LabeledCheckBox* m_show_again_checkbox; VisibleButtons m_button_style; // ORCA VisibleButtons instead ButtonStyle bool not_show_again = false; std::string show_again_config_text = ""; @@ -291,7 +291,7 @@ protected: Button* m_button_ok; Button* m_button_cancel; Button* m_button_update_nozzle; - wxCheckBox* m_show_again_checkbox; + LabeledCheckBox* m_show_again_checkbox; bool not_show_again = false; std::string show_again_config_text = ""; }; diff --git a/src/slic3r/GUI/SavePresetDialog.cpp b/src/slic3r/GUI/SavePresetDialog.cpp index 46d7088749..cf36428b66 100644 --- a/src/slic3r/GUI/SavePresetDialog.cpp +++ b/src/slic3r/GUI/SavePresetDialog.cpp @@ -11,7 +11,7 @@ #include #include "slic3r/GUI/Widgets/RadioGroup.hpp" #include "libslic3r/Config.hpp" -#include "slic3r/GUI/Widgets/CheckBox.hpp" +#include "slic3r/GUI/Widgets/LabeledCheckBox.hpp" #include #include "slic3r/GUI/wxExtensions.hpp" #include "slic3r/GUI/GUI_Utils.hpp" @@ -143,21 +143,9 @@ SavePresetDialog::Item::Item(Preset::Type type, const std::string &suffix, wxBox const std::string parent_name = sel_preset.is_system ? sel_preset.name : sel_preset.inherits(); const bool has_parent = !parent_name.empty(); - wxBoxSizer *detach_sizer = new wxBoxSizer(wxHORIZONTAL); - - auto detach_tooltip = _L("Copies all inherited values from the parent into this preset and removes the parent relationship. Presets compatible only with the parent may become unsupported."); - - auto detach_checkbox = new ::CheckBox(parent); - detach_checkbox->SetToolTip(detach_tooltip); - - auto detach_label = new wxStaticText(parent, wxID_ANY, has_parent ? _L("Detach from parent") : _L("Save without parent")); - detach_label->SetFont(::Label::Body_14); - detach_label->SetForegroundColour(wxColour("#363636")); - detach_label->SetToolTip(detach_tooltip); - - detach_sizer->Add(detach_checkbox, 0, wxALIGN_LEFT | wxLEFT, BORDER_W); - detach_sizer->Add(detach_label , 0, wxALIGN_CENTRE_VERTICAL | wxLEFT, FromDIP(5)); - sizer->Add(detach_sizer, 0, wxEXPAND | wxTOP, BORDER_W); + auto detach_checkbox = new LabeledCheckBox(parent, has_parent ? _L("Detach from parent") : _L("Save without parent")); + detach_checkbox->SetToolTip(_L("Copies all inherited values from the parent into this preset and removes the parent relationship. Presets compatible only with the parent may become unsupported.")); + sizer->Add(detach_checkbox, 0, wxTOP | wxLEFT, BORDER_W); sizer->AddSpacer(FromDIP(5)); const wxString parent_text = has_parent ? from_u8(parent_name) : _L("Unique preset"); @@ -172,19 +160,10 @@ SavePresetDialog::Item::Item(Preset::Type type, const std::string &suffix, wxBox // Set initial state (unchecked by default) detach_checkbox->SetValue(m_detach); // Bind the checkbox event to update the detach state for this item - detach_checkbox->Bind(wxEVT_TOGGLEBUTTON, [this, detach_checkbox](wxCommandEvent& event) { - m_detach = detach_checkbox->GetValue(); - event.Skip(); // Let CheckBox update its bitmap for the new state. + detach_checkbox->Bind(wxEVT_CHECKBOX, [this](wxCommandEvent& event) { + m_detach = event.IsChecked(); + event.Skip(); }); - - auto on_toggle = [detach_checkbox]() { - detach_checkbox->SetValue(!detach_checkbox->GetValue()); - wxCommandEvent ev(wxEVT_TOGGLEBUTTON, detach_checkbox->GetId()); - ev.SetEventObject(detach_checkbox); - detach_checkbox->GetEventHandler()->ProcessEvent(ev); - }; - detach_label->Bind(wxEVT_LEFT_DOWN, [on_toggle](wxMouseEvent& e) {if(!e.LeftDClick()) on_toggle();}); - detach_label->Bind(wxEVT_LEFT_DCLICK, [on_toggle](wxMouseEvent& e) {on_toggle();}); } m_radio_group->Bind(wxEVT_COMMAND_RADIOBOX_SELECTED, [this](wxCommandEvent &e) { diff --git a/src/slic3r/GUI/StepMeshDialog.cpp b/src/slic3r/GUI/StepMeshDialog.cpp index 0841777a43..109bdbb4db 100644 --- a/src/slic3r/GUI/StepMeshDialog.cpp +++ b/src/slic3r/GUI/StepMeshDialog.cpp @@ -15,7 +15,6 @@ #include #include #include -#include #include #include "GUI_App.hpp" #include "I18N.hpp" @@ -259,33 +258,33 @@ StepMeshDialog::StepMeshDialog(wxWindow* parent, Slic3r::Step& file, double line bSizer->Add(angle_sizer, 0, wxEXPAND | wxLEFT | wxRIGHT, LEFT_RIGHT_PADING); - // App-styled check boxes, the same as in the AMF and 3MF import dialogs. + // Same check boxes as in the AMF and 3MF import dialogs. m_split_compound_checkbox = add_import_checkbox(this, *bSizer, _L("Split compound and compsolid into multiple objects"), wxGetApp().app_config->get_bool("is_split_compound"), wxLEFT | wxRIGHT | wxTOP, LEFT_RIGHT_PADING); if (m_import_options != nullptr) { - m_split_compound_checkbox.SetToolTip(_L("Loads each body of a multi-body part separately. Needed to keep the bodies' original names.")); - m_split_compound_checkbox.SetValue(m_import_options->split_compound); + m_split_compound_checkbox->SetToolTip(_L("Loads each body of a multi-body part separately. Needed to keep the bodies' original names.")); + m_split_compound_checkbox->SetValue(m_import_options->split_compound); m_load_mode = new RadioGroup(this, {_L("Load as an assembly"), _L("Load as a single object (can be split later)")}, wxVERTICAL); m_load_mode->SetSelection(m_import_options->load_as_assembly ? 0 : 1); m_load_mode->SetRadioTooltip(1, _L("The original bodies and names are kept inside the object. Use Split to parts to show them as separate parts.")); bSizer->Add(m_load_mode, 0, wxLEFT | wxRIGHT | wxTOP, LEFT_RIGHT_PADING); m_keep_names_checkbox = add_import_checkbox(this, *bSizer, _L("Keep original names"), m_import_options->keep_names, wxLEFT | wxRIGHT | wxTOP, LEFT_RIGHT_PADING); - m_keep_names_checkbox.SetToolTip(_L("Use the body names stored in the file, when there are any. Needs Split compound for parts with several bodies.")); + m_keep_names_checkbox->SetToolTip(_L("Use the body names stored in the file, when there are any. Needs Split compound for parts with several bodies.")); m_sort_names_checkbox = add_import_checkbox(this, *bSizer, _L("Sort parts by name"), m_import_options->sort_names, wxLEFT | wxRIGHT | wxTOP, LEFT_RIGHT_PADING); - m_sort_names_checkbox.SetToolTip(_L("Sort the parts inside each imported assembly in the object list. This does not change the order used for slicing. Available when Keep original names is on.")); + m_sort_names_checkbox->SetToolTip(_L("Sort the parts inside each imported assembly in the object list. This does not change the order used for slicing. Available when Keep original names is on.")); // The dialog opens with the remembered values; only the user's clicks move the linked option. - m_keep_names_checkbox.box->Bind(wxEVT_TOGGLEBUTTON, [this](wxCommandEvent& e) { + m_keep_names_checkbox->Bind(wxEVT_CHECKBOX, [this](wxCommandEvent& e) { // Body names of a multi-body part exist only after splitting it. - if (m_keep_names_checkbox.GetValue()) - m_split_compound_checkbox.SetValue(true); + if (m_keep_names_checkbox->GetValue()) + m_split_compound_checkbox->SetValue(true); e.Skip(); }); - m_split_compound_checkbox.box->Bind(wxEVT_TOGGLEBUTTON, [this](wxCommandEvent& e) { - if (!m_split_compound_checkbox.GetValue() && m_keep_names_checkbox.GetValue()) { - m_keep_names_checkbox.SetValue(false); - m_sort_names_checkbox.Enable(false); + m_split_compound_checkbox->Bind(wxEVT_CHECKBOX, [this](wxCommandEvent& e) { + if (!m_split_compound_checkbox->GetValue() && m_keep_names_checkbox->GetValue()) { + m_keep_names_checkbox->SetValue(false); + m_sort_names_checkbox->Enable(false); } e.Skip(); }); @@ -307,14 +306,14 @@ StepMeshDialog::StepMeshDialog(wxWindow* parent, Slic3r::Step& file, double line m_save_default_checkbox = add_import_checkbox(this, *bSizer, m_import_options ? _L("Remember my choice") : _L("Save these settings as default"), false, wxLEFT | wxRIGHT, LEFT_RIGHT_PADING); - m_save_default_checkbox.SetToolTip(_L("If enabled, the values above are stored as the defaults used for future STEP imports (and shown in Preferences).")); + m_save_default_checkbox->SetToolTip(_L("If enabled, the values above are stored as the defaults used for future STEP imports (and shown in Preferences).")); bSizer->AddSpacer(FromDIP(10)); m_checkbox = add_import_checkbox(this, *bSizer, m_import_options ? _L("Don't ask again") : _L("Don't show again"), false, wxLEFT, LEFT_RIGHT_PADING); if (m_import_options != nullptr) - m_checkbox.SetToolTip(_L("Save these choices and apply them without asking next time. You can show this dialog again in Preferences.")); + m_checkbox->SetToolTip(_L("Save these choices and apply them without asking next time. You can show this dialog again in Preferences.")); wxBoxSizer* bSizer_button = new wxBoxSizer(wxHORIZONTAL); @@ -339,21 +338,21 @@ StepMeshDialog::StepMeshDialog(wxWindow* parent, Slic3r::Step& file, double line validate_number_range(linear_input->GetTextCtrl()->GetValue(), 0.001, 0.1)) { if (m_import_options != nullptr) { // The callback uses these values now; AppConfig is updated only after batch success. - m_import_options->keep_names = m_keep_names_checkbox.GetValue(); - m_import_options->split_compound = m_split_compound_checkbox.GetValue(); - m_import_options->sort_names = m_sort_names_checkbox.GetValue(); + m_import_options->keep_names = m_keep_names_checkbox->GetValue(); + m_import_options->split_compound = m_split_compound_checkbox->GetValue(); + m_import_options->sort_names = m_sort_names_checkbox->GetValue(); m_import_options->load_as_assembly = m_load_mode->GetSelection() == 0; - m_import_options->remember = m_save_default_checkbox.GetValue(); - m_import_options->dont_ask = m_checkbox.GetValue(); + m_import_options->remember = m_save_default_checkbox->GetValue(); + m_import_options->dont_ask = m_checkbox->GetValue(); m_import_options->linear_deflection = get_linear_deflection(); m_import_options->angle_deflection = get_angle_deflection(); m_import_options->chosen = true; } else { - if (m_checkbox.GetValue()) { + if (m_checkbox->GetValue()) { wxGetApp().app_config->set_bool("enable_step_mesh_setting", false); } - if (m_save_default_checkbox.GetValue()) { - wxGetApp().app_config->set_bool("is_split_compound", m_split_compound_checkbox.GetValue()); + if (m_save_default_checkbox->GetValue()) { + wxGetApp().app_config->set_bool("is_split_compound", m_split_compound_checkbox->GetValue()); wxGetApp().app_config->set("linear_deflection", float_to_string_decimal_point(get_linear_deflection(), 3)); wxGetApp().app_config->set("angle_deflection", float_to_string_decimal_point(get_angle_deflection(), 2)); } diff --git a/src/slic3r/GUI/StepMeshDialog.hpp b/src/slic3r/GUI/StepMeshDialog.hpp index ce5b95f022..2cb7ae0108 100644 --- a/src/slic3r/GUI/StepMeshDialog.hpp +++ b/src/slic3r/GUI/StepMeshDialog.hpp @@ -7,6 +7,7 @@ #include "GUI_Utils.hpp" #include "libslic3r/Format/STEP.hpp" #include "Widgets/Button.hpp" +#include "Widgets/LabeledCheckBox.hpp" #include "GeometryImportDialog.hpp" class Button; class RadioGroup; @@ -35,19 +36,19 @@ public: } } inline bool get_split_compound_value() { - return m_split_compound_checkbox.GetValue(); + return m_split_compound_checkbox->GetValue(); } private: // A non-null context defers all preference writes until the whole import is ready. Slic3r::GUI::GeometryImportOptions* m_import_options = nullptr; - Slic3r::GUI::ImportCheckBox m_keep_names_checkbox; - Slic3r::GUI::ImportCheckBox m_sort_names_checkbox; + LabeledCheckBox* m_keep_names_checkbox = nullptr; + LabeledCheckBox* m_sort_names_checkbox = nullptr; // Item 0 loads as an assembly, item 1 as a single object. RadioGroup* m_load_mode = nullptr; Slic3r::Step& m_file; - Slic3r::GUI::ImportCheckBox m_checkbox; - Slic3r::GUI::ImportCheckBox m_split_compound_checkbox; - Slic3r::GUI::ImportCheckBox m_save_default_checkbox; + LabeledCheckBox* m_checkbox = nullptr; + LabeledCheckBox* m_split_compound_checkbox = nullptr; + LabeledCheckBox* m_save_default_checkbox = nullptr; wxString m_linear_last; wxString m_angle_last; wxStaticText* mesh_face_number_text; diff --git a/src/slic3r/GUI/Tab.cpp b/src/slic3r/GUI/Tab.cpp index 95d5c886b2..f08efd85f8 100644 --- a/src/slic3r/GUI/Tab.cpp +++ b/src/slic3r/GUI/Tab.cpp @@ -8591,14 +8591,9 @@ static void toggle_compatible_condition(Tab& tab, const std::string& key, bool e // Return a callback to create a Tab widget to mark the preferences as compatible / incompatible to the current printer. wxSizer* Tab::compatible_widget_create(wxWindow* parent, PresetDependencies &deps) { - deps.checkbox = new ::CheckBox(parent, wxID_ANY); + deps.checkbox = new LabeledCheckBox(parent, _L("All")); wxGetApp().UpdateDarkUI(deps.checkbox, false, true); - deps.checkbox_title = new wxStaticText(parent, wxID_ANY, _L("All")); - deps.checkbox_title->SetFont(Label::Body_14); - deps.checkbox_title->SetForegroundColour(wxColour("#363636")); - wxGetApp().UpdateDarkUI(deps.checkbox_title, false, true); - // ORCA modernize button style Button* btn = new Button(parent, _(L("Set")) + " " + dots); btn->SetStyle(ButtonStyle::Regular, ButtonType::Parameter); @@ -8606,11 +8601,11 @@ wxSizer* Tab::compatible_widget_create(wxWindow* parent, PresetDependencies &dep auto sizer = new wxBoxSizer(wxHORIZONTAL); sizer->Add((deps.checkbox), 0, wxALIGN_CENTER_VERTICAL); - sizer->Add((deps.checkbox_title), 0, wxALIGN_CENTER_VERTICAL); sizer->Add(new wxStaticText(parent, wxID_ANY, " ")); // weirdly didnt apply AddSpacer or wxRIGHT border sizer->Add((deps.btn), 0, wxALIGN_CENTER_VERTICAL); - auto on_toggle = [this, &deps](const bool &state){ + deps.checkbox->Bind(wxEVT_CHECKBOX, ([this, &deps](wxCommandEvent& e) { + bool state = e.IsChecked(); deps.checkbox->SetValue(state); deps.btn->Enable(!state); // All printers have been made compatible with this preset. @@ -8618,21 +8613,6 @@ wxSizer* Tab::compatible_widget_create(wxWindow* parent, PresetDependencies &dep this->load_key_value(deps.key_list, std::vector {}); toggle_compatible_condition(*this, deps.key_condition, state); this->update_changed_ui(); - }; - - deps.checkbox_title->Bind(wxEVT_LEFT_DOWN,([&deps, on_toggle](wxMouseEvent& e) { - if (e.GetEventType() == wxEVT_LEFT_DCLICK) return; - on_toggle(!deps.checkbox->GetValue()); - e.Skip(); - })); - - deps.checkbox_title->Bind(wxEVT_LEFT_DCLICK,([&deps, on_toggle](wxMouseEvent& e) { - on_toggle(!deps.checkbox->GetValue()); - e.Skip(); - })); - - deps.checkbox->Bind(wxEVT_TOGGLEBUTTON, ([on_toggle](wxCommandEvent& e) { - on_toggle(e.IsChecked()); e.Skip(); }), deps.checkbox->GetId()); diff --git a/src/slic3r/GUI/Tab.hpp b/src/slic3r/GUI/Tab.hpp index c698b7dff0..330d0d1618 100644 --- a/src/slic3r/GUI/Tab.hpp +++ b/src/slic3r/GUI/Tab.hpp @@ -51,6 +51,7 @@ #include "ParamsPanel.hpp" #include "Widgets/TextInput.hpp" #include "Widgets/CheckBox.hpp" // ORCA +#include "Widgets/LabeledCheckBox.hpp" // ORCA #include "Widgets/ComboBox.hpp" class TabCtrl; @@ -188,8 +189,7 @@ protected: struct PresetDependencies { Preset::Type type = Preset::TYPE_INVALID; - ::CheckBox* checkbox = nullptr; - wxStaticText* checkbox_title = nullptr; + LabeledCheckBox* checkbox = nullptr; Button *btn = nullptr; std::string key_list; // "compatible_printers" std::string key_condition; diff --git a/src/slic3r/GUI/TextureImportDialog.cpp b/src/slic3r/GUI/TextureImportDialog.cpp index cee0b5fe5b..4bb4791760 100644 --- a/src/slic3r/GUI/TextureImportDialog.cpp +++ b/src/slic3r/GUI/TextureImportDialog.cpp @@ -34,6 +34,7 @@ #include "slic3r/GUI/Widgets/SpinInput.hpp" #include #include +#include #include "libslic3r/TriangleMesh.hpp" #include #include @@ -2195,10 +2196,8 @@ void TextureImportDialog::build_mapping_panel(wxWindow* parent, wxSizer* sizer) sizer->Add(header_sizer, 0, wxEXPAND | wxBOTTOM, FromDIP(4)); wxBoxSizer* merge_sizer = new wxBoxSizer(wxHORIZONTAL); - m_auto_merge_cb = new wxCheckBox(parent, wxID_ANY, _L("Auto-merge same filament")); - m_auto_merge_cb->SetFont(Label::Body_14); + m_auto_merge_cb = new LabeledCheckBox(parent, _L("Auto-merge same filament")); m_auto_merge_cb->SetToolTip(_L("Automatically merge identical filaments into existing filaments in the project")); - m_auto_merge_cb->SetForegroundColour(secondary_fg); m_auto_merge_cb->SetValue(true); m_auto_merge_cb->Bind(wxEVT_CHECKBOX, &TextureImportDialog::on_auto_merge_toggled, this); merge_sizer->Add(m_auto_merge_cb, 0, wxALIGN_CENTER_VERTICAL | wxTOP | wxBOTTOM, FromDIP(5)); diff --git a/src/slic3r/GUI/TextureImportDialog.hpp b/src/slic3r/GUI/TextureImportDialog.hpp index b1a2449fca..8dc6fe968d 100644 --- a/src/slic3r/GUI/TextureImportDialog.hpp +++ b/src/slic3r/GUI/TextureImportDialog.hpp @@ -14,7 +14,7 @@ #include #include #include "Widgets/SpinInput.hpp" -#include +#include "Widgets/LabeledCheckBox.hpp" #include #include "Widgets/Button.hpp" #include @@ -365,7 +365,7 @@ private: SpinInput* m_smooth_spin = nullptr; Button* m_btn_apply = nullptr; - wxCheckBox* m_auto_merge_cb = nullptr; + LabeledCheckBox* m_auto_merge_cb = nullptr; Button* m_btn_auto_mix = nullptr; Button* m_btn_mix_reset = nullptr; bool m_auto_mix_applied = false; diff --git a/src/slic3r/GUI/UVEditorCanvas.cpp b/src/slic3r/GUI/UVEditorCanvas.cpp index 502a1cd912..e535ea7262 100644 --- a/src/slic3r/GUI/UVEditorCanvas.cpp +++ b/src/slic3r/GUI/UVEditorCanvas.cpp @@ -32,7 +32,6 @@ #include #include #include -#include #include "3DScene.hpp" #include "BitmapCache.hpp" @@ -43,7 +42,7 @@ #include "OpenGLManager.hpp" #include "Plater.hpp" #include "wxExtensions.hpp" -#include "Widgets/CheckBox.hpp" +#include "Widgets/LabeledCheckBox.hpp" #include "Widgets/SpinInput.hpp" #include "libslic3r/AppConfig.hpp" @@ -2036,18 +2035,16 @@ UVEditorPanel::UVEditorPanel(wxWindow *parent) : wxPanel(parent, wxID_ANY) "texture not running continuously across the cut. Takes effect at the next Unwrap."); seam_label->SetToolTip(seam_tip); m_seam_angle->SetToolTip(seam_tip); - m_connect = new ::CheckBox(this); - auto *connect_label = text(_L("Connect islands"), c.ink); - const wxString connect_tip = _L("Lay the unwrap out as a connected net: pieces that share an edge are unfolded next to each " - "other (a cube becomes a joined net rather than six loose squares). They stay separate " - "islands, so you can still move any of them by hand afterwards."); - m_connect->SetToolTip(connect_tip); - connect_label->SetToolTip(connect_tip); + m_connect = new LabeledCheckBox(this, _L("Connect islands")); + m_connect->SetFont(GetFont()); // same as the other texts of the pane + m_connect->SetForegroundColour(c.ink); + m_connect->SetToolTip(_L("Lay the unwrap out as a connected net: pieces that share an edge are unfolded next to each " + "other (a cube becomes a joined net rather than six loose squares). They stay separate " + "islands, so you can still move any of them by hand afterwards.")); settings->Add(seam_label, 0, wxALIGN_CENTER_VERTICAL); settings->Add(m_seam_angle, 0, wxALIGN_CENTER_VERTICAL | wxLEFT, gap); settings->AddStretchSpacer(); settings->Add(m_connect, 0, wxALIGN_CENTER_VERTICAL); - settings->Add(connect_label, 0, wxALIGN_CENTER_VERTICAL | wxLEFT, FromDIP(4)); // ---- tool strip ---- auto *strip = new wxBoxSizer(wxVERTICAL); @@ -2134,20 +2131,11 @@ UVEditorPanel::UVEditorPanel(wxWindow *parent) : wxPanel(parent, wxID_ANY) if (value != int(std::lround(m_canvas->pane_state().seam_angle_deg))) m_canvas->run_command(UVEditorCanvas::Command::SetSeamAngle, float(value)); }); - const auto send_connect = [this]() { + m_connect->Bind(wxEVT_CHECKBOX, [this](wxCommandEvent &e) { if (m_connect->GetValue() != m_canvas->pane_state().connect_islands) m_canvas->run_command(UVEditorCanvas::Command::SetConnectIslands, m_connect->GetValue() ? 1.f : 0.f); - }; - m_connect->Bind(wxEVT_TOGGLEBUTTON, [send_connect](wxCommandEvent &e) { - send_connect(); e.Skip(); }); - connect_label->Bind(wxEVT_LEFT_DOWN, [this, send_connect](wxMouseEvent &) { - if (!m_connect->IsEnabled()) - return; - m_connect->SetValue(!m_connect->GetValue()); - send_connect(); - }); m_canvas->set_status_callback([this](const wxString &label) { if (m_status != nullptr && m_status->GetLabel() != label) { diff --git a/src/slic3r/GUI/UVEditorCanvas.hpp b/src/slic3r/GUI/UVEditorCanvas.hpp index a01d058983..0f005005e0 100644 --- a/src/slic3r/GUI/UVEditorCanvas.hpp +++ b/src/slic3r/GUI/UVEditorCanvas.hpp @@ -30,7 +30,7 @@ // Orca's own widgets (slic3r/GUI/Widgets), declared at global scope. class SpinInput; -class CheckBox; +class LabeledCheckBox; namespace Slic3r::GUI { @@ -437,7 +437,7 @@ private: UVToolButton *m_unwrap = nullptr; ::SpinInput *m_seam_angle = nullptr; - ::CheckBox *m_connect = nullptr; + LabeledCheckBox *m_connect = nullptr; UVToolButton *m_select[3]{}; UVToolButton *m_mark_seams = nullptr; diff --git a/src/slic3r/GUI/UnsavedChangesDialog.cpp b/src/slic3r/GUI/UnsavedChangesDialog.cpp index 322826ed0b..a3108cd088 100644 --- a/src/slic3r/GUI/UnsavedChangesDialog.cpp +++ b/src/slic3r/GUI/UnsavedChangesDialog.cpp @@ -68,7 +68,6 @@ #include "MsgDialog.hpp" #include "PresetComboBoxes.hpp" -#include "Widgets/CheckBox.hpp" #include "Widgets/DialogButtons.hpp" #ifdef __linux__ @@ -930,7 +929,7 @@ inline int UnsavedChangesDialog::ShowModal() } } int r = DPIDialog::ShowModal(); - if (r != wxID_CANCEL && dynamic_cast<::CheckBox*>(FindWindowById(wxID_APPLY))->GetValue()) { + if (r != wxID_CANCEL && dynamic_cast<::LabeledCheckBox*>(FindWindowById(wxID_APPLY))->GetValue()) { wxGetApp().app_config->set(choise_key, std::to_string(int(m_exit_action))); } return r; @@ -1117,16 +1116,11 @@ void UnsavedChangesDialog::build(Preset::Type type, PresetCollection *dependent_ wxBoxSizer *m_sizer_button = new wxBoxSizer(wxHORIZONTAL); - auto checkbox_sizer = new wxBoxSizer(wxHORIZONTAL); - auto checkbox = new ::CheckBox(this, wxID_APPLY); - checkbox_sizer->Add(checkbox, 0, wxALL | wxALIGN_CENTER, FromDIP(2)); + auto checkbox = new LabeledCheckBox(this, _L("Remember my choice.")); + checkbox->SetId(wxID_APPLY); - auto checkbox_text = new wxStaticText(this, wxID_ANY, _L("Remember my choice."), wxDefaultPosition, wxDefaultSize, 0); - checkbox_sizer->Add(checkbox_text, 0, wxALL | wxALIGN_CENTER, FromDIP(2)); - checkbox_text->SetFont(::Label::Body_13); - checkbox_text->SetForegroundColour(StateColor::darkModeColorFor(wxColour("#323A3D"))); - m_sizer_button->Add(checkbox_sizer, 0, wxLEFT, FromDIP(22)); - checkbox_sizer->Show(bool(m_buttons & REMEMBER_CHOISE)); + m_sizer_button->Add(checkbox, 0, wxLEFT | wxALIGN_CENTER_VERTICAL, FromDIP(22)); + checkbox->Show(bool(m_buttons & REMEMBER_CHOISE)); if (dependent_presets != nullptr) { auto wiki_btn = new Button(this, "", "toolbar_wiki", 0, 15); @@ -2200,7 +2194,7 @@ void DiffPresetDialog::create_presets_sizer() void DiffPresetDialog::create_show_all_presets_chb() { - m_show_all_presets = new wxCheckBox(this, wxID_ANY, _L("Show all presets (including incompatible)")); + m_show_all_presets = new LabeledCheckBox(this, _L("Show all presets (including incompatible)")); m_show_all_presets->Bind(wxEVT_CHECKBOX, [this](wxCommandEvent&) { bool show_all = m_show_all_presets->GetValue(); for (auto preset_combos : m_preset_combos) { @@ -2305,7 +2299,7 @@ void DiffPresetDialog::create_buttons() void DiffPresetDialog::create_edit_sizer() { // Add check box for the edit mode - m_use_for_transfer = new wxCheckBox(this, wxID_ANY, _L("Transfer values from left to right")); + m_use_for_transfer = new LabeledCheckBox(this, _L("Transfer values from left to right")); m_use_for_transfer->SetToolTip(_L("If enabled, this dialog can be used for transfer selected values from left to right preset.")); m_use_for_transfer->Bind(wxEVT_CHECKBOX, [this](wxCommandEvent&) { bool use = m_use_for_transfer->GetValue(); diff --git a/src/slic3r/GUI/UnsavedChangesDialog.hpp b/src/slic3r/GUI/UnsavedChangesDialog.hpp index be65c28cfd..4308d83664 100644 --- a/src/slic3r/GUI/UnsavedChangesDialog.hpp +++ b/src/slic3r/GUI/UnsavedChangesDialog.hpp @@ -27,6 +27,7 @@ #include "wxExtensions.hpp" #include "libslic3r/PresetBundle.hpp" #include "Widgets/Button.hpp" +#include "Widgets/LabeledCheckBox.hpp" #include "Widgets/ScrolledWindow.hpp" #include "Lazy.hpp" @@ -453,8 +454,8 @@ class DiffPresetDialog : public DPIDialog, public LazyInstance wxBoxSizer* m_presets_sizer { nullptr }; wxStaticText* m_top_info_line { nullptr }; wxStaticText* m_bottom_info_line { nullptr }; - wxCheckBox* m_show_all_presets { nullptr }; - wxCheckBox* m_use_for_transfer { nullptr }; + LabeledCheckBox* m_show_all_presets { nullptr }; + LabeledCheckBox* m_use_for_transfer { nullptr }; wxBoxSizer* m_buttons { nullptr }; wxBoxSizer* m_edit_sizer { nullptr }; diff --git a/src/slic3r/GUI/Widgets/LabeledCheckBox.cpp b/src/slic3r/GUI/Widgets/LabeledCheckBox.cpp new file mode 100644 index 0000000000..168a707b61 --- /dev/null +++ b/src/slic3r/GUI/Widgets/LabeledCheckBox.cpp @@ -0,0 +1,307 @@ +#include "LabeledCheckBox.hpp" + +#include "CheckBox.hpp" +#include "Label.hpp" +#include "StateColor.hpp" +#include "StaticBox.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include // wxEVT_TOGGLEBUTTON +#include +#include +#include +#include + +#include +#include + +static wxColour GetParentBackground(wxWindow* parent) +{ + wxWindow* child = parent; + for (wxWindow* win = parent; win; child = win, win = win->GetParent()) + if (dynamic_cast(win)) + return child->GetBackgroundColour(); + return parent->GetBackgroundColour(); +} + +LabeledCheckBox::LabeledCheckBox(wxWindow* parent, const wxString& label, wxWindowID id) + : wxPanel(parent, id) +{ + m_check = new CheckBox(this); + + m_text_box = new StaticBox(this); + m_text_box->SetCornerRadius(0); + + // Hidden while creation. wxGTK measures label itself and GTK reports size for a new font too late + m_text_box->Hide(); + m_text = new Label(m_text_box, Label::Body_14, label); + m_text_box->Show(!label.empty()); + UpdateFocusTarget(); + + // Two sizers, as horizontal and vertical padding differ + wxBoxSizer* text_sizer = new wxBoxSizer(wxHORIZONTAL); + text_sizer->Add(m_text, 0, wxLEFT | wxRIGHT); + wxBoxSizer* box_sizer = new wxBoxSizer(wxVERTICAL); + box_sizer->Add(text_sizer, 0, wxTOP | wxBOTTOM); + m_text_box->SetSizer(box_sizer); + + wxBoxSizer* sizer = new wxBoxSizer(wxHORIZONTAL); + sizer->Add(m_check, 0, wxTOP); + sizer->Add(m_text_box); + SetSizer(sizer); + + wxPanel::SetLabel(label); + wxPanel::SetFont(Label::Body_14); + SetBackgroundColour(GetParentBackground(parent)); + SetForegroundColour(StateColor::darkModeColorFor(wxColour("#363636"))); + UpdateMetrics(); + Fit(); + + m_check->Bind(wxEVT_TOGGLEBUTTON, [this](wxCommandEvent&) { + // Focus to frame once the click is over. Pressed button cancels its click on MSW. A click does not focus it at all on macOS + CallAfter([this] { TakeFocus(); }); + OnToggled(); + }); + m_check->Bind(wxEVT_SET_FOCUS, [this](wxFocusEvent& e) { ShowFocus(true); e.Skip(); }); + m_check->Bind(wxEVT_KILL_FOCUS, [this](wxFocusEvent& e) { ShowFocus(false); e.Skip(); }); + m_text_box->Bind(wxEVT_SET_FOCUS, [this](wxFocusEvent& e) { ShowFocus(true); e.Skip(); }); + m_text_box->Bind(wxEVT_KILL_FOCUS, [this](wxFocusEvent& e) { ShowFocus(false); e.Skip(); }); + m_text_box->Bind(wxEVT_KEY_DOWN, &LabeledCheckBox::OnKeyDown, this); + for (wxWindow* win : std::initializer_list{m_text_box, m_text}) { + win->Bind(wxEVT_LEFT_DOWN, &LabeledCheckBox::OnLabelClick, this); + win->Bind(wxEVT_LEFT_DCLICK, &LabeledCheckBox::OnLabelClick, this); // 2nd click of a double click + win->Bind(wxEVT_ENTER_WINDOW, &LabeledCheckBox::OnLabelHover, this); + win->Bind(wxEVT_LEAVE_WINDOW, &LabeledCheckBox::OnLabelHover, this); + } + Bind(wxEVT_SIZE, &LabeledCheckBox::OnSize, this); +} + +void LabeledCheckBox::SetValue(bool value) +{ + m_check->SetValue(value); + ShowHover(); +} + +void LabeledCheckBox::SetHalfChecked(bool half) +{ + m_check->SetHalfChecked(half); + ShowHover(); +} + +void LabeledCheckBox::Wrap(int width) +{ + m_auto_wrap = false; + m_wrap_width = width; + Relayout(); +} + +void LabeledCheckBox::AutoWrap(bool enable) +{ + m_auto_wrap = enable; + m_wrap_width = -1; // wrapped again on the next resize + Relayout(); +} + +void LabeledCheckBox::OnSize(wxSizeEvent& e) +{ + e.Skip(); + // Never wrap below the min width, and not for our own best width: it already fits + const int width = std::max(GetClientSize().x, GetMinSize().x); + const wxSize best = GetBestSize(); + if (!m_auto_wrap || width == m_wrap_width || width == best.x) + return; + + m_wrap_width = width; + UpdateMetrics(); + if (GetBestSize() != best) // Height changed, let the parent lay out again + CallAfter([this]() { SendSizeEventToParent(); }); +} + +void LabeledCheckBox::OnToggled() +{ + m_check->SetHalfChecked(false); // also refreshes the bitmap + ShowHover(); + + // A handler may destroy us + const wxWeakRef self(this); + const wxWindowID id = GetId(); + const bool value = GetValue(); + for (wxEventType type : {wxEVT_CHECKBOX, wxEVT_TOGGLEBUTTON}) { + wxCommandEvent evt(type, id); + evt.SetEventObject(this); + evt.SetInt(value); + ProcessWindowEvent(evt); + if (!self) + return; + } +} + +void LabeledCheckBox::OnLabelHover(wxMouseEvent& e) +{ + e.Skip(); + // Label and frame send enter / leave to each other, so check the position on leave. + // Event position, as wxGetMousePosition() does not work on Wayland + wxPoint pos = e.GetPosition(); + if (e.GetEventObject() == m_text) + pos += m_text->GetPosition(); + m_hovered = e.Entering() || m_text_box->GetClientRect().Contains(pos); + m_check->SetHalfChecked(m_check->IsHalfChecked()); // back to the normal icon + ShowHover(); +} + +void LabeledCheckBox::ShowHover() +{ + if (!m_hovered) + return; + // CheckBox sets its icons on every change, so this is called after each of them. + // Reset them first: on MSW setting the normal icon drops the hover one. + m_check->SetHalfChecked(m_check->IsHalfChecked()); + m_check->SetBitmapLabel(m_check->GetBitmapCurrent()); +} + +void LabeledCheckBox::OnLabelClick(wxMouseEvent& e) +{ + if (!IsEnabled()) + return e.Skip(); + TakeFocus(); + m_check->SetValue(!GetValue()); + OnToggled(); +} + +void LabeledCheckBox::OnKeyDown(wxKeyEvent& e) +{ + if (e.GetKeyCode() == WXK_SPACE) { + if (IsEnabled()) { + m_check->SetValue(!GetValue()); + OnToggled(); + } + return; + } + if (e.GetKeyCode() != WXK_TAB || !m_text_box->HandleAsNavigationKey(e)) + e.Skip(); +} + +// Frame takes keyboard focus: a native button cant take it while macOS full keyboard access is off ([NSView canBecomeKeyView]) +void LabeledCheckBox::UpdateFocusTarget() +{ + if (m_text_box->IsShown()) + m_check->DisableFocusFromKeyboard(); // one tab stop. SetCanFocus() would work on GTK only +} + +// With no label there is no frame to focus, only the check +void LabeledCheckBox::TakeFocus() +{ + if (m_text_box->IsShown()) + m_text_box->SetFocus(); + else + m_check->SetFocus(); +} + +void LabeledCheckBox::ShowFocus(bool focused) +{ + if (!IsBeingDeleted()) + m_text_box->SetBorderColor(focused ? wxColour("#009688") : GetBackgroundColour()); +} + +void LabeledCheckBox::UpdateLabelColor() +{ + // Own state only: IsEnabled() is also false while an ancestor is disabled, e.g. the main frame under a modal dialog + if (m_text->SetForegroundColour(m_check->IsThisEnabled() ? GetForegroundColour() : StateColor::darkModeColorFor(wxColour("#6B6A6A")))) + m_text->Refresh(); +} + +void LabeledCheckBox::UpdateMetrics() +{ + const wxSize padding = FromDIP(wxSize(5, 2)); // around the text, same as RadioGroup + wxSizer* text_sizer = m_text->GetContainingSizer(); + text_sizer->GetItem(m_text)->SetBorder(padding.x); + m_text_box->GetSizer()->GetItem(text_sizer)->SetBorder(padding.y); + // Keep the check on the first text line + const int offset = m_text_box->IsShown() ? padding.y + (m_text->GetCharHeight() - m_check->GetMinSize().y) / 2 : 0; + GetSizer()->GetItem(m_check)->SetBorder(std::max(offset, 0)); + + // Label::Wrap() starts from the full text, -1 unwraps + const int text_width = m_wrap_width - m_check->GetMinSize().x - 2 * padding.x; + m_text->Wrap(m_wrap_width > 0 && text_width > 0 ? text_width : -1); +} + +void LabeledCheckBox::Relayout() +{ + UpdateMetrics(); + Fit(); + SendSizeEventToParent(); +} + +void LabeledCheckBox::Rescale() +{ + m_check->Rescale(); + ShowHover(); + Relayout(); +} + +void LabeledCheckBox::SetLabel(const wxString& label) +{ + wxPanel::SetLabel(label); + m_text->SetLabel(label); + m_text_box->Show(!label.empty()); + UpdateFocusTarget(); + Relayout(); +} + +bool LabeledCheckBox::SetFont(const wxFont& font) +{ + const bool changed = wxPanel::SetFont(font); + m_text->SetFont(font); + Relayout(); + return changed; +} + +bool LabeledCheckBox::SetForegroundColour(const wxColour& colour) +{ + const bool changed = wxPanel::SetForegroundColour(colour); + UpdateLabelColor(); + return changed; +} + +bool LabeledCheckBox::SetBackgroundColour(const wxColour& colour) +{ + const bool changed = wxPanel::SetBackgroundColour(colour); + m_check->SetBackgroundColour(colour); + m_text_box->SetBackgroundColour(colour); + m_text->SetBackgroundColour(colour); + ShowFocus(HasFocus()); // a hidden frame has the background color + return changed; +} + +bool LabeledCheckBox::Enable(bool enable) +{ + if (!m_check->Enable(enable)) + return false; + m_text_box->Enable(enable); // it holds the focus, so it must not be a tab stop while disabled + UpdateLabelColor(); + return true; +} + +void LabeledCheckBox::DoSetToolTip(wxToolTip* tip) +{ + const wxString text = tip ? tip->GetTip() : wxString(); + for (wxWindow* win : std::initializer_list{m_check, m_text_box, m_text}) + win->SetToolTip(text); + wxPanel::DoSetToolTip(tip); +} + +// wx only changes the text of an existing tooltip here and does not call DoSetToolTip() again +void LabeledCheckBox::DoSetToolTipText(const wxString& tip) +{ + wxPanel::DoSetToolTipText(tip); + for (wxWindow* win : std::initializer_list{m_check, m_text_box, m_text}) + win->SetToolTip(tip); +} diff --git a/src/slic3r/GUI/Widgets/LabeledCheckBox.hpp b/src/slic3r/GUI/Widgets/LabeledCheckBox.hpp new file mode 100644 index 0000000000..8f3dacffac --- /dev/null +++ b/src/slic3r/GUI/Widgets/LabeledCheckBox.hpp @@ -0,0 +1,74 @@ +#ifndef slic3r_GUI_LabeledCheckBox_hpp_ +#define slic3r_GUI_LabeledCheckBox_hpp_ + +#include "CheckBox.hpp" +#include "Label.hpp" +#include "StaticBox.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// CheckBox with a clickable label +class LabeledCheckBox : public wxPanel +{ +public: + LabeledCheckBox(wxWindow* parent, const wxString& label = wxEmptyString, wxWindowID id = wxID_ANY); + + void SetValue(bool value); + bool GetValue() const { return m_check->GetValue(); } + bool IsChecked() const { return m_check->GetValue(); } + void SetHalfChecked(bool half = true); + + void Wrap(int width); + void AutoWrap(bool enable = true); + + Label* GetLabelCtrl() { return m_text; } + const Label* GetLabelCtrl() const { return m_text; } + + void Rescale(); + + void SetLabel(const wxString& label) override; + bool SetFont(const wxFont& font) override; + bool SetForegroundColour(const wxColour& colour) override; // label color + bool SetBackgroundColour(const wxColour& colour) override; + + bool Enable(bool enable = true) override; + bool IsEnabled() const { return m_check->IsEnabled(); } + + bool HasFocus() const override { return m_text_box->HasFocus() || m_check->HasFocus(); } + +protected: + void DoSetToolTip(wxToolTip* tip) override; + void DoSetToolTipText(const wxString& tip) override; + +private: + void OnToggled(); // sends the events + void OnLabelClick(wxMouseEvent& e); + void OnLabelHover(wxMouseEvent& e); + void OnKeyDown(wxKeyEvent& e); // Space toggles, like a native check box + void OnSize(wxSizeEvent& e); + void UpdateFocusTarget(); // the frame takes the focus when there is a label + void TakeFocus(); + void ShowFocus(bool focused); + void ShowHover(); // hover icon on the check while the mouse is on the label + void UpdateLabelColor(); + void UpdateMetrics(); // borders and wrap + void Relayout(); + + CheckBox* m_check {nullptr}; + StaticBox* m_text_box {nullptr}; + Label* m_text {nullptr}; + + int m_wrap_width {-1}; // control width to wrap for, -1: no wrap + bool m_auto_wrap {false}; + bool m_hovered {false}; // mouse is on the label +}; + +#endif // !slic3r_GUI_LabeledCheckBox_hpp_ diff --git a/src/slic3r/GUI/calib_dlg.cpp b/src/slic3r/GUI/calib_dlg.cpp index 6f0e51a64a..ea9c655fb8 100644 --- a/src/slic3r/GUI/calib_dlg.cpp +++ b/src/slic3r/GUI/calib_dlg.cpp @@ -14,6 +14,7 @@ #include #include "slic3r/GUI/Widgets/Button.hpp" #include "slic3r/GUI/Widgets/Label.hpp" +#include #include "slic3r/GUI/Widgets/LabeledStaticBox.hpp" #include "slic3r/GUI/Widgets/RadioGroup.hpp" #include "slic3r/GUI/Widgets/TextInput.hpp" @@ -65,20 +66,15 @@ int GetTextMax(wxWindow* parent, const std::vector& labels) return text_size.x + parent->FromDIP(10); } -CheckBox* add_scale_checkbox(wxWindow* parent, wxSizer* settings_sizer) +LabeledCheckBox* add_scale_checkbox(wxWindow* parent, wxSizer* settings_sizer) { - auto row = new wxBoxSizer(wxHORIZONTAL); - auto cb = new CheckBox(parent); + auto cb = new LabeledCheckBox(parent, _L("Auto-scale for nozzle")); cb->SetValue(true); - auto text = new wxStaticText(parent, wxID_ANY, _L("Auto-scale for nozzle"), wxDefaultPosition, wxDefaultSize, wxALIGN_LEFT); cb->SetToolTip(_L("This model is designed around a 0.4 mm nozzle with a 0.2 mm layer height.\n" "When the scaling option is enabled (recommended), it dynamically resizes to match your current nozzle diameter" " and an appropriate layer height, making the test both accurate and easy to read.\n" "Turn scaling off only if you wish to print the reference model exactly as-is.")); - text->SetToolTip(cb->GetToolTipText()); - row->Add(cb , 0, wxALL | wxALIGN_CENTER_VERTICAL, parent->FromDIP(2)); - row->Add(text, 0, wxALL | wxALIGN_CENTER_VERTICAL, parent->FromDIP(2)); - settings_sizer->Add(row, 0, wxLEFT | wxTOP, parent->FromDIP(3)); + settings_sizer->Add(cb, 0, wxLEFT | wxTOP, parent->FromDIP(3)); return cb; } @@ -837,16 +833,12 @@ VFA_Test_Dlg::VFA_Test_Dlg(wxWindow* parent, wxWindowID id, Plater* plater) // Auto-adjust parameters to the filament's max volumetric speed auto auto_adjust_sizer = new wxBoxSizer(wxHORIZONTAL); - m_cbAutoAdjust = new CheckBox(this); + m_cbAutoAdjust = new LabeledCheckBox(this, _L("Auto-adjust to max volumetric speed")); m_cbAutoAdjust->SetValue(true); - auto auto_adjust_text = new wxStaticText(this, wxID_ANY, _L("Auto-adjust to max volumetric speed"), wxDefaultPosition, wxDefaultSize, wxALIGN_LEFT); m_cbAutoAdjust->SetToolTip(_L("If the end speed would exceed the filament's maximum volumetric speed, automatically lower the layer " "height (keeping standard values and staying within the machine's limits) to reach it. If even the " "minimum layer height is not enough, lower the end speed instead.")); - auto_adjust_text->SetToolTip(m_cbAutoAdjust->GetToolTipText()); - auto_adjust_sizer->Add(m_cbAutoAdjust , 0, wxALL | wxALIGN_CENTER_VERTICAL, FromDIP(2)); - auto_adjust_sizer->Add(auto_adjust_text, 0, wxALL | wxALIGN_CENTER_VERTICAL, FromDIP(2)); - settings_sizer->Add(auto_adjust_sizer, 0, wxLEFT | wxTOP, FromDIP(3)); + settings_sizer->Add(m_cbAutoAdjust, 0, wxLEFT | wxTOP, FromDIP(3)); settings_sizer->AddSpacer(FromDIP(5)); diff --git a/src/slic3r/GUI/calib_dlg.hpp b/src/slic3r/GUI/calib_dlg.hpp index eb0c5c9c01..478a8933d1 100644 --- a/src/slic3r/GUI/calib_dlg.hpp +++ b/src/slic3r/GUI/calib_dlg.hpp @@ -10,6 +10,7 @@ #include "Widgets/ComboBox.hpp" #include "Widgets/TextInput.hpp" #include "Widgets/LabeledStaticBox.hpp" +#include "Widgets/LabeledCheckBox.hpp" #include "Widgets/RadioGroup.hpp" #include "GUI_App.hpp" #include "wx/hyperlink.h" @@ -72,7 +73,7 @@ protected: TextInput* m_tiStart; TextInput* m_tiEnd; TextInput* m_tiStep; - CheckBox* m_cbResize; + LabeledCheckBox* m_cbResize; Plater* m_plater; }; @@ -107,8 +108,8 @@ protected: TextInput* m_tiStart; TextInput* m_tiEnd; TextInput* m_tiStep; - CheckBox* m_cbAutoAdjust; - CheckBox* m_cbResize; + LabeledCheckBox* m_cbAutoAdjust; + LabeledCheckBox* m_cbResize; Plater* m_plater; }; From cbf282e6b383429586c8a8a1c268b67327297e0a Mon Sep 17 00:00:00 2001 From: HanifKoh <76276251+HanifKoh@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:37:02 +0800 Subject: [PATCH 10/60] Sign Each Windows Binary Once and Keep the Signed NSIS Plugins (#17483) --- .github/workflows/build_orca.yml | 26 ++++++++++++++++++-- scripts/sign_windows.ps1 | 41 +++++++++++++++++++++++++++++++- 2 files changed, 64 insertions(+), 3 deletions(-) diff --git a/.github/workflows/build_orca.yml b/.github/workflows/build_orca.yml index 2b567c1f07..08ec367fdb 100644 --- a/.github/workflows/build_orca.yml +++ b/.github/workflows/build_orca.yml @@ -529,6 +529,9 @@ jobs: "ORCA_SIGN_JSIGN=$jar" | Out-File -Append -FilePath $env:GITHUB_ENV -Encoding utf8 "ORCA_SIGN_CERTFILE=$cert" | Out-File -Append -FilePath $env:GITHUB_ENV -Encoding utf8 "ORCA_SIGN_KMS_KEY=$env:KMS_KEY" | Out-File -Append -FilePath $env:GITHUB_ENV -Encoding utf8 + # Names the certificate in the signed NSIS plugin cache key, so a new certificate re-signs them. + "cert-id=$((Get-FileHash -LiteralPath $cert -Algorithm SHA256).Hash.Substring(0, 16))" | + Out-File -Append -FilePath $env:GITHUB_OUTPUT -Encoding utf8 - name: Set up Java for code signing if: steps.codesign.outcome == 'success' @@ -569,14 +572,25 @@ jobs: token_format: access_token create_credentials_file: false + # The NSIS plugins change only with the NSIS version, so they are signed once per certificate and + # kept; the signing below skips files that are already signed. + - name: Restore signed NSIS plugins + id: nsis-plugins + if: steps.codesign.outcome == 'success' && !vars.SELF_HOSTED + uses: actions/cache/restore@v6 + with: + path: ${{ runner.temp }}/nsis/Plugins + key: nsis-plugins-signed-${{ env.NSIS_VERSION }}-${{ steps.codesign.outputs.cert-id }} + # Signs what the portable zip, the artifact and the MSIX package ship, the profile validator, - # and the NSIS plugins the installer carries. The installer build signs its own copy of the - # app, since cpack installs the files again. + # and the NSIS plugins the installer carries. cpack installs the app again for the installer; + # ORCA_SIGN_REUSE lets its signing hook copy these signed files instead of signing them again. - name: Sign Windows binaries if: steps.codesign.outcome == 'success' shell: pwsh env: ORCA_SIGN_TOKEN: ${{ steps.codesign_auth.outputs.access_token }} + ORCA_SIGN_REUSE: ${{ runner.temp }}/signed-files.json run: | $paths = @("$env:BUILD_DIR/OrcaSlicer") foreach ($extra in 'build/src/Release/OrcaSlicer_profile_validator.exe', "$env:RUNNER_TEMP/nsis/Plugins") { @@ -584,6 +598,13 @@ jobs: } ./scripts/sign_windows.ps1 -Path $paths + - name: Save signed NSIS plugins + if: steps.codesign.outcome == 'success' && !vars.SELF_HOSTED && steps.nsis-plugins.outputs.cache-hit != 'true' + uses: actions/cache/save@v6 + with: + path: ${{ runner.temp }}/nsis/Plugins + key: nsis-plugins-signed-${{ env.NSIS_VERSION }}-${{ steps.codesign.outputs.cert-id }} + - name: Pack unit tests Win if: runner.os == 'Windows' && inputs.compiler == 'clang' working-directory: ${{ github.workspace }} @@ -609,6 +630,7 @@ jobs: # Read by scripts/sign_windows.ps1 when CMake wired signing into the installer. env: ORCA_SIGN_TOKEN: ${{ steps.codesign_auth.outputs.access_token }} + ORCA_SIGN_REUSE: ${{ runner.temp }}/signed-files.json run: | cpack -G NSIS if ($LASTEXITCODE -ne 0) { diff --git a/scripts/sign_windows.ps1 b/scripts/sign_windows.ps1 index c900f52d9c..fb2ecf481b 100644 --- a/scripts/sign_windows.ps1 +++ b/scripts/sign_windows.ps1 @@ -27,6 +27,10 @@ ORCA_SIGN_CERTFILE PEM certificate chain issued for that key, leaf certificate first. ORCA_SIGN_JSIGN Path of the Jsign jar. Java comes from JAVA_HOME, else from PATH. ORCA_SIGN_TOKEN OAuth access token allowed to sign with the key. Not needed for -Verify. + ORCA_SIGN_REUSE Optional record of the files signed so far, kept across runs of this script. + A file whose content before signing matches one already signed takes a copy + of that signed file instead of being signed again; cpack installs a fresh + copy of the app for the installer. Created if missing. Runs under PowerShell 7 and Windows PowerShell 5.1. @@ -137,6 +141,34 @@ if (-not $unsigned) { return } +# The record maps a file's SHA-256 before signing to the signed file. A copy is taken only from a +# file that still carries the release signature. +$record = @{} +$hashes = @{} +$toSign = $unsigned +if ($env:ORCA_SIGN_REUSE) { + if (Test-Path -LiteralPath $env:ORCA_SIGN_REUSE) { + (Get-Content -LiteralPath $env:ORCA_SIGN_REUSE -Raw -Encoding UTF8 | ConvertFrom-Json).PSObject.Properties | + ForEach-Object { $record[$_.Name] = $_.Value } + } + $toSign = @() + foreach ($file in $unsigned) { + $hash = (Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash + $hashes[$file] = $hash + $signed = $record[$hash] + if ($signed -and (Test-Path -LiteralPath $signed) -and + (Get-AuthenticodeSignature -LiteralPath $signed).SignerCertificate.Thumbprint -eq $release.Thumbprint) { + Copy-Item -LiteralPath $signed -Destination $file -Force + } else { + $toSign += $file + } + } + Write-Host "$($unsigned.Count - $toSign.Count) of them copied from files already signed." + if (-not $toSign) { + return + } +} + $java = 'java' if ($env:JAVA_HOME) { $java = Join-Path $env:JAVA_HOME 'bin\java.exe' @@ -144,7 +176,7 @@ if ($env:JAVA_HOME) { # Jsign reads the files to sign from a list file, one path per line (UTF-8 without a BOM). $list = [IO.Path]::GetTempFileName() try { - [IO.File]::WriteAllLines($list, [string[]] $unsigned) + [IO.File]::WriteAllLines($list, [string[]] $toSign) & $java -jar $jsign --storetype GOOGLECLOUD --keystore $keyRing --alias $key ` --storepass env:ORCA_SIGN_TOKEN --certfile $certFile --alg SHA-256 ` --tsaurl $TimestampUrls --tsmode RFC3161 --tsretries 5 --tsretrywait 15 ` @@ -155,3 +187,10 @@ try { } finally { Remove-Item -LiteralPath $list -ErrorAction SilentlyContinue } + +if ($env:ORCA_SIGN_REUSE) { + foreach ($file in $toSign) { + $record[$hashes[$file]] = $file + } + $record | ConvertTo-Json | Set-Content -LiteralPath $env:ORCA_SIGN_REUSE -Encoding UTF8 +} From 191760b5cb6d9a8e6e4d553afe5e176d52edf978 Mon Sep 17 00:00:00 2001 From: HanifKoh <76276251+HanifKoh@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:49:03 +0800 Subject: [PATCH 11/60] Ship the Linux Preset Caches Before Packing the AppImage (#17485) --- .github/workflows/build_orca.yml | 24 ++----- build_linux.sh | 18 +++-- docs/HLSD/preset-cache.md | 3 +- scripts/build_preset_cache.sh | 71 ++++++++++--------- .../platform/unix/build_linux_image.sh.in | 14 +++- 5 files changed, 69 insertions(+), 61 deletions(-) diff --git a/.github/workflows/build_orca.yml b/.github/workflows/build_orca.yml index 08ec367fdb..861a661966 100644 --- a/.github/workflows/build_orca.yml +++ b/.github/workflows/build_orca.yml @@ -770,7 +770,8 @@ jobs: run: | # Build + tar the unit tests (-t) on both Linux legs so each arch # (x86_64 + aarch64) gets tested by its own unit_tests_linux_* job. - ./build_linux.sh -istrlL + # -P ships the system preset caches into the package before the AppImage is packed from it. + ./build_linux.sh -istrlLP ./scripts/check_appimage_libs.sh ./build/package ./build/package/bin/orca-slicer appimage=./build/OrcaSlicer_Linux_AppImage${{ env.ubuntu-ver-str }}${{ env.arch_suffix }}_${{ env.ver }}.AppImage mv -n ./build/OrcaSlicer_Linux_V${{ env.ver_pure }}.AppImage "$appimage" @@ -790,23 +791,6 @@ jobs: retention-days: 5 if-no-files-found: error - - name: Build system preset cache (Linux) - if: runner.os == 'Linux' - shell: bash - run: | - # Both were packed from resources/ before the caches existed, so the - # AppImage is unpacked first and the caches shipped into it and into - # the package tree; the source tree keeps its JSONs for later steps. - appimage=$(find build -maxdepth 1 -name "OrcaSlicer_Linux_AppImage*.AppImage" | head -1) - chmod +x "$appimage" - "$appimage" --appimage-extract - ./scripts/build_preset_cache.sh -b build build/package/resources/profiles squashfs-root/resources/profiles - # The runtime extracts every directory as 0700, and appimagetool (continuous - # build 333 onwards) refuses to pack a tree other users cannot read. - chmod -R a+rX squashfs-root - appimagetool=$(find build -name "appimagetool.AppImage" | head -1) - ARCH=$(uname -m) "$appimagetool" --appimage-extract-and-run squashfs-root "$appimage" - rm -rf squashfs-root # Ship the freshly-built validator so slice_check_linux (build_all.yml) # can slice-sweep the shipped profiles with this PR's engine. Taken from # the aarch64 leg so the sweep also exercises the arm build; x86_64 on @@ -855,8 +839,8 @@ jobs: path: './build/src/Release/OrcaSlicer_profile_validator' # generate_system_cache is what scripts/build_preset_cache.sh bakes the - # .opc caches with; it was already built by the "Build system - # preset cache (Linux)" step above. The .opc format is 64-bit + # .opc caches with; build_linux.sh -P already built it to ship the + # caches in the package. The .opc format is 64-bit # little-endian native, i.e. identical across every platform Orca ships, # so only the Linux binary is published. - name: Upload generate_system_cache Ubuntu diff --git a/build_linux.sh b/build_linux.sh index b4c03e52ec..484fbf7ccb 100755 --- a/build_linux.sh +++ b/build_linux.sh @@ -8,7 +8,7 @@ SCRIPT_PATH=$(dirname "$(readlink -f "${0}")") pushd "${SCRIPT_PATH}" > /dev/null function usage() { - echo "Usage: ./${SCRIPT_NAME} [-1][-b][-c][-d][-D][-e][-F][-g][-h][-i][-j N][-J N][-p][-r][-s][-t][-u][-l][-L] [-- CMAKE_ARGS...]" + echo "Usage: ./${SCRIPT_NAME} [-1][-b][-c][-d][-D][-e][-F][-g][-h][-i][-j N][-J N][-p][-P][-r][-s][-t][-u][-l][-L] [-- CMAKE_ARGS...]" echo " -1: limit builds to one core (where possible)" echo " -j N: limit builds to N cores (where possible)" echo " -J N: build up to N dependencies at a time, each still using -j jobs (default: 1)" @@ -23,6 +23,7 @@ function usage() { echo " -h: prints this help text" echo " -i: build the Orca Slicer AppImage (optional)" echo " -p: disable precompiled headers (on by default): more ccache hits after header changes, slower misses" + echo " -P: ship the system preset caches in the package and AppImage, deleting the preset JSONs they replace (CI packaging)" echo " -r: skip RAM and disk checks (low RAM compiling)" echo " -s: build the Orca Slicer (optional)" echo " -t: build tests (optional), requires -s flag" @@ -47,7 +48,7 @@ unset name BUILD_DIR=build BUILD_CONFIG=Release FORWARDED_ARGS=() -while getopts ":1j:J:bcCdDeFghiprstulL" opt ; do +while getopts ":1j:J:bcCdDeFghipPrstulL" opt ; do case ${opt} in 1 ) export CMAKE_BUILD_PARALLEL_LEVEL=1 @@ -104,6 +105,10 @@ while getopts ":1j:J:bcCdDeFghiprstulL" opt ; do SLIC3R_PRECOMPILED_HEADERS="OFF" FORWARDED_ARGS+=("-p") ;; + P ) + SHIP_PRESET_CACHES="1" + FORWARDED_ARGS+=("-P") + ;; r ) SKIP_RAM_CHECK="1" FORWARDED_ARGS+=("-r") @@ -648,11 +653,14 @@ if [[ -n "${BUILD_IMAGE}" || -n "${BUILD_ORCA}" ]] ; then pushd $BUILD_DIR > /dev/null build_linux_image="./src/build_linux_image.sh" if [[ -e ${build_linux_image} ]] ; then - extra_script_args="" + extra_script_args=() if [[ -n "${BUILD_IMAGE}" ]] ; then - extra_script_args="-i" + extra_script_args+=("-i") fi - print_and_run ${build_linux_image} ${extra_script_args} -R "${BUILD_CONFIG}" + if [[ -n "${SHIP_PRESET_CACHES}" ]] ; then + extra_script_args+=("-c") + fi + print_and_run ${build_linux_image} "${extra_script_args[@]}" -R "${BUILD_CONFIG}" echo "done" fi diff --git a/docs/HLSD/preset-cache.md b/docs/HLSD/preset-cache.md index 41a52bd633..7005583dd8 100644 --- a/docs/HLSD/preset-cache.md +++ b/docs/HLSD/preset-cache.md @@ -358,7 +358,8 @@ step, not something a build should do to a working tree by surprise: the Windows refuses that target unless given `--prune-source`, and CI passes it. Generation runs after the build, in the same job, so the caches ship with a build that -can read them. +can read them. On Linux it runs while the package tree is staged (`build_linux.sh -P`), so +the AppImage is packed from a tree that already holds them. The flatpak differs only in where the script is called from. Nothing outside flatpak-builder ever builds it, so there is no packaged tree for the workflow to point diff --git a/scripts/build_preset_cache.sh b/scripts/build_preset_cache.sh index 71d2c2db6c..b5728ddc31 100755 --- a/scripts/build_preset_cache.sh +++ b/scripts/build_preset_cache.sh @@ -89,17 +89,43 @@ find_tool() { printf '%s' "$best" } -# The preset files a vendor profile lists, relative to its vendor directory, one -# per line. Nothing when the profile is missing. -listed_presets() { - [ -f "$1" ] || return 0 - python3 - "$1" <<'EOF' -import json, sys -with open(sys.argv[1], encoding="utf-8") as f: - profile = json.load(f) -for key in ("machine_model_list", "process_list", "filament_list", "machine_list"): - for entry in profile.get(key, []): - print(entry["sub_path"]) +# Prune one profiles directory for every vendor that has a cache in the first: +# drop the vendor profile, the preset files it lists, and the directories that +# leaves empty. One process for all vendors; starting one per vendor dominated +# the run. +prune_cached_presets() { + python3 - "$1" "$2" <<'EOF' +import json, os, sys +caches_dir, target = sys.argv[1:3] +shipped = pruned = 0 +for name in sorted(os.listdir(caches_dir)): + if not name.endswith(".opc"): + continue + vendor = name[:-len(".opc")] + shipped += 1 + # Read the list from the target's own profile, before it goes: the source + # profile may already be gone when an earlier target pruned it. + profile_path = os.path.join(target, vendor + ".json") + listed = [] + if os.path.isfile(profile_path): + with open(profile_path, encoding="utf-8") as f: + profile = json.load(f) + for key in ("machine_model_list", "process_list", "filament_list", "machine_list"): + listed += [entry["sub_path"] for entry in profile.get(key, [])] + os.remove(profile_path) + pruned += 1 + vendor_dir = os.path.join(target, vendor) + if not os.path.isdir(vendor_dir): + continue + for sub_path in listed: + path = vendor_dir + "/" + sub_path # not os.path.join: an absolute sub_path stays inside + if sub_path and os.path.isfile(path): + os.remove(path) + pruned += 1 + for root, _, _ in os.walk(vendor_dir, topdown=False): + if not os.listdir(root): + os.rmdir(root) +print(f"{target}: {shipped} caches, dropped {pruned} preset JSONs") EOF } @@ -158,26 +184,5 @@ for target in "$@"; do cp "$profiles_dir"/*.opc "$resolved"/ fi - pruned=0 - shipped=0 - for cache in "$profiles_dir"/*.opc; do - vendor=$(basename "$cache" .opc) - shipped=$(( shipped + 1 )) - # Read the list from the target's own profile, before it goes: the - # source profile may already be gone when an earlier target pruned it. - listed=$(listed_presets "$resolved/$vendor.json") - if [ -f "$resolved/$vendor.json" ]; then - rm -f "$resolved/$vendor.json" - pruned=$(( pruned + 1 )) - fi - [ -d "$resolved/$vendor" ] || continue - while IFS= read -r sub_path; do - if [ -n "$sub_path" ] && [ -f "$resolved/$vendor/$sub_path" ]; then - rm -f "$resolved/$vendor/$sub_path" - pruned=$(( pruned + 1 )) - fi - done <<< "$listed" - find "$resolved/$vendor" -type d -empty -delete - done - echo "$resolved: $shipped caches, dropped $pruned preset JSONs" + prune_cached_presets "$profiles_dir" "$resolved" done diff --git a/src/dev-utils/platform/unix/build_linux_image.sh.in b/src/dev-utils/platform/unix/build_linux_image.sh.in index a7f99ba775..f47952ad81 100755 --- a/src/dev-utils/platform/unix/build_linux_image.sh.in +++ b/src/dev-utils/platform/unix/build_linux_image.sh.in @@ -22,13 +22,17 @@ fi # shellcheck source=/dev/null source "${POLICY_FILE}" -while getopts ":ihR:" opt; do +while getopts ":ichR:" opt; do case ${opt} in i ) export BUILD_IMAGE="1" ;; - h ) echo "Usage: ./build_linux_image.sh [-i][-R config]" + c ) + SHIP_PRESET_CACHES="1" + ;; + h ) echo "Usage: ./build_linux_image.sh [-i][-c][-R config]" echo " -i: Generate Appimage (optional)" + echo " -c: Ship the system preset caches, deleting the preset JSONs they replace" echo " -R: Specify from which config to obtain the binary: Release, RelWithDebInfo, or Debug" exit 1 ;; @@ -185,6 +189,12 @@ echo -n "[9/9] Generating Linux app..." fi cp -Rf ../resources "$APPDIR/resources" + # Before the AppImage is packed from this tree, so it ships the caches without a repack. + if [ -n "$SHIP_PRESET_CACHES" ]; then + # Caches copied in with resources may be stale; the script ships a fresh set. + rm -f "$APPDIR/resources/profiles"/*.opc + "${REPO_ROOT}/scripts/build_preset_cache.sh" -b . -c "$CONFIG" "$APPDIR/resources/profiles" + fi ORIGINAL_BINARY_LOCATION="" if [ -f "src/${CONFIG}/@SLIC3R_APP_CMD@" ]; then From d6ec712c2e6cda166676dc73d096fcbdebd7f908 Mon Sep 17 00:00:00 2001 From: Ian Chua Date: Mon, 16 Nov 2026 13:54:55 +0800 Subject: [PATCH 12/60] fix: windows plugin update deletion failure (#17462) * fix: windows plugin update deletion failure * fix: retry transient Windows plugin deletion failures --- src/slic3r/plugin/PluginFsUtils.cpp | 70 +++++++++++++++++++++++++++++ src/slic3r/plugin/PluginManager.cpp | 30 ++++--------- 2 files changed, 79 insertions(+), 21 deletions(-) diff --git a/src/slic3r/plugin/PluginFsUtils.cpp b/src/slic3r/plugin/PluginFsUtils.cpp index 36cb1e8eb8..071a8331e0 100644 --- a/src/slic3r/plugin/PluginFsUtils.cpp +++ b/src/slic3r/plugin/PluginFsUtils.cpp @@ -140,6 +140,75 @@ bool delete_plugin_root(const boost::filesystem::path& resolved_root, const std: { namespace fs = boost::filesystem; +#ifdef _WIN32 + // Windows can report a deletion that is already under way as a transient error: a just-removed + // child can stay visible for a moment (ERROR_DIR_NOT_EMPTY, 145), a scanner or shell preview can + // still hold a handle (ERROR_SHARING_VIOLATION, 32), and Boost 1.84's child-open path maps + // STATUS_SHARING_VIOLATION to ERROR_NOT_SUPPORTED (50). Retry only those three codes, and keep + // each reported as returned: 50 and 145 are different failures and are never relabeled. + constexpr unsigned max_attempts = 5; + constexpr std::chrono::milliseconds retry_delays[max_attempts - 1] = { + std::chrono::milliseconds(100), std::chrono::milliseconds(250), + std::chrono::milliseconds(500), std::chrono::milliseconds(1000)}; + + const auto is_transient_delete_error = [](const boost::system::error_code& err) { + return err.category() == boost::system::system_category() && + (err.value() == ERROR_DIR_NOT_EMPTY || err.value() == ERROR_SHARING_VIOLATION || + err.value() == ERROR_NOT_SUPPORTED); + }; + + boost::system::error_code ec; + boost::system::error_code last_retry_error; + std::uintmax_t removed_count = 0; + unsigned attempts = 0; + + for (;;) { + ++attempts; + ec.clear(); + removed_count = fs::remove_all(resolved_root, ec); + if (!ec) + break; + + if (attempts < max_attempts && is_transient_delete_error(ec)) { + const std::chrono::milliseconds delay = retry_delays[attempts - 1]; + BOOST_LOG_TRIVIAL(warning) << "Failed to delete plugin folder " << resolved_root.string() + << " transiently: attempt=" << attempts << "/" << max_attempts + << " error_value=" << ec.value() << " error_category=" << ec.category().name() + << " message=" << ec.message() << " delay_ms=" << delay.count(); + last_retry_error = ec; + ::Sleep(static_cast(delay.count())); + continue; + } + + break; + } + + if (ec) { + // TRN %1% is a folder path, %2% the system error message. + error = GUI::format(_u8L("Failed to delete plugin folder %1%: %2%"), resolved_root.string(), ec.message()); + BOOST_LOG_TRIVIAL(error) << "Failed to delete plugin folder " << resolved_root.string() + << " after attempts=" << attempts << " error_value=" << ec.value() + << " error_category=" << ec.category().name() << " message=" << ec.message(); + return false; + } + + if (attempts > 1) { + // Recovered after one or more transient failures: keep the last failure for diagnosis. + BOOST_LOG_TRIVIAL(info) << "Deleted plugin: " << plugin_id << " from " << resolved_root.string() + << " after attempts=" << attempts << " last_error_value=" << last_retry_error.value() + << " last_error_category=" << last_retry_error.category().name() + << " last_error_message=" << last_retry_error.message(); + return true; + } + + if (removed_count == 0) { + return true; + } + + BOOST_LOG_TRIVIAL(info) << "Deleted plugin: " << plugin_id << " from " << resolved_root.string(); + return true; +#else + // Non-Windows behavior is unchanged: one remove_all() call, no retries. boost::system::error_code ec; const auto removed_count = fs::remove_all(resolved_root, ec); if (ec) { @@ -154,6 +223,7 @@ bool delete_plugin_root(const boost::filesystem::path& resolved_root, const std: BOOST_LOG_TRIVIAL(info) << "Deleted plugin: " << plugin_id << " from " << resolved_root.string(); return true; +#endif } diff --git a/src/slic3r/plugin/PluginManager.cpp b/src/slic3r/plugin/PluginManager.cpp index fb0166c214..7425f2d255 100644 --- a/src/slic3r/plugin/PluginManager.cpp +++ b/src/slic3r/plugin/PluginManager.cpp @@ -137,25 +137,6 @@ bool PluginManager::initialize() // Uninstalled in shutdown() before the interpreter finalizes. plugin_hooks::install(); - // Persist auto-load / capability state to each plugin's .install_state.json sidecar. - // On load: write enabled=true plus the current capability flags. On unload: flip enabled=false. - // The on-unload callback is skipped during shutdown, so app exit does not wipe the auto-load list. - subscribe_on_load_callback([this](const std::string& key) { write_loaded_plugin_install_state(key); }); - subscribe_on_unload_callback([this](const std::string& key) { - if (m_shutting_down.load(std::memory_order_acquire)) - return; - std::lock_guard state_lock(install_state_mutex()); - PluginDescriptor descriptor; - if (!try_get_plugin_descriptor(key, descriptor) || descriptor.plugin_root.empty()) - return; - const boost::filesystem::path root(descriptor.plugin_root); - PluginInstallState state; - if (read_install_state(root, state)) { - state.enabled = false; - write_install_state(root, state); - } - }); - BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << ": Plugin manager initialized"; return true; @@ -1075,6 +1056,11 @@ void PluginManager::load_plugin_impl(const std::string& plugin_key, bool skip_de clear_plugin_error(plugin_key); + // Persist only after the plugin is committed as loaded. Lifecycle callbacks are dispatched + // asynchronously from worker threads and must not own sidecar persistence. + if (!m_shutting_down.load(std::memory_order_acquire)) + write_loaded_plugin_install_state(plugin_key); + { std::lock_guard lock(m_mutex); m_load_errors.erase(plugin_key); @@ -1128,8 +1114,10 @@ bool PluginManager::unload_plugin(const std::string& plugin_key) // Teardown runs outside m_mutex: it calls into Python and must not hold the registry lock. plugin_loader::unload(removed); - // The .install_state.json sidecar is flipped to enabled=false by the on-unload callback - // (skipped during shutdown), so the auto-load list survives app exit. + // Persist before returning: callers may delete or replace the plugin directory next. + if (!m_shutting_down.load(std::memory_order_acquire)) + mark_plugin_install_state_disabled(plugin_key); + BOOST_LOG_TRIVIAL(info) << "Unloaded plugin: " << plugin_key; return true; From e0f7f0b7eeac019668d637e1733bbf9f665a6b39 Mon Sep 17 00:00:00 2001 From: HanifKoh <76276251+HanifKoh@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:35:35 +0800 Subject: [PATCH 13/60] Work Around the MSVC 14.52 ARM64 Internal Compiler Error in OCCT (#17601) The windows-11-vs2026-arm runner image 20261112.217.1 moved from MSVC 14.51 to 14.52, and its cl.exe crashes with C1001 while optimizing OCCT's BRepGraph_LayerTopoSupplement.cxx. clang-cl builds compile OCCT with cl on ARM64, so every Windows arm64 deps build on that image fails. A second OCCT patch compiles that one file without optimization when the compiler is cl targeting ARM64. Other compilers and architectures see no change. --- ...-BRepGraph-MSVC-ARM64-ICE-workaround.patch | 25 +++++++++++++++++++ deps/OCCT/OCCT.cmake | 6 ++++- 2 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 deps/OCCT/0002-BRepGraph-MSVC-ARM64-ICE-workaround.patch diff --git a/deps/OCCT/0002-BRepGraph-MSVC-ARM64-ICE-workaround.patch b/deps/OCCT/0002-BRepGraph-MSVC-ARM64-ICE-workaround.patch new file mode 100644 index 0000000000..9b007cd57b --- /dev/null +++ b/deps/OCCT/0002-BRepGraph-MSVC-ARM64-ICE-workaround.patch @@ -0,0 +1,25 @@ +diff --git a/src/ModelingData/TKBRep/BRepGraph/BRepGraph_LayerTopoSupplement.cxx b/src/ModelingData/TKBRep/BRepGraph/BRepGraph_LayerTopoSupplement.cxx +index 44e59b0..8833fed 100644 +--- a/src/ModelingData/TKBRep/BRepGraph/BRepGraph_LayerTopoSupplement.cxx ++++ b/src/ModelingData/TKBRep/BRepGraph/BRepGraph_LayerTopoSupplement.cxx +@@ -21,6 +21,12 @@ + #include + #include + ++// MSVC 14.52 for ARM64 crashes with an internal compiler error (C1001) while ++// optimizing this file, so it is compiled without optimization there. ++#if defined(_MSC_VER) && !defined(__clang__) && defined(_M_ARM64) ++ #pragma optimize("", off) ++#endif ++ + IMPLEMENT_STANDARD_RTTIEXT(BRepGraph_LayerTopoSupplement, BRepGraph_Layer) + + namespace +@@ -384,3 +390,7 @@ void BRepGraph_LayerTopoSupplement::removeOwner(const BRepGraph_NodeId theOwner) + myOwnerToUids.UnBind(theOwner); + touch(); + } ++ ++#if defined(_MSC_VER) && !defined(__clang__) && defined(_M_ARM64) ++ #pragma optimize("", on) ++#endif diff --git a/deps/OCCT/OCCT.cmake b/deps/OCCT/OCCT.cmake index c0bd0e1608..d41b3bd886 100644 --- a/deps/OCCT/OCCT.cmake +++ b/deps/OCCT/OCCT.cmake @@ -50,7 +50,11 @@ orcaslicer_add_cmake_project(OCCT URL_HASH SHA256=7c033d917ee8f040c0512d289dcc5f02c148889d5bac17c3e25639accb44f0da # Makes BRepMesh triangulate cone faces whose seam pcurve is slightly tilted # (Open-Cascade-SAS/OCCT#572); remove the patch once an OCCT release includes the fix. - PATCH_COMMAND git apply ${OCCT_DIRECTORY_FLAG} --verbose --ignore-space-change --whitespace=fix ${CMAKE_CURRENT_LIST_DIR}/0001-BRepMesh-seam-pcurve-at-edge-parameter.patch + # 0002 compiles one file without optimization under cl for ARM64, where MSVC 14.52 crashes + # on it with an internal compiler error; remove it once the runner image ships a fixed MSVC. + PATCH_COMMAND git apply ${OCCT_DIRECTORY_FLAG} --verbose --ignore-space-change --whitespace=fix + ${CMAKE_CURRENT_LIST_DIR}/0001-BRepMesh-seam-pcurve-at-edge-parameter.patch + ${CMAKE_CURRENT_LIST_DIR}/0002-BRepGraph-MSVC-ARM64-ICE-workaround.patch #DEPENDS dep_Boost CMAKE_ARGS -DCMAKE_CXX_STANDARD=17 From baeadeb3e1a333fbedb09747755acfe031431898 Mon Sep 17 00:00:00 2001 From: HanifKoh <76276251+HanifKoh@users.noreply.github.com> Date: Mon, 16 Nov 2026 18:07:36 +0800 Subject: [PATCH 14/60] Build the Windows Installer While the Zip and PDB Archive Are Packed (#17484) cpack now runs in the background while the portable zip and the PDB archive are packed, and a later step waits for it, prints its log and fails on its exit code. makensis compresses on one core, so the two archive steps no longer add to the job's length. --- .github/workflows/build_orca.yml | 60 ++++++++++++++++++++++++-------- 1 file changed, 45 insertions(+), 15 deletions(-) diff --git a/.github/workflows/build_orca.yml b/.github/workflows/build_orca.yml index 861a661966..891e984983 100644 --- a/.github/workflows/build_orca.yml +++ b/.github/workflows/build_orca.yml @@ -624,16 +624,58 @@ jobs: # NSIS is x86-only; it runs (and the installer it emits runs) under ARM64's # x86 emulation, packaging the native arm64 payload from build-arm64. - - name: Create installer Win + # makensis compresses on one core and its signing hook waits on the network, so the installer + # builds in the background while the portable zip and the PDB archive are made; "Finish + # installer Win" waits for it. cpack installs its own copy of the app from the build tree, and + # the others only read build/OrcaSlicer and the PDBs. + - name: Start installer Win + id: start_installer if: runner.os == 'Windows' && !vars.SELF_HOSTED working-directory: ${{ github.workspace }}/${{ env.BUILD_DIR }} # Read by scripts/sign_windows.ps1 when CMake wired signing into the installer. env: ORCA_SIGN_TOKEN: ${{ steps.codesign_auth.outputs.access_token }} ORCA_SIGN_REUSE: ${{ runner.temp }}/signed-files.json + shell: pwsh run: | - cpack -G NSIS - if ($LASTEXITCODE -ne 0) { + $exit = Join-Path $env:RUNNER_TEMP 'cpack.exit' + $log = Join-Path $env:RUNNER_TEMP 'cpack.log' + # A hidden window of its own, writing its output to a file, holds none of this step's pipes, + # so the step ends without waiting for cpack. The exit code is written under another name + # and renamed, so the wait never reads half of it. + $cpack = Start-Process pwsh -WindowStyle Hidden -PassThru -ArgumentList '-NoProfile', '-Command', + "cpack -G NSIS *> '$log'; Set-Content '$exit.tmp' `$LASTEXITCODE; Move-Item '$exit.tmp' '$exit'" + Set-Content (Join-Path $env:RUNNER_TEMP 'cpack.pid') $cpack.Id + + - name: Pack app + if: runner.os == 'Windows' + working-directory: ${{ github.workspace }}/${{ env.BUILD_DIR }} + shell: cmd + run: '"C:/Program Files/7-Zip/7z.exe" a -tzip OrcaSlicer_Windows_${{ env.ver }}${{ env.ARCH_SUFFIX }}_portable.zip ${{ github.workspace }}/${{ env.BUILD_DIR }}/OrcaSlicer' + + - name: Pack PDB + if: runner.os == 'Windows' && inputs.arch != 'arm64' && !vars.SELF_HOSTED + working-directory: ${{ github.workspace }}/${{ env.BUILD_DIR }}/src/Release + shell: cmd + run: '"C:/Program Files/7-Zip/7z.exe" a -m0=lzma2 -mx9 Debug_PDB_${{ env.ver }}_for_developers_only.7z *.pdb' + + # Also after a failed pack step, so cpack's log is still shown. + - name: Finish installer Win + if: ${{ !cancelled() && steps.start_installer.outcome == 'success' }} + working-directory: ${{ github.workspace }}/${{ env.BUILD_DIR }} + timeout-minutes: 30 + shell: pwsh + run: | + $exit = Join-Path $env:RUNNER_TEMP 'cpack.exit' + $cpackId = Get-Content (Join-Path $env:RUNNER_TEMP 'cpack.pid') + while (-not (Test-Path $exit)) { + if (-not (Get-Process -Id $cpackId -ErrorAction SilentlyContinue) -and -not (Test-Path $exit)) { + throw 'cpack stopped without leaving an exit code.' + } + Start-Sleep -Seconds 5 + } + Get-Content (Join-Path $env:RUNNER_TEMP 'cpack.log') + if ((Get-Content $exit) -ne '0') { # makensis writes its errors, and the signing hook's output, only to this log. Get-Content _CPack_Packages/*/NSIS/NSISOutput.log -Tail 80 exit 1 @@ -660,18 +702,6 @@ jobs: } ./scripts/sign_windows.ps1 -Verify -Path $paths - - name: Pack app - if: runner.os == 'Windows' - working-directory: ${{ github.workspace }}/${{ env.BUILD_DIR }} - shell: cmd - run: '"C:/Program Files/7-Zip/7z.exe" a -tzip OrcaSlicer_Windows_${{ env.ver }}${{ env.ARCH_SUFFIX }}_portable.zip ${{ github.workspace }}/${{ env.BUILD_DIR }}/OrcaSlicer' - - - name: Pack PDB - if: runner.os == 'Windows' && inputs.arch != 'arm64' && !vars.SELF_HOSTED - working-directory: ${{ github.workspace }}/${{ env.BUILD_DIR }}/src/Release - shell: cmd - run: '"C:/Program Files/7-Zip/7z.exe" a -m0=lzma2 -mx9 Debug_PDB_${{ env.ver }}_for_developers_only.7z *.pdb' - - name: Upload artifacts Win zip if: runner.os == 'Windows' uses: actions/upload-artifact@v7 From 4b161be15085f578638752dc891b2795ee6861d3 Mon Sep 17 00:00:00 2001 From: Ian Chua Date: Mon, 16 Nov 2026 18:55:18 +0800 Subject: [PATCH 15/60] fix: prevent oversized AMS mapping popup on Wayland (#17606) --- src/slic3r/GUI/AmsMappingPopup.cpp | 49 +++++++++++++++--------------- 1 file changed, 24 insertions(+), 25 deletions(-) diff --git a/src/slic3r/GUI/AmsMappingPopup.cpp b/src/slic3r/GUI/AmsMappingPopup.cpp index ad657f35b3..3a76ed75a9 100644 --- a/src/slic3r/GUI/AmsMappingPopup.cpp +++ b/src/slic3r/GUI/AmsMappingPopup.cpp @@ -35,6 +35,9 @@ #include "slic3r/GUI/DeviceCore/DevDefs.h" #include "slic3r/GUI/wxExtensions.hpp" #include "slic3r/GUI/GUI_Utils.hpp" +#ifdef __WXGTK__ +#include "LinuxDisplayBackend.hpp" +#endif #include "slic3r/GUI/Widgets/SwitchButton.hpp" #include #include "slic3r/GUI/Widgets/AMSItem.hpp" @@ -1018,31 +1021,24 @@ AmsMapingPopup::AmsMapingPopup(wxWindow *parent, bool use_in_sync_dialog) : wxRect screen_size = wxDisplay(display_idx).GetClientArea(); auto parent_size = m_parent_item->GetRect(); - auto content_size = m_sizer_main_h->GetMinSize(); - int popup_width = content_size.x + FromDIP(28); - int popup_height = content_size.y; - wxSize popup_size(popup_width, popup_height); + auto content_size = m_sizer_main_h->GetMinSize(); + int popup_width = content_size.x + FromDIP(28); + int popup_height = content_size.y; + const int frame_padding = FromDIP(28); + const bool horizontal_scroll = popup_width + frame_padding > screen_size.GetWidth(); + const int viewport_width = horizontal_scroll + ? std::max(screen_size.GetWidth() - frame_padding, 0) + : popup_width; + const int popup_total_width = viewport_width + frame_padding; + wxSize popup_size(popup_total_width, popup_height); - // Horizontal Direction Processing - if (show_pos.x + popup_size.x > screen_size.GetRight()) - { - show_pos.x = screen_size.GetRight() - popup_size.x; - } - - //if popup size bigger than screen - if (show_pos.x < screen_size.GetLeft()) - { - show_pos.x = screen_size.GetLeft(); - m_scrolled_window->SetMaxSize(wxSize(screen_size.GetWidth(), popup_height)); - m_scrolled_window->SetMinSize(wxSize(screen_size.GetWidth(), popup_height)); - m_scrolled_window->SetScrollRate(FromDIP(10), FromDIP(20)); - } - else - { - m_scrolled_window->SetMaxSize(wxSize(popup_width, popup_height)); - m_scrolled_window->SetMinSize(wxSize(popup_width, popup_height)); - m_scrolled_window->SetScrollRate(0, FromDIP(20)); - } + // Keep placement independent from content overflow. A tile anchor outside the + // display bounds must not make the scroll viewport as wide as the display. + const int max_show_x = std::max(screen_size.GetLeft(), screen_size.GetRight() - popup_total_width); + show_pos.x = std::clamp(show_pos.x, screen_size.GetLeft(), max_show_x); + m_scrolled_window->SetMaxSize(wxSize(viewport_width, popup_height)); + m_scrolled_window->SetMinSize(wxSize(viewport_width, popup_height)); + m_scrolled_window->SetScrollRate(horizontal_scroll ? FromDIP(10) : 0, FromDIP(20)); //Vertical Direction Processing int available_height_below = screen_size.GetBottom() - (show_pos.y + parent_size.height); @@ -1075,7 +1071,10 @@ AmsMapingPopup::AmsMapingPopup(wxWindow *parent, bool use_in_sync_dialog) : } Layout(); Fit(); - this->Move(show_pos); +#if defined(__WXGTK__) + if (!is_running_on_wayland()) +#endif + this->Move(show_pos); } }); } From 59acdedd065e5213445163a581947353d3208ccd Mon Sep 17 00:00:00 2001 From: HanifKoh <76276251+HanifKoh@users.noreply.github.com> Date: Mon, 16 Nov 2026 19:30:35 +0800 Subject: [PATCH 16/60] Keep Heavy Boost and Plugin Headers Out of Widely Included Headers (#17494) * Keep Heavy Boost and Plugin Headers Out of Widely Included Headers Several headers that most of the code includes pulled in large libraries they barely use, so hundreds of files compiled them for nothing: - Point.hpp, Line.hpp, Polygon.hpp and ExPolygon.hpp included all of Boost.Polygon to declare traits. Point and Line now include only the concept headers they need, and the polygon traits move to BoostPolygonTraits.hpp, included by BridgeDetector.cpp, the one file that runs Boost.Polygon algorithms on polygons. - ProjectTask.hpp included Boost.Thread and the filesystem streams but only uses boost::filesystem::path. - Utils.hpp included Boost.DateTime for one inline function, which moves to utils.cpp. - Semver.hpp used boost::format for two version strings; std::to_string prints the same. - MainFrame.hpp held PluginPages by value, which brought in the web view and plugin headers; it now holds it by unique_ptr. - Model.hpp included STEP.hpp, and with it OpenCASCADE, for a forward-declarable type and two typedefs. Files that relied on these headers arriving indirectly now include what they use. * Include What the Polygon Traits and the End-Time Helper Use * Drop Two Unneeded Includes and Include the Filesystem Directory Header --- src/libslic3r/BoostPolygonTraits.hpp | 195 +++++++++++++++++++ src/libslic3r/BridgeDetector.cpp | 1 + src/libslic3r/BuildVolume.cpp | 1 + src/libslic3r/CMakeLists.txt | 1 + src/libslic3r/ExPolygon.hpp | 104 ---------- src/libslic3r/Flow.cpp | 1 + src/libslic3r/Format/3mf.cpp | 1 + src/libslic3r/Format/bbs_3mf.cpp | 4 + src/libslic3r/GCode.cpp | 1 + src/libslic3r/GCode/Thumbnails.hpp | 1 + src/libslic3r/GCodeReader.cpp | 1 + src/libslic3r/Line.hpp | 3 +- src/libslic3r/Model.cpp | 1 + src/libslic3r/Model.hpp | 8 +- src/libslic3r/Point.hpp | 3 +- src/libslic3r/Polygon.hpp | 83 -------- src/libslic3r/PresetBundle.cpp | 1 + src/libslic3r/PrintApply.cpp | 1 + src/libslic3r/PrintBase.cpp | 1 + src/libslic3r/ProjectTask.hpp | 3 - src/libslic3r/Semver.hpp | 5 +- src/libslic3r/Utils.hpp | 22 +-- src/libslic3r/utils.cpp | 18 ++ src/slic3r/GUI/3DBed.cpp | 1 + src/slic3r/GUI/ActionRegistry.cpp | 1 + src/slic3r/GUI/DeviceCore/DevFan.cpp | 1 + src/slic3r/GUI/Field.cpp | 1 + src/slic3r/GUI/FilamentGroupPopup.cpp | 1 + src/slic3r/GUI/GUI_Factories.cpp | 1 + src/slic3r/GUI/GUI_ObjectTable.cpp | 1 + src/slic3r/GUI/GUI_ObjectTableSettings.cpp | 1 + src/slic3r/GUI/GUI_Preview.cpp | 1 + src/slic3r/GUI/Gizmos/GLGizmoPainterBase.cpp | 1 + src/slic3r/GUI/MainFrame.cpp | 10 +- src/slic3r/GUI/MainFrame.hpp | 7 +- src/slic3r/GUI/NetworkTestDialog.cpp | 1 + src/slic3r/GUI/ObjectDataViewModel.cpp | 1 + src/slic3r/GUI/ParamsPanel.cpp | 1 + src/slic3r/GUI/PhysicalPrinterDialog.cpp | 1 + src/slic3r/GUI/Plater.cpp | 1 + src/slic3r/GUI/Preferences.cpp | 1 + src/slic3r/GUI/PresetBundleDialog.hpp | 2 +- src/slic3r/GUI/PrinterWebView.cpp | 1 + src/slic3r/GUI/SafetyOptionsDialog.cpp | 1 + src/slic3r/GUI/Selection.cpp | 1 + src/slic3r/GUI/Widgets/Label.cpp | 1 + src/slic3r/GUI/wxExtensions.cpp | 1 + src/slic3r/Utils/PrintHost.cpp | 1 + src/slic3r/Utils/UndoRedo.cpp | 1 + tests/libslic3r/test_semver.cpp | 19 ++ 50 files changed, 296 insertions(+), 225 deletions(-) create mode 100644 src/libslic3r/BoostPolygonTraits.hpp diff --git a/src/libslic3r/BoostPolygonTraits.hpp b/src/libslic3r/BoostPolygonTraits.hpp new file mode 100644 index 0000000000..786106d819 --- /dev/null +++ b/src/libslic3r/BoostPolygonTraits.hpp @@ -0,0 +1,195 @@ +#pragma once + +// Boost.Polygon traits for Polygon, Polygons, ExPolygon and ExPolygons, for the code that runs +// Boost.Polygon algorithms on them. The point and segment traits stay in Point.hpp and Line.hpp. +// Kept apart because boost/polygon/polygon.hpp is costly to parse in every file. + +#include + +#include + +#include "ExPolygon.hpp" +#include "Point.hpp" +#include "Polygon.hpp" +#include "libslic3r.h" + +namespace boost { namespace polygon { + template <> + struct geometry_concept{ typedef polygon_concept type; }; + + template <> + struct polygon_traits { + typedef coord_t coordinate_type; + typedef Slic3r::Points::const_iterator iterator_type; + typedef Slic3r::Point point_type; + + // Get the begin iterator + static inline iterator_type begin_points(const Slic3r::Polygon& t) { + return t.points.begin(); + } + + // Get the end iterator + static inline iterator_type end_points(const Slic3r::Polygon& t) { + return t.points.end(); + } + + // Get the number of sides of the polygon + static inline std::size_t size(const Slic3r::Polygon& t) { + return t.points.size(); + } + + // Get the winding direction of the polygon + static inline winding_direction winding(const Slic3r::Polygon& /* t */) { + return unknown_winding; + } + }; + + template <> + struct polygon_mutable_traits { + // expects stl style iterators + template + static inline Slic3r::Polygon& set_points(Slic3r::Polygon& polygon, iT input_begin, iT input_end) { + polygon.points.clear(); + while (input_begin != input_end) { + polygon.points.push_back(Slic3r::Point()); + boost::polygon::assign(polygon.points.back(), *input_begin); + ++input_begin; + } + // skip last point since Boost will set last point = first point + polygon.points.pop_back(); + return polygon; + } + }; + + template <> + struct geometry_concept { typedef polygon_set_concept type; }; + + //next we map to the concept through traits + template <> + struct polygon_set_traits { + typedef coord_t coordinate_type; + typedef Slic3r::Polygons::const_iterator iterator_type; + typedef Slic3r::Polygons operator_arg_type; + + static inline iterator_type begin(const Slic3r::Polygons& polygon_set) { + return polygon_set.begin(); + } + + static inline iterator_type end(const Slic3r::Polygons& polygon_set) { + return polygon_set.end(); + } + + //don't worry about these, just return false from them + static inline bool clean(const Slic3r::Polygons& /* polygon_set */) { return false; } + static inline bool sorted(const Slic3r::Polygons& /* polygon_set */) { return false; } + }; + + template <> + struct polygon_set_mutable_traits { + template + static inline void set(Slic3r::Polygons& polygons, input_iterator_type input_begin, input_iterator_type input_end) { + polygons.assign(input_begin, input_end); + } + }; +} } + +namespace boost { namespace polygon { + template <> + struct polygon_traits { + typedef coord_t coordinate_type; + typedef Slic3r::Points::const_iterator iterator_type; + typedef Slic3r::Point point_type; + + // Get the begin iterator + static inline iterator_type begin_points(const Slic3r::ExPolygon& t) { + return t.contour.points.begin(); + } + + // Get the end iterator + static inline iterator_type end_points(const Slic3r::ExPolygon& t) { + return t.contour.points.end(); + } + + // Get the number of sides of the polygon + static inline std::size_t size(const Slic3r::ExPolygon& t) { + return t.contour.points.size(); + } + + // Get the winding direction of the polygon + static inline winding_direction winding(const Slic3r::ExPolygon& /* t */) { + return unknown_winding; + } + }; + + template <> + struct polygon_mutable_traits { + //expects stl style iterators + template + static inline Slic3r::ExPolygon& set_points(Slic3r::ExPolygon& expolygon, iT input_begin, iT input_end) { + expolygon.contour.points.assign(input_begin, input_end); + // skip last point since Boost will set last point = first point + expolygon.contour.points.pop_back(); + return expolygon; + } + }; + + + template <> + struct geometry_concept { typedef polygon_with_holes_concept type; }; + + template <> + struct polygon_with_holes_traits { + typedef Slic3r::Polygons::const_iterator iterator_holes_type; + typedef Slic3r::Polygon hole_type; + static inline iterator_holes_type begin_holes(const Slic3r::ExPolygon& t) { + return t.holes.begin(); + } + static inline iterator_holes_type end_holes(const Slic3r::ExPolygon& t) { + return t.holes.end(); + } + static inline unsigned int size_holes(const Slic3r::ExPolygon& t) { + return (int)t.holes.size(); + } + }; + + template <> + struct polygon_with_holes_mutable_traits { + template + static inline Slic3r::ExPolygon& set_holes(Slic3r::ExPolygon& t, iT inputBegin, iT inputEnd) { + t.holes.assign(inputBegin, inputEnd); + return t; + } + }; + + //first we register CPolygonSet as a polygon set + template <> + struct geometry_concept { typedef polygon_set_concept type; }; + + //next we map to the concept through traits + template <> + struct polygon_set_traits { + typedef coord_t coordinate_type; + typedef Slic3r::ExPolygons::const_iterator iterator_type; + typedef Slic3r::ExPolygons operator_arg_type; + + static inline iterator_type begin(const Slic3r::ExPolygons& polygon_set) { + return polygon_set.begin(); + } + + static inline iterator_type end(const Slic3r::ExPolygons& polygon_set) { + return polygon_set.end(); + } + + //don't worry about these, just return false from them + static inline bool clean(const Slic3r::ExPolygons& /* polygon_set */) { return false; } + static inline bool sorted(const Slic3r::ExPolygons& /* polygon_set */) { return false; } + }; + + template <> + struct polygon_set_mutable_traits { + template + static inline void set(Slic3r::ExPolygons& expolygons, input_iterator_type input_begin, input_iterator_type input_end) { + expolygons.assign(input_begin, input_end); + } + }; +} } diff --git a/src/libslic3r/BridgeDetector.cpp b/src/libslic3r/BridgeDetector.cpp index ad1b8bb6fb..20f0f48eae 100644 --- a/src/libslic3r/BridgeDetector.cpp +++ b/src/libslic3r/BridgeDetector.cpp @@ -1,4 +1,5 @@ #include "BridgeDetector.hpp" +#include "BoostPolygonTraits.hpp" #include "BoundingBox.hpp" #include "ClipperUtils.hpp" #include "ExPolygon.hpp" diff --git a/src/libslic3r/BuildVolume.cpp b/src/libslic3r/BuildVolume.cpp index eb5a447249..29a583bef8 100644 --- a/src/libslic3r/BuildVolume.cpp +++ b/src/libslic3r/BuildVolume.cpp @@ -12,6 +12,7 @@ #include #include +#include #include #include #include diff --git a/src/libslic3r/CMakeLists.txt b/src/libslic3r/CMakeLists.txt index afc1b8df88..b18c3590ab 100644 --- a/src/libslic3r/CMakeLists.txt +++ b/src/libslic3r/CMakeLists.txt @@ -81,6 +81,7 @@ set(lisbslic3r_sources Arrange.hpp BlacklistedLibraryCheck.cpp BlacklistedLibraryCheck.hpp + BoostPolygonTraits.hpp BoundingBox.cpp BoundingBox.hpp BridgeDetector.cpp diff --git a/src/libslic3r/ExPolygon.hpp b/src/libslic3r/ExPolygon.hpp index 5df348281a..276419308c 100644 --- a/src/libslic3r/ExPolygon.hpp +++ b/src/libslic3r/ExPolygon.hpp @@ -516,108 +516,4 @@ bool remove_small_and_small_holes(ExPolygons &expolygons, double min_area } // namespace Slic3r -// start Boost -#include -namespace boost { namespace polygon { - template <> - struct polygon_traits { - typedef coord_t coordinate_type; - typedef Slic3r::Points::const_iterator iterator_type; - typedef Slic3r::Point point_type; - - // Get the begin iterator - static inline iterator_type begin_points(const Slic3r::ExPolygon& t) { - return t.contour.points.begin(); - } - - // Get the end iterator - static inline iterator_type end_points(const Slic3r::ExPolygon& t) { - return t.contour.points.end(); - } - - // Get the number of sides of the polygon - static inline std::size_t size(const Slic3r::ExPolygon& t) { - return t.contour.points.size(); - } - - // Get the winding direction of the polygon - static inline winding_direction winding(const Slic3r::ExPolygon& /* t */) { - return unknown_winding; - } - }; - - template <> - struct polygon_mutable_traits { - //expects stl style iterators - template - static inline Slic3r::ExPolygon& set_points(Slic3r::ExPolygon& expolygon, iT input_begin, iT input_end) { - expolygon.contour.points.assign(input_begin, input_end); - // skip last point since Boost will set last point = first point - expolygon.contour.points.pop_back(); - return expolygon; - } - }; - - - template <> - struct geometry_concept { typedef polygon_with_holes_concept type; }; - - template <> - struct polygon_with_holes_traits { - typedef Slic3r::Polygons::const_iterator iterator_holes_type; - typedef Slic3r::Polygon hole_type; - static inline iterator_holes_type begin_holes(const Slic3r::ExPolygon& t) { - return t.holes.begin(); - } - static inline iterator_holes_type end_holes(const Slic3r::ExPolygon& t) { - return t.holes.end(); - } - static inline unsigned int size_holes(const Slic3r::ExPolygon& t) { - return (int)t.holes.size(); - } - }; - - template <> - struct polygon_with_holes_mutable_traits { - template - static inline Slic3r::ExPolygon& set_holes(Slic3r::ExPolygon& t, iT inputBegin, iT inputEnd) { - t.holes.assign(inputBegin, inputEnd); - return t; - } - }; - - //first we register CPolygonSet as a polygon set - template <> - struct geometry_concept { typedef polygon_set_concept type; }; - - //next we map to the concept through traits - template <> - struct polygon_set_traits { - typedef coord_t coordinate_type; - typedef Slic3r::ExPolygons::const_iterator iterator_type; - typedef Slic3r::ExPolygons operator_arg_type; - - static inline iterator_type begin(const Slic3r::ExPolygons& polygon_set) { - return polygon_set.begin(); - } - - static inline iterator_type end(const Slic3r::ExPolygons& polygon_set) { - return polygon_set.end(); - } - - //don't worry about these, just return false from them - static inline bool clean(const Slic3r::ExPolygons& /* polygon_set */) { return false; } - static inline bool sorted(const Slic3r::ExPolygons& /* polygon_set */) { return false; } - }; - - template <> - struct polygon_set_mutable_traits { - template - static inline void set(Slic3r::ExPolygons& expolygons, input_iterator_type input_begin, input_iterator_type input_end) { - expolygons.assign(input_begin, input_end); - } - }; -} } -// end Boost - #endif diff --git a/src/libslic3r/Flow.cpp b/src/libslic3r/Flow.cpp index b9cc86d404..26a8cffa94 100644 --- a/src/libslic3r/Flow.cpp +++ b/src/libslic3r/Flow.cpp @@ -7,6 +7,7 @@ #include #include +#include #include #include #include "PrintConfig.hpp" diff --git a/src/libslic3r/Format/3mf.cpp b/src/libslic3r/Format/3mf.cpp index 723746ffa2..030da53a9d 100644 --- a/src/libslic3r/Format/3mf.cpp +++ b/src/libslic3r/Format/3mf.cpp @@ -53,6 +53,7 @@ #include #include #include +#include #include #include #include diff --git a/src/libslic3r/Format/bbs_3mf.cpp b/src/libslic3r/Format/bbs_3mf.cpp index 4d56e7090f..d51543de65 100644 --- a/src/libslic3r/Format/bbs_3mf.cpp +++ b/src/libslic3r/Format/bbs_3mf.cpp @@ -91,6 +91,10 @@ #include #include #include +#include +#include +#include +#include #include #include #include diff --git a/src/libslic3r/GCode.cpp b/src/libslic3r/GCode.cpp index b5864701e9..77c9c0a7f2 100644 --- a/src/libslic3r/GCode.cpp +++ b/src/libslic3r/GCode.cpp @@ -103,6 +103,7 @@ #include #include #include +#include #include "SVG.hpp" diff --git a/src/libslic3r/GCode/Thumbnails.hpp b/src/libslic3r/GCode/Thumbnails.hpp index bbe8039d80..da7679fb30 100644 --- a/src/libslic3r/GCode/Thumbnails.hpp +++ b/src/libslic3r/GCode/Thumbnails.hpp @@ -13,6 +13,7 @@ #include #include +#include #include namespace Slic3r { class ConfigBase; } diff --git a/src/libslic3r/GCodeReader.cpp b/src/libslic3r/GCodeReader.cpp index 1b545f86b5..0d169b8413 100644 --- a/src/libslic3r/GCodeReader.cpp +++ b/src/libslic3r/GCodeReader.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include diff --git a/src/libslic3r/Line.hpp b/src/libslic3r/Line.hpp index f75ef7fc66..10c0d1627f 100644 --- a/src/libslic3r/Line.hpp +++ b/src/libslic3r/Line.hpp @@ -322,7 +322,8 @@ BoundingBox get_extents(const Lines &lines); } // namespace Slic3r // start Boost -#include +#include +#include namespace boost { namespace polygon { template <> struct geometry_concept { typedef segment_concept type; }; diff --git a/src/libslic3r/Model.cpp b/src/libslic3r/Model.cpp index e9a0067350..0ef98d09bd 100644 --- a/src/libslic3r/Model.cpp +++ b/src/libslic3r/Model.cpp @@ -61,6 +61,7 @@ #include #include #include +#include #include "SVG.hpp" #include diff --git a/src/libslic3r/Model.hpp b/src/libslic3r/Model.hpp index b607e5eb20..7d981a3062 100644 --- a/src/libslic3r/Model.hpp +++ b/src/libslic3r/Model.hpp @@ -25,8 +25,6 @@ //BBS: add bbs 3mf #include "Format/bbs_3mf.hpp" -//BBS: add step -#include "Format/STEP.hpp" //BBS: add stl #include "Format/STL.hpp" #include "Format/OBJ.hpp" @@ -79,6 +77,12 @@ class BBLProject; class KeyStore; struct MeshRepairStats; +// From Format/STEP.hpp, which pulls in OpenCASCADE; declared here so only STEP code includes it. +// The typedefs must stay identical to the ones there. +class Step; +typedef std::function ImportStepProgressFn; +typedef std::function StepIsUtf8Fn; + namespace UndoRedo { class StackImpl; } diff --git a/src/libslic3r/Point.hpp b/src/libslic3r/Point.hpp index 6b8c1a81d7..7d4bc29fdf 100644 --- a/src/libslic3r/Point.hpp +++ b/src/libslic3r/Point.hpp @@ -785,7 +785,8 @@ namespace std { // start Boost #include -#include +#include +#include namespace boost { namespace polygon { template <> struct geometry_concept { using type = point_concept; }; diff --git a/src/libslic3r/Polygon.hpp b/src/libslic3r/Polygon.hpp index 9c5801985e..17be078211 100644 --- a/src/libslic3r/Polygon.hpp +++ b/src/libslic3r/Polygon.hpp @@ -312,87 +312,4 @@ using PolygonPoints = std::vector; bool overlaps(const Polygons& polys1, const Polygons& polys2); } // Slic3r -// start Boost -#include -namespace boost { namespace polygon { - template <> - struct geometry_concept{ typedef polygon_concept type; }; - - template <> - struct polygon_traits { - typedef coord_t coordinate_type; - typedef Slic3r::Points::const_iterator iterator_type; - typedef Slic3r::Point point_type; - - // Get the begin iterator - static inline iterator_type begin_points(const Slic3r::Polygon& t) { - return t.points.begin(); - } - - // Get the end iterator - static inline iterator_type end_points(const Slic3r::Polygon& t) { - return t.points.end(); - } - - // Get the number of sides of the polygon - static inline std::size_t size(const Slic3r::Polygon& t) { - return t.points.size(); - } - - // Get the winding direction of the polygon - static inline winding_direction winding(const Slic3r::Polygon& /* t */) { - return unknown_winding; - } - }; - - template <> - struct polygon_mutable_traits { - // expects stl style iterators - template - static inline Slic3r::Polygon& set_points(Slic3r::Polygon& polygon, iT input_begin, iT input_end) { - polygon.points.clear(); - while (input_begin != input_end) { - polygon.points.push_back(Slic3r::Point()); - boost::polygon::assign(polygon.points.back(), *input_begin); - ++input_begin; - } - // skip last point since Boost will set last point = first point - polygon.points.pop_back(); - return polygon; - } - }; - - template <> - struct geometry_concept { typedef polygon_set_concept type; }; - - //next we map to the concept through traits - template <> - struct polygon_set_traits { - typedef coord_t coordinate_type; - typedef Slic3r::Polygons::const_iterator iterator_type; - typedef Slic3r::Polygons operator_arg_type; - - static inline iterator_type begin(const Slic3r::Polygons& polygon_set) { - return polygon_set.begin(); - } - - static inline iterator_type end(const Slic3r::Polygons& polygon_set) { - return polygon_set.end(); - } - - //don't worry about these, just return false from them - static inline bool clean(const Slic3r::Polygons& /* polygon_set */) { return false; } - static inline bool sorted(const Slic3r::Polygons& /* polygon_set */) { return false; } - }; - - template <> - struct polygon_set_mutable_traits { - template - static inline void set(Slic3r::Polygons& polygons, input_iterator_type input_begin, input_iterator_type input_end) { - polygons.assign(input_begin, input_end); - } - }; -} } -// end Boost - #endif diff --git a/src/libslic3r/PresetBundle.cpp b/src/libslic3r/PresetBundle.cpp index 91f1ffdc18..a6ea1347bb 100644 --- a/src/libslic3r/PresetBundle.cpp +++ b/src/libslic3r/PresetBundle.cpp @@ -81,6 +81,7 @@ #include #include #include +#include #include #include #include diff --git a/src/libslic3r/PrintApply.cpp b/src/libslic3r/PrintApply.cpp index dd5f447574..233eeb580a 100644 --- a/src/libslic3r/PrintApply.cpp +++ b/src/libslic3r/PrintApply.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include diff --git a/src/libslic3r/PrintBase.cpp b/src/libslic3r/PrintBase.cpp index 7b022c8c84..a749c27cf5 100644 --- a/src/libslic3r/PrintBase.cpp +++ b/src/libslic3r/PrintBase.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include diff --git a/src/libslic3r/ProjectTask.hpp b/src/libslic3r/ProjectTask.hpp index 96e3cd2d7a..febc864bed 100644 --- a/src/libslic3r/ProjectTask.hpp +++ b/src/libslic3r/ProjectTask.hpp @@ -6,10 +6,7 @@ #include #include #include -#include -#include #include -#include namespace Slic3r { diff --git a/src/libslic3r/Semver.hpp b/src/libslic3r/Semver.hpp index 7c79f404ce..ec90bd92eb 100644 --- a/src/libslic3r/Semver.hpp +++ b/src/libslic3r/Semver.hpp @@ -10,7 +10,6 @@ #include #include #include -#include #include #include "semver/semver.h" @@ -160,7 +159,7 @@ public: std::string res; int patch_1 = ver.patch/100; int patch_2 = ver.patch%100; - res = (boost::format("%1%.%2%.%3%.%4%") % ver.major % ver.minor % patch_1 % patch_2).str(); + res = std::to_string(ver.major) + "." + std::to_string(ver.minor) + "." + std::to_string(patch_1) + "." + std::to_string(patch_2); if (ver.prerelease != nullptr) { res += '-'; res += ver.prerelease; } if (ver.metadata != nullptr) { res += '+'; res += ver.metadata; } @@ -169,7 +168,7 @@ public: std::string to_string_sf() const { //BBS: version format std::string res; - res = (boost::format("%1%.%2%.%3%") % ver.major % ver.minor % ver.patch).str(); + res = std::to_string(ver.major) + "." + std::to_string(ver.minor) + "." + std::to_string(ver.patch); if (ver.prerelease != nullptr) { res += '-'; res += ver.prerelease; } if (ver.metadata != nullptr) { res += '+'; res += ver.metadata; } diff --git a/src/libslic3r/Utils.hpp b/src/libslic3r/Utils.hpp index 290d7755a6..1fe3d354c0 100644 --- a/src/libslic3r/Utils.hpp +++ b/src/libslic3r/Utils.hpp @@ -7,9 +7,6 @@ #include #include #include -#include -#include -#include #include #include #include @@ -26,10 +23,8 @@ #include #include -#include +#include #include -#include -#include "boost/date_time/posix_time/ptime.hpp" #include #include @@ -741,20 +736,7 @@ inline std::string get_bbl_monitor_time_dhm(float time_in_secs) return buffer; } -inline std::string get_bbl_monitor_end_time_dhm(float time_in_secs) -{ - if (time_in_secs == 0.0f) - return {}; - - std::stringstream stream; - boost::posix_time::ptime now = boost::posix_time::second_clock::local_time(); - auto endTime = now + boost::posix_time::seconds(static_cast(time_in_secs)); - auto facet = new boost::posix_time::time_facet("%H:%M");//%Y-%m-%d %H:%M:%S - stream.imbue(std::locale(std::locale::classic(), facet)); - stream << endTime; - - return stream.str(); -} +std::string get_bbl_monitor_end_time_dhm(float time_in_secs); inline std::string get_bbl_remain_time_dhms(float time_in_secs) { diff --git a/src/libslic3r/utils.cpp b/src/libslic3r/utils.cpp index 617e5c2aa2..c7c4ce5333 100644 --- a/src/libslic3r/utils.cpp +++ b/src/libslic3r/utils.cpp @@ -17,6 +17,9 @@ #include #include #include +#include +#include +#include #include #include #include @@ -1381,6 +1384,21 @@ bool is_shapes_dir(const std::string& dir) namespace Slic3r { +std::string get_bbl_monitor_end_time_dhm(float time_in_secs) +{ + if (time_in_secs == 0.0f) + return {}; + + std::stringstream stream; + boost::posix_time::ptime now = boost::posix_time::second_clock::local_time(); + auto endTime = now + boost::posix_time::seconds(static_cast(time_in_secs)); + auto facet = new boost::posix_time::time_facet("%H:%M");//%Y-%m-%d %H:%M:%S + stream.imbue(std::locale(std::locale::classic(), facet)); + stream << endTime; + + return stream.str(); +} + size_t get_utf8_sequence_length(const std::string& text, size_t pos) { assert(pos < text.size()); diff --git a/src/slic3r/GUI/3DBed.cpp b/src/slic3r/GUI/3DBed.cpp index d7fd871f27..c8d8aa90c0 100644 --- a/src/slic3r/GUI/3DBed.cpp +++ b/src/slic3r/GUI/3DBed.cpp @@ -22,6 +22,7 @@ #include #include +#include #include #include "slic3r/GUI/GLModel.hpp" #include diff --git a/src/slic3r/GUI/ActionRegistry.cpp b/src/slic3r/GUI/ActionRegistry.cpp index bb171a5c68..6aeaeba73e 100644 --- a/src/slic3r/GUI/ActionRegistry.cpp +++ b/src/slic3r/GUI/ActionRegistry.cpp @@ -1,4 +1,5 @@ #include "ActionRegistry.hpp" +#include "slic3r/plugin/host/PluginPages.hpp" #include "GUI.hpp" #include "GUI_App.hpp" diff --git a/src/slic3r/GUI/DeviceCore/DevFan.cpp b/src/slic3r/GUI/DeviceCore/DevFan.cpp index c4fc80116b..e1d32de0a2 100644 --- a/src/slic3r/GUI/DeviceCore/DevFan.cpp +++ b/src/slic3r/GUI/DeviceCore/DevFan.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include diff --git a/src/slic3r/GUI/Field.cpp b/src/slic3r/GUI/Field.cpp index 75449c843e..15427850bd 100644 --- a/src/slic3r/GUI/Field.cpp +++ b/src/slic3r/GUI/Field.cpp @@ -69,6 +69,7 @@ #include #include #include +#include #include #include "OG_CustomCtrl.hpp" #include "MsgDialog.hpp" diff --git a/src/slic3r/GUI/FilamentGroupPopup.cpp b/src/slic3r/GUI/FilamentGroupPopup.cpp index 9675aadf63..6436e437e2 100644 --- a/src/slic3r/GUI/FilamentGroupPopup.cpp +++ b/src/slic3r/GUI/FilamentGroupPopup.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include "slic3r/GUI/wxExtensions.hpp" diff --git a/src/slic3r/GUI/GUI_Factories.cpp b/src/slic3r/GUI/GUI_Factories.cpp index 4221b1cfa7..caf6cbfd20 100644 --- a/src/slic3r/GUI/GUI_Factories.cpp +++ b/src/slic3r/GUI/GUI_Factories.cpp @@ -50,6 +50,7 @@ #include "libslic3r/Point.hpp" #include #include +#include #include "slic3r/GUI/Tab.hpp" #include "ParamsPanel.hpp" #include "MsgDialog.hpp" diff --git a/src/slic3r/GUI/GUI_ObjectTable.cpp b/src/slic3r/GUI/GUI_ObjectTable.cpp index f64ac6794c..b158c40122 100644 --- a/src/slic3r/GUI/GUI_ObjectTable.cpp +++ b/src/slic3r/GUI/GUI_ObjectTable.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include "libslic3r/Config.hpp" #include #include diff --git a/src/slic3r/GUI/GUI_ObjectTableSettings.cpp b/src/slic3r/GUI/GUI_ObjectTableSettings.cpp index 310b49f2a7..9087902d00 100644 --- a/src/slic3r/GUI/GUI_ObjectTableSettings.cpp +++ b/src/slic3r/GUI/GUI_ObjectTableSettings.cpp @@ -29,6 +29,7 @@ #include "slic3r/GUI/Field.hpp" #include "slic3r/GUI/GUI.hpp" #include +#include #include #include diff --git a/src/slic3r/GUI/GUI_Preview.cpp b/src/slic3r/GUI/GUI_Preview.cpp index 3358715885..9fca3283e8 100644 --- a/src/slic3r/GUI/GUI_Preview.cpp +++ b/src/slic3r/GUI/GUI_Preview.cpp @@ -12,6 +12,7 @@ #include #include "libslic3r/Config.hpp" #include +#include #include "libslic3r/CustomGCode.hpp" #include #include diff --git a/src/slic3r/GUI/Gizmos/GLGizmoPainterBase.cpp b/src/slic3r/GUI/Gizmos/GLGizmoPainterBase.cpp index af0acefa03..f056eda3e7 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoPainterBase.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoPainterBase.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include "slic3r/GUI/GUI_App.hpp" diff --git a/src/slic3r/GUI/MainFrame.cpp b/src/slic3r/GUI/MainFrame.cpp index 7feed2ca47..79402a34be 100644 --- a/src/slic3r/GUI/MainFrame.cpp +++ b/src/slic3r/GUI/MainFrame.cpp @@ -1,4 +1,5 @@ #include "MainFrame.hpp" +#include "slic3r/plugin/host/PluginPages.hpp" #include #include "slic3r/GUI/Event.hpp" @@ -407,6 +408,7 @@ MainFrame::~MainFrame() = default; MainFrame::MainFrame() : DPIFrame(NULL, wxID_ANY, "", wxDefaultPosition, wxDefaultSize, BORDERLESS_FRAME_STYLE, "mainframe") + , m_plugin_pages(std::make_unique()) , m_printhost_queue_dlg(new PrintHostQueueDialog(this)) // BBS , m_recent_projects(18) @@ -1343,7 +1345,7 @@ void MainFrame::shutdown() m_idle.stop(); if (ProjectPanel* project = ProjectPanel::if_built()) project->shutdown(); - m_plugin_pages.shutdown(); + m_plugin_pages->shutdown(); if (m_plater != nullptr) m_plater->remove_dock_panes(); #ifdef SLIC3R_CAD @@ -1645,7 +1647,7 @@ void MainFrame::init_tabpanel() { // Plugin pages are appended after the built-in tabs; their ids are namespaced // (plugin..) so they can't collide with the built-in TAB_ID_* constants. - m_plugin_pages.initialize(m_tabpanel); + m_plugin_pages->initialize(m_tabpanel); if (m_plater) { // load initial config @@ -1724,7 +1726,7 @@ void MainFrame::show_device(bool should_use_native) { #endif // _MSW_DARK_MODE fit_tab_labels(); // ORCA on printer change - m_plugin_pages.relayout(); // re-sync plugin tabs against the native tabs just mutated above + m_plugin_pages->relayout(); // re-sync plugin tabs against the native tabs just mutated above if (m_prebuild_started) m_idle.start(); return; @@ -1784,7 +1786,7 @@ void MainFrame::show_device(bool should_use_native) { _L("Device"), "tab_monitor_active"); } fit_tab_labels(); // ORCA on printer change - m_plugin_pages.relayout(); // re-sync plugin tabs against the native tabs just mutated above + m_plugin_pages->relayout(); // re-sync plugin tabs against the native tabs just mutated above if (m_prebuild_started) m_idle.start(); } diff --git a/src/slic3r/GUI/MainFrame.hpp b/src/slic3r/GUI/MainFrame.hpp index d4ca99a5a2..69b5930e6e 100644 --- a/src/slic3r/GUI/MainFrame.hpp +++ b/src/slic3r/GUI/MainFrame.hpp @@ -34,7 +34,6 @@ #include -#include "slic3r/plugin/host/PluginPages.hpp" // Stable identifiers for MainFrame::m_tabpanel's built-in pages. These are // names rather than positional indices so optional pages cannot shift them. @@ -68,6 +67,8 @@ class wxProgressDialog; namespace Slic3r { +class PluginPages; + namespace GUI { @@ -497,7 +498,7 @@ public: void fit_tab_labels(); // ORCA // True while either of the two tabs backed by m_plater is selected. bool is_prepare_or_preview_tab() const; - PluginPages& plugin_pages() { return m_plugin_pages; } + PluginPages& plugin_pages() { return *m_plugin_pages; } PA_Calibration_Dlg* m_pa_calib_dlg{ nullptr }; FlowRateCalibrationDialog* m_flow_rate_calib_dlg{ nullptr }; @@ -533,7 +534,7 @@ public: LazyPage* m_calibration_page{ nullptr }; LazyPage* m_home_page { nullptr }; LazyPage* m_printer_view_page{nullptr}; - PluginPages m_plugin_pages; + std::unique_ptr m_plugin_pages; wxLogWindow* m_log_window { nullptr }; // BBS //wxBookCtrlBase* m_tabpanel { nullptr }; diff --git a/src/slic3r/GUI/NetworkTestDialog.cpp b/src/slic3r/GUI/NetworkTestDialog.cpp index 964004b67c..9cb92b15b9 100644 --- a/src/slic3r/GUI/NetworkTestDialog.cpp +++ b/src/slic3r/GUI/NetworkTestDialog.cpp @@ -9,6 +9,7 @@ #include "libslic3r/AppConfig.hpp" #include #include +#include #include #include #include diff --git a/src/slic3r/GUI/ObjectDataViewModel.cpp b/src/slic3r/GUI/ObjectDataViewModel.cpp index af4f61f320..c2a3ca620b 100644 --- a/src/slic3r/GUI/ObjectDataViewModel.cpp +++ b/src/slic3r/GUI/ObjectDataViewModel.cpp @@ -1,4 +1,5 @@ #include "ObjectDataViewModel.hpp" +#include #include "wxExtensions.hpp" #include "BitmapCache.hpp" #include "GUI_App.hpp" diff --git a/src/slic3r/GUI/ParamsPanel.cpp b/src/slic3r/GUI/ParamsPanel.cpp index 689fdd8ca8..f9510ea5d1 100644 --- a/src/slic3r/GUI/ParamsPanel.cpp +++ b/src/slic3r/GUI/ParamsPanel.cpp @@ -36,6 +36,7 @@ #include #include #include +#include #include #include diff --git a/src/slic3r/GUI/PhysicalPrinterDialog.cpp b/src/slic3r/GUI/PhysicalPrinterDialog.cpp index 121c109a10..0b11b38a8d 100644 --- a/src/slic3r/GUI/PhysicalPrinterDialog.cpp +++ b/src/slic3r/GUI/PhysicalPrinterDialog.cpp @@ -26,6 +26,7 @@ #include #include #include +#include #include #include diff --git a/src/slic3r/GUI/Plater.cpp b/src/slic3r/GUI/Plater.cpp index 4ff37b6157..72b6b6364a 100644 --- a/src/slic3r/GUI/Plater.cpp +++ b/src/slic3r/GUI/Plater.cpp @@ -1,4 +1,5 @@ #include "Plater.hpp" +#include "LazyPage.hpp" #include "../Utils/NetworkAgent.hpp" #include "IPrinterAgent.hpp" #include "CalibUtils.hpp" diff --git a/src/slic3r/GUI/Preferences.cpp b/src/slic3r/GUI/Preferences.cpp index 16a6b390b2..d5098715d8 100644 --- a/src/slic3r/GUI/Preferences.cpp +++ b/src/slic3r/GUI/Preferences.cpp @@ -1,4 +1,5 @@ #include "Preferences.hpp" +#include "slic3r/plugin/host/PluginPages.hpp" #include "CloudProvider.hpp" #include "ColorPickerDialog.hpp" #include "OptionsGroup.hpp" diff --git a/src/slic3r/GUI/PresetBundleDialog.hpp b/src/slic3r/GUI/PresetBundleDialog.hpp index 161aa43804..6632b65076 100644 --- a/src/slic3r/GUI/PresetBundleDialog.hpp +++ b/src/slic3r/GUI/PresetBundleDialog.hpp @@ -6,7 +6,7 @@ #include "Widgets/WebViewHostDialog.hpp" #include "libslic3r/AppConfig.hpp" #include -#include +#include #include #include #include diff --git a/src/slic3r/GUI/PrinterWebView.cpp b/src/slic3r/GUI/PrinterWebView.cpp index dd597ad38d..a870c12e23 100644 --- a/src/slic3r/GUI/PrinterWebView.cpp +++ b/src/slic3r/GUI/PrinterWebView.cpp @@ -17,6 +17,7 @@ #include #include +#include #include diff --git a/src/slic3r/GUI/SafetyOptionsDialog.cpp b/src/slic3r/GUI/SafetyOptionsDialog.cpp index 716b6ac5c4..394d1514ef 100644 --- a/src/slic3r/GUI/SafetyOptionsDialog.cpp +++ b/src/slic3r/GUI/SafetyOptionsDialog.cpp @@ -22,6 +22,7 @@ #include #include #include +#include #include static const wxColour STATIC_BOX_LINE_COL = wxColour(238, 238, 238); diff --git a/src/slic3r/GUI/Selection.cpp b/src/slic3r/GUI/Selection.cpp index 7209de73a0..e51eb396c9 100644 --- a/src/slic3r/GUI/Selection.cpp +++ b/src/slic3r/GUI/Selection.cpp @@ -48,6 +48,7 @@ #include #include +#include #include #include diff --git a/src/slic3r/GUI/Widgets/Label.cpp b/src/slic3r/GUI/Widgets/Label.cpp index 0e5d9eab43..b618a055e6 100644 --- a/src/slic3r/GUI/Widgets/Label.cpp +++ b/src/slic3r/GUI/Widgets/Label.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #ifdef __linux__ diff --git a/src/slic3r/GUI/wxExtensions.cpp b/src/slic3r/GUI/wxExtensions.cpp index ec7ff5ae70..95df57b6f2 100644 --- a/src/slic3r/GUI/wxExtensions.cpp +++ b/src/slic3r/GUI/wxExtensions.cpp @@ -27,6 +27,7 @@ #include #include #include +#include #include #include diff --git a/src/slic3r/Utils/PrintHost.cpp b/src/slic3r/Utils/PrintHost.cpp index c595d6c73c..479b3daaac 100644 --- a/src/slic3r/Utils/PrintHost.cpp +++ b/src/slic3r/Utils/PrintHost.cpp @@ -20,6 +20,7 @@ #include #include #include +#include #include #include diff --git a/src/slic3r/Utils/UndoRedo.cpp b/src/slic3r/Utils/UndoRedo.cpp index a326051d55..745e9913be 100644 --- a/src/slic3r/Utils/UndoRedo.cpp +++ b/src/slic3r/Utils/UndoRedo.cpp @@ -33,6 +33,7 @@ #include "slic3r/GUI/3DScene.hpp" #include +#include #ifndef NDEBUG // #define SLIC3R_UNDOREDO_DEBUG diff --git a/tests/libslic3r/test_semver.cpp b/tests/libslic3r/test_semver.cpp index 81abd967be..e3321eb50f 100644 --- a/tests/libslic3r/test_semver.cpp +++ b/tests/libslic3r/test_semver.cpp @@ -30,3 +30,22 @@ TEST_CASE("A dev build ranks above its alpha and beta and below its release", "[ TEST_CASE("Two dev builds of the same version are equal", "[Semver]") { CHECK(Semver("2.5.0-dev") == Semver("2.5.0-dev")); } + +TEST_CASE("Versions print with the patch split in two, or as three parts", "[Semver]") { + // to_string() prints the patch as patch / 100 and patch % 100; to_string_sf() prints it whole. + const Semver release(2, 5, 103); + CHECK(release.to_string() == "2.5.1.3"); + CHECK(release.to_string_sf() == "2.5.103"); + + const Semver dev(2, 6, 0, nullptr, "dev"); + CHECK(dev.to_string() == "2.6.0.0-dev"); + CHECK(dev.to_string_sf() == "2.6.0-dev"); + + const Semver large(10, 20, 1234); + CHECK(large.to_string() == "10.20.12.34"); + CHECK(large.to_string_sf() == "10.20.1234"); + + const Semver tagged(1, 2, 3, "build7"); + CHECK(tagged.to_string() == "1.2.0.3+build7"); + CHECK(tagged.to_string_sf() == "1.2.3+build7"); +} From c49e32c1e76e312838ef6c5b07bd5ec9f9d63bac Mon Sep 17 00:00:00 2001 From: Ian Bassi Date: Mon, 16 Nov 2026 17:55:09 -0300 Subject: [PATCH 17/60] =?UTF-8?q?Set=20feature=20speeds=20in=20mm=C2=B3/s?= =?UTF-8?q?=20or=20%=20of=20max=20volumetric=20speed=20(#16299)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/HLSD/volumetric-speeds.md | 106 +++++++++++ src/libslic3r/Fill/Fill.cpp | 32 +++- src/libslic3r/GCode.cpp | 259 +++++++++++++++----------- src/libslic3r/GCode.hpp | 8 + src/libslic3r/GCode/WipeTower.cpp | 3 + src/libslic3r/GCode/WipeTower.hpp | 5 + src/libslic3r/GCode/WipeTower2.cpp | 8 + src/libslic3r/GCode/WipeTower2.hpp | 13 ++ src/libslic3r/Layer.cpp | 3 + src/libslic3r/Preset.cpp | 15 +- src/libslic3r/Print.cpp | 4 + src/libslic3r/PrintConfig.cpp | 216 +++++++++++++++++++-- src/libslic3r/PrintConfig.hpp | 14 ++ src/libslic3r/PrintObject.cpp | 14 +- src/slic3r/GUI/ConfigManipulation.cpp | 18 +- src/slic3r/GUI/GUI_Factories.cpp | 13 +- src/slic3r/GUI/Plater.cpp | 2 + src/slic3r/GUI/Tab.cpp | 20 ++ tests/fff_print/test_gcode.cpp | 161 ++++++++++++++++ 19 files changed, 776 insertions(+), 138 deletions(-) create mode 100644 docs/HLSD/volumetric-speeds.md diff --git a/docs/HLSD/volumetric-speeds.md b/docs/HLSD/volumetric-speeds.md new file mode 100644 index 0000000000..243154e713 --- /dev/null +++ b/docs/HLSD/volumetric-speeds.md @@ -0,0 +1,106 @@ +# Volumetric speeds — High Level Design + +## Purpose + +A linear speed (mm/s) extrudes a different flow on every line whose cross section +differs: a wide gap fill line, an Arachne wall that widens, a thicker first layer +or an adaptive layer height all push more plastic at the same feed rate. Users who +tune a profile around the hotend's melting capacity think in mm³/s instead. + +Volumetric speeds let a process profile set the speed of each feature as a flow. +Each line is printed at that flow divided by its own cross section, so every line +of a feature extrudes the same flow whatever its width or height. + +## Settings + +`enable_volumetric_speeds` switches every feature at once. It is a global +`PrintConfig` option and is off by default, so existing profiles and projects +slice exactly as before. + +Each feature whose linear speed is an absolute value has a volumetric alternative, +`_volumetric_flow`: first layer, first layer infill, outer and inner +wall, sparse infill, internal solid infill, top surface, gap infill, support, +support interface, and external and internal bridges. Each one is a nullable +per-nozzle-variant vector in the same config class as its linear counterpart, so +the wall, infill, bridge and support flows can be overridden per object like +their speeds. A value is either absolute (mm³/s) or a percentage of the +`filament_max_volumetric_speed` of the filament printing the line. The filament +limit still caps the result, whichever form is used. + +The keys end in `_volumetric_flow` because `outer_wall_volumetric_speed` is +already a custom G-code placeholder that vendor change-filament G-code reads. + +Some speeds have no volumetric alternative and apply over the resolved speeds: + +- Small perimeter, small support perimeter, overhang and scarf joint speeds are + modifiers. A percentage is taken of the resolved feature speed, which is the + same as a percentage of its flow; an absolute value stays in mm/s. +- Ironing extrudes a small fraction of a full line, so a flow target would give + meaningless feed rates. +- Travel speeds and the skirt speed override do not extrude, or override the + feature speed outright. + +## Speed resolution + +`GCode::_extrude` resolves every feature speed through `GCode::feature_speed`, +which returns the linear speed, or with volumetric speeds the configured flow +divided by the path's flow. That flow is `GCode::extrusion_mm3_per_mm`: the +geometric flow times the print, filament and role flow ratios and the mixed-colour +sub-layer ratio. The E values and the filament limit use the same flow, so the +configured flow is the flow the printer extrudes. A path that extrudes nothing, +such as the move inward before an outer wall seam, keeps the linear speed. + +Speeds derived from a feature speed follow it: the first-layer speeds and the +interpolation over the slow-down layers, the overhang reference speeds, small +perimeters (resolved per path in `extrude_loop`), small support perimeters +(from the first path of each support entity) and the skirt and brim, which +`_extrude` prints at the support speed by role. + +Calibration prints set linear speeds, some of them per layer through the +calibration config, so `feature_speed` ignores volumetric speeds whenever +`Print::calib_mode()` is set. The flow rate calibration sets no calibration mode, +so its setup turns the option off in the print preset instead. + +## Max external volumetric speed + +`filament_max_external_volumetric_speed` is a per-variant filament option, 0 by +default, that caps the flow of the visible features below the filament's max +volumetric speed, with or without volumetric speeds. It applies to outer walls, +to what prints at the external bridge speed (bridge infill and overhang walls), +and to top surfaces on a layer where their region is not ironed. + +`GCode::volumetric_speed_limit` returns the flow limit of a path's role, and +`_extrude` uses it everywhere the filament limit used to cap a speed, including +the resonance-avoidance re-cap and the overhang reference speed. Resonance +avoidance moves an outer wall in the upper half of its band up to the band's top; +when the limit keeps the wall below that top, the wall drops to the band's bottom +instead, so the boost never exceeds the limit. Whether a top +surface is ironed follows `Layer::choose_ironing_extruder`, the rule the ironing +generator uses, so an ironed top surface keeps the higher limit. Calibration prints +ignore the option, as they do volumetric speeds. A volumetric speed in percent is +still a share of the filament's max volumetric speed, not of this limit. + +## Outside the G-code generator + +- Fill grouping and perimeter merging: `SurfaceFillParams` compares the + volumetric flow of the infill role next to its linear speed, and + `Layer::is_perimeter_compatible` compares the wall and gap fill flows. Both + compare them whether or not the option is on; that can only keep apart regions + whose volumetric values were overridden per object. +- Wipe towers borrow feature speeds: `WipeTower2` the sparse infill, inner wall and + first layer speeds, `WipeTower` the first layer speed. With volumetric speeds, + `set_layer` derives them from the configured flows and the tower's own line cross + section on that layer. A percentage uses the maximum volumetric speed of the + initial tool, as the linear values use its nozzle. +- The `outer_wall_volumetric_speed` placeholder reports the configured outer wall + flow, capped by the filament limit and the max external volumetric speed. +- Each key invalidates the same steps as its linear counterpart, except the gap + fill flow, which invalidates perimeters because perimeter merging compares it. + +## GUI + +The Speed page opens with a "Speed definition" group holding the switch, and each +volumetric row sits under its linear row (the bridge rows as a pair). +`ConfigManipulation::toggle_print_fff_options` shows exactly one row of each pair +through `toggle_line`, so the choice holds on every page, in the object settings +and in the Object Table, whose Speed category lists both keys of each pair. diff --git a/src/libslic3r/Fill/Fill.cpp b/src/libslic3r/Fill/Fill.cpp index d2d6bfb0f5..bde6919482 100644 --- a/src/libslic3r/Fill/Fill.cpp +++ b/src/libslic3r/Fill/Fill.cpp @@ -296,6 +296,8 @@ struct SurfaceFillParams size_t idx = 0; // Infill speed setting for the effective extrusion role. float role_speed = 0; + // Its volumetric alternative, used with enable_volumetric_speeds. + FloatOrPercent role_volumetric_flow; // Params for lattice infill angles float lateral_lattice_angle_1 = 0.f; @@ -352,6 +354,8 @@ struct SurfaceFillParams RETURN_COMPARE_NON_EQUAL_TYPED(unsigned, bridge); RETURN_COMPARE_NON_EQUAL_TYPED(unsigned, extrusion_role); RETURN_COMPARE_NON_EQUAL(role_speed); + RETURN_COMPARE_NON_EQUAL(role_volumetric_flow.value); + RETURN_COMPARE_NON_EQUAL_TYPED(unsigned, role_volumetric_flow.percent); RETURN_COMPARE_NON_EQUAL(lateral_lattice_angle_1); RETURN_COMPARE_NON_EQUAL(lateral_lattice_angle_2); RETURN_COMPARE_NON_EQUAL(symmetric_infill_y_axis); @@ -388,6 +392,7 @@ struct SurfaceFillParams this->flow == rhs.flow && this->extrusion_role == rhs.extrusion_role && this->role_speed == rhs.role_speed && + this->role_volumetric_flow == rhs.role_volumetric_flow && this->lateral_lattice_angle_1 == rhs.lateral_lattice_angle_1 && this->lateral_lattice_angle_2 == rhs.lateral_lattice_angle_2 && this->infill_lock_depth == rhs.infill_lock_depth && @@ -1073,16 +1078,23 @@ std::vector group_fills(const Layer &layer, LockRegionParam &lock_p layerm.flow(extrusion_role, (surface.thickness == -1) ? layer.height : surface.thickness); params.role_speed = 0; - if (params.extrusion_role == erBridgeInfill) - params.role_speed = region_config.bridge_speed.get_at(layer.get_extruder_id(params.extruder)); - else if (params.extrusion_role == erInternalBridgeInfill) - params.role_speed = region_config.get_abs_value_at("internal_bridge_speed", layer.get_extruder_id(params.extruder)); - else if (params.extrusion_role == erInternalInfill) - params.role_speed = region_config.sparse_infill_speed.get_at(layer.get_extruder_id(params.extruder)); - else if (params.extrusion_role == erTopSolidInfill) - params.role_speed = region_config.top_surface_speed.get_at(layer.get_extruder_id(params.extruder)); - else if (params.extrusion_role == erSolidInfill) - params.role_speed = region_config.internal_solid_infill_speed.get_at(layer.get_extruder_id(params.extruder)); + const size_t role_extruder_id = layer.get_extruder_id(params.extruder); + if (params.extrusion_role == erBridgeInfill) { + params.role_speed = region_config.bridge_speed.get_at(role_extruder_id); + params.role_volumetric_flow = region_config.bridge_volumetric_flow.get_at(role_extruder_id); + } else if (params.extrusion_role == erInternalBridgeInfill) { + params.role_speed = region_config.get_abs_value_at("internal_bridge_speed", role_extruder_id); + params.role_volumetric_flow = region_config.internal_bridge_volumetric_flow.get_at(role_extruder_id); + } else if (params.extrusion_role == erInternalInfill) { + params.role_speed = region_config.sparse_infill_speed.get_at(role_extruder_id); + params.role_volumetric_flow = region_config.sparse_infill_volumetric_flow.get_at(role_extruder_id); + } else if (params.extrusion_role == erTopSolidInfill) { + params.role_speed = region_config.top_surface_speed.get_at(role_extruder_id); + params.role_volumetric_flow = region_config.top_surface_volumetric_flow.get_at(role_extruder_id); + } else if (params.extrusion_role == erSolidInfill) { + params.role_speed = region_config.internal_solid_infill_speed.get_at(role_extruder_id); + params.role_volumetric_flow = region_config.internal_solid_infill_volumetric_flow.get_at(role_extruder_id); + } // Calculate flow spacing for infill pattern generation. if (surface.is_solid() || is_bridge) { params.spacing = params.flow.spacing(); diff --git a/src/libslic3r/GCode.cpp b/src/libslic3r/GCode.cpp index 77c9c0a7f2..09890f570f 100644 --- a/src/libslic3r/GCode.cpp +++ b/src/libslic3r/GCode.cpp @@ -762,6 +762,14 @@ static std::vector get_path_of_change_filament(const Print& print) static float get_outer_wall_volumetric_speed(const FullPrintConfig& config, const Print& print, int filament_id, int filament_variant_idx, int extruder_id) { float outer_wall_volumetric_speed = 0; float filament_max_volumetric_speed = config.filament_max_volumetric_speed.get_at(filament_variant_idx); + const bool calibrating = print.calib_mode() != CalibMode::Calib_None; + // Orca: the outer wall is also limited by the max external volumetric speed. + float max_volumetric_speed = filament_max_volumetric_speed; + if (const float max_external = float(config.filament_max_external_volumetric_speed.get_at(filament_variant_idx)); max_external > 0 && !calibrating) + max_volumetric_speed = std::min(max_volumetric_speed, max_external); + if (config.enable_volumetric_speeds && !calibrating) + return std::min(float(print.default_region_config().outer_wall_volumetric_flow.get_at(extruder_id).get_abs_value(filament_max_volumetric_speed)), + max_volumetric_speed); const double filament_diameter = config.filament_diameter.get_at(filament_id); float outer_wall_line_width = print.default_region_config().get_abs_value("outer_wall_line_width", filament_diameter); if (outer_wall_line_width == 0.0) { @@ -771,8 +779,8 @@ static std::vector get_path_of_change_filament(const Print& print) Flow outer_wall_flow = Flow(outer_wall_line_width, config.layer_height, config.nozzle_diameter.get_at(extruder_id)); float outer_wall_speed = print.default_region_config().outer_wall_speed.get_at(extruder_id); outer_wall_volumetric_speed = outer_wall_speed * outer_wall_flow.mm3_per_mm(); - if (outer_wall_volumetric_speed > filament_max_volumetric_speed) - outer_wall_volumetric_speed = filament_max_volumetric_speed; + if (outer_wall_volumetric_speed > max_volumetric_speed) + outer_wall_volumetric_speed = max_volumetric_speed; return outer_wall_volumetric_speed; } @@ -2174,6 +2182,8 @@ static std::vector get_path_of_change_filament(const Print& print) #define EXTRUDER_CONFIG(OPT) m_config.OPT.get_at(m_writer.filament()->extruder_id()) #define FILAMENT_CONFIG(OPT) m_config.OPT.get_at(get_filament_config_index(m_writer.filament()->id())) #define NOZZLE_CONFIG(OPT) m_config.OPT.get_at(get_nozzle_config_index(m_writer.filament()->id())) +// Speed of FEATURE (FEATURE_speed, or FEATURE_volumetric_flow with volumetric speeds) for a path of the given flow. +#define FEATURE_SPEED(FEATURE, MM3_PER_MM) feature_speed(NOZZLE_CONFIG(FEATURE##_speed), m_config.FEATURE##_volumetric_flow, MM3_PER_MM) void GCode::PlaceholderParserIntegration::reset() { @@ -5979,14 +5989,14 @@ std::string GCode::generate_skirt(const Print &print, path.mm3_per_mm = mm3_per_mm; } - //FIXME using the support_speed of the 1st object printed. + // _extrude() prints skirt paths at the support speed. if (first_layer && i==loops.first) { //set skirt start point location const Point desired_start_point = Skirt::find_start_point(loop, skirt_start_angle); - gcode += this->extrude_loop(loop, "skirt", NOZZLE_CONFIG(support_speed), {}, &desired_start_point); + gcode += this->extrude_loop(loop, "skirt", -1., {}, &desired_start_point); } else - gcode += this->extrude_loop(loop, "skirt", NOZZLE_CONFIG(support_speed)); + gcode += this->extrude_loop(loop, "skirt"); // If we only want a single wall on non-first layers, break now if (!first_layer && print.m_config.single_loop_draft_shield) { @@ -6072,7 +6082,7 @@ std::string GCode::generate_object_brim( m_avoid_crossing_perimeters.use_external_mp(); for (const ExtrusionEntity *ee : by_layer[layer_idx].entities) if (ee != nullptr) - gcode += this->extrude_entity(*ee, "brim", NOZZLE_CONFIG(support_speed)); + gcode += this->extrude_entity(*ee, "brim"); m_avoid_crossing_perimeters.use_external_mp(false); m_avoid_crossing_perimeters.disable_once(); return gcode; @@ -6102,7 +6112,7 @@ std::string GCode::generate_object_brim( m_avoid_crossing_perimeters.use_external_mp(); for (const ExtrusionEntity* ee : brim.entities) if (ee != nullptr) - gcode += this->extrude_entity(*ee, "brim", NOZZLE_CONFIG(support_speed)); + gcode += this->extrude_entity(*ee, "brim"); m_avoid_crossing_perimeters.use_external_mp(false); m_avoid_crossing_perimeters.disable_once(); for (const ObjectInstanceID& instance : instances) @@ -6301,7 +6311,7 @@ std::string GCode::emit_belt_brim_bands(const Print &print, m_avoid_crossing_perimeters.use_external_mp(); for (const ExtrusionEntity *ee : band->fills.entities) if (ee != nullptr) - gcode += this->extrude_entity(*ee, "brim", NOZZLE_CONFIG(support_speed)); + gcode += this->extrude_entity(*ee, "brim"); m_avoid_crossing_perimeters.use_external_mp(false); m_avoid_crossing_perimeters.disable_once(); } @@ -8608,13 +8618,7 @@ std::string GCode::extrude_loop(const ExtrusionLoop& loop_ if (paths.empty()) return ""; // SoftFever: check loop lenght for small perimeter. - double small_peri_speed = -1; - if (speed == -1 && loop.length() <= SMALL_PERIMETER_LENGTH(NOZZLE_CONFIG(small_perimeter_threshold))) { - if(NOZZLE_CONFIG(small_perimeter_speed).value == 0) - small_peri_speed = NOZZLE_CONFIG(outer_wall_speed) * 0.5; - else - small_peri_speed = NOZZLE_CONFIG(small_perimeter_speed).get_abs_value(NOZZLE_CONFIG(outer_wall_speed)); - } + const bool is_small_perimeter = speed == -1 && loop.length() <= SMALL_PERIMETER_LENGTH(NOZZLE_CONFIG(small_perimeter_threshold)); // extrude along the path std::string gcode; @@ -8693,10 +8697,16 @@ std::string GCode::extrude_loop(const ExtrusionLoop& loop_ } - const auto speed_for_path = [&speed, &small_peri_speed](const ExtrusionPath& path) { + const auto speed_for_path = [this, speed, is_small_perimeter](const ExtrusionPath& path) { // don't apply small perimeter setting for overhangs/bridges/non-perimeters - const bool is_small_small_perimeter = small_peri_speed > 0 && !is_bridge(path.role()) && is_perimeter(path.role()); - return is_small_small_perimeter ? small_peri_speed : speed; + if (!is_small_perimeter || is_bridge(path.role()) || !is_perimeter(path.role())) + return speed; + // The outer wall speed depends on the path's flow with volumetric speeds. + const double outer_wall_speed = FEATURE_SPEED(outer_wall, extrusion_mm3_per_mm(path, this->on_first_layer(path_slicing_point(path)))); + const FloatOrPercent &small_perimeter_speed = NOZZLE_CONFIG(small_perimeter_speed); + const double small_peri_speed = small_perimeter_speed.value == 0 ? outer_wall_speed * 0.5 : + small_perimeter_speed.get_abs_value(outer_wall_speed); + return small_peri_speed > 0 ? small_peri_speed : speed; }; @@ -9068,14 +9078,16 @@ std::string GCode::extrude_support(const ExtrusionEntityCollection &support_fill static constexpr const char* support_ironing_label = "support ironing"; // Not static: it captures `this` by reference. - const auto speed_for_path = [&](double length, ExtrusionRole role, double default_speed = -1.0) { + const auto speed_for_path = [&](double length, ExtrusionRole role, const ExtrusionPath *first_path, double default_speed = -1.0) { if (!is_support(role) || length > SMALL_PERIMETER_LENGTH(NOZZLE_CONFIG(small_support_perimeter_threshold))) return default_speed; double small_perimeter_speed = -1.0; + // The support speeds depend on the paths' flow with volumetric speeds. + const double mm3_per_mm = first_path ? extrusion_mm3_per_mm(*first_path, this->on_first_layer(path_slicing_point(*first_path))) : 0.; const auto base_speed = (role == erSupportMaterialInterface) - ? NOZZLE_CONFIG(support_interface_speed) : NOZZLE_CONFIG(support_speed); + ? FEATURE_SPEED(support_interface, mm3_per_mm) : FEATURE_SPEED(support, mm3_per_mm); if (NOZZLE_CONFIG(small_support_perimeter_speed).value == 0) small_perimeter_speed = base_speed * 0.5; @@ -9124,13 +9136,14 @@ std::string GCode::extrude_support(const ExtrusionEntityCollection &support_fill const ExtrusionEntityCollection* collection = dynamic_cast(ee); if (path) { - gcode += extrude_path(*path, label, speed_for_path(path->length(), role)); + gcode += extrude_path(*path, label, speed_for_path(path->length(), role, path)); } else if (multipath) { - gcode += extrude_multi_path(*multipath, label, speed_for_path(multipath->length(), role)); + gcode += extrude_multi_path(*multipath, label, speed_for_path(multipath->length(), role, + multipath->paths.empty() ? nullptr : &multipath->paths.front())); } else if (loop) { - gcode += extrude_loop(*loop, label, speed_for_path(loop->length(), role)); + gcode += extrude_loop(*loop, label, speed_for_path(loop->length(), role, loop->paths.empty() ? nullptr : &loop->paths.front())); } else if (collection) { gcode += extrude_support(*collection, support_extrusion_role); @@ -9275,6 +9288,84 @@ static bool overhang_fan_active(float overlap, int overhang_fan_threshold, Extru return overlap_threshold >= 0.f && overlap <= overlap_threshold; } +Vec3d GCode::path_slicing_point(const ExtrusionPath &path) const +{ + return {unscale(path.first_point().x()), unscale(path.first_point().y()), + m_layer ? m_layer->print_z : (m_belt_brim_z ? *m_belt_brim_z : 0.0)}; +} + +double GCode::extrusion_mm3_per_mm(const ExtrusionPath &path, bool on_first_layer) const +{ + const bool sloped = dynamic_cast(&path) != nullptr; + // Effective flow = Geometric volume * print flow ratio * filament flow ratio * role-based-flow-ratios + double _mm3_per_mm = path.mm3_per_mm * this->config().print_flow_ratio; + _mm3_per_mm *= FILAMENT_CONFIG(filament_flow_ratio); + + if (path.role() == erTopSolidInfill) { + _mm3_per_mm *= NOZZLE_CONFIG(top_solid_infill_flow_ratio); + } else if (path.role() == erBottomSurface) { + _mm3_per_mm *= m_config.bottom_solid_infill_flow_ratio; + } else if (path.role() == erInternalBridgeInfill) { + _mm3_per_mm *= m_config.internal_bridge_flow; + } else if (path.role() == erBrim) { + _mm3_per_mm *= m_config.brim_flow_ratio; + } else if (sloped) { + _mm3_per_mm *= m_config.scarf_joint_flow_ratio; + } + + if (m_config.set_other_flow_ratios) { + if (path.role() == erExternalPerimeter) { + _mm3_per_mm *= m_config.outer_wall_flow_ratio; + } else if (path.role() == erPerimeter) { + _mm3_per_mm *= m_config.inner_wall_flow_ratio; + } else if (path.role() == erOverhangPerimeter) { + _mm3_per_mm *= m_config.overhang_flow_ratio; + } else if (path.role() == erInternalInfill) { + _mm3_per_mm *= m_config.sparse_infill_flow_ratio; + } else if (path.role() == erSolidInfill) { + _mm3_per_mm *= m_config.internal_solid_infill_flow_ratio; + } else if (path.role() == erGapFill) { + _mm3_per_mm *= m_config.gap_fill_flow_ratio; + } else if (path.role() == erSupportMaterial) { // Should this condition also cover erSupportTransition? + _mm3_per_mm *= m_config.support_flow_ratio; + } else if (path.role() == erSupportMaterialInterface) { + _mm3_per_mm *= m_config.support_interface_flow_ratio; + } + + // Additionally, adjust the value if we are on the first layer (except for brims and skirts) + if (on_first_layer && (path.role() != erBrim && path.role() != erSkirt)) { + _mm3_per_mm *= m_config.first_layer_flow_ratio; + } + } + + // Mixed-color sublayer: scale the flow down to the sub-layer's share of the layer height. + if (m_sub_layer_flow_ratio > 0.0) + _mm3_per_mm *= m_sub_layer_flow_ratio; + return _mm3_per_mm; +} + +double GCode::feature_speed(double speed, const ConfigOptionFloatsOrPercentsNullable &volumetric_flow, double mm3_per_mm) const +{ + // Orca: calibrations set linear speeds, and a path that extrudes nothing has no flow to divide by. + if (!m_config.enable_volumetric_speeds || m_print->calib_mode() != CalibMode::Calib_None || mm3_per_mm <= 0.) + return speed; + const double max_volumetric_speed = FILAMENT_CONFIG(filament_max_volumetric_speed); + return volumetric_flow.get_at(get_nozzle_config_index(m_writer.filament()->id())).get_abs_value(max_volumetric_speed) / mm3_per_mm; +} + +double GCode::volumetric_speed_limit(ExtrusionRole role) const +{ + const double max_volumetric_speed = FILAMENT_CONFIG(filament_max_volumetric_speed); + const double max_external_volumetric_speed = FILAMENT_CONFIG(filament_max_external_volumetric_speed); + // Orca: visible features are outer walls, what prints at the external bridge speed, and top surfaces this layer does not iron. + const bool visible = role == erExternalPerimeter || role == erOverhangPerimeter || role == erBridgeInfill || + (role == erTopSolidInfill && m_layer != nullptr && + Layer::choose_ironing_extruder(m_config, m_config.spiral_mode.value, m_layer->upper_layer == nullptr) < 0); + if (max_external_volumetric_speed <= 0. || !visible || m_print->calib_mode() != CalibMode::Calib_None) + return max_volumetric_speed; + return max_volumetric_speed > 0. ? std::min(max_volumetric_speed, max_external_volumetric_speed) : max_external_volumetric_speed; +} + std::string GCode::_extrude(const ExtrusionPath &path, const std::string &path_description, double speed) { std::vector> uncut_line_lengths; @@ -9370,11 +9461,7 @@ std::string GCode::_extrude_piece(const ExtrusionPath &path, const std::string & // evaluator is inactive (non-belt printers, or belt printers without // a Z-axis shear) `path_on_first_layer` falls back to the legacy // layer-id check, so behavior is bit-identical to the pre-feature path. - const Vec3d path_point_mm{ - unscale(path.first_point().x()), - unscale(path.first_point().y()), - m_layer ? m_layer->print_z : (m_belt_brim_z ? *m_belt_brim_z : 0.0) - }; + const Vec3d path_point_mm = path_slicing_point(path); bool path_on_first_layer = this->on_first_layer(path_point_mm); // On a belt a path is judged by how high above the belt all of it is: it is on the first // layer when all of it is, and takes the slow_down_layers step of its middle. A piece cut @@ -9526,56 +9613,10 @@ std::string GCode::_extrude_piece(const ExtrusionPath &path, const std::string & } // calculate effective extrusion length per distance unit (e_per_mm) - double filament_flow_ratio = FILAMENT_CONFIG(filament_flow_ratio); - // We set _mm3_per_mm to effectove flow = Geometric volume * print flow ratio * filament flow ratio * role-based-flow-ratios - auto _mm3_per_mm = path.mm3_per_mm * this->config().print_flow_ratio; - _mm3_per_mm *= filament_flow_ratio; + const double _mm3_per_mm = extrusion_mm3_per_mm(path, path_on_first_layer); - if (path.role() == erTopSolidInfill) { - _mm3_per_mm *= NOZZLE_CONFIG(top_solid_infill_flow_ratio); - } else if (path.role() == erBottomSurface) { - _mm3_per_mm *= m_config.bottom_solid_infill_flow_ratio; - } else if (path.role() == erInternalBridgeInfill) { - _mm3_per_mm *= m_config.internal_bridge_flow; - } else if (path.role() == erBrim) { - _mm3_per_mm *= m_config.brim_flow_ratio; - } else if (sloped) { - _mm3_per_mm *= m_config.scarf_joint_flow_ratio; - } - - if (m_config.set_other_flow_ratios) { - if (path.role() == erExternalPerimeter) { - _mm3_per_mm *= m_config.outer_wall_flow_ratio; - } else if (path.role() == erPerimeter) { - _mm3_per_mm *= m_config.inner_wall_flow_ratio; - } else if (path.role() == erOverhangPerimeter) { - _mm3_per_mm *= m_config.overhang_flow_ratio; - } else if (path.role() == erInternalInfill) { - _mm3_per_mm *= m_config.sparse_infill_flow_ratio; - } else if (path.role() == erSolidInfill) { - _mm3_per_mm *= m_config.internal_solid_infill_flow_ratio; - } else if (path.role() == erGapFill) { - _mm3_per_mm *= m_config.gap_fill_flow_ratio; - } else if (path.role() == erSupportMaterial) { // Should this condition also cover erSupportTransition? - _mm3_per_mm *= m_config.support_flow_ratio; - } else if (path.role() == erSupportMaterialInterface) { - _mm3_per_mm *= m_config.support_interface_flow_ratio; - } - - // Additionally, adjust the value if we are on the first layer (except for brims and skirts) - if (path_on_first_layer && (path.role() != erBrim && path.role() != erSkirt)) { - _mm3_per_mm *= m_config.first_layer_flow_ratio; - } - } - - // Mixed-color sublayer: this path belongs to one sub-layer of a split layer, so scale the - // flow down to that sub-layer's share of the nominal layer height and report the sub-height - // as the effective extrusion height. Inert (ratio == 0) outside the sublayer emission block. - float effective_height = path.height; - if (m_sub_layer_flow_ratio > 0.0) { - _mm3_per_mm *= m_sub_layer_flow_ratio; - effective_height = static_cast(m_sub_layer_height); - } + // Mixed-color sublayer: report the sub-layer height as the effective extrusion height. + const float effective_height = m_sub_layer_flow_ratio > 0.0 ? static_cast(m_sub_layer_height) : path.height; // _mm3_per_mm already includes the filament flow ratio, so convert it with the bare cross-section // rather than e_per_mm3(), which would apply the ratio a second time. @@ -9584,38 +9625,40 @@ std::string GCode::_extrude_piece(const ExtrusionPath &path, const std::string & // set speed if (speed == -1) { if (path.role() == erPerimeter) { - speed = NOZZLE_CONFIG(inner_wall_speed); + speed = FEATURE_SPEED(inner_wall, _mm3_per_mm); if (sloped) { speed = std::min(speed, m_config.scarf_joint_speed.get_abs_value(speed)); } } else if (path.role() == erExternalPerimeter) { - speed = NOZZLE_CONFIG(outer_wall_speed); + speed = FEATURE_SPEED(outer_wall, _mm3_per_mm); if (sloped) { speed = std::min(speed, m_config.scarf_joint_speed.get_abs_value(speed)); } } else if(path.role() == erInternalBridgeInfill) { - speed = m_config.internal_bridge_speed.get_at(nozzle).get_abs_value(m_config.bridge_speed.get_at(nozzle)); + speed = feature_speed(m_config.internal_bridge_speed.get_at(nozzle).get_abs_value(m_config.bridge_speed.get_at(nozzle)), + m_config.internal_bridge_volumetric_flow, _mm3_per_mm); } else if (path.role() == erOverhangPerimeter || path.role() == erSupportTransition || path.role() == erBridgeInfill) { - speed = NOZZLE_CONFIG(bridge_speed); + speed = FEATURE_SPEED(bridge, _mm3_per_mm); } else if (path.role() == erInternalInfill) { - speed = NOZZLE_CONFIG(sparse_infill_speed); + speed = FEATURE_SPEED(sparse_infill, _mm3_per_mm); } else if (path.role() == erSolidInfill) { - speed = NOZZLE_CONFIG(internal_solid_infill_speed); + speed = FEATURE_SPEED(internal_solid_infill, _mm3_per_mm); } else if (path.role() == erTopSolidInfill) { - speed = NOZZLE_CONFIG(top_surface_speed); + speed = FEATURE_SPEED(top_surface, _mm3_per_mm); } else if (path.role() == erIroning) { const size_t filament_idx = get_filament_config_index(m_writer.filament()->id()); speed = m_config.filament_ironing_speed.is_nil(filament_idx) ? m_config.ironing_speed.value : m_config.filament_ironing_speed.get_at(filament_idx); } else if (path.role() == erBottomSurface) { - speed = NOZZLE_CONFIG(initial_layer_infill_speed); + speed = FEATURE_SPEED(initial_layer_infill, _mm3_per_mm); } else if (path.role() == erGapFill) { - speed = NOZZLE_CONFIG(gap_infill_speed); - } else if (path.role() == erSupportMaterial) { - speed = NOZZLE_CONFIG(support_speed); + speed = FEATURE_SPEED(gap_infill, _mm3_per_mm); + } else if (path.role() == erSupportMaterial || path.role() == erSkirt || path.role() == erBrim) { + //FIXME skirt and brim use the support speed of the 1st object printed. + speed = FEATURE_SPEED(support, _mm3_per_mm); } else if (path.role() == erSupportMaterialInterface) { - speed = NOZZLE_CONFIG(support_interface_speed); + speed = FEATURE_SPEED(support_interface, _mm3_per_mm); } else { throw Slic3r::InvalidArgument("Invalid speed"); } @@ -9654,15 +9697,15 @@ std::string GCode::_extrude_piece(const ExtrusionPath &path, const std::string & //wall lines have be attached if (path.role() != erBottomSurface) { const bool use_first_layer_speed = is_perimeter(path.role()) || path.role() == erBrim; - speed = use_first_layer_speed ? NOZZLE_CONFIG(initial_layer_speed) : - NOZZLE_CONFIG(initial_layer_infill_speed); + speed = use_first_layer_speed ? FEATURE_SPEED(initial_layer, _mm3_per_mm) : + FEATURE_SPEED(initial_layer_infill, _mm3_per_mm); } } else if (m_config.slow_down_layers > 1 && m_config.raft_layers == 0) { if (_layer > 0 && _layer < m_config.slow_down_layers) { const auto first_layer_speed = is_perimeter(path.role()) - ? NOZZLE_CONFIG(initial_layer_speed) - : NOZZLE_CONFIG(initial_layer_infill_speed); + ? FEATURE_SPEED(initial_layer, _mm3_per_mm) + : FEATURE_SPEED(initial_layer_infill, _mm3_per_mm); if (first_layer_speed < speed) { speed = std::min( speed, @@ -9674,8 +9717,8 @@ std::string GCode::_extrude_piece(const ExtrusionPath &path, const std::string & if (_layer > m_config.raft_layers && (_layer - m_config.raft_layers) < m_config.slow_down_layers) { const auto first_layer_speed - = is_perimeter(path.role()) ? NOZZLE_CONFIG(initial_layer_speed) : - NOZZLE_CONFIG(initial_layer_infill_speed); + = is_perimeter(path.role()) ? FEATURE_SPEED(initial_layer, _mm3_per_mm) : + FEATURE_SPEED(initial_layer_infill, _mm3_per_mm); if (first_layer_speed < speed) { speed = std::min(speed, Slic3r::lerp(first_layer_speed, speed, (double) (_layer - m_config.raft_layers) / m_config.slow_down_layers)); @@ -9698,9 +9741,10 @@ std::string GCode::_extrude_piece(const ExtrusionPath &path, const std::string & // m_config.max_volumetric_speed.value / _mm3_per_mm // ); //} - if (FILAMENT_CONFIG(filament_max_volumetric_speed) > 0) { + const double max_volumetric_speed = volumetric_speed_limit(path.role()); + if (max_volumetric_speed > 0) { // cap speed with max_volumetric_speed anyway (even if user is not using autospeed) - speed = std::min(speed, FILAMENT_CONFIG(filament_max_volumetric_speed) / _mm3_per_mm); + speed = std::min(speed, max_volumetric_speed / _mm3_per_mm); } // ORCA: resonance‑avoidance on short external perimeters { @@ -9714,10 +9758,10 @@ std::string GCode::_extrude_piece(const ExtrusionPath &path, const std::string & } // re‑apply volumetric cap - if (FILAMENT_CONFIG(filament_max_volumetric_speed) > 0) { + if (max_volumetric_speed > 0) { speed = std::min( speed, - FILAMENT_CONFIG(filament_max_volumetric_speed) / _mm3_per_mm + max_volumetric_speed / _mm3_per_mm ); } @@ -9725,7 +9769,10 @@ std::string GCode::_extrude_piece(const ExtrusionPath &path, const std::string & // - speeds in lower half of range: clamp down to "min" // - speeds in upper half of range: boost up to "max" if (m_resonance_avoidance && speed < m_config.max_resonance_avoidance_speed.value) { - if (speed < m_config.min_resonance_avoidance_speed.value + + // ORCA: a wall the volumetric limit keeps below "max" cannot be boosted, so it clamps down to "min". + const bool can_boost = max_volumetric_speed <= 0 || + m_config.max_resonance_avoidance_speed.value <= max_volumetric_speed / _mm3_per_mm; + if (!can_boost || speed < m_config.min_resonance_avoidance_speed.value + ((m_config.max_resonance_avoidance_speed.value - m_config.min_resonance_avoidance_speed.value) / 2)) { speed = std::min(speed, m_config.min_resonance_avoidance_speed.value); } else { @@ -9750,12 +9797,12 @@ std::string GCode::_extrude_piece(const ExtrusionPath &path, const std::string & if (need_overhang_detection && !path_on_first_layer && !object_layer_over_raft() && (is_bridge(path.role()) || is_perimeter(path.role()))) { bool is_external = is_external_perimeter(path.role()); - double ref_speed = is_external ? NOZZLE_CONFIG(outer_wall_speed) : NOZZLE_CONFIG(inner_wall_speed); + double ref_speed = is_external ? FEATURE_SPEED(outer_wall, _mm3_per_mm) : FEATURE_SPEED(inner_wall, _mm3_per_mm); if (ref_speed == 0) - ref_speed = FILAMENT_CONFIG(filament_max_volumetric_speed) / _mm3_per_mm; + ref_speed = max_volumetric_speed / _mm3_per_mm; - if (FILAMENT_CONFIG(filament_max_volumetric_speed) > 0) { - ref_speed = std::min(ref_speed, FILAMENT_CONFIG(filament_max_volumetric_speed) / _mm3_per_mm); + if (max_volumetric_speed > 0) { + ref_speed = std::min(ref_speed, max_volumetric_speed / _mm3_per_mm); } if (sloped) { ref_speed = std::min(ref_speed, m_config.scarf_joint_speed.get_abs_value(ref_speed)); @@ -9772,7 +9819,7 @@ std::string GCode::_extrude_piece(const ExtrusionPath &path, const std::string & if (NOZZLE_CONFIG(slowdown_for_curled_perimeters)){ const FloatOrPercent fully_unsupported_speed = path.role() == erBridgeInfill ? - FloatOrPercent{NOZZLE_CONFIG(bridge_speed) * 100 / ref_speed, true} : + FloatOrPercent{FEATURE_SPEED(bridge, _mm3_per_mm) * 100 / ref_speed, true} : (NOZZLE_CONFIG(overhang_4_4_speed).get_abs_value(ref_speed) < 0.5 ? FloatOrPercent{100, true} : FloatOrPercent{NOZZLE_CONFIG(overhang_4_4_speed).get_abs_value(ref_speed) * 100 / ref_speed, true}); @@ -9810,7 +9857,7 @@ std::string GCode::_extrude_piece(const ExtrusionPath &path, const std::string & (NOZZLE_CONFIG(overhang_4_4_speed).get_abs_value(ref_speed) < 0.5) ? FloatOrPercent{100, true} : FloatOrPercent{NOZZLE_CONFIG(overhang_4_4_speed).get_abs_value(ref_speed) * 100 / ref_speed, true}, - FloatOrPercent{NOZZLE_CONFIG(bridge_speed) * 100 / ref_speed, true}}); + FloatOrPercent{FEATURE_SPEED(bridge, _mm3_per_mm) * 100 / ref_speed, true}}); new_points = m_extrusion_quality_estimator.estimate_extrusion_quality(path, overhang_overlap_levels, dynamic_overhang_speeds, ref_speed, speed, NOZZLE_CONFIG(slowdown_for_curled_perimeters), diff --git a/src/libslic3r/GCode.hpp b/src/libslic3r/GCode.hpp index 07902dbdc2..316b18e6e2 100644 --- a/src/libslic3r/GCode.hpp +++ b/src/libslic3r/GCode.hpp @@ -987,6 +987,14 @@ protected: ExtrusionPaths belt_cut_at_band_edges(const ExtrusionPath &path, std::vector> &uncut_line_lengths) const; // _extrude() of a path that stays in one band above the belt (see belt_cut_at_band_edges()). std::string _extrude_piece(const ExtrusionPath &path, const std::string &path_description, double speed); + // First point of the path in the slicing frame, for the per-point first-layer test. + Vec3d path_slicing_point(const ExtrusionPath &path) const; + // Flow in mm³ per mm the path is extruded with, after the flow ratios (the first layer's when `on_first_layer`). + double extrusion_mm3_per_mm(const ExtrusionPath &path, bool on_first_layer) const; + // Feed rate of a feature: its linear `speed`, or with volumetric speeds its flow divided by `mm3_per_mm`. + double feature_speed(double speed, const ConfigOptionFloatsOrPercentsNullable &volumetric_flow, double mm3_per_mm) const; + // Max flow in mm³/s of a path with this role, 0 for no limit. + double volumetric_speed_limit(ExtrusionRole role) const; bool _needSAFC(const ExtrusionPath &path); void print_machine_envelope(GCodeOutputStream& file, Print& print); void _print_first_layer_bed_temperature(GCodeOutputStream &file, Print &print, const std::string &gcode, unsigned int first_printing_extruder_id, bool wait); diff --git a/src/libslic3r/GCode/WipeTower.cpp b/src/libslic3r/GCode/WipeTower.cpp index 184ecf8cec..badd6dd42b 100644 --- a/src/libslic3r/GCode/WipeTower.cpp +++ b/src/libslic3r/GCode/WipeTower.cpp @@ -2033,6 +2033,9 @@ WipeTower::WipeTower(const PrintConfig& config, int plate_idx, Vec3d plate_origi m_first_layer_speed = config.initial_layer_speed.get_at(get_extruder_index(config, (unsigned int) initial_tool)); if (m_first_layer_speed == 0.f) // just to make sure autospeed doesn't break it. m_first_layer_speed = default_speed / 2.f; + if (config.enable_volumetric_speeds) + m_first_layer_volumetric_flow = float(config.initial_layer_volumetric_flow.get_at(get_extruder_index(config, (unsigned int) initial_tool)) + .get_abs_value(config.filament_max_volumetric_speed.get_at(initial_tool))); // If this is a single extruder MM printer, we will use all the SE-specific config values. // Otherwise, the defaults will be used to turn off the SE stuff. diff --git a/src/libslic3r/GCode/WipeTower.hpp b/src/libslic3r/GCode/WipeTower.hpp index dd000737c7..7b1aaed45e 100644 --- a/src/libslic3r/GCode/WipeTower.hpp +++ b/src/libslic3r/GCode/WipeTower.hpp @@ -304,6 +304,9 @@ public: // Calculate extrusion flow from desired line width, nozzle diameter, filament diameter and layer_height: m_extrusion_flow = extrusion_flow(layer_height); + // Orca: with volumetric speeds, the first layer speed is its flow divided by the line cross section. + if (m_first_layer_volumetric_flow > 0.f) + m_first_layer_speed = m_first_layer_volumetric_flow / (m_extrusion_flow * filament_area()); // Advance m_layer_info iterator, making sure we got it right while (!m_plan.empty() && m_layer_info->z < print_z - WT_EPSILON && m_layer_info+1 != m_plan.end()) ++m_layer_info; @@ -509,6 +512,8 @@ private: int m_old_temperature = -1; // To keep track of what was the last temp that we set (so we don't issue the command when not neccessary) float m_travel_speed = 0.f; float m_first_layer_speed = 0.f; + // Volumetric flow (mm³/s) set_layer() derives m_first_layer_speed from, 0 without volumetric speeds. + float m_first_layer_volumetric_flow = 0.f; size_t m_first_layer_idx = size_t(-1); Vec2f m_origin; std::vector m_last_layer_id; diff --git a/src/libslic3r/GCode/WipeTower2.cpp b/src/libslic3r/GCode/WipeTower2.cpp index ccd3d78e92..c34a5e2699 100644 --- a/src/libslic3r/GCode/WipeTower2.cpp +++ b/src/libslic3r/GCode/WipeTower2.cpp @@ -1086,6 +1086,14 @@ WipeTower2::WipeTower2(const PrintConfig& config, const PrintRegionConfig& defau if (m_perimeter_speed == 0.f) m_perimeter_speed = 80.f; + if (config.enable_volumetric_speeds) { + const size_t extruder_idx = get_extruder_index(config, (unsigned int)initial_tool); + const double max_volumetric_speed = config.filament_max_volumetric_speed.get_at(initial_tool); + m_infill_volumetric_flow = float(default_region_config.sparse_infill_volumetric_flow.get_at(extruder_idx).get_abs_value(max_volumetric_speed)); + m_perimeter_volumetric_flow = float(default_region_config.inner_wall_volumetric_flow.get_at(extruder_idx).get_abs_value(max_volumetric_speed)); + m_first_layer_volumetric_flow = float(config.initial_layer_volumetric_flow.get_at(extruder_idx).get_abs_value(max_volumetric_speed)); + } + // If this is a single extruder MM printer, we will use all the SE-specific config values. // Otherwise, the defaults will be used to turn off the SE stuff. diff --git a/src/libslic3r/GCode/WipeTower2.hpp b/src/libslic3r/GCode/WipeTower2.hpp index 4ca320c329..5fbb2153c7 100644 --- a/src/libslic3r/GCode/WipeTower2.hpp +++ b/src/libslic3r/GCode/WipeTower2.hpp @@ -136,6 +136,15 @@ public: // Calculate extrusion flow from desired line width, nozzle diameter, filament diameter and layer_height: m_extrusion_flow = extrusion_flow(layer_height); + + // Orca: with volumetric speeds, a speed is its flow divided by this layer's line cross section. + const float mm3_per_mm = m_extrusion_flow * filament_area(); + if (m_infill_volumetric_flow > 0.f) + m_infill_speed = m_infill_volumetric_flow / mm3_per_mm; + if (m_perimeter_volumetric_flow > 0.f) + m_perimeter_speed = m_perimeter_volumetric_flow / mm3_per_mm; + if (m_first_layer_volumetric_flow > 0.f) + m_first_layer_speed = m_first_layer_volumetric_flow / mm3_per_mm; } // Return the wipe tower position. @@ -248,6 +257,10 @@ private: float m_wipe_tower_max_purge_speed = 90.f; float m_perimeter_speed = 0.f; float m_first_layer_speed = 0.f; + // Volumetric flows (mm³/s) set_layer() derives the speeds above from, 0 without volumetric speeds. + float m_infill_volumetric_flow = 0.f; + float m_perimeter_volumetric_flow = 0.f; + float m_first_layer_volumetric_flow = 0.f; size_t m_first_layer_idx = size_t(-1); bool m_enable_tower_interface_features = false; bool m_enable_tower_interface_cooldown_during_tower = false; diff --git a/src/libslic3r/Layer.cpp b/src/libslic3r/Layer.cpp index c58a1b1a7b..f3d4be36b7 100644 --- a/src/libslic3r/Layer.cpp +++ b/src/libslic3r/Layer.cpp @@ -174,6 +174,9 @@ bool Layer::is_perimeter_compatible(const Print& print, const PrintRegion& a, co && config.small_perimeter_speed.get_at(print.get_extruder_id(config.outer_wall_filament_id)) == other_config.small_perimeter_speed.get_at(print.get_extruder_id(config.outer_wall_filament_id)) && config.small_support_perimeter_speed.get_at(print.get_extruder_id(config.outer_wall_filament_id)) == other_config.small_support_perimeter_speed.get_at(print.get_extruder_id(config.outer_wall_filament_id)) && config.gap_infill_speed.get_at(print.get_extruder_id(config.outer_wall_filament_id)) == other_config.gap_infill_speed.get_at(print.get_extruder_id(config.outer_wall_filament_id)) + && config.inner_wall_volumetric_flow.get_at(print.get_extruder_id(config.outer_wall_filament_id)) == other_config.inner_wall_volumetric_flow.get_at(print.get_extruder_id(config.outer_wall_filament_id)) + && config.outer_wall_volumetric_flow.get_at(print.get_extruder_id(config.outer_wall_filament_id)) == other_config.outer_wall_volumetric_flow.get_at(print.get_extruder_id(config.outer_wall_filament_id)) + && config.gap_infill_volumetric_flow.get_at(print.get_extruder_id(config.outer_wall_filament_id)) == other_config.gap_infill_volumetric_flow.get_at(print.get_extruder_id(config.outer_wall_filament_id)) && config.filter_out_gap_fill.value == other_config.filter_out_gap_fill.value && config.detect_overhang_wall == other_config.detect_overhang_wall && config.unsupported_wall_last == other_config.unsupported_wall_last diff --git a/src/libslic3r/Preset.cpp b/src/libslic3r/Preset.cpp index c16497001b..ac5143dabf 100644 --- a/src/libslic3r/Preset.cpp +++ b/src/libslic3r/Preset.cpp @@ -1381,6 +1381,19 @@ static std::vector s_Preset_print_options{ "overhang_3_4_speed", "overhang_4_4_speed", "initial_layer_infill_speed", + "enable_volumetric_speeds", + "initial_layer_volumetric_flow", + "initial_layer_infill_volumetric_flow", + "outer_wall_volumetric_flow", + "inner_wall_volumetric_flow", + "sparse_infill_volumetric_flow", + "internal_solid_infill_volumetric_flow", + "top_surface_volumetric_flow", + "gap_infill_volumetric_flow", + "support_volumetric_flow", + "support_interface_volumetric_flow", + "bridge_volumetric_flow", + "internal_bridge_volumetric_flow", "only_one_wall_top", "timelapse_type", "wall_generator", @@ -1524,7 +1537,7 @@ static std::vector s_Preset_print_options{ static std::vector s_Preset_filament_options {/*"filament_colour", */ "default_filament_colour", "required_nozzle_HRC", "filament_diameter", "pellet_flow_coefficient", "volumetric_speed_coefficients", "filament_type", "filament_soluble", "filament_is_support", "filament_printable", "filament_extruder_compatibility", - "filament_max_volumetric_speed", "filament_adaptive_volumetric_speed", + "filament_max_volumetric_speed", "filament_max_external_volumetric_speed", "filament_adaptive_volumetric_speed", "filament_flow_ratio", "filament_density", "filament_adhesiveness_category", "filament_cost", "filament_minimal_purge_on_wipe_tower", "filament_tower_interface_pre_extrusion_dist", "filament_tower_interface_pre_extrusion_length", "filament_tower_ironing_area", "filament_tower_interface_purge_volume", "filament_tower_interface_print_temp", diff --git a/src/libslic3r/Print.cpp b/src/libslic3r/Print.cpp index 22f74f3ccf..dec0ed3072 100644 --- a/src/libslic3r/Print.cpp +++ b/src/libslic3r/Print.cpp @@ -308,6 +308,7 @@ bool Print::invalidate_state_by_config_options(const ConfigOptionResolver & /* n "nozzle_height", "extruder_colour", "filament_flow_ratio", + "filament_max_external_volumetric_speed", "reduce_fan_stop_start_freq", "dont_slow_down_outer_wall", "fan_cooling_layer_time", @@ -579,6 +580,9 @@ bool Print::invalidate_state_by_config_options(const ConfigOptionResolver & /* n || opt_key == "travel_speed" || opt_key == "travel_speed_z" || opt_key == "initial_layer_speed" + || opt_key == "enable_volumetric_speeds" + || opt_key == "initial_layer_volumetric_flow" + || opt_key == "initial_layer_infill_volumetric_flow" || opt_key == "initial_layer_travel_speed" || opt_key == "initial_layer_travel_acceleration" || opt_key == "initial_layer_travel_jerk" diff --git a/src/libslic3r/PrintConfig.cpp b/src/libslic3r/PrintConfig.cpp index d9c2ca9ac6..01729fa5ae 100644 --- a/src/libslic3r/PrintConfig.cpp +++ b/src/libslic3r/PrintConfig.cpp @@ -2046,7 +2046,7 @@ void PrintConfigDef::init_fff_params() def->tooltip = L("Speed of the externally visible bridge extrusions.\n\n" "In addition, if Slow down for curled perimeters is disabled, " "it will be the print speed of overhang walls that are supported by less than 13%, " - "whether they are part of a bridge or an overhang."); + "whether they are part of a bridge or an overhang.\n\nThe resulting speed is limited by the filament's \"Max volumetric speed\" and \"Max external volumetric speed\"."); def->sidetext = L("mm/s"); // millimeters per second, CIS languages need translation def->min = 1; def->mode = comAdvanced; @@ -2056,7 +2056,7 @@ void PrintConfigDef::init_fff_params() def = this->add("internal_bridge_speed", coFloatsOrPercents); def->label = L("Internal"); def->category = L("Speed"); - def->tooltip = L("Speed of internal bridges. If the value is expressed as a percentage, it will be calculated based on the bridge_speed. Default value is 150%."); + def->tooltip = L("Speed of internal bridges. If the value is expressed as a percentage, it will be calculated based on the bridge_speed. Default value is 150%.\n\nThe resulting speed is limited by the filament's \"Max volumetric speed\"."); def->sidetext = L("mm/s or %"); def->ratio_over = "bridge_speed"; def->min = 1; @@ -2702,7 +2702,7 @@ void PrintConfigDef::init_fff_params() def = this->add("outer_wall_speed", coFloats); def->label = L("Outer wall"); def->category = L("Speed"); - def->tooltip = L("This is the printing speed for the outer walls of parts. These are generally printed slower than inner walls for higher quality."); + def->tooltip = L("This is the printing speed for the outer walls of parts. These are generally printed slower than inner walls for higher quality.\n\nThe resulting speed is limited by the filament's \"Max volumetric speed\" and \"Max external volumetric speed\"."); def->sidetext = L("mm/s"); // millimeters per second, CIS languages need translation def->min = 1; def->mode = comAdvanced; @@ -2714,7 +2714,7 @@ void PrintConfigDef::init_fff_params() def->category = L("Speed"); def->tooltip = L("This separate setting will affect the speed of perimeters having radius <= small_perimeter_threshold " "(usually holes). If expressed as percentage (for example: 80%) it will be calculated " - "on the outer wall speed setting above."); + "on the outer wall speed setting above.\n\nThe resulting speed is limited by the filament's \"Max volumetric speed\" and, on outer walls, \"Max external volumetric speed\"."); def->sidetext = L("mm/s or %"); def->ratio_over = "outer_wall_speed"; def->min = 1; @@ -2737,7 +2737,7 @@ void PrintConfigDef::init_fff_params() def->category = L("Speed"); def->tooltip = L("Same as \"Small perimeters\", but for supports. " "This separate setting will affect the speed of support for areas <= `small_support_perimeter_threshold`. " - "If expressed as a percentage (for example: 80%), it will be calculated on the support or support interface speed setting above."); + "If expressed as a percentage (for example: 80%), it will be calculated on the support or support interface speed setting above.\n\nThe resulting speed is limited by the filament's \"Max volumetric speed\"."); def->sidetext = L("mm/s or %"); def->ratio_over = "support_speed"; def->min = 1; @@ -2753,6 +2753,168 @@ void PrintConfigDef::init_fff_params() def->mode = comAdvanced; def->set_default_value(new ConfigOptionFloatsNullable{0}); + def = this->add("enable_volumetric_speeds", coBool); + def->label = L("Volumetric speeds"); + def->category = L("Speed"); + def->tooltip = L("Set the speed of each feature as a volumetric flow (mm³/s) instead of a linear speed (mm/s). " + "Each line is then printed at its feature's flow divided by the line's cross section, so lines of different " + "width or height extrude the same flow. A volumetric speed expressed as a percentage is calculated on the " + "filament's \"Max volumetric speed\", which still limits every speed, as \"Max external volumetric speed\" " + "does for the visible features.\n\n" + "Small perimeter, overhang, ironing and travel speeds keep their own settings, applied over the resulting " + "speeds. Calibration prints ignore this option."); + def->mode = comAdvanced; + def->set_default_value(new ConfigOptionBool(false)); + + // Orca: named *_volumetric_flow because outer_wall_volumetric_speed is already a custom G-code placeholder. + const char *flow_tooltip = L("Volumetric flow of this feature when volumetric speeds are enabled. If expressed as a percentage, " + "it is calculated on the filament's \"Max volumetric speed\".\n\n" + "The resulting speed is limited by the filament's \"Max volumetric speed\"."); + const char *walls_flow_tooltip = L("Volumetric flow of this feature when volumetric speeds are enabled. If expressed as a percentage, " + "it is calculated on the filament's \"Max volumetric speed\".\n\n" + "The resulting speed is limited by the filament's \"Max volumetric speed\" and, on outer walls, " + "\"Max external volumetric speed\"."); + const char *external_flow_tooltip = L("Volumetric flow of this feature when volumetric speeds are enabled. If expressed as a percentage, " + "it is calculated on the filament's \"Max volumetric speed\".\n\n" + "The resulting speed is limited by the filament's \"Max volumetric speed\" and " + "\"Max external volumetric speed\"."); + const char *top_flow_tooltip = L("Volumetric flow of this feature when volumetric speeds are enabled. If expressed as a percentage, " + "it is calculated on the filament's \"Max volumetric speed\".\n\n" + "The resulting speed is limited by the filament's \"Max volumetric speed\" and, unless the surface " + "is ironed, \"Max external volumetric speed\"."); + + def = this->add("initial_layer_volumetric_flow", coFloatsOrPercents); + def->label = L("First layer"); + def->full_label = L("First layer volumetric speed"); + def->category = L("Speed"); + def->tooltip = walls_flow_tooltip; + def->sidetext = L(u8"mm³/s or %"); // cubic millimeters per second, CIS languages need translation + def->min = 0.1; + def->mode = comAdvanced; + def->nullable = true; + def->set_default_value(new ConfigOptionFloatsOrPercentsNullable{FloatOrPercent(25, true)}); + + def = this->add("initial_layer_infill_volumetric_flow", coFloatsOrPercents); + def->label = L("First layer infill"); + def->full_label = L("First layer infill volumetric speed"); + def->category = L("Speed"); + def->tooltip = flow_tooltip; + def->sidetext = L(u8"mm³/s or %"); // cubic millimeters per second, CIS languages need translation + def->min = 0.1; + def->mode = comAdvanced; + def->nullable = true; + def->set_default_value(new ConfigOptionFloatsOrPercentsNullable{FloatOrPercent(50, true)}); + + def = this->add("outer_wall_volumetric_flow", coFloatsOrPercents); + def->label = L("Outer wall"); + def->full_label = L("Outer wall volumetric speed"); + def->category = L("Speed"); + def->tooltip = external_flow_tooltip; + def->sidetext = L(u8"mm³/s or %"); // cubic millimeters per second, CIS languages need translation + def->min = 0.1; + def->mode = comAdvanced; + def->nullable = true; + def->set_default_value(new ConfigOptionFloatsOrPercentsNullable{FloatOrPercent(50, true)}); + + def = this->add("inner_wall_volumetric_flow", coFloatsOrPercents); + def->label = L("Inner wall"); + def->full_label = L("Inner wall volumetric speed"); + def->category = L("Speed"); + def->tooltip = flow_tooltip; + def->sidetext = L(u8"mm³/s or %"); // cubic millimeters per second, CIS languages need translation + def->min = 0.1; + def->mode = comAdvanced; + def->nullable = true; + def->set_default_value(new ConfigOptionFloatsOrPercentsNullable{FloatOrPercent(100, true)}); + + def = this->add("sparse_infill_volumetric_flow", coFloatsOrPercents); + def->label = L("Sparse infill"); + def->full_label = L("Sparse infill volumetric speed"); + def->category = L("Speed"); + def->tooltip = flow_tooltip; + def->sidetext = L(u8"mm³/s or %"); // cubic millimeters per second, CIS languages need translation + def->min = 0.1; + def->mode = comAdvanced; + def->nullable = true; + def->set_default_value(new ConfigOptionFloatsOrPercentsNullable{FloatOrPercent(100, true)}); + + def = this->add("internal_solid_infill_volumetric_flow", coFloatsOrPercents); + def->label = L("Internal solid infill"); + def->full_label = L("Internal solid infill volumetric speed"); + def->category = L("Speed"); + def->tooltip = flow_tooltip; + def->sidetext = L(u8"mm³/s or %"); // cubic millimeters per second, CIS languages need translation + def->min = 0.1; + def->mode = comAdvanced; + def->nullable = true; + def->set_default_value(new ConfigOptionFloatsOrPercentsNullable{FloatOrPercent(100, true)}); + + def = this->add("top_surface_volumetric_flow", coFloatsOrPercents); + def->label = L("Top surface"); + def->full_label = L("Top surface volumetric speed"); + def->category = L("Speed"); + def->tooltip = top_flow_tooltip; + def->sidetext = L(u8"mm³/s or %"); // cubic millimeters per second, CIS languages need translation + def->min = 0.1; + def->mode = comAdvanced; + def->nullable = true; + def->set_default_value(new ConfigOptionFloatsOrPercentsNullable{FloatOrPercent(50, true)}); + + def = this->add("gap_infill_volumetric_flow", coFloatsOrPercents); + def->label = L("Gap infill"); + def->full_label = L("Gap infill volumetric speed"); + def->category = L("Speed"); + def->tooltip = flow_tooltip; + def->sidetext = L(u8"mm³/s or %"); // cubic millimeters per second, CIS languages need translation + def->min = 0.1; + def->mode = comAdvanced; + def->nullable = true; + def->set_default_value(new ConfigOptionFloatsOrPercentsNullable{FloatOrPercent(50, true)}); + + def = this->add("support_volumetric_flow", coFloatsOrPercents); + def->label = L("Support"); + def->full_label = L("Support volumetric speed"); + def->category = L("Speed"); + def->tooltip = flow_tooltip; + def->sidetext = L(u8"mm³/s or %"); // cubic millimeters per second, CIS languages need translation + def->min = 0.1; + def->mode = comAdvanced; + def->nullable = true; + def->set_default_value(new ConfigOptionFloatsOrPercentsNullable{FloatOrPercent(100, true)}); + + def = this->add("support_interface_volumetric_flow", coFloatsOrPercents); + def->label = L("Support interface"); + def->full_label = L("Support interface volumetric speed"); + def->category = L("Speed"); + def->tooltip = flow_tooltip; + def->sidetext = L(u8"mm³/s or %"); // cubic millimeters per second, CIS languages need translation + def->min = 0.1; + def->mode = comAdvanced; + def->nullable = true; + def->set_default_value(new ConfigOptionFloatsOrPercentsNullable{FloatOrPercent(50, true)}); + + def = this->add("bridge_volumetric_flow", coFloatsOrPercents); + def->label = L("External"); + def->full_label = L("External bridge volumetric speed"); + def->category = L("Speed"); + def->tooltip = external_flow_tooltip; + def->sidetext = L(u8"mm³/s or %"); // cubic millimeters per second, CIS languages need translation + def->min = 0.1; + def->mode = comAdvanced; + def->nullable = true; + def->set_default_value(new ConfigOptionFloatsOrPercentsNullable{FloatOrPercent(25, true)}); + + def = this->add("internal_bridge_volumetric_flow", coFloatsOrPercents); + def->label = L("Internal"); + def->full_label = L("Internal bridge volumetric speed"); + def->category = L("Speed"); + def->tooltip = flow_tooltip; + def->sidetext = L(u8"mm³/s or %"); // cubic millimeters per second, CIS languages need translation + def->min = 0.1; + def->mode = comAdvanced; + def->nullable = true; + def->set_default_value(new ConfigOptionFloatsOrPercentsNullable{FloatOrPercent(40, true)}); + def = this->add("wall_sequence", coEnum); def->label = L("Walls printing order"); def->category = L("Quality"); @@ -3193,6 +3355,17 @@ void PrintConfigDef::init_fff_params() def->mode = comAdvanced; def->set_default_value(new ConfigOptionFloats { 2. }); + def = this->add("filament_max_external_volumetric_speed", coFloats); + def->label = L("Max external volumetric speed"); + def->tooltip = L("Lower volumetric speed limit for the visible external features: outer walls, external bridges and overhang walls, " + "and top surfaces that are not ironed. It applies on top of the max volumetric speed. 0 means no extra limit.\n\n" + "Set it to the highest flow at which this material still prints glossy, to keep the surface finish while the " + "rest of the print runs at the max volumetric speed."); + def->sidetext = L(u8"mm³/s"); // cubic millimeters per second, CIS languages need translation + def->min = 0; + def->mode = comAdvanced; + def->set_default_value(new ConfigOptionFloats { 0. }); + def = this->add("machine_load_filament_time", coFloat); def->label = L("Filament load time"); def->tooltip = L("Time to load new filament when switch filament. It's usually applicable for single-extruder multi-material machines. " @@ -4076,7 +4249,7 @@ void PrintConfigDef::init_fff_params() def = this->add("initial_layer_speed", coFloats); def->label = L("First layer"); - def->tooltip = L("This is the speed for the walls and brim of the first layer."); + def->tooltip = L("This is the speed for the walls and brim of the first layer.\n\nThe resulting speed is limited by the filament's \"Max volumetric speed\" and, on outer walls, \"Max external volumetric speed\"."); def->sidetext = L("mm/s"); // millimeters per second, CIS languages need translation def->min = 1; def->mode = comAdvanced; @@ -4085,7 +4258,7 @@ void PrintConfigDef::init_fff_params() def = this->add("initial_layer_infill_speed", coFloats); def->label = L("First layer infill"); - def->tooltip = L("This is the speed for the first layer except for walls and brim, such as infill, gap fill and support."); + def->tooltip = L("This is the speed for the first layer except for walls and brim, such as infill, gap fill and support.\n\nThe resulting speed is limited by the filament's \"Max volumetric speed\"."); def->sidetext = L("mm/s"); // millimeters per second, CIS languages need translation def->min = 1; def->mode = comAdvanced; @@ -4405,7 +4578,7 @@ void PrintConfigDef::init_fff_params() def = this->add("gap_infill_speed", coFloats); def->label = L("Gap infill"); def->category = L("Speed"); - def->tooltip = L("This is the speed for gap infill. Gaps usually have irregular line width and should be printed more slowly."); + def->tooltip = L("This is the speed for gap infill. Gaps usually have irregular line width and should be printed more slowly.\n\nThe resulting speed is limited by the filament's \"Max volumetric speed\"."); def->sidetext = L("mm/s"); // millimeters per second, CIS languages need translation def->min = 1; def->mode = comAdvanced; @@ -5055,7 +5228,7 @@ void PrintConfigDef::init_fff_params() def = this->add("sparse_infill_speed", coFloats); def->label = L("Sparse infill"); def->category = L("Speed"); - def->tooltip = L("This is the speed for internal sparse infill."); + def->tooltip = L("This is the speed for internal sparse infill.\n\nThe resulting speed is limited by the filament's \"Max volumetric speed\"."); def->sidetext = L("mm/s"); // millimeters per second, CIS languages need translation def->min = 1; def->mode = comAdvanced; @@ -5222,7 +5395,7 @@ void PrintConfigDef::init_fff_params() def = this->add("ironing_speed", coFloat); def->label = L("Ironing speed"); def->category = L("Quality"); - def->tooltip = L("This is the print speed for ironing lines."); + def->tooltip = L("This is the print speed for ironing lines.\n\nThe resulting speed is limited by the filament's \"Max volumetric speed\"."); def->sidetext = L("mm/s"); // millimeters per second, CIS languages need translation def->min = 1; def->mode = comAdvanced; @@ -5957,7 +6130,7 @@ void PrintConfigDef::init_fff_params() def = this->add("inner_wall_speed", coFloats); def->label = L("Inner wall"); def->category = L("Speed"); - def->tooltip = L("This is the speed for inner walls."); + def->tooltip = L("This is the speed for inner walls.\n\nThe resulting speed is limited by the filament's \"Max volumetric speed\"."); def->sidetext = L("mm/s"); // millimeters per second, CIS languages need translation def->aliases = { "perimeter_feed_rate" }; def->min = 1; @@ -6881,7 +7054,7 @@ void PrintConfigDef::init_fff_params() def = this->add("internal_solid_infill_speed", coFloats); def->label = L("Internal solid infill"); def->category = L("Speed"); - def->tooltip = L("This is the speed for internal solid infill, not including the top or bottom surface."); + def->tooltip = L("This is the speed for internal solid infill, not including the top or bottom surface.\n\nThe resulting speed is limited by the filament's \"Max volumetric speed\"."); def->sidetext = L("mm/s"); // millimeters per second, CIS languages need translation def->min = 1; def->mode = comAdvanced; @@ -7546,7 +7719,7 @@ void PrintConfigDef::init_fff_params() def = this->add("support_interface_speed", coFloats); def->label = L("Support interface"); def->category = L("Speed"); - def->tooltip = L("This is the speed for support interfaces."); + def->tooltip = L("This is the speed for support interfaces.\n\nThe resulting speed is limited by the filament's \"Max volumetric speed\"."); def->sidetext = L("mm/s"); // millimeters per second, CIS languages need translation def->min = 1; def->mode = comAdvanced; @@ -7618,7 +7791,7 @@ void PrintConfigDef::init_fff_params() def = this->add("support_speed", coFloats); def->label = L("Support"); def->category = L("Speed"); - def->tooltip = L("This is the speed for support."); + def->tooltip = L("This is the speed for support.\n\nThe resulting speed is limited by the filament's \"Max volumetric speed\"."); def->sidetext = L("mm/s"); // millimeters per second, CIS languages need translation def->min = 1; def->mode = comAdvanced; @@ -8151,7 +8324,7 @@ void PrintConfigDef::init_fff_params() def = this->add("top_surface_speed", coFloats); def->label = L("Top surface"); def->category = L("Speed"); - def->tooltip = L("This is the speed for solid top surface infill."); + def->tooltip = L("This is the speed for solid top surface infill.\n\nThe resulting speed is limited by the filament's \"Max volumetric speed\" and, unless the surface is ironed, \"Max external volumetric speed\"."); def->sidetext = L("mm/s"); // millimeters per second, CIS languages need translation def->min = 1; def->mode = comAdvanced; @@ -10136,6 +10309,18 @@ std::set print_options_with_variant = { "gap_infill_speed", "support_speed", "support_interface_speed", + "initial_layer_volumetric_flow", //coFloatsOrPercents + "initial_layer_infill_volumetric_flow", + "outer_wall_volumetric_flow", + "inner_wall_volumetric_flow", + "sparse_infill_volumetric_flow", + "internal_solid_infill_volumetric_flow", + "top_surface_volumetric_flow", + "gap_infill_volumetric_flow", + "support_volumetric_flow", + "support_interface_volumetric_flow", + "bridge_volumetric_flow", + "internal_bridge_volumetric_flow", "travel_speed", "travel_speed_z", "initial_layer_travel_speed", @@ -10166,6 +10351,7 @@ std::set print_options_with_variant = { std::set filament_options_with_variant = { "filament_flow_ratio", "filament_max_volumetric_speed", + "filament_max_external_volumetric_speed", // Per-variant ramming / pre-cooling / nozzle-change filament overrides "filament_ramming_volumetric_speed", "filament_pre_cooling_temperature", diff --git a/src/libslic3r/PrintConfig.hpp b/src/libslic3r/PrintConfig.hpp index 27e6fc0306..f98b7df2cc 100644 --- a/src/libslic3r/PrintConfig.hpp +++ b/src/libslic3r/PrintConfig.hpp @@ -1335,12 +1335,14 @@ PRINT_CONFIG_CLASS_DEFINE( // Spacing between interface lines (the hatching distance). Set zero to get a solid interface. ((ConfigOptionFloat, support_interface_spacing)) ((ConfigOptionFloatsNullable, support_interface_speed)) + ((ConfigOptionFloatsOrPercentsNullable, support_interface_volumetric_flow)) ((ConfigOptionEnum, support_base_pattern)) ((ConfigOptionEnum, support_interface_pattern)) // Spacing between support material lines (the hatching distance). ((ConfigOptionFloat, support_base_pattern_spacing)) ((ConfigOptionFloat, support_expansion)) ((ConfigOptionFloatsNullable, support_speed)) + ((ConfigOptionFloatsOrPercentsNullable, support_volumetric_flow)) ((ConfigOptionEnum, support_style)) // Orca: a flag enabling the ability to override flow ratios @@ -1466,6 +1468,8 @@ PRINT_CONFIG_CLASS_DEFINE( ((ConfigOptionFloat, internal_bridge_flow)) ((ConfigOptionFloatsNullable, bridge_speed)) ((ConfigOptionFloatsOrPercentsNullable, internal_bridge_speed)) + ((ConfigOptionFloatsOrPercentsNullable, bridge_volumetric_flow)) + ((ConfigOptionFloatsOrPercentsNullable, internal_bridge_volumetric_flow)) ((ConfigOptionEnum, ensure_vertical_shell_thickness)) ((ConfigOptionPercent, top_surface_density)) ((ConfigOptionPercent, bottom_surface_density)) @@ -1476,6 +1480,7 @@ PRINT_CONFIG_CLASS_DEFINE( ((ConfigOptionEnum, internal_solid_infill_pattern)) ((ConfigOptionFloatOrPercent, outer_wall_line_width)) ((ConfigOptionFloatsNullable, outer_wall_speed)) + ((ConfigOptionFloatsOrPercentsNullable, outer_wall_volumetric_flow)) ((ConfigOptionFloat, infill_direction)) ((ConfigOptionFloat, solid_infill_direction)) ((ConfigOptionFloat, top_layer_direction)) @@ -1511,11 +1516,13 @@ PRINT_CONFIG_CLASS_DEFINE( ((ConfigOptionPercent, fuzzy_skin_ripple_offset)) ((ConfigOptionInt, fuzzy_skin_layers_between_ripple_offset)) ((ConfigOptionFloatsNullable, gap_infill_speed)) + ((ConfigOptionFloatsOrPercentsNullable, gap_infill_volumetric_flow)) ((ConfigOptionInt, sparse_infill_filament_id)) ((ConfigOptionFloatOrPercent, sparse_infill_line_width)) ((ConfigOptionPercent, infill_wall_overlap)) ((ConfigOptionPercent, top_bottom_infill_wall_overlap)) ((ConfigOptionFloatsNullable, sparse_infill_speed)) + ((ConfigOptionFloatsOrPercentsNullable, sparse_infill_volumetric_flow)) ((ConfigOptionPercent, skeleton_infill_density)) ((ConfigOptionPercent, skin_infill_density)) ((ConfigOptionFloat, infill_lock_depth)) @@ -1552,6 +1559,7 @@ PRINT_CONFIG_CLASS_DEFINE( ((ConfigOptionInt, inner_wall_filament_id)) ((ConfigOptionFloatOrPercent, inner_wall_line_width)) ((ConfigOptionFloatsNullable, inner_wall_speed)) + ((ConfigOptionFloatsOrPercentsNullable, inner_wall_volumetric_flow)) // Total number of perimeters. ((ConfigOptionInt, wall_loops)) ((ConfigOptionBool, alternate_extra_wall)) @@ -1561,6 +1569,7 @@ PRINT_CONFIG_CLASS_DEFINE( ((ConfigOptionInt, bottom_surface_filament_id)) ((ConfigOptionFloatOrPercent, internal_solid_infill_line_width)) ((ConfigOptionFloatsNullable, internal_solid_infill_speed)) + ((ConfigOptionFloatsOrPercentsNullable, internal_solid_infill_volumetric_flow)) // Detect thin walls. ((ConfigOptionBool, detect_thin_wall)) ((ConfigOptionFloatOrPercent, top_surface_line_width)) @@ -1571,6 +1580,7 @@ PRINT_CONFIG_CLASS_DEFINE( ((ConfigOptionFloat, top_surface_expansion_margin)) ((ConfigOptionEnum, top_surface_expansion_direction)) ((ConfigOptionFloatsNullable, top_surface_speed)) + ((ConfigOptionFloatsOrPercentsNullable, top_surface_volumetric_flow)) //BBS ((ConfigOptionBoolsNullable, enable_overhang_speed)) ((ConfigOptionFloatsOrPercentsNullable, overhang_1_4_speed)) @@ -1757,6 +1767,7 @@ PRINT_CONFIG_CLASS_DEFINE( ((ConfigOptionStrings, default_filament_colour)) ((ConfigOptionInts, temperature_vitrification)) //BBS ((ConfigOptionFloats, filament_max_volumetric_speed)) + ((ConfigOptionFloats, filament_max_external_volumetric_speed)) ((ConfigOptionInts, required_nozzle_HRC)) ((ConfigOptionEnum, filament_map_mode)) ((ConfigOptionInts, filament_map)) @@ -2049,9 +2060,12 @@ PRINT_CONFIG_CLASS_DERIVED_DEFINE( ((ConfigOptionFloatOrPercent, initial_layer_line_width)) ((ConfigOptionFloat, initial_layer_print_height)) ((ConfigOptionFloatsNullable, initial_layer_speed)) + ((ConfigOptionFloatsOrPercentsNullable, initial_layer_volumetric_flow)) //BBS ((ConfigOptionFloatsNullable, initial_layer_infill_speed)) + ((ConfigOptionFloatsOrPercentsNullable, initial_layer_infill_volumetric_flow)) + ((ConfigOptionBool, enable_volumetric_speeds)) ((ConfigOptionInts, nozzle_temperature_initial_layer)) ((ConfigOptionInts, full_fan_speed_layer)) // ORCA: explicit override for the part cooling fan speed on the first printed layer. diff --git a/src/libslic3r/PrintObject.cpp b/src/libslic3r/PrintObject.cpp index 69f9410876..bb7346426d 100644 --- a/src/libslic3r/PrintObject.cpp +++ b/src/libslic3r/PrintObject.cpp @@ -1503,7 +1503,13 @@ bool PrintObject::invalidate_state_by_config_options( || opt_key == "inner_wall_speed" || opt_key == "support_speed" || opt_key == "internal_solid_infill_speed" - || opt_key == "top_surface_speed") { + || opt_key == "top_surface_speed" + || opt_key == "outer_wall_volumetric_flow" + || opt_key == "inner_wall_volumetric_flow" + || opt_key == "sparse_infill_volumetric_flow" + || opt_key == "internal_solid_infill_volumetric_flow" + || opt_key == "top_surface_volumetric_flow" + || opt_key == "support_volumetric_flow") { // Brim is printed below supports, support invalidates brim and skirt. steps.emplace_back(posSupportMaterial); if (opt_key == "brim_type" || opt_key == "brim_width") { @@ -1530,7 +1536,8 @@ bool PrintObject::invalidate_state_by_config_options( || opt_key == "seam_gap" || opt_key == "role_based_wipe_speed" || opt_key == "wipe_on_loops" - || opt_key == "wipe_speed") { + || opt_key == "wipe_speed" + || opt_key == "gap_infill_volumetric_flow") { steps.emplace_back(posPerimeters); } else if ( opt_key == "small_area_infill_flow_compensation_model") { @@ -1841,6 +1848,9 @@ bool PrintObject::invalidate_state_by_config_options( || opt_key == "overhang_4_4_speed" || opt_key == "bridge_speed" || opt_key == "internal_bridge_speed" + || opt_key == "support_interface_volumetric_flow" + || opt_key == "bridge_volumetric_flow" + || opt_key == "internal_bridge_volumetric_flow" || opt_key == "outer_wall_speed" || opt_key == "small_perimeter_speed" || opt_key == "small_perimeter_threshold" diff --git a/src/slic3r/GUI/ConfigManipulation.cpp b/src/slic3r/GUI/ConfigManipulation.cpp index 97cf6b9cea..6eebb50e09 100644 --- a/src/slic3r/GUI/ConfigManipulation.cpp +++ b/src/slic3r/GUI/ConfigManipulation.cpp @@ -816,7 +816,8 @@ void ConfigManipulation::toggle_print_fff_options(DynamicPrintConfig *config, in for (auto el : { "extra_perimeters_on_overhangs", "ensure_vertical_shell_thickness", "detect_thin_wall", "detect_overhang_wall", "seam_position", "staggered_inner_seams", "wall_sequence", "outer_wall_line_width" }) toggle_field(el, have_perimeters, -1, wall_loops_reason); - for (auto el : { "inner_wall_speed", "outer_wall_speed", "small_perimeter_speed", "small_perimeter_threshold" }) + for (auto el : { "inner_wall_speed", "outer_wall_speed", "small_perimeter_speed", "small_perimeter_threshold", + "inner_wall_volumetric_flow", "outer_wall_volumetric_flow" }) toggle_field(el, have_perimeters, variant_index, wall_loops_reason); bool have_infill = config->option("sparse_infill_density")->value > 0; @@ -945,7 +946,8 @@ void ConfigManipulation::toggle_print_fff_options(DynamicPrintConfig *config, in "solid_infill_direction", "solid_infill_rotate_template", "internal_solid_infill_pattern", "internal_solid_filament_id", "top_surface_filament_id", "bottom_surface_filament_id", }) toggle_field(el, have_infill || has_solid_infill, -1, infill_or_shell_reason); - for (auto el : { "sparse_infill_speed", "bridge_speed", "internal_bridge_speed"}) + for (auto el : { "sparse_infill_speed", "bridge_speed", "internal_bridge_speed", + "sparse_infill_volumetric_flow", "bridge_volumetric_flow", "internal_bridge_volumetric_flow" }) toggle_field(el, have_infill || has_solid_infill, variant_index, infill_or_shell_reason); toggle_field("top_shell_thickness", ! has_spiral_vase && has_top_shell_layers, -1, _L("Disable spiral vase mode and set top shell layers above zero to edit top shell thickness.")); @@ -953,9 +955,21 @@ void ConfigManipulation::toggle_print_fff_options(DynamicPrintConfig *config, in // Gap fill is newly allowed in between perimeter lines even for empty infill (see GH #1476). toggle_field("gap_infill_speed", have_perimeters, variant_index, wall_loops_reason); + toggle_field("gap_infill_volumetric_flow", have_perimeters, variant_index, wall_loops_reason); toggle_field("top_surface_line_width", has_top_shell, -1, top_shell_reason); toggle_field("top_surface_speed", has_top_shell, variant_index, top_shell_reason); + toggle_field("top_surface_volumetric_flow", has_top_shell, variant_index, top_shell_reason); + + // Orca: each feature shows either its linear speed or its volumetric alternative. + const bool use_volumetric_speeds = config->opt_bool("enable_volumetric_speeds"); + const wxString linear_speed_reason = _L("Disable volumetric speeds to use this setting."); + const wxString volumetric_speed_reason = _L("Enable volumetric speeds to use this setting."); + for (const std::string feature : { "initial_layer", "initial_layer_infill", "outer_wall", "inner_wall", "sparse_infill", + "internal_solid_infill", "top_surface", "gap_infill", "support", "support_interface", "bridge" }) { + toggle_line(feature + "_speed", !use_volumetric_speeds, variant_index, linear_speed_reason); + toggle_line(feature + "_volumetric_flow", use_volumetric_speeds, variant_index, volumetric_speed_reason); + } bool have_default_acceleration = config->opt_float_nullable("default_acceleration", variant_index) > 0; diff --git a/src/slic3r/GUI/GUI_Factories.cpp b/src/slic3r/GUI/GUI_Factories.cpp index caf6cbfd20..75c3d22265 100644 --- a/src/slic3r/GUI/GUI_Factories.cpp +++ b/src/slic3r/GUI/GUI_Factories.cpp @@ -125,7 +125,8 @@ std::map> SettingsFactory::OBJECT_C {"support_object_xy_distance", "",30}, {"bridge_no_support", "",31},{"max_bridge_length", "",32},{"support_critical_regions_only", "",33},{"support_remove_small_overhang","",34}, {"support_object_first_layer_gap","",35} }}, - { L("Speed"), {{"support_speed", "",12}, {"support_interface_speed", "",13} + { L("Speed"), {{"support_speed", "",12}, {"support_interface_speed", "",13}, + {"support_volumetric_flow", "",12}, {"support_interface_volumetric_flow", "",13} }} }; @@ -189,18 +190,26 @@ std::map> SettingsFactory::PART_CATE {"minimum_sparse_infill_area", "", 1}}}, {L("Speed"), {{"outer_wall_speed", "", 1}, + {"outer_wall_volumetric_flow", "", 1}, {"inner_wall_speed", "", 2}, + {"inner_wall_volumetric_flow", "", 2}, {"sparse_infill_speed", "", 3}, + {"sparse_infill_volumetric_flow", "", 3}, {"top_surface_speed", "", 4}, + {"top_surface_volumetric_flow", "", 4}, {"internal_solid_infill_speed", "", 5}, + {"internal_solid_infill_volumetric_flow", "", 5}, {"enable_overhang_speed", "", 6}, {"overhang_1_4_speed", "", 7}, {"overhang_2_4_speed", "", 8}, {"overhang_3_4_speed", "", 9}, {"overhang_4_4_speed", "", 10}, {"bridge_speed", "", 11}, + {"bridge_volumetric_flow", "", 11}, {"gap_infill_speed", "", 12}, - {"internal_bridge_speed", "", 13}}}}; + {"gap_infill_volumetric_flow", "", 12}, + {"internal_bridge_speed", "", 13}, + {"internal_bridge_volumetric_flow", "", 13}}}}; std::vector SettingsFactory::get_options(const bool is_part) { diff --git a/src/slic3r/GUI/Plater.cpp b/src/slic3r/GUI/Plater.cpp index 72b6b6364a..0f4059e553 100644 --- a/src/slic3r/GUI/Plater.cpp +++ b/src/slic3r/GUI/Plater.cpp @@ -17657,6 +17657,8 @@ void adjust_settings_for_flowrate_calib(ModelObjectPtrs& objects, bool linear, i _obj->config.set_key_value("seam_slope_type", new ConfigOptionEnum(SeamScarfType::None)); _obj->config.set_key_value("gap_fill_target", new ConfigOptionEnum(GapFillTarget::gftNowhere)); print_config->set_key_value("max_volumetric_extrusion_rate_slope", new ConfigOptionFloat(0)); + // ORCA: the speeds above are linear, and no calibration mode switches volumetric speeds off here. + print_config->set_key_value("enable_volumetric_speeds", new ConfigOptionBool(false)); // ORCA: request the calibration's special toolpath order (chords first, center spiral // last and inside-out) so opposing directions collide into the tactile lip the test // reads. The special order only applies while the fill order is Default, so reset the diff --git a/src/slic3r/GUI/Tab.cpp b/src/slic3r/GUI/Tab.cpp index f08efd85f8..23e8ad0107 100644 --- a/src/slic3r/GUI/Tab.cpp +++ b/src/slic3r/GUI/Tab.cpp @@ -3252,23 +3252,36 @@ void TabPrint::build() optgroup->append_single_option_line("ensure_vertical_shell_thickness", "strength_settings_advanced#ensure-vertical-shell-thickness"); page = add_options_page(L("Speed"), "custom-gcode_speed"); // ORCA: icon only visible on placeholders + // Orca: each speed below is followed by its volumetric alternative; ConfigManipulation shows one of the two. + optgroup = page->new_optgroup(L("Speed definition"), L"param_volumetric_speed", 15); + optgroup->append_single_option_line("enable_volumetric_speeds", "speed_settings_other_layers_speed#volumetric-speeds"); optgroup = page->new_optgroup(L("First layer speed"), L"param_speed_first", 15); optgroup->append_single_option_line("initial_layer_speed", "speed_settings_initial_layer_speed#initial-layer", 0); + optgroup->append_single_option_line("initial_layer_volumetric_flow", "speed_settings_initial_layer_speed#initial-layer", 0); optgroup->append_single_option_line("initial_layer_infill_speed", "speed_settings_initial_layer_speed#initial-layer-infill", 0); + optgroup->append_single_option_line("initial_layer_infill_volumetric_flow", "speed_settings_initial_layer_speed#initial-layer-infill", 0); optgroup->append_single_option_line("initial_layer_travel_speed", "speed_settings_initial_layer_speed#initial-layer-travel-speed", 0); optgroup->append_single_option_line("slow_down_layers", "speed_settings_initial_layer_speed#number-of-slow-layers"); optgroup = page->new_optgroup(L("Other layers speed"), L"param_speed", 15); optgroup->append_single_option_line("outer_wall_speed", "speed_settings_other_layers_speed#outer-wall", 0); + optgroup->append_single_option_line("outer_wall_volumetric_flow", "speed_settings_other_layers_speed#outer-wall", 0); optgroup->append_single_option_line("inner_wall_speed", "speed_settings_other_layers_speed#inner-wall", 0); + optgroup->append_single_option_line("inner_wall_volumetric_flow", "speed_settings_other_layers_speed#inner-wall", 0); optgroup->append_single_option_line("small_perimeter_speed", "speed_settings_other_layers_speed#small-perimeters", 0); optgroup->append_single_option_line("small_perimeter_threshold", "speed_settings_other_layers_speed#small-perimeters-threshold", 0); optgroup->append_single_option_line("sparse_infill_speed", "speed_settings_other_layers_speed#sparse-infill", 0); + optgroup->append_single_option_line("sparse_infill_volumetric_flow", "speed_settings_other_layers_speed#sparse-infill", 0); optgroup->append_single_option_line("internal_solid_infill_speed", "speed_settings_other_layers_speed#internal-solid-infill", 0); + optgroup->append_single_option_line("internal_solid_infill_volumetric_flow", "speed_settings_other_layers_speed#internal-solid-infill", 0); optgroup->append_single_option_line("top_surface_speed", "speed_settings_other_layers_speed#top-surface", 0); + optgroup->append_single_option_line("top_surface_volumetric_flow", "speed_settings_other_layers_speed#top-surface", 0); optgroup->append_single_option_line("gap_infill_speed", "speed_settings_other_layers_speed#gap-infill", 0); + optgroup->append_single_option_line("gap_infill_volumetric_flow", "speed_settings_other_layers_speed#gap-infill", 0); optgroup->append_single_option_line("ironing_speed", "speed_settings_other_layers_speed#ironing-speed"); optgroup->append_single_option_line("support_speed", "speed_settings_other_layers_speed#support", 0); + optgroup->append_single_option_line("support_volumetric_flow", "speed_settings_other_layers_speed#support", 0); optgroup->append_single_option_line("support_interface_speed", "speed_settings_other_layers_speed#support-interface", 0); + optgroup->append_single_option_line("support_interface_volumetric_flow", "speed_settings_other_layers_speed#support-interface", 0); optgroup->append_single_option_line("small_support_perimeter_speed", "speed_settings_other_layers_speed#small-tree-support-perimeters", 0); optgroup->append_single_option_line("small_support_perimeter_threshold", "speed_settings_other_layers_speed#small-tree-support-perimeters-threshold", 0); optgroup = page->new_optgroup(L("Overhang speed"), L"param_overhang_speed", 15); @@ -3284,9 +3297,15 @@ void TabPrint::build() optgroup->append_line(line); optgroup->append_separator(); line = { L("Bridge"), L("Set speed for external and internal bridges") }; + line.label_path = "speed_settings_overhang_speed#bridge-speed"; line.append_option(optgroup->get_option("bridge_speed", 0)); line.append_option(optgroup->get_option("internal_bridge_speed", 0)); optgroup->append_line(line); + line = { L("Bridge"), L("Set volumetric speed for external and internal bridges") }; + line.label_path = "speed_settings_overhang_speed#bridge-speed"; + line.append_option(optgroup->get_option("bridge_volumetric_flow", 0)); + line.append_option(optgroup->get_option("internal_bridge_volumetric_flow", 0)); + optgroup->append_line(line); optgroup = page->new_optgroup(L("Travel speed"), L"param_travel_speed", 15); optgroup->append_single_option_line("travel_speed", "speed_settings_travel", 0); @@ -4959,6 +4978,7 @@ void TabFilament::build() optgroup = page->new_optgroup(L("Volumetric speed limitation"), L"param_volumetric_speed"); optgroup->append_single_option_line("filament_adaptive_volumetric_speed", "material_volumetric_speed_limitation#adaptive-volumetric-speed", 0); optgroup->append_single_option_line("filament_max_volumetric_speed", "material_volumetric_speed_limitation#max-volumetric-speed", 0); + optgroup->append_single_option_line("filament_max_external_volumetric_speed", "material_volumetric_speed_limitation#max-external-volumetric-speed", 0); //line = { "", "" }; //line.full_width = 1; diff --git a/tests/fff_print/test_gcode.cpp b/tests/fff_print/test_gcode.cpp index d56f29afbb..44e7b489c1 100644 --- a/tests/fff_print/test_gcode.cpp +++ b/tests/fff_print/test_gcode.cpp @@ -28,12 +28,16 @@ #include #include #include +#include #include #include #include #include +#include #include #include +#include +#include #include #include #include @@ -795,3 +799,160 @@ TEST_CASE("The temperature tower steps the temperature of the tool printing it", CHECK(tools == std::set{multi_tool ? "1" : "none"}); } } + +namespace { + +constexpr double filament_diameter = 1.75; +constexpr double max_volumetric_speed = 20.; +constexpr double layer_height = 0.2; + +// A 20mm cube sliced at 0.2mm layers with volumetric speeds `enabled` and `extra` applied last. +std::string volumetric_speed_gcode(bool enabled, std::initializer_list extra) +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + config.set_deserialize_strict({ + {"enable_volumetric_speeds", enabled ? "1" : "0"}, + {"filament_diameter", filament_diameter}, + {"filament_max_volumetric_speed", max_volumetric_speed}, + {"layer_height", layer_height}, + {"initial_layer_print_height", layer_height}, + {"slow_down_for_layer_cooling", "0"}, + {"slow_down_layers", "0"}, + {"enable_arc_fitting", "0"}, + }); + config.set_deserialize_strict(extra); + return Test::slice({Test::cube(20.)}, config); +} + +// For each extrusion move longer than 1mm of `role` above the first layer: its feed rate (mm/s) and extruded flow (mm³/s). +std::vector> role_speeds_and_flows(const std::string &gcode, std::string_view role) +{ + const double filament_area = 0.25 * M_PI * filament_diameter * filament_diameter; + std::vector> moves; + bool in_role = false; + GCodeReader parser; + parser.parse_buffer(gcode, [&](GCodeReader &self, const GCodeReader::GCodeLine &line) { + const std::string_view comment = line.comment(); + if (comment.find("TYPE:") != std::string_view::npos) + in_role = comment.substr(comment.find("TYPE:") + 5) == role; + if (in_role && line.extruding(self) && line.dist_XY(self) > 1. && line.new_Z(self) > 1.5 * layer_height) { + const double speed = line.new_F(self) / Test::MM_PER_MIN; + moves.emplace_back(speed, line.dist_E(self) * filament_area / line.dist_XY(self) * speed); + } + }); + return moves; +} + +} // namespace + +TEST_CASE("Volumetric speeds print each feature at its configured flow", "[GCode]") +{ + const auto [key, role] = GENERATE(table({ + {"outer_wall_volumetric_flow", "Outer wall"}, + {"inner_wall_volumetric_flow", "Inner wall"}, + {"sparse_infill_volumetric_flow", "Sparse infill"}, + {"internal_solid_infill_volumetric_flow", "Internal solid infill"}, + {"top_surface_volumetric_flow", "Top surface"}, + })); + INFO(key); + const double flow = 6.; + const auto moves = role_speeds_and_flows(volumetric_speed_gcode(true, {{key, flow}}), role); + + REQUIRE_FALSE(moves.empty()); + for (const auto &[speed, extruded_flow] : moves) + CHECK_THAT(extruded_flow, Catch::Matchers::WithinRel(flow, 0.01)); +} + +TEST_CASE("A volumetric speed in percent is a share of the filament's max volumetric speed, which caps it", "[GCode]") +{ + const auto [value, expected_flow] = GENERATE(table({ + {"50%", 0.5 * max_volumetric_speed}, + {"300%", max_volumetric_speed}, + {"40", max_volumetric_speed}, + })); + INFO(value); + const auto moves = role_speeds_and_flows(volumetric_speed_gcode(true, {{"outer_wall_volumetric_flow", value}}), "Outer wall"); + + REQUIRE_FALSE(moves.empty()); + for (const auto &[speed, extruded_flow] : moves) + CHECK_THAT(extruded_flow, Catch::Matchers::WithinRel(expected_flow, 0.01)); +} + +TEST_CASE("Volumetric speeds are ignored while disabled", "[GCode]") +{ + const double outer_wall_speed = 50.; + const auto moves = role_speeds_and_flows( + volumetric_speed_gcode(false, {{"outer_wall_speed", outer_wall_speed}, {"outer_wall_volumetric_flow", "2"}}), "Outer wall"); + + REQUIRE_FALSE(moves.empty()); + for (const auto &[speed, extruded_flow] : moves) + CHECK_THAT(speed, Catch::Matchers::WithinRel(outer_wall_speed, 0.001)); +} + +TEST_CASE("The max external volumetric speed limits outer walls but not inner walls", "[GCode]") +{ + // At 200mm/s both walls would extrude well above the external limit and below the filament limit. + const double max_external = 5.; + const std::string gcode = volumetric_speed_gcode(false, {{"filament_max_external_volumetric_speed", max_external}, + {"outer_wall_speed", 200.}, + {"inner_wall_speed", 200.}}); + const auto outer_wall = role_speeds_and_flows(gcode, "Outer wall"); + const auto inner_wall = role_speeds_and_flows(gcode, "Inner wall"); + + REQUIRE_FALSE(outer_wall.empty()); + REQUIRE_FALSE(inner_wall.empty()); + for (const auto &[speed, extruded_flow] : outer_wall) + CHECK_THAT(extruded_flow, Catch::Matchers::WithinRel(max_external, 0.01)); + for (const auto &[speed, extruded_flow] : inner_wall) + CHECK(extruded_flow > 2. * max_external); +} + +TEST_CASE("The max external volumetric speed limits top surfaces only when they are not ironed", "[GCode]") +{ + const auto [ironing_type, limited] = GENERATE(table({ + {"no ironing", true}, + {"top", false}, + })); + INFO(ironing_type); + const double max_external = 5.; + const auto moves = role_speeds_and_flows(volumetric_speed_gcode(false, {{"filament_max_external_volumetric_speed", max_external}, + {"top_surface_speed", 200.}, + {"ironing_type", ironing_type}}), + "Top surface"); + + REQUIRE_FALSE(moves.empty()); + for (const auto &[speed, extruded_flow] : moves) { + if (limited) + CHECK_THAT(extruded_flow, Catch::Matchers::WithinRel(max_external, 0.01)); + else + CHECK(extruded_flow > 2. * max_external); + } +} + +// Resonance avoidance moves an outer wall in the upper half of its band up to the band's top. When the +// volumetric limit keeps the wall below that top, the boost would exceed the limit, so the wall drops to +// the band's bottom instead. +TEST_CASE("Resonance avoidance keeps outer walls within their volumetric speed limit", "[GCode]") +{ + static constexpr double min_avoided = 40., max_avoided = 90.; + const auto [limit_key, limit, outer_wall_speed, expected_speed] = GENERATE(table({ + // 6 mm3/s caps a 0.2 mm wall at about 75-80 mm/s, in the upper half of the band. + {"filament_max_external_volumetric_speed", 6., 200., min_avoided}, + {"filament_max_volumetric_speed", 6., 200., min_avoided}, + // 10 mm3/s allows the top of the band, so a 75 mm/s wall is still boosted to it. + {"filament_max_external_volumetric_speed", 10., 75., max_avoided}, + })); + INFO(limit_key << " = " << limit << ", outer wall " << outer_wall_speed << " mm/s"); + const auto moves = role_speeds_and_flows(volumetric_speed_gcode(false, {{limit_key, limit}, + {"outer_wall_speed", outer_wall_speed}, + {"resonance_avoidance", "1"}, + {"min_resonance_avoidance_speed", min_avoided}, + {"max_resonance_avoidance_speed", max_avoided}}), + "Outer wall"); + + REQUIRE_FALSE(moves.empty()); + for (const auto &[speed, extruded_flow] : moves) { + CHECK(extruded_flow <= limit * 1.01); + CHECK_THAT(speed, Catch::Matchers::WithinAbs(expected_speed, 0.5)); + } +} From 9cdaaedad786974743122961e53aaa1301aa47ef Mon Sep 17 00:00:00 2001 From: Kiss Lorand <50251547+kisslorand@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:35:55 +0200 Subject: [PATCH 18/60] Fix Measure geometry after nonuniform scaling (#17549) --- src/libslic3r/Measure.cpp | 4 +- src/slic3r/GUI/Gizmos/GLGizmoMeasure.cpp | 24 +++- src/slic3r/GUI/Gizmos/GLGizmoMeasure.hpp | 1 + tests/libslic3r/CMakeLists.txt | 1 + tests/libslic3r/test_measure.cpp | 158 +++++++++++++++++++++++ 5 files changed, 178 insertions(+), 10 deletions(-) create mode 100644 tests/libslic3r/test_measure.cpp diff --git a/src/libslic3r/Measure.cpp b/src/libslic3r/Measure.cpp index 918bbac1f2..63a85176ff 100644 --- a/src/libslic3r/Measure.cpp +++ b/src/libslic3r/Measure.cpp @@ -1417,10 +1417,8 @@ void SurfaceFeature::translate(const Transform3d &tran) } case Measure::SurfaceFeatureType::Plane: { // m_pt1 is normal; - Vec3d temp_pt1 = m_pt2 + m_pt1; - temp_pt1 = tran * temp_pt1; + m_pt1 = (tran.linear().inverse().transpose() * m_pt1).normalized(); m_pt2 = tran * m_pt2; - m_pt1 = (temp_pt1 - m_pt2).normalized(); break; } case Measure::SurfaceFeatureType::Circle: { diff --git a/src/slic3r/GUI/Gizmos/GLGizmoMeasure.cpp b/src/slic3r/GUI/Gizmos/GLGizmoMeasure.cpp index 9d74e11bf1..4ffa7ff925 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoMeasure.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoMeasure.cpp @@ -294,7 +294,8 @@ bool GLGizmoMeasure::on_mouse(const wxMouseEvent &mouse_event) case EMode::FeatureSelection: { item = { false, m_curr_feature, m_curr_feature }; break; } case EMode::PointSelection: { item = { false, m_curr_feature, Measure::SurfaceFeature(*m_curr_point_on_feature_position)}; - auto local_pt = m_curr_feature->world_tran.inverse() * (*m_curr_point_on_feature_position); + const auto &base = m_mesh_measure_transform.at(static_cast(m_curr_feature->volume)); + auto local_pt = base * m_curr_feature->world_tran.inverse() * (*m_curr_point_on_feature_position); item.feature->origin_surface_feature = std::make_shared(local_pt); item.feature->world_tran = m_curr_feature->world_tran; item.feature->volume = m_curr_feature->volume; @@ -519,6 +520,7 @@ void GLGizmoMeasure::on_set_state() m_editing_distance = false; m_is_editing_distance_first_frame = true; std::map>().swap(m_mesh_measure_map); + m_mesh_measure_transform.clear(); } else { m_mode = EMode::FeatureSelection; @@ -712,8 +714,9 @@ void GLGizmoMeasure::on_render() std::optional curr_feature = std::nullopt; if (m_curr_measuring) { curr_feature = wxGetMouseState().LeftIsDown() ? m_curr_feature : - mouse_on_object ? m_curr_measuring->get_feature(model_facet_idx, position_on_model, - m_mesh_raycaster_map[m_last_hit_volume]->get_transform(), m_only_select_plane) : + mouse_on_object ? m_curr_measuring->get_feature(model_facet_idx, + m_mesh_measure_transform.at(m_last_hit_volume) * position_on_model, + m_mesh_raycaster_map[m_last_hit_volume]->get_transform() * m_mesh_measure_transform.at(m_last_hit_volume).inverse(), m_only_select_plane) : std::nullopt; } if (m_measure_mode == EMeasureMode::ONLY_ASSEMBLY && curr_feature.has_value()) { @@ -2346,10 +2349,17 @@ void GLGizmoMeasure::register_single_mesh_pick() } else { const ModelObject* obj = selection.get_model()->objects[v->object_idx()]; const ModelVolume* vol = obj->volumes[v->volume_idx()]; - auto mesh = vol->mesh_ptr(); + indexed_triangle_set mesh = vol->mesh_ptr()->its; + Transform3d base = Transform3d::Identity(); + base.linear() = world_tran.get_matrix().linear(); + for (Vec3f &vertex : mesh.vertices) + vertex = (base * vertex.cast()).cast(); + if (base.linear().determinant() < 0.0) + its_flip_triangles(mesh); + m_mesh_measure_transform[v] = base; m_mesh_raycaster_map[v] = std::make_shared(-1, *v->mesh_raycaster, world_tran.get_matrix()); m_mesh_raycaster_map[v]->set_transform(world_tran.get_matrix()); - m_mesh_measure_map[v] = std::make_shared(mesh->its); + m_mesh_measure_map[v] = std::make_shared(mesh); } } } @@ -2479,7 +2489,7 @@ void GLGizmoMeasure::update_world_plane_features(Measure::Measuring *cur_measuri feautre.world_plane_features->clear(); // resize(cur_plane_features->size()); for (size_t i = 0; i < cur_plane_features->size(); i++) { Measure::SurfaceFeature temp(cur_plane_features->at(i)); - temp.translate(feautre.world_tran); + temp.translate(feautre.world_tran * m_mesh_measure_transform.at(static_cast(feautre.volume)).inverse()); feautre.world_plane_features->push_back(std::move(temp)); } } @@ -2497,7 +2507,7 @@ void GLGizmoMeasure::update_feature_by_tran(Measure::SurfaceFeature &feature) case Measure::SurfaceFeatureType::Circle: case Measure::SurfaceFeatureType::Plane: { feature.clone(*feature.origin_surface_feature); - feature.translate(feature.world_tran); + feature.translate(feature.world_tran * m_mesh_measure_transform.at(volume).inverse()); if (feature.get_type() == Measure::SurfaceFeatureType::Circle) { m_feature_circle_first.last_circle_feature.reset(); m_feature_circle_first.inv_zoom = 0; diff --git a/src/slic3r/GUI/Gizmos/GLGizmoMeasure.hpp b/src/slic3r/GUI/Gizmos/GLGizmoMeasure.hpp index 33d0998cea..9ae8a983b8 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoMeasure.hpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoMeasure.hpp @@ -167,6 +167,7 @@ protected: Measure::MeasurementResult m_measurement_result; Measure::AssemblyAction m_assembly_action; std::map> m_mesh_measure_map; + std::map m_mesh_measure_transform; std::shared_ptr m_curr_measuring{nullptr}; //first feature diff --git a/tests/libslic3r/CMakeLists.txt b/tests/libslic3r/CMakeLists.txt index f20e7e791e..41c0fb05df 100644 --- a/tests/libslic3r/CMakeLists.txt +++ b/tests/libslic3r/CMakeLists.txt @@ -51,6 +51,7 @@ add_executable(${_TEST_NAME}_tests test_fill_plane_path.cpp test_adaptive_infill_field.cpp test_geometry.cpp + test_measure.cpp test_kdtree.cpp test_lightning.cpp test_imex_arrange.cpp diff --git a/tests/libslic3r/test_measure.cpp b/tests/libslic3r/test_measure.cpp new file mode 100644 index 0000000000..d8d8866d0a --- /dev/null +++ b/tests/libslic3r/test_measure.cpp @@ -0,0 +1,158 @@ +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "libslic3r/Measure.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/TriangleMesh.hpp" +#include "libslic3r/libslic3r.h" + +using namespace Slic3r; +using namespace Slic3r::Measure; +using Catch::Matchers::WithinAbs; + +TEST_CASE("Scaled plane normals remain perpendicular to the transformed surface", "[Measure]") +{ + const Vec3d normal = Vec3d(1, 0, 1).normalized(); + SurfaceFeature plane(SurfaceFeatureType::Plane, normal, Vec3d::Zero()); + Transform3d transform = Transform3d::Identity(); + transform.linear() = Vec3d(2, 3, 4).asDiagonal(); + plane.translate(transform); + const Vec3d transformed_normal = std::get<1>(plane.get_plane()); + CHECK_THAT(transformed_normal.dot(transform.linear() * Vec3d(1, 0, -1)), WithinAbs(0.0, 1e-12)); + CHECK_THAT(transformed_normal.norm(), WithinAbs(1.0, 1e-12)); +} + +TEST_CASE("Uniform in-plane scaling preserves a circle radius", "[Measure]") +{ + SurfaceFeature circle(SurfaceFeatureType::Circle, Vec3d(1, 2, 3), Vec3d::UnitZ(), std::nullopt, 5.0); + Transform3d transform = Transform3d::Identity(); + transform.linear() = Vec3d(2, 2, 4).asDiagonal(); + circle.translate(transform); + const auto [center, radius, normal] = circle.get_circle(); + CHECK_THAT(radius, WithinAbs(10.0, 1e-12)); + CHECK_THAT((center - Vec3d(2, 4, 12)).norm(), WithinAbs(0.0, 1e-12)); + CHECK_THAT(normal.dot(Vec3d::UnitZ()), WithinAbs(1.0, 1e-12)); +} + +TEST_CASE("Circle detection uses the transformed mesh boundary", "[Measure]") +{ + auto circle_radius = [](double source_y_scale, double x_scale, double y_scale, bool noisy = false) { + indexed_triangle_set mesh = its_make_cylinder(10., 20., PI / 90.); + for (size_t i = 2; i < mesh.vertices.size(); ++i) { + Vec3f &vertex = mesh.vertices[i]; + const float radial_scale = noisy && (i / 2) % 2 == 0 ? 1.0005f : 1.f; + vertex.x() *= radial_scale; + vertex.y() *= radial_scale * float(source_y_scale); + } + for (Vec3f &vertex : mesh.vertices) { + vertex.x() *= float(x_scale); + vertex.y() *= float(y_scale); + } + Measuring measuring(mesh); + for (int i = 0; i < measuring.get_num_of_planes(); ++i) { + const auto &features = measuring.get_plane_features(i); + const auto circle = std::find_if(features.begin(), features.end(), [](const SurfaceFeature &feature) { + return feature.get_type() == SurfaceFeatureType::Circle; + }); + if (circle != features.end()) + return std::get<1>(circle->get_circle()); + } + return -1.0; + }; + + CHECK_THAT(circle_radius(1., 2., 2.), WithinAbs(20., 0.01)); + CHECK_THAT(circle_radius(1., 1., 1.), WithinAbs(10., 0.01)); + CHECK_THAT(circle_radius(2., 2., 1.), WithinAbs(20., 0.01)); + CHECK_THAT(circle_radius(1., 1., 1., true), WithinAbs(10., 0.01)); + CHECK(circle_radius(1., 2., 1.) < 0.); +} + +TEST_CASE("Plane features follow the geometry of a stretched mesh", "[Measure]") +{ + indexed_triangle_set mesh = its_make_cube(10., 10., 10.); + Transform3d transform = Transform3d::Identity(); + transform.linear() << 2., 0., 1., 0., 3., 0., 0., 0., 4.; + for (Vec3f &vertex : mesh.vertices) + vertex = (transform * vertex.cast()).cast(); + + Measuring measuring(mesh); + const auto normals = its_face_normals(mesh); + std::optional first_plane; + bool checked_angle = false; + for (size_t i = 0; i < mesh.indices.size(); ++i) { + const auto &triangle = mesh.indices[i]; + const Vec3d point = (mesh.vertices[triangle[0]].cast() + + mesh.vertices[triangle[1]].cast() + + mesh.vertices[triangle[2]].cast()) / 3.; + const auto feature = measuring.get_feature(i, point, Transform3d::Identity(), true); + REQUIRE(feature.has_value()); + REQUIRE(feature->get_type() == SurfaceFeatureType::Plane); + const Vec3d normal = std::get<1>(feature->get_plane()); + CHECK_THAT(normal.dot(normals[i].cast()), WithinAbs(1., 1e-5)); + if (!first_plane) { + first_plane = feature; + } else if (!checked_angle) { + const Vec3d first_normal = std::get<1>(first_plane->get_plane()); + const double normal_dot = std::abs(first_normal.dot(normal)); + if (normal_dot < 0.999 && normal_dot > 0.001) { + const auto result = get_measurement(*first_plane, *feature); + REQUIRE(result.angle.has_value()); + CHECK_THAT(std::abs(std::cos(result.angle->angle)), WithinAbs(normal_dot, 1e-5)); + checked_angle = true; + } + } + } + CHECK(checked_angle); +} + +TEST_CASE("Mirrored mesh features retain their orientation", "[Measure]") +{ + const auto mirror = [](indexed_triangle_set &mesh) { + for (Vec3f &vertex : mesh.vertices) + vertex.x() = -vertex.x(); + its_flip_triangles(mesh); + }; + + SECTION("circle") { + indexed_triangle_set mesh = its_make_cylinder(10., 20., PI / 90.); + mirror(mesh); + Measuring measuring(mesh); + int circles = 0; + for (int i = 0; i < measuring.get_num_of_planes(); ++i) { + for (const SurfaceFeature &feature : measuring.get_plane_features(i)) { + if (feature.get_type() == SurfaceFeatureType::Circle) { + const auto &[center, radius, normal] = feature.get_circle(); + CHECK_THAT(radius, WithinAbs(10., 0.01)); + CHECK(normal.dot(center - Vec3d(0., 0., 10.)) > 0.); + ++circles; + } + } + } + CHECK(circles == 2); + } + + SECTION("sloped planes") { + indexed_triangle_set mesh = its_make_pyramid(10.f, 10.f); + mirror(mesh); + const auto normals = its_face_normals(mesh); + Measuring measuring(mesh); + for (size_t i = 2; i < mesh.indices.size(); ++i) { + const auto &triangle = mesh.indices[i]; + const Vec3d point = (mesh.vertices[triangle[0]].cast() + + mesh.vertices[triangle[1]].cast() + + mesh.vertices[triangle[2]].cast()) / 3.; + const auto feature = measuring.get_feature(i, point, Transform3d::Identity(), true); + REQUIRE(feature.has_value()); + REQUIRE(feature->get_type() == SurfaceFeatureType::Plane); + CHECK_THAT(std::get<1>(feature->get_plane()).dot(normals[i].cast()), WithinAbs(1., 1e-5)); + } + } +} + From 5841f9652d2fb2ab437797850829c19f3191efaf Mon Sep 17 00:00:00 2001 From: HanifKoh <76276251+HanifKoh@users.noreply.github.com> Date: Tue, 17 Nov 2026 07:44:59 +0800 Subject: [PATCH 19/60] Skip Empty Test Result Publishes and Unrelated Labels in Optional Builds (#17602) --- .github/workflows/build_all.yml | 2 ++ .github/workflows/build_optional.yml | 24 +++++++++++++++++------- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/.github/workflows/build_all.yml b/.github/workflows/build_all.yml index 3fb204ef42..3f6543f88f 100644 --- a/.github/workflows/build_all.yml +++ b/.github/workflows/build_all.yml @@ -291,7 +291,9 @@ jobs: path: test-results # Best-effort: a read-only token (e.g. fork PRs) can't write the check, so # don't let a publish failure fail the run. The test jobs gate correctness. + # Skipped when every build failed: there is nothing to publish. - name: Publish Test Results + if: ${{ hashFiles('test-results/**/*.xml') != '' }} continue-on-error: true uses: EnricoMi/publish-unit-test-result-action@v2 with: diff --git a/.github/workflows/build_optional.yml b/.github/workflows/build_optional.yml index fa2f356999..3e4c1391fc 100644 --- a/.github/workflows/build_optional.yml +++ b/.github/workflows/build_optional.yml @@ -17,12 +17,14 @@ # listed instead. The macOS and the cl.exe builds never start on their own: # what breaks only cl comes from source changes, which no path rule can see. # -# Each label added starts a run of its own, and the pull request's checks show -# the newest run only, so every run builds everything the labels and the -# changed files ask for. Each build keeps its own concurrency group: the newest -# run's build cancels the one an earlier run of the commit started, and a push -# cancels the builds of the commit it replaces. cancel_closed_pr_builds.yml -# joins the groups by name, so update that file with any change here. +# Each build-* or macos-priority label added starts a run of its own, and the +# pull request's checks show the newest run only, so every run builds +# everything the labels and the changed files ask for; any other label builds +# nothing. Each build keeps its own concurrency group: a build entering its +# group cancels the one already in it, so when two runs start together the +# last to enter wins, not necessarily the newest run. A push cancels the +# builds of the commit it replaces. cancel_closed_pr_builds.yml joins the +# groups by name, so update that file with any change here. name: Optional builds on: @@ -60,6 +62,9 @@ on: jobs: select: name: Select builds + # A label that asks for no build must not restart the builds in progress. + # macos-priority restarts them, to move the macOS build to its own line. + if: ${{ github.event.action != 'labeled' || startsWith(github.event.label.name, 'build-') || github.event.label.name == 'macos-priority' }} runs-on: ubuntu-24.04 outputs: flatpak: ${{ steps.select.outputs.flatpak }} @@ -186,7 +191,9 @@ jobs: publish_test_results: name: Publish Test Results needs: [flatpak, unit_tests_windows_arm64] - if: ${{ !cancelled() && (needs.flatpak.result != 'skipped' || needs.unit_tests_windows_arm64.result != 'skipped') }} + # Concurrency cancels the builds of a superseded run, not the run, so + # !cancelled() alone would still publish for it. + if: ${{ !cancelled() && (contains(fromJSON('["success", "failure"]'), needs.flatpak.result) || contains(fromJSON('["success", "failure"]'), needs.unit_tests_windows_arm64.result)) }} runs-on: ubuntu-latest steps: - name: Download Test Results @@ -196,7 +203,10 @@ jobs: path: test-results # Best-effort, as in build_all.yml: a read-only token (e.g. fork PRs) # can't write the check. The test jobs gate correctness. + # A build that failed runs no tests; publishing nothing would post an + # empty result. - name: Publish Test Results + if: ${{ hashFiles('test-results/**/*.xml') != '' }} continue-on-error: true uses: EnricoMi/publish-unit-test-result-action@v2 with: From 32f6db87e828373a83c5ea5c4b2f12f9b0fe50c2 Mon Sep 17 00:00:00 2001 From: Kiss Lorand <50251547+kisslorand@users.noreply.github.com> Date: Tue, 17 Nov 2026 04:20:41 +0200 Subject: [PATCH 20/60] Fix validation of legacy bed exclusion areas (#17618) --- src/libslic3r/PrintConfig.cpp | 16 ++++++++++++---- src/libslic3r/PrintConfig.hpp | 3 ++- tests/libslic3r/test_exclusion_volumes.cpp | 8 +++++++- 3 files changed, 21 insertions(+), 6 deletions(-) diff --git a/src/libslic3r/PrintConfig.cpp b/src/libslic3r/PrintConfig.cpp index 01729fa5ae..61b012b5a7 100644 --- a/src/libslic3r/PrintConfig.cpp +++ b/src/libslic3r/PrintConfig.cpp @@ -14061,18 +14061,26 @@ bool is_valid_bed_exclude_area(const Pointfs &points) } const Polygon polygon = Polygon::new_scale(points); - if (has_duplicate_points(polygon)) - return false; - const Points &vertices = polygon.points; if (polygon.area() == 0.0) return false; + const auto edges_cross = [](const Point &first_start, const Point &first_end, + const Point &second_start, const Point &second_end) { + const int first_start_side = int128::orient(first_start, first_end, second_start); + const int first_end_side = int128::orient(first_start, first_end, second_end); + const int second_start_side = int128::orient(second_start, second_end, first_start); + const int second_end_side = int128::orient(second_start, second_end, first_end); + return first_start_side != 0 && first_end_side != 0 && + second_start_side != 0 && second_end_side != 0 && + first_start_side != first_end_side && second_start_side != second_end_side; + }; + const size_t count = vertices.size(); for (size_t idx = 0; idx + 2 < count; ++idx) { const size_t end = idx == 0 ? count - 1 : count; for (size_t other = idx + 2; other < end; ++other) { - if (Geometry::segments_intersect( + if (edges_cross( vertices[idx], vertices[idx + 1], vertices[other], vertices[(other + 1) % count])) return false; } diff --git a/src/libslic3r/PrintConfig.hpp b/src/libslic3r/PrintConfig.hpp index f98b7df2cc..a170065227 100644 --- a/src/libslic3r/PrintConfig.hpp +++ b/src/libslic3r/PrintConfig.hpp @@ -2595,7 +2595,8 @@ int bed_exclusion_extruder_for_filament(size_t filament_id, const std::vector Date: Tue, 17 Nov 2026 14:28:08 +0800 Subject: [PATCH 21/60] fix: nozzle sync table flash and white box (#17607) * fix: nozzle table height measurement before dialog layout * fix: white flash when nozzle list table loads --- resources/web/flush/NozzleListTable.html | 61 ++++++---- src/slic3r/GUI/Widgets/MultiNozzleSync.cpp | 135 +++++++++++++++------ src/slic3r/GUI/Widgets/MultiNozzleSync.hpp | 8 +- 3 files changed, 147 insertions(+), 57 deletions(-) diff --git a/resources/web/flush/NozzleListTable.html b/resources/web/flush/NozzleListTable.html index 51da2cbd52..7c660e856b 100644 --- a/resources/web/flush/NozzleListTable.html +++ b/resources/web/flush/NozzleListTable.html @@ -4,13 +4,17 @@ 喷嘴选择表格 +