lib3mf-core 0.4.0

Parse and validate 3MF files for manufacturing workflows - production-ready with streaming parser and comprehensive validation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
use crate::error::{Lib3mfError, Result};
use crate::model::{
    BaseMaterialsGroup, ColorGroup, CompositeMaterials, Geometry, Model, MultiProperties, Object,
    Texture2DGroup, Unit,
};
use crate::parser::boolean_parser::parse_boolean_shape;
use crate::parser::build_parser::parse_build;
use crate::parser::component_parser::parse_components;
use crate::parser::displacement_parser::{parse_displacement_2d, parse_displacement_mesh};
use crate::parser::material_parser::{
    parse_base_materials, parse_color_group, parse_composite_materials, parse_multi_properties,
    parse_texture_2d_group,
};
use crate::parser::mesh_parser::parse_mesh;
use crate::parser::slice_parser::parse_slice_stack_content;
use crate::parser::volumetric_parser::parse_volumetric_stack_content;
use crate::parser::xml_parser::{XmlParser, get_attribute, get_attribute_f32, get_attribute_u32};
use quick_xml::events::Event;
use std::io::BufRead;

/// Parses a complete 3MF model XML document from the given reader into a `Model`.
pub fn parse_model<R: BufRead>(reader: R) -> Result<Model> {
    let mut parser = XmlParser::new(reader);
    let mut model = Model::default();
    let mut seen_model_element = false;
    let mut seen_build_element = false;
    let mut model_ended = false;

    loop {
        match parser.read_next_event()? {
            Event::Start(e) => match e.name().as_ref() {
                b"model" => {
                    if seen_model_element {
                        return Err(Lib3mfError::Validation(
                            "Multiple <model> elements found. Only one <model> element is allowed per document".to_string(),
                        ));
                    }
                    if model_ended {
                        return Err(Lib3mfError::Validation(
                            "Multiple <model> elements found. Only one <model> element is allowed per document".to_string(),
                        ));
                    }
                    seen_model_element = true;

                    // Validate that xml:space attribute is not present
                    // The 3MF spec does not allow xml:space on the model element
                    if get_attribute(&e, b"xml:space").is_some() {
                        return Err(Lib3mfError::Validation(
                            "The xml:space attribute is not allowed on the <model> element in 3MF files".to_string(),
                        ));
                    }

                    if let Some(unit_str) = get_attribute(&e, b"unit") {
                        model.unit = match unit_str.as_ref() {
                            "micron" => Unit::Micron,
                            "millimeter" => Unit::Millimeter,
                            "centimeter" => Unit::Centimeter,
                            "inch" => Unit::Inch,
                            "foot" => Unit::Foot,
                            "meter" => Unit::Meter,
                            _ => Unit::Millimeter, // Default or warn?
                        };
                    }
                    model.language = get_attribute(&e, b"xml:lang").map(|s| s.into_owned());

                    // Extract extra namespace declarations (e.g., xmlns:BambuStudio)
                    for attr in e.attributes().flatten() {
                        let key = std::str::from_utf8(attr.key.as_ref()).unwrap_or("");
                        if let Some(prefix) = key.strip_prefix("xmlns:") {
                            // Skip known namespaces that we already emit
                            let known = ["m", "p", "b", "d", "s", "v", "sec", "bl"];
                            if !known.contains(&prefix) {
                                let uri = String::from_utf8_lossy(&attr.value).to_string();
                                model.extra_namespaces.insert(prefix.to_string(), uri);
                            }
                        }
                    }
                }
                b"metadata" => {
                    let name = get_attribute(&e, b"name")
                        .ok_or(Lib3mfError::Validation("Metadata missing name".to_string()))?
                        .into_owned();
                    if model.metadata.contains_key(&name) {
                        return Err(Lib3mfError::Validation(format!(
                            "Duplicate metadata name '{}'. Each metadata name must be unique",
                            name
                        )));
                    }
                    let content = parser.read_text_content()?;
                    model.metadata.insert(name, content);
                }
                b"resources" => parse_resources(&mut parser, &mut model)?,
                b"build" => {
                    seen_build_element = true;
                    model.build = parse_build(&mut parser)?;
                }
                _ => {}
            },
            Event::Empty(e) => {
                if e.name().as_ref() == b"metadata" {
                    let name = get_attribute(&e, b"name")
                        .ok_or(Lib3mfError::Validation("Metadata missing name".to_string()))?;
                    if model.metadata.contains_key(name.as_ref()) {
                        return Err(Lib3mfError::Validation(format!(
                            "Duplicate metadata name '{}'. Each metadata name must be unique",
                            name
                        )));
                    }
                    model.metadata.insert(name.into_owned(), String::new());
                }
            }
            Event::End(e) if e.name().as_ref() == b"model" => {
                model_ended = true;
            }
            Event::Eof => break,
            _ => {}
        }
    }

    if !seen_build_element {
        return Err(Lib3mfError::Validation(
            "Missing required <build> element. Every 3MF model must contain a <build> element"
                .to_string(),
        ));
    }

    Ok(model)
}

