Skip to main content

brep_kernel/io/three_mf/
mod.rs

1//! 3MF (3D Manufacturing Format) import and export. [`write_3mf`] exports
2//! solids; [`write_3mf_meshes`] preserves imported mesh appearance.
3//!
4//! [`read_3mf`] reads a 3MF package (an OPC ZIP container) and returns the
5//! meshes its `<resources>` define plus the flattened list of instances the
6//! `<build>` places, in millimetres. It is a READER: the triangle soup it
7//! produces goes into the same mesh-to-solid chain STL and OBJ use
8//! (`brep_reconstruction::stl_conversion::convert_stl_mesh_to_step`); no
9//! geometry is built here.
10//!
11//! # What is supported
12//!
13//! The core specification (3MF Core Specification 1.x,
14//! `http://schemas.microsoft.com/3dmanufacturing/core/2015/02`):
15//!
16//! * `<model unit>` — `micron`, `millimeter`, `centimeter`, `inch`, `foot`,
17//!   `meter`, defaulting to `millimeter`; every coordinate and translation is
18//!   converted to millimetres, the unit the kernel works in.
19//! * `<resources>` with `<object id type>` carrying either a `<mesh>`
20//!   (`<vertices><vertex x y z>`, `<triangles><triangle v1 v2 v3>`) or a
21//!   `<components>` list of `<component objectid transform>`.
22//! * `<build>` with `<item objectid transform>`.
23//! * The 3x4 row-vector `transform` attribute on components and items, composed
24//!   inner-to-outer, with the winding of a mirrored instance reversed so the
25//!   soup stays outward-facing.
26//!
27//! # Colours
28//!
29//! The core specification's one property group IS read: `<basematerials>` with
30//! its `<base displaycolor="#RRGGBB">` entries, an object's `pid`/`pindex`
31//! default and a triangle's own `pid`/`p1`. Each triangle of
32//! [`ThreeMfMesh::triangle_colors`] (and of the flattened
33//! [`ThreeMfReadResult::triangle_colors`]) is the colour it resolves to, or
34//! `None` — a triangle with no resolvable RGB property. The vectors are empty
35//! when no triangle resolves. Legacy malformed or dangling base-material
36//! references remain `None`; extension references are checked explicitly. This is what the
37//! writer ([`write_3mf`]) emits, so an export re-imports with its colours.
38//!
39//! # Materials extensions
40//!
41//! Colour groups preserve RGBA at each triangle corner. Texture groups retain
42//! per-corner UVs, packaged PNG bytes and sampling settings. Composite materials
43//! retain their constituent display colours and fractions. RGB-only consumers
44//! receive a per-triangle preview; textures have no invented flat colour.
45//! [`write_3mf_meshes`] exports this appearance without solid reconstruction.
46//!
47//! Required extension prefixes are resolved by namespace URI. Unknown required
48//! extensions and unsupported material resources refuse by name. Simple beam
49//! lattices remain named, placed non-solid data alongside their triangle meshes.
50//! Clipping, balls, beam properties and representation meshes refuse precisely;
51//! consumers must not present the triangle soup alone as the complete solid.
52//! Other optional extension subtrees and metadata are skipped.
53//!
54//! Anything the core specification makes required and the file omits — the
55//! start-part relationship, an object id, a triangle's vertex indices, a
56//! component's or item's `objectid` — is refused with a [`ThreeMfError`]
57//! naming the package part it was read from.
58//!
59//! # Bounds
60//!
61//! Nothing here grows to fit its input. The container refuses encryption,
62//! ZIP64, multi-disk packages and any compression but stored and deflate; a
63//! part is refused before decompression when it DECLARES more than
64//! [`MAX_PART_BYTES`], the deflate output stops at the declared size, and every
65//! part's CRC-32 and length are verified after it. The XML reader refuses a
66//! `<!DOCTYPE>` outright (so no entity is expanded, internal or external) and
67//! caps nesting. The model is held to [`MAX_MESH_VERTICES`],
68//! [`MAX_MESH_TRIANGLES`], [`MAX_INSTANCES`], [`MAX_TOTAL_TRIANGLES`] and
69//! [`MAX_COMPONENT_DEPTH`]. Every offset in the container is computed with
70//! `checked_add`, because the kernel's release profile sets
71//! `overflow-checks = false`.
72//!
73//! # Dependency review (why the container is hand-rolled)
74//!
75//! `BREP_kernel` publishes to crates.io and compiles to wasm on nine declared
76//! dependencies, seven of them unconditional; `zip` and `flate2` appear nowhere
77//! in `BREP_kernel/Cargo.lock` (they are in `BREP_app`'s lock only, pulled in by
78//! the egui/image stack, not by anything the kernel links). `zip` with
79//! `default-features = false, features = ["deflate"]` still adds `flate2`,
80//! `miniz_oxide`, `crc32fast`, `adler2` and their support crates to a published
81//! geometry kernel. The container here is ~1000 lines of reader for a format the
82//! kernel needs in one place, matching how STEP, IGES, STL and OBJ are already
83//! read: [`zip`] parses the central directory, [`inflate`] implements RFC 1951,
84//! [`xml`] is a bounded pull parser. Every one of them refuses rather than grows.
85
86pub(crate) mod inflate;
87mod model;
88mod mesh_write;
89pub use mesh_write::write_3mf_meshes;
90mod write;
91mod xml;
92mod zip;
93
94pub use write::{write_3mf, ThreeMfSolid, ThreeMfWriteReport};
95
96
97use serde::Serialize;
98
99/// The 3MF core-specification namespace this reader accepts elements from.
100pub const MATERIAL_NAMESPACE: &str = "http://schemas.microsoft.com/3dmanufacturing/material/2015/02";
101pub const BEAM_NAMESPACE: &str = "http://schemas.microsoft.com/3dmanufacturing/beamlattice/2017/02";
102pub const CORE_NAMESPACE: &str = "http://schemas.microsoft.com/3dmanufacturing/core/2015/02";
103/// The OPC relationships namespace of `_rels/.rels`.
104const RELATIONSHIP_NAMESPACE: &str = "http://schemas.openxmlformats.org/package/2006/relationships";
105/// The relationship type naming the package's primary 3D model part.
106const MODEL_RELATIONSHIP: &str = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel";
107/// The package-level relationships part; required of every OPC package.
108const RELATIONSHIP_PART: &str = "_rels/.rels";
109
110/// Largest part this reader will expand, compressed or stored. A 3MF model part
111/// is XML: 256 MiB is roughly five million triangles of it.
112pub const MAX_PART_BYTES: usize = 256 * 1024 * 1024;
113/// Largest vertex and triangle counts accepted for one `<mesh>`.
114pub const MAX_MESH_VERTICES: usize = 8_000_000;
115pub const MAX_MESH_TRIANGLES: usize = 16_000_000;
116/// Largest number of placements the `<build>` may flatten to.
117pub const MAX_INSTANCES: usize = 65_536;
118/// Largest flattened triangle total across all instances.
119pub const MAX_TOTAL_TRIANGLES: usize = 32_000_000;
120/// Deepest `<components>` nesting followed when flattening. The core spec's
121/// "an object must be defined before it is referenced" already forbids cycles;
122/// this bounds the work a legal but pathological file can ask for.
123pub const MAX_COMPONENT_DEPTH: usize = 32;
124
125/// Why a 3MF package was refused. Every variant that belongs to a package part
126/// names it, so the message says where in the container the fault is.
127#[derive(Clone, Debug, PartialEq, Eq)]
128pub enum ThreeMfError {
129    /// The bytes are not a readable OPC/ZIP container at all.
130    Container(String),
131    /// A part is in the container but its bytes cannot be recovered: a bad
132    /// local header, a short read, a failed CRC-32.
133    Damaged { part: String, detail: String },
134    /// A part the core specification requires is absent.
135    MissingPart { part: String, detail: String },
136    /// A container or format feature this reader refuses on purpose.
137    Unsupported { part: String, detail: String },
138    /// A part exceeds one of this reader's documented bounds.
139    Bounds { part: String, detail: String },
140    /// A part is not well-formed XML.
141    Xml { part: String, detail: String },
142    /// A part is well-formed XML but violates the core specification.
143    Model { part: String, detail: String },
144}
145
146impl ThreeMfError {
147    /// The package part the failure was found in, when it belongs to one.
148    pub fn part(&self) -> Option<&str> {
149        match self {
150            Self::Container(_) => None,
151            Self::Damaged { part, .. }
152            | Self::MissingPart { part, .. }
153            | Self::Unsupported { part, .. }
154            | Self::Bounds { part, .. }
155            | Self::Xml { part, .. }
156            | Self::Model { part, .. } => Some(part),
157        }
158    }
159}
160
161impl core::fmt::Display for ThreeMfError {
162    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
163        match self {
164            Self::Container(detail) => write!(f, "3MF package: {detail}"),
165            Self::Damaged { part, detail } => write!(f, "3MF '{part}' is damaged: {detail}"),
166            Self::MissingPart { part, detail } => write!(f, "3MF '{part}' is missing: {detail}"),
167            Self::Unsupported { part, detail } => write!(f, "3MF '{part}': {detail}"),
168            Self::Bounds { part, detail } => write!(f, "3MF '{part}' exceeds a bound: {detail}"),
169            Self::Xml { part, detail } => write!(f, "3MF '{part}' is not well-formed: {detail}"),
170            Self::Model { part, detail } => write!(f, "3MF '{part}': {detail}"),
171        }
172    }
173}
174
175impl std::error::Error for ThreeMfError {}
176
177/// The `unit` a model part declares, with its conversion to millimetres.
178#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
179pub enum ThreeMfUnit {
180    Micron,
181    Millimeter,
182    Centimeter,
183    Inch,
184    Foot,
185    Meter,
186}
187
188impl ThreeMfUnit {
189    /// The spec's unit table (3MF Core, `<model unit>`), in millimetres.
190    pub fn millimetres(self) -> f64 {
191        match self {
192            Self::Micron => 0.001,
193            Self::Millimeter => 1.0,
194            Self::Centimeter => 10.0,
195            Self::Inch => 25.4,
196            Self::Foot => 304.8,
197            Self::Meter => 1000.0,
198        }
199    }
200
201    pub fn name(self) -> &'static str {
202        match self {
203            Self::Micron => "micron",
204            Self::Millimeter => "millimeter",
205            Self::Centimeter => "centimeter",
206            Self::Inch => "inch",
207            Self::Foot => "foot",
208            Self::Meter => "meter",
209        }
210    }
211
212    fn parse(text: &str) -> Option<Self> {
213        Some(match text {
214            "micron" => Self::Micron,
215            "millimeter" => Self::Millimeter,
216            "centimeter" => Self::Centimeter,
217            "inch" => Self::Inch,
218            "foot" => Self::Foot,
219            "meter" => Self::Meter,
220            _ => return None,
221        })
222    }
223}
224
225/// Lossless per-corner appearance, in triangle winding order.
226#[derive(Clone, Debug, PartialEq, Serialize)]
227pub enum ThreeMfAppearance {
228    Colors([[u8; 4]; 3]),
229    Texture { texture_id: u32, uv: [[f64; 2]; 3] },
230    Composite { colors: Vec<[u8; 3]>, weights: [Vec<f64>; 3] },
231}
232
233impl ThreeMfAppearance {
234    /// RGB preview for consumers that support only one colour per face.
235    pub fn preview_rgb(&self) -> Option<[u8; 3]> {
236        let mut rgb = [0; 3];
237        match self {
238            Self::Colors(colors) => {
239                // Core 3MF requires a consumer without gradients to use p1.
240                rgb.copy_from_slice(&colors[0][..3]);
241            }
242            Self::Composite { colors, weights } => {
243                let weights = &weights[0];
244                let sum: f64 = weights.iter().take(colors.len()).sum();
245                for i in 0..3 {
246                    let mixed: f64 = colors.iter().enumerate().map(|(j, c)| {
247                        let fraction = if sum > 0.0 { weights.get(j).copied().unwrap_or(0.0) / sum }
248                            else { 1.0 / colors.len() as f64 };
249                        c[i] as f64 * fraction
250                    }).sum();
251                    rgb[i] = mixed.round().clamp(0.0,255.0) as u8;
252                }
253            }
254            Self::Texture { .. } => return None,
255        }
256        Some(rgb)
257    }
258    fn reverse(&mut self) {
259        match self {
260            Self::Colors(c) => c.swap(1, 2),
261            Self::Texture { uv, .. } => uv.swap(1, 2),
262            Self::Composite { weights, .. } => weights.swap(1, 2),
263        }
264    }
265}
266
267/// Beam parameters retained as non-solid data, in object-local millimetres.
268/// Apply the containing instance's full affine transform to the beam surface;
269/// transforming only the endpoints/radii is insufficient for shear or scaling.
270#[derive(Clone, Debug, PartialEq, Serialize)]
271pub struct ThreeMfBeam {
272    pub vertices: [u32; 2],
273    pub radii: [f64; 2],
274    pub caps: [String; 2],
275}
276
277/// A lattice retained independently of the triangle soup, never claimed as a solid.
278#[derive(Clone, Debug, PartialEq, Serialize)]
279pub struct ThreeMfBeamLattice {
280    pub min_length: f64,
281    pub beams: Vec<ThreeMfBeam>,
282}
283
284/// A packaged PNG and its sampling settings. Pixels remain encoded.
285#[derive(Clone, Debug, PartialEq, Serialize)]
286pub struct ThreeMfTexture {
287    pub id: u32,
288    pub path: String,
289    pub png: Vec<u8>,
290    pub tile_u: String,
291    pub tile_v: String,
292    pub filter: String,
293}
294
295/// One `<object>`'s mesh, in millimetres and in the object's own coordinates.
296/// Shared: an object placed three times is ONE entry here and three
297/// [`ThreeMfInstance`]s.
298#[derive(Clone, Debug, Default, PartialEq, Serialize)]
299pub struct ThreeMfMesh {
300    /// The id of the `<object>` this mesh belongs to.
301    pub object_id: u32,
302    /// Non-solid lattice data; named and placed through the mesh instances.
303    pub beam_lattice: Option<ThreeMfBeamLattice>,
304    /// Vertex coordinates as xyz triples, millimetres.
305    pub positions: Vec<f64>,
306    /// Triangle corners, three indices into `positions`/3.
307    pub indices: Vec<u32>,
308    /// One entry per triangle — the 8-bit sRGB colour its base material gives
309    /// it, or `None` — when at least one triangle of the mesh resolves to a
310    /// colour; EMPTY otherwise. See the module doc's "Colours".
311    pub triangle_colors: Vec<Option<[u8; 3]>>,
312    /// Lossless appearance parallel to triangles; empty when absent.
313    pub triangle_appearance: Vec<Option<ThreeMfAppearance>>,
314}
315
316impl ThreeMfMesh {
317    pub fn vertex_count(&self) -> usize {
318        self.positions.len() / 3
319    }
320    pub fn triangle_count(&self) -> usize {
321        self.indices.len() / 3
322    }
323}
324
325/// One placement of one mesh: a `<build><item>`, or a `<component>` reached
326/// through one, with the transforms from the item down composed.
327#[derive(Clone, Debug, PartialEq, Serialize)]
328pub struct ThreeMfInstance {
329    /// The mesh-bearing object placed (not the item's `objectid` when the item
330    /// pointed at a `<components>` object).
331    pub object_id: u32,
332    /// Index into [`ThreeMfReadResult::meshes`].
333    pub mesh: usize,
334    /// The composed 3x4 row-vector transform, in 3MF attribute order
335    /// (`m00 m01 m02 m10 m11 m12 m20 m21 m22 m30 m31 m32`), translation in mm.
336    pub transform: [f64; 12],
337    /// Where this instance's geometry sits in the flattened buffers: its
338    /// vertices are `positions[first_vertex * 3 ..][.. vertex_count * 3]` and
339    /// its triangles `indices[first_triangle * 3 ..][.. triangle_count * 3]`.
340    /// Instances are laid out in order and never share a vertex, which is what
341    /// lets a consumer take one body out without re-flattening the build.
342    pub first_vertex: usize,
343    pub vertex_count: usize,
344    pub first_triangle: usize,
345    pub triangle_count: usize,
346    /// The placed object's `name`, or failing that the nearest named
347    /// `<components>` object above it; `None` when nothing on the way was
348    /// named. Carries no geometry.
349    pub name: Option<String>,
350}
351
352impl ThreeMfInstance {
353    /// Place an object-local point: `x' = x·m00 + y·m10 + z·m20 + m30`.
354    pub fn transform_point(&self, point: [f64; 3]) -> [f64; 3] {
355        transform_point(&self.transform, point)
356    }
357}
358
359/// Everything [`read_3mf`] recovered from a package.
360#[derive(Clone, Debug, Serialize)]
361pub struct ThreeMfReadResult {
362    /// The part the model was read from (from the start-part relationship).
363    pub model_part: String,
364    /// The unit the file declared, before conversion.
365    pub unit: ThreeMfUnit,
366    /// Packaged textures referenced by material resources.
367    pub textures: Vec<ThreeMfTexture>,
368    /// One entry per mesh-bearing `<object>` in `<resources>`, in document
369    /// order — including any the build never places.
370    pub meshes: Vec<ThreeMfMesh>,
371    /// The `<build>`, flattened through `<components>`: one entry per placed
372    /// mesh. Objects of a type other than `model` are not placed.
373    pub instances: Vec<ThreeMfInstance>,
374    /// Every instance's triangles in world coordinates, millimetres — the soup
375    /// the mesh-to-solid chain reads.
376    pub positions: Vec<f64>,
377    /// Triangle corners into `positions`/3, winding preserved (reversed for a
378    /// mirrored instance so the result stays outward-facing).
379    pub indices: Vec<u32>,
380    /// Parallel to the flattened triangles (`indices.len() / 3` entries, each
381    /// following its triangle through the instance order and a mirrored
382    /// placement's winding reversal) when any placed triangle resolves to a
383    /// colour; EMPTY otherwise.
384    pub triangle_colors: Vec<Option<[u8; 3]>>,
385    /// Lossless appearance parallel to triangles; empty when absent.
386    pub triangle_appearance: Vec<Option<ThreeMfAppearance>>,
387}
388
389impl ThreeMfReadResult {
390    pub fn vertex_count(&self) -> usize {
391        self.positions.len() / 3
392    }
393    pub fn triangle_count(&self) -> usize {
394        self.indices.len() / 3
395    }
396
397    /// ONE instance's triangle soup: its world-space vertices and its triangles
398    /// rebased onto them. A multi-instance build is several bodies in one
399    /// buffer — this is how a consumer takes them apart by PLACEMENT without
400    /// knowing how `read_3mf` laid them out. The importer does not need it: the
401    /// mesh-to-solid chain splits the whole soup into its vertex-connected
402    /// components and reconstructs each as its own body. It is the answer when
403    /// the question is which instance a body came from, which the geometry
404    /// alone cannot say (two instances that touch are one component).
405    pub fn instance_mesh(&self, instance: usize) -> Option<(Vec<f64>, Vec<u32>)> {
406        let instance = self.instances.get(instance)?;
407        let positions = self
408            .positions
409            .get(instance.first_vertex * 3..(instance.first_vertex + instance.vertex_count) * 3)?
410            .to_vec();
411        let base = instance.first_vertex as u32;
412        let indices = self
413            .indices
414            .get(
415                instance.first_triangle * 3
416                    ..(instance.first_triangle + instance.triangle_count) * 3,
417            )?
418            .iter()
419            .map(|index| index - base)
420            .collect();
421        Some((positions, indices))
422    }
423}
424
425/// The identity 3x4 transform, in 3MF attribute order.
426pub const IDENTITY: [f64; 12] = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0];
427
428/// Place a point with a 3MF row-vector transform.
429pub fn transform_point(transform: &[f64; 12], point: [f64; 3]) -> [f64; 3] {
430    let [x, y, z] = point;
431    [
432        x * transform[0] + y * transform[3] + z * transform[6] + transform[9],
433        x * transform[1] + y * transform[4] + z * transform[7] + transform[10],
434        x * transform[2] + y * transform[5] + z * transform[8] + transform[11],
435    ]
436}
437
438/// Compose `inner` then `outer` (row vectors: `p · inner · outer`) — a
439/// component's transform inside the item that placed it.
440pub fn compose(inner: &[f64; 12], outer: &[f64; 12]) -> [f64; 12] {
441    let mut out = [0.0; 12];
442    for row in 0..4 {
443        for column in 0..3 {
444            let mut sum = if row == 3 { outer[9 + column] } else { 0.0 };
445            for k in 0..3 {
446                sum += inner[row * 3 + k] * outer[k * 3 + column];
447            }
448            out[row * 3 + column] = sum;
449        }
450    }
451    out
452}
453
454/// The determinant of the transform's linear part; negative means the instance
455/// is mirrored and its triangle winding has to be reversed.
456fn determinant(transform: &[f64; 12]) -> f64 {
457    let m = transform;
458    m[0] * (m[4] * m[8] - m[5] * m[7]) - m[1] * (m[3] * m[8] - m[5] * m[6])
459        + m[2] * (m[3] * m[7] - m[4] * m[6])
460}
461
462/// Read a 3MF package: locate the model part through the OPC relationships,
463/// parse the core model, and flatten the build into a millimetre triangle soup.
464///
465/// See the module documentation for what is read, what is ignored, and the
466/// bounds every part is held to.
467pub fn read_3mf(bytes: &[u8]) -> Result<ThreeMfReadResult, ThreeMfError> {
468    let archive = zip::ZipArchive::open(bytes).map_err(map_zip)?;
469    let relationships = archive.find(RELATIONSHIP_PART).ok_or_else(|| {
470        ThreeMfError::MissingPart {
471            part: RELATIONSHIP_PART.into(),
472            detail: "an OPC package must carry the package relationships part".into(),
473        }
474    })?;
475    let relationships_text = read_text(&archive, relationships, RELATIONSHIP_PART)?;
476    let model_part = start_part(&relationships_text)?;
477    let model_entry = archive.find(&model_part).ok_or_else(|| ThreeMfError::MissingPart {
478        part: model_part.clone(),
479        detail: format!("'{RELATIONSHIP_PART}' names it as the 3D model start part"),
480    })?;
481    let model_text = read_text(&archive, model_entry, &model_part)?;
482    let mut document = model::parse_model(&model_part, &model_text)?;
483    let mut texture_bytes = 0usize;
484    for texture in &mut document.textures {
485        let entry = archive.find(&texture.path).ok_or_else(|| ThreeMfError::MissingPart {
486            part: texture.path.clone(), detail: format!("texture2d {} references this PNG", texture.id),
487        })?;
488        texture.png = archive.read(entry, MAX_PART_BYTES.saturating_sub(texture_bytes)).map_err(map_zip)?;
489        texture_bytes += texture.png.len();
490        if !texture.png.starts_with(b"\x89PNG\r\n\x1a\n") {
491            return Err(ThreeMfError::Model { part: texture.path.clone(), detail: "texture2d is not a PNG".into() });
492        }
493    }
494    flatten(model_part, document)
495}
496
497/// Map a container fault onto the typed refusal, keeping the part name.
498fn map_zip(error: zip::ZipError) -> ThreeMfError {
499    let part = error.entry.clone().unwrap_or_else(|| "[package]".into());
500    match error.fault {
501        zip::ZipFault::Container => match &error.entry {
502            Some(entry) => ThreeMfError::Container(format!("{entry}: {}", error.message)),
503            None => ThreeMfError::Container(error.message),
504        },
505        zip::ZipFault::Damaged => ThreeMfError::Damaged { part, detail: error.message },
506        zip::ZipFault::Unsupported => ThreeMfError::Unsupported { part, detail: error.message },
507        zip::ZipFault::Bounds => ThreeMfError::Bounds { part, detail: error.message },
508    }
509}
510
511fn read_text(
512    archive: &zip::ZipArchive<'_>,
513    entry: &zip::ZipEntry,
514    part: &str,
515) -> Result<String, ThreeMfError> {
516    let bytes = archive.read(entry, MAX_PART_BYTES).map_err(map_zip)?;
517    String::from_utf8(bytes).map_err(|_| ThreeMfError::Xml {
518        part: part.to_owned(),
519        detail: "the part is not UTF-8 text".into(),
520    })
521}
522
523/// The `Target` of the package's 3D-model start-part relationship.
524fn start_part(text: &str) -> Result<String, ThreeMfError> {
525    let mut reader = xml::XmlReader::new(text);
526    loop {
527        let event = reader.next().map_err(|error| ThreeMfError::Xml {
528            part: RELATIONSHIP_PART.into(),
529            detail: error.to_string(),
530        })?;
531        match event {
532            xml::Event::Start(tag) => {
533                if tag.namespace != RELATIONSHIP_NAMESPACE {
534                    reader.skip_subtree(&tag).map_err(|error| ThreeMfError::Xml {
535                        part: RELATIONSHIP_PART.into(),
536                        detail: error.to_string(),
537                    })?;
538                    continue;
539                }
540                if tag.name != "Relationship" {
541                    continue;
542                }
543                if tag.attribute("Type") != Some(MODEL_RELATIONSHIP) {
544                    continue;
545                }
546                let target = tag.attribute("Target").ok_or_else(|| ThreeMfError::Model {
547                    part: RELATIONSHIP_PART.into(),
548                    detail: "the 3D model relationship has no Target".into(),
549                })?;
550                let target = target.trim_start_matches('/');
551                if target.is_empty() {
552                    return Err(ThreeMfError::Model {
553                        part: RELATIONSHIP_PART.into(),
554                        detail: "the 3D model relationship has an empty Target".into(),
555                    });
556                }
557                return Ok(target.to_owned());
558            }
559            xml::Event::End { .. } => {}
560            xml::Event::Eof => break,
561        }
562    }
563    Err(ThreeMfError::MissingPart {
564        part: RELATIONSHIP_PART.into(),
565        detail: format!("no relationship of type '{MODEL_RELATIONSHIP}' names a 3D model part"),
566    })
567}
568
569/// Walk the build, composing transforms, into instances and one triangle soup.
570fn flatten(
571    model_part: String,
572    document: model::ModelDocument,
573) -> Result<ThreeMfReadResult, ThreeMfError> {
574    let scale = document.unit.millimetres();
575    let meshes = document
576        .meshes
577        .iter()
578        .map(|mesh| {
579            let mut triangle_appearance = mesh.properties.iter()
580                .map(|p| document.appearance(p.or(mesh.object_property), &model_part))
581                .collect::<Result<Vec<_>, _>>()?;
582            let mut triangle_colors: Vec<_> = triangle_appearance.iter()
583                .map(|a| a.as_ref().and_then(ThreeMfAppearance::preview_rgb)).collect();
584            if triangle_appearance.iter().all(Option::is_none) { triangle_appearance.clear(); }
585            if triangle_colors.iter().all(Option::is_none) {
586                triangle_colors.clear();
587            }
588            Ok(ThreeMfMesh {
589                object_id: mesh.object_id,
590                beam_lattice: mesh.beam_lattice.clone().map(|mut lattice| {
591                    lattice.min_length *= scale;
592                    for beam in &mut lattice.beams { for r in &mut beam.radii { *r *= scale; } }
593                    lattice
594                }),
595                positions: mesh.positions.iter().map(|value| value * scale).collect(),
596                indices: mesh.indices.clone(),
597                triangle_colors,
598                triangle_appearance,
599            })
600        })
601        .collect::<Result<Vec<_>, ThreeMfError>>()?;
602    let mut instances = Vec::new();
603    for item in &document.items {
604        let mut transform = item.transform;
605        for value in &mut transform[9..12] {
606            *value *= scale;
607        }
608        place(&document, &model_part, item.object_id, transform, 0, None, &mut instances)?;
609    }
610    let mut positions = Vec::new();
611    let mut indices = Vec::new();
612    let mut triangle_colors: Vec<Option<[u8; 3]>> = Vec::new();
613    let colored = instances.iter().any(|instance| !meshes[instance.mesh].triangle_colors.is_empty());
614    let mut triangle_appearance = Vec::new();
615    let has_appearance = instances.iter().any(|i| !meshes[i.mesh].triangle_appearance.is_empty());
616    let mut triangles = 0usize;
617    for instance in &mut instances {
618        let mesh = &meshes[instance.mesh];
619        triangles += mesh.triangle_count();
620        if triangles > MAX_TOTAL_TRIANGLES {
621            return Err(ThreeMfError::Bounds {
622                part: model_part,
623                detail: format!(
624                    "the build places more than {MAX_TOTAL_TRIANGLES} triangles in total"
625                ),
626            });
627        }
628        instance.first_vertex = positions.len() / 3;
629        instance.vertex_count = mesh.vertex_count();
630        instance.first_triangle = indices.len() / 3;
631        instance.triangle_count = mesh.triangle_count();
632        let base = instance.first_vertex as u32;
633        for point in mesh.positions.chunks_exact(3) {
634            let placed = instance.transform_point([point[0], point[1], point[2]]);
635            positions.extend(placed);
636        }
637        // A mirrored placement turns the mesh inside out; reversing the winding
638        // keeps every triangle facing out of the body, which is what the
639        // mesh-to-solid chain reads.
640        let mirrored = determinant(&instance.transform) < 0.0;
641        for triangle in mesh.indices.chunks_exact(3) {
642            if mirrored {
643                indices.extend([base + triangle[0], base + triangle[2], base + triangle[1]]);
644            } else {
645                indices.extend([base + triangle[0], base + triangle[1], base + triangle[2]]);
646            }
647        }
648        if has_appearance {
649            for i in 0..mesh.triangle_count() {
650                let mut appearance = mesh.triangle_appearance.get(i).cloned().flatten();
651                if mirrored { if let Some(a) = &mut appearance { a.reverse(); } }
652                triangle_appearance.push(appearance);
653            }
654        }
655        // A colour rides with its triangle whichever way it is wound.
656        if colored {
657            if mesh.triangle_colors.is_empty() {
658                triangle_colors.extend(std::iter::repeat(None).take(mesh.triangle_count()));
659            } else {
660                triangle_colors.extend_from_slice(&mesh.triangle_colors);
661            }
662        }
663    }
664    Ok(ThreeMfReadResult {
665        model_part,
666        unit: document.unit,
667        textures: document.textures,
668        meshes,
669        instances,
670        positions,
671        indices,
672        triangle_colors,
673        triangle_appearance,
674    })
675}
676
677/// Place `object_id` under `transform`, recursing through `<components>`.
678fn place(
679    document: &model::ModelDocument,
680    model_part: &str,
681    object_id: u32,
682    transform: [f64; 12],
683    depth: usize,
684    inherited_name: Option<&str>,
685    instances: &mut Vec<ThreeMfInstance>,
686) -> Result<(), ThreeMfError> {
687    if depth > MAX_COMPONENT_DEPTH {
688        return Err(ThreeMfError::Bounds {
689            part: model_part.to_owned(),
690            detail: format!("components nest deeper than {MAX_COMPONENT_DEPTH} levels"),
691        });
692    }
693    let object = document.object(object_id).ok_or_else(|| ThreeMfError::Model {
694        part: model_part.to_owned(),
695        detail: format!("object {object_id} is placed but never defined"),
696    })?;
697    let name = object.name.as_deref().or(inherited_name);
698    match &object.content {
699        model::ObjectContent::Mesh(mesh) => {
700            // Only PRINTABLE geometry reaches the soup: support, surface and
701            // "other" objects describe the print job, not the part.
702            if object.model_type {
703                if instances.len() + 1 > MAX_INSTANCES {
704                    return Err(ThreeMfError::Bounds {
705                        part: model_part.to_owned(),
706                        detail: format!("the build places more than {MAX_INSTANCES} instances"),
707                    });
708                }
709                instances.push(ThreeMfInstance {
710                    object_id: object.id,
711                    mesh: *mesh,
712                    transform,
713                    // Filled by `flatten` when the soup is laid out.
714                    first_vertex: 0,
715                    vertex_count: 0,
716                    first_triangle: 0,
717                    triangle_count: 0,
718                    name: name.map(str::to_owned),
719                });
720            }
721            Ok(())
722        }
723        model::ObjectContent::Components(components) => {
724            for component in components {
725                let mut inner = component.transform;
726                // The component's translation is in the file's unit; the
727                // enclosing transform is already in millimetres, so scaling
728                // here (not in `flatten`) keeps one conversion per level.
729                let scale = document.unit.millimetres();
730                for value in &mut inner[9..12] {
731                    *value *= scale;
732                }
733                let composed = compose(&inner, &transform);
734                place(
735                    document,
736                    model_part,
737                    component.object_id,
738                    composed,
739                    depth + 1,
740                    name,
741                    instances,
742                )?;
743            }
744            Ok(())
745        }
746    }
747}