1mod 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
99pub 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";
103const RELATIONSHIP_NAMESPACE: &str = "http://schemas.openxmlformats.org/package/2006/relationships";
105const MODEL_RELATIONSHIP: &str = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel";
107const RELATIONSHIP_PART: &str = "_rels/.rels";
109
110pub const MAX_PART_BYTES: usize = 256 * 1024 * 1024;
113pub const MAX_MESH_VERTICES: usize = 8_000_000;
115pub const MAX_MESH_TRIANGLES: usize = 16_000_000;
116pub const MAX_INSTANCES: usize = 65_536;
118pub const MAX_TOTAL_TRIANGLES: usize = 32_000_000;
120pub const MAX_COMPONENT_DEPTH: usize = 32;
124
125#[derive(Clone, Debug, PartialEq, Eq)]
128pub enum ThreeMfError {
129 Container(String),
131 Damaged { part: String, detail: String },
134 MissingPart { part: String, detail: String },
136 Unsupported { part: String, detail: String },
138 Bounds { part: String, detail: String },
140 Xml { part: String, detail: String },
142 Model { part: String, detail: String },
144}
145
146impl ThreeMfError {
147 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#[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 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#[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 pub fn preview_rgb(&self) -> Option<[u8; 3]> {
236 let mut rgb = [0; 3];
237 match self {
238 Self::Colors(colors) => {
239 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#[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#[derive(Clone, Debug, PartialEq, Serialize)]
279pub struct ThreeMfBeamLattice {
280 pub min_length: f64,
281 pub beams: Vec<ThreeMfBeam>,
282}
283
284#[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#[derive(Clone, Debug, Default, PartialEq, Serialize)]
299pub struct ThreeMfMesh {
300 pub object_id: u32,
302 pub beam_lattice: Option<ThreeMfBeamLattice>,
304 pub positions: Vec<f64>,
306 pub indices: Vec<u32>,
308 pub triangle_colors: Vec<Option<[u8; 3]>>,
312 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#[derive(Clone, Debug, PartialEq, Serialize)]
328pub struct ThreeMfInstance {
329 pub object_id: u32,
332 pub mesh: usize,
334 pub transform: [f64; 12],
337 pub first_vertex: usize,
343 pub vertex_count: usize,
344 pub first_triangle: usize,
345 pub triangle_count: usize,
346 pub name: Option<String>,
350}
351
352impl ThreeMfInstance {
353 pub fn transform_point(&self, point: [f64; 3]) -> [f64; 3] {
355 transform_point(&self.transform, point)
356 }
357}
358
359#[derive(Clone, Debug, Serialize)]
361pub struct ThreeMfReadResult {
362 pub model_part: String,
364 pub unit: ThreeMfUnit,
366 pub textures: Vec<ThreeMfTexture>,
368 pub meshes: Vec<ThreeMfMesh>,
371 pub instances: Vec<ThreeMfInstance>,
374 pub positions: Vec<f64>,
377 pub indices: Vec<u32>,
380 pub triangle_colors: Vec<Option<[u8; 3]>>,
385 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 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
425pub 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
428pub 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
438pub 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
454fn 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
462pub 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
497fn 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
523fn 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
569fn 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 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 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
677fn 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 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 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 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}