fn parse_resources<R: BufRead>(parser: &mut XmlParser<R>, model: &mut Model) -> Result<()> {
    loop {
        match parser.read_next_event()? {
            Event::Start(e) => {
                let local_name = e.local_name();
                match local_name.as_ref() {
                    b"object" => {
                        let id = crate::model::ResourceId(get_attribute_u32(&e, b"id")?);
                        let name = get_attribute(&e, b"name").map(|s| s.into_owned());
                        let part_number = get_attribute(&e, b"partnumber").map(|s| s.into_owned());
                        let pid = get_attribute_u32(&e, b"pid")
                            .map(crate::model::ResourceId)
                            .ok();
                        let pindex = get_attribute_u32(&e, b"pindex").ok();
                        let uuid = crate::parser::xml_parser::get_attribute_uuid(&e)?;

                        // Check for slicestackid (default or prefixed)
                        let slice_stack_id = get_attribute_u32(&e, b"slicestackid")
                            .or_else(|_| get_attribute_u32(&e, b"s:slicestackid"))
                            .map(crate::model::ResourceId)
                            .ok();

                        // Check for volumetricstackid (hypothetical prefix v:)
                        let vol_stack_id = get_attribute_u32(&e, b"volumetricstackid")
                            .or_else(|_| get_attribute_u32(&e, b"v:volumetricstackid"))
                            .map(crate::model::ResourceId)
                            .ok();

                        let object_type = match get_attribute(&e, b"type") {
                            Some(type_str) => match type_str.as_ref() {
                                "model" => crate::model::ObjectType::Model,
                                "support" => crate::model::ObjectType::Support,
                                "solidsupport" => crate::model::ObjectType::SolidSupport,
                                "surface" => crate::model::ObjectType::Surface,
                                "other" => crate::model::ObjectType::Other,
                                unknown => {
                                    return Err(Lib3mfError::Validation(format!(
                                        "Invalid object type '{}'. Valid types are: model, support, solidsupport, surface, other",
                                        unknown
                                    )));
                                }
                            },
                            None => crate::model::ObjectType::Model,
                        };

                        let thumbnail = get_attribute(&e, b"thumbnail").map(|s| s.into_owned());

                        let geometry_content = parse_object_geometry(parser)?;

                        let geometry = if let Some(ssid) = slice_stack_id {
                            if geometry_content.has_content() {
                                eprintln!(
                                    "Warning: Object {} has slicestackid but also contains geometry content; geometry will be ignored",
                                    id.0
                                );
                            }
                            crate::model::Geometry::SliceStack(ssid)
                        } else if let Some(vsid) = vol_stack_id {
                            if geometry_content.has_content() {
                                eprintln!(
                                    "Warning: Object {} has volumetricstackid but also contains geometry content; geometry will be ignored",
                                    id.0
                                );
                            }
                            crate::model::Geometry::VolumetricStack(vsid)
                        } else {
                            geometry_content
                        };

                        let object = Object {
                            id,
                            object_type,
                            name,
                            part_number,
                            uuid,
                            pid,
                            pindex,
                            thumbnail,
                            geometry,
                        };
                        model.resources.add_object(object)?;
                    }
                    b"basematerials" => {
                        let id = crate::model::ResourceId(get_attribute_u32(&e, b"id")?);
                        let group = parse_base_materials(parser, id)?;
                        model.resources.add_base_materials(group)?;
                    }
                    b"colorgroup" => {
                        let id = crate::model::ResourceId(get_attribute_u32(&e, b"id")?);
                        let group = parse_color_group(parser, id)?;
                        model.resources.add_color_group(group)?;
                    }
                    b"texture2d" => {
                        let id = crate::model::ResourceId(get_attribute_u32(&e, b"id")?);
                        let path = get_attribute(&e, b"path")
                            .ok_or(Lib3mfError::Validation(
                                "texture2d missing required 'path' attribute".to_string(),
                            ))?
                            .into_owned();
                        let contenttype = get_attribute(&e, b"contenttype")
                            .ok_or(Lib3mfError::Validation(
                                "texture2d missing required 'contenttype' attribute".to_string(),
                            ))?
                            .into_owned();

                        // Validate content type - must be a valid image MIME type
                        if contenttype.is_empty()
                            || (!contenttype.starts_with("image/png")
                                && !contenttype.starts_with("image/jpeg")
                                && !contenttype.starts_with("image/jpg"))
                        {
                            return Err(Lib3mfError::Validation(format!(
                                "Invalid contenttype '{}'. Must be 'image/png' or 'image/jpeg'",
                                contenttype
                            )));
                        }

                        let texture = crate::model::Texture2D {
                            id,
                            path,
                            contenttype,
                        };
                        model.resources.add_texture_2d(texture)?;
                    }
                    b"texture2dgroup" => {
                        let id = crate::model::ResourceId(get_attribute_u32(&e, b"id")?);
                        let texid = crate::model::ResourceId(get_attribute_u32(&e, b"texid")?);
                        let group = parse_texture_2d_group(parser, id, texid)?;
                        model.resources.add_texture_2d_group(group)?;
                    }
                    b"compositematerials" => {
                        let id = crate::model::ResourceId(get_attribute_u32(&e, b"id")?);
                        let matid = crate::model::ResourceId(get_attribute_u32(&e, b"matid")?);
                        let matindices_str = get_attribute(&e, b"matindices").ok_or_else(|| {
                            Lib3mfError::Validation(
                                "compositematerials missing matindices".to_string(),
                            )
                        })?;
                        let indices = matindices_str
                            .split_whitespace()
                            .map(|s| {
                                s.parse::<u32>().map_err(|_| {
                                    Lib3mfError::Validation("Invalid matindices value".to_string())
                                })
                            })
                            .collect::<Result<Vec<u32>>>()?;
                        let group = parse_composite_materials(parser, id, matid, indices)?;
                        model.resources.add_composite_materials(group)?;
                    }
                    b"multiproperties" => {
                        let id = crate::model::ResourceId(get_attribute_u32(&e, b"id")?);
                        let pids_str = get_attribute(&e, b"pids").ok_or_else(|| {
                            Lib3mfError::Validation("multiproperties missing pids".to_string())
                        })?;
                        let pids = pids_str
                            .split_whitespace()
                            .map(|s| {
                                s.parse::<u32>()
                                    .map_err(|_| {
                                        Lib3mfError::Validation("Invalid pid value".to_string())
                                    })
                                    .map(crate::model::ResourceId)
                            })
                            .collect::<Result<Vec<crate::model::ResourceId>>>()?;

                        let blend_methods =
                            if let Some(blendmethods_str) = get_attribute(&e, b"blendmethods") {
                                blendmethods_str
                                    .split_whitespace()
                                    .map(|s| match s {
                                        "mix" => Ok(crate::model::BlendMethod::Mix),
                                        "multiply" => Ok(crate::model::BlendMethod::Multiply),
                                        _ => Err(Lib3mfError::Validation(format!(
                                            "Invalid blend method: {}",
                                            s
                                        ))),
                                    })
                                    .collect::<Result<Vec<crate::model::BlendMethod>>>()?
                            } else {
                                // Default to Multiply for all pids when blendmethods not specified
                                vec![crate::model::BlendMethod::Multiply; pids.len()]
                            };

                        let group = parse_multi_properties(parser, id, pids, blend_methods)?;
                        model.resources.add_multi_properties(group)?;
                    }
                    b"slicestack" => {
                        let id = crate::model::ResourceId(get_attribute_u32(&e, b"id")?);
                        let z_bottom = get_attribute_f32(&e, b"zbottom").unwrap_or(0.0);
                        let stack = parse_slice_stack_content(parser, id, z_bottom)?;
                        model.resources.add_slice_stack(stack)?;
                    }
                    b"volumetricstack" => {
                        let id = crate::model::ResourceId(get_attribute_u32(&e, b"id")?);
                        let stack = parse_volumetric_stack_content(parser, id, 0.0)?;
                        model.resources.add_volumetric_stack(stack)?;
                    }
                    b"booleanshape" => {
                        let id = crate::model::ResourceId(get_attribute_u32(&e, b"id")?);
                        let base_object_id =
                            crate::model::ResourceId(get_attribute_u32(&e, b"objectid")?);
                        let base_transform = if let Some(s) = get_attribute(&e, b"transform") {
                            crate::parser::component_parser::parse_transform(&s)?
                        } else {
                            glam::Mat4::IDENTITY
                        };
                        let base_path = get_attribute(&e, b"path")
                            .or_else(|| get_attribute(&e, b"p:path"))
                            .map(|s| s.into_owned());

                        let bool_shape =
                            parse_boolean_shape(parser, base_object_id, base_transform, base_path)?;

                        // Per spec, booleanshape is a model-type object
                        let object = Object {
                            id,
                            object_type: crate::model::ObjectType::Model,
                            name: None,
                            part_number: None,
                            uuid: None,
                            pid: None,
                            pindex: None,
                            thumbnail: None,
                            geometry: Geometry::BooleanShape(bool_shape),
                        };
                        model.resources.add_object(object)?;
                    }
                    b"displacement2d" => {
                        let id = crate::model::ResourceId(get_attribute_u32(&e, b"id")?);
                        let path = get_attribute(&e, b"path")
                            .ok_or_else(|| {
                                Lib3mfError::Validation(
                                    "displacement2d missing path attribute".to_string(),
                                )
                            })?
                            .into_owned();

                        let channel = if let Some(ch_str) = get_attribute(&e, b"channel") {
                            match ch_str.as_ref() {
                                "R" => crate::model::Channel::R,
                                "G" => crate::model::Channel::G,
                                "B" => crate::model::Channel::B,
                                "A" => crate::model::Channel::A,
                                _ => crate::model::Channel::G,
                            }
                        } else {
                            crate::model::Channel::G
                        };

                        let tile_style = if let Some(ts_str) = get_attribute(&e, b"tilestyle") {
                            match ts_str.to_lowercase().as_str() {
                                "wrap" => crate::model::TileStyle::Wrap,
                                "mirror" => crate::model::TileStyle::Mirror,
                                "clamp" => crate::model::TileStyle::Clamp,
                                "none" => crate::model::TileStyle::None,
                                _ => crate::model::TileStyle::Wrap,
                            }
                        } else {
                            crate::model::TileStyle::Wrap
                        };

                        let filter = if let Some(f_str) = get_attribute(&e, b"filter") {
                            match f_str.to_lowercase().as_str() {
                                "linear" => crate::model::FilterMode::Linear,
                                "nearest" => crate::model::FilterMode::Nearest,
                                _ => crate::model::FilterMode::Linear,
                            }
                        } else {
                            crate::model::FilterMode::Linear
                        };

                        let height = get_attribute_f32(&e, b"height")?;
                        let offset = get_attribute_f32(&e, b"offset").unwrap_or(0.0);

                        let displacement = parse_displacement_2d(
                            parser, id, path, channel, tile_style, filter, height, offset,
                        )?;
                        model.resources.add_displacement_2d(displacement)?;
                    }
                    _ => {}
                }
            }
            Event::Empty(e) => {
                // Handle self-closing elements like <colorgroup id="5"/>
                let local_name = e.local_name();
                match local_name.as_ref() {
                    b"colorgroup" => {
                        let id = crate::model::ResourceId(get_attribute_u32(&e, b"id")?);
                        let group = ColorGroup {
                            id,
                            colors: Vec::new(),
                        };
                        model.resources.add_color_group(group)?;
                    }
                    b"texture2dgroup" => {
                        let id = crate::model::ResourceId(get_attribute_u32(&e, b"id")?);
                        let texture_id = crate::model::ResourceId(get_attribute_u32(&e, b"texid")?);
                        let group = Texture2DGroup {
                            id,
                            texture_id,
                            coords: Vec::new(),
                        };
                        model.resources.add_texture_2d_group(group)?;
                    }
                    b"basematerials" => {
                        let id = crate::model::ResourceId(get_attribute_u32(&e, b"id")?);
                        let group = BaseMaterialsGroup {
                            id,
                            materials: Vec::new(),
                        };
                        model.resources.add_base_materials(group)?;
                    }
                    b"compositematerials" => {
                        let id = crate::model::ResourceId(get_attribute_u32(&e, b"id")?);
                        let base_material_id =
                            crate::model::ResourceId(get_attribute_u32(&e, b"matid")?);
                        let matindices_str = get_attribute(&e, b"matindices").ok_or_else(|| {
                            Lib3mfError::Validation(
                                "compositematerials missing matindices".to_string(),
                            )
                        })?;
                        let indices = matindices_str
                            .split_whitespace()
                            .map(|s| {
                                s.parse::<u32>().map_err(|_| {
                                    Lib3mfError::Validation("Invalid matindices value".to_string())
                                })
                            })
                            .collect::<Result<Vec<u32>>>()?;
                        let group = CompositeMaterials {
                            id,
                            base_material_id,
                            indices,
                            composites: Vec::new(),
                        };
                        model.resources.add_composite_materials(group)?;
                    }
                    b"multiproperties" => {
                        let id = crate::model::ResourceId(get_attribute_u32(&e, b"id")?);
                        let pids_str = get_attribute(&e, b"pids").ok_or_else(|| {
                            Lib3mfError::Validation("multiproperties missing pids".to_string())
                        })?;
                        let pids = pids_str
                            .split_whitespace()
                            .map(|s| {
                                s.parse::<u32>()
                                    .map_err(|_| {
                                        Lib3mfError::Validation("Invalid pid value".to_string())
                                    })
                                    .map(crate::model::ResourceId)
                            })
                            .collect::<Result<Vec<crate::model::ResourceId>>>()?;

                        let blend_methods =
                            if let Some(blendmethods_str) = get_attribute(&e, b"blendmethods") {
                                blendmethods_str
                                    .split_whitespace()
                                    .map(|s| match s {
                                        "mix" => Ok(crate::model::BlendMethod::Mix),
                                        "multiply" => Ok(crate::model::BlendMethod::Multiply),
                                        _ => Err(Lib3mfError::Validation(format!(
                                            "Invalid blend method: {}",
                                            s
                                        ))),
                                    })
                                    .collect::<Result<Vec<crate::model::BlendMethod>>>()?
                            } else {
                                // Default to Multiply for all pids when blendmethods not specified
                                vec![crate::model::BlendMethod::Multiply; pids.len()]
                            };

                        let group = MultiProperties {
                            id,
                            pids,
                            blend_methods,
                            multis: Vec::new(),
                        };
                        model.resources.add_multi_properties(group)?;
                    }
                    _ => {}
                }
            }
            Event::End(e) if e.name().as_ref() == b"resources" => break,
            Event::Eof => {
                return Err(Lib3mfError::Validation(
                    "Unexpected EOF in resources".to_string(),
                ));
            }
            _ => {}
        }
    }
    Ok(())
}

