diff --git a/docs/HLSD/painted-modifiers.md b/docs/HLSD/painted-modifiers.md new file mode 100644 index 0000000000..af0cd3daa9 --- /dev/null +++ b/docs/HLSD/painted-modifiers.md @@ -0,0 +1,159 @@ +# Painted Modifiers — High Level Design + +## Purpose and scope + +A painted modifier overrides print settings like a modifier volume does, but +its shape is painted on the surface of a part instead of being a mesh of its +own. The user paints the area, and the modifier covers the part of the object +behind the paint, up to a chosen depth. + +Painted modifiers are listed in the object list together with the modifier +volumes and share their priority rule: where several modifiers overlap and set +the same option, the one lower in the list wins. This holds between painted +modifiers, between painted and mesh modifiers, and in any mix of the two. + +Color painting and fuzzy-skin painting are not part of this order. They are +applied after all modifiers, as before. + +## Data model + +A painted modifier is a `ModelVolume` of type +`ModelVolumeType::PAINTED_MODIFIER` in `ModelObject::volumes`, so it takes part +in everything the volume list already provides: its position in the list, its +name and settings (`ModelVolume::config`), undo/redo and change detection. + +| Member | Meaning | +| --- | --- | +| `painted_modifier_facets` | The painted facets, `ENFORCER` state only. | +| `painted_modifier_depth` | How far the paint reaches into the part, in mm. | +| `painted_modifier_host` | `ObjectID` of the model part it is painted on. | + +The volume shares the mesh (`std::shared_ptr`) and the +transformation of its host part, so the painted facets index the host's +triangles and the volume costs no geometry memory. One painted modifier is +painted on one part; painting several parts takes one painted modifier per part. + +The facets live on the painted modifier rather than on its host because one +facet holds a single paint state: overlapping painted modifiers need a mask +each. + +### Host link + +`ModelObject::painted_modifier_host()` resolves the link by `ObjectID`. The ID +survives copies made with `assign_copy` and undo/redo; +`ModelObject::assign_new_unique_ids_recursive()` remaps it when an object is +cloned with new IDs, and `convert_units()` remaps it to the converted volumes. +Mesh edits such as simplify, repair or smoothing give a part a new ID through +`ModelVolume::set_new_unique_id()`, which moves the links of its painted +modifiers along. Mesh identity is not used as the link, since pasting a part +inside its object shares the mesh between two parts. + +`ModelObject::sync_painted_modifiers()` makes each painted modifier follow its +host: + +- it copies the host's transformation, because a part moved alone in the scene + moves without its painted modifiers, which have no scene geometry; +- when the host's mesh was replaced, it carries the paint over with + `TriangleSelector::remap_painting()` and shares the new mesh. + +Operations that replace the meshes of all volumes keep the paint of painted +modifiers through `ModelVolume::save_painting()` and `restore_painting()`, like +any other paint. Repair skips painted modifiers, which follow their repaired host. + +The GUI calls it before every `Print::apply()`, before saving a project and when +the paint tool opens. A painted modifier whose host was deleted keeps its own +mesh and transformation; the object list deletes the painted modifiers of a part +together with it. + +`ModelObject::sort_volumes()` sorts painted modifiers as modifiers, so the +stable sort keeps the user's order within the modifier group. + +## Slicing + +### Shape + +`PrintObject::slice_volumes()` slices a painted modifier like any other volume, +which yields its host's cross-section on every layer, then replaces these slices +with `painted_modifier_segmentation()` (`MultiMaterialSegmentation.cpp`): + +1. **Walls.** The painted facets are projected onto the contours of the + cross-section and every layer is split by the paint state of the nearest + contour, with the same Voronoi segmentation as color painting + (`segment_layers_by_painted_contours()`). With a depth above 0 the painted + part is cut to a band of that width along the contour. +2. **Top and bottom.** Painted facets facing up or down are projected down or up + through the cross-sections, as long as they stay inside the part and within + the depth. A depth of 0 reaches through as many layers as the top and bottom + shells; the color penetration layer options belong to color painting and do + not apply. + +A depth of 0 therefore means: across the whole part up to the nearest unpainted +surface, and as deep as the shells below and above painted faces. + +The shape is computed from the host's own slices before region assignment, +because it has to enter the modifier chain. Color painting, in contrast, +segments the merged regions after assignment. + +### Precedence + +`generate_print_object_regions()` walks the volume list in order and treats a +painted modifier exactly like a mesh modifier (`ModelVolume::is_region_modifier()`): +it becomes a child region of every earlier part or modifier region whose bounding +box it overlaps, with that region's settings plus its own. `slices_to_regions()` +then moves the overlap of its slices out of each parent region into the child. +A later modifier is applied on top of the result of the earlier ones, so it wins +on shared options and inherits the others. + +### Change detection + +`Print::apply()` reslices an object when its painted modifiers are added, +removed, reordered or moved (`model_volume_list_changed()`), or when their paint +or depth change (`model_painted_modifier_data_changed()`). Setting changes go +through `verify_update_print_object_regions()` like those of mesh modifiers. + +## Project files + +`store_bbs_3mf()` writes a painted modifier so that older versions load it as a +modifier without effect, never as a printable part: + +- the `` has `subtype="modifier_part"`; +- `painted_modifier_depth` marks it as painted and `painted_modifier_host` holds + the index of the host in the object's volumes; +- its settings are prefixed with `painted_modifier_config:`, which older readers + drop; +- the paint is the triangle attribute `paint_modifier` of its own copy of the + host mesh. + +The reader restores the type, depth and settings, links the host by index and +calls `sync_painted_modifiers()`, which shares the host's mesh again. The +PrusaSlicer-format writer `store_3mf()` stores no paint for them and writes them +as modifiers with prefixed settings only. + +## Application + +- **Object list.** Painted modifiers are added from the object's "Add Painted + Modifier" menu item or a part's context menu, appear among the modifiers with + their own icon, and can be dragged among mesh modifiers. Their type cannot be + changed, and their context menu offers rename, delete, process settings and + filament. +- **Scene.** They have no `GLVolume`; `Selection` counts only the volumes shown + in the scene to decide whether a whole instance is selected. Selecting a + painted modifier in the list selects its instance, shows its settings and opens + its paint tool. +- **Paint tool.** `GLGizmoPaintedModifier` sits in the canvas toolbar with the + other paint tools and paints one painted modifier at a time: the one selected + in the list, or else the object's last one. Only its host can be painted; a hit + on another part counts as a miss, so other parts still occlude + (`GLGizmoPainterBase::is_mesh_paintable()`). With "New painted modifier" + chosen, or on an object without any, the first stroke creates one on the part + it paints. The tool also edits the depth. + +## Known limitations + +- The paint tool shows the paint of the edited painted modifier only. +- Cutting a host part or reloading it from disk replaces it with new volumes, + so its painted modifiers lose their host; they keep their shape but no longer + follow the part. +- Splitting a host part into parts keeps its painted modifiers on the first + piece; paint on the other pieces is dropped. +- The paint is not shown outside the paint tool. diff --git a/localization/i18n/list.txt b/localization/i18n/list.txt index 847b1f7937..b5c2f0e866 100644 --- a/localization/i18n/list.txt +++ b/localization/i18n/list.txt @@ -63,6 +63,8 @@ src/slic3r/GUI/Gizmos/GLGizmoMmuSegmentation.cpp src/slic3r/GUI/Gizmos/GLGizmoMmuSegmentation.hpp src/slic3r/GUI/Gizmos/GLGizmoFuzzySkin.cpp src/slic3r/GUI/Gizmos/GLGizmoFuzzySkin.hpp +src/slic3r/GUI/Gizmos/GLGizmoPaintedModifier.cpp +src/slic3r/GUI/Gizmos/GLGizmoPaintedModifier.hpp src/slic3r/GUI/Gizmos/GLGizmoMove.cpp src/slic3r/GUI/Gizmos/GLGizmoRotate.cpp src/slic3r/GUI/Gizmos/GLGizmoScale.cpp diff --git a/resources/images/menu_add_painted_modifier.svg b/resources/images/menu_add_painted_modifier.svg new file mode 100644 index 0000000000..cc4105616d --- /dev/null +++ b/resources/images/menu_add_painted_modifier.svg @@ -0,0 +1 @@ + diff --git a/resources/images/toolbar_painted_modifier.svg b/resources/images/toolbar_painted_modifier.svg new file mode 100644 index 0000000000..d3dd025054 --- /dev/null +++ b/resources/images/toolbar_painted_modifier.svg @@ -0,0 +1 @@ + diff --git a/resources/images/toolbar_painted_modifier_dark.svg b/resources/images/toolbar_painted_modifier_dark.svg new file mode 100644 index 0000000000..a388d24ad3 --- /dev/null +++ b/resources/images/toolbar_painted_modifier_dark.svg @@ -0,0 +1 @@ + diff --git a/src/OrcaSlicer.cpp b/src/OrcaSlicer.cpp index 672906e06a..e6b110f70b 100644 --- a/src/OrcaSlicer.cpp +++ b/src/OrcaSlicer.cpp @@ -4099,7 +4099,7 @@ int CLI::run(int argc, char **argv) object->config.assign_config(std::move(object_config)); } for (ModelVolume* v : object->volumes) { - if (v->is_model_part() || v->is_modifier()) { + if (v->is_model_part() || v->is_region_modifier()) { DynamicPrintConfig volume_config = v->config.get(); if (!volume_config.empty()) { /* if (current_extruder_count < new_extruder_count) diff --git a/src/libslic3r/Format/3mf.cpp b/src/libslic3r/Format/3mf.cpp index 0a277a4d15..723746ffa2 100644 --- a/src/libslic3r/Format/3mf.cpp +++ b/src/libslic3r/Format/3mf.cpp @@ -157,6 +157,8 @@ static constexpr const char* VOLUME_TYPE_KEY = "volume_type"; static constexpr const char* PRECISE_SEAM_TYPE_KEY = "precise_seam_type"; // Preserve dormant settings without turning an older reader's modifier into an active override. static constexpr char PRECISE_SEAM_CONFIG_PREFIX[] = "precise_seam_config:"; +// This format does not store paint for painted modifiers, so they are written as modifiers whose settings readers drop. +static constexpr char PAINTED_MODIFIER_CONFIG_PREFIX[] = "painted_modifier_config:"; static constexpr const char* MATRIX_KEY = "matrix"; static constexpr const char* SOURCE_FILE_KEY = "source_file"; static constexpr const char* SOURCE_OBJECT_ID_KEY = "source_object_id"; @@ -3196,12 +3198,12 @@ ModelVolumeType type_from_string(const std::string &s) // stores volume's modifier field (legacy, to support old slicers) // Readers with only the legacy flag still see helper geometry as a modifier. - if (volume->is_modifier() || volume->is_precise_seam()) + if (volume->is_modifier() || volume->is_precise_seam() || volume->is_painted_modifier()) stream << " <" << METADATA_TAG << " " << TYPE_ATTR << "=\"" << VOLUME_TYPE << "\" " << KEY_ATTR << "=\"" << MODIFIER_KEY << "\" " << VALUE_ATTR << "=\"1\"/>\n"; // This Prusa-format reader uses ParameterModifier, not Bambu's modifier_part. // The base type overrides the legacy flag, so it must also be backward-compatible. // Use the same spelling for ordinary modifiers, including a downgraded seam helper. - const bool store_as_modifier = volume->is_modifier() || volume->is_precise_seam(); + const bool store_as_modifier = volume->is_modifier() || volume->is_precise_seam() || volume->is_painted_modifier(); stream << " <" << METADATA_TAG << " " << TYPE_ATTR << "=\"" << VOLUME_TYPE << "\" " << KEY_ATTR << "=\"" << VOLUME_TYPE_KEY << "\" " << VALUE_ATTR << "=\"" << (store_as_modifier ? "ParameterModifier" : ModelVolume::type_to_string(volume->type())) << "\"/>\n"; if (volume->is_precise_seam()) @@ -3242,8 +3244,8 @@ ModelVolumeType type_from_string(const std::string &s) // stores volume's config data for (const std::string& key : volume->config.keys()) { // Seam settings are inactive but must survive changing the helper back into a part/modifier. - const bool dormant = volume->is_precise_seam(); - const std::string stored_key = dormant ? PRECISE_SEAM_CONFIG_PREFIX + key : key; + const std::string stored_key = volume->is_precise_seam() ? PRECISE_SEAM_CONFIG_PREFIX + key : + volume->is_painted_modifier() ? PAINTED_MODIFIER_CONFIG_PREFIX + key : key; const std::string value = volume->config.opt_serialize(key); // Config serialization is C-style, not XML: escape active settings too, including tabs. stream << " <" << METADATA_TAG << " " << TYPE_ATTR << "=\"" << VOLUME_TYPE << "\" " << KEY_ATTR << "=\"" << stored_key << "\" " << VALUE_ATTR << "=\"" << xml_escape_double_quotes_attribute_value(value) << "\"/>\n"; diff --git a/src/libslic3r/Format/bbs_3mf.cpp b/src/libslic3r/Format/bbs_3mf.cpp index c845a2f99b..4d56e7090f 100644 --- a/src/libslic3r/Format/bbs_3mf.cpp +++ b/src/libslic3r/Format/bbs_3mf.cpp @@ -364,6 +364,7 @@ static constexpr const char* TEXTURE_DISPLACEMENT_ATTRS[Slic3r::TEXTURE_DISPLACE "paint_texture_4", "paint_texture_5", "paint_texture_6", "paint_texture_7" }; static constexpr const char* TEXTURE_DISPLACEMENT_KEY = "texture_displacement"; static constexpr const char* TEXTURE_DISPLACEMENT_DIR = "Metadata/texture_displacement/"; +static constexpr const char* PAINTED_MODIFIER_ATTR = "paint_modifier"; // BBS static constexpr const char* FACE_PROPERTY_ATTR = "face_property"; @@ -429,6 +430,10 @@ static constexpr const char* PART_TYPE_KEY = "part_type"; static constexpr const char* PRECISE_SEAM_TYPE_KEY = "precise_seam_type"; // Preserve dormant settings without turning an older reader's modifier into an active override. static constexpr char PRECISE_SEAM_CONFIG_PREFIX[] = "precise_seam_config:"; +// Painted modifiers are stored as modifiers with prefixed settings, so older readers load them as inert modifiers. +static constexpr const char* PAINTED_MODIFIER_DEPTH_KEY = "painted_modifier_depth"; +static constexpr const char* PAINTED_MODIFIER_HOST_KEY = "painted_modifier_host"; +static constexpr char PAINTED_MODIFIER_CONFIG_PREFIX[] = "painted_modifier_config:"; static constexpr const char* MATRIX_KEY = "matrix"; static constexpr const char* SOURCE_FILE_KEY = "source_file"; static constexpr const char* SOURCE_OBJECT_ID_KEY = "source_object_id"; @@ -860,6 +865,7 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result) // One per texture displacement layer slot, indexed like `triangles` but stored only as far as the // slot's last painted triangle: empty when the slot has no paint, which is nearly every file. std::vector texture_displacement[TEXTURE_DISPLACEMENT_MAX_LAYERS]; + std::vector painted_modifier; // BBS std::vector face_properties; @@ -882,6 +888,7 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result) fuzzy_skin.clear(); for (std::vector &slot : texture_displacement) slot.clear(); + painted_modifier.clear(); } }; @@ -4053,6 +4060,7 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result) mask.resize(m_curr_object->geometry.triangles.size()); mask.back() = paint; } + m_curr_object->geometry.painted_modifier.push_back(bbs_get_attribute_value_string(attributes, num_attributes, PAINTED_MODIFIER_ATTR)); // BBS m_curr_object->geometry.face_properties.push_back(bbs_get_attribute_value_string(attributes, num_attributes, FACE_PROPERTY_ATTR)); } @@ -5224,6 +5232,8 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result) //unsigned int geo_tri_count = (unsigned int)geometry.triangles.size(); unsigned int renamed_volumes_count = 0; + // Painted modifiers and the index of their host volume, resolved once all volumes exist. + std::vector> painted_modifier_hosts; for (unsigned int index = 0; index < sub_objects.size(); index++) { @@ -5385,6 +5395,7 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result) volume->seam_facets.reserve(triangles_count); volume->mmu_segmentation_facets.reserve(triangles_count); volume->fuzzy_skin_facets.reserve(triangles_count); + volume->painted_modifier_facets.reserve(triangles_count); for (size_t i=0; igeometry.custom_supports.size()); assert(i < sub_object->geometry.custom_seam.size()); @@ -5398,6 +5409,8 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result) volume->mmu_segmentation_facets.set_triangle_from_string(i, sub_object->geometry.mmu_segmentation[i]); if (!sub_object->geometry.fuzzy_skin[i].empty()) volume->fuzzy_skin_facets.set_triangle_from_string(i, sub_object->geometry.fuzzy_skin[i]); + if (!sub_object->geometry.painted_modifier[i].empty()) + volume->painted_modifier_facets.set_triangle_from_string(i, sub_object->geometry.painted_modifier[i]); } volume->supported_facets.shrink_to_fit(); volume->seam_facets.shrink_to_fit(); @@ -5417,6 +5430,8 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result) facets.shrink_to_fit(); facets.touch(); } + volume->painted_modifier_facets.shrink_to_fit(); + volume->painted_modifier_facets.touch(); } volume->set_type(volume_data->part_type); @@ -5428,6 +5443,8 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result) // Apply the seam mode after all base-type metadata, regardless of XML key order. ModelVolumeType precise_seam_type = ModelVolumeType::INVALID; + std::optional painted_modifier_depth; + int painted_modifier_host = -1; // apply the remaining volume's metadata for (const Metadata& metadata : volume_data->metadata) { if (metadata.key == NAME_KEY) @@ -5441,8 +5458,12 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result) volume->set_type(ModelVolume::type_from_string(metadata.value)); else if (metadata.key == PRECISE_SEAM_TYPE_KEY) precise_seam_type = ModelVolume::type_from_string(metadata.value); - else if (boost::starts_with(metadata.key, PRECISE_SEAM_CONFIG_PREFIX)) + else if (boost::starts_with(metadata.key, PRECISE_SEAM_CONFIG_PREFIX) || boost::starts_with(metadata.key, PAINTED_MODIFIER_CONFIG_PREFIX)) continue; // Restore dormant settings only after the final volume type is known. + else if (metadata.key == PAINTED_MODIFIER_DEPTH_KEY) + painted_modifier_depth = float(::atof(metadata.value.c_str())); + else if (metadata.key == PAINTED_MODIFIER_HOST_KEY) + painted_modifier_host = ::atoi(metadata.value.c_str()); else if (metadata.key == SOURCE_FILE_KEY) volume->source.input_file = metadata.value; else if (metadata.key == SOURCE_OBJECT_ID_KEY) @@ -5469,6 +5490,17 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result) // Ignore seam metadata on other base types; legacy inline seam types still load above. if (volume->is_modifier() && is_precise_seam(precise_seam_type)) volume->set_type(precise_seam_type); + else if (volume->is_modifier() && painted_modifier_depth) { + volume->set_type(ModelVolumeType::PAINTED_MODIFIER); + volume->painted_modifier_depth = std::max(0.f, *painted_modifier_depth); + painted_modifier_hosts.emplace_back(volume, painted_modifier_host); + for (const Metadata& metadata : volume_data->metadata) + if (boost::starts_with(metadata.key, PAINTED_MODIFIER_CONFIG_PREFIX)) { + const std::string key = metadata.key.substr(sizeof(PAINTED_MODIFIER_CONFIG_PREFIX) - 1); + if (!key.empty()) + volume->config.set_deserialize(key, metadata.value, config_substitutions); + } + } // Unknown seam modes must remain inert modifiers, even when dormant settings are present. if (volume->is_precise_seam()) { @@ -5492,6 +5524,11 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result) } } + for (auto [volume, host_idx] : painted_modifier_hosts) + if (host_idx >= 0 && host_idx < int(object.volumes.size()) && object.volumes[host_idx]->is_model_part()) + volume->painted_modifier_host = object.volumes[host_idx]->id(); + object.sync_painted_modifiers(); + return true; } /* @@ -5931,6 +5968,7 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result) mask.resize(current_object->geometry.triangles.size()); mask.back() = paint; } + current_object->geometry.painted_modifier.push_back(bbs_get_attribute_value_string(attributes, num_attributes, PAINTED_MODIFIER_ATTR)); // BBS current_object->geometry.face_properties.push_back(bbs_get_attribute_value_string(attributes, num_attributes, FACE_PROPERTY_ATTR)); } @@ -7388,7 +7426,8 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result) && (shared_volume->seam_facets.equals(volume->seam_facets)) && (shared_volume->mmu_segmentation_facets.equals(volume->mmu_segmentation_facets)) && (shared_volume->fuzzy_skin_facets.equals(volume->fuzzy_skin_facets)) - && same_texture_paint) + && same_texture_paint + && (shared_volume->painted_modifier_facets.equals(volume->painted_modifier_facets))) { auto data = iter->second.first; const_cast<_BBS_3MF_Exporter *>(this)->m_volume_paths.insert({volume, {data->sub_path, data->volumes_objectID.find(iter->second.second)->second}}); @@ -7818,6 +7857,15 @@ void PlateData::parse_filament_info(GCodeProcessorResult *result) output_buffer += "\""; } + std::string painted_modifier_data_string = volume->painted_modifier_facets.get_triangle_as_string(i); + if (!painted_modifier_data_string.empty()) { + output_buffer += " "; + output_buffer += PAINTED_MODIFIER_ATTR; + output_buffer += "=\""; + output_buffer += painted_modifier_data_string; + output_buffer += "\""; + } + // BBS if (i < its.properties.size()) { std::string prop_str = its.properties[i].to_string(); @@ -8351,11 +8399,20 @@ bool _BBS_3MF_Exporter::_add_model_config_file_to_archive(mz_zip_archive& archiv stream << ID_ATTR << "=\"" << volume_id << "\" "; // Older slicers must recognize the base type even when they ignore seam metadata. - const ModelVolumeType stored_type = volume->is_precise_seam() ? ModelVolumeType::PARAMETER_MODIFIER : volume->type(); + const ModelVolumeType stored_type = volume->is_precise_seam() || volume->is_painted_modifier() ? ModelVolumeType::PARAMETER_MODIFIER : volume->type(); stream << SUBTYPE_ATTR << "=\"" << ModelVolume::type_to_string(stored_type) << "\">\n"; if (volume->is_precise_seam()) stream << " <" << METADATA_TAG << " " << KEY_ATTR << "=\"" << PRECISE_SEAM_TYPE_KEY << "\" " << VALUE_ATTR << "=\"" << ModelVolume::type_to_string(volume->type()) << "\"/>\n"; + if (volume->is_painted_modifier()) { + stream << " <" << METADATA_TAG << " " << KEY_ATTR << "=\"" << PAINTED_MODIFIER_DEPTH_KEY << "\" " << VALUE_ATTR << "=\"" << + volume->painted_modifier_depth << "\"/>\n"; + const ModelVolumePtrs &obj_volumes = obj_metadata.second.object->volumes; + const ModelVolume *host = obj_metadata.second.object->painted_modifier_host(*volume); + if (auto host_it = std::find(obj_volumes.begin(), obj_volumes.end(), host); host_it != obj_volumes.end()) + stream << " <" << METADATA_TAG << " " << KEY_ATTR << "=\"" << PAINTED_MODIFIER_HOST_KEY << "\" " << VALUE_ATTR << "=\"" << + (host_it - obj_volumes.begin()) << "\"/>\n"; + } //stream << " <" << PART_TAG << " " << ID_ATTR << "=\"" << it->second << "\" " << SUBTYPE_ATTR << "=\"" << ModelVolume::type_to_string(volume->type()) << "\">\n"; // stores volume's name @@ -8406,8 +8463,8 @@ bool _BBS_3MF_Exporter::_add_model_config_file_to_archive(mz_zip_archive& archiv // stores volume's config data for (const std::string& key : volume->config.keys()) { // Seam settings are inactive but must survive changing the helper back into a part/modifier. - const bool dormant = volume->is_precise_seam(); - const std::string stored_key = dormant ? PRECISE_SEAM_CONFIG_PREFIX + key : key; + const std::string stored_key = volume->is_precise_seam() ? PRECISE_SEAM_CONFIG_PREFIX + key : + volume->is_painted_modifier() ? PAINTED_MODIFIER_CONFIG_PREFIX + key : key; const std::string value = volume->config.opt_serialize(key); // Config serialization is C-style, not XML: escape active settings too, including tabs. stream << " <" << METADATA_TAG << " "<< KEY_ATTR << "=\"" << stored_key << "\" " << VALUE_ATTR << "=\"" << xml_escape_double_quotes_attribute_value(value) << "\"/>\n"; diff --git a/src/libslic3r/GCode/PreciseSeam.cpp b/src/libslic3r/GCode/PreciseSeam.cpp index de62fe1cfd..7c053bde09 100644 --- a/src/libslic3r/GCode/PreciseSeam.cpp +++ b/src/libslic3r/GCode/PreciseSeam.cpp @@ -770,6 +770,7 @@ static EnforcedBlockedSeamPoint convert_weak_modifier_type(ModelVolumeType type) case ModelVolumeType::PRECISE_SEAM_CENTER: case ModelVolumeType::PRECISE_SEAM_LEFT: case ModelVolumeType::PRECISE_SEAM_RIGHT: + case ModelVolumeType::PAINTED_MODIFIER: break; } assert(false && "convert_weak_modifier_type called with non-weak type"); diff --git a/src/libslic3r/Model.cpp b/src/libslic3r/Model.cpp index 4d0577a536..e9a0067350 100644 --- a/src/libslic3r/Model.cpp +++ b/src/libslic3r/Model.cpp @@ -1420,8 +1420,15 @@ ModelObject& ModelObject::assign_copy(ModelObject &&rhs) void ModelObject::assign_new_unique_ids_recursive() { this->set_new_unique_id(); - for (ModelVolume *model_volume : this->volumes) + std::vector old_volume_ids; + for (ModelVolume *model_volume : this->volumes) { + old_volume_ids.push_back(model_volume->id()); model_volume->assign_new_unique_ids_recursive(); + } + for (ModelVolume *model_volume : this->volumes) + if (model_volume->is_painted_modifier()) + if (auto it = std::find(old_volume_ids.begin(), old_volume_ids.end(), model_volume->painted_modifier_host); it != old_volume_ids.end()) + model_volume->painted_modifier_host = this->volumes[it - old_volume_ids.begin()]->id(); for (ModelInstance *model_instance : this->instances) model_instance->assign_new_unique_ids_recursive(); this->layer_height_profile.set_new_unique_id(); @@ -1534,6 +1541,57 @@ ModelVolume* ModelObject::add_volume_with_shared_mesh(const ModelVolume &other, return v; } +ModelVolume* ModelObject::add_painted_modifier(const ModelVolume &host) +{ + assert(host.is_model_part()); + ModelVolume *v = this->add_volume_with_shared_mesh(host, ModelVolumeType::PAINTED_MODIFIER); + v->m_convex_hull = host.m_convex_hull; + v->set_transformation(host.get_transformation()); + v->painted_modifier_host = host.id(); + return v; +} + +const ModelVolume* ModelObject::painted_modifier_host(const ModelVolume &painted_modifier) const +{ + assert(painted_modifier.is_painted_modifier()); + for (const ModelVolume *v : this->volumes) + if (v->is_model_part() && v->id() == painted_modifier.painted_modifier_host) + return v; + return nullptr; +} + +bool ModelObject::sync_painted_modifiers() +{ + bool changed = false; + for (ModelVolume *v : this->volumes) { + if (! v->is_painted_modifier()) + continue; + const ModelVolume *host = this->painted_modifier_host(*v); + if (host == nullptr) + continue; + if (v->mesh_ptr() != host->mesh_ptr()) { + const indexed_triangle_set &its_old = v->mesh().its; + const indexed_triangle_set &its_new = host->mesh().its; + if (! v->painted_modifier_facets.empty() && (its_old.vertices != its_new.vertices || its_old.indices != its_new.indices)) + v->painted_modifier_facets.set_data(TriangleSelector::remap_painting(its_old, v->painted_modifier_facets.get_data(), its_new, + v->get_matrix().inverse() * host->get_matrix(), {})); + v->m_mesh = host->m_mesh; + v->m_convex_hull = host->m_convex_hull; + changed = true; + } + if (! host->get_matrix().isApprox(v->get_matrix())) { + v->set_transformation(host->get_transformation()); + changed = true; + } + } + return changed; +} + +bool ModelObject::has_painted_modifiers() const +{ + return std::any_of(this->volumes.cbegin(), this->volumes.cend(), [](const ModelVolume *mv) { return mv->is_painted_modifier(); }); +} + void ModelObject::delete_volume(size_t idx) { ModelVolumePtrs::iterator i = this->volumes.begin() + idx; @@ -1614,9 +1672,11 @@ bool ModelObject::hides_imported_parts() const void ModelObject::sort_volumes(bool full_sort) { + // Painted modifiers share the group of modifiers, so that the user may order them together. + auto sort_type = [](const ModelVolume *v) { return v->is_painted_modifier() ? ModelVolumeType::PARAMETER_MODIFIER : v->type(); }; // sort volumes inside the object to order "Model Part, Negative Volume, Modifier, Support Blocker and Support Enforcer. " if (full_sort) - std::stable_sort(volumes.begin(), volumes.end(), [](ModelVolume* vl, ModelVolume* vr) { + std::stable_sort(volumes.begin(), volumes.end(), [&sort_type](ModelVolume* vl, ModelVolume* vr) { // Special handling for Precise Seam modifiers: group-based sorting with user order preservation if (vl->is_precise_seam() && vr->is_precise_seam()) { // Strong (center/left/right) always before weak (enforced/blocked/neutral) @@ -1631,13 +1691,13 @@ void ModelObject::sort_volumes(bool full_sort) } // For non-Precise-Seam or mixed types: use standard enum-based ordering - return vl->type() < vr->type(); + return sort_type(vl) < sort_type(vr); }); // sort have to controll "place" of the support blockers/enforcers. But one of the model parts have to be on the first place. else - std::stable_sort(volumes.begin(), volumes.end(), [](ModelVolume* vl, ModelVolume* vr) { - ModelVolumeType vl_type = vl->type() > ModelVolumeType::PARAMETER_MODIFIER ? vl->type() : ModelVolumeType::PARAMETER_MODIFIER; - ModelVolumeType vr_type = vr->type() > ModelVolumeType::PARAMETER_MODIFIER ? vr->type() : ModelVolumeType::PARAMETER_MODIFIER; + std::stable_sort(volumes.begin(), volumes.end(), [&sort_type](ModelVolume* vl, ModelVolume* vr) { + ModelVolumeType vl_type = sort_type(vl) > ModelVolumeType::PARAMETER_MODIFIER ? sort_type(vl) : ModelVolumeType::PARAMETER_MODIFIER; + ModelVolumeType vr_type = sort_type(vr) > ModelVolumeType::PARAMETER_MODIFIER ? sort_type(vr) : ModelVolumeType::PARAMETER_MODIFIER; // Apply same Precise Seam grouping logic for partial sort if (vl->is_precise_seam() && vr->is_precise_seam()) { @@ -2127,11 +2187,13 @@ void ModelObject::convert_units(ModelObjectPtrs& new_objects, ConversionType con new_object->input_file.clear(); int vol_idx = 0; + std::map new_volume_ids; for (ModelVolume* volume : volumes) { if (!volume->mesh().empty()) { TriangleMesh mesh(volume->mesh()); ModelVolume* vol = new_object->add_volume(mesh); + new_volume_ids[volume->id()] = vol->id(); vol->name = volume->name; vol->set_type(volume->type()); // Don't copy the config's ID. @@ -2154,6 +2216,9 @@ void ModelObject::convert_units(ModelObjectPtrs& new_objects, ConversionType con vol->seam_facets.assign(volume->seam_facets); vol->mmu_segmentation_facets.assign(volume->mmu_segmentation_facets); vol->fuzzy_skin_facets.assign(volume->fuzzy_skin_facets); + vol->painted_modifier_facets.assign(volume->painted_modifier_facets); + vol->painted_modifier_depth = volume->painted_modifier_depth; + vol->painted_modifier_host = volume->painted_modifier_host; // Perform conversion only if the target "imperial" state is different from the current one. // This check supports conversion of "mixed" set of volumes, each with different "imperial" state. @@ -2173,6 +2238,11 @@ void ModelObject::convert_units(ModelObjectPtrs& new_objects, ConversionType con } vol_idx ++; } + for (ModelVolume *vol : new_object->volumes) + if (vol->is_painted_modifier()) + if (auto it = new_volume_ids.find(vol->painted_modifier_host); it != new_volume_ids.end()) + vol->painted_modifier_host = it->second; + new_object->sync_painted_modifiers(); new_object->invalidate_bounding_box(); new_objects.push_back(new_object); @@ -2266,6 +2336,7 @@ void ModelVolume::reset_extra_facets() this->seam_facets.reset(); this->mmu_segmentation_facets.reset(); this->fuzzy_skin_facets.reset(); + this->painted_modifier_facets.reset(); // Texture-displacement paint data has no remap-across-topology-change support yet (see // build_texture_displacement()'s documented limitation), so it must be dropped here rather // than left referring to a mesh that no longer matches it. @@ -2279,13 +2350,14 @@ void ModelVolume::reset_extra_facets() std::optional ModelVolume::save_painting() const { - if (is_any_painted() && is_model_part() && !mesh().empty()) { + if (is_any_painted() && (is_model_part() || is_painted_modifier()) && !mesh().empty()) { TriangleSelector::SavedPainting sp; - sp.mesh = mesh(); - sp.supported = supported_facets.get_data(); - sp.seam = seam_facets.get_data(); - sp.mmu = mmu_segmentation_facets.get_data(); - sp.fuzzy = fuzzy_skin_facets.get_data(); + sp.mesh = mesh(); + sp.supported = supported_facets.get_data(); + sp.seam = seam_facets.get_data(); + sp.mmu = mmu_segmentation_facets.get_data(); + sp.fuzzy = fuzzy_skin_facets.get_data(); + sp.painted_modifier = painted_modifier_facets.get_data(); return sp; } @@ -2318,6 +2390,7 @@ void ModelVolume::restore_painting(const std::optionalseam, seam_facets); remap_one(saved->mmu, mmu_segmentation_facets); remap_one(saved->fuzzy, fuzzy_skin_facets); + remap_one(saved->painted_modifier, painted_modifier_facets); } static void invalidate_translations(ModelObject* object, const ModelInstance* src_instance) @@ -3042,6 +3115,8 @@ ModelVolumeType ModelVolume::type_from_string(const std::string &s) return ModelVolumeType::PRECISE_SEAM_BLOCKED; if (s == "precise_seam_neutral") return ModelVolumeType::PRECISE_SEAM_NEUTRAL; + if (s == "painted_modifier") + return ModelVolumeType::PAINTED_MODIFIER; //assert(s == "0"); // Default value if invalud type string received. return ModelVolumeType::MODEL_PART; @@ -3062,6 +3137,7 @@ std::string ModelVolume::type_to_string(const ModelVolumeType t) case ModelVolumeType::PRECISE_SEAM_ENFORCED: return "precise_seam_enforced"; case ModelVolumeType::PRECISE_SEAM_BLOCKED: return "precise_seam_blocked"; case ModelVolumeType::PRECISE_SEAM_NEUTRAL: return "precise_seam_neutral"; + case ModelVolumeType::PAINTED_MODIFIER: return "painted_modifier"; default: assert(false); return "normal_part"; @@ -3186,6 +3262,7 @@ void ModelVolume::assign_new_unique_ids_recursive() seam_facets.set_new_unique_id(); mmu_segmentation_facets.set_new_unique_id(); fuzzy_skin_facets.set_new_unique_id(); + painted_modifier_facets.set_new_unique_id(); // As set_new_unique_id() already does: the undo/redo stack stores FacetsAnnotation contents keyed // by ObjectID, so a clone left sharing these ids with its source can be handed the source's mask // on an undo - after which a paint mask and the mesh it was recorded against no longer match. @@ -4406,6 +4483,15 @@ bool model_fuzzy_skin_data_changed(const ModelObject &mo, const ModelObject &mo_ [](const ModelVolume &mv_old, const ModelVolume &mv_new){ return mv_old.fuzzy_skin_facets.timestamp_matches(mv_new.fuzzy_skin_facets); }); } +bool model_painted_modifier_data_changed(const ModelObject &mo, const ModelObject &mo_new) +{ + return model_property_changed(mo, mo_new, + [](const ModelVolumeType t) { return t == ModelVolumeType::PAINTED_MODIFIER; }, + [](const ModelVolume &mv_old, const ModelVolume &mv_new) { + return mv_old.painted_modifier_facets.timestamp_matches(mv_new.painted_modifier_facets) && mv_old.painted_modifier_depth == mv_new.painted_modifier_depth; + }); +} + bool model_brim_points_data_changed(const ModelObject& mo, const ModelObject& mo_new) { if (mo.brim_points.size() != mo_new.brim_points.size()) diff --git a/src/libslic3r/Model.hpp b/src/libslic3r/Model.hpp index 562c7aa900..b607e5eb20 100644 --- a/src/libslic3r/Model.hpp +++ b/src/libslic3r/Model.hpp @@ -367,6 +367,8 @@ enum class ModelVolumeType : int { PRECISE_SEAM_ENFORCED, PRECISE_SEAM_BLOCKED, PRECISE_SEAM_NEUTRAL, + // Settings modifier whose shape is painted on its host part, see docs/HLSD/painted-modifiers.md. + PAINTED_MODIFIER, }; // Free functions for checking ModelVolumeType without a ModelVolume object. @@ -449,6 +451,13 @@ public: ModelVolume* add_volume(const ModelVolume &volume, ModelVolumeType type = ModelVolumeType::INVALID); ModelVolume* add_volume(const ModelVolume &volume, TriangleMesh &&mesh); ModelVolume* add_volume_with_shared_mesh(const ModelVolume &other, ModelVolumeType type = ModelVolumeType::MODEL_PART); + // Adds an empty painted modifier sharing the mesh and the transformation of a model part. + ModelVolume* add_painted_modifier(const ModelVolume &host); + // The model part a painted modifier is painted on, nullptr if it was deleted. + const ModelVolume* painted_modifier_host(const ModelVolume &painted_modifier) const; + // Makes the painted modifiers follow the transformation and the mesh of their hosts. Returns true if any of them changed. + bool sync_painted_modifiers(); + bool has_painted_modifiers() const; void delete_volume(size_t idx); void clear_volumes(); void sort_volumes(bool full_sort); @@ -928,6 +937,13 @@ public: // List of mesh facets painted for fuzzy skin. FacetsAnnotation fuzzy_skin_facets; + // Shape of a painted modifier: facets of the shared host mesh it covers. + FacetsAnnotation painted_modifier_facets; + // How far a painted modifier reaches into its host part, in mm. 0 means the whole cross-section nearest the paint. + float painted_modifier_depth { 0.f }; + // The model part a painted modifier is painted on. + ObjectID painted_modifier_host; + // One independent paint mask per texture-displacement layer slot (see texture_displacement_layers // below). Unlike the other facets fields above, a triangle may be painted (ENFORCER) in more // than one of these simultaneously -- that overlap is what makes the layers "blend". @@ -1013,7 +1029,7 @@ public: // Save painting data before reset_extra_facets() discards it. // Used for replacing mesh without losing painting data. - // Only for model parts (not modifiers/connectors). + // Only for model parts and painted modifiers (not modifiers/connectors). std::optional save_painting() const; // Remap painting data from previous saved source to this mesh @@ -1041,6 +1057,9 @@ public: bool is_support_enforcer() const { return m_type == ModelVolumeType::SUPPORT_ENFORCER; } bool is_support_blocker() const { return m_type == ModelVolumeType::SUPPORT_BLOCKER; } bool is_support_modifier() const { return m_type == ModelVolumeType::SUPPORT_BLOCKER || m_type == ModelVolumeType::SUPPORT_ENFORCER; } + bool is_painted_modifier() const { return m_type == ModelVolumeType::PAINTED_MODIFIER; } + // Overrides the settings of the regions it overlaps, by its mesh or by its paint. + bool is_region_modifier() const { return this->is_modifier() || this->is_painted_modifier(); } // Check if this volume is any of the precise seam modifier subtypes bool is_precise_seam() const { return Slic3r::is_precise_seam(m_type); } // Helper to check if volume is a "strong" Precise Seam type (center, left, right) @@ -1152,14 +1171,21 @@ public: Transform3d get_matrix_no_offset() const { return m_transformation.get_matrix_no_offset(); } void set_new_unique_id() { + const ObjectID old_id = this->id(); ObjectBase::set_new_unique_id(); this->config.set_new_unique_id(); this->supported_facets.set_new_unique_id(); this->seam_facets.set_new_unique_id(); this->mmu_segmentation_facets.set_new_unique_id(); this->fuzzy_skin_facets.set_new_unique_id(); + this->painted_modifier_facets.set_new_unique_id(); for (int i = 0; i < int(TEXTURE_DISPLACEMENT_MAX_LAYERS); ++i) this->texture_displacement_facet(i).set_new_unique_id(); + // Mesh edits renew the ID of a part, its painted modifiers stay on it. + if (this->object != nullptr && this->is_model_part()) + for (ModelVolume *v : this->object->volumes) + if (v->painted_modifier_host == old_id) + v->painted_modifier_host = this->id(); } bool is_fdm_support_painted() const { return !this->supported_facets.empty(); } @@ -1168,7 +1194,8 @@ public: bool is_fuzzy_skin_painted() const { return !this->fuzzy_skin_facets.empty(); } bool is_texture_displacement_painted() const { return !this->texture_displacement_facets_all_empty(); } bool is_any_painted() const { - return is_fdm_support_painted() || is_seam_painted() || is_mm_painted() || is_fuzzy_skin_painted() || is_texture_displacement_painted(); + return is_fdm_support_painted() || is_seam_painted() || is_mm_painted() || is_fuzzy_skin_painted() || is_texture_displacement_painted() || + !this->painted_modifier_facets.empty(); } // Orca: Implement prusa's filament shrink compensation approach @@ -1269,6 +1296,7 @@ private: config(other.config), m_type(other.m_type), object(object), m_transformation(other.m_transformation), supported_facets(other.supported_facets), seam_facets(other.seam_facets), mmu_segmentation_facets(other.mmu_segmentation_facets), fuzzy_skin_facets(other.fuzzy_skin_facets), + painted_modifier_facets(other.painted_modifier_facets), painted_modifier_depth(other.painted_modifier_depth), painted_modifier_host(other.painted_modifier_host), texture_displacement_facets_0(other.texture_displacement_facets_0), texture_displacement_facets_1(other.texture_displacement_facets_1), texture_displacement_facets_2(other.texture_displacement_facets_2), texture_displacement_facets_3(other.texture_displacement_facets_3), texture_displacement_facets_4(other.texture_displacement_facets_4), texture_displacement_facets_5(other.texture_displacement_facets_5), @@ -1299,6 +1327,7 @@ private: // Providing a new mesh, therefore this volume will get a new unique ID assigned. ModelVolume(ModelObject *object, const ModelVolume &other, TriangleMesh &&mesh) : name(other.name), import_display_order(other.import_display_order), source(other.source), config(other.config), object(object), m_mesh(new TriangleMesh(std::move(mesh))), m_type(other.m_type), m_transformation(other.m_transformation), + painted_modifier_depth(other.painted_modifier_depth), painted_modifier_host(other.painted_modifier_host), cut_info(other.cut_info), text_configuration(other.text_configuration), emboss_shape(other.emboss_shape) { assert(this->id().valid()); @@ -1338,7 +1367,7 @@ private: friend class cereal::access; friend class UndoRedo::StackImpl; // Used for deserialization, therefore no IDs are allocated. - ModelVolume() : ObjectBase(-1), config(-1), supported_facets(-1), seam_facets(-1), mmu_segmentation_facets(-1), fuzzy_skin_facets(-1), + ModelVolume() : ObjectBase(-1), config(-1), supported_facets(-1), seam_facets(-1), mmu_segmentation_facets(-1), fuzzy_skin_facets(-1), painted_modifier_facets(-1), texture_displacement_facets_0(-1), texture_displacement_facets_1(-1), texture_displacement_facets_2(-1), texture_displacement_facets_3(-1), texture_displacement_facets_4(-1), texture_displacement_facets_5(-1), texture_displacement_facets_6(-1), texture_displacement_facets_7(-1), object(nullptr) { @@ -1368,6 +1397,10 @@ private: mesh_changed |= t != mmu_segmentation_facets.timestamp(); cereal::load_by_value(ar, fuzzy_skin_facets); mesh_changed |= t != fuzzy_skin_facets.timestamp(); + t = painted_modifier_facets.timestamp(); + cereal::load_by_value(ar, painted_modifier_facets); + mesh_changed |= t != painted_modifier_facets.timestamp(); + ar(painted_modifier_depth, painted_modifier_host); for (int i = 0; i < int(TEXTURE_DISPLACEMENT_MAX_LAYERS); ++i) { FacetsAnnotation &f = texture_displacement_facet(i); Timestamp tf = f.timestamp(); @@ -1396,6 +1429,8 @@ private: cereal::save_by_value(ar, seam_facets); cereal::save_by_value(ar, mmu_segmentation_facets); cereal::save_by_value(ar, fuzzy_skin_facets); + cereal::save_by_value(ar, painted_modifier_facets); + ar(painted_modifier_depth, painted_modifier_host); for (int i = 0; i < int(TEXTURE_DISPLACEMENT_MAX_LAYERS); ++i) cereal::save_by_value(ar, texture_displacement_facet(i)); ar(texture_displacement_layers, texture_displacement_options, texture_uv); @@ -1962,6 +1997,8 @@ extern bool model_mmu_segmentation_data_changed(const ModelObject& mo, const Mod // Test whether the now ModelObject has newer fuzzy skin data than the old one. // The function assumes that volumes list is synchronized. extern bool model_fuzzy_skin_data_changed(const ModelObject &mo, const ModelObject &mo_new); +// Test whether the paint or the depth of painted modifiers differ. +extern bool model_painted_modifier_data_changed(const ModelObject &mo, const ModelObject &mo_new); bool model_brim_points_data_changed(const ModelObject& mo, const ModelObject& mo_new); diff --git a/src/libslic3r/MultiMaterialSegmentation.cpp b/src/libslic3r/MultiMaterialSegmentation.cpp index 79ae7e2d8a..acb083078a 100644 --- a/src/libslic3r/MultiMaterialSegmentation.cpp +++ b/src/libslic3r/MultiMaterialSegmentation.cpp @@ -2185,67 +2185,48 @@ static bool has_layer_only_one_color(const std::vector &colored_po return true; } -std::vector> segmentation_by_painting(const PrintObject &print_object, - const std::function &extract_facets_info, - const size_t num_facets_states, - const float segmentation_max_width, - const float segmentation_interlocking_depth, - const bool segmentation_interlocking_beam, - const IncludeTopAndBottomLayers include_top_and_bottom_layers, - const std::function &throw_on_cancel_callback) +// Merges the slices of a layer and removes the defects that break the Voronoi diagrams of the segmentation. +static ExPolygons segmentation_input_expolygons(const ExPolygons &slices) { - const size_t num_layers = print_object.layers().size(); - std::vector> segmented_regions(num_layers); - segmented_regions.assign(num_layers, std::vector(num_facets_states)); + ExPolygons ex_polygons; + for (const ExPolygon &expolygon : slices) + Slic3r::append(ex_polygons, offset_ex(expolygon, float(10 * SCALED_EPSILON))); + // All expolygons are expanded by SCALED_EPSILON, merged, and then shrunk again by SCALED_EPSILON + // to ensure that very close polygons will be merged. + ex_polygons = union_ex(ex_polygons); + // Remove all expolygons and holes with an area less than 0.1mm^2 + remove_small_and_small_holes(ex_polygons, Slic3r::sqr(scale_(0.1f))); + // Occasionally, some input polygons contained self-intersections that caused problems with Voronoi diagrams + // and consequently with the extraction of colored segments by function extract_colored_segments. + // Calling simplify_polygons removes these self-intersections. + // Also, occasionally input polygons contained several points very close together (distance between points is 1 or so). + // Such close points sometimes caused that the Voronoi diagram has self-intersecting edges around these vertices. + // This consequently leads to issues with the extraction of colored segments by function extract_colored_segments. + // Calling expolygons_simplify fixed these issues. + return remove_duplicates(expolygons_simplify(offset_ex(ex_polygons, -10.f * float(SCALED_EPSILON)), 5 * SCALED_EPSILON), scaled(0.01), PI/6); +} + +// Splits each layer by the state of the nearest painted part of its contour, after projecting the painted facets of painted_volumes onto the contours. +static std::vector> segment_layers_by_painted_contours(const PrintObject &print_object, + const std::vector &input_expolygons, + const std::vector &layer_bboxes, + const std::vector &painted_volumes, + const std::function &extract_facets_info, + const size_t num_facets_states, + const std::function &throw_on_cancel_callback) +{ + const size_t num_layers = input_expolygons.size(); + std::vector> segmented_regions(num_layers, std::vector(num_facets_states)); std::vector> painted_lines(num_layers); std::array painted_lines_mutex; std::vector edge_grids(num_layers); const ConstLayerPtrsAdaptor layers = print_object.layers(); - std::vector input_expolygons(num_layers); - - throw_on_cancel_callback(); + assert(layers.size() == num_layers); #ifdef MM_SEGMENTATION_DEBUG static int iRun = 0; #endif // MM_SEGMENTATION_DEBUG - // Merge all regions and remove small holes - BOOST_LOG_TRIVIAL(debug) << "Print object segmentation - Slices preprocessing in parallel - Begin"; - tbb::parallel_for(tbb::blocked_range(0, num_layers), [&layers, &input_expolygons, &throw_on_cancel_callback](const tbb::blocked_range &range) { - for (size_t layer_idx = range.begin(); layer_idx < range.end(); ++layer_idx) { - throw_on_cancel_callback(); - ExPolygons ex_polygons; - for (LayerRegion *region : layers[layer_idx]->regions()) - for (const Surface &surface : region->slices.surfaces) - Slic3r::append(ex_polygons, offset_ex(surface.expolygon, float(10 * SCALED_EPSILON))); - // All expolygons are expanded by SCALED_EPSILON, merged, and then shrunk again by SCALED_EPSILON - // to ensure that very close polygons will be merged. - ex_polygons = union_ex(ex_polygons); - // Remove all expolygons and holes with an area less than 0.1mm^2 - remove_small_and_small_holes(ex_polygons, Slic3r::sqr(scale_(0.1f))); - // Occasionally, some input polygons contained self-intersections that caused problems with Voronoi diagrams - // and consequently with the extraction of colored segments by function extract_colored_segments. - // Calling simplify_polygons removes these self-intersections. - // Also, occasionally input polygons contained several points very close together (distance between points is 1 or so). - // Such close points sometimes caused that the Voronoi diagram has self-intersecting edges around these vertices. - // This consequently leads to issues with the extraction of colored segments by function extract_colored_segments. - // Calling expolygons_simplify fixed these issues. - input_expolygons[layer_idx] = remove_duplicates(expolygons_simplify(offset_ex(ex_polygons, -10.f * float(SCALED_EPSILON)), 5 * SCALED_EPSILON), scaled(0.01), PI/6); - -#ifdef MM_SEGMENTATION_DEBUG_INPUT - export_processed_input_expolygons_to_svg(debug_out_path("mm-input-%d-%d.svg", layer_idx, iRun), layers[layer_idx]->regions(), input_expolygons[layer_idx]); -#endif // MM_SEGMENTATION_DEBUG_INPUT - } - }); // end of parallel_for - BOOST_LOG_TRIVIAL(debug) << "Print object segmentation - Slices preprocessing in parallel - End"; - - std::vector layer_bboxes(num_layers); - for (size_t layer_idx = 0; layer_idx < num_layers; ++layer_idx) { - throw_on_cancel_callback(); - layer_bboxes[layer_idx] = get_extents(layers[layer_idx]->regions()); - layer_bboxes[layer_idx].merge(get_extents(input_expolygons[layer_idx])); - } - for (size_t layer_idx = 0; layer_idx < num_layers; ++layer_idx) { throw_on_cancel_callback(); BoundingBox bbox = layer_bboxes[layer_idx]; @@ -2263,13 +2244,13 @@ std::vector> segmentation_by_painting(const PrintObject BOOST_LOG_TRIVIAL(debug) << "Print object segmentation - Projection of painted triangles - Begin"; // The layers were sliced in this frame (belt rotation, remap and Z lift included), and it already centers the object. const Transform3d object_trafo = print_object.trafo_sliced(); - for (const ModelVolume *mv : print_object.model_object()->volumes) { + for (const ModelVolume *mv : painted_volumes) { const ModelVolumeFacetsInfo facets_info = extract_facets_info(*mv); tbb::parallel_for(tbb::blocked_range(1, num_facets_states), [&mv, &object_trafo, &facets_info, &layers, &edge_grids, &painted_lines, &painted_lines_mutex, &input_expolygons, &throw_on_cancel_callback](const tbb::blocked_range &range) { for (size_t extruder_idx = range.begin(); extruder_idx < range.end(); ++extruder_idx) { throw_on_cancel_callback(); const indexed_triangle_set custom_facets = facets_info.facets_annotation.get_facets(*mv, EnforcerBlockerType(extruder_idx)); - if (!mv->is_model_part() || custom_facets.indices.empty()) + if (custom_facets.indices.empty()) continue; const Transform3f tr = (object_trafo * mv->get_matrix()).cast(); @@ -2438,6 +2419,64 @@ std::vector> segmentation_by_painting(const PrintObject } }); // end of parallel_for BOOST_LOG_TRIVIAL(debug) << "Print object segmentation - layers segmentation in parallel - end"; + +#ifdef MM_SEGMENTATION_DEBUG + ++iRun; +#endif // MM_SEGMENTATION_DEBUG + + return segmented_regions; +} + +std::vector> segmentation_by_painting(const PrintObject &print_object, + const std::function &extract_facets_info, + const size_t num_facets_states, + const float segmentation_max_width, + const float segmentation_interlocking_depth, + const bool segmentation_interlocking_beam, + const IncludeTopAndBottomLayers include_top_and_bottom_layers, + const std::function &throw_on_cancel_callback) +{ + const size_t num_layers = print_object.layers().size(); + const ConstLayerPtrsAdaptor layers = print_object.layers(); + std::vector input_expolygons(num_layers); + + throw_on_cancel_callback(); + +#ifdef MM_SEGMENTATION_DEBUG + static int iRun = 0; +#endif // MM_SEGMENTATION_DEBUG + + // Merge all regions and remove small holes + BOOST_LOG_TRIVIAL(debug) << "Print object segmentation - Slices preprocessing in parallel - Begin"; + tbb::parallel_for(tbb::blocked_range(0, num_layers), [&layers, &input_expolygons, &throw_on_cancel_callback](const tbb::blocked_range &range) { + for (size_t layer_idx = range.begin(); layer_idx < range.end(); ++layer_idx) { + throw_on_cancel_callback(); + ExPolygons slices; + for (LayerRegion *region : layers[layer_idx]->regions()) + for (const Surface &surface : region->slices.surfaces) + slices.push_back(surface.expolygon); + input_expolygons[layer_idx] = segmentation_input_expolygons(slices); + +#ifdef MM_SEGMENTATION_DEBUG_INPUT + export_processed_input_expolygons_to_svg(debug_out_path("mm-input-%d-%d.svg", layer_idx, iRun), layers[layer_idx]->regions(), input_expolygons[layer_idx]); +#endif // MM_SEGMENTATION_DEBUG_INPUT + } + }); // end of parallel_for + BOOST_LOG_TRIVIAL(debug) << "Print object segmentation - Slices preprocessing in parallel - End"; + + std::vector layer_bboxes(num_layers); + for (size_t layer_idx = 0; layer_idx < num_layers; ++layer_idx) { + throw_on_cancel_callback(); + layer_bboxes[layer_idx] = get_extents(layers[layer_idx]->regions()); + layer_bboxes[layer_idx].merge(get_extents(input_expolygons[layer_idx])); + } + + std::vector model_parts; + for (const ModelVolume *mv : print_object.model_object()->volumes) + if (mv->is_model_part()) + model_parts.push_back(mv); + std::vector> segmented_regions = segment_layers_by_painted_contours(print_object, input_expolygons, layer_bboxes, model_parts, + extract_facets_info, num_facets_states, throw_on_cancel_callback); throw_on_cancel_callback(); if ((segmentation_max_width > 0.f || segmentation_interlocking_depth > 0.f) && !segmentation_interlocking_beam) { @@ -2501,4 +2540,106 @@ std::vector> fuzzy_skin_segmentation_by_painting(const P return segmentation_by_painting(print_object, extract_facets_info, num_facets_states, max_external_perimeter_width, 0.f, false, IncludeTopAndBottomLayers::No, throw_on_cancel_callback); } +// Projects the painted top / bottom surfaces of a painted modifier down / up through its slices. +// A depth of 0 reaches as deep as the top / bottom shells. The color penetration layers apply to color painting only. +static std::vector painted_modifier_top_and_bottom(const PrintObject &print_object, + const ModelVolume &painted_modifier, + const std::vector &input_expolygons, + const std::function &throw_on_cancel_callback) +{ + const size_t num_layers = input_expolygons.size(); + std::vector out(num_layers); + const indexed_triangle_set painted = painted_modifier.painted_modifier_facets.get_facets_strict(painted_modifier, EnforcerBlockerType::ENFORCER); + if (painted.indices.empty()) + return out; + + const float depth = painted_modifier.painted_modifier_depth; + int max_top_layers = 0, max_bottom_layers = 0; + for (size_t i = 0; i < print_object.num_printing_regions(); ++ i) { + const PrintRegionConfig &config = print_object.printing_region(i).config(); + max_top_layers = std::max(max_top_layers, config.top_shell_layers.value); + max_bottom_layers = std::max(max_bottom_layers, config.bottom_shell_layers.value); + } + + const std::vector zs = zs_from_layers(print_object.layers()); + std::vector top_raw, bottom_raw; + slice_mesh_slabs(painted, zs, print_object.trafo_sliced() * painted_modifier.get_matrix(), &top_raw, &bottom_raw, nullptr, throw_on_cancel_callback); + + // Projections of each source layer, keyed by the layer they land on, gathered after the parallel loop. + std::vector>> projections(num_layers); + tbb::parallel_for(tbb::blocked_range(0, num_layers), [&](const tbb::blocked_range &range) { + for (size_t layer_idx = range.begin(); layer_idx < range.end(); ++ layer_idx) { + throw_on_cancel_callback(); + auto project = [&](Polygons &raw, const Polygons &occluding, bool down) { + remove_small(raw, Slic3r::sqr(scale_(0.1f))); + // A surface covered by the next layer in its direction is not a top / bottom surface. + ExPolygons surface = diff_ex(raw, occluding); + if (surface.empty()) + return; + ExPolygons column = input_expolygons[layer_idx]; + for (int target = int(layer_idx), step = 0; target >= 0 && target < int(num_layers); target += down ? -1 : 1, ++ step) { + if (depth > 0.f ? std::abs(zs[target] - zs[layer_idx]) >= depth : step > 0 && step >= (down ? max_top_layers : max_bottom_layers)) + break; + column = intersection_ex(column, input_expolygons[target]); + ExPolygons projection = intersection_ex(surface, column); + if (projection.empty()) + break; + projections[layer_idx].emplace_back(size_t(target), std::move(projection)); + } + }; + if (! top_raw.empty() && ! top_raw[layer_idx].empty()) + project(top_raw[layer_idx], layer_idx + 1 < num_layers ? to_polygons(input_expolygons[layer_idx + 1]) : Polygons(), true); + if (! bottom_raw.empty() && ! bottom_raw[layer_idx].empty()) + project(bottom_raw[layer_idx], layer_idx > 0 ? to_polygons(input_expolygons[layer_idx - 1]) : Polygons(), false); + } + }); + + for (std::vector> &layer_projections : projections) + for (auto &[target, projection] : layer_projections) + append(out[target], std::move(projection)); + return out; +} + +std::vector painted_modifier_segmentation(const PrintObject &print_object, + const ModelVolume &painted_modifier, + const std::vector &slices, + const std::function &throw_on_cancel_callback) +{ + assert(painted_modifier.is_painted_modifier()); + const size_t num_layers = slices.size(); + assert(num_layers == print_object.layers().size()); + if (painted_modifier.painted_modifier_facets.empty()) + return std::vector(num_layers); + + std::vector input_expolygons(num_layers); + tbb::parallel_for(tbb::blocked_range(0, num_layers), [&](const tbb::blocked_range &range) { + for (size_t layer_idx = range.begin(); layer_idx < range.end(); ++ layer_idx) { + throw_on_cancel_callback(); + input_expolygons[layer_idx] = segmentation_input_expolygons(slices[layer_idx]); + } + }); + std::vector layer_bboxes(num_layers); + for (size_t layer_idx = 0; layer_idx < num_layers; ++ layer_idx) { + layer_bboxes[layer_idx] = get_extents(slices[layer_idx]); + layer_bboxes[layer_idx].merge(get_extents(input_expolygons[layer_idx])); + } + + const auto extract_facets_info = [](const ModelVolume &mv) -> ModelVolumeFacetsInfo { + return {mv.painted_modifier_facets, true, false}; + }; + std::vector> segmented = segment_layers_by_painted_contours(print_object, input_expolygons, layer_bboxes, {&painted_modifier}, + extract_facets_info, 2, throw_on_cancel_callback); + if (painted_modifier.painted_modifier_depth > 0.f) + cut_segmented_layers(input_expolygons, segmented, float(scale_(painted_modifier.painted_modifier_depth)), 0.f, throw_on_cancel_callback); + + std::vector out = painted_modifier_top_and_bottom(print_object, painted_modifier, input_expolygons, throw_on_cancel_callback); + tbb::parallel_for(tbb::blocked_range(0, num_layers), [&](const tbb::blocked_range &range) { + for (size_t layer_idx = range.begin(); layer_idx < range.end(); ++ layer_idx) { + append(out[layer_idx], std::move(segmented[layer_idx][1])); + out[layer_idx] = union_ex(out[layer_idx]); + } + }); + return out; +} + } // namespace Slic3r diff --git a/src/libslic3r/MultiMaterialSegmentation.hpp b/src/libslic3r/MultiMaterialSegmentation.hpp index 6b230e8cad..b4980e37cb 100644 --- a/src/libslic3r/MultiMaterialSegmentation.hpp +++ b/src/libslic3r/MultiMaterialSegmentation.hpp @@ -63,6 +63,12 @@ std::vector> multi_material_segmentation_by_painting(con // Returns fuzzy skin segmentation based on painting in fuzzy skin segmentation gizmo std::vector> fuzzy_skin_segmentation_by_painting(const PrintObject &print_object, const std::function &throw_on_cancel_callback); +// Returns the part of each layer of a painted modifier's slices that its paint covers. +std::vector painted_modifier_segmentation(const PrintObject &print_object, + const ModelVolume &painted_modifier, + const std::vector &slices, + const std::function &throw_on_cancel_callback); + // Effective outer-wall line width for a region, resolved against its own nozzle with PrintRegion::flow's fallback. double resolve_outer_wall_line_width(const PrintRegionConfig ®ion_config, const PrintObjectConfig &object_config, const PrintConfig &print_config); diff --git a/src/libslic3r/Print.cpp b/src/libslic3r/Print.cpp index 129f67c39c..dd953971e2 100644 --- a/src/libslic3r/Print.cpp +++ b/src/libslic3r/Print.cpp @@ -3484,6 +3484,9 @@ void Print::process(long long *time_cost_with_cache, bool use_cache) return false; if (!model_volume1.fuzzy_skin_facets.equals(model_volume2.fuzzy_skin_facets)) return false; + if (!model_volume1.painted_modifier_facets.equals(model_volume2.painted_modifier_facets) || + model_volume1.painted_modifier_depth != model_volume2.painted_modifier_depth) + return false; if (model_volume1.config.get() != model_volume2.config.get()) return false; } diff --git a/src/libslic3r/PrintApply.cpp b/src/libslic3r/PrintApply.cpp index 551645054e..dd5f447574 100644 --- a/src/libslic3r/PrintApply.cpp +++ b/src/libslic3r/PrintApply.cpp @@ -122,6 +122,9 @@ static inline void model_volume_list_copy_configs(ModelObject &model_object_dst, mv_dst.mmu_segmentation_facets.assign(mv_src.mmu_segmentation_facets); assert(mv_dst.fuzzy_skin_facets.id() == mv_src.fuzzy_skin_facets.id()); mv_dst.fuzzy_skin_facets.assign(mv_src.fuzzy_skin_facets); + assert(mv_dst.painted_modifier_facets.id() == mv_src.painted_modifier_facets.id()); + mv_dst.painted_modifier_facets.assign(mv_src.painted_modifier_facets); + mv_dst.painted_modifier_depth = mv_src.painted_modifier_depth; //FIXME what to do with the materials? // mv_dst.m_material_id = mv_src.m_material_id; ++ i_src; @@ -624,7 +627,8 @@ private: static inline bool model_volume_solid_or_modifier(const ModelVolume &mv) { ModelVolumeType type = mv.type(); - return type == ModelVolumeType::MODEL_PART || type == ModelVolumeType::NEGATIVE_VOLUME || type == ModelVolumeType::PARAMETER_MODIFIER; + return type == ModelVolumeType::MODEL_PART || type == ModelVolumeType::NEGATIVE_VOLUME || type == ModelVolumeType::PARAMETER_MODIFIER || + type == ModelVolumeType::PAINTED_MODIFIER; } static inline Transform3f trafo_for_bbox(const Transform3d &object_trafo, const Transform3d &volume_trafo) @@ -842,10 +846,10 @@ bool verify_update_print_object_regions( // Remember whether a given modifier ModelVolume was visited already. auto it_model_volume_modifier_last = model_volumes.end(); for (PrintObjectRegions::VolumeRegion ®ion : layer_range.volume_regions) - if (region.model_volume->is_model_part() || region.model_volume->is_modifier()) { + if (region.model_volume->is_model_part() || region.model_volume->is_region_modifier()) { auto it_model_volume = lower_bound_by_predicate(model_volumes.begin(), model_volumes.end(), [®ion](const ModelVolume *l){ return l->id() < region.model_volume->id(); }); assert(it_model_volume != model_volumes.end() && (*it_model_volume)->id() == region.model_volume->id()); - if (region.model_volume->is_modifier() && it_model_volume != it_model_volume_modifier_last) { + if (region.model_volume->is_region_modifier() && it_model_volume != it_model_volume_modifier_last) { // A modifier ModelVolume is visited for the first time. // A visited modifier may not have had parent volume_regions created overlapping with some model parts or modifiers, // if the visited modifier did not modify their properties. Now the visited modifier's configuration may have changed, @@ -857,7 +861,7 @@ bool verify_update_print_object_regions( for (int parent_region_id = next_region_id - 1; parent_region_id >= 0; -- parent_region_id) { const PrintObjectRegions::VolumeRegion &parent_region = layer_range.volume_regions[parent_region_id]; assert(parent_region.model_volume != region.model_volume); - if (parent_region.model_volume->is_model_part() || parent_region.model_volume->is_modifier()) { + if (parent_region.model_volume->is_model_part() || parent_region.model_volume->is_region_modifier()) { // volume_regions are produced in decreasing order of parent volume_regions ids. // Some regions may not have been generated the last time by generate_print_object_regions(). assert(next_region_id == int(layer_range.volume_regions.size()) || @@ -1186,14 +1190,14 @@ static PrintObjectRegions* generate_print_object_regions( // Add a negative (subtractor) volume. Such volume has neither region nor parent volume assigned. layer_range.volume_regions.push_back({ &volume, -1, nullptr, bbox }); } else { - assert(volume.is_modifier()); + assert(volume.is_region_modifier()); // Modifiers may be chained one over the other. Check for overlap, merge DynamicPrintConfigs. bool added = false; int parent_model_part_id = -1; for (int parent_region_id = int(layer_range.volume_regions.size()) - 1; parent_region_id >= 0; -- parent_region_id) { const PrintObjectRegions::VolumeRegion &parent_region = layer_range.volume_regions[parent_region_id]; const ModelVolume &parent_volume = *parent_region.model_volume; - if (parent_volume.is_model_part() || parent_volume.is_modifier()) + if (parent_volume.is_model_part() || parent_volume.is_region_modifier()) if (PrintObjectRegions::BoundingBox parent_bbox = find_modifier_volume_extents(layer_range, parent_region_id); parent_bbox.intersects(*bbox)) { // Only create new region for a modifier, which actually modifies config of it's parent. if (PrintRegionConfig config = region_config_from_model_volume(parent_region.region->config(), nullptr, volume, num_extruders, variant_index); @@ -1218,7 +1222,7 @@ static PrintObjectRegions* generate_print_object_regions( for (unsigned int painted_extruder_id : painting_extruders) for (int parent_region_id = 0; parent_region_id < int(layer_range.volume_regions.size()); ++ parent_region_id) if (const PrintObjectRegions::VolumeRegion &parent_region = layer_range.volume_regions[parent_region_id]; - parent_region.model_volume->is_model_part() || parent_region.model_volume->is_modifier()) { + parent_region.model_volume->is_model_part() || parent_region.model_volume->is_region_modifier()) { PrintRegionConfig cfg = parent_region.region->config(); cfg.outer_wall_filament_id.value = painted_extruder_id; cfg.inner_wall_filament_id.value = painted_extruder_id; @@ -1242,7 +1246,7 @@ static PrintObjectRegions* generate_print_object_regions( // FuzzySkinPaintedRegion can override different parts of the Layer than PaintedRegions, // so FuzzySkinPaintedRegion has to point to both VolumeRegion and PaintedRegion. for (int parent_volume_region_id = 0; parent_volume_region_id < int(layer_range.volume_regions.size()); ++parent_volume_region_id) { - if (const PrintObjectRegions::VolumeRegion &parent_volume_region = layer_range.volume_regions[parent_volume_region_id]; parent_volume_region.model_volume->is_model_part() || parent_volume_region.model_volume->is_modifier()) { + if (const PrintObjectRegions::VolumeRegion &parent_volume_region = layer_range.volume_regions[parent_volume_region_id]; parent_volume_region.model_volume->is_model_part() || parent_volume_region.model_volume->is_region_modifier()) { PrintRegionConfig cfg = parent_volume_region.region->config(); if (cfg.fuzzy_skin.value != FuzzySkinType::Disabled_fuzzy) cfg.fuzzy_skin.value = FuzzySkinType::All; layer_range.fuzzy_skin_painted_regions.push_back({FuzzySkinParentType::VolumeRegion, parent_volume_region_id, get_create_region(std::move(cfg))}); @@ -1312,7 +1316,7 @@ void Print::update_shrinkage_compensation(size_t num_extruders, std::vector if (std::none_of(model_object->instances.begin(), model_object->instances.end(), [](const ModelInstance *mi) { return mi->is_printable(); })) continue; std::vector modifiers; - std::copy_if(model_object->volumes.begin(), model_object->volumes.end(), std::back_inserter(modifiers), [](const ModelVolume *mv) { return mv->is_modifier(); }); + std::copy_if(model_object->volumes.begin(), model_object->volumes.end(), std::back_inserter(modifiers), [](const ModelVolume *mv) { return mv->is_region_modifier(); }); for (const ModelVolume *part : model_object->volumes) { if (! part->is_model_part()) continue; @@ -1830,7 +1834,8 @@ Print::ApplyStatus Print::apply(const Model &model, DynamicPrintConfig new_full_ PrintObjectStatusDB print_object_status_db(m_objects); // 3) Synchronize ModelObjects & PrintObjects. - const std::initializer_list solid_or_modifier_types { ModelVolumeType::MODEL_PART, ModelVolumeType::NEGATIVE_VOLUME, ModelVolumeType::PARAMETER_MODIFIER }; + const std::initializer_list solid_or_modifier_types { ModelVolumeType::MODEL_PART, ModelVolumeType::NEGATIVE_VOLUME, ModelVolumeType::PARAMETER_MODIFIER, + ModelVolumeType::PAINTED_MODIFIER }; const std::initializer_list precise_seam_types { ModelVolumeType::PRECISE_SEAM_CENTER, ModelVolumeType::PRECISE_SEAM_LEFT, ModelVolumeType::PRECISE_SEAM_RIGHT, ModelVolumeType::PRECISE_SEAM_ENFORCED, @@ -1850,7 +1855,8 @@ Print::ApplyStatus Print::apply(const Model &model, DynamicPrintConfig new_full_ bool solid_or_modifier_differ = model_volume_list_changed(model_object, model_object_new, solid_or_modifier_types) || model_mmu_segmentation_data_changed(model_object, model_object_new) || (model_object_new.is_mm_painted() && num_extruders_changed) || - model_fuzzy_skin_data_changed(model_object, model_object_new); + model_fuzzy_skin_data_changed(model_object, model_object_new) || + model_painted_modifier_data_changed(model_object, model_object_new); bool supports_differ = model_volume_list_changed(model_object, model_object_new, ModelVolumeType::SUPPORT_BLOCKER) || model_volume_list_changed(model_object, model_object_new, ModelVolumeType::SUPPORT_ENFORCER); bool precise_seam_differ = model_volume_list_changed(model_object, model_object_new, precise_seam_types); @@ -1934,6 +1940,7 @@ Print::ApplyStatus Print::apply(const Model &model, DynamicPrintConfig new_full_ //FIXME What to do with m_material_id? model_volume_list_copy_configs(model_object /* dst */, model_object_new /* src */, ModelVolumeType::MODEL_PART); model_volume_list_copy_configs(model_object /* dst */, model_object_new /* src */, ModelVolumeType::PARAMETER_MODIFIER); + model_volume_list_copy_configs(model_object /* dst */, model_object_new /* src */, ModelVolumeType::PAINTED_MODIFIER); // Synchronize Precise Seam modifier volumes model_volume_list_copy_configs(model_object /* dst */, model_object_new /* src */, precise_seam_types); layer_height_ranges_copy_configs(model_object.layer_config_ranges /* dst */, model_object_new.layer_config_ranges /* src */); diff --git a/src/libslic3r/PrintObjectSlice.cpp b/src/libslic3r/PrintObjectSlice.cpp index c5e99348af..19916efe1f 100644 --- a/src/libslic3r/PrintObjectSlice.cpp +++ b/src/libslic3r/PrintObjectSlice.cpp @@ -170,7 +170,8 @@ static std::vector slice_volume( static inline bool model_volume_needs_slicing(const ModelVolume &mv) { ModelVolumeType type = mv.type(); - return type == ModelVolumeType::MODEL_PART || type == ModelVolumeType::NEGATIVE_VOLUME || type == ModelVolumeType::PARAMETER_MODIFIER; + return type == ModelVolumeType::MODEL_PART || type == ModelVolumeType::NEGATIVE_VOLUME || type == ModelVolumeType::PARAMETER_MODIFIER || + type == ModelVolumeType::PAINTED_MODIFIER; } // Slice printable volumes, negative volumes and modifier volumes, sorted by ModelVolume::id(). @@ -484,7 +485,7 @@ static std::vector> slices_to_regions( for (int idx_region = 0; idx_region < int(layer_range.volume_regions.size()); ++ idx_region) if (! temp_slices[idx_region].expolygons.empty()) { const PrintObjectRegions::VolumeRegion ®ion = layer_range.volume_regions[idx_region]; - if (region.model_volume->is_modifier()) { + if (region.model_volume->is_region_modifier()) { assert(region.parent > -1); bool next_region_same_modifier = idx_region + 1 < int(temp_slices.size()) && layer_range.volume_regions[idx_region + 1].model_volume == region.model_volume; RegionSlice &parent_slice = temp_slices[region.parent]; @@ -1369,6 +1370,12 @@ void PrintObject::slice_volumes() print->config(), this->config(), this->trafo_centered(), this->model_object()->volumes, m_shared_regions->layer_ranges, slice_zs, throw_on_cancel_callback, &m_belt_min_z); + // A painted modifier was sliced as its whole host, keep only what its paint covers. + for (const ModelVolume *model_volume : this->model_object()->volumes) + if (model_volume->is_painted_modifier()) + if (auto it = std::find_if(objSliceByVolume.begin(), objSliceByVolume.end(), [model_volume](const VolumeSlices &vs) { return vs.volume_id == model_volume->id(); }); + it != objSliceByVolume.end()) + it->slices = painted_modifier_segmentation(*this, *model_volume, it->slices, throw_on_cancel_callback); } //BBS: "model_part" volumes are grouded according to their connections diff --git a/src/libslic3r/TriangleSelector.hpp b/src/libslic3r/TriangleSelector.hpp index 46ebfb99df..c5db09b285 100644 --- a/src/libslic3r/TriangleSelector.hpp +++ b/src/libslic3r/TriangleSelector.hpp @@ -433,6 +433,7 @@ public: TriangleSplittingData seam; TriangleSplittingData mmu; TriangleSplittingData fuzzy; + TriangleSplittingData painted_modifier; }; // Remap painting data from source mesh to target mesh using spatial mapping. diff --git a/src/slic3r/CMakeLists.txt b/src/slic3r/CMakeLists.txt index d96ce59bd9..268b48c664 100644 --- a/src/slic3r/CMakeLists.txt +++ b/src/slic3r/CMakeLists.txt @@ -203,6 +203,8 @@ set(SLIC3R_GUI_SOURCES GUI/Gizmos/GLGizmoMmuSegmentation.hpp GUI/Gizmos/GLGizmoMove.cpp GUI/Gizmos/GLGizmoMove.hpp + GUI/Gizmos/GLGizmoPaintedModifier.cpp + GUI/Gizmos/GLGizmoPaintedModifier.hpp GUI/Gizmos/GLGizmoPainterBase.cpp GUI/Gizmos/GLGizmoPainterBase.hpp GUI/Gizmos/GLGizmoRotate.cpp diff --git a/src/slic3r/GUI/3DScene.cpp b/src/slic3r/GUI/3DScene.cpp index e72117c080..d76c8fd4cd 100644 --- a/src/slic3r/GUI/3DScene.cpp +++ b/src/slic3r/GUI/3DScene.cpp @@ -427,6 +427,7 @@ ColorRGBA color_from_model_volume(const ModelVolume& model_volume) case ModelVolumeType::PARAMETER_MODIFIER: case ModelVolumeType::SUPPORT_BLOCKER: case ModelVolumeType::SUPPORT_ENFORCER: + case ModelVolumeType::PAINTED_MODIFIER: break; } return GLVolume::MODEL_MIDIFIER_COL; // unreachable fallback diff --git a/src/slic3r/GUI/GLCanvas3D.cpp b/src/slic3r/GUI/GLCanvas3D.cpp index a7f510d206..39aa45a34b 100644 --- a/src/slic3r/GUI/GLCanvas3D.cpp +++ b/src/slic3r/GUI/GLCanvas3D.cpp @@ -2670,7 +2670,8 @@ void GLCanvas3D::toggle_model_objects_visibility(bool visible, const ModelObject if ( (gizmo_type == GLGizmosManager::FdmSupports || gizmo_type == GLGizmosManager::Seam || gizmo_type == GLGizmosManager::Cut - || gizmo_type == GLGizmosManager::FuzzySkin) + || gizmo_type == GLGizmosManager::FuzzySkin + || gizmo_type == GLGizmosManager::PaintedModifier) && !vol->is_modifier) { vol->force_neutral_color = true; } @@ -3426,7 +3427,8 @@ void GLCanvas3D::_render_scene(const Camera& camera, const Size& cnv_size) const bool show_exclusion_intersections = m_show_bed && (!m_main_toolbar.is_enabled() || (gizmo_type != GLGizmosManager::FdmSupports && gizmo_type != GLGizmosManager::Seam && - gizmo_type != GLGizmosManager::MmSegmentation && gizmo_type != GLGizmosManager::FuzzySkin)); + gizmo_type != GLGizmosManager::MmSegmentation && gizmo_type != GLGizmosManager::FuzzySkin && + gizmo_type != GLGizmosManager::PaintedModifier)); if (show_exclusion_intersections) wxGetApp().plater()->get_partplate_list().render_exclusion_volume_intersections( camera.get_view_matrix(), camera.get_projection_matrix()); @@ -3842,6 +3844,9 @@ void GLCanvas3D::reload_scene(bool refresh_immediately, bool force_full_scene_re const ModelInstance* model_instance = model_object->instances[instance_idx]; for (int volume_idx = 0; volume_idx < (int)model_object->volumes.size(); ++volume_idx) { const ModelVolume* model_volume = model_object->volumes[volume_idx]; + // A painted modifier shares its host's mesh; its paint is shown by its gizmo only. + if (model_volume->is_painted_modifier()) + continue; if (m_canvas_type == ECanvasType::CanvasAssembleView) { if (model_volume->is_model_part()) model_volume_state.emplace_back(model_volume, model_instance->id(), GLVolume::CompositeID(object_idx, volume_idx, instance_idx)); @@ -4032,7 +4037,7 @@ void GLCanvas3D::reload_scene(bool refresh_immediately, bool force_full_scene_re const ModelObject &model_object = *m_model->objects[obj_idx]; for (int volume_idx = 0; volume_idx < (int)model_object.volumes.size(); ++ volume_idx) { const ModelVolume &model_volume = *model_object.volumes[volume_idx]; - if (m_canvas_type == ECanvasType::CanvasAssembleView && !model_volume.is_model_part()) + if ((m_canvas_type == ECanvasType::CanvasAssembleView && !model_volume.is_model_part()) || model_volume.is_painted_modifier()) continue; for (int instance_idx = 0; instance_idx < (int)model_object.instances.size(); ++ instance_idx) { const ModelInstance &model_instance = *model_object.instances[instance_idx]; @@ -5751,7 +5756,8 @@ void GLCanvas3D::on_mouse(wxMouseEvent& evt) && m_gizmos.get_current_type() != GLGizmosManager::Seam && m_gizmos.get_current_type() != GLGizmosManager::Cut && m_gizmos.get_current_type() != GLGizmosManager::MmSegmentation - && m_gizmos.get_current_type() != GLGizmosManager::FuzzySkin) { + && m_gizmos.get_current_type() != GLGizmosManager::FuzzySkin + && m_gizmos.get_current_type() != GLGizmosManager::PaintedModifier) { m_rectangle_selection.start_dragging(m_mouse.position, evt.ShiftDown() ? GLSelectionRectangle::Select : GLSelectionRectangle::Deselect); if (!has_mouse_capture()) // ORCA keep tracking mouse position while drag active and cursor not in window bounds @@ -5951,7 +5957,7 @@ void GLCanvas3D::on_mouse(wxMouseEvent& evt) const Vec3d rot = (Vec3d(pos.x(), pos.y(), 0.) - m_mouse.drag.start_position_3D) * (PI * TRACKBALLSIZE / 180.) * mult; if (this->m_canvas_type == ECanvasType::CanvasAssembleView || m_gizmos.get_current_type() == GLGizmosManager::FdmSupports || m_gizmos.get_current_type() == GLGizmosManager::Seam || m_gizmos.get_current_type() == GLGizmosManager::MmSegmentation || - m_gizmos.get_current_type() == GLGizmosManager::FuzzySkin) { + m_gizmos.get_current_type() == GLGizmosManager::FuzzySkin || m_gizmos.get_current_type() == GLGizmosManager::PaintedModifier) { // Orca: Reuse the centralized pivot policy for scene-oriented tools. const std::optional rotate_target = get_camera_orbit_target(ECameraNavigationType::Mouse); if (rotate_target.has_value()) @@ -12918,7 +12924,7 @@ std::optional GLCanvas3D::get_camera_orbit_target(ECameraNavigationType n const GLGizmosManager::EType gizmo_type = m_gizmos.get_current_type(); const bool use_scene_target = m_canvas_type == ECanvasType::CanvasAssembleView || gizmo_type == GLGizmosManager::FdmSupports || gizmo_type == GLGizmosManager::Seam || - gizmo_type == GLGizmosManager::MmSegmentation || gizmo_type == GLGizmosManager::FuzzySkin; + gizmo_type == GLGizmosManager::MmSegmentation || gizmo_type == GLGizmosManager::FuzzySkin || gizmo_type == GLGizmosManager::PaintedModifier; if (use_scene_target) { if (!m_selection.is_empty()) return m_selection.get_bounding_box().center(); diff --git a/src/slic3r/GUI/GUI_Factories.cpp b/src/slic3r/GUI/GUI_Factories.cpp index 2674610f5a..b091c519bf 100644 --- a/src/slic3r/GUI/GUI_Factories.cpp +++ b/src/slic3r/GUI/GUI_Factories.cpp @@ -35,6 +35,7 @@ #include #include #include +#include #include #include "libslic3r/Utils.hpp" #include "libslic3r/Format/bbs_3mf.hpp" @@ -367,7 +368,7 @@ wxBitmap SettingsFactory::get_category_bitmap(const std::string& category_name, //------------------------------------- // Note: id accords to type of the sub-object (adding volume), so sequence of the menu items is important -static const constexpr std::array, 11> ADD_VOLUME_MENU_ITEMS = {{ +static const constexpr std::array, 12> ADD_VOLUME_MENU_ITEMS = {{ // menu_item Name menu_item bitmap name {L("Add Part"), "menu_add_part" }, // ~ModelVolumeType::MODEL_PART {L("Add Negative Part"), "menu_add_negative" }, // ~ModelVolumeType::NEGATIVE_VOLUME @@ -381,6 +382,7 @@ static const constexpr std::array, 11> ADD {L("Add Precise Seam"), "menu_precise_seam_enforced"}, // ~ModelVolumeType::PRECISE_SEAM_ENFORCED {L("Add Precise Seam"), "menu_precise_seam_blocked"}, // ~ModelVolumeType::PRECISE_SEAM_BLOCKED {L("Add Precise Seam"), "menu_precise_seam_neutral"}, // ~ModelVolumeType::PRECISE_SEAM_NEUTRAL + {L("Add Painted Modifier"), "menu_add_painted_modifier"}, // ~ModelVolumeType::PAINTED_MODIFIER }}; // Note: id accords to type of the sub-object (adding volume), so sequence of the menu items is important @@ -793,6 +795,9 @@ void MenuFactory::append_menu_items_add_volume(wxMenu* menu) if (type >= int(ModelVolumeType::PRECISE_SEAM_LEFT) && type <= int(ModelVolumeType::PRECISE_SEAM_NEUTRAL)) continue; + // Added next to the mesh modifiers below, as it has no shape to choose. + if (type == int(ModelVolumeType::PAINTED_MODIFIER)) + continue; auto& item = ADD_VOLUME_MENU_ITEMS[type]; @@ -804,11 +809,21 @@ void MenuFactory::append_menu_items_add_volume(wxMenu* menu) wxMenu* sub_menu = append_submenu_add_generic(menu, ModelVolumeType(type)); append_submenu(menu, sub_menu, wxID_ANY, _(item.first), "", icon_name, []() { return obj_list()->is_instance_or_object_selected(); }, m_parent); + + if (type == int(ModelVolumeType::PARAMETER_MODIFIER)) + append_menu_item_add_painted_modifier(menu, []() { return obj_list()->is_instance_or_object_selected(); }); } append_menu_item_layers_editing(menu); } +wxMenuItem* MenuFactory::append_menu_item_add_painted_modifier(wxMenu* menu, std::function enable_condition) +{ + const auto &item = ADD_VOLUME_MENU_ITEMS[int(ModelVolumeType::PAINTED_MODIFIER)]; + return append_menu_item(menu, wxID_ANY, _(item.first), _L("Add a modifier whose shape is painted on the part"), + [](wxCommandEvent&) { obj_list()->add_painted_modifier(); }, item.second, menu, enable_condition, m_parent); +} + wxMenuItem* MenuFactory::append_menu_item_layers_editing(wxMenu* menu) { return append_menu_item(menu, wxID_ANY, _L("Height Range Modifier"), "", @@ -1876,6 +1891,10 @@ void MenuFactory::create_bbl_part_menu() m_part_transform_menu = append_menu_item_transform(&m_part_menu, false /*multi_selection*/, true /*mirror*/, true /*is_scalable*/); append_menu_item_align_distribute(menu); append_menu_item_modify(&m_part_menu, false /*multi_selection*/, true /*splittable*/, true /*mesh*/, false /*mesh_boolean*/); + append_menu_item_add_painted_modifier(menu, []() { + const ModelVolume *volume = obj_list()->get_selected_model_volume(); + return volume != nullptr && volume->is_model_part(); + }); append_menu_item_edit_text(menu); //m_part_geometry_pos = m_part_menu.GetMenuItemCount(); // pos for geometry related items @@ -1894,6 +1913,23 @@ void MenuFactory::create_bbl_part_menu() append_menu_item_more(&m_part_menu, false /*multi_selection*/, true /*disk_op*/, false /*export_op*/); } +void MenuFactory::create_painted_modifier_menu() +{ + wxMenu* menu = &m_painted_modifier_menu; + + append_menu_item(menu, wxID_ANY, _L("Edit Painting"), _L("Paint the area of the selected painted modifier"), + [](wxCommandEvent&) { + if (const ModelVolume *volume = obj_list()->get_selected_model_volume(); volume != nullptr && volume->is_painted_modifier()) + obj_list()->open_painted_modifier_tool(*volume); + }, "", menu); + append_menu_item_rename(menu); + // The scene selects the whole instance while a painted modifier is selected, so delete through the list. + append_menu_item(menu, wxID_ANY, _L("Delete"), _L("Delete the selected painted modifier"), + [](wxCommandEvent&) { obj_list()->remove(); }, "menu_delete", menu); + menu->AppendSeparator(); + append_menu_item_per_object_process(menu); +} + void MenuFactory::create_bbl_assemble_part_menu() { wxMenu* menu = &m_assemble_part_menu; @@ -2097,6 +2133,7 @@ void MenuFactory::init(wxWindow* parent) create_svg_part_menu(); create_extra_object_menu(); create_bbl_part_menu(); + create_painted_modifier_menu(); create_bbl_assemble_object_menu(); create_bbl_assemble_part_menu(); @@ -2159,6 +2196,12 @@ wxMenu* MenuFactory::part_menu() return &m_part_menu; } +wxMenu* MenuFactory::painted_modifier_menu() +{ + append_menu_item_change_filament(&m_painted_modifier_menu); + return &m_painted_modifier_menu; +} + wxMenu* MenuFactory::text_part_menu() { append_menu_item_per_object_settings(&m_text_part_menu, FindPositionById(&m_text_part_menu, m_text_project_marker) + 1); @@ -2572,7 +2615,7 @@ void MenuFactory::append_menu_item_change_filament(wxMenu* menu, size_t pos) if (sels.Count() == 1) { const auto sel_vol = obj_list()->get_selected_model_volume(); - if (sel_vol && sel_vol->type() != ModelVolumeType::MODEL_PART && sel_vol->type() != ModelVolumeType::PARAMETER_MODIFIER) + if (sel_vol && ! sel_vol->is_model_part() && ! sel_vol->is_region_modifier()) return; } @@ -2592,7 +2635,7 @@ void MenuFactory::append_menu_item_change_filament(wxMenu* menu, size_t pos) const ModelConfig& config = obj_list()->get_item_config(sels[0]); // BBS const auto sel_vol = obj_list()->get_selected_model_volume(); - if (sel_vol && sel_vol->type() == ModelVolumeType::PARAMETER_MODIFIER) + if (sel_vol && sel_vol->is_region_modifier()) initial_extruder = config.has("extruder") ? config.extruder() : 0; else initial_extruder = config.has("extruder") ? config.extruder() : 1; @@ -2601,7 +2644,8 @@ void MenuFactory::append_menu_item_change_filament(wxMenu* menu, size_t pos) // BBS bool has_modifier = false; for (auto sel : sels) { - if (obj_list()->GetModel()->GetVolumeType(sel) == ModelVolumeType::PARAMETER_MODIFIER) { + if (const ModelVolumeType type = obj_list()->GetModel()->GetVolumeType(sel); + type == ModelVolumeType::PARAMETER_MODIFIER || type == ModelVolumeType::PAINTED_MODIFIER) { has_modifier = true; break; } diff --git a/src/slic3r/GUI/GUI_Factories.hpp b/src/slic3r/GUI/GUI_Factories.hpp index d2ab760205..140fcbdf64 100644 --- a/src/slic3r/GUI/GUI_Factories.hpp +++ b/src/slic3r/GUI/GUI_Factories.hpp @@ -6,6 +6,7 @@ #include #include #include +#include #include @@ -88,6 +89,7 @@ public: wxMenu* part_menu(); wxMenu* text_part_menu(); wxMenu* svg_part_menu(); + wxMenu* painted_modifier_menu(); wxMenu* instance_menu(); wxMenu* layer_menu(); wxMenu* multi_selection_menu(); @@ -122,6 +124,7 @@ private: MenuWithSeparators m_svg_part_menu; int m_svg_props_marker; int m_svg_project_marker; + MenuWithSeparators m_painted_modifier_menu; MenuWithSeparators m_sla_object_menu; MenuWithSeparators m_default_menu; MenuWithSeparators m_instance_menu; @@ -152,6 +155,7 @@ private: //BBS: add bbl object menu void create_extra_object_menu(); void create_bbl_part_menu(); + void create_painted_modifier_menu(); void create_bbl_assemble_object_menu(); void create_bbl_assemble_part_menu(); @@ -164,6 +168,7 @@ private: void append_menu_item_add_svg(wxMenu *menu, ModelVolumeType type, bool is_submenu_item = true); void append_menu_items_add_volume(wxMenu* menu); wxMenuItem* append_menu_item_layers_editing(wxMenu* menu); + wxMenuItem* append_menu_item_add_painted_modifier(wxMenu* menu, std::function enable_condition); wxMenuItem* append_menu_item_settings(wxMenu* menu); wxMenuItem* append_menu_item_change_type(wxMenu* menu); wxMenuItem* append_menu_item_instance_to_object(wxMenu* menu); diff --git a/src/slic3r/GUI/GUI_ObjectList.cpp b/src/slic3r/GUI/GUI_ObjectList.cpp index bc3e95bed1..a6478b3b99 100644 --- a/src/slic3r/GUI/GUI_ObjectList.cpp +++ b/src/slic3r/GUI/GUI_ObjectList.cpp @@ -105,9 +105,11 @@ #include #endif /* __WXMSW__ */ #include "Gizmos/GLGizmoScale.hpp" +#include "Gizmos/GLGizmoPaintedModifier.hpp" #include "Gizmos/GLGizmosManager.hpp" #include "libslic3r/TriangleMeshDeal.hpp" +#include "libslic3r/TriangleSelector.hpp" class wxMenu; namespace Slic3r { class Step; } @@ -478,6 +480,7 @@ void ObjectList::create_objects_ctrl() bmp_choice_renderer->set_has_default_extruder([this, get_filament_context_item]() { const wxDataViewItem item = get_filament_context_item(); return m_objects_model->GetVolumeType(item) == ModelVolumeType::PARAMETER_MODIFIER || + m_objects_model->GetVolumeType(item) == ModelVolumeType::PAINTED_MODIFIER || m_objects_model->GetItemType(item) == itLayer; }); AppendColumn(new wxDataViewColumn(_L("Fila."), bmp_choice_renderer, @@ -1695,7 +1698,8 @@ void ObjectList::show_context_menu(const bool evt_context_menu) return; const ModelVolume *volume = object(obj_idx)->volumes[vol_idx]; - menu = volume->is_text() ? plater->text_part_menu() : + menu = volume->is_painted_modifier() ? plater->painted_modifier_menu() : + volume->is_text() ? plater->text_part_menu() : volume->is_svg() ? plater->svg_part_menu() : // ORCA fixes missing "Edit SVG" item for Add/Negative/Modifier SVG objects in object list plater->part_menu(); } @@ -2008,6 +2012,11 @@ bool ObjectList::can_drop(const wxDataViewItem& item, int& src_obj_id, int& src_ if (dragged_item_v_type == item_v_type && dragged_item_v_type != ModelVolumeType::MODEL_PART) return true; + // Mesh and painted modifiers share one group: their order in the list is their priority. + auto is_region_modifier = [](ModelVolumeType t) { return t == ModelVolumeType::PARAMETER_MODIFIER || t == ModelVolumeType::PAINTED_MODIFIER; }; + if (is_region_modifier(dragged_item_v_type) && is_region_modifier(item_v_type)) + return true; + // Use tree item types: hidden cut connectors make tree indices differ from volumes indices. if (is_precise_seam(dragged_item_v_type) && is_precise_seam(item_v_type)) // Allow reordering only within the strong or weak modifier group. @@ -3066,6 +3075,12 @@ bool ObjectList::del_subobject_from_object(const int obj_idx, const int idx, con take_snapshot(_u8L("Delete part")); + if (volume->is_model_part()) + for (int pm_idx = int(object->volumes.size()) - 1; pm_idx > idx; --pm_idx) + if (const ModelVolume *pm = object->volumes[pm_idx]; pm->is_painted_modifier() && object->painted_modifier_host(*pm) == volume) { + m_objects_model->Delete(m_objects_model->GetItemByVolumeId(obj_idx, m_objects_model->get_real_volume_index_in_ui(obj_idx, pm_idx))); + object->delete_volume(pm_idx); + } object->delete_volume(idx); if (object->volumes.size() == 1) { @@ -4019,6 +4034,8 @@ void ObjectList::part_selection_changed() const ModelVolume *volume = (*m_objects)[obj_idx]->volumes[volume_id]; enable_manipulation = !((*m_objects)[obj_idx]->is_cut() && (volume->is_cut_connector() || volume->is_model_part())); + if (volume->is_painted_modifier() && GetSelectedItemsCount() == 1) + open_painted_modifier_tool(*volume); } else if (type & itInstance) { og_name = _L("Instance manipulation"); @@ -5130,6 +5147,11 @@ void ObjectList::update_selections() if ( ( m_selection_mode & (smSettings|smLayer|smLayerRoot|smVolume) ) == 0) m_selection_mode = smInstance; + // The scene shows the instance of a selected painted modifier. + if (GetSelectedItemsCount() == 1 && is_painted_modifier_item(GetSelection()) && selection.is_single_full_instance() && + m_objects_model->GetObjectIdByItem(GetSelection()) == selection.get_object_idx()) + return; + // We doesn't update selection if itSettings | itLayerRoot | itLayer Item for the current object/part is selected if (GetSelectedItemsCount() == 1 && m_objects_model->GetItemType(GetSelection()) & (itSettings | itLayerRoot | itLayer)) { @@ -5344,7 +5366,14 @@ void ObjectList::update_selections_on_canvas() const ItemType& type = m_objects_model->GetItemType(item); const int obj_idx = m_objects_model->GetObjectIdByItem(item); - if (type == itVolume) { + if (type == itVolume && is_painted_modifier_item(item)) { + // A painted modifier has no geometry in the scene: select its instance, so that its paint tool may be opened. + mode = Selection::Instance; + int inst_idx = selection.get_object_idx() == obj_idx && selection.get_instance_idx() != -1 ? selection.get_instance_idx() : 0; + std::vector idxs = selection.get_volume_idxs_from_instance(obj_idx, inst_idx); + volume_idxs.insert(volume_idxs.end(), idxs.begin(), idxs.end()); + } + else if (type == itVolume) { int vol_idx = m_objects_model->GetVolumeIdByItem(item); vol_idx = m_objects_model->get_real_volume_index_in_3d(obj_idx,vol_idx); std::vector idxs = selection.get_volume_idxs_from_volume(obj_idx, std::max(instance_idx, 0), vol_idx); @@ -5775,6 +5804,60 @@ bool ObjectList::fix_cut_selection(wxDataViewItemArray &sels) return false; } +bool ObjectList::is_painted_modifier_item(const wxDataViewItem &item) const +{ + if (!item || m_objects_model->GetItemType(item) != itVolume) + return false; + const int obj_idx = m_objects_model->GetObjectIdByItem(item); + const int vol_idx = m_objects_model->get_real_volume_index_in_3d(obj_idx, m_objects_model->GetVolumeIdByItem(item)); + return obj_idx >= 0 && obj_idx < int(m_objects->size()) && vol_idx >= 0 && vol_idx < int((*m_objects)[obj_idx]->volumes.size()) && + (*m_objects)[obj_idx]->volumes[vol_idx]->is_painted_modifier(); +} + +ModelVolume *ObjectList::add_painted_modifier(int obj_idx, const ModelVolume &host, const TriangleSelector *paint) +{ + ModelObject &model_object = *(*m_objects)[obj_idx]; + int count = 1; + for (const ModelVolume *v : model_object.volumes) + count += v->is_painted_modifier(); + ModelVolume *painted_modifier = model_object.add_painted_modifier(host); + painted_modifier->name = into_u8(format_wxstr(_L("Painted modifier %1%"), count)); + if (paint != nullptr) + painted_modifier->painted_modifier_facets.set(*paint); + reorder_volumes_and_get_selection(obj_idx); + changed_object(obj_idx); + return painted_modifier; +} + +void ObjectList::open_painted_modifier_tool(const ModelVolume &painted_modifier) +{ + GLGizmosManager &gizmos_mgr = wxGetApp().plater()->get_view3D_canvas3D()->get_gizmos_manager(); + if (auto *gizmo = dynamic_cast(gizmos_mgr.get_gizmo(GLGizmosManager::EType::PaintedModifier))) + gizmo->set_target(&painted_modifier); + if (gizmos_mgr.get_current_type() != GLGizmosManager::EType::PaintedModifier) + gizmos_mgr.open_gizmo(GLGizmosManager::EType::PaintedModifier); +} + +void ObjectList::add_painted_modifier() +{ + const int obj_idx = get_selected_obj_idx(); + if (obj_idx < 0) + return; + ModelObject &model_object = *(*m_objects)[obj_idx]; + // Paint on the selected part, or on the first part of the selected object. + const ModelVolume *host = get_selected_model_volume(); + if (host == nullptr || ! host->is_model_part()) { + auto it = std::find_if(model_object.volumes.begin(), model_object.volumes.end(), [](const ModelVolume *v) { return v->is_model_part(); }); + if (it == model_object.volumes.end()) + return; + host = *it; + } + take_snapshot(_u8L("Add painted modifier")); + ModelVolume *painted_modifier = add_painted_modifier(obj_idx, *host); + select_item(ObjectVolumeID{&model_object, painted_modifier}); + wxGetApp().params_panel()->switch_to_object(true); +} + ModelVolume* ObjectList::get_selected_model_volume() { wxDataViewItem item = GetSelection(); @@ -6051,7 +6134,8 @@ void ObjectList::set_volume_type(ModelVolumeType new_type, bool preserve_ps_subt // --- Collect selected volumes from the object tree, falling back to the 3D canvas --- std::vector volumes; auto add_volume = [&volumes](int obj_idx, ModelVolume* volume) { - if (volume == nullptr) + // A painted modifier has no shape of its own to keep as another type. + if (volume == nullptr || volume->is_painted_modifier()) return; auto it = std::find_if(volumes.begin(), volumes.end(), [volume](const VolumeSelection& other) { return other.volume == volume; }); if (it == volumes.end()) @@ -7025,8 +7109,8 @@ void ObjectList::set_extruder_for_selected_items(const int extruder) int vol_idx = m_objects_model->GetVolumeIdByItem(item); vol_idx = m_objects_model->get_real_volume_index_in_3d(obj_idx, vol_idx); if ((obj_idx < m_objects->size()) && (obj_idx < (*m_objects)[obj_idx]->volumes.size())) { - auto volume_type = (*m_objects)[obj_idx]->volumes[vol_idx]->type(); - if (volume_type != ModelVolumeType::MODEL_PART && volume_type != ModelVolumeType::PARAMETER_MODIFIER) + const ModelVolume *volume = (*m_objects)[obj_idx]->volumes[vol_idx]; + if (! volume->is_model_part() && ! volume->is_region_modifier()) continue; } } diff --git a/src/slic3r/GUI/GUI_ObjectList.hpp b/src/slic3r/GUI/GUI_ObjectList.hpp index 32657721b9..9b125e9e9a 100644 --- a/src/slic3r/GUI/GUI_ObjectList.hpp +++ b/src/slic3r/GUI/GUI_ObjectList.hpp @@ -37,6 +37,7 @@ class DynamicPrintConfig; class ModelConfig; class ModelObject; class ModelVolume; +class TriangleSelector; class TriangleMesh; enum class ModelVolumeType : int; @@ -498,6 +499,13 @@ public: //BBS: remove const qualifier void set_extruder_for_selected_items(const int extruder); wxDataViewItemArray reorder_volumes_and_get_selection(int obj_idx, std::function add_to_selection = nullptr); + // Adds a painted modifier on a part to the model and to the list, without an undo snapshot. + // The paint, if any, is stored before the scene refresh, which rebuilds an open paint tool from the model. + ModelVolume* add_painted_modifier(int obj_idx, const ModelVolume &host, const TriangleSelector *paint = nullptr); + // Adds a painted modifier on the selected part or object and selects it. + void add_painted_modifier(); + void open_painted_modifier_tool(const ModelVolume &painted_modifier); + bool is_painted_modifier_item(const wxDataViewItem &item) const; void apply_volumes_order(); // BBS diff --git a/src/slic3r/GUI/GUI_ObjectTable.cpp b/src/slic3r/GUI/GUI_ObjectTable.cpp index 85a3b65f84..f64ac6794c 100644 --- a/src/slic3r/GUI/GUI_ObjectTable.cpp +++ b/src/slic3r/GUI/GUI_ObjectTable.cpp @@ -382,10 +382,11 @@ void GridCellFilamentsRenderer::Draw(wxGrid &grid, wxGridCellAttr &attr, wxDC &d (grid_row->model_volume_type != ModelVolumeType::SUPPORT_BLOCKER) && \ (grid_row->model_volume_type != ModelVolumeType::SUPPORT_ENFORCER) && \ (grid_row->model_volume_type != ModelVolumeType::PARAMETER_MODIFIER) && \ + (grid_row->model_volume_type != ModelVolumeType::PAINTED_MODIFIER) && \ !is_precise_seam(grid_row->model_volume_type)) { // Precise Seam is non-printing helper geometry dc.DrawBitmap(*bitmap, wxPoint(rect.x + offset_x, rect.y + offset_y)); } - else if (grid_row->model_volume_type == ModelVolumeType::PARAMETER_MODIFIER){ + else if (grid_row->model_volume_type == ModelVolumeType::PARAMETER_MODIFIER || grid_row->model_volume_type == ModelVolumeType::PAINTED_MODIFIER){ dc.DrawText(_L("Default"), wxPoint(rect.x + offset_x, rect.y + offset_y)); } diff --git a/src/slic3r/GUI/Gizmos/GLGizmoPaintedModifier.cpp b/src/slic3r/GUI/Gizmos/GLGizmoPaintedModifier.cpp new file mode 100644 index 0000000000..dfcc750a42 --- /dev/null +++ b/src/slic3r/GUI/Gizmos/GLGizmoPaintedModifier.cpp @@ -0,0 +1,388 @@ +#include "GLGizmoPaintedModifier.hpp" + +#include "libslic3r/Color.hpp" +#include "libslic3r/Model.hpp" +#include "libslic3r/ObjectID.hpp" +#include "libslic3r/TriangleSelector.hpp" + +#include "slic3r/GUI/3DScene.hpp" +#include "slic3r/GUI/Event.hpp" +#include "slic3r/GUI/GLCanvas3D.hpp" +#include "slic3r/GUI/GUI.hpp" +#include "slic3r/GUI/GUI_App.hpp" +#include "slic3r/GUI/GUI_ObjectList.hpp" +#include "slic3r/GUI/GUI_Utils.hpp" +#include "slic3r/GUI/I18N.hpp" +#include "slic3r/GUI/ImGuiWrapper.hpp" +#include "slic3r/GUI/Plater.hpp" +#include "slic3r/GUI/Gizmos/GLGizmoBase.hpp" +#include "slic3r/GUI/Gizmos/GLGizmoPainterBase.hpp" +#include "slic3r/GUI/Gizmos/GLGizmosCommon.hpp" +#include "slic3r/GUI/Gizmos/GLGizmosManager.hpp" +#include "slic3r/Utils/UndoRedo.hpp" +#include "GLGizmoUtils.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace Slic3r::GUI { + +GLGizmoPaintedModifier::GLGizmoPaintedModifier(GLCanvas3D &parent, const std::string &icon_filename, unsigned int sprite_id) + : GLGizmoPainterBase(parent, icon_filename, sprite_id), m_current_tool(ImGui::CircleButtonIcon) +{ +} + +std::string GLGizmoPaintedModifier::on_get_name() const +{ + return _u8L("Painted modifier"); +} + +bool GLGizmoPaintedModifier::on_init() +{ + const wxString ctrl = GUI::shortkey_ctrl_prefix(); + const wxString shift = GUI::shortkey_shift_prefix(); + + m_desc["target"] = _L("Modifier"); + m_desc["new"] = _L("New painted modifier"); + m_desc["depth"] = _L("Depth"); + m_desc["depth_tooltip"] = _L("How far the painted area reaches into the part, measured from the painted surface.\n" + "0 reaches across the whole part, up to the nearest unpainted surface."); + m_desc["no_host"] = _L("The part this modifier was painted on has been removed."); + m_desc["remove_all"] = _L("Erase all"); + m_desc["tool_type"] = _L("Tool type"); + m_desc["cursor_size"] = _L("Brush size"); + m_desc["smart_fill_angle"] = _L("Smart fill angle"); + m_desc["add_area"] = _L("Paint the modifier area"); + m_desc["remove_area"] = _L("Erase the modifier area"); + + const std::pair add_shortcut = {_L("Left mouse button"), m_desc["add_area"]}; + const std::pair remove_shortcut = {shift + _L("Left mouse button"), m_desc["remove_area"]}; + m_shortcuts_brush = {add_shortcut, remove_shortcut, {ctrl + _L("Mouse wheel"), m_desc["cursor_size"]}}; + m_shortcuts_triangle = {add_shortcut, remove_shortcut}; + m_shortcuts_smart_fill = {add_shortcut, remove_shortcut, {ctrl + _L("Mouse wheel"), m_desc["smart_fill_angle"]}}; + return true; +} + +void GLGizmoPaintedModifier::on_shutdown() +{ + m_parent.use_slope(false); + m_parent.toggle_model_objects_visibility(true); +} + +void GLGizmoPaintedModifier::set_target(const ModelVolume *painted_modifier) +{ + const ObjectID id = painted_modifier ? painted_modifier->id() : ObjectID(); + if (id == m_target_id) + return; + m_target_id = id; + if (m_state == On) + update_from_model_object(false); +} + +ModelVolume *GLGizmoPaintedModifier::target(const ModelObject &mo) const +{ + if (m_target_id.invalid()) + return nullptr; + auto it = std::find_if(mo.volumes.begin(), mo.volumes.end(), [this](const ModelVolume *v) { return v->id() == m_target_id; }); + return it != mo.volumes.end() && (*it)->is_painted_modifier() ? *it : nullptr; +} + +bool GLGizmoPaintedModifier::is_mesh_paintable(int mesh_id) const +{ + return m_target_id.invalid() || mesh_id == m_target_mesh_id; +} + +void GLGizmoPaintedModifier::render_painter_gizmo() +{ + const Selection &selection = m_parent.get_selection(); + + glsafe(::glEnable(GL_BLEND)); + glsafe(::glEnable(GL_DEPTH_TEST)); + + render_triangles(selection); + m_c->object_clipper()->render_cut(); + m_c->instances_hider()->render_cut(); + render_cursor(); + + glsafe(::glDisable(GL_BLEND)); +} + +void GLGizmoPaintedModifier::render_tooltip_button(float x, float y) +{ + auto get_shortcuts = [this]() -> std::vector> { + switch (m_tool_type) { + case ToolType::BRUSH: return m_cursor_type == TriangleSelector::POINTER ? m_shortcuts_triangle : m_shortcuts_brush; + case ToolType::SMART_FILL: return m_shortcuts_smart_fill; + default: return {}; + } + }; + GLGizmoUtils::render_tooltip_button(m_imgui, m_parent, get_shortcuts(), x, y); +} + +void GLGizmoPaintedModifier::on_render_input_window(float x, float y, float bottom_limit) +{ + ModelObject *mo = m_c->selection_info()->model_object(); + if (!mo) + return; + ModelVolume *painted_modifier = target(*mo); + + float scale = m_parent.get_scale(); +#ifdef WIN32 + const int dpi = get_dpi_for_window(wxGetApp().GetTopWindow()); + scale *= float(dpi) / float(DPI_DEFAULT); +#endif // WIN32 + + y = std::min(y, bottom_limit - m_imgui->scaled(22.f)); +#if BBS_TOOLBAR_ON_TOP + GizmoImguiSetNextWIndowPos(x, y, ImGuiCond_Always, 0.0f, 0.0f); +#else + GizmoImguiSetNextWIndowPos(x, y, ImGuiCond_Always, 1.0f, 0.0f); +#endif + + ImGuiWrapper::push_toolbar_style(m_parent.get_scale()); + const float f_scale = m_parent.get_gizmos_manager().get_layout_scale(); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(6.0f, 4.0f * f_scale)); + + GizmoImguiBegin(get_name(), ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar); + + const float space_size = m_imgui->get_style_scaling() * 8; + const float sliders_left_width = std::max({m_imgui->calc_text_size(m_desc["cursor_size"]).x, m_imgui->calc_text_size(m_desc["smart_fill_angle"]).x, + m_imgui->calc_text_size(m_desc["depth"]).x, m_imgui->calc_text_size(m_desc["target"]).x}) + + m_imgui->scaled(1.5f); + const float sliders_width = m_imgui->scaled(7.0f); + const float drag_left_width = ImGui::GetStyle().WindowPadding.x + sliders_width - space_size; + const float slider_icon_width = m_imgui->get_slider_icon_size().x; + const float empty_button_width = m_imgui->calc_button_size("").x; + const float max_tooltip_width = ImGui::GetFontSize() * 20.0f; + + // The painted modifier the strokes go to, or a new one created by the next stroke. + std::vector painted_modifiers; + std::vector options; + int selection = -1; + for (ModelVolume *mv : mo->volumes) + if (mv->is_painted_modifier()) { + if (mv == painted_modifier) + selection = int(painted_modifiers.size()); + options.push_back(mv->name + "##" + std::to_string(painted_modifiers.size())); + painted_modifiers.push_back(mv); + } + options.push_back(into_u8(m_desc["new"]) + "##new"); + if (selection < 0) + selection = int(options.size()) - 1; + ImGuiWrapper::push_combo_style(m_parent.get_scale()); + if (m_imgui->combo(m_desc["target"], options, selection, 0, sliders_left_width, sliders_width + slider_icon_width * 1.5f + space_size)) { + ModelVolume *selected = selection < int(painted_modifiers.size()) ? painted_modifiers[selection] : nullptr; + set_target(selected); + if (selected) + wxGetApp().obj_list()->select_item(ObjectVolumeID{mo, selected}); + } + ImGuiWrapper::pop_combo_style(); + + m_imgui->disabled_begin(painted_modifier == nullptr); + ImGui::AlignTextToFramePadding(); + m_imgui->text(m_desc["depth"]); + ImGui::SameLine(sliders_left_width); + ImGui::PushItemWidth(sliders_width); + ImGui::BBLDragFloat("##painted_modifier_depth", &m_depth, 0.1f, 0.f, 1000.f, "%.2f mm"); + if (painted_modifier && ImGui::IsItemDeactivatedAfterEdit() && std::max(0.f, m_depth) != painted_modifier->painted_modifier_depth) { + Plater::TakeSnapshot snapshot(wxGetApp().plater(), _u8L("Change painted modifier depth"), UndoRedo::SnapshotType::GizmoAction); + painted_modifier->painted_modifier_depth = std::max(0.f, m_depth); + m_parent.post_event(SimpleEvent(EVT_GLCANVAS_SCHEDULE_BACKGROUND_PROCESS)); + } + if (ImGui::IsItemHovered()) + m_imgui->tooltip(m_desc["depth_tooltip"], max_tooltip_width); + m_imgui->disabled_end(); + + ImGui::Separator(); + + ImGui::AlignTextToFramePadding(); + m_imgui->text(m_desc["tool_type"]); + + const std::array tool_ids = {ImGui::CircleButtonIcon, ImGui::SphereButtonIcon, ImGui::TriangleButtonIcon, ImGui::FillButtonIcon}; + const std::array icons = m_is_dark_mode ? + std::array{ImGui::CircleButtonDarkIcon, ImGui::SphereButtonDarkIcon, ImGui::TriangleButtonDarkIcon, ImGui::FillButtonDarkIcon} : + tool_ids; + const std::array tool_tips = {_L("Circle"), _L("Sphere"), _L("Triangle"), _L("Fill")}; + for (int i = 0; i < int(tool_ids.size()); i++) { + if (i != 0) + ImGui::SameLine((empty_button_width + m_imgui->scaled(1.75f)) * i + m_imgui->scaled(1.5f)); + + const bool is_active = m_current_tool == tool_ids[i]; + ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, 1.f); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 3.f * scale); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(4.f * scale, 4.f * scale)); + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1, 1, 1, 1)); + ImGui::PushStyleColor(ImGuiCol_Button, is_active ? ImVec4(0.f, .59f, .53f, .25f) : ImVec4(0, 0, 0, 0)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, is_active ? ImVec4(0.f, .59f, .53f, .25f) : ImVec4(.6f, .6f, .6f, .2f)); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, is_active ? ImVec4(0.f, .59f, .53f, .30f) : ImVec4(0, 0, 0, 0)); + ImGui::PushStyleColor(ImGuiCol_Border, is_active ? ImGuiWrapper::COL_ORCA : ImVec4(0, 0, 0, 0)); + ImGui::PushStyleColor(ImGuiCol_BorderActive, is_active ? ImGuiWrapper::COL_ORCA : ImVec4(0, 0, 0, 0)); + const bool btn_clicked = m_imgui->glyph_button(icons[i], ImVec2(16.f * scale, 16.f * scale)); + ImGui::PopStyleColor(6); + ImGui::PopStyleVar(3); + + if (btn_clicked && m_current_tool != tool_ids[i]) { + m_current_tool = tool_ids[i]; + for (auto &triangle_selector : m_triangle_selectors) { + triangle_selector->seed_fill_unselect_all_triangles(); + triangle_selector->request_update_render_data(); + } + } + if (ImGui::IsItemHovered()) + m_imgui->tooltip(tool_tips[i], max_tooltip_width); + } + + ImGui::Dummy(ImVec2(0.0f, ImGui::GetFontSize() * 0.1)); + + if (m_current_tool == ImGui::CircleButtonIcon || m_current_tool == ImGui::SphereButtonIcon) { + m_cursor_type = m_current_tool == ImGui::CircleButtonIcon ? TriangleSelector::CursorType::CIRCLE : TriangleSelector::CursorType::SPHERE; + m_tool_type = ToolType::BRUSH; + + ImGui::AlignTextToFramePadding(); + m_imgui->text(m_desc["cursor_size"]); + ImGui::SameLine(sliders_left_width); + ImGui::PushItemWidth(sliders_width); + m_imgui->bbl_slider_float_style("##cursor_radius", &m_cursor_radius, CursorRadiusMin, CursorRadiusMax, "%.2f", 1.0f, true); + ImGui::SameLine(drag_left_width + sliders_left_width); + ImGui::PushItemWidth(1.5 * slider_icon_width); + ImGui::BBLDragFloat("##cursor_radius_input", &m_cursor_radius, 0.05f, 0.0f, 0.0f, "%.2f"); + } else if (m_current_tool == ImGui::TriangleButtonIcon) { + m_cursor_type = TriangleSelector::CursorType::POINTER; + m_tool_type = ToolType::BRUSH; + } else { + assert(m_current_tool == ImGui::FillButtonIcon); + m_cursor_type = TriangleSelector::CursorType::POINTER; + m_tool_type = ToolType::SMART_FILL; + + ImGui::AlignTextToFramePadding(); + m_imgui->text(m_desc["smart_fill_angle"]); + const std::string format_str = std::string("%.f") + I18N::translate_utf8("°", "Face angle threshold," + "placed after the number with no whitespace in between."); + ImGui::SameLine(sliders_left_width); + ImGui::PushItemWidth(sliders_width); + if (m_imgui->bbl_slider_float_style("##smart_fill_angle", &m_smart_fill_angle, SmartFillAngleMin, SmartFillAngleMax, format_str.data(), 1.0f, true)) + for (auto &triangle_selector : m_triangle_selectors) { + triangle_selector->seed_fill_unselect_all_triangles(); + triangle_selector->request_update_render_data(); + } + ImGui::SameLine(drag_left_width + sliders_left_width); + ImGui::PushItemWidth(1.5 * slider_icon_width); + ImGui::BBLDragFloat("##smart_fill_angle_input", &m_smart_fill_angle, 0.05f, 0.0f, 0.0f, "%.2f"); + } + + ImGui::Separator(); + + render_tooltip_button(x, y); + + ImGui::SameLine(); + m_imgui->disabled_begin(painted_modifier == nullptr || m_target_mesh_id < 0 || painted_modifier->painted_modifier_facets.empty()); + if (m_imgui->button(m_desc["remove_all"])) { + Plater::TakeSnapshot snapshot(wxGetApp().plater(), _u8L("Reset selection"), UndoRedo::SnapshotType::GizmoAction); + m_triangle_selectors[m_target_mesh_id]->reset(); + m_triangle_selectors[m_target_mesh_id]->request_update_render_data(true); + update_model_object(); + m_parent.set_as_dirty(); + } + m_imgui->disabled_end(); + + ImGui::SameLine(); + GLGizmoUtils::begin_right_aligned_buttons({_L("Done")}); + if (m_imgui->button(_L("Done"))) + m_parent.reset_all_gizmos(); + + if (painted_modifier != nullptr && m_target_mesh_id < 0) { + ImGui::Separator(); + ImGui::PushStyleColor(ImGuiCol_Text, ImGuiWrapper::COL_WARNING); + m_imgui->text_wrapped(m_desc["no_host"], ImGui::GetContentRegionAvail().x); + ImGui::PopStyleColor(); + } + + ImGui::PopStyleVar(1); // ImGuiStyleVar_FramePadding + GizmoImguiEnd(); + ImGuiWrapper::pop_toolbar_style(); +} + +void GLGizmoPaintedModifier::update_model_object() +{ + ModelObject *mo = m_c->selection_info()->model_object(); + if (mo == nullptr) + return; + + ModelVolume *painted_modifier = target(*mo); + if (painted_modifier == nullptr) { + // The first stroke creates the painted modifier on the part it painted. + std::vector parts; + for (const ModelVolume *mv : mo->volumes) + if (mv->is_model_part()) + parts.push_back(mv); + for (int mesh_id = 0; mesh_id < int(std::min(parts.size(), m_triangle_selectors.size())); ++mesh_id) + if (m_triangle_selectors[mesh_id]->has_facets(EnforcerBlockerType::ENFORCER)) { + const ModelObjectPtrs &objects = wxGetApp().model().objects; + const int obj_idx = int(std::find(objects.begin(), objects.end(), mo) - objects.begin()); + // Adding it reloads the scene, which may rebuild this tool from the model: the stroke goes in with it. + painted_modifier = wxGetApp().obj_list()->add_painted_modifier(obj_idx, *parts[mesh_id], m_triangle_selectors[mesh_id].get()); + set_target(painted_modifier); + wxGetApp().obj_list()->select_item(ObjectVolumeID{mo, painted_modifier}); + return; + } + return; + } + + if (m_target_mesh_id >= 0 && painted_modifier->painted_modifier_facets.set(*m_triangle_selectors[m_target_mesh_id])) + m_parent.post_event(SimpleEvent(EVT_GLCANVAS_SCHEDULE_BACKGROUND_PROCESS)); +} + +void GLGizmoPaintedModifier::update_from_model_object(bool first_update) +{ + wxBusyCursor wait; + + m_triangle_selectors.clear(); + m_target_mesh_id = -1; + ModelObject *mo = m_c->selection_info()->model_object(); + if (mo == nullptr) + return; + mo->sync_painted_modifiers(); + + const ModelVolume *painted_modifier = target(*mo); + if (painted_modifier == nullptr && first_update) { + // Opened from the toolbar: continue with the last painted modifier of the object. + auto it = std::find_if(mo->volumes.rbegin(), mo->volumes.rend(), [](const ModelVolume *v) { return v->is_painted_modifier(); }); + if (it != mo->volumes.rend()) + painted_modifier = *it; + } + m_target_id = painted_modifier ? painted_modifier->id() : ObjectID(); + if (painted_modifier != nullptr) + m_depth = painted_modifier->painted_modifier_depth; + const ModelVolume *host = painted_modifier ? mo->painted_modifier_host(*painted_modifier) : nullptr; + + const std::vector ebt_colors = {GLVolume::NEUTRAL_COLOR, TriangleSelectorGUI::enforcers_color, TriangleSelectorGUI::blockers_color}; + int mesh_id = -1; + for (const ModelVolume *mv : mo->volumes) { + if (!mv->is_model_part()) + continue; + ++mesh_id; + m_triangle_selectors.emplace_back(std::make_unique(mv->mesh(), ebt_colors)); + if (mv == host) { + m_target_mesh_id = mesh_id; + // Reset of TriangleSelector is done inside TriangleSelectorGUI's constructor, so we don't need it to perform it again in deserialize(). + m_triangle_selectors.back()->deserialize(painted_modifier->painted_modifier_facets.get_data(), false); + } + m_triangle_selectors.back()->request_update_render_data(); + } +} + +wxString GLGizmoPaintedModifier::handle_snapshot_action_name(bool shift_down, GLGizmoPainterBase::Button button_down) const +{ + return shift_down ? _L("Erase the modifier area") : _L("Paint the modifier area"); +} + +} // namespace Slic3r::GUI diff --git a/src/slic3r/GUI/Gizmos/GLGizmoPaintedModifier.hpp b/src/slic3r/GUI/Gizmos/GLGizmoPaintedModifier.hpp new file mode 100644 index 0000000000..1c9b4cb202 --- /dev/null +++ b/src/slic3r/GUI/Gizmos/GLGizmoPaintedModifier.hpp @@ -0,0 +1,75 @@ +#pragma once + +#include "GLGizmoPainterBase.hpp" + +#include "libslic3r/ObjectID.hpp" +#include "libslic3r/TriangleSelector.hpp" +#include "slic3r/GUI/I18N.hpp" + +#include +#include +#include +#include + +#include + +namespace Slic3r { +class ModelObject; +class ModelVolume; +} // namespace Slic3r + +namespace Slic3r::GUI { + +class GLCanvas3D; + +// Paints the shape of one painted modifier on its host part, see docs/HLSD/painted-modifiers.md. +class GLGizmoPaintedModifier : public GLGizmoPainterBase +{ +public: + GLGizmoPaintedModifier(GLCanvas3D &parent, const std::string &icon_filename, unsigned int sprite_id); + + void render_painter_gizmo() override; + + // The painted modifier receiving the strokes. Without one, the next stroke creates it on the part painted. + void set_target(const ModelVolume *painted_modifier); + +protected: + void on_render_input_window(float x, float y, float bottom_limit) override; + std::string on_get_name() const override; + + wxString handle_snapshot_action_name(bool shift_down, Button button_down) const override; + + std::string get_gizmo_entering_text() const override { return _u8L("Entering painted modifier"); } + std::string get_gizmo_leaving_text() const override { return _u8L("Leaving painted modifier"); } + std::string get_action_snapshot_name() const override { return _u8L("Painted modifier editing"); } + + EnforcerBlockerType get_left_button_state_type() const override { return EnforcerBlockerType::ENFORCER; } + EnforcerBlockerType get_right_button_state_type() const override { return EnforcerBlockerType::NONE; } + bool is_mesh_paintable(int mesh_id) const override; + +private: + bool on_init() override; + + void update_model_object() override; + void update_from_model_object(bool first_update) override; + + void on_opening() override {} + void on_shutdown() override; + PainterGizmoType get_painter_type() const override { return PainterGizmoType::PAINTED_MODIFIER; } + + ModelVolume *target(const ModelObject &mo) const; + void render_tooltip_button(float x, float y); + + ObjectID m_target_id; + // Index of the target's host among the model parts, -1 when the target has no host. + int m_target_mesh_id { -1 }; + float m_depth { 0.f }; + wchar_t m_current_tool { 0 }; + + std::map m_desc; + std::vector> m_shortcuts_brush; + std::vector> m_shortcuts_triangle; + std::vector> m_shortcuts_smart_fill; +}; + +} // namespace Slic3r::GUI diff --git a/src/slic3r/GUI/Gizmos/GLGizmoPainterBase.cpp b/src/slic3r/GUI/Gizmos/GLGizmoPainterBase.cpp index d2d78fc1e5..af0acefa03 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoPainterBase.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoPainterBase.cpp @@ -1156,6 +1156,8 @@ void GLGizmoPainterBase::update_raycast_cache(const Vec2d& mouse_position, } } } + if (closest_hit_mesh_id != -1 && ! is_mesh_paintable(closest_hit_mesh_id)) + closest_hit_mesh_id = -1; m_rr = {mouse_position, closest_hit_mesh_id, closest_hit, closest_facet}; } diff --git a/src/slic3r/GUI/Gizmos/GLGizmoPainterBase.hpp b/src/slic3r/GUI/Gizmos/GLGizmoPainterBase.hpp index 7aa1f1bdca..ba9d135bd1 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmoPainterBase.hpp +++ b/src/slic3r/GUI/Gizmos/GLGizmoPainterBase.hpp @@ -38,7 +38,8 @@ enum class PainterGizmoType { SEAM, MM_SEGMENTATION, FUZZY_SKIN, - TEXTURE_DISPLACEMENT + TEXTURE_DISPLACEMENT, + PAINTED_MODIFIER }; class TriangleSelectorGUI : public TriangleSelector { @@ -255,6 +256,8 @@ protected: virtual EnforcerBlockerType get_left_button_state_type() const { return EnforcerBlockerType::ENFORCER; } virtual EnforcerBlockerType get_right_button_state_type() const { return EnforcerBlockerType::BLOCKER; } + // A hit on a model part that may not be painted counts as a miss, so that the part still occludes. + virtual bool is_mesh_paintable(int mesh_id) const { return true; } float m_cursor_radius = 1.f; // BBS diff --git a/src/slic3r/GUI/Gizmos/GLGizmosManager.cpp b/src/slic3r/GUI/Gizmos/GLGizmosManager.cpp index 38a15e7fb8..4c6a41386d 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmosManager.cpp +++ b/src/slic3r/GUI/Gizmos/GLGizmosManager.cpp @@ -16,6 +16,7 @@ //#include "slic3r/GUI/Gizmos/GLGizmoSlaSupports.hpp" #include "slic3r/GUI/Gizmos/GLGizmoFdmSupports.hpp" #include "slic3r/GUI/Gizmos/GLGizmoFuzzySkin.hpp" +#include "slic3r/GUI/Gizmos/GLGizmoPaintedModifier.hpp" #include "slic3r/GUI/Gizmos/GLGizmoBrimEars.hpp" #include "slic3r/GUI/Gizmos/GLGizmoCut.hpp" //#include "slic3r/GUI/Gizmos/GLGizmoFaceDetector.hpp" @@ -193,6 +194,9 @@ void GLGizmosManager::switch_gizmos_icon_filename() case(EType::FuzzySkin): gizmo->set_icon_filename(m_is_dark ? "toolbar_fuzzy_skin_paint_dark.svg" : "toolbar_fuzzy_skin_paint.svg"); break; + case(EType::PaintedModifier): + gizmo->set_icon_filename(m_is_dark ? "toolbar_painted_modifier_dark.svg" : "toolbar_painted_modifier.svg"); + break; case(EType::TextureDisplacement): // One shared icon in both themes (no dedicated dark variant yet) - but it must still be // *this* gizmo's icon. Handing it the fuzzy-skin one here quietly replaced the icon set at @@ -249,6 +253,7 @@ bool GLGizmosManager::init() m_gizmos.emplace_back(new GLGizmoSeam(m_parent, m_is_dark ? "toolbar_seam_dark.svg" : "toolbar_seam.svg", EType::Seam)); m_gizmos.emplace_back(new GLGizmoFuzzySkin(m_parent, m_is_dark ? "toolbar_fuzzy_skin_paint_dark.svg" : "toolbar_fuzzy_skin_paint.svg", EType::FuzzySkin)); m_gizmos.emplace_back(new GLGizmoMmuSegmentation(m_parent, m_is_dark ? "mmu_segmentation_dark.svg" : "mmu_segmentation.svg", EType::MmSegmentation)); + m_gizmos.emplace_back(new GLGizmoPaintedModifier(m_parent, m_is_dark ? "toolbar_painted_modifier_dark.svg" : "toolbar_painted_modifier.svg", EType::PaintedModifier)); // One shared icon (no dedicated dark variant yet); it recolours acceptably in both themes. m_gizmos.emplace_back(new GLGizmoTextureDisplacement(m_parent, "toolbar_texture_displacement.svg", EType::TextureDisplacement)); m_gizmos.emplace_back(new GLGizmoEmboss(m_parent, m_is_dark ? "toolbar_text_dark.svg" : "toolbar_text.svg", EType::Emboss)); @@ -500,7 +505,8 @@ void GLGizmosManager::set_hover_id(int id) void GLGizmosManager::update_section_view() { - if (m_current != FdmSupports && m_current != Seam && m_current != MmSegmentation && m_current != FuzzySkin && m_current != BrimEars) + if (m_current != FdmSupports && m_current != Seam && m_current != MmSegmentation && m_current != FuzzySkin && m_current != PaintedModifier && + m_current != BrimEars) return; CommonGizmosDataObjects::ObjectClipper* clipper = m_common_gizmos_data ? m_common_gizmos_data->object_clipper() : nullptr; @@ -607,6 +613,8 @@ bool GLGizmosManager::gizmo_event(SLAGizmoEventType action, const Vec2d& mouse_p return dynamic_cast(m_gizmos[Cut].get())->gizmo_event(action, mouse_position, shift_down, alt_down, control_down); else if (m_current == FuzzySkin) return dynamic_cast(m_gizmos[FuzzySkin].get())->gizmo_event(action, mouse_position, shift_down, alt_down, control_down); + else if (m_current == PaintedModifier) + return dynamic_cast(m_gizmos[PaintedModifier].get())->gizmo_event(action, mouse_position, shift_down, alt_down, control_down); else if (m_current == TextureDisplacement) return dynamic_cast(m_gizmos[TextureDisplacement].get())->gizmo_event(action, mouse_position, shift_down, alt_down, control_down); else if (m_current == MeshBoolean) @@ -622,6 +630,7 @@ bool GLGizmosManager::is_paint_gizmo() return m_current == EType::FdmSupports || m_current == EType::MmSegmentation || m_current == EType::FuzzySkin || + m_current == EType::PaintedModifier || m_current == EType::TextureDisplacement || m_current == EType::Seam; } @@ -731,7 +740,8 @@ bool GLGizmosManager::on_mouse_wheel(const wxMouseEvent &evt) { bool processed = false; - if (/*m_current == SlaSupports || m_current == Hollow ||*/ m_current == FdmSupports || m_current == Seam || m_current == MmSegmentation || m_current == FuzzySkin || m_current == BrimEars) { + if (/*m_current == SlaSupports || m_current == Hollow ||*/ m_current == FdmSupports || m_current == Seam || m_current == MmSegmentation || m_current == FuzzySkin || + m_current == PaintedModifier || m_current == BrimEars) { float rot = (float)evt.GetWheelRotation() / (float)evt.GetWheelDelta(); if (gizmo_event((rot > 0.f ? SLAGizmoEventType::MouseWheelUp : SLAGizmoEventType::MouseWheelDown), Vec2d::Zero(), evt.ShiftDown(), evt.AltDown() // BBS @@ -1568,6 +1578,8 @@ std::string get_name_from_gizmo_etype(GLGizmosManager::EType type) return "Fuzzy Skin Painting"; case GLGizmosManager::EType::TextureDisplacement: return "Texture Displacement"; + case GLGizmosManager::EType::PaintedModifier: + return "Painted Modifier"; default: return ""; } diff --git a/src/slic3r/GUI/Gizmos/GLGizmosManager.hpp b/src/slic3r/GUI/Gizmos/GLGizmosManager.hpp index a61b05376a..20de8b6176 100644 --- a/src/slic3r/GUI/Gizmos/GLGizmosManager.hpp +++ b/src/slic3r/GUI/Gizmos/GLGizmosManager.hpp @@ -95,6 +95,7 @@ public: Seam, FuzzySkin, MmSegmentation, + PaintedModifier, TextureDisplacement, Emboss, Svg, diff --git a/src/slic3r/GUI/ObjectDataViewModel.cpp b/src/slic3r/GUI/ObjectDataViewModel.cpp index 7eaa8ee6bb..af4f61f320 100644 --- a/src/slic3r/GUI/ObjectDataViewModel.cpp +++ b/src/slic3r/GUI/ObjectDataViewModel.cpp @@ -64,6 +64,13 @@ static constexpr char WarningIcon[] = "obj_warning"; static constexpr char WarningManifoldIcon[] = "obj_warning"; static constexpr char LockIcon[] = "cut_"; +// Volumes printed with a filament of their own choice. +static bool volume_shows_extruder(Slic3r::ModelVolumeType type) +{ + return type == Slic3r::ModelVolumeType::MODEL_PART || type == Slic3r::ModelVolumeType::PARAMETER_MODIFIER || + type == Slic3r::ModelVolumeType::PAINTED_MODIFIER; +} + ObjectDataViewModelNode::ObjectDataViewModelNode(PartPlate* part_plate, wxString name) : m_parent(nullptr), m_name(name), @@ -109,7 +116,7 @@ ObjectDataViewModelNode::ObjectDataViewModelNode(ObjectDataViewModelNode* pare m_is_text_volume(is_text_volume), m_is_svg_volume(is_svg_volume), m_idx(idx), - m_extruder(type == Slic3r::ModelVolumeType::MODEL_PART || type == Slic3r::ModelVolumeType::PARAMETER_MODIFIER ? extruder : "") + m_extruder(volume_shows_extruder(type) ? extruder : "") { set_icons(); init_container(); @@ -214,7 +221,7 @@ void ObjectDataViewModelNode::set_icons() void ObjectDataViewModelNode::set_extruder_icon() { if (m_type & (itInstance | itInstanceRoot | itLayerRoot) || - ((m_type & itVolume) && m_volume_type != Slic3r::ModelVolumeType::MODEL_PART && m_volume_type != Slic3r::ModelVolumeType::PARAMETER_MODIFIER)) + ((m_type & itVolume) && ! volume_shows_extruder(m_volume_type))) return; // don't set colored bitmap for Instance UpdateExtruderAndColorIcon(); @@ -415,7 +422,7 @@ void ObjectDataViewModelNode::SetPlateIdx(const int& idx) void ObjectDataViewModelNode::UpdateExtruderAndColorIcon(wxString extruder /*= ""*/) { - if (m_type == itVolume && m_volume_type != ModelVolumeType::MODEL_PART && m_volume_type != ModelVolumeType::PARAMETER_MODIFIER) + if (m_type == itVolume && ! volume_shows_extruder(m_volume_type)) return; if (extruder.empty()) extruder = m_extruder; @@ -430,7 +437,7 @@ void ObjectDataViewModelNode::UpdateExtruderAndColorIcon(wxString extruder /*= " extruder_idx = atoi(m_parent->GetExtruder().c_str()); } // BBS - else if (m_type & itVolume && m_volume_type == ModelVolumeType::PARAMETER_MODIFIER) { + else if (m_type & itVolume && (m_volume_type == ModelVolumeType::PARAMETER_MODIFIER || m_volume_type == ModelVolumeType::PAINTED_MODIFIER)) { m_extruder_bmp = *get_default_extruder_color_icon(); return; } @@ -568,7 +575,7 @@ void ObjectDataViewModel::UpdateBitmapForNode(ObjectDataViewModelNode *node) bool is_volume_node = node->GetType() & itVolume; int vol_type = static_cast(node->GetVolumeType()); // Extended range to include Precise Seam modifier types - is_volume_node &= (vol_type >= int(ModelVolumeType::MODEL_PART) && vol_type <= int(ModelVolumeType::PRECISE_SEAM_NEUTRAL)); + is_volume_node &= (vol_type >= int(ModelVolumeType::MODEL_PART) && vol_type <= int(ModelVolumeType::PAINTED_MODIFIER)); if (!node->has_warning_icon() && !node->has_lock()) { node->SetBitmap(is_volume_node ? ( @@ -698,7 +705,7 @@ wxDataViewItem ObjectDataViewModel::AddVolumeChild( const wxDataViewItem &parent // BBS wxString extruder_str; if (extruder == 0) { - if (volume_type == ModelVolumeType::PARAMETER_MODIFIER) + if (volume_type == ModelVolumeType::PARAMETER_MODIFIER || volume_type == ModelVolumeType::PAINTED_MODIFIER) extruder_str = _L("default"); else extruder_str = root->m_extruder; diff --git a/src/slic3r/GUI/Plater.cpp b/src/slic3r/GUI/Plater.cpp index c625c42bcd..1828475f83 100644 --- a/src/slic3r/GUI/Plater.cpp +++ b/src/slic3r/GUI/Plater.cpp @@ -11716,6 +11716,10 @@ unsigned int Plater::priv::update_background_process(bool force_validation, bool background_process.fff_print()->set_check_multi_filaments_compatibility(wxGetApp().app_config->get("enable_high_low_temp_mixed_printing") == "false"); + // Painted modifiers have no geometry in the scene, the parts they are painted on were moved without them. + for (ModelObject *model_object : this->model.objects) + model_object->sync_painted_modifiers(); + Print::ApplyStatus invalidated; const auto& preset_bundle = wxGetApp().preset_bundle; if (preset_bundle->get_printer_extruder_count() > 1) { @@ -21111,6 +21115,8 @@ int Plater::export_3mf(const boost::filesystem::path& output_path, SaveStrategy } } + for (ModelObject *model_object : p->model.objects) + model_object->sync_painted_modifiers(); bool store_result = Slic3r::store_bbs_3mf(store_params); // reset designed info if (!has_design_info) @@ -24654,6 +24660,7 @@ wxMenu* Plater::object_menu() { return p->menus.object_menu(); wxMenu* Plater::part_menu() { return p->menus.part_menu(); } wxMenu* Plater::text_part_menu() { return p->menus.text_part_menu(); } wxMenu* Plater::svg_part_menu() { return p->menus.svg_part_menu(); } +wxMenu* Plater::painted_modifier_menu() { return p->menus.painted_modifier_menu(); } wxMenu* Plater::sla_object_menu() { return p->menus.sla_object_menu(); } wxMenu* Plater::default_menu() { return p->menus.default_menu(); } wxMenu* Plater::instance_menu() { return p->menus.instance_menu(); } diff --git a/src/slic3r/GUI/Plater.hpp b/src/slic3r/GUI/Plater.hpp index 623f836c1d..6cf4103f6b 100644 --- a/src/slic3r/GUI/Plater.hpp +++ b/src/slic3r/GUI/Plater.hpp @@ -1064,6 +1064,7 @@ public: wxMenu* part_menu(); wxMenu* text_part_menu(); wxMenu* svg_part_menu(); + wxMenu* painted_modifier_menu(); wxMenu* sla_object_menu(); wxMenu* default_menu(); wxMenu* instance_menu(); diff --git a/src/slic3r/GUI/Selection.cpp b/src/slic3r/GUI/Selection.cpp index 1a27227456..7209de73a0 100644 --- a/src/slic3r/GUI/Selection.cpp +++ b/src/slic3r/GUI/Selection.cpp @@ -70,6 +70,12 @@ static const Slic3r::ColorRGBA TRANSPARENT_PLANE_COLOR = { 0.8f, 0.8f, 0.8f, 0.5 namespace Slic3r { namespace GUI { +// Volumes that have a GLVolume in the scene: painted modifiers have none. +static unsigned int scene_volumes_count(const ModelObject &model_object) +{ + return (unsigned int)std::count_if(model_object.volumes.begin(), model_object.volumes.end(), [](const ModelVolume *v) { return ! v->is_painted_modifier(); }); +} + Selection::VolumeCache::TransformCache::TransformCache() : position(Vec3d::Zero()) , rotation_matrix(Transform3d::Identity()) @@ -873,7 +879,7 @@ bool Selection::is_single_full_instance() const volumes_idxs.insert(volume_idx); } - return m_model->objects[object_idx]->volumes.size() == volumes_idxs.size(); + return scene_volumes_count(*m_model->objects[object_idx]) == volumes_idxs.size(); } bool Selection::is_from_single_object() const @@ -2348,7 +2354,7 @@ void Selection::update_type() else { const ModelObject* model_object = m_model->objects[first->object_idx()]; - unsigned int volumes_count = (unsigned int)model_object->volumes.size(); + unsigned int volumes_count = scene_volumes_count(*model_object); unsigned int instances_count = (unsigned int)model_object->instances.size(); if (volumes_count * instances_count == 1) { @@ -2381,7 +2387,7 @@ void Selection::update_type() if (m_cache.content.size() == 1) // single object { const ModelObject* model_object = m_model->objects[m_cache.content.begin()->first]; - unsigned int model_volumes_count = (unsigned int)model_object->volumes.size(); + unsigned int model_volumes_count = scene_volumes_count(*model_object); unsigned int instances_count = (unsigned int)model_object->instances.size(); unsigned int selected_instances_count = (unsigned int)m_cache.content.begin()->second.size(); @@ -2431,7 +2437,7 @@ void Selection::update_type() bool is_wipe_tower = it->first >= 1000; int actual_obj_id = is_wipe_tower ? it->first - 1000 : it->first; const ModelObject *model_object = m_model->objects[actual_obj_id]; - unsigned int volumes_count = (unsigned int)model_object->volumes.size(); + unsigned int volumes_count = scene_volumes_count(*model_object); unsigned int instances_count = (unsigned int)model_object->instances.size(); sels_cntr += volumes_count * instances_count; } @@ -3222,7 +3228,7 @@ bool Selection::is_from_fully_selected_instance(unsigned int volume_idx) const return false; unsigned int count = (unsigned int)std::count_if(m_list.begin(), m_list.end(), SameInstance(object_idx, volume->instance_idx(), *m_volumes)); - return count == (unsigned int)m_model->objects[object_idx]->volumes.size(); + return count == scene_volumes_count(*m_model->objects[object_idx]); } void Selection::paste_volumes_from_clipboard() diff --git a/src/slic3r/GUI/Tab.cpp b/src/slic3r/GUI/Tab.cpp index 3cddbb97d8..07645f5cda 100644 --- a/src/slic3r/GUI/Tab.cpp +++ b/src/slic3r/GUI/Tab.cpp @@ -7374,7 +7374,7 @@ void Tab::load_current_preset() object->config.assign_config(std::move(object_config)); } for (ModelVolume* v : object->volumes) { - if (v->is_model_part() || v->is_modifier()) { + if (v->is_model_part() || v->is_region_modifier()) { DynamicPrintConfig volume_config = v->config.get(); if (!volume_config.empty()) { volume_config.update_values_from_multi_to_multi_2(prev_variant_list,new_variant_list,new_print_config, print_options_with_variant); diff --git a/src/slic3r/Utils/FixModelByCgal.cpp b/src/slic3r/Utils/FixModelByCgal.cpp index 081d9dcf0d..4f801ba8c1 100644 --- a/src/slic3r/Utils/FixModelByCgal.cpp +++ b/src/slic3r/Utils/FixModelByCgal.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -38,10 +39,12 @@ bool fix_model_with_cgal_gui(ModelObject &model_object, int volume_idx, GUI::Pro // Keeps the backup manager from reading a mesh while the worker replaces it. SaveObjectGaurd backup_gaurd(model_object); + // A painted modifier follows the mesh of its host. std::vector volumes; if (volume_idx < 0) - volumes = model_object.volumes; - else if (std::size_t(volume_idx) < model_object.volumes.size()) + std::copy_if(model_object.volumes.begin(), model_object.volumes.end(), std::back_inserter(volumes), + [](const ModelVolume *volume) { return !volume->is_painted_modifier(); }); + else if (std::size_t(volume_idx) < model_object.volumes.size() && !model_object.volumes[volume_idx]->is_painted_modifier()) volumes.push_back(model_object.volumes[volume_idx]); std::mutex mtx; diff --git a/src/slic3r/plugin/host/PluginHostModel.cpp b/src/slic3r/plugin/host/PluginHostModel.cpp index 8d9be8dd3d..195a593d41 100644 --- a/src/slic3r/plugin/host/PluginHostModel.cpp +++ b/src/slic3r/plugin/host/PluginHostModel.cpp @@ -43,7 +43,8 @@ void host_bindings::register_model(py::module_& host) .value("PreciseSeamRight", ModelVolumeType::PRECISE_SEAM_RIGHT) .value("PreciseSeamEnforced", ModelVolumeType::PRECISE_SEAM_ENFORCED) .value("PreciseSeamBlocked", ModelVolumeType::PRECISE_SEAM_BLOCKED) - .value("PreciseSeamNeutral", ModelVolumeType::PRECISE_SEAM_NEUTRAL); + .value("PreciseSeamNeutral", ModelVolumeType::PRECISE_SEAM_NEUTRAL) + .value("PaintedModifier", ModelVolumeType::PAINTED_MODIFIER); py::class_>(host, "ModelVolume") .def("id", [](const ModelVolume& volume) { return volume.id().id; }) diff --git a/tests/fff_print/CMakeLists.txt b/tests/fff_print/CMakeLists.txt index 7fc1f0bb3b..1300e1be8d 100644 --- a/tests/fff_print/CMakeLists.txt +++ b/tests/fff_print/CMakeLists.txt @@ -24,6 +24,7 @@ add_executable(${_TEST_NAME}_tests test_model.cpp test_multifilament.cpp test_multimaterial_segmentation.cpp + test_painted_modifier.cpp test_perimeters.cpp # Seam geometry and pipeline regressions share the existing Print fixtures. test_precise_seam.cpp diff --git a/tests/fff_print/test_painted_modifier.cpp b/tests/fff_print/test_painted_modifier.cpp new file mode 100644 index 0000000000..7e9fa59ccb --- /dev/null +++ b/tests/fff_print/test_painted_modifier.cpp @@ -0,0 +1,243 @@ +#include +#include +#include +#include +#include + +#include "test_helpers.hpp" + +#include "libslic3r/BoundingBox.hpp" +#include "libslic3r/Config.hpp" +#include "libslic3r/ExPolygon.hpp" +#include "libslic3r/Layer.hpp" +#include "libslic3r/Model.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/Print.hpp" +#include "libslic3r/PrintConfig.hpp" +#include "libslic3r/Surface.hpp" +#include "libslic3r/SurfaceCollection.hpp" +#include "libslic3r/TriangleMesh.hpp" +#include "libslic3r/TriangleSelector.hpp" +#include "libslic3r/libslic3r.h" + +#include +#include +#include + +using namespace Slic3r; +using Catch::Matchers::WithinAbs; + +namespace { +constexpr int default_walls = 2; + +// Paints the facets of a painted modifier's mesh that face along `direction`. +void paint_facing(ModelVolume &painted_modifier, const Vec3f &direction) +{ + const indexed_triangle_set &its = painted_modifier.mesh().its; + TriangleSelector selector(painted_modifier.mesh()); + for (int facet_idx = 0; facet_idx < int(its.indices.size()); ++facet_idx) + if (its_face_normal(its, facet_idx).dot(direction) > 0.99f) + selector.set_facet(facet_idx, EnforcerBlockerType::ENFORCER); + painted_modifier.painted_modifier_facets.set(selector); +} + +// A 20 mm cube sliced at 0.2 mm, with modifiers added in object list order. +struct Scene { + Model model; + Print print; + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + ModelObject *object; + + Scene() + { + config.set_deserialize_strict({{"layer_height", "0.2"}, {"initial_layer_print_height", "0.2"}, {"wall_loops", std::to_string(default_walls)}}); + object = model.add_object(); + object->add_volume(Test::cube(20)); + object->add_instance(); + } + + ModelVolume &part() { return *object->volumes.front(); } + + ModelVolume &add_painted_modifier(int walls, float depth, const Vec3f &direction = Vec3f::UnitX()) + { + ModelVolume *painted_modifier = object->add_painted_modifier(part()); + painted_modifier->painted_modifier_depth = depth; + painted_modifier->config.set_key_value("wall_loops", new ConfigOptionInt(walls)); + paint_facing(*painted_modifier, direction); + return *painted_modifier; + } + + // A modifier enclosing the whole part. + ModelVolume &add_enclosing_modifier(int walls) + { + ModelVolume *modifier = object->add_volume(Test::cube(30), ModelVolumeType::PARAMETER_MODIFIER); + modifier->set_offset(part().get_offset()); + modifier->config.set_key_value("wall_loops", new ConfigOptionInt(walls)); + modifier->config.set_key_value("sparse_infill_density", new ConfigOptionPercent(50)); + return *modifier; + } + + void slice() + { + object->ensure_on_bed(); + print.auto_assign_extruders(object); + print.apply(model, config); + print.validate(); + print.set_status_silent(); + print.process(); + } + + const Layer &layer_at(double z) const + { + const PrintObject &print_object = *print.objects().front(); + const auto it = std::find_if(print_object.layers().begin(), print_object.layers().end(), [z](const Layer *l) { return l->slice_z > z; }); + REQUIRE(it != print_object.layers().end()); + return **it; + } +}; + +// Area in mm² of the layer regions printed with the given number of walls. +double area_with_walls(const Layer &layer, int walls) +{ + double area = 0.; + for (const LayerRegion *region : layer.regions()) + if (region->region().config().wall_loops.value == walls) + for (const Surface &surface : region->slices.surfaces) + area += surface.expolygon.area(); + return area * SCALING_FACTOR * SCALING_FACTOR; +} + +const LayerRegion *region_with_walls(const Layer &layer, int walls) +{ + for (const LayerRegion *region : layer.regions()) + if (region->region().config().wall_loops.value == walls && ! region->slices.empty()) + return region; + return nullptr; +} + +// Painting one side of a 20 mm square claims the triangle of the square nearest to that side. +constexpr double nearest_side_area = 20. * 10. / 2.; +// A 3 mm deep band of that triangle is a trapezoid with parallel sides of 20 and 14 mm. +constexpr double band_area = 3. * (20. + 14.) / 2.; +constexpr double tolerance = 4.; +} // namespace + +TEST_CASE("A painted modifier applies its settings only near the painted side of its part", "[PaintedModifier]") +{ + Scene scene; + scene.add_painted_modifier(5, 0.f); + scene.slice(); + const Layer &layer = scene.layer_at(10.); + + CHECK_THAT(area_with_walls(layer, 5), WithinAbs(nearest_side_area, tolerance)); + CHECK_THAT(area_with_walls(layer, default_walls), WithinAbs(400. - nearest_side_area, tolerance)); + const LayerRegion *painted = region_with_walls(layer, 5); + REQUIRE(painted != nullptr); + // The +X side was painted, so the region lies in the +X half of the layer. + const BoundingBox painted_bbox = get_extents(painted->slices.surfaces); + const BoundingBox layer_bbox = get_extents(layer.lslices); + CHECK(painted_bbox.min.x() >= layer_bbox.center().x() - scaled(0.5)); + CHECK(painted_bbox.max.x() >= layer_bbox.max.x() - scaled(0.5)); +} + +TEST_CASE("Painted modifier depth limits how far the paint reaches into the part", "[PaintedModifier]") +{ + Scene scene; + scene.add_painted_modifier(5, 3.f); + scene.slice(); + const Layer &layer = scene.layer_at(10.); + + CHECK_THAT(area_with_walls(layer, 5), WithinAbs(band_area, tolerance)); + const LayerRegion *painted = region_with_walls(layer, 5); + REQUIRE(painted != nullptr); + CHECK_THAT(unscaled(get_extents(painted->slices.surfaces).size().x()), WithinAbs(3., 0.2)); +} + +TEST_CASE("A painted top face reaches down by the painted modifier depth", "[PaintedModifier]") +{ + Scene scene; + scene.add_painted_modifier(5, 1.f, Vec3f::UnitZ()); + scene.slice(); + + CHECK_THAT(area_with_walls(scene.layer_at(19.8), 5), WithinAbs(400., tolerance)); + CHECK_THAT(area_with_walls(scene.layer_at(19.2), 5), WithinAbs(400., tolerance)); + CHECK(area_with_walls(scene.layer_at(18.), 5) == 0.); + CHECK(area_with_walls(scene.layer_at(10.), 5) == 0.); +} + +TEST_CASE("A painted modifier and a mesh modifier apply the settings of the later one in the object list", "[PaintedModifier]") +{ + Scene scene; + scene.add_enclosing_modifier(3); + scene.add_painted_modifier(5, 0.f); + scene.slice(); + { + const Layer &layer = scene.layer_at(10.); + CHECK_THAT(area_with_walls(layer, 5), WithinAbs(nearest_side_area, tolerance)); + CHECK_THAT(area_with_walls(layer, 3), WithinAbs(400. - nearest_side_area, tolerance)); + // The painted modifier overrides only the walls, the mesh modifier still sets the infill below it. + const LayerRegion *painted = region_with_walls(layer, 5); + REQUIRE(painted != nullptr); + CHECK_THAT(painted->region().config().sparse_infill_density.value, WithinAbs(50., 1e-9)); + } + + // Moving the mesh modifier after the painted one in the list lets it win everywhere. + std::swap(scene.object->volumes[1], scene.object->volumes[2]); + scene.slice(); + { + const Layer &layer = scene.layer_at(10.); + CHECK(area_with_walls(layer, 5) == 0.); + CHECK_THAT(area_with_walls(layer, 3), WithinAbs(400., tolerance)); + } +} + +TEST_CASE("Overlapping painted modifiers apply the settings of the later one in the object list", "[PaintedModifier]") +{ + const bool deep_first = GENERATE(true, false); + CAPTURE(deep_first); + Scene scene; + if (deep_first) { + scene.add_painted_modifier(5, 0.f); + scene.add_painted_modifier(4, 3.f); + } else { + scene.add_painted_modifier(4, 3.f); + scene.add_painted_modifier(5, 0.f); + } + scene.slice(); + const Layer &layer = scene.layer_at(10.); + + if (deep_first) { + CHECK_THAT(area_with_walls(layer, 4), WithinAbs(band_area, tolerance)); + CHECK_THAT(area_with_walls(layer, 5), WithinAbs(nearest_side_area - band_area, tolerance)); + } else { + CHECK(area_with_walls(layer, 4) == 0.); + CHECK_THAT(area_with_walls(layer, 5), WithinAbs(nearest_side_area, tolerance)); + } +} + +TEST_CASE("Repainting a painted modifier reslices its object", "[PaintedModifier]") +{ + Scene scene; + ModelVolume &painted_modifier = scene.add_painted_modifier(5, 0.f); + scene.slice(); + const coord_t center_x = get_extents(scene.layer_at(10.).lslices).center().x(); + REQUIRE(get_extents(region_with_walls(scene.layer_at(10.), 5)->slices.surfaces).min.x() >= center_x - scaled(0.5)); + + paint_facing(painted_modifier, -Vec3f::UnitX()); + scene.slice(); + const LayerRegion *painted = region_with_walls(scene.layer_at(10.), 5); + REQUIRE(painted != nullptr); + CHECK(get_extents(painted->slices.surfaces).max.x() <= center_x + scaled(0.5)); +} + +TEST_CASE("A painted modifier without paint changes nothing", "[PaintedModifier]") +{ + Scene scene; + ModelVolume *painted_modifier = scene.object->add_painted_modifier(scene.part()); + painted_modifier->config.set_key_value("wall_loops", new ConfigOptionInt(5)); + scene.slice(); + + const Layer &layer = scene.layer_at(10.); + CHECK(area_with_walls(layer, 5) == 0.); + CHECK_THAT(area_with_walls(layer, default_walls), WithinAbs(400., tolerance)); +} diff --git a/tests/libslic3r/CMakeLists.txt b/tests/libslic3r/CMakeLists.txt index 809f74f212..f20e7e791e 100644 --- a/tests/libslic3r/CMakeLists.txt +++ b/tests/libslic3r/CMakeLists.txt @@ -65,6 +65,7 @@ add_executable(${_TEST_NAME}_tests test_minimum_spanning_tree.cpp test_nozzle_volume_type.cpp test_obj.cpp + test_painted_modifier.cpp test_step.cpp test_stl.cpp test_triangle_mesh_deal.cpp diff --git a/tests/libslic3r/test_painted_modifier.cpp b/tests/libslic3r/test_painted_modifier.cpp new file mode 100644 index 0000000000..24cca19b40 --- /dev/null +++ b/tests/libslic3r/test_painted_modifier.cpp @@ -0,0 +1,227 @@ +#include +#include +#include +#include +#include + +#include "test_utils.hpp" + +#include "libslic3r/Config.hpp" +#include "libslic3r/Format/ProjectStrategy.hpp" +#include "libslic3r/Format/bbs_3mf.hpp" +#include "libslic3r/Geometry.hpp" +#include "libslic3r/Model.hpp" +#include "libslic3r/Point.hpp" +#include "libslic3r/Preset.hpp" +#include "libslic3r/PrintConfig.hpp" +#include "libslic3r/Semver.hpp" +#include "libslic3r/TriangleMesh.hpp" +#include "libslic3r/TriangleSelector.hpp" +#include "libslic3r/miniz_extension.hpp" + +#include + +#include +#include +#include + +using namespace Slic3r; +using Catch::Matchers::WithinAbs; + +namespace { +// An object with one part and a painted modifier covering the facets of its +X side. +struct Scene { + // Keep the backup directory alive longer than its model. + ScopedTemporaryDir backup{"orca_painted_modifier"}; + Model model; + ModelObject *object; + ModelVolume *part; + ModelVolume *painted_modifier; + + Scene() + { + model.set_backup_path(backup.string()); + object = model.add_object(); + part = object->add_volume(make_cube(20, 20, 20)); + Geometry::Transformation transformation; + transformation.set_offset(Vec3d(1., 2., 3.)); + transformation.set_rotation(Vec3d(0., 0., 0.3)); + part->set_transformation(transformation); + painted_modifier = object->add_painted_modifier(*part); + painted_modifier->name = "painted"; + painted_modifier->painted_modifier_depth = 2.5f; + painted_modifier->config.set_key_value("wall_loops", new ConfigOptionInt(5)); + const indexed_triangle_set &its = part->mesh().its; + TriangleSelector selector(part->mesh()); + for (int facet_idx = 0; facet_idx < int(its.indices.size()); ++facet_idx) + if (its_face_normal(its, facet_idx).x() > 0.99f) + selector.set_facet(facet_idx, EnforcerBlockerType::ENFORCER); + painted_modifier->painted_modifier_facets.set(selector); + object->add_instance(); + } +}; + +// Area in mm² of the facets a painted modifier covers. +double painted_area(const ModelVolume &painted_modifier) +{ + const indexed_triangle_set its = painted_modifier.painted_modifier_facets.get_facets_strict(painted_modifier, EnforcerBlockerType::ENFORCER); + double area = 0.; + for (const stl_triangle_vertex_indices &face : its.indices) { + const Vec3d a = its.vertices[face(0)].cast(); + area += 0.5 * (its.vertices[face(1)].cast() - a).cross(its.vertices[face(2)].cast() - a).norm(); + } + return area; +} + +void save(const std::string &path, Model &model, bool share_mesh) +{ + DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); + StoreParams params; + params.path = path.c_str(); + params.model = &model; + params.config = &config; + params.strategy = SaveStrategy::Zip64 | SaveStrategy::Silence; + if (share_mesh) + params.strategy = params.strategy | SaveStrategy::ShareMesh; + REQUIRE(store_bbs_3mf(params)); +} + +void load(const std::string &path, Model &model) +{ + struct ImportedResources { + PlateDataPtrs plates; + std::vector presets; + ~ImportedResources() { release_PlateData_list(plates); for (Preset *preset : presets) delete preset; } + } resources; + DynamicPrintConfig config; + ConfigSubstitutionContext substitutions{ForwardCompatibilitySubstitutionRule::Enable}; + bool bbs = false, orca = false; + Semver version; + REQUIRE(load_bbs_3mf(path.c_str(), &config, &substitutions, &model, &resources.plates, &resources.presets, &bbs, &orca, &version, nullptr, + LoadStrategy::LoadModel | LoadStrategy::LoadConfig)); +} + +std::string model_settings(const std::string &path) +{ + struct Reader { + mz_zip_archive zip{}; + ~Reader() { if (zip.m_pState) close_zip_reader(&zip); } + } reader; + REQUIRE(open_zip_reader(&reader.zip, path)); + const int index = mz_zip_reader_locate_file(&reader.zip, "Metadata/model_settings.config", nullptr, 0); + REQUIRE(index >= 0); + mz_zip_archive_file_stat stat; + REQUIRE(mz_zip_reader_file_stat(&reader.zip, mz_uint(index), &stat)); + std::string data(size_t(stat.m_uncomp_size), '\0'); + REQUIRE(mz_zip_reader_extract_to_mem(&reader.zip, mz_uint(index), data.data(), data.size(), 0)); + return data; +} + +// The element of the volume holding the given metadata key. +std::string part_block(const std::string &xml, const std::string &key) +{ + const size_t key_pos = xml.find("key=\"" + key + "\""); + REQUIRE(key_pos != std::string::npos); + const size_t begin = xml.rfind("", key_pos); + REQUIRE(begin != std::string::npos); + REQUIRE(end != std::string::npos); + return xml.substr(begin, end - begin); +} +} // namespace + +TEST_CASE("A painted modifier survives a 3MF round trip", "[PaintedModifier]") +{ + const bool share_mesh = GENERATE(false, true); + CAPTURE(share_mesh); + Scene source; + ScopedTemporaryFile file(".3mf"); + save(file.string(), source.model, share_mesh); + + Model destination; + load(file.string(), destination); + REQUIRE(destination.objects.size() == 1); + const ModelObject &object = *destination.objects.front(); + REQUIRE(object.volumes.size() == 2); + const ModelVolume &part = *object.volumes[0]; + const ModelVolume &painted_modifier = *object.volumes[1]; + REQUIRE(painted_modifier.is_painted_modifier()); + CHECK(painted_modifier.name == "painted"); + CHECK_THAT(painted_modifier.painted_modifier_depth, WithinAbs(2.5, 1e-6)); + REQUIRE(painted_modifier.config.has("wall_loops")); + CHECK(painted_modifier.config.opt_int("wall_loops") == 5); + CHECK(object.painted_modifier_host(painted_modifier) == &part); + CHECK(painted_modifier.mesh_ptr() == part.mesh_ptr()); + CHECK(painted_modifier.get_matrix().isApprox(part.get_matrix())); + CHECK(painted_modifier.painted_modifier_facets.get_data() == source.painted_modifier->painted_modifier_facets.get_data()); +} + +TEST_CASE("A painted modifier is stored as a modifier whose settings older readers drop", "[PaintedModifier]") +{ + Scene source; + ScopedTemporaryFile file(".3mf"); + save(file.string(), source.model, false); + + const std::string block = part_block(model_settings(file.string()), "painted_modifier_depth"); + CHECK(block.find("subtype=\"modifier_part\"") != std::string::npos); + CHECK(block.find("key=\"painted_modifier_config:wall_loops\"") != std::string::npos); + CHECK(block.find("key=\"wall_loops\"") == std::string::npos); +} + +TEST_CASE("Sorting volumes keeps painted and mesh modifiers in the user's order", "[PaintedModifier]") +{ + Scene scene; + ModelVolume *blocker = scene.object->add_volume(make_cube(1, 1, 1), ModelVolumeType::SUPPORT_BLOCKER); + ModelVolume *modifier = scene.object->add_volume(make_cube(1, 1, 1), ModelVolumeType::PARAMETER_MODIFIER); + ModelVolume *second = scene.object->add_painted_modifier(*scene.part); + scene.object->sort_volumes(true); + + const ModelVolumePtrs expected{scene.part, scene.painted_modifier, modifier, second, blocker}; + CHECK(scene.object->volumes == expected); +} + +TEST_CASE("A painted modifier follows the transformation and the mesh of its host", "[PaintedModifier]") +{ + Scene scene; + scene.part->set_offset(Vec3d(7., -4., 2.)); + CHECK(scene.object->sync_painted_modifiers()); + CHECK(scene.painted_modifier->get_matrix().isApprox(scene.part->get_matrix())); + + // Replacing the host mesh with an equal one keeps the paint and shares the new mesh. + const auto data = scene.painted_modifier->painted_modifier_facets.get_data(); + scene.part->set_mesh(TriangleMesh(scene.part->mesh())); + CHECK(scene.object->sync_painted_modifiers()); + CHECK(scene.painted_modifier->mesh_ptr() == scene.part->mesh_ptr()); + CHECK(scene.painted_modifier->painted_modifier_facets.get_data() == data); + CHECK_FALSE(scene.object->sync_painted_modifiers()); +} + +TEST_CASE("A painted modifier stays on its host when the host gets a new ID", "[PaintedModifier]") +{ + Scene scene; + // Mesh edits such as simplify or repair renew the ID of the edited part. + scene.part->set_new_unique_id(); + CHECK(scene.object->painted_modifier_host(*scene.painted_modifier) == scene.part); +} + +TEST_CASE("Replacing the mesh of a painted modifier keeps its paint", "[PaintedModifier]") +{ + Scene scene; + REQUIRE_THAT(painted_area(*scene.painted_modifier), WithinAbs(20. * 20., 1e-3)); + const auto saved = scene.painted_modifier->save_painting(); + REQUIRE(saved.has_value()); + // Like the mesh operations, rebuild the mesh from its triangles. + scene.painted_modifier->set_mesh(TriangleMesh(scene.part->mesh().its)); + scene.painted_modifier->restore_painting(saved); + CHECK_THAT(painted_area(*scene.painted_modifier), WithinAbs(20. * 20., 1.)); +} + +TEST_CASE("A cloned object keeps its painted modifiers on their hosts", "[PaintedModifier]") +{ + Scene scene; + Model copy; + ModelObject *object = copy.add_object(*scene.object); + REQUIRE(object->volumes.size() == 2); + CHECK(object->volumes[0]->id() != scene.part->id()); + CHECK(object->painted_modifier_host(*object->volumes[1]) == object->volumes[0]); +}