diff --git a/crates/io/src/threemf.rs b/crates/io/src/threemf.rs index ef48cc6fe..ac4f47de2 100644 --- a/crates/io/src/threemf.rs +++ b/crates/io/src/threemf.rs @@ -10,8 +10,10 @@ //! items may name an object in another model part of the package (`p:path`, the 3MF Production //! extension, which slicers use for multi-part projects); those parts are read too. Only the root //! model's build counts (readers must ignore the others), and a part that can't be read fails -//! only the placements that need it. Packages are untrusted: sizes, entry counts, model parts, -//! mesh sizes and component nesting are capped. +//! only the placements that need it. Bodies are named after their objects; a slicer project whose +//! objects have no name in the model names them in its settings (Bambu Studio's +//! `Metadata/model_settings.config`), and those names are used. Packages are untrusted: sizes, +//! entry counts, model parts, mesh sizes and component nesting are capped. use std::collections::{BTreeMap, HashMap}; use std::fmt::Write as _; @@ -679,6 +681,69 @@ fn in_part(name: &str, e: IoError) -> String { } } +/// Where Bambu Studio keeps a project's per-object settings, among them the objects' names (its +/// root model's objects have none): ``, +/// with `N` the root model object a build item places. The `` elements inside describe the +/// object's volumes. +const SLICER_SETTINGS: &str = "Metadata/model_settings.config"; + +/// The object names in slicer settings `xml` ([`SLICER_SETTINGS`]), by object id. Only an +/// object's own `name` counts (the first, if there are several); its parts' names and all other +/// settings are left alone. +fn slicer_names(xml: &[u8]) -> std::result::Result, String> { + let mut rd = Reader::from_reader(xml); + rd.config_mut().trim_text(true); + let mut buf = Vec::new(); + let mut names = HashMap::new(); + let mut depth = 0usize; + let mut elements = 0usize; + // The object being read: its id (if it has a usable one) and the depth of its element. + let mut object: Option<(Option, usize)> = None; + loop { + let ev = rd.read_event_into(&mut buf).map_err(|e| e.to_string())?; + let start = matches!(ev, Event::Start(_)); + match &ev { + Event::Start(e) | Event::Empty(e) => { + let at = depth + 1; + if start { + depth = at; + if depth > MAX_XML_DEPTH { + return Err("XML nested too deeply".into()); + } + } + elements += 1; + if elements > MAX_ELEMENTS { + return Err("too many elements".into()); + } + match (e.local_name().as_ref(), object) { + (b"object", None) if at == 2 && start => { + object = Some((attrs(e).get("id").and_then(|v| v.trim().parse::().ok()), at)); + } + (b"metadata", Some((Some(id), d))) if at == d + 1 => { + let a = attrs(e); + if a.get("key").is_some_and(|k| k == "name") + && let Some(v) = a.get("value").map(|v| v.trim()).filter(|v| !v.is_empty()) + { + names.entry(id).or_insert_with(|| v.to_string()); + } + } + _ => {} + } + } + Event::End(_) => { + if object.is_some_and(|(_, d)| d == depth) { + object = None; + } + depth = depth.saturating_sub(1); + } + Event::Eof => break, + _ => {} + } + buf.clear(); + } + Ok(names) +} + /// Append object `id` of model part `part` (and its components) placed by `xf` to `out`. fn flatten<'a>( pkg: &'a Package, @@ -840,12 +905,17 @@ pub fn read_3mf(bytes: &[u8]) -> Result<(Vec, Vec)> { let mut out = Vec::new(); let mut warnings = Vec::new(); let mut total = 0usize; + // Bodies of root model objects without a name of their own: (index in `out`, object id). + let mut unnamed = Vec::new(); for (k, item) in model.build.iter().enumerate() { let part = item.part.as_ref().map_or(pkg.root.as_str(), |p| p.key.as_str()); let mut mo = MeshObject::default(); match flatten(&pkg, part, item.id, &item.xf, &mut mo, &mut Vec::new(), &mut total) { Ok(()) if !mo.triangles.is_empty() => { let name = pkg.parts.get(part).and_then(|m| m.objects.get(&item.id)).map(|o| o.name.trim().to_string()).filter(|n| !n.is_empty()); + if name.is_none() && part == pkg.root { + unnamed.push((out.len(), item.id)); + } mo.name = name.unwrap_or_else(|| format!("Mesh{}", k + 1)); out.push(mo); } @@ -853,6 +923,28 @@ pub fn read_3mf(bytes: &[u8]) -> Result<(Vec, Vec)> { Err(e) => warnings.push(format!("build item {}: {e}", k + 1)), } } + // A slicer project names its objects in its settings (#3858). Those are read only when a body + // needs a name, within what the model parts left of the budget, and settings that can't be + // read only leave the generic names. + if !unnamed.is_empty() + && let Some(&idx) = entries.get(&part_key(SLICER_SETTINGS)) + { + let names = match read_entry(&mut zip, idx, SLICER_SETTINGS, MAX_PART.saturating_sub(model_bytes)) { + Ok(Some(xml)) => slicer_names(&xml), + Ok(None) => Err("it expands past what the model parts left of the 1 GB budget".into()), + Err(e) => Err(e.to_string()), + }; + match names { + Ok(names) => { + for (i, id) in unnamed { + if let (Some(o), Some(name)) = (out.get_mut(i), names.get(&id)) { + o.name.clone_from(name); + } + } + } + Err(e) => warnings.push(format!("object names in `{SLICER_SETTINGS}` not read: {e}")), + } + } if out.is_empty() { return bad(warnings.first().cloned().unwrap_or_else(|| "no meshes to build".into())); } @@ -1088,9 +1180,9 @@ pub(crate) mod tests { /// A package shaped like a slicer project (Bambu Studio, OrcaSlicer): object UUIDs, printable /// build items, thumbnails, slicer configs, and the meshes in a part of their own with an empty - /// build (T3). Each object on the plate is one body with all its volumes. The slicer's config - /// (names, which volumes are modifiers) isn't read, so the bodies are named `MeshN` and the - /// modifier comes in as solid. + /// build (T3). Each object on the plate is one body with all its volumes, named as in the + /// slicer's config (#3858). The rest of the config (which volumes are modifiers) isn't read, so + /// the modifier comes in as solid. #[test] fn slicer_project_package() { let ns = r#"xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02" xmlns:BambuStudio="http://schemas.bambulab.com/package/2021" xmlns:p="http://schemas.microsoft.com/3dmanufacturing/production/2015/06" requiredextensions="p""#; @@ -1164,13 +1256,78 @@ pub(crate) mod tests { let (objs, warnings) = read_3mf(&package).unwrap(); assert!(warnings.is_empty(), "{warnings:?}"); let names: Vec<&str> = objs.iter().map(|o| o.name.as_str()).collect(); - assert_eq!(names, ["Mesh1", "Mesh2"]); + assert_eq!(names, ["Cube", "Bracket"]); assert_eq!((objs[0].triangles.len(), objs[1].triangles.len()), (4, 8)); assert!((volume(&objs[0]) - 1000.0 / 6.0).abs() < 1e-6, "{}", volume(&objs[0])); assert!((volume(&objs[1]) - (8000.0 + 64.0) / 6.0).abs() < 1e-6, "{}", volume(&objs[1])); assert!(objs[0].positions.iter().all(|p| p.x >= 128.0 - 1e-9 && p.y >= 128.0 - 1e-9)); } + /// The body names and warnings of a package with slicer settings `settings` (or none): root + /// objects 2 and 6 without a name and 4 named `Own`, each placing the tetrahedron of the + /// objects part, one build item each, and a fourth build item placing that tetrahedron itself. + fn named_by_settings(settings: Option<&str>) -> (Vec, Vec) { + let path = "/3D/Objects/object_1.model"; + let own = assembly(4, &[(path, 1)]).replace(r#"type="model""#, r#"type="model" name="Own""#); + let root = root_model( + &format!("{}{own}{}", assembly(2, &[(path, 1)]), assembly(6, &[(path, 1)])), + &format!(r#""#), + ); + let part = model_part("millimeter", &tet_object(1, "", 1.0)); + let mut parts = vec![("3D/3dmodel.model", root.as_str()), (OBJECTS_PART, part.as_str())]; + parts.extend(settings.map(|s| (SLICER_SETTINGS, s))); + let (objs, warnings) = read_3mf(&package_parts(&parts)).unwrap(); + (objs.into_iter().map(|o| o.name).collect(), warnings) + } + + /// Slicer settings name the root objects that have no name of their own, by object id, with + /// the object's first name, trimmed (#3858). A name in the model comes first; the names of + /// an object's parts, settings outside an object, objects the build doesn't place and objects + /// of other model parts change nothing. + #[test] + fn slicer_settings_name_unnamed_objects() { + let settings = r#" + + + + + + + + + +"#; + let (names, warnings) = named_by_settings(Some(settings)); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(names, ["Left wall", "Own", "Mesh3", "Mesh4"]); + // Without settings, the generic names as before. + assert_eq!(named_by_settings(None), (vec!["Mesh1".into(), "Own".into(), "Mesh3".into(), "Mesh4".into()], Vec::new())); + } + + /// Settings that can't be read never fail the import: the bodies keep the generic names, with + /// a warning saying why. They are read only when a body needs a name, so a package whose + /// objects all have one opens without a word about them. + #[test] + fn broken_slicer_settings_only_warn() { + let generic: Vec = ["Mesh1", "Own", "Mesh3", "Mesh4"].map(String::from).into(); + let deep = format!("{}", "".repeat(MAX_XML_DEPTH + 1)); + for (settings, why) in + [(r#""#, "config"), (deep.as_str(), "nested too deeply")] + { + let (names, warnings) = named_by_settings(Some(settings)); + assert_eq!(names, generic); + assert!( + warnings.len() == 1 + && warnings[0].starts_with("object names in `Metadata/model_settings.config` not read: ") + && warnings[0].contains(why), + "{warnings:?}" + ); + } + let [(r, root), (o, objects)] = production_parts(); + let (objs, warnings) = read_3mf(&package_parts(&[(r, &root), (o, &objects), (SLICER_SETTINGS, "")])).unwrap(); + assert!(warnings.is_empty() && objs[0].name == "Pair", "{warnings:?}"); + } + /// Placements in every part draw on one budget (T4): three parts fanning out 300 ways each /// (27 million placements of an empty object) stop at it, and only the build item that went /// over fails. diff --git a/docs/book/src/guide/files.md b/docs/book/src/guide/files.md index 093f53b59..0fba0b57c 100644 --- a/docs/book/src/guide/files.md +++ b/docs/book/src/guide/files.md @@ -36,10 +36,11 @@ message: save the file uncompressed first. A 3MF project saved by a slicer comes in too, also when it keeps its objects in model parts of their own inside the file (the 3MF Production extension): each object on the build plates becomes -one mesh body, with all its volumes merged where the slicer placed them. Slicer-only data -(modifier, negative and support volumes, painting, per-object settings, and names kept in the -slicer's metadata) is not read: modifier and negative volumes come in as ordinary solid geometry, -and objects without a name in the model itself are called Mesh1, Mesh2, … +one mesh body, with all its volumes merged where the slicer placed them. Each body is named after +its object: the name in the model, else the one the slicer keeps in its project settings (Bambu +Studio's `Metadata/model_settings.config`), else Mesh1, Mesh2, … Other slicer-only data +(modifier, negative and support volumes, painting, per-object settings) is not read: modifier and +negative volumes come in as ordinary solid geometry. **File → Export STL…** and **File → Export 3MF…** (also **Save As Mesh** on the Insert tab's Files panel, and in the right-click menu of a body) open the same dialog with that format chosen; it saves