Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

3MF export: a component's bodies as one object with parts (#8139) (#8187)

austin62jaked8d22cd52afb
diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs
index 9440a3998b..211f70e944 100644
--- a/crates/engine/src/cmd/file.rs
+++ b/crates/engine/src/cmd/file.rs
@@ -56,12 +56,12 @@ pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("file.export", "Export", export)
.icon("export")
.noundo()
- .params("path; format?: stl|stla|obj|step|3mf|3mf-tagged|urdf|json (default from extension; 3mf-tagged: 3MF whose triangles carry their B-rep face, at full precision, for meshing and analysis tools; docs/formats/3mf-face-tags.md; obj: the colours of the bodies go in a material library (`.mtl`) written next to the mesh file; urdf: the whole assembly as a robot, with STL meshes written next to it; docs/urdf.md); bodies?: [names] (JSON and URDF export the complete design); urdf only: mesh_prefix? (before each mesh file name, e.g. package://robot/meshes/), effort? (default 1000), velocity? (default 10); quality?: standard|fine|finest (STL, OBJ and 3MF: how closely the mesh follows curved faces, a chord tolerance of 2e-4, 5e-5 or 1e-5 of each body's size; default standard)"),
+ .params("path; format?: stl|stla|obj|step|3mf|3mf-tagged|urdf|json (default from extension; 3mf-tagged: 3MF whose triangles carry their B-rep face, at full precision, for meshing and analysis tools; docs/formats/3mf-face-tags.md; obj: the colours of the bodies go in a material library (`.mtl`) written next to the mesh file; urdf: the whole assembly as a robot, with STL meshes written next to it; docs/urdf.md); bodies?: [names] (JSON and URDF export the complete design); urdf only: mesh_prefix? (before each mesh file name, e.g. package://robot/meshes/), effort? (default 1000), velocity? (default 10); quality?: standard|fine|finest (STL, OBJ and 3MF: how closely the mesh follows curved faces, a chord tolerance of 2e-4, 5e-5 or 1e-5 of each body's size; default standard); objects?: body|component (3MF only: one object per body, the default, or one object for each placed component with two or more bodies, with those bodies as its parts, so a slicer loads them as one object with parts)"),
CommandSpec::new("file.save_mesh", "Save As Mesh", save_mesh)
.at("INSERT", "FILES")
.icon("mesh_export")
.noundo()
- .params("path; format?: stl|3mf|3mf-tagged (default from the extension, else stl; 3mf-tagged: docs/formats/3mf-face-tags.md); bodies?: [names] (default: all); ascii?: bool (STL); slicer?: id or name from file.slicers, the program path it lists, or a program the user added under Custom… (send the saved file there, through the same steps as file.send_to_slicer: a slicer that has to be started first is waited for; may be deprecated later in favour of file.send_to_slicer or a Send to App workflow, kept for scripts); single_instance?: bool (default true; see file.send_to_slicer); quality?: standard|fine|finest (STL, OBJ and 3MF: how closely the mesh follows curved faces, a chord tolerance of 2e-4, 5e-5 or 1e-5 of each body's size; default standard)"),
+ .params("path; format?: stl|3mf|3mf-tagged (default from the extension, else stl; 3mf-tagged: docs/formats/3mf-face-tags.md); bodies?: [names] (default: all); ascii?: bool (STL); slicer?: id or name from file.slicers, the program path it lists, or a program the user added under Custom… (send the saved file there, through the same steps as file.send_to_slicer: a slicer that has to be started first is waited for; may be deprecated later in favour of file.send_to_slicer or a Send to App workflow, kept for scripts); single_instance?: bool (default true; see file.send_to_slicer); quality?: standard|fine|finest (STL, OBJ and 3MF: how closely the mesh follows curved faces, a chord tolerance of 2e-4, 5e-5 or 1e-5 of each body's size; default standard); objects?: body|component (3MF only: one object per body, the default, or one object for each placed component with two or more bodies, with those bodies as its parts, so a slicer loads them as one object with parts)"),
CommandSpec::new("file.send_to_slicer", "Send to Slicer", send_to_slicer)
.enabled(starts_programs)
.at("INSERT", "FILES")
@@ -618,7 +618,52 @@ fn mesh_quality(p: &Value, cmd: &str) -> Result<solidcraft_io::MeshQuality> {
}
}
-fn export_to(s: &Session, path: &str, format: Format, bodies: &[String], quality: solidcraft_io::MeshQuality) -> Result<Value> {
+/// The 3MF parts a mesh export's `objects` asks for (#8139): none for `body` (the default, one
+/// object per body), or for `component` one part per placement of a component with two or more
+/// bodies ([`component_parts`]). Other formats have no parts, so `component` is refused there.
+pub(super) fn mesh_parts(s: &Session, p: &Value, cmd: &str, format: Format) -> Result<Vec<(String, Vec<String>)>> {
+ match p.get("objects") {
+ None | Some(Value::Null) => Ok(Vec::new()),
+ Some(v) => match v.as_str() {
+ Some("body") => Ok(Vec::new()),
+ Some("component") if matches!(format, Format::ThreeMf | Format::ThreeMfTagged) => Ok(component_parts(s)),
+ Some("component") => Err(bad(cmd, "`objects: component` is for 3MF: other formats have no parts")),
+ _ => Err(bad(cmd, format!("`objects` must be body or component, not {v}"))),
+ },
+ }
+}
+
+/// Each placement of a component that holds two or more bodies, by its occurrence's name, with
+/// the names its bodies have where they are placed (as the export names them). The design's own
+/// bodies and a component's single body are left out: they stay objects of their own.
+fn component_parts(s: &Session) -> Vec<(String, Vec<String>)> {
+ let doc = &s.doc;
+ if doc.occurrences.is_empty() {
+ return Vec::new();
+ }
+ let st = s.model.state();
+ let owners = doc.model_body_components(&st);
+ let names = solidcraft_doc::WorldNames::new(doc, &st);
+ doc.placements()
+ .into_iter()
+ .filter(|(comp, _, _)| *comp != 0)
+ .filter_map(|(comp, path, _)| {
+ let bodies: Vec<String> =
+ st.bodies.iter().zip(&owners).filter(|(_, owner)| **owner == comp).map(|(b, _)| names.name(&b.name, comp, &path)).collect();
+ let name = path.last().and_then(|id| doc.occurrences.iter().find(|o| o.id == *id)).map(|o| o.name.clone()).unwrap_or_default();
+ (bodies.len() >= 2).then_some((name, bodies))
+ })
+ .collect()
+}
+
+fn export_to(
+ s: &Session,
+ path: &str,
+ format: Format,
+ bodies: &[String],
+ parts: &[(String, Vec<String>)],
+ quality: solidcraft_io::MeshQuality,
+) -> Result<Value> {
if format == Format::Obj {
// The colours of the bodies go in a material library beside the mesh file.
return export_obj(s, path, bodies, quality);
@@ -635,7 +680,7 @@ fn export_to(s: &Session, path: &str, format: Format, bodies: &[String], quality
} else {
// Bodies carry the colour they are shown in (appearance, material or imported), and the
// file the design's properties where the format has a place for them.
- solidcraft_io::export_with_quality(&s.doc.painted(&s.world_state()), bodies, format, &name, &s.doc.metadata, quality)?
+ solidcraft_io::export_with_parts(&s.doc.painted(&s.world_state()), bodies, parts, format, &name, &s.doc.metadata, quality)?
};
solidcraft_io::vfs::write(path, &bytes).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
Ok(json!({"path": path, "bytes": bytes.len(), "format": format!("{format:?}")}))
@@ -649,7 +694,8 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
return export_urdf(s, path, p);
}
let quality = mesh_quality(p, cmd)?;
- export_to(s, path, format, &string_list(cmd, p, "bodies")?, quality)
+ let parts = mesh_parts(s, p, cmd, format)?;
+ export_to(s, path, format, &string_list(cmd, p, "bodies")?, &parts, quality)
}
/// The OBJ export: the mesh file and the material library beside it, with the colours of the
@@ -755,10 +801,11 @@ fn save_mesh(s: &mut Session, p: &Value) -> Result<Value> {
// and may be deprecated later in favour of `file.send_to_slicer` or a Send to App workflow; that is
// a possibility, not a plan.
let quality = mesh_quality(p, cmd)?;
+ let parts = mesh_parts(s, p, cmd, format)?;
if let Some(spec) = str_(p, "slicer") {
#[cfg(target_arch = "wasm32")]
{
- let _ = spec;
+ let _ = (spec, parts);
return Err(bad(cmd, "a slicer can't be started from the browser"));
}
#[cfg(not(target_arch = "wasm32"))]
@@ -769,6 +816,7 @@ fn save_mesh(s: &mut Session, p: &Value) -> Result<Value> {
kind: crate::slicers::TargetKind::Slicer,
spec,
bodies: string_list(cmd, p, "bodies")?,
+ parts,
format,
quality,
dest: send::Dest::Path(path),
@@ -777,7 +825,7 @@ fn save_mesh(s: &mut Session, p: &Value) -> Result<Value> {
},
);
}
- export_to(s, path, format, &string_list(cmd, p, "bodies")?, quality)
+ export_to(s, path, format, &string_list(cmd, p, "bodies")?, &parts, quality)
}
/// The browser build can't start a program.
@@ -811,6 +859,7 @@ fn send_to_slicer(s: &mut Session, p: &Value) -> Result<Value> {
kind: crate::slicers::TargetKind::Slicer,
spec,
bodies: string_list(cmd, p, "bodies")?,
+ parts: Vec::new(),
format,
quality: Default::default(),
dest: send::Dest::Folder,
@@ -883,6 +932,62 @@ mod urdf_tests;
mod tests {
use super::*;
+ /// #8139: with `objects: "component"` a 3MF has one object for each placement of a component
+ /// with two or more bodies, its bodies the object's parts; the design's own bodies stay objects
+ /// of their own. The default (and `objects: "body"`) is one object per body, as before. Read
+ /// back, an object with parts is one mesh with all its parts' triangles.
+ #[test]
+ fn a_components_bodies_export_to_3mf_as_one_object_with_parts() {
+ let dir = std::env::temp_dir().join(format!("solidcraft-3mf-parts-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = |n: &str| dir.join(n).to_string_lossy().to_string();
+ let read = |p: &str| -> Vec<(String, usize)> {
+ let (objects, warnings) = solidcraft_io::read_3mf(&std::fs::read(p).unwrap()).unwrap();
+ assert!(warnings.is_empty(), "{warnings:?}");
+ objects.iter().map(|o| (o.name.clone(), o.triangles.len())).collect()
+ };
+ let mut s = Session::default();
+ s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10, "corner": [-30, 0, 0], "body_name": "Loose"})).unwrap();
+ s.execute("component.create", &json!({"name": "Bracket"})).unwrap();
+ s.execute("solid.box", &json!({"length": 20, "width": 20, "height": 10, "body_name": "Base"})).unwrap();
+ s.execute("solid.cylinder", &json!({"radius": 5, "height": 10, "base": [10, 10, 10], "operation": "new", "body_name": "Boss"})).unwrap();
+ s.execute("component.activate", &json!({"component": "root"})).unwrap();
+
+ s.execute("file.export", &json!({"path": path("bodies.3mf")})).unwrap();
+ let bodies = read(&path("bodies.3mf"));
+ assert_eq!(bodies.len(), 3, "one object per body: {bodies:?}");
+ s.execute("file.export", &json!({"path": path("body.3mf"), "objects": "body"})).unwrap();
+ assert_eq!(read(&path("body.3mf")), bodies);
+ let loose = bodies.iter().find(|(n, _)| n == "Loose").map(|(_, t)| *t).unwrap_or(0);
+ let bracket: usize = bodies.iter().filter(|(n, _)| n != "Loose").map(|(_, t)| t).sum();
+
+ s.execute("file.export", &json!({"path": path("parts.3mf"), "objects": "component"})).unwrap();
+ let parts = read(&path("parts.3mf"));
+ assert_eq!(parts, [("Loose".to_string(), loose), ("Bracket:1".to_string(), bracket)], "{bodies:?}");
+ s.execute("file.save_mesh", &json!({"path": path("saved.3mf"), "objects": "component"})).unwrap();
+ assert_eq!(read(&path("saved.3mf")), parts);
+ s.execute("file.export", &json!({"path": path("tagged.3mf"), "format": "3mf-tagged", "objects": "component"})).unwrap();
+ assert_eq!(read(&path("tagged.3mf")), parts);
+
+ // Placed again, each placement is an object of its own.
+ s.execute("occurrence.copy", &json!({"component": "Bracket", "translate": [0, 40, 0]})).unwrap();
+ s.execute("file.export", &json!({"path": path("two.3mf"), "objects": "component"})).unwrap();
+ let two = read(&path("two.3mf"));
+ assert_eq!(two, [("Loose".to_string(), loose), ("Bracket:1".to_string(), bracket), ("Bracket:2".to_string(), bracket)]);
+
+ // Other formats have no parts, and `objects` is body or component.
+ let e = s.execute("file.export", &json!({"path": path("parts.stl"), "objects": "component"})).unwrap_err().to_string();
+ assert!(e.contains("`objects: component` is for 3MF"), "{e}");
+ let e = s.execute("file.save_mesh", &json!({"path": path("parts.stl"), "objects": "component"})).unwrap_err().to_string();
+ assert!(e.contains("`objects: component` is for 3MF"), "{e}");
+ for bad in [json!("parts"), json!(true), json!(2)] {
+ let e = s.execute("file.export", &json!({"path": path("bad.3mf"), "objects": bad})).unwrap_err().to_string();
+ assert!(e.contains("`objects` must be body or component"), "{bad}: {e}");
+ }
+ assert!(!std::path::Path::new(&path("parts.stl")).exists() && !std::path::Path::new(&path("bad.3mf")).exists());
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
/// #4747: a mesh export's `quality` follows curved faces more closely. A 3 mm hole in a
/// 200 mm plate gets more triangles at fine and more again at finest, in STL and 3MF alike
/// (Save As Mesh too); standard is what the export always gave; anything else is refused.
diff --git a/crates/engine/src/cmd/file_send.rs b/crates/engine/src/cmd/file_send.rs
index 6f70b71cb5..1ed3d64bcc 100644
--- a/crates/engine/src/cmd/file_send.rs
+++ b/crates/engine/src/cmd/file_send.rs
@@ -53,6 +53,8 @@ pub(super) struct Send<'a> {
/// The target as the caller named it: an id, a name, or a program path.
pub spec: &'a str,
pub bodies: Vec<String>,
+ /// 3MF objects with parts (`objects: "component"`, #8139). Only for [`Dest::Path`].
+ pub parts: Vec<(String, Vec<String>)>,
pub format: Format,
/// Only for [`Dest::Path`]; the slicer folder's file is always standard.
pub quality: solidcraft_io::MeshQuality,
@@ -79,7 +81,7 @@ pub(super) fn send(s: &mut Session, r: Send<'_>) -> Result<Value> {
return Err(bad(r.cmd, format!("{} does not take {}", target.name, format_name(r.format))));
}
let mut out = match r.dest {
- Dest::Path(path) => export_to(s, path, r.format, &r.bodies, r.quality)?,
+ Dest::Path(path) => export_to(s, path, r.format, &r.bodies, &r.parts, r.quality)?,
Dest::Folder => write_in_folder(s, &r)?,
};
let path = out.get("path").and_then(Value::as_str).unwrap_or_default().to_string();
diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs
index 25467c82df..ff4e149582 100644
--- a/crates/io/src/lib.rs
+++ b/crates/io/src/lib.rs
@@ -48,7 +48,9 @@ mod gltf_in;
pub use gltf_in::{GltfImport, Loader, MAX_GLTF_BYTES, MeshPlan, PlanPlace, glb_container, is_gltf_path, read_gltf};
mod obj;
pub use obj::read_obj;
-pub use threemf::{MAX_3MF_BYTES, MeshObject, model_xml, model_xml_with, read_3mf, weld, write_3mf, write_3mf_with};
+pub use threemf::{
+ MAX_3MF_BYTES, MeshObject, model_xml, model_xml_parts, model_xml_with, read_3mf, weld, write_3mf, write_3mf_parts, write_3mf_with,
+};
pub use urdf::{UrdfOptions, UrdfPackage, urdf};
use solidcraft_doc::{Document, Metadata, ModelState};
@@ -682,6 +684,21 @@ pub fn export_with_quality(
name: &str,
meta: &Metadata,
quality: MeshQuality,
+) -> Result<Vec<u8>> {
+ export_with_parts(state, bodies, &[], format, name, meta, quality)
+}
+
+/// [`export_with_quality`], and in 3MF each of `parts` (a name and the names of its bodies)
+/// written as one object with those bodies as its parts ([`model_xml_parts`], #8139).
+/// Bodies of a part that are not exported are left out of it. Other formats have no parts.
+pub fn export_with_parts(
+ state: &ModelState,
+ bodies: &[String],
+ parts: &[(String, Vec<String>)],
+ format: Format,
+ name: &str,
+ meta: &Metadata,
+ quality: MeshQuality,
) -> Result<Vec<u8>> {
let sel = selected(state, bodies)?;
Ok(match format {
@@ -716,7 +733,9 @@ pub fn export_with_quality(
}
Format::ThreeMf | Format::ThreeMfTagged => {
let objs: Vec<MeshObject> = sel.iter().map(|b| mesh_object(b, format == Format::ThreeMfTagged, quality)).collect::<Result<_>>()?;
- write_3mf_with(&objs, &threemf_metadata(meta))?
+ let index = |n: &String| sel.iter().position(|b| &b.name == n);
+ let parts: Vec<(String, Vec<usize>)> = parts.iter().map(|(p, names)| (p.clone(), names.iter().filter_map(index).collect())).collect();
+ write_3mf_parts(&objs, &parts, &threemf_metadata(meta))?
}
Format::Design => return Err(IoError::Format("sc (save the document instead)".into())),
Format::Urdf => return Err(IoError::Format("urdf (an assembly package; use file.export)".into())),
diff --git a/crates/io/src/threemf.rs b/crates/io/src/threemf.rs
index 65c703a2cd..c2c768baf0 100644
--- a/crates/io/src/threemf.rs
+++ b/crates/io/src/threemf.rs
@@ -251,6 +251,15 @@ pub fn model_xml(objects: &[MeshObject]) -> String {
/// The model part's XML with model metadata after `Application`: (3MF metadata name, such as
/// `Title` or `Designer`, and its text).
pub fn model_xml_with(objects: &[MeshObject], metadata: &[(&str, &str)]) -> String {
+ model_xml_parts(objects, &[], metadata)
+}
+
+/// [`model_xml_with`], with `parts`: each a name and the indices of two or more `objects` written
+/// as one object whose `<components>` are their meshes, built once, so a slicer loads them as
+/// one object with parts (#8139). An index out of range or already in an earlier part is left
+/// out of it, and a part left with fewer than two objects is not made: those objects are built
+/// on their own, as every object not in a part is.
+pub fn model_xml_parts(objects: &[MeshObject], parts: &[(String, Vec<usize>)], metadata: &[(&str, &str)]) -> String {
let mut x = String::new();
x.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
let ft = if objects.iter().any(MeshObject::tagged) { format!(" xmlns:ft=\"{FACE_TAGS_NS}\"") } else { String::new() };
@@ -314,10 +323,37 @@ pub fn model_xml_with(objects: &[MeshObject], metadata: &[(&str, &str)]) -> Stri
}
x.push_str(" </triangles>\n </mesh>\n </object>\n");
}
+ // Each part an object after the meshes it names (a component refers back), built in their
+ // place; the meshes in it are not built on their own.
+ let mut in_part = vec![false; objects.len()];
+ let mut built: Vec<usize> = Vec::new();
+ for (name, members) in parts {
+ let mut kept: Vec<usize> = Vec::new();
+ for &k in members {
+ if k < objects.len() && !in_part[k] && !kept.contains(&k) {
+ kept.push(k);
+ }
+ }
+ if kept.len() < 2 {
+ continue;
+ }
+ let id = objects.len() + 2 + built.len();
+ let _ = writeln!(x, " <object id=\"{id}\" type=\"model\" name=\"{}\">", esc(name));
+ x.push_str(" <components>\n");
+ for &k in &kept {
+ in_part[k] = true;
+ let _ = writeln!(x, " <component objectid=\"{}\"/>", k + 2);
+ }
+ x.push_str(" </components>\n </object>\n");
+ built.push(id);
+ }
x.push_str(" </resources>\n <build>\n");
- for k in 0..objects.len() {
+ for k in (0..objects.len()).filter(|&k| !in_part[k]) {
let _ = writeln!(x, " <item objectid=\"{}\"/>", k + 2);
}
+ for id in built {
+ let _ = writeln!(x, " <item objectid=\"{id}\"/>");
+ }
x.push_str(" </build>\n</model>\n");
x
}
@@ -329,6 +365,11 @@ pub fn write_3mf(objects: &[MeshObject]) -> Result<Vec<u8>> {
/// A 3MF package of meshes with model metadata (see [`model_xml_with`]).
pub fn write_3mf_with(objects: &[MeshObject], metadata: &[(&str, &str)]) -> Result<Vec<u8>> {
+ write_3mf_parts(objects, &[], metadata)
+}
+
+/// A 3MF package of meshes, some of them written as objects with parts (see [`model_xml_parts`]).
+pub fn write_3mf_parts(objects: &[MeshObject], parts: &[(String, Vec<usize>)], metadata: &[(&str, &str)]) -> Result<Vec<u8>> {
if objects.is_empty() {
return Err(IoError::Empty);
}
@@ -336,7 +377,7 @@ pub fn write_3mf_with(objects: &[MeshObject], metadata: &[(&str, &str)]) -> Resu
let rels = format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">\n <Relationship Target=\"/3D/3dmodel.model\" Id=\"rel0\" Type=\"{MODEL_REL}\"/>\n</Relationships>\n"
);
- let model = model_xml_with(objects, metadata);
+ let model = model_xml_parts(objects, parts, metadata);
let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
for (name, data) in [("[Content_Types].xml", content_types.as_bytes()), ("_rels/.rels", rels.as_bytes()), ("3D/3dmodel.model", model.as_bytes())]
{
@@ -965,6 +1006,35 @@ pub(crate) mod tests {
}
}
+ /// #8139: objects in a part are written once as meshes and built once, as one object whose
+ /// components are those meshes; the others are built on their own, as before. Read back, the
+ /// part is one object named after it, with every triangle of its meshes.
+ #[test]
+ fn a_part_is_one_object_whose_components_are_its_meshes() {
+ let objects = [tetra("Cube"), tetra("Dome"), tetra("Loose")];
+ let x = model_xml_parts(&objects, &[("Bracket:1".into(), vec![0, 1])], &[]);
+ assert_eq!(x.matches("<mesh>").count(), 3, "{x}");
+ assert!(x.contains("<object id=\"5\" type=\"model\" name=\"Bracket:1\">"), "{x}");
+ assert!(x.contains("<component objectid=\"2\"/>") && x.contains("<component objectid=\"3\"/>"), "{x}");
+ let build = x.split("<build>").nth(1).unwrap_or_default();
+ assert_eq!(build.matches("<item ").count(), 2, "{x}");
+ assert!(build.contains("objectid=\"4\"") && build.contains("objectid=\"5\""), "{x}");
+ let (read, warnings) = read_3mf(&write_3mf_parts(&objects, &[("Bracket:1".into(), vec![0, 1])], &[]).unwrap()).unwrap();
+ assert!(warnings.is_empty(), "{warnings:?}");
+ let names: Vec<&str> = read.iter().map(|o| o.name.as_str()).collect();
+ assert_eq!(names, ["Loose", "Bracket:1"]);
+ assert_eq!(read[1].triangles.len(), 8);
+ // Without parts the file is as before: one built object per mesh.
+ assert_eq!(model_xml_parts(&objects, &[], &[]), model_xml_with(&objects, &[]));
+ assert_eq!(model_xml_with(&objects, &[]).split("<build>").nth(1).unwrap_or_default().matches("<item ").count(), 3);
+ // A part of one object, an index out of range, or one already in a part makes nothing new.
+ for parts in [vec![("One".to_string(), vec![2])], vec![("Out".to_string(), vec![0, 7])]] {
+ assert_eq!(model_xml_parts(&objects, &parts, &[]), model_xml_with(&objects, &[]), "{parts:?}");
+ }
+ let x = model_xml_parts(&objects, &[("A".into(), vec![0, 1]), ("B".into(), vec![1, 2])], &[]);
+ assert!(x.contains("name=\"A\"") && !x.contains("name=\"B\""), "{x}");
+ }
+
/// A see-through object writes its alpha; triangles of faces with colours of their own
/// point at their entries.
#[test]
diff --git a/docs/book/src/guide/files.md b/docs/book/src/guide/files.md
index d257e619c8..7156b007f1 100644
--- a/docs/book/src/guide/files.md
+++ b/docs/book/src/guide/files.md
@@ -47,6 +47,13 @@ panel, and in the right-click menu of a body) open the same dialog with that for
the selected bodies as STL, 3MF or 3MF with face tags (below) to a file you name, and you can change
the format there.
+A 3MF has one object per body, so a slicer arranges the bodies of a multi-body part apart on the
+bed. Scripts and the control channel can keep each component together: `file.export` or
+`file.save_mesh` with `objects: "component"` writes every placed component that holds two or more
+bodies as one 3MF object whose parts are those bodies. PrusaSlicer, OrcaSlicer, Bambu Studio and
+Cura then load it as one object with a part per body, and each part can take its own filament. The
+design's own bodies, and a component with a single body, stay objects of their own.
+
**File → Send to Slicer** (also on the Insert tab's Files panel, and in the right-click menu of a
body) is the short way: it saves the selected bodies as a 3MF in millimetres, without face tags,
and sends it to a slicer. It always asks which one and pre-selects the slicer you used last time,