From 32dbacb4231c772af9837ff08e2945625067f1ba Mon Sep 17 00:00:00 2001 From: Arthur Porto <227830219+Art-Porto@users.noreply.github.com> Date: Wed, 11 Nov 2026 15:34:10 -0300 Subject: [PATCH] Variable layer height on several objects, and with the prime tower on objects of different heights (#16462) * Variable layer height on several objects, and with the prime tower on objects of different heights The variable layer height tool now opens with several objects selected. Adaptive, Smooth, Reset and manual edits apply to all of them: they share one profile, the finest layer height any of them asks for at each Z, unless "Each object separately" is ticked. Every selected object is painted with its layer heights. With a profile each, up to three objects get a bar of their own, drawn to one scale, and the bar under the mouse is the one edited. The prime tower check compares the layers objects are sliced at over the height they share, rather than the raw profiles, which never matched once the profile of a lower object ended at its own top. Precise Z height, which fits the last layers of each object to its own height, is left out of such a print, with a warning. * Check the prime tower layers on the sliced objects, and note the new strings for translators * Include what the new tests use * Compare the layers as sliced, before the prime tower is generated from them * Check that precise Z height stays on without a prime tower * Keep each object's layer height texture on the GPU, and mark only lower tops The variable layer height tool sent a 1024x1024 texture to the GPU for every selected object on every frame, and set_config(), run after every edit, dropped the other objects' textures so that each was generated again. Each other object now has a texture of its own on the GPU. It is generated and sent only when its profile, its height or the slicing parameters it shows change, which set_config() now only asks to check. The object shown sends its texture only when it is generated, and while the objects share one profile, those on its layers are drawn with its texture and need none of their own. The textures of objects no longer selected are freed. The bars and the layer height curves are built again only when what they show changes, and each bar is scaled with its own object's layer heights. A lower object's top is marked only when it is lower than the object shown, objects ending at the same height share one label, and a label stays on the canvas and below the one above it. The comment on precise_z_height_overridden() now says what the override trades: the tower can join the off-grid layers to the tower layer below, but a joined layer holds two purges, which makes the tower deeper. * Fix the precise Z warning, shared profiles across first layers and the bar clicked - The precise Z override, and its warning, now need an object with precise Z height on. Every plate with a prime tower and variable layer height on objects of different heights warned about a setting that is off by default. - The objects the override slices again get their slicing parameters back at once, since validate() reads them before slicing. - When the objects share one profile, an object that starts its layers elsewhere than the object shown, with a raft of its own say, keeps its own. The shared profile starts with the first layer of the object shown, and PrintObject::update_layer_height_profile() dropped it on such an object, which then printed at the preset layer height. - Clicking a bar edits its object, even when no frame was drawn since the mouse got there. - Select all is ignored while a profile is painted, and select all plates while the tool is open. - The bars' models are made again, not copied, when their number changes: a copy shares the GPU buffers that the original deletes. - Objects with no height above the bed are left out of the tool, and a profile fitted within EPSILON above one of its entries no longer runs past it. * Keep the object top labels below the toolbar row When the toolbar row ends next to the bar, the label of an object that ends near the top of the tallest one covered the toolbar's last buttons. Such a label now starts below the row, with its arrow pointing up to the line on the bar. * Fill the layer height texture up to the top of the object The last layer can end under the top of the object, by up to half a layer, and no layer wrote the cells there. The top face is drawn with them, so it showed what the buffer held before: black on the texture of an object made for the first time, or the colours of another object. The last layer now fills them, with the shade of its top. * Draw horizontal faces without the layer stripes A horizontal face lies at one height, so the stripes cannot show on it, only the shade they have there. That shade changed whenever a layer under it moved, and the tops flickered at every stroke. Such a face now gets the plain colour of its layer height, from the 2nd level of the texture. That level is now read at its own level of detail instead of with a bias. On a horizontal face the texture coordinates do not change, so the GPU picks the 1st level however large the bias, and read it at the coordinates of the 2nd: the tops showed black, or the colour of another height. The 110 shader does so where GL_ARB_shader_texture_lod is available, and keeps the stripes elsewhere. * Include ObjectID.hpp where ObjectWithTimestamp is used clang-tidy (misc-include-cleaner) asks for the header to be included directly. * Find the horizontal faces with the inverse transpose of the world matrix The variable layer height shader took the normals to world space with the world matrix itself, which is only right under a uniform scale. With a non-uniform scale it drew sloped faces as flat, and once the object was also rotated it missed real flat ones. The normals now go through the inverse transpose of the world matrix, which render_object_volumes() already built for the view normal matrix. * Note why the precise Z override keys on has_wipe_tower() Since #16999 the tower is printed only when slicing finds it is needed, so the override also applies on plates where no tower is printed in the end. --- .../shaders/110/variable_layer_height.fs | 24 +- .../shaders/110/variable_layer_height.vs | 7 + .../shaders/140/variable_layer_height.fs | 10 +- .../shaders/140/variable_layer_height.vs | 7 + src/libslic3r/Print.cpp | 28 +- src/libslic3r/Print.hpp | 15 + src/libslic3r/PrintApply.cpp | 22 + src/libslic3r/PrintObject.cpp | 5 + src/libslic3r/PrintObjectSlice.cpp | 2 +- src/libslic3r/Slicing.cpp | 101 ++- src/libslic3r/Slicing.hpp | 14 + src/slic3r/GUI/GLCanvas3D.cpp | 761 +++++++++++++++--- src/slic3r/GUI/GLCanvas3D.hpp | 109 ++- src/slic3r/GUI/Plater.cpp | 4 +- tests/fff_print/test_wipe_tower.cpp | 222 +++++ tests/libslic3r/CMakeLists.txt | 1 + tests/libslic3r/test_slicing.cpp | 129 +++ 17 files changed, 1312 insertions(+), 149 deletions(-) create mode 100644 tests/libslic3r/test_slicing.cpp diff --git a/resources/shaders/110/variable_layer_height.fs b/resources/shaders/110/variable_layer_height.fs index 693c1c6a0b..7269751050 100644 --- a/resources/shaders/110/variable_layer_height.fs +++ b/resources/shaders/110/variable_layer_height.fs @@ -1,4 +1,6 @@ #version 110 +// Orca: texture2DLod() in a fragment shader. +#extension GL_ARB_shader_texture_lod : enable #define M_PI 3.1415926535897932384626433832795 @@ -9,11 +11,14 @@ uniform float z_to_texture_row; uniform float z_texture_row_to_normalized; uniform float z_cursor; uniform float z_cursor_band_width; +// Orca: 0 leaves the colour as it is, 1 turns it into a flat grey. +uniform float dimming; // x = tainted, y = specular; varying vec2 intensity; varying float object_z; +varying float horizontal; void main() { @@ -31,11 +36,24 @@ void main() float dx_vtc = dFdx(z_in_cells); float dy_vtc = dFdy(z_in_cells); float lod = clamp(0.5 * log2(max(dx_vtc * dx_vtc, dy_vtc * dy_vtc)), 0., 1.); +#ifdef GL_ARB_shader_texture_lod + // Orca: a horizontal face gets the colour of the layer height alone, without the stripes. + lod = max(lod, horizontal); +#endif // Sample the Z texture. Texture coordinates are normalized to <0, 1>. vec4 color = vec4(0.25, 0.25, 0.25, 1.0); - if (z_texture_row >= 0.0) - color = mix(texture2D(z_texture, vec2(z_texture_col, z_texture_row_to_normalized * (z_texture_row + 0.5 )), -10000.), - texture2D(z_texture, vec2(z_texture_col, z_texture_row_to_normalized * (z_texture_row * 2. + 1.)), 10000.), lod); + if (z_texture_row >= 0.0) { + vec2 level1 = vec2(z_texture_col, z_texture_row_to_normalized * (z_texture_row * 2. + 1.)); +#ifdef GL_ARB_shader_texture_lod + // Orca: the 2nd level is read at its own level of detail, not with a bias. On a horizontal face the texture + // coordinates do not change, so the GPU picks the 1st level however large the bias, read at the coordinates of the 2nd. + vec4 color1 = texture2DLod(z_texture, level1, 1.); +#else + vec4 color1 = texture2D(z_texture, level1, 10000.); +#endif + color = mix(texture2D(z_texture, vec2(z_texture_col, z_texture_row_to_normalized * (z_texture_row + 0.5 )), -10000.), color1, lod); + } // Mix the final color. gl_FragColor = vec4(vec3(intensity.y), 1.0) + intensity.x * mix(color, vec4(1.0, 1.0, 0.0, 1.0), z_blend); + gl_FragColor.rgb = mix(gl_FragColor.rgb, vec3(0.3), dimming); } diff --git a/resources/shaders/110/variable_layer_height.vs b/resources/shaders/110/variable_layer_height.vs index 2d6334f44e..539ea8cd71 100644 --- a/resources/shaders/110/variable_layer_height.vs +++ b/resources/shaders/110/variable_layer_height.vs @@ -18,6 +18,8 @@ uniform mat4 view_model_matrix; uniform mat4 projection_matrix; uniform mat3 view_normal_matrix; uniform mat4 volume_world_matrix; +// Orca: the inverse transpose of volume_world_matrix, which takes the normals to world space under any scale or rotation. +uniform mat3 volume_world_normal_matrix; uniform float object_max_z; attribute vec3 v_position; @@ -29,6 +31,10 @@ varying vec2 intensity; varying float object_z; +// Orca: 1 on a horizontal face, which lies at one height: the stripes of the layers cannot show on it, +// only the shade they have there, which changes whenever a layer under it moves. +varying float horizontal; + void main() { // ===================================================== @@ -55,6 +61,7 @@ void main() // Scaled to widths of the Z texture. object_z = (object_max_z > 0.0) ? object_max_z * v_tex_coord.y : (volume_world_matrix * vec4(v_position, 1.0)).z; + horizontal = (object_max_z > 0.0) ? 0.0 : step(0.999, abs(normalize(volume_world_normal_matrix * v_normal).z)); gl_Position = projection_matrix * position; } diff --git a/resources/shaders/140/variable_layer_height.fs b/resources/shaders/140/variable_layer_height.fs index 658f812286..acb508c274 100644 --- a/resources/shaders/140/variable_layer_height.fs +++ b/resources/shaders/140/variable_layer_height.fs @@ -9,11 +9,14 @@ uniform float z_to_texture_row; uniform float z_texture_row_to_normalized; uniform float z_cursor; uniform float z_cursor_band_width; +// Orca: 0 leaves the colour as it is, 1 turns it into a flat grey. +uniform float dimming; // x = tainted, y = specular; in vec2 intensity; in float object_z; +in float horizontal; out vec4 out_color; @@ -33,11 +36,16 @@ void main() float dx_vtc = dFdx(z_in_cells); float dy_vtc = dFdy(z_in_cells); float lod = clamp(0.5 * log2(max(dx_vtc * dx_vtc, dy_vtc * dy_vtc)), 0., 1.); + // Orca: a horizontal face gets the colour of the layer height alone, without the stripes. + lod = max(lod, horizontal); // Sample the Z texture. Texture coordinates are normalized to <0, 1>. + // Orca: the 2nd level is read at its own level of detail, not with a bias. On a horizontal face the texture + // coordinates do not change, so the GPU picks the 1st level however large the bias, read at the coordinates of the 2nd. vec4 color = vec4(0.25, 0.25, 0.25, 1.0); if (z_texture_row >= 0.0) color = mix(texture(z_texture, vec2(z_texture_col, z_texture_row_to_normalized * (z_texture_row + 0.5 )), -10000.), - texture(z_texture, vec2(z_texture_col, z_texture_row_to_normalized * (z_texture_row * 2. + 1.)), 10000.), lod); + textureLod(z_texture, vec2(z_texture_col, z_texture_row_to_normalized * (z_texture_row * 2. + 1.)), 1.), lod); // Mix the final color. out_color = vec4(vec3(intensity.y), 1.0) + intensity.x * mix(color, vec4(1.0, 1.0, 0.0, 1.0), z_blend); + out_color.rgb = mix(out_color.rgb, vec3(0.3), dimming); } diff --git a/resources/shaders/140/variable_layer_height.vs b/resources/shaders/140/variable_layer_height.vs index d8deb2f9ee..d6904bcc1b 100644 --- a/resources/shaders/140/variable_layer_height.vs +++ b/resources/shaders/140/variable_layer_height.vs @@ -18,6 +18,8 @@ uniform mat4 view_model_matrix; uniform mat4 projection_matrix; uniform mat3 view_normal_matrix; uniform mat4 volume_world_matrix; +// Orca: the inverse transpose of volume_world_matrix, which takes the normals to world space under any scale or rotation. +uniform mat3 volume_world_normal_matrix; uniform float object_max_z; in vec3 v_position; @@ -29,6 +31,10 @@ out vec2 intensity; out float object_z; +// Orca: 1 on a horizontal face, which lies at one height: the stripes of the layers cannot show on it, +// only the shade they have there, which changes whenever a layer under it moves. +out float horizontal; + void main() { // ===================================================== @@ -55,6 +61,7 @@ void main() // Scaled to widths of the Z texture. object_z = (object_max_z > 0.0) ? object_max_z * v_tex_coord.y : (volume_world_matrix * vec4(v_position, 1.0)).z; + horizontal = (object_max_z > 0.0) ? 0.0 : step(0.999, abs(normalize(volume_world_normal_matrix * v_normal).z)); gl_Position = projection_matrix * position; } diff --git a/src/libslic3r/Print.cpp b/src/libslic3r/Print.cpp index a2400c4905..129f67c39c 100644 --- a/src/libslic3r/Print.cpp +++ b/src/libslic3r/Print.cpp @@ -2106,26 +2106,21 @@ StringObjectException Print::validate_wipe_tower_layering() const layer_z_series.assign(m_objects.size(), std::vector()); for (size_t idx_object = 0; idx_object < m_objects.size(); ++idx_object) { - layer_z_series[idx_object] = generate_object_layers(m_objects[idx_object]->slicing_parameters(), layer_height_profile(idx_object), m_objects[idx_object]->config().precise_z_height.value); + layer_z_series[idx_object] = generate_object_layers(m_objects[idx_object]->slicing_parameters(), layer_height_profile(idx_object), m_objects[idx_object]->precise_z_height()); } for (size_t idx_object = 0; idx_object < m_objects.size(); ++idx_object) { if (idx_object == tallest_object_idx) continue; - // Check that the layer height profiles are equal. This will happen when one object is - // a copy of another, or when a layer height modifier is used the same way on both objects. - // The latter case might create a floating point inaccuracy mismatch, so compare - // element-wise using an epsilon check. - size_t i = 0; + // Orca: check that the objects are sliced at the same Z over the height they share. The + // profiles themselves cannot be compared: one that ends at a lower object's top has an + // entry there that the tallest object's profile lacks, though both give the same layers. + const std::vector &layers = layer_z_series[idx_object]; + const std::vector &layers_tallest = layer_z_series[tallest_object_idx]; const coordf_t eps = 0.5 * EPSILON; // layers closer than EPSILON will be merged later. Let's make // this check a bit more sensitive to make sure we never consider two different layers as one. - while (i < layer_height_profiles[idx_object].size() && i < layer_height_profiles[tallest_object_idx].size()) { - // BBS: remove the break condition, because a variable layer height object and a new object will not be checked when slicing - //if (i % 2 == 0 && layer_height_profiles[tallest_object_idx][i] > layer_height_profiles[idx_object][layer_height_profiles[idx_object].size() - 2]) - // break; - if (std::abs(layer_height_profiles[idx_object][i] - layer_height_profiles[tallest_object_idx][i]) > eps) + for (size_t i = 0; i < layers.size() && i < layers_tallest.size(); ++i) + if (std::abs(layers[i] - layers_tallest[i]) > eps) return {L("The prime tower is only supported if all objects have the same variable layer height.")}; - ++i; - } } } return {}; @@ -2489,7 +2484,10 @@ StringObjectException Print::validate(std::vector *warnin return {L("The project contains multiple managed belt purge towers. Reload the plate or toggle the belt purge tower off and on to regenerate it.")}; } - if (m_config.enable_prime_tower) { + if (m_precise_z_height_overridden) + // TRN "Precise Z height" is a print setting, "prime tower" the tower that purges the nozzle between filaments. + warn(L("Precise Z height is not applied: with the prime tower, objects of different heights that use variable layer height have to share their layers."), "precise_z_height"); + else if (m_config.enable_prime_tower) { for (const PrintObject* object : m_objects) { if (object->config().precise_z_height.value) { warn(L("Enabling both precise Z height and the prime tower may cause slicing errors."), "precise_z_height"); @@ -2575,7 +2573,7 @@ StringObjectException Print::validate(std::vector *warnin have_height = raw_z > 0; } else { //FIXME It is quite expensive to generate object layers just to get the print height! - auto layers = generate_object_layers(print_object.slicing_parameters(), layer_height_profile(print_object_idx), print_object.config().precise_z_height.value); + auto layers = generate_object_layers(print_object.slicing_parameters(), layer_height_profile(print_object_idx), print_object.precise_z_height()); if (!layers.empty()) { // The object layers start above the raft. const double raft_z = print_object.slicing_parameters().object_print_z_min; diff --git a/src/libslic3r/Print.hpp b/src/libslic3r/Print.hpp index be4fe4df33..e7545739d9 100644 --- a/src/libslic3r/Print.hpp +++ b/src/libslic3r/Print.hpp @@ -498,6 +498,8 @@ public: // The slicing parameters are dependent on various configuration values // (layer height, first layer height, raft settings, print nozzle diameter etc). const SlicingParameters& slicing_parameters() const { return m_slicing_params; } + // Orca: whether precise Z height shapes the layers of this object; see Print::precise_z_height_overridden(). + bool precise_z_height() const; // Orca: XYZ shrinkage compensation has introduced the const Vec3d &object_shrinkage_compensation parameter to the function below static SlicingParameters slicing_parameters(const DynamicPrintConfig &full_config, const ModelObject &model_object, float object_max_z, const Vec3d &object_shrinkage_compensation, std::vector variant_index = std::vector()); @@ -1200,6 +1202,18 @@ public: StringObjectException validate_wipe_tower_layering() const; // Belt purge prism (belt-mode replacement for the wipe tower). bool has_belt_purge_tower() const; + // Orca: precise Z height fits the last layers of each object to its own height. With a prime tower + // and variable layer height on objects of different heights, that puts the last layers of a lower + // object between the layers of the others. The tower can still print them, each joined to the tower + // layer below (ToolOrdering::fill_wipe_tower_partitions()), but a joined layer holds the purges of + // both, which makes the tower deeper. So precise Z height is left out of the whole print instead: + // the objects stay on the same layers, and the last layer of a lower object ends where the shared + // layers do, a fraction of a layer off its own top. + // It keys on has_wipe_tower(), which reads the config, so it also applies when the tower turns out + // not to be needed after slicing, such as support in another filament that no object needs. Keying + // it on wipe_tower_certain_before_slicing() would keep precise Z there, but a plate whose support + // does need the tower would then be refused after slicing. + bool precise_z_height_overridden() const { return m_precise_z_height_overridden; } const WipeTowerData& wipe_tower_data(size_t filaments_cnt = 0) const; const ToolOrdering& tool_ordering() const { return m_tool_ordering; } @@ -1587,6 +1601,7 @@ private: // Estimated print time, filament consumed. PrintStatistics m_print_statistics; bool m_support_used {false}; + bool m_precise_z_height_overridden {false}; StatisticsByExtruderCount m_statistics_by_extruder_count; std::vector m_slice_used_filaments; diff --git a/src/libslic3r/PrintApply.cpp b/src/libslic3r/PrintApply.cpp index a19f23c60c..551645054e 100644 --- a/src/libslic3r/PrintApply.cpp +++ b/src/libslic3r/PrintApply.cpp @@ -2304,6 +2304,28 @@ Print::ApplyStatus Print::apply(const Model &model, DynamicPrintConfig new_full_ m_support_used |= object->config().enable_support; } + // Orca: see precise_z_height_overridden(). The objects it applies to are sliced again when it flips. + { + const auto precise_z_height = [](const PrintObject *object) { return object->config().precise_z_height.value; }; + const auto custom_layering = [](const PrintObject *object) { return object->model_object()->has_custom_layering(); }; + const auto other_height = [this](const PrintObject *object) { + return std::abs(object->slicing_parameters().object_print_z_height() - m_objects.front()->slicing_parameters().object_print_z_height()) > EPSILON; + }; + const bool overridden = this->has_wipe_tower() && + std::any_of(m_objects.begin(), m_objects.end(), precise_z_height) && + std::any_of(m_objects.begin(), m_objects.end(), custom_layering) && + std::any_of(m_objects.begin(), m_objects.end(), other_height); + if (overridden != m_precise_z_height_overridden) { + m_precise_z_height_overridden = overridden; + for (PrintObject *object : m_objects) + if (precise_z_height(object)) { + update_apply_status(object->invalidate_step(posSlice)); + // invalidate_step() drops the slicing parameters, and validate() reads them before slicing. + object->update_slicing_parameters(); + } + } + } + #ifdef _DEBUG check_model_ids_equal(m_model, model); #endif /* _DEBUG */ diff --git a/src/libslic3r/PrintObject.cpp b/src/libslic3r/PrintObject.cpp index 1265b0856b..4ae026a0ca 100644 --- a/src/libslic3r/PrintObject.cpp +++ b/src/libslic3r/PrintObject.cpp @@ -874,6 +874,11 @@ void PrintObject::ironing() } } +bool PrintObject::precise_z_height() const +{ + return m_config.precise_z_height.value && !m_print->precise_z_height_overridden(); +} + bool PrintObject::need_z_contouring() const { size_t num_regions = this->num_printing_regions(); diff --git a/src/libslic3r/PrintObjectSlice.cpp b/src/libslic3r/PrintObjectSlice.cpp index 701231a7e0..c5e99348af 100644 --- a/src/libslic3r/PrintObjectSlice.cpp +++ b/src/libslic3r/PrintObjectSlice.cpp @@ -908,7 +908,7 @@ void PrintObject::slice() m_belt_min_z = 0.; m_belt_global_z_offset = 0.; this->clear_layers(); - m_layers = new_layers(this, generate_object_layers(m_slicing_params, layer_height_profile, m_config.precise_z_height.value)); + m_layers = new_layers(this, generate_object_layers(m_slicing_params, layer_height_profile, this->precise_z_height())); this->slice_volumes(); m_print->throw_if_canceled(); diff --git a/src/libslic3r/Slicing.cpp b/src/libslic3r/Slicing.cpp index 209050e4ed..476b096863 100644 --- a/src/libslic3r/Slicing.cpp +++ b/src/libslic3r/Slicing.cpp @@ -816,6 +816,96 @@ bool adjust_layer_series_to_align_object_height(const SlicingParameters &slicing return true; } +std::vector layer_height_profile_fit_to_height( + const std::vector &layer_height_profile, + coordf_t object_height) +{ + assert(layer_height_profile.size() >= 2); + assert(layer_height_profile.size() % 2 == 0); + assert(layer_height_profile[0] == 0); + assert(object_height > EPSILON); + + std::vector out; + out.reserve(layer_height_profile.size() + 2); + size_t i = 0; + for (; i < layer_height_profile.size() && layer_height_profile[i] < object_height - EPSILON; i += 2) { + out.push_back(layer_height_profile[i]); + out.push_back(layer_height_profile[i + 1]); + } + + // The last entry has to sit exactly at the top of the object, see PrintObject::update_layer_height_profile(). + coordf_t height = layer_height_profile.back(); + if (i < layer_height_profile.size() && i >= 2) { + const coordf_t z1 = layer_height_profile[i - 2]; + const coordf_t z2 = layer_height_profile[i]; + // The next entry can lie a hair under the top, within the EPSILON the loop above allows. + height = lerp(layer_height_profile[i - 1], layer_height_profile[i + 1], std::clamp((object_height - z1) / (z2 - z1), 0., 1.)); + } + out.push_back(object_height); + out.push_back(height); + return out; +} + +std::vector layer_height_profile_merge_finest( + const std::vector> &layer_height_profiles) +{ + assert(! layer_height_profiles.empty()); + const std::vector *tallest = &layer_height_profiles.front(); + for (const std::vector &profile : layer_height_profiles) { + assert(profile.size() >= 4); + assert(profile.size() % 2 == 0); + if (profile[profile.size() - 2] > (*tallest)[tallest->size() - 2]) + tallest = &profile; + } + const coordf_t top = (*tallest)[tallest->size() - 2]; + + // Index of the entry each profile was last read at. The Zs only grow, so it never moves back. + std::vector cursors(layer_height_profiles.size(), 0); + // The finest layer height asked for at z. Above its own top an object asks for nothing, but its + // last layer height is eased back up at the rate the adaptive profile allows from one layer to + // the next, rather than released at once: a jump there is a seam on the taller objects. + const auto finest_at = [&layer_height_profiles, &cursors](coordf_t z) { + coordf_t height = std::numeric_limits::max(); + for (size_t idx_profile = 0; idx_profile < layer_height_profiles.size(); ++idx_profile) { + const std::vector &profile = layer_height_profiles[idx_profile]; + const size_t end = profile.size() - 2; + const coordf_t profile_top = profile[end]; + if (z > profile_top + EPSILON) { + const coordf_t last = profile[end - 1]; + height = std::min(height, std::sqrt(last * last + 2. * LAYER_HEIGHT_CHANGE_STEP * (z - profile_top))); + continue; + } + size_t &i = cursors[idx_profile]; + while (i + 2 < end && profile[i + 2] <= z) + i += 2; + height = std::min(height, i + 2 < end ? + lerp(profile[i + 1], profile[i + 3], (z - profile[i]) / (profile[i + 2] - profile[i])) : + profile[i + 1]); + } + return height; + }; + + // One entry per layer, as layer_height_profile_adaptive() lays its profile out, which is the + // spacing smooth_height_profile() counts on. A fixed first layer keeps its own two entries. + std::vector out{ 0., (*tallest)[1] }; + coordf_t print_z = (*tallest)[1]; + if (std::abs((*tallest)[2] - print_z) < EPSILON && std::abs((*tallest)[3] - print_z) < EPSILON) { + out.push_back(print_z); + out.push_back(print_z); + } + while (print_z + EPSILON < top) { + const coordf_t height = finest_at(print_z); + if (height < EPSILON) + break; + out.push_back(print_z); + out.push_back(height); + print_z += height; + } + out.push_back(top); + out.push_back(out[out.size() - 2]); + return out; +} + // Produce object layers as pairs of low / high layer boundaries, stored into a linear vector. std::vector generate_object_layers( const SlicingParameters &slicing_params, @@ -951,8 +1041,12 @@ int generate_layer_height_texture( assert(mid <= slicing_params.object_print_z_height()); coordf_t h = hi - lo; hi = std::min(hi, slicing_params.object_print_z_height()); + // Orca: the last layer can end under the top of the object, by up to half a layer, and the top face is + // drawn with the cells there. The last layer fills them, which no layer did: they kept what the buffer + // held before, black or the colours of another object. + const bool last_layer = idx_layer + 2 >= layers.size(); int cell_first = std::clamp(int(ceil(lo * z_to_cell)), 0, ncells-1); - int cell_last = std::clamp(int(floor(hi * z_to_cell)), 0, ncells-1); + int cell_last = last_layer ? ncells - 1 : std::clamp(int(floor(hi * z_to_cell)), 0, ncells-1); for (int cell = cell_first; cell <= cell_last; ++ cell) { coordf_t idxf = (0.5 * hscale + (h - slicing_params.layer_height)) * coordf_t(palette_raw.size()-1) / hscale; int idx1 = std::clamp(int(floor(idxf)), 0, int(palette_raw.size() - 1)); @@ -960,7 +1054,8 @@ int generate_layer_height_texture( coordf_t t = idxf - coordf_t(idx1); const Vec3crd &color1 = palette_raw[idx1]; const Vec3crd &color2 = palette_raw[idx2]; - coordf_t z = cell_to_z * coordf_t(cell); + // Above the last layer, the shade of its top. + coordf_t z = std::min(cell_to_z * coordf_t(cell), hi); assert(lo - EPSILON <= z && z <= hi + EPSILON); // Intensity profile to visualize the layers. coordf_t intensity = cos(M_PI * 0.7 * (mid - z) / h); @@ -988,7 +1083,7 @@ int generate_layer_height_texture( } if (level_of_detail_2nd_level) { cell_first = std::clamp(int(ceil(lo * z_to_cell1)), 0, ncells1-1); - cell_last = std::clamp(int(floor(hi * z_to_cell1)), 0, ncells1-1); + cell_last = last_layer ? ncells1 - 1 : std::clamp(int(floor(hi * z_to_cell1)), 0, ncells1-1); for (int cell = cell_first; cell <= cell_last; ++ cell) { coordf_t idxf = (0.5 * hscale + (h - slicing_params.layer_height)) * coordf_t(palette_raw.size()-1) / hscale; int idx1 = std::clamp(int(floor(idxf)), 0, int(palette_raw.size() - 1)); diff --git a/src/libslic3r/Slicing.hpp b/src/libslic3r/Slicing.hpp index 344dfafb99..79bd4a6b76 100644 --- a/src/libslic3r/Slicing.hpp +++ b/src/libslic3r/Slicing.hpp @@ -162,6 +162,20 @@ std::vector layer_height_profile_from_ranges( const SlicingParameters &slicing_params, const t_layer_config_ranges &layer_config_ranges); +// Orca: fit a layer height profile onto an object of another height, so that both objects are sliced +// at the same Z over the height they share. The profile is cut at object_height, or its last +// layer height is carried up to it. +std::vector layer_height_profile_fit_to_height( + const std::vector &layer_height_profile, + coordf_t object_height); + +// Orca: one profile for several objects, taking the finest of their layer heights at every Z, up to +// the top of the tallest one, with one entry per layer. The entry at the top of a profile only +// closes it, so each profile counts with its last layer height before it, and above that top the +// layer height is eased back up rather than released at once. +std::vector layer_height_profile_merge_finest( + const std::vector> &layer_height_profiles); + std::vector layer_height_profile_adaptive( const SlicingParameters& slicing_params, const ModelObject& object, float quality_factor); diff --git a/src/slic3r/GUI/GLCanvas3D.cpp b/src/slic3r/GUI/GLCanvas3D.cpp index 8ca886ee50..ff37a9b81f 100644 --- a/src/slic3r/GUI/GLCanvas3D.cpp +++ b/src/slic3r/GUI/GLCanvas3D.cpp @@ -24,6 +24,7 @@ #include "slic3r/GUI/IMSlider.hpp" #include "libslic3r/Preset.hpp" #include "libslic3r/Model.hpp" +#include "libslic3r/ObjectID.hpp" #include #include "slic3r/GUI/SceneRaycaster.hpp" #include "slic3r/GUI/Camera.hpp" @@ -308,6 +309,8 @@ GLCanvas3D::LayersEditing::~LayersEditing() glsafe(::glDeleteTextures(1, &m_z_texture_id)); m_z_texture_id = 0; } + for (auto &[object_id, object] : m_other_textures) + this->release_object_texture(object); delete m_slicing_parameters; } @@ -315,8 +318,14 @@ const float GLCanvas3D::LayersEditing::THICKNESS_BAR_WIDTH = 70.0f; void GLCanvas3D::LayersEditing::init() { - glsafe(::glGenTextures(1, (GLuint*)&m_z_texture_id)); - glsafe(::glBindTexture(GL_TEXTURE_2D, m_z_texture_id)); + m_z_texture_id = create_texture(); +} + +unsigned int GLCanvas3D::LayersEditing::create_texture() +{ + GLuint texture_id = 0; + glsafe(::glGenTextures(1, &texture_id)); + glsafe(::glBindTexture(GL_TEXTURE_2D, texture_id)); if (!OpenGLManager::get_gl_info().is_core_profile() || !OpenGLManager::get_gl_info().is_mesa()) { glsafe(::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)); glsafe(::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)); @@ -325,6 +334,7 @@ void GLCanvas3D::LayersEditing::init() glsafe(::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST)); glsafe(::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 1)); glsafe(::glBindTexture(GL_TEXTURE_2D, 0)); + return texture_id; } void GLCanvas3D::LayersEditing::set_config(const DynamicPrintConfig* config) @@ -334,6 +344,9 @@ void GLCanvas3D::LayersEditing::set_config(const DynamicPrintConfig* config) m_slicing_parameters = nullptr; m_layers_texture.valid = false; m_layer_height_profile.clear(); + // The other objects read their slicing parameters and profiles again the next time they are drawn. + // Their textures stay: they are regenerated only if what they show has changed. + ++m_config_version; } void GLCanvas3D::LayersEditing::select_object(const Model& model, int object_id) @@ -354,6 +367,7 @@ void GLCanvas3D::LayersEditing::select_object(const Model& model, int object_id) m_model_object = model_object_new; m_object_max_z = new_max_z; } + m_model = &model; } bool GLCanvas3D::LayersEditing::is_allowed() const @@ -363,6 +377,59 @@ bool GLCanvas3D::LayersEditing::is_allowed() const float GLCanvas3D::LayersEditing::s_overlay_window_width; +// Orca: on a bar shared by several objects, the height at which lower ones end: a line across the +// bar, and an arrow pointing at it from the names of the objects. The label is kept on the canvas, +// below min_label_top, the bottom of the label above it, and below the toolbar row when it would reach +// into that row: toolbar_end is the bottom right corner of the row. Returns the bottom of this label. +static float render_object_top_mark(const std::string& label, float bar_left, float bar_right, float y, float min_label_top, float canvas_height, + const ImVec2& toolbar_end) +{ + ImDrawList* draw_list = ImGui::GetBackgroundDrawList(); + const ImU32 color = ImGui::GetColorU32(ImGuiWrapper::COL_ORCA); + const float arrow = 0.6f * ImGui::GetFontSize(); + const float tip = bar_left - 2.0f; + draw_list->AddLine({ bar_left, y }, { bar_right, y }, color, 2.0f); + + const ImVec2 text_size = ImGui::CalcTextSize(label.c_str()); + const ImVec2 padding = { 0.4f * ImGui::GetFontSize(), 0.2f * ImGui::GetFontSize() }; + const float half_box = 0.5f * text_size.y + padding.y; + const float text_x = tip - arrow - 2.0f * padding.x - text_size.x; + const float min_top = text_x - padding.x < toolbar_end.x ? std::max(min_label_top, toolbar_end.y) : min_label_top; + const float label_y = std::min(std::max(y, std::max(min_top, 0.0f) + half_box), canvas_height - half_box); + draw_list->AddTriangleFilled({ tip, y }, { tip - arrow, label_y - 0.6f * arrow }, { tip - arrow, label_y + 0.6f * arrow }, color); + + const ImVec2 text_pos = { text_x, label_y - 0.5f * text_size.y }; + draw_list->AddRectFilled({ text_pos.x - padding.x, text_pos.y - padding.y }, { text_pos.x + text_size.x + padding.x, text_pos.y + text_size.y + padding.y }, + color, padding.y); + draw_list->AddText(text_pos, IM_COL32_WHITE, label.c_str()); + return label_y + half_box; +} + +// Orca: the names of the objects that end at one height, such as "Cube x3, Cone" with a multiplication +// sign: the first three names, then how many objects are left. +static std::string object_top_mark_label(const std::vector>& names) +{ + static constexpr size_t max_names = 3; + std::string label; + size_t listed = 0; + size_t total = 0; + for (size_t i = 0; i < names.size(); ++i) { + total += names[i].second; + if (i >= max_names) + continue; + if (i > 0) + label += ", "; + label += names[i].first; + if (names[i].second > 1) + // U+00D7 MULTIPLICATION SIGN, in the default ImGui glyph range. + label += " \xC3\x97" + std::to_string(names[i].second); + listed += names[i].second; + } + if (listed < total) + label += " +" + std::to_string(total - listed); + return label; +} + void GLCanvas3D::LayersEditing::render_variable_layer_height_dialog(GLCanvas3D& canvas) { if (!m_enabled) return; @@ -458,6 +525,19 @@ void GLCanvas3D::LayersEditing::render_variable_layer_height_dialog(GLCanvas3D& ImGui::AlignTextToFramePadding(); imgui.text(_L("Keep min")); + if (!m_other_object_ids.empty()) { + // Several objects are selected: by default they share one profile, which the prime tower requires. + imgui.bbl_checkbox("##each_separately", m_each_separately); + ImGui::SameLine(); + ImGui::AlignTextToFramePadding(); + // TRN Variable layer height tool, checkbox shown with several objects selected: give each object its own + // layer heights instead of one profile they all share. + imgui.text(_L("Each object separately")); + if (m_bar_object_ids.size() > 1) + // TRN Variable layer height tool: each selected object has a layer height bar at the right edge of the 3D view. + imgui.text(_L("Point at a bar to edit its object.")); + } + ImGui::Separator(); const wxString shift = GUI::shortkey_shift_prefix(); @@ -473,7 +553,7 @@ void GLCanvas3D::LayersEditing::render_variable_layer_height_dialog(GLCanvas3D& GLGizmoUtils::render_tooltip_button(&imgui, canvas, shortcuts, x, y); ImGui::SameLine(); - imgui.disabled_begin(check_object_layers_fixed(*m_slicing_parameters, m_layer_height_profile)); + imgui.disabled_begin(m_other_object_ids.empty() && check_object_layers_fixed(*m_slicing_parameters, m_layer_height_profile)); if (imgui.button(_L("Reset"))) { wxPostEvent((wxEvtHandler*) canvas.get_wxglcanvas(), SimpleEvent(EVT_GLCANVAS_RESET_LAYER_HEIGHT_PROFILE)); } @@ -495,6 +575,47 @@ void GLCanvas3D::LayersEditing::render_variable_layer_height_dialog(GLCanvas3D& imgui.end(); ImGui::PopStyleVar(2); imgui.pop_toolbar_style(); + + if (m_bar_object_ids.size() <= 1 && m_object_max_z > 0.0f) { + // One mark for each height at which other objects end. An object as tall as the one shown ends at + // the top of the bar and needs none, and objects that end at the same height share one. + struct TopMark + { + double z; + std::vector> names; + }; + std::vector marks; + for (int object_id : m_other_object_ids) { + if (object_id < 0 || object_id >= int(m_model->objects.size())) + continue; + const ModelObject& object = *m_model->objects[object_id]; + const double z = object.max_z(); + if (z > double(m_object_max_z) - EPSILON) + continue; + auto mark = std::find_if(marks.begin(), marks.end(), [z](const TopMark& m) { return std::abs(m.z - z) < EPSILON; }); + if (mark == marks.end()) + mark = marks.insert(marks.end(), TopMark{ z, {} }); + auto name = std::find_if(mark->names.begin(), mark->names.end(), [&object](const auto& n) { return n.first == object.name; }); + if (name == mark->names.end()) + mark->names.emplace_back(object.name, 1); + else + ++name->second; + } + // From the top down, so that a label pushed down by the one above it does not cover the next. + std::sort(marks.begin(), marks.end(), [](const TopMark& lhs, const TopMark& rhs) { return lhs.z > rhs.z; }); + const float cnv_width = float(cnv_size.get_width()); + const float cnv_height = float(cnv_size.get_height()); + float label_bottom = 0.0f; + // The toolbar row can end next to the bar, where the labels near its top would cover its last buttons. + ImVec2 toolbar_end(0.0f, 0.0f); + if (canvas.m_main_toolbar.is_enabled()) + toolbar_end = ImVec2(float(canvas.get_main_toolbar_offset()) + canvas.m_main_toolbar.get_width() + canvas.m_separator_toolbar.get_width() + + canvas.m_gizmos.get_scaled_total_width() + canvas.m_assemble_view_toolbar.get_width(), + std::max(canvas.m_main_toolbar.get_height(), canvas.m_gizmos.get_scaled_total_height())); + for (const TopMark& mark : marks) + label_bottom = render_object_top_mark(object_top_mark_label(mark.names), cnv_width - thickness_bar_width(canvas), cnv_width, + cnv_height * (1.0f - float(mark.z) / m_object_max_z), label_bottom, cnv_height, toolbar_end); + } } void GLCanvas3D::LayersEditing::render_overlay(GLCanvas3D& canvas) @@ -519,19 +640,99 @@ float GLCanvas3D::LayersEditing::get_cursor_z_relative(const GLCanvas3D& canvas) -1000.0f; } +// Whether the point is on any of the bars. bool GLCanvas3D::LayersEditing::bar_rect_contains(const GLCanvas3D& canvas, float x, float y) { - const Rect& rect = get_bar_rect_screen(canvas); - return rect.get_left() <= x && x <= rect.get_right() && rect.get_top() <= y && y <= rect.get_bottom(); + return bar_at(canvas, x, y) >= 0; } +int GLCanvas3D::LayersEditing::bar_at(const GLCanvas3D& canvas, float x, float y) +{ + const Size& cnv_size = canvas.get_canvas_size(); + const float w = (float)cnv_size.get_width(); + const float h = (float)cnv_size.get_height(); + const float bar_w = thickness_bar_width(canvas); + const int bars = std::max(1, int(canvas.m_layers_editing.m_bar_object_ids.size())); + if (x < w - float(bars) * bar_w || x > w || y < 0.0f || y > h) + return -1; + const int bar = std::min(bars - 1, int((w - x) / bar_w)); + // Above a lower bar the scene shows through, and the mouse belongs to it. + return y < h * (1.0f - canvas.m_layers_editing.bar_fraction(size_t(bar))) ? -1 : bar; +} + +// Whether a bar is being pointed at or painted. +bool GLCanvas3D::LayersEditing::bar_in_focus(const GLCanvas3D& canvas) const +{ + const Vec2d mouse_pos = canvas.get_local_mouse_position(); + return state == Editing || bar_at(canvas, float(mouse_pos.x()), float(mouse_pos.y())) >= 0; +} + +size_t GLCanvas3D::LayersEditing::active_bar() const +{ + const auto it = std::find(m_bar_object_ids.begin(), m_bar_object_ids.end(), last_object_id); + return it == m_bar_object_ids.end() ? 0 : size_t(it - m_bar_object_ids.begin()); +} + +// The bar of the object shown, which is the one the mouse edits. Rect GLCanvas3D::LayersEditing::get_bar_rect_screen(const GLCanvas3D& canvas) { const Size& cnv_size = canvas.get_canvas_size(); float w = (float)cnv_size.get_width(); float h = (float)cnv_size.get_height(); + const float bar_w = thickness_bar_width(canvas); + const size_t active = canvas.m_layers_editing.active_bar(); + const float right = w - float(active) * bar_w; - return { w - thickness_bar_width(canvas), 0.0f, w, h }; + return { right - bar_w, h * (1.0f - canvas.m_layers_editing.bar_fraction(active)), right, h }; +} + +int GLCanvas3D::LayersEditing::choose_shown_object(const GLCanvas3D& canvas, const Model& model, const std::vector& object_ids) +{ + // Objects past MAX_BARS still get Adaptive, Smooth and Reset, but have no bar to show or paint. + const bool bars_notice = m_each_separately && object_ids.size() > MAX_BARS; + if (bars_notice != m_bars_notice_shown) { + m_bars_notice_shown = bars_notice; + // TRN "Adaptive", "Smooth" and "Reset" are the buttons of the variable layer height tool. + const std::string notice_text = _u8L("Variable layer height: only the three tallest selected objects have a bar. The others still take Adaptive, Smooth and Reset."); + NotificationManager& notification_manager = *wxGetApp().plater()->get_notification_manager(); + if (bars_notice) + notification_manager.push_plater_warning_notification(notice_text); + else + notification_manager.close_plater_warning_notification(notice_text); + } + + m_bar_object_ids.clear(); + m_bar_fractions.clear(); + if (object_ids.empty()) + return -1; + + m_bar_object_ids.assign(object_ids.begin(), object_ids.begin() + (m_each_separately ? std::min(object_ids.size(), MAX_BARS) : 1)); + const double tallest = model.objects[m_bar_object_ids.front()]->max_z(); + for (int object_id : m_bar_object_ids) + m_bar_fractions.emplace_back(tallest > 0. ? float(std::min(1., model.objects[object_id]->max_z() / tallest)) : 1.0f); + int shown = std::find(m_bar_object_ids.begin(), m_bar_object_ids.end(), last_object_id) != m_bar_object_ids.end() ? + last_object_id : m_bar_object_ids.front(); + // A profile being painted stays with its object, wherever the mouse wanders. + if (state != Editing) { + const Vec2d mouse_pos = canvas.get_local_mouse_position(); + if (const int bar = bar_at(canvas, float(mouse_pos.x()), float(mouse_pos.y())); bar >= 0) + shown = m_bar_object_ids[bar]; + } + return shown; +} + +void GLCanvas3D::LayersEditing::release_unselected_textures(const Model& model, const std::vector& object_ids) +{ + for (auto it = m_other_textures.begin(); it != m_other_textures.end();) { + const size_t id = it->first; + const bool selected = std::any_of(object_ids.begin(), object_ids.end(), [&model, id](int object_id) { return model.objects[object_id]->id().id == id; }); + if (selected) + ++it; + else { + this->release_object_texture(it->second); + it = m_other_textures.erase(it); + } + } } bool GLCanvas3D::LayersEditing::is_initialized() const @@ -577,6 +778,8 @@ void GLCanvas3D::LayersEditing::render_active_object_annotations(const GLCanvas3 return; const float cnv_inv_width = 1.0f / cnv_width; + // The width the mouse is tested against, so that every bar is drawn where it is hit. + const float bar_w = thickness_bar_width(canvas); GLShaderProgram* shader = wxGetApp().get_shader("variable_layer_height"); if (shader == nullptr) @@ -584,47 +787,64 @@ void GLCanvas3D::LayersEditing::render_active_object_annotations(const GLCanvas3 shader->start_using(); - shader->set_uniform("z_to_texture_row", float(m_layers_texture.cells - 1) / (float(m_layers_texture.width) * m_object_max_z)); + generate_layer_height_texture(); + shader->set_uniform("z_texture_row_to_normalized", 1.0f / (float)m_layers_texture.height); - shader->set_uniform("z_cursor", m_object_max_z * this->get_cursor_z_relative(canvas)); shader->set_uniform("z_cursor_band_width", band_width); - shader->set_uniform("object_max_z", m_object_max_z); + shader->set_uniform("dimming", 0.0f); shader->set_uniform("view_model_matrix", Transform3d::Identity()); shader->set_uniform("projection_matrix", Transform3d::Identity()); shader->set_uniform("view_normal_matrix", (Matrix3d)Matrix3d::Identity()); - glsafe(::glPixelStorei(GL_UNPACK_ALIGNMENT, 1)); - glsafe(::glBindTexture(GL_TEXTURE_2D, m_z_texture_id)); + // Render the color bars, one per object that has one. Each is drawn at the scale of its own object. + const size_t active = this->active_bar(); + const size_t bars = std::max(1, m_bar_object_ids.size()); + this->reset_bar_models(bars); + for (size_t bar = 0; bar < bars; ++bar) { + const LayersTexture* texture = &m_layers_texture; + float max_z = m_object_max_z; + if (bar == active) + this->bind_shown_texture(); + else { + ObjectTexture& other = this->other_object(m_bar_object_ids[bar]); + texture = &this->bind_object_texture(other); + max_z = float(other.max_z); + } - // Render the color bar - if (!m_profile.background.is_initialized() || m_profile.old_canvas_width != cnv_width) { - m_profile.old_canvas_width = cnv_width; - m_profile.background.reset(); + shader->set_uniform("z_to_texture_row", float(texture->cells - 1) / (float(texture->width) * max_z)); + shader->set_uniform("z_cursor", bar == active ? max_z * this->get_cursor_z_relative(canvas) : -1000.0f * max_z); + shader->set_uniform("object_max_z", max_z); - GLModel::Geometry init_data; - init_data.format = { GLModel::Geometry::EPrimitiveType::Triangles, GLModel::Geometry::EVertexLayout::P3N3T2 }; - init_data.reserve_vertices(4); - init_data.reserve_indices(6); + BarModels& models = m_bar_models[bar]; + const std::vector layout{ cnv_width, bar_w, this->bar_fraction(bar) }; + if (models.background_layout != layout) { + models.background_layout = layout; + models.background.reset(); - // vertices - const float l = 1.0f - 2.0f * THICKNESS_BAR_WIDTH * cnv_inv_width; - const float r = 1.0f; - const float t = 1.0f; - const float b = -1.0f; - init_data.add_vertex(Vec3f(l, b, 0.0f), Vec3f::UnitZ(), Vec2f(0.0f, 0.0f)); - init_data.add_vertex(Vec3f(r, b, 0.0f), Vec3f::UnitZ(), Vec2f(1.0f, 0.0f)); - init_data.add_vertex(Vec3f(r, t, 0.0f), Vec3f::UnitZ(), Vec2f(1.0f, 1.0f)); - init_data.add_vertex(Vec3f(l, t, 0.0f), Vec3f::UnitZ(), Vec2f(0.0f, 1.0f)); + GLModel::Geometry init_data; + init_data.format = { GLModel::Geometry::EPrimitiveType::Triangles, GLModel::Geometry::EVertexLayout::P3N3T2 }; + init_data.reserve_vertices(4); + init_data.reserve_indices(6); - // indices - init_data.add_triangle(0, 1, 2); - init_data.add_triangle(2, 3, 0); + // vertices + const float l = 1.0f - 2.0f * float(bar + 1) * bar_w * cnv_inv_width; + const float r = 1.0f - 2.0f * float(bar) * bar_w * cnv_inv_width; + const float t = -1.0f + 2.0f * this->bar_fraction(bar); + const float b = -1.0f; + init_data.add_vertex(Vec3f(l, b, 0.0f), Vec3f::UnitZ(), Vec2f(0.0f, 0.0f)); + init_data.add_vertex(Vec3f(r, b, 0.0f), Vec3f::UnitZ(), Vec2f(1.0f, 0.0f)); + init_data.add_vertex(Vec3f(r, t, 0.0f), Vec3f::UnitZ(), Vec2f(1.0f, 1.0f)); + init_data.add_vertex(Vec3f(l, t, 0.0f), Vec3f::UnitZ(), Vec2f(0.0f, 1.0f)); - m_profile.background.init_from(std::move(init_data)); + // indices + init_data.add_triangle(0, 1, 2); + init_data.add_triangle(2, 3, 0); + + models.background.init_from(std::move(init_data)); + } + models.background.render(); } - m_profile.background.render(); - glsafe(::glBindTexture(GL_TEXTURE_2D, 0)); shader->stop_using(); @@ -646,52 +866,102 @@ void GLCanvas3D::LayersEditing::render_profile(const GLCanvas3D& canvas) if (cnv_width == 0.0f || cnv_height == 0.0f) return; - // Make the vertical bar a bit wider so the layer height curve does not touch the edge of the bar region. - const float scale_x = THICKNESS_BAR_WIDTH / float(1.12 * m_slicing_parameters->max_layer_height); - const float scale_y = cnv_height / m_object_max_z; - + const float bar_w = thickness_bar_width(canvas); const float cnv_inv_width = 1.0f / cnv_width; const float cnv_inv_height = 1.0f / cnv_height; + const auto to_ndc_x = [cnv_inv_width](float x) { return 2.0f * (x * cnv_inv_width - 0.5f); }; + const auto to_ndc_y = [cnv_inv_height](float y) { return 2.0f * (y * cnv_inv_height - 0.5f); }; - // Baseline - if (!m_profile.baseline.is_initialized() || m_profile.old_layer_height_profile != m_layer_height_profile) { - m_profile.baseline.reset(); + const size_t active = this->active_bar(); + const size_t bars = std::max(1, m_bar_object_ids.size()); + this->reset_bar_models(bars); - GLModel::Geometry init_data; - init_data.format = { GLModel::Geometry::EPrimitiveType::Lines, GLModel::Geometry::EVertexLayout::P2}; - init_data.color = ColorRGBA::BLACK(); - init_data.reserve_vertices(2); - init_data.reserve_indices(2); + // The layer height curve of each bar, at the scale of its own object and of its own layer heights. + // The straight lines are laid out from the canvas, the active bar, and the axis and the top of each bar. + std::vector lines_layout{ cnv_width, cnv_height, bar_w, float(active) }; + for (size_t bar = 0; bar < bars; ++bar) { + const ObjectTexture* other = bar == active ? nullptr : &this->other_object(m_bar_object_ids[bar]); + const SlicingParameters& params = other == nullptr ? *m_slicing_parameters : other->slicing_parameters; + const std::vector& profile = other == nullptr ? m_layer_height_profile : other->profile; + const float max_z = other == nullptr ? m_object_max_z : float(other->max_z); + // Make the vertical bar a bit wider so the layer height curve does not touch the edge of the bar region. + const float scale_x = bar_w / float(1.12 * params.max_layer_height); + const float scale_y = cnv_height * this->bar_fraction(bar) / max_z; + const float left = cnv_width - float(bar + 1) * bar_w; + lines_layout.push_back(to_ndc_x(left + float(params.layer_height) * scale_x)); + lines_layout.push_back(this->bar_fraction(bar)); - // vertices - const float axis_x = 2.0f * ((cnv_width - THICKNESS_BAR_WIDTH + float(m_slicing_parameters->layer_height) * scale_x) * cnv_inv_width - 0.5f); - init_data.add_vertex(Vec2f(axis_x, -1.0f)); - init_data.add_vertex(Vec2f(axis_x, 1.0f)); + BarModels& models = m_bar_models[bar]; + const std::vector layout{ cnv_width, cnv_height, bar_w, this->bar_fraction(bar), max_z, float(params.max_layer_height) }; + if (models.profile_layout != layout || models.profile_source != profile) { + models.profile_layout = layout; + models.profile_source = profile; + models.profile.reset(); + if (profile.size() >= 4) { + GLModel::Geometry init_data; + init_data.format = { GLModel::Geometry::EPrimitiveType::LineStrip, GLModel::Geometry::EVertexLayout::P2 }; + init_data.color = ColorRGBA::BLUE(); + init_data.reserve_vertices(profile.size() / 2); + init_data.reserve_indices(profile.size() / 2); - // indices - init_data.add_line(0, 1); - - m_profile.baseline.init_from(std::move(init_data)); + // vertices + indices + for (unsigned int i = 0; i + 1 < (unsigned int)profile.size(); i += 2) { + init_data.add_vertex(Vec2f(to_ndc_x(left + float(profile[i + 1]) * scale_x), to_ndc_y(float(profile[i]) * scale_y))); + init_data.add_index(i / 2); + } + models.profile.init_from(std::move(init_data)); + } + } } - if (!m_profile.profile.is_initialized() || m_profile.old_layer_height_profile != m_layer_height_profile) { - m_profile.old_layer_height_profile = m_layer_height_profile; - m_profile.profile.reset(); + if (m_bar_lines_layout != lines_layout) { + m_bar_lines_layout = lines_layout; - GLModel::Geometry init_data; - init_data.format = { GLModel::Geometry::EPrimitiveType::LineStrip, GLModel::Geometry::EVertexLayout::P2 }; - init_data.color = ColorRGBA::BLUE(); - init_data.reserve_vertices(m_layer_height_profile.size() / 2); - init_data.reserve_indices(m_layer_height_profile.size() / 2); - - // vertices + indices - for (unsigned int i = 0; i < (unsigned int)m_layer_height_profile.size(); i += 2) { - init_data.add_vertex(Vec2f(2.0f * ((cnv_width - THICKNESS_BAR_WIDTH + float(m_layer_height_profile[i + 1]) * scale_x) * cnv_inv_width - 0.5f), - 2.0f * (float(m_layer_height_profile[i]) * scale_y * cnv_inv_height - 0.5))); - init_data.add_index(i / 2); + // Straight lines: the baseline of each bar and, with several bars, the outline of each. + GLModel::Geometry lines_data; + lines_data.format = { GLModel::Geometry::EPrimitiveType::Lines, GLModel::Geometry::EVertexLayout::P2 }; + lines_data.color = ColorRGBA::BLACK(); + unsigned int lines_count = 0; + const auto add_line = [&lines_data, &lines_count](const Vec2f& from, const Vec2f& to) { + lines_data.add_vertex(from); + lines_data.add_vertex(to); + lines_data.add_line(2 * lines_count, 2 * lines_count + 1); + ++lines_count; + }; + for (size_t bar = 0; bar < bars; ++bar) { + const float axis_x = lines_layout[4 + 2 * bar]; + const float top = -1.0f + 2.0f * lines_layout[5 + 2 * bar]; + add_line(Vec2f(axis_x, -1.0f), Vec2f(axis_x, top)); + if (bars > 1) { + // The outline of the bar: its left edge and its top. The next bar to the right is at least as tall. + const float left = to_ndc_x(cnv_width - float(bar + 1) * bar_w); + const float right = to_ndc_x(cnv_width - float(bar) * bar_w); + add_line(Vec2f(left, -1.0f), Vec2f(left, top)); + add_line(Vec2f(left, top), Vec2f(right, top)); + } } + m_bar_lines.reset(); + m_bar_lines.init_from(std::move(lines_data)); - m_profile.profile.init_from(std::move(init_data)); + // With several bars, the one pointed at is framed in white. + m_bar_frame.reset(); + if (bars > 1) { + GLModel::Geometry frame_data; + frame_data.format = { GLModel::Geometry::EPrimitiveType::Lines, GLModel::Geometry::EVertexLayout::P2 }; + frame_data.color = ColorRGBA::WHITE(); + // Kept a pixel inside the bar, so the frame is not drawn over by the edge between bars. + const float l = to_ndc_x(cnv_width - float(active + 1) * bar_w + 1.0f); + const float r = to_ndc_x(cnv_width - float(active) * bar_w - 1.0f); + const float t = to_ndc_y(cnv_height * this->bar_fraction(active) - 1.0f); + frame_data.add_vertex(Vec2f(l, -1.0f)); + frame_data.add_vertex(Vec2f(l, t)); + frame_data.add_vertex(Vec2f(r, t)); + frame_data.add_vertex(Vec2f(r, -1.0f)); + frame_data.add_line(0, 1); + frame_data.add_line(1, 2); + frame_data.add_line(2, 3); + m_bar_frame.init_from(std::move(frame_data)); + } } #if SLIC3R_OPENGL_ES @@ -713,8 +983,12 @@ void GLCanvas3D::LayersEditing::render_profile(const GLCanvas3D& canvas) #if !SLIC3R_OPENGL_ES } #endif // !SLIC3R_OPENGL_ES - m_profile.baseline.render(); - m_profile.profile.render(); + m_bar_lines.render(); + if (bars > 1 && this->bar_in_focus(canvas)) + m_bar_frame.render(); + for (size_t bar = 0; bar < bars; ++bar) + if (m_bar_models[bar].profile.is_initialized()) + m_bar_models[bar].profile.render(); shader->stop_using(); } } @@ -738,42 +1012,203 @@ void GLCanvas3D::LayersEditing::render_volumes(const GLCanvas3D& canvas, const G generate_layer_height_texture(); // Uniforms were resolved, go ahead using the layer editing shader. - shader->set_uniform("z_to_texture_row", float(m_layers_texture.cells - 1) / (float(m_layers_texture.width) * float(m_object_max_z))); shader->set_uniform("z_texture_row_to_normalized", 1.0f / float(m_layers_texture.height)); - shader->set_uniform("z_cursor", float(m_object_max_z) * float(this->get_cursor_z_relative(canvas))); shader->set_uniform("z_cursor_band_width", float(this->band_width)); + // The band at the height under the mouse goes on the objects the edit will change: all of them + // while they share a profile, or the object shown alone when each has its own. + const float z_cursor = float(m_object_max_z) * float(this->get_cursor_z_relative(canvas)); + shader->set_uniform("projection_matrix", wxGetApp().plater()->get_camera().get_projection_matrix()); - const Camera& camera = wxGetApp().plater()->get_camera(); - shader->set_uniform("projection_matrix", camera.get_projection_matrix()); + // Orca: the other selected objects. Those on the layers of the object shown are drawn with its + // texture, the others with their own. With a profile each, pointing at a bar tones down the + // objects it does not edit. + const float dimming = m_each_separately && this->bar_in_focus(canvas) ? 0.6f : 0.0f; + for (int object_id : this->edited_object_ids()) + if (object_id != this->last_object_id) { + ObjectTexture& other = this->other_object(object_id); + if (this->shares_shown_layers(other)) { + this->bind_shown_texture(); + this->render_object_volumes(volumes, *shader, object_id, m_layers_texture, m_object_max_z, z_cursor, dimming); + } else { + const LayersTexture& texture = this->bind_object_texture(other); + this->render_object_volumes(volumes, *shader, object_id, texture, other.max_z, + this->follows_shown_object(other.slicing_parameters) ? z_cursor : -1000.0f * float(other.max_z), dimming); + } + } + this->bind_shown_texture(); + this->render_object_volumes(volumes, *shader, this->last_object_id, m_layers_texture, m_object_max_z, z_cursor, 0.0f); + // Revert back to the previous shader. + glBindTexture(GL_TEXTURE_2D, 0); +} - // Initialize the layer height texture mapping. - const GLsizei w = (GLsizei)m_layers_texture.width; - const GLsizei h = (GLsizei)m_layers_texture.height; - const GLsizei half_w = w / 2; - const GLsizei half_h = h / 2; - glsafe(::glPixelStorei(GL_UNPACK_ALIGNMENT, 1)); - glsafe(::glBindTexture(GL_TEXTURE_2D, m_z_texture_id)); - glsafe(::glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0)); - glsafe(::glTexImage2D(GL_TEXTURE_2D, 1, GL_RGBA, half_w, half_h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0)); - glsafe(::glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, m_layers_texture.data.data())); - glsafe(::glTexSubImage2D(GL_TEXTURE_2D, 1, 0, 0, half_w, half_h, GL_RGBA, GL_UNSIGNED_BYTE, m_layers_texture.data.data() + m_layers_texture.width * m_layers_texture.height * 4)); +void GLCanvas3D::LayersEditing::render_object_volumes(const GLVolumeCollection& volumes, GLShaderProgram& shader, int object_id, const LayersTexture& texture, double object_max_z, float z_cursor, float dimming) +{ + shader.set_uniform("z_to_texture_row", float(texture.cells - 1) / (float(texture.width) * float(object_max_z))); + shader.set_uniform("z_cursor", z_cursor); + shader.set_uniform("dimming", dimming); + + const Transform3d& view_matrix = wxGetApp().plater()->get_camera().get_view_matrix(); for (GLVolume* glvolume : volumes.volumes) { // Render the object using the layer editing shader and texture. - if (!glvolume->is_active || glvolume->composite_id.object_id != this->last_object_id || glvolume->is_modifier) + if (!glvolume->is_active || glvolume->composite_id.object_id != object_id || glvolume->is_modifier) continue; - shader->set_uniform("volume_world_matrix", glvolume->world_matrix()); - shader->set_uniform("object_max_z", 0.0f); - const Transform3d& view_matrix = camera.get_view_matrix(); + shader.set_uniform("volume_world_matrix", glvolume->world_matrix()); + shader.set_uniform("object_max_z", 0.0f); const Transform3d model_matrix = glvolume->world_matrix(); - shader->set_uniform("view_model_matrix", view_matrix * model_matrix); - const Matrix3d view_normal_matrix = view_matrix.matrix().block(0, 0, 3, 3) * model_matrix.matrix().block(0, 0, 3, 3).inverse().transpose(); - shader->set_uniform("view_normal_matrix", view_normal_matrix); + shader.set_uniform("view_model_matrix", view_matrix * model_matrix); + // Orca: the shader also tells the horizontal faces from the normals in world space, which need the inverse transpose + // too: the world matrix itself tilts them under a non-uniform scale. + const Matrix3d world_normal_matrix = model_matrix.matrix().block(0, 0, 3, 3).inverse().transpose(); + shader.set_uniform("volume_world_normal_matrix", world_normal_matrix); + const Matrix3d view_normal_matrix = view_matrix.matrix().block(0, 0, 3, 3) * world_normal_matrix; + shader.set_uniform("view_normal_matrix", view_normal_matrix); glvolume->render(); } - // Revert back to the previous shader. - glBindTexture(GL_TEXTURE_2D, 0); +} + +// Sends the texture to the GPU as texture_id and leaves it bound. +void GLCanvas3D::LayersEditing::load_texture(const LayersTexture& texture, unsigned int texture_id) +{ + // Initialize the layer height texture mapping. + const GLsizei w = (GLsizei)texture.width; + const GLsizei h = (GLsizei)texture.height; + const GLsizei half_w = w / 2; + const GLsizei half_h = h / 2; + glsafe(::glPixelStorei(GL_UNPACK_ALIGNMENT, 1)); + glsafe(::glBindTexture(GL_TEXTURE_2D, texture_id)); + glsafe(::glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0)); + glsafe(::glTexImage2D(GL_TEXTURE_2D, 1, GL_RGBA, half_w, half_h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0)); + glsafe(::glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, texture.data.data())); + glsafe(::glTexSubImage2D(GL_TEXTURE_2D, 1, 0, 0, half_w, half_h, GL_RGBA, GL_UNSIGNED_BYTE, texture.data.data() + texture.width * texture.height * 4)); +} + +void GLCanvas3D::LayersEditing::bind_shown_texture() +{ + if (m_layers_texture.uploaded) + glsafe(::glBindTexture(GL_TEXTURE_2D, m_z_texture_id)); + else { + load_texture(m_layers_texture, m_z_texture_id); + m_layers_texture.uploaded = true; + } +} + +// A copy of a GLModel shares the GPU buffers that the original deletes, so the models of the bars +// are not moved when the vector grows: they are all made again when the number of bars changes. +void GLCanvas3D::LayersEditing::reset_bar_models(size_t bars) +{ + if (m_bar_models.size() != bars) { + m_bar_models.clear(); + m_bar_models.resize(bars); + } +} + +bool GLCanvas3D::LayersEditing::is_edited_object(int object_id) const +{ + return object_id == last_object_id || std::find(m_other_object_ids.begin(), m_other_object_ids.end(), object_id) != m_other_object_ids.end(); +} + +// Orca: whether two objects, whatever their heights, are sliced at the same layers by the same profile, +// and have their layer heights drawn in the same colours. +static bool same_layer_parameters(const SlicingParameters& lhs, const SlicingParameters& rhs) +{ + return lhs.layer_height == rhs.layer_height && lhs.min_layer_height == rhs.min_layer_height && + lhs.max_layer_height == rhs.max_layer_height && lhs.first_object_layer_height == rhs.first_object_layer_height && + lhs.first_object_layer_height_fixed() == rhs.first_object_layer_height_fixed() && + lhs.object_print_z_min == rhs.object_print_z_min && lhs.object_shrinkage_compensation_z == rhs.object_shrinkage_compensation_z; +} + +GLCanvas3D::LayersEditing::ObjectTexture& GLCanvas3D::LayersEditing::other_object(int object_id) +{ + const ModelObject& model_object = *m_model->objects[object_id]; + ObjectTexture& object = m_other_textures[model_object.id().id]; + const ObjectWithTimestamp::Timestamp timestamp = model_object.layer_height_profile.timestamp(); + const double max_z = model_object.max_z(); + if (object.config_version != m_config_version || object.model_profile_timestamp != timestamp || object.max_z != max_z) { + object.config_version = m_config_version; + object.model_profile_timestamp = timestamp; + object.max_z = max_z; + const SlicingParameters slicing_parameters = this->slicing_parameters_of(model_object); + std::vector profile; + PrintObject::update_layer_height_profile(model_object, slicing_parameters, profile); + if (profile != object.profile || !same_layer_parameters(slicing_parameters, object.slicing_parameters) || + slicing_parameters.object_print_z_height() != object.slicing_parameters.object_print_z_height()) { + object.profile = std::move(profile); + object.slicing_parameters = slicing_parameters; + object.texture.valid = false; + object.shares_version = size_t(-1); + } + } + return object; +} + +const GLCanvas3D::LayersEditing::LayersTexture& GLCanvas3D::LayersEditing::bind_object_texture(ObjectTexture& object) +{ + LayersTexture& texture = object.texture; + if (!texture.valid) { + if (texture.data.empty()) { + texture.width = 1024; + texture.height = 1024; + texture.levels = 2; + texture.data.assign(texture.width * texture.height * 5, 0); + } + texture.cells = Slic3r::generate_layer_height_texture( + object.slicing_parameters, + Slic3r::generate_object_layers(object.slicing_parameters, object.profile, false), + texture.data.data(), texture.height, texture.width, true); + texture.valid = true; + texture.uploaded = false; + } + if (object.texture_id == 0) + object.texture_id = create_texture(); + if (texture.uploaded) + glsafe(::glBindTexture(GL_TEXTURE_2D, object.texture_id)); + else { + load_texture(texture, object.texture_id); + texture.uploaded = true; + // The GPU keeps the texture; the 5 MB here are only needed to make it again. + std::vector().swap(texture.data); + } + return texture; +} + +bool GLCanvas3D::LayersEditing::follows_shown_object(const SlicingParameters& slicing_parameters) const +{ + // The first entries of a shared profile are those of the object shown, and + // PrintObject::update_layer_height_profile() drops a profile whose first layer is not the object's own. + return !m_each_separately && m_slicing_parameters != nullptr && + std::abs(slicing_parameters.first_object_layer_height - m_slicing_parameters->first_object_layer_height) < EPSILON && + slicing_parameters.first_object_layer_height_fixed() == m_slicing_parameters->first_object_layer_height_fixed() && + std::abs(slicing_parameters.object_print_z_min - m_slicing_parameters->object_print_z_min) < EPSILON; +} + +bool GLCanvas3D::LayersEditing::shares_shown_layers(ObjectTexture& object) const +{ + if (!this->follows_shown_object(object.slicing_parameters)) + return false; + // While a profile is painted, the others take it when the stroke ends (accept_changes()), so they show it already. + if (state == Editing) + return true; + if (object.shares_version != m_layers_texture_version) { + object.shares_version = m_layers_texture_version; + object.shares = m_slicing_parameters != nullptr && m_layer_height_profile.size() >= 4 && object.max_z > EPSILON && + same_layer_parameters(object.slicing_parameters, *m_slicing_parameters); + if (object.shares) { + const std::vector fitted = layer_height_profile_fit_to_height(m_layer_height_profile, object.max_z); + object.shares = fitted.size() == object.profile.size() && + std::equal(fitted.begin(), fitted.end(), object.profile.begin(), [](double lhs, double rhs) { return std::abs(lhs - rhs) < EPSILON; }); + } + } + return object.shares; +} + +void GLCanvas3D::LayersEditing::release_object_texture(ObjectTexture& object) +{ + if (object.texture_id != 0) { + glsafe(::glDeleteTextures(1, &object.texture_id)); + object.texture_id = 0; + } } void GLCanvas3D::LayersEditing::adjust_layer_height_profile() @@ -784,33 +1219,88 @@ void GLCanvas3D::LayersEditing::adjust_layer_height_profile() m_layers_texture.valid = false; } +std::vector GLCanvas3D::LayersEditing::edited_object_ids() const +{ + std::vector object_ids{ last_object_id }; + for (int object_id : m_other_object_ids) + if (object_id >= 0 && object_id < int(m_model->objects.size()) && object_id != last_object_id) + object_ids.emplace_back(object_id); + return object_ids; +} + +SlicingParameters GLCanvas3D::LayersEditing::slicing_parameters_of(const ModelObject& model_object) const +{ + return PrintObject::slicing_parameters(*m_config, model_object, float(model_object.max_z()), m_shrinkage_compensation); +} + +// profiles[0] is the profile of the object shown. +void GLCanvas3D::LayersEditing::set_profiles(GLCanvas3D& canvas, const std::vector& object_ids, const std::vector>& profiles) +{ + for (size_t i = 0; i < object_ids.size(); ++i) { + m_model->objects[object_ids[i]]->layer_height_profile.set(profiles[i]); + wxGetApp().obj_list()->update_info_items(object_ids[i]); + } + m_layer_height_profile = profiles.front(); + m_layers_texture.valid = false; + canvas.post_event(SimpleEvent(EVT_GLCANVAS_SCHEDULE_BACKGROUND_PROCESS)); +} + void GLCanvas3D::LayersEditing::reset_layer_height_profile(GLCanvas3D & canvas) { - const_cast(m_model_object)->layer_height_profile.clear(); + for (int object_id : this->edited_object_ids()) { + m_model->objects[object_id]->layer_height_profile.clear(); + wxGetApp().obj_list()->update_info_items(object_id); + } m_layer_height_profile.clear(); m_layers_texture.valid = false; canvas.post_event(SimpleEvent(EVT_GLCANVAS_SCHEDULE_BACKGROUND_PROCESS)); - wxGetApp().obj_list()->update_info_items(last_object_id); } void GLCanvas3D::LayersEditing::adaptive_layer_height_profile(GLCanvas3D & canvas, float quality_factor) { this->update_slicing_parameters(); - m_layer_height_profile = layer_height_profile_adaptive(*m_slicing_parameters, *m_model_object, quality_factor); - const_cast(m_model_object)->layer_height_profile.set(m_layer_height_profile); - m_layers_texture.valid = false; - canvas.post_event(SimpleEvent(EVT_GLCANVAS_SCHEDULE_BACKGROUND_PROCESS)); - wxGetApp().obj_list()->update_info_items(last_object_id); + const std::vector object_ids = this->edited_object_ids(); + std::vector> profiles; + // The objects that share one profile: all of them by default, but an object that starts its layers + // elsewhere (a raft of its own, say) keeps its own adaptive profile, as does one too thin for a profile. + std::vector sharing; + for (size_t i = 0; i < object_ids.size(); ++i) { + const ModelObject& model_object = *m_model->objects[object_ids[i]]; + const SlicingParameters slicing_parameters = this->slicing_parameters_of(model_object); + profiles.emplace_back(layer_height_profile_adaptive(slicing_parameters, model_object, quality_factor)); + if (profiles.back().size() >= 4 && (i == 0 || this->follows_shown_object(slicing_parameters))) + sharing.emplace_back(i); + } + if (sharing.size() > 1 && sharing.front() == 0 && !m_each_separately) { + // One profile for them: the finest layer height any of them asks for at each Z. + std::vector> shared; + for (size_t i : sharing) + shared.emplace_back(profiles[i]); + const std::vector merged = layer_height_profile_merge_finest(shared); + for (size_t i : sharing) + profiles[i] = layer_height_profile_fit_to_height(merged, m_model->objects[object_ids[i]]->max_z()); + } + this->set_profiles(canvas, object_ids, profiles); } void GLCanvas3D::LayersEditing::smooth_layer_height_profile(GLCanvas3D & canvas, const HeightProfileSmoothingParams & smoothing_params) { this->update_slicing_parameters(); - m_layer_height_profile = smooth_height_profile(m_layer_height_profile, *m_slicing_parameters, smoothing_params); - const_cast(m_model_object)->layer_height_profile.set(m_layer_height_profile); - m_layers_texture.valid = false; - canvas.post_event(SimpleEvent(EVT_GLCANVAS_SCHEDULE_BACKGROUND_PROCESS)); - wxGetApp().obj_list()->update_info_items(last_object_id); + const std::vector object_ids = this->edited_object_ids(); + // The object shown is the tallest one, so its profile covers the others when they share one. + std::vector> profiles{ smooth_height_profile(m_layer_height_profile, *m_slicing_parameters, smoothing_params) }; + for (size_t i = 1; i < object_ids.size(); ++i) { + const ModelObject& model_object = *m_model->objects[object_ids[i]]; + const SlicingParameters slicing_parameters = this->slicing_parameters_of(model_object); + if (this->follows_shown_object(slicing_parameters)) + profiles.emplace_back(layer_height_profile_fit_to_height(profiles.front(), model_object.max_z())); + else { + std::vector profile; + PrintObject::update_layer_height_profile(model_object, slicing_parameters, profile); + profiles.emplace_back(smooth_height_profile(profile, slicing_parameters, smoothing_params)); + } + } + this->set_profiles(canvas, object_ids, profiles); } void GLCanvas3D::LayersEditing::generate_layer_height_texture() @@ -840,6 +1330,9 @@ void GLCanvas3D::LayersEditing::generate_layer_height_texture() Slic3r::generate_object_layers(*m_slicing_parameters, m_layer_height_profile, false), m_layers_texture.data.data(), m_layers_texture.height, m_layers_texture.width, level_of_detail_2nd_level); m_layers_texture.valid = true; + // Orca: sent to the GPU when next drawn, and the other objects check whether they still share it. + m_layers_texture.uploaded = false; + ++m_layers_texture_version; } void GLCanvas3D::LayersEditing::accept_changes(GLCanvas3D & canvas) @@ -847,6 +1340,15 @@ void GLCanvas3D::LayersEditing::accept_changes(GLCanvas3D & canvas) if (last_object_id >= 0) { wxGetApp().plater()->take_snapshot("Variable layer height - Manual edit"); const_cast(m_model_object)->layer_height_profile.set(m_layer_height_profile); + // The other selected objects share the profile that was just edited, if they can. + for (int object_id : this->edited_object_ids()) + if (object_id != last_object_id) { + ModelObject& model_object = *m_model->objects[object_id]; + if (this->follows_shown_object(this->slicing_parameters_of(model_object))) { + model_object.layer_height_profile.set(layer_height_profile_fit_to_height(m_layer_height_profile, model_object.max_z())); + wxGetApp().obj_list()->update_info_items(object_id); + } + } canvas.post_event(SimpleEvent(EVT_GLCANVAS_SCHEDULE_BACKGROUND_PROCESS)); wxGetApp().obj_list()->update_info_items(last_object_id); } @@ -2347,6 +2849,21 @@ void GLCanvas3D::smooth_layer_height_profile(const HeightProfileSmoothingParams& m_dirty = true; } +std::vector GLCanvas3D::get_layers_editing_object_idxs() const +{ + std::vector object_idxs; + if (m_model == nullptr) + return object_idxs; + for (const auto& [object_idx, instance_idxs] : m_selection.get_content()) + // Orca: an object needs some height above the bed to have layers to edit. + if (object_idx >= 0 && object_idx < int(m_model->objects.size()) && m_model->objects[object_idx]->max_z() > EPSILON) + object_idxs.emplace_back(object_idx); + std::stable_sort(object_idxs.begin(), object_idxs.end(), [this](int lhs, int rhs) { + return m_model->objects[lhs]->max_z() > m_model->objects[rhs]->max_z(); + }); + return object_idxs; +} + void GLCanvas3D::enable_layers_editing(bool enable) { m_layers_editing.set_enabled(enable); @@ -4282,8 +4799,10 @@ bool GLCanvas3D::handle_shortcut(const KeyChord& chord) }; switch (shortcut) { + // Orca: the variable layer height tool works on several objects, so selecting all the plate's stays + // available in it, though not while a profile is painted. All the plates' would mix their layers. case Shortcut::SelectAll: - if (!painting && !m_layers_editing.is_enabled()) + if (!painting && m_layers_editing.state != LayersEditing::Editing) post_event(SimpleEvent(EVT_GLCANVAS_SELECT_CURR_PLATE_ALL)); break; case Shortcut::SelectAllPlates: @@ -4997,7 +5516,9 @@ void GLCanvas3D::on_mouse(wxMouseEvent& evt) #endif /* SLIC3R_DEBUG_MOUSE_EVENTS */ } const int selected_object_idx = m_selection.get_object_idx(); - const int layer_editing_object_idx = is_layers_editing_enabled() ? selected_object_idx : -1; + // Orca: with several objects selected, the tool shows the tallest one. + const int layer_editing_object_idx = is_layers_editing_enabled() ? + (selected_object_idx != -1 ? selected_object_idx : m_layers_editing.last_object_id) : -1; const bool mouse_in_layer_editing = layer_editing_object_idx != -1 && m_layers_editing.bar_rect_contains(*this, pos(0), pos(1)); if (!mouse_in_layer_editing && m_main_toolbar.on_mouse(evt, *this)) { @@ -5211,6 +5732,8 @@ void GLCanvas3D::on_mouse(wxMouseEvent& evt) m_layers_editing.state = LayersEditing::Unknown; if (mouse_in_layer_editing) { // A volume is selected and the mouse is inside the layer thickness bar. + // Orca: edit the object of the bar under the mouse, though no frame was drawn since it got there. + _update_layers_editing_objects(false); // Start editing the layer height. m_layers_editing.state = LayersEditing::Editing; _perform_layer_editing_action(&evt); @@ -9769,8 +10292,8 @@ void GLCanvas3D::_render_objects(GLVolumeCollection::ERenderType type, bool with m_camera_clipping_plane = _get_volumes_clipping_plane(); if (m_picking_enabled) - // Update the layer editing selection to the first object selected, update the current object maximum Z. - m_layers_editing.select_object(*m_model, this->is_layers_editing_enabled() ? m_selection.get_object_idx() : -1); + // Update the layer editing selection to the tallest object selected, update the current object maximum Z. + _update_layers_editing_objects(true); if (const BuildVolume &build_volume = m_bed.build_volume(); build_volume.valid()) { switch (build_volume.type()) { @@ -9885,11 +10408,10 @@ void GLCanvas3D::_render_objects(GLVolumeCollection::ERenderType type, bool with if (dynamic_cast(gm.get_current()) == nullptr) { if (m_picking_enabled && m_layers_editing.is_enabled() && (m_layers_editing.last_object_id != -1) && (m_layers_editing.object_max_z() > 0.0f)) { - int object_id = m_layers_editing.last_object_id; const Camera& camera = wxGetApp().plater()->get_camera(); - m_volumes.render(type, false, camera.get_view_matrix(), camera.get_projection_matrix(), [object_id](const GLVolume& volume) { + m_volumes.render(type, false, camera.get_view_matrix(), camera.get_projection_matrix(), [this](const GLVolume& volume) { // Which volume to paint without the layer height profile shader? - return volume.is_active && (volume.is_modifier || volume.composite_id.object_id != object_id); + return volume.is_active && (volume.is_modifier || !m_layers_editing.is_edited_object(volume.composite_id.object_id)); }, true, nullptr, outlined_volumes); m_layers_editing.render_volumes(*this, m_volumes); } @@ -12285,6 +12807,17 @@ void GLCanvas3D::_update_volumes_hover_state() } } +void GLCanvas3D::_update_layers_editing_objects(bool rendering) +{ + std::vector object_idxs = this->is_layers_editing_enabled() ? this->get_layers_editing_object_idxs() : std::vector(); + if (rendering) + m_layers_editing.release_unselected_textures(*m_model, object_idxs); + const int shown = m_layers_editing.choose_shown_object(*this, *m_model, object_idxs); + m_layers_editing.select_object(*m_model, shown); + object_idxs.erase(std::remove(object_idxs.begin(), object_idxs.end(), shown), object_idxs.end()); + m_layers_editing.set_other_objects(std::move(object_idxs)); +} + void GLCanvas3D::_perform_layer_editing_action(wxMouseEvent* evt) { int object_idx_selected = m_layers_editing.last_object_id; diff --git a/src/slic3r/GUI/GLCanvas3D.hpp b/src/slic3r/GUI/GLCanvas3D.hpp index 9728363568..b178d3638f 100644 --- a/src/slic3r/GUI/GLCanvas3D.hpp +++ b/src/slic3r/GUI/GLCanvas3D.hpp @@ -17,6 +17,7 @@ #include "libslic3r/Polygon.hpp" #include "libslic3r/Technologies.hpp" #include "libslic3r/Model.hpp" +#include "libslic3r/ObjectID.hpp" #include "libvgcode/include/Types.hpp" #include "libslic3r/libslic3r.h" #include "libslic3r/Line.hpp" @@ -268,6 +269,11 @@ class GLCanvas3D const DynamicPrintConfig* m_config{ nullptr }; // ModelObject for the currently selected object (Model::objects[last_object_id]). const ModelObject* m_model_object{ nullptr }; + // Orca: the other selected objects, edited along with the one shown. Indices into m_model->objects. + const Model* m_model{ nullptr }; + std::vector m_other_object_ids; + // Orca: whether several selected objects each get a profile of their own, or share one. + bool m_each_separately{ false }; // Maximum z of the currently selected object (Model::objects[last_object_id]). float m_object_max_z{ 0.0f }; // Owned by LayersEditing. @@ -296,8 +302,58 @@ class GLCanvas3D size_t cells{ 0 }; // Does it need to be refreshed? bool valid{ false }; + // Orca: whether the GPU has the data as it is now. + bool uploaded{ false }; }; LayersTexture m_layers_texture; + // Orca: counts the times m_layers_texture was generated, so that the other objects can tell + // whether they still are on the layers it shows. + size_t m_layers_texture_version{ 0 }; + // Orca: counts the calls to set_config(), after which the other objects check their slicing + // parameters and their profiles again. + size_t m_config_version{ 0 }; + // Orca: the layer heights of the other selected objects, keyed by ModelObject ID. The texture is + // generated and sent to the GPU only when the object is drawn with it, and only again when the + // profile or the slicing parameters it shows change. + struct ObjectTexture + { + LayersTexture texture; + unsigned int texture_id{ 0 }; + // What the profile was read from: the object's own profile, its height and the configuration. + ObjectWithTimestamp::Timestamp model_profile_timestamp{ 0 }; + double max_z{ 0. }; + size_t config_version{ size_t(-1) }; + SlicingParameters slicing_parameters; + // The profile the object is sliced with: its own, or the one of its height ranges. + std::vector profile; + // Whether it is on the layers of m_layers_texture, as of shares_version. + bool shares{ false }; + size_t shares_version{ size_t(-1) }; + }; + std::map m_other_textures; + // Orca: the bars and the lines over them are rebuilt only when what they show changes. + struct BarModels + { + GLModel background; + std::vector background_layout; + GLModel profile; + std::vector profile_layout; + std::vector profile_source; + }; + std::vector m_bar_models; + GLModel m_bar_lines; + GLModel m_bar_frame; + std::vector m_bar_lines_layout; + // Orca: the objects that have a bar of their own, the rightmost bar first. With one profile + // shared between the selected objects that is the tallest object alone; with a profile each, + // the tallest ones, up to MAX_BARS. The object shown (last_object_id) is one of them. + static constexpr size_t MAX_BARS = 3; + std::vector m_bar_object_ids; + // Height of each bar as a fraction of the canvas height: the bars share one scale, set by the + // tallest object, so a lower object has a lower bar. + std::vector m_bar_fractions; + // Whether the notice that some selected objects have no bar is up. + bool m_bars_notice_shown{ false }; public: EState state{ Unknown }; @@ -306,15 +362,6 @@ class GLCanvas3D int last_object_id{ -1 }; float last_z{ 0.0f }; LayerHeightEditActionType last_action{ LAYER_HEIGHT_EDIT_ACTION_INCREASE }; - struct Profile - { - GLModel baseline; - GLModel profile; - GLModel background; - float old_canvas_width{ 0.0f }; - std::vector old_layer_height_profile; - }; - Profile m_profile; LayersEditing() = default; ~LayersEditing(); @@ -323,6 +370,14 @@ class GLCanvas3D void set_config(const DynamicPrintConfig* config); void select_object(const Model& model, int object_id); + void set_other_objects(std::vector object_ids) { m_other_object_ids = std::move(object_ids); } + // Orca: lays out the bars for the selected objects (tallest first) and returns the object to + // show and edit: the one whose bar the mouse is on, or else the one shown so far. + int choose_shown_object(const GLCanvas3D& canvas, const Model& model, const std::vector& object_ids); + // Orca: frees the textures of the objects that are no longer selected. Needs the GL context. + void release_unselected_textures(const Model& model, const std::vector& object_ids); + // Orca: whether the tool paints this object with its layer heights. + bool is_edited_object(int object_id) const; bool is_allowed() const; @@ -343,6 +398,8 @@ class GLCanvas3D static bool bar_rect_contains(const GLCanvas3D& canvas, float x, float y); static Rect get_bar_rect_screen(const GLCanvas3D& canvas); static float get_overlay_window_width() { return LayersEditing::s_overlay_window_width; } + // Orca: the width taken by the bars beyond the first one, which notifications have to clear too. + float extra_bars_width() const { return m_enabled && m_bar_object_ids.size() > 1 ? float(m_bar_object_ids.size() - 1) * THICKNESS_BAR_WIDTH : 0.0f; } float object_max_z() const { return m_object_max_z; } @@ -351,9 +408,36 @@ class GLCanvas3D private: bool is_initialized() const; void generate_layer_height_texture(); + // Orca: the layer heights of another selected object, read again when they may have changed. + ObjectTexture& other_object(int object_id); + // Orca: its texture, generated and sent to the GPU if needed, and bound. + const LayersTexture& bind_object_texture(ObjectTexture& object); + // Orca: the texture of the object shown, sent to the GPU if needed, and bound. + void bind_shown_texture(); + // Orca: whether the object is drawn with the texture of the object shown. + bool shares_shown_layers(ObjectTexture& object) const; + // Orca: whether an object with these slicing parameters takes the profile of the object shown when + // they share one. It has to start its layers where that profile does. + bool follows_shown_object(const SlicingParameters& slicing_parameters) const; + static unsigned int create_texture(); + static void load_texture(const LayersTexture& texture, unsigned int texture_id); + void release_object_texture(ObjectTexture& object); + void reset_bar_models(size_t bars); + // Index into m_bar_object_ids of the bar of the object shown. + size_t active_bar() const; + bool bar_in_focus(const GLCanvas3D& canvas) const; + float bar_fraction(size_t bar) const { return bar < m_bar_fractions.size() ? m_bar_fractions[bar] : 1.0f; } + // Index of the bar under the given point, or -1. + static int bar_at(const GLCanvas3D& canvas, float x, float y); + // Draws the object with the texture that is bound. + void render_object_volumes(const GLVolumeCollection& volumes, GLShaderProgram& shader, int object_id, const LayersTexture& texture, double object_max_z, float z_cursor, float dimming); void render_active_object_annotations(const GLCanvas3D& canvas); void render_profile(const GLCanvas3D& canvas); void update_slicing_parameters(); + // Orca: the object shown, followed by the other selected ones. + std::vector edited_object_ids() const; + SlicingParameters slicing_parameters_of(const ModelObject& model_object) const; + void set_profiles(GLCanvas3D& canvas, const std::vector& object_ids, const std::vector>& profiles); static float thickness_bar_width(const GLCanvas3D& canvas); }; @@ -1096,6 +1180,8 @@ public: bool is_layers_editing_enabled() const { return m_layers_editing.is_enabled(); } bool is_layers_editing_allowed() const { return m_layers_editing.is_allowed(); } + // Orca: the selected objects the variable layer height tool edits, tallest first. The tallest is the one it shows. + std::vector get_layers_editing_object_idxs() const; void reset_layer_height_profile(); void adaptive_layer_height_profile(float quality_factor); @@ -1484,6 +1570,9 @@ public: void apply_retina_scale(Vec2d &screen_coordinate) const; void _perform_layer_editing_action(wxMouseEvent* evt = nullptr); + // Orca: hands the variable layer height tool the selected objects and the one to show. While + // rendering, it also frees the textures of the objects no longer selected. + void _update_layers_editing_objects(bool rendering); // Convert the screen space coordinate to an object space coordinate. // If the Z screen space coordinate is not provided, a depth buffer value is substituted. @@ -1690,7 +1779,7 @@ private: bool _deactivate_layersediting_menu(); // BBS FIXME - float get_overlay_window_width() { return 0; /*LayersEditing::get_overlay_window_width();*/ } + float get_overlay_window_width() { return m_layers_editing.extra_bars_width(); /*LayersEditing::get_overlay_window_width();*/ } }; const ModelVolume *get_model_volume(const GLVolume &v, const Model &model); diff --git a/src/slic3r/GUI/Plater.cpp b/src/slic3r/GUI/Plater.cpp index 30fdb056c4..595736406c 100644 --- a/src/slic3r/GUI/Plater.cpp +++ b/src/slic3r/GUI/Plater.cpp @@ -15466,8 +15466,8 @@ bool Plater::priv::layers_height_allowed() const if (printer_technology != ptFFF) return false; - int obj_idx = get_selected_object_idx(); - return 0 <= obj_idx && obj_idx < (int)model.objects.size() && model.objects[obj_idx]->max_z() > SINKING_Z_THRESHOLD && view3D->is_layers_editing_allowed(); + // Orca: one object or several. + return !view3D->get_canvas3d()->get_layers_editing_object_idxs().empty() && view3D->is_layers_editing_allowed(); } bool Plater::priv::can_layers_editing() const diff --git a/tests/fff_print/test_wipe_tower.cpp b/tests/fff_print/test_wipe_tower.cpp index 03f44e851f..5ae4bcac86 100644 --- a/tests/fff_print/test_wipe_tower.cpp +++ b/tests/fff_print/test_wipe_tower.cpp @@ -9,6 +9,7 @@ #include #include #include "libslic3r/Model.hpp" +#include "libslic3r/Layer.hpp" #include "libslic3r/Print.hpp" #include #include @@ -32,6 +33,7 @@ #include "libslic3r/LocalesUtils.hpp" #include "libslic3r/ModelArrange.hpp" #include "libslic3r/PrintConfig.hpp" +#include "libslic3r/Slicing.hpp" #include "libslic3r/Utils.hpp" #include "test_helpers.hpp" @@ -449,6 +451,226 @@ TEST_CASE("The tower is sized for the thinnest layer any object on the plate is CHECK_THAT(print.wipe_tower_data(2).depth, Catch::Matchers::WithinAbs(20., 1e-4)); } +// A 20 mm and a 10 mm tall box sharing one variable layer height profile: 0.2 mm layers up to +// 5 mm, thinning to 0.1 mm at 10 mm and staying there. `fit` says whether the lower box gets the +// profile cut to its own height, or the tall box's profile as it is. Each box prints with its own +// filament, which is what makes the tower real. +static std::string validate_two_heights_with_variable_layers(bool fit, bool precise_z_height = false, + std::vector *warnings = nullptr) +{ + const DynamicPrintConfig config = multifilament_config(2, { + { "enable_prime_tower", "1" }, + { "wipe_tower_x", "50" }, // inside the 200x200 test bed + { "wipe_tower_y", "50" }, // (the default y, 220, is not) + { "layer_change_gcode", "G92 E0\n" }, // validate() wants the relative-E reset + { "layer_height", "0.2" }, + { "initial_layer_print_height", "0.2" }, + { "precise_z_height", precise_z_height ? "1" : "0" }, + { "raft_layers", "0" } }); + const std::vector> overrides{ { { "extruder", "1" } }, { { "extruder", "2" } } }; + const std::vector profile = { 0., 0.2, 5., 0.2, 10., 0.1, 20., 0.1 }; + + Print print; + Model model; + init_print(std::vector{ make_cube(20, 20, 20), make_cube(20, 20, 10) }, print, model, config, &overrides); + model.objects[0]->layer_height_profile.set(profile); + model.objects[1]->layer_height_profile.set(fit ? layer_height_profile_fit_to_height(profile, 10.) : profile); + print.apply(model, config); + REQUIRE(print.has_wipe_tower()); + // Precise Z height would fit the last layers of each box to its own height, so it is left out when it is on. + REQUIRE(print.precise_z_height_overridden() == precise_z_height); + // Leaving it out slices the boxes again, which must not leave them without slicing parameters. + for (const PrintObject *object : print.objects()) + REQUIRE(object->slicing_parameters().valid); + return print.validate(warnings).string; +} + +TEST_CASE("Objects of different heights keep the prime tower when they share a variable layer height profile", "[WipeTower]") +{ + CHECK_THAT(validate_two_heights_with_variable_layers(true), !Catch::Matchers::ContainsSubstring("layer height")); +} + +TEST_CASE("Precise Z height is left out when objects of different heights share their layers under the prime tower", "[WipeTower]") +{ + CHECK_THAT(validate_two_heights_with_variable_layers(true, true), !Catch::Matchers::ContainsSubstring("layer height")); +} + +TEST_CASE("Leaving precise Z height out is reported only when it is on", "[WipeTower]") +{ + const auto reported = [](bool precise_z_height) { + std::vector warnings; + validate_two_heights_with_variable_layers(true, precise_z_height, &warnings); + return std::any_of(warnings.begin(), warnings.end(), [](const StringObjectException &warning) { + return warning.string.find("Precise Z height is not applied") != std::string::npos; + }); + }; + CHECK(reported(true)); + CHECK_FALSE(reported(false)); +} + +TEST_CASE("Precise Z height applies again once the prime tower is turned off", "[WipeTower]") +{ + DynamicPrintConfig config = multifilament_config(2, { + { "enable_prime_tower", "1" }, + { "wipe_tower_x", "50" }, + { "wipe_tower_y", "50" }, + { "layer_change_gcode", "G92 E0\n" }, + { "layer_height", "0.2" }, + { "initial_layer_print_height", "0.2" }, + { "precise_z_height", "1" }, + { "raft_layers", "0" } }); + const std::vector> overrides{ { { "extruder", "1" } }, { { "extruder", "2" } } }; + const std::vector profile = { 0., 0.2, 5., 0.2, 10., 0.1, 20., 0.1 }; + + Print print; + Model model; + init_print(std::vector{ make_cube(20, 20, 20), make_cube(20, 20, 10.05) }, print, model, config, &overrides); + model.objects[0]->layer_height_profile.set(profile); + model.objects[1]->layer_height_profile.set(layer_height_profile_fit_to_height(profile, 10.05)); + print.apply(model, config); + REQUIRE(print.precise_z_height_overridden()); + REQUIRE(print.objects().size() == 2); + CHECK_FALSE(print.get_object(1)->precise_z_height()); + + config.set_deserialize_strict({ { "enable_prime_tower", "0" } }); + print.apply(model, config); + REQUIRE_FALSE(print.has_wipe_tower()); + CHECK_FALSE(print.precise_z_height_overridden()); + REQUIRE(print.objects().size() == 2); + PrintObject &lower = *print.get_object(1); + CHECK(lower.precise_z_height()); + REQUIRE(lower.slicing_parameters().valid); + lower.slice(); + REQUIRE(lower.layer_count() > 50); + CHECK_THAT(lower.get_layer(int(lower.layer_count()) - 1)->print_z, Catch::Matchers::WithinAbs(10.05, 1e-4)); +} + +TEST_CASE("A variable layer height profile that does not end at the object's top is rejected with the prime tower", "[WipeTower]") +{ + // The profile is dropped for the lower box, which is then sliced at a constant 0.2 mm. + CHECK_THAT(validate_two_heights_with_variable_layers(false), Catch::Matchers::ContainsSubstring("same variable layer height")); +} + +// Two boxes of different heights, both with a height range modifier over the same 2 to 5 mm. +// `range_layer_height` is the layer height the modifier asks for on the lower box; the tall one keeps +// the 0.2 mm of the print, so 0.2 leaves every layer where it was. +static std::string validate_two_heights_with_height_ranges(double range_layer_height) +{ + const DynamicPrintConfig config = multifilament_config(2, { + { "enable_prime_tower", "1" }, + { "wipe_tower_x", "50" }, + { "wipe_tower_y", "50" }, + { "layer_change_gcode", "G92 E0\n" }, + { "layer_height", "0.2" }, + { "initial_layer_print_height", "0.2" }, + { "raft_layers", "0" } }); + const std::vector> overrides{ { { "extruder", "1" } }, { { "extruder", "2" } } }; + + Print print; + Model model; + init_print(std::vector{ make_cube(20, 20, 20), make_cube(20, 20, 10) }, print, model, config, &overrides); + for (size_t idx = 0; idx < 2; ++idx) { + DynamicPrintConfig range_config; + // Every layer range carries a layer height, also one that only changes another setting. + range_config.set_key_value("layer_height", new ConfigOptionFloat(idx == 1 ? range_layer_height : 0.2)); + range_config.set_key_value("wall_loops", new ConfigOptionInt(3)); + model.objects[idx]->layer_config_ranges[{ 2., 5. }].assign_config(std::move(range_config)); + } + print.apply(model, config); + REQUIRE(print.has_wipe_tower()); + return print.validate().string; +} + +TEST_CASE("Height range modifiers that leave the layers alone keep the prime tower on objects of different heights", "[WipeTower]") +{ + CHECK_THAT(validate_two_heights_with_height_ranges(0.2), !Catch::Matchers::ContainsSubstring("layer height")); +} + +TEST_CASE("Height range modifiers that put the objects on different layers are rejected with the prime tower", "[WipeTower]") +{ + CHECK_THAT(validate_two_heights_with_height_ranges(0.1), Catch::Matchers::ContainsSubstring("same variable layer height")); +} + +TEST_CASE("Objects of different heights sharing a profile are sliced on the same layers under the prime tower", "[WipeTower]") +{ + // What the prime tower needs is that the objects are sliced at the same Z, which this checks on the + // sliced layers rather than on validate() alone. The lower box is 10.05 mm tall, between two layers + // of the shared profile: with precise Z height on, its last layers would be fitted to end at + // 10.05 mm and leave the tall box's, if only by a micrometre or so. The print leaves precise Z height + // out, so they must not. + const DynamicPrintConfig config = multifilament_config(2, { + { "enable_prime_tower", "1" }, + { "wipe_tower_x", "50" }, + { "wipe_tower_y", "50" }, + { "layer_change_gcode", "G92 E0\n" }, + { "layer_height", "0.2" }, + { "initial_layer_print_height", "0.2" }, + { "precise_z_height", "1" }, + { "raft_layers", "0" } }); + const std::vector> overrides{ { { "extruder", "1" } }, { { "extruder", "2" } } }; + const std::vector profile = { 0., 0.2, 5., 0.2, 10., 0.1, 20., 0.1 }; + + Print print; + Model model; + init_print(std::vector{ make_cube(20, 20, 20), make_cube(20, 20, 10.05) }, print, model, config, &overrides); + model.objects[0]->layer_height_profile.set(profile); + model.objects[1]->layer_height_profile.set(layer_height_profile_fit_to_height(profile, 10.05)); + print.apply(model, config); + REQUIRE(print.has_wipe_tower()); + REQUIRE(print.precise_z_height_overridden()); + REQUIRE(print.validate().string.empty()); + REQUIRE(print.objects().size() == 2); + + // Slicing the objects is where precise Z height would act, so their layers are compared right + // after it, before the tower is generated from them. + PrintObject &tall = *print.get_object(0); + PrintObject &lower = *print.get_object(1); + tall.slice(); + lower.slice(); + REQUIRE(lower.layer_count() > 50); + REQUIRE(lower.layer_count() < tall.layer_count()); + for (size_t idx = 0; idx < lower.layer_count(); ++idx) { + INFO("layer " << idx); + CHECK_THAT(lower.get_layer(int(idx))->print_z, Catch::Matchers::WithinAbs(tall.get_layer(int(idx))->print_z, 1e-6)); + } + + // And the tower is generated from those layers. + print.process(); + CHECK(print.is_step_done(psWipeTower)); +} + +TEST_CASE("Precise Z height still fits objects of different heights when there is no prime tower", "[WipeTower]") +{ + // The same plate as above without the tower: nothing asks the objects to share their layers, so + // precise Z height stays on and fits the last layers of the 10.05 mm box to end at its top, where + // the shared profile alone would stop at about 10.0515 mm. + const DynamicPrintConfig config = multifilament_config(2, { + { "enable_prime_tower", "0" }, + { "layer_change_gcode", "G92 E0\n" }, + { "layer_height", "0.2" }, + { "initial_layer_print_height", "0.2" }, + { "precise_z_height", "1" }, + { "raft_layers", "0" } }); + const std::vector> overrides{ { { "extruder", "1" } }, { { "extruder", "2" } } }; + const std::vector profile = { 0., 0.2, 5., 0.2, 10., 0.1, 20., 0.1 }; + + Print print; + Model model; + init_print(std::vector{ make_cube(20, 20, 20), make_cube(20, 20, 10.05) }, print, model, config, &overrides); + model.objects[0]->layer_height_profile.set(profile); + model.objects[1]->layer_height_profile.set(layer_height_profile_fit_to_height(profile, 10.05)); + print.apply(model, config); + REQUIRE_FALSE(print.has_wipe_tower()); + REQUIRE_FALSE(print.precise_z_height_overridden()); + REQUIRE(print.objects().size() == 2); + + PrintObject &lower = *print.get_object(1); + CHECK(lower.precise_z_height()); + lower.slice(); + REQUIRE(lower.layer_count() > 50); + CHECK_THAT(lower.get_layer(int(lower.layer_count()) - 1)->print_z, Catch::Matchers::WithinAbs(10.05, 1e-4)); +} + TEST_CASE("Validation is given the tower's effective width, not the configured one", "[WipeTower]") { // A rib wall squares the tower, so its width is its depth. Validation reads this rather diff --git a/tests/libslic3r/CMakeLists.txt b/tests/libslic3r/CMakeLists.txt index 6c878026e8..809f74f212 100644 --- a/tests/libslic3r/CMakeLists.txt +++ b/tests/libslic3r/CMakeLists.txt @@ -83,6 +83,7 @@ add_executable(${_TEST_NAME}_tests test_wipe_tower_estimate.cpp test_wipe_tower.cpp test_wipe_path.cpp + test_slicing.cpp test_optimizers.cpp test_ordering_strategies.cpp test_parameter_utils.cpp diff --git a/tests/libslic3r/test_slicing.cpp b/tests/libslic3r/test_slicing.cpp new file mode 100644 index 0000000000..afa7a3988b --- /dev/null +++ b/tests/libslic3r/test_slicing.cpp @@ -0,0 +1,129 @@ +#include +#include +#include +#include + +#include +#include + +#include "libslic3r/Slicing.hpp" +#include "libslic3r/libslic3r.h" + +using namespace Slic3r; + +// Profiles are flat lists of (z, layer height) pairs. +static void check_profile(const std::vector &profile, const std::vector &expected) +{ + REQUIRE(profile.size() == expected.size()); + for (size_t i = 0; i < expected.size(); ++i) { + INFO("entry " << i); + CHECK_THAT(profile[i], Catch::Matchers::WithinAbs(expected[i], 1e-9)); + } +} + +TEST_CASE("A layer height profile fitted to a lower object is cut at its top", "[Slicing]") +{ + // 0.2 mm up to 5 mm, thinning to 0.1 mm at 10 mm: halfway through the ramp, 7.5 mm, is 0.15 mm. + const std::vector profile = { 0., 0.2, 5., 0.2, 10., 0.1, 20., 0.1 }; + check_profile(layer_height_profile_fit_to_height(profile, 7.5), { 0., 0.2, 5., 0.2, 7.5, 0.15 }); +} + +TEST_CASE("A layer height profile fitted just above one of its entries does not run past it", "[Slicing]") +{ + // The entry at 9.99999 mm lies within EPSILON under the top, so the cut falls between it and the one + // below and must take its layer height, not run on past it to below 0.1 mm. + const std::vector profile = { 0., 0.2, 9.9, 0.2, 9.99999, 0.1, 20., 0.1 }; + const std::vector fitted = layer_height_profile_fit_to_height(profile, 10.); + REQUIRE(fitted.size() == 6); + CHECK_THAT(fitted[4], Catch::Matchers::WithinAbs(10., 1e-12)); + CHECK(fitted[5] >= 0.1); + CHECK(fitted[5] <= 0.2); +} + +TEST_CASE("A layer height profile fitted to a taller object carries its last layer height up", "[Slicing]") +{ + const std::vector profile = { 0., 0.2, 5., 0.2, 10., 0.1 }; + check_profile(layer_height_profile_fit_to_height(profile, 30.), { 0., 0.2, 5., 0.2, 10., 0.1, 30., 0.1 }); +} + +TEST_CASE("A layer height profile fitted to its own height is unchanged", "[Slicing]") +{ + const std::vector profile = { 0., 0.2, 5., 0.2, 10., 0.1 }; + check_profile(layer_height_profile_fit_to_height(profile, 10.), profile); +} + +TEST_CASE("Merged layer height profiles take the finest layer height up to the top of each object", "[Slicing]") +{ + // A 20 mm object at a constant 0.2 mm, and a 10 mm one thinning to 0.1 mm at 5 mm. The 0.3 mm + // entry closing the lower profile is not a layer height the object asks for. + const std::vector tall = { 0., 0.2, 10., 0.2, 20., 0.2 }; + const std::vector lower = { 0., 0.2, 5., 0.1, 10., 0.3 }; + const std::vector merged = layer_height_profile_merge_finest({ tall, lower }); + + REQUIRE(merged.size() >= 4); + REQUIRE(merged.size() % 2 == 0); + CHECK_THAT(merged[0], Catch::Matchers::WithinAbs(0., 1e-9)); + CHECK_THAT(merged[1], Catch::Matchers::WithinAbs(0.2, 1e-9)); + CHECK_THAT(merged[merged.size() - 2], Catch::Matchers::WithinAbs(20., 1e-9)); + for (size_t i = 2; i + 2 < merged.size(); i += 2) { + INFO("entry at z = " << merged[i]); + // One entry per layer: each starts where the layer before it ended. + if (i + 4 < merged.size()) + CHECK_THAT(merged[i + 2], Catch::Matchers::WithinAbs(merged[i] + merged[i + 1], 1e-9)); + if (merged[i] < 5.) + // Thinning with the lower object: 0.2 mm at the bed, 0.1 mm at 5 mm. + CHECK_THAT(merged[i + 1], Catch::Matchers::WithinAbs(0.2 - 0.02 * merged[i], 1e-9)); + else if (merged[i] < 10.) + CHECK_THAT(merged[i + 1], Catch::Matchers::WithinAbs(0.1, 1e-9)); + else { + // Above the lower object the layers grow back to the 0.2 mm of the tall one, by no + // more than the 0.04 mm the adaptive profile allows from one layer to the next. + CHECK(merged[i + 1] <= 0.2 + 1e-9); + CHECK(merged[i + 1] - merged[i - 1] <= 0.04 + 1e-9); + } + if (merged[i] > 11.) + CHECK_THAT(merged[i + 1], Catch::Matchers::WithinAbs(0.2, 1e-9)); + } +} + +TEST_CASE("The layer height texture is filled up to the top of an object whose last layer ends under it", "[Slicing]") +{ + // A 10 mm object with 0.15 mm layers: the last one ends at 9.9 mm, as generate_object_layers() leaves it + // when one more layer would end too far above the top. The top face is drawn with the cells above 9.9 mm. + SlicingParameters params; + params.object_print_z_min = 0.; + params.object_print_z_max = 10.; + params.layer_height = 0.2; + params.min_layer_height = 0.07; + params.max_layer_height = 0.28; + std::vector layers; + for (int i = 0; i < 66; ++i) { + layers.push_back(0.15 * i); + layers.push_back(0.15 * (i + 1)); + } + REQUIRE_THAT(layers.back(), Catch::Matchers::WithinAbs(9.9, 1e-9)); + + // The buffer starts out black and transparent, as the texture of an object is made the first time. + const int rows = 256; + const int cols = 256; + std::vector data(size_t(rows) * size_t(cols) * 5, 0); + const int ncells = generate_layer_height_texture(params, layers, data.data(), rows, cols, true); + REQUIRE(ncells > 0); + // Each cell, up to the last, is written: opaque. + for (int cell = 0; cell < ncells; ++cell) { + const int row = cell / (cols - 1); + const int col = cell - row * (cols - 1); + INFO("cell " << cell << " of " << ncells); + CHECK(int(data[(size_t(row) * cols + col) * 4 + 3]) == 255); + } + // And so in the second level of detail, half as many cells in a texture half as wide. + const unsigned char *data1 = data.data() + size_t(rows) * cols * 4; + const int cols1 = cols / 2; + const int ncells1 = ncells / 2; + for (int cell = 0; cell < ncells1; ++cell) { + const int row = cell / (cols1 - 1); + const int col = cell - row * (cols1 - 1); + INFO("second level cell " << cell << " of " << ncells1); + CHECK(int(data1[(size_t(row) * cols1 + col) * 4 + 3]) == 255); + } +}