fn parse_object_geometry<R: BufRead>(parser: &mut XmlParser<R>) -> Result<Geometry> {
    // We are inside <object> tag. We expect either <mesh> or <components> next.
    // NOTE: object is open. We read until </object>.

    // Actually, parse_object_geometry needs to look for mesh/components.
    // If <object> was Empty, we wouldn't be here (logic above needs check).
    // The previous match Event::Start(object) means it has content.

    let mut geometry = Geometry::Mesh(crate::model::Mesh::default()); // Default fallback? Or Option/Result?

    loop {
        match parser.read_next_event()? {
            Event::Start(e) => {
                let local_name = e.local_name();
                match local_name.as_ref() {
                    b"mesh" => {
                        geometry = Geometry::Mesh(parse_mesh(parser)?);
                    }
                    b"components" => {
                        geometry = Geometry::Components(parse_components(parser)?);
                    }
                    b"displacementmesh" => {
                        geometry = Geometry::DisplacementMesh(parse_displacement_mesh(parser)?);
                    }
                    _ => {}
                }
            }
            Event::End(e) if e.name().as_ref() == b"object" => break,
            Event::Eof => {
                return Err(Lib3mfError::Validation(
                    "Unexpected EOF in object".to_string(),
                ));
            }
            _ => {}
        }
    }
    Ok(geometry)
}