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
//! # Fornjot Exporter
//!
//! This library is part of the [Fornjot] ecosystem. Fornjot is an open-source,
//! code-first CAD application; and collection of libraries that make up the CAD
//! application, but can be used independently.
//!
//! This library is an internal component of Fornjot. It is not relevant to end
//! users that just want to create CAD models.
//!
//! The purpose of this library is to export Fornjot models to external file
//! formats.
//!
//! [Fornjot]: https://www.fornjot.app/

#![warn(missing_docs)]

use std::{fs::File, io::Write, path::Path};

use thiserror::Error;

use fj_interop::mesh::Mesh;
use fj_math::{Point, Triangle};

/// Export the provided mesh to the file at the given path.
///
/// This function will create a file if it does not exist, and will truncate it if it does.
///
/// Currently 3MF & STL file types are supported. The case insensitive file extension of
/// the provided path is used to switch between supported types.
pub fn export(mesh: &Mesh<Point<3>>, path: &Path) -> Result<(), Error> {
    match path.extension() {
        Some(extension) if extension.to_ascii_uppercase() == "3MF" => {
            export_3mf(mesh, path)
        }
        Some(extension) if extension.to_ascii_uppercase() == "STL" => {
            export_stl(mesh, path)
        }
        Some(extension) if extension.to_ascii_uppercase() == "OBJ" => {
            export_obj(mesh, path)
        }
        Some(extension) => Err(Error::InvalidExtension(
            extension.to_string_lossy().into_owned(),
        )),
        None => Err(Error::NoExtension),
    }
}

fn export_3mf(mesh: &Mesh<Point<3>>, path: &Path) -> Result<(), Error> {
    let vertices = mesh
        .vertices()
        .map(|point| threemf::model::Vertex {
            x: point.x.into_f64(),
            y: point.y.into_f64(),
            z: point.z.into_f64(),
        })
        .collect();

    let indices: Vec<_> = mesh.indices().collect();
    let triangles = indices
        .chunks(3)
        .map(|triangle| threemf::model::Triangle {
            v1: triangle[0] as usize,
            v2: triangle[1] as usize,
            v3: triangle[2] as usize,
        })
        .collect();

    let mesh = threemf::Mesh {
        vertices: threemf::model::Vertices { vertex: vertices },
        triangles: threemf::model::Triangles {
            triangle: triangles,
        },
    };

    threemf::write(path, mesh)?;

    Ok(())
}

fn export_stl(mesh: &Mesh<Point<3>>, path: &Path) -> Result<(), Error> {
    let points = mesh
        .triangles()
        .map(|triangle| triangle.inner.points())
        .collect::<Vec<_>>();

    let vertices = points.iter().map(|points| {
        points.map(|point| point.coords.components.map(|s| s.into_f32()))
    });

    let normals = points
        .iter()
        .map(|&points| points.into())
        .map(|triangle: Triangle<3>| triangle.normal())
        .map(|vector| vector.components.map(|s| s.into_f32()));

    let triangles = vertices
        .zip(normals)
        .map(|([v1, v2, v3], normal)| stl::Triangle {
            normal,
            v1,
            v2,
            v3,
            attr_byte_count: 0,
        })
        .collect::<Vec<_>>();

    let mut file = File::create(path)?;

    let binary_stl_file = stl::BinaryStlFile {
        header: stl::BinaryStlHeader {
            header: [0u8; 80],
            num_triangles: triangles
                .len()
                .try_into()
                .map_err(|_| Error::InvalidTriangleCount)?,
        },
        triangles,
    };

    stl::write_stl(&mut file, &binary_stl_file)?;

    Ok(())
}

fn export_obj(mesh: &Mesh<Point<3>>, path: &Path) -> Result<(), Error> {
    let mut f = File::create(path)?;

    for (cnt, t) in mesh.triangles().enumerate() {
        // write each point of the triangle
        for v in t.inner.points() {
            wavefront_rs::obj::writer::Writer::write(
                &mut f,
                &wavefront_rs::obj::entity::Entity::Vertex {
                    x: v.x.into_f64(),
                    y: v.y.into_f64(),
                    z: v.z.into_f64(),
                    w: None,
                },
            )
            .or(Err(Error::OBJ))?;
            f.write_all(b"\n")?;
        }

        // write the triangle
        wavefront_rs::obj::writer::Writer::write(
            &mut f,
            &wavefront_rs::obj::entity::Entity::Face {
                vertices: vec![
                    wavefront_rs::obj::entity::FaceVertex {
                        vertex: (cnt * 3 + 1) as i64,
                        texture: None,
                        normal: None,
                    },
                    wavefront_rs::obj::entity::FaceVertex {
                        vertex: (cnt * 3 + 2) as i64,
                        texture: None,
                        normal: None,
                    },
                    wavefront_rs::obj::entity::FaceVertex {
                        vertex: (cnt * 3 + 3) as i64,
                        texture: None,
                        normal: None,
                    },
                ],
            },
        )
        .or(Err(Error::OBJ))?;
        f.write_all(b"\n")?;
    }

    Ok(())
}

/// An error that can occur while exporting
#[derive(Debug, Error)]
pub enum Error {
    /// No extension specified
    #[error("no extension specified")]
    NoExtension,

    /// Unrecognized extension found
    #[error("unrecognized extension found `{0:?}`")]
    InvalidExtension(String),

    /// I/O error whilst exporting to file
    #[error("I/O error whilst exporting to file")]
    Io(#[from] std::io::Error),

    /// Maximum triangle count exceeded
    #[error("maximum triangle count exceeded")]
    InvalidTriangleCount,

    /// Threemf error whilst exporting to 3MF file
    #[error("threemf error whilst exporting to 3MF file")]
    ThreeMF(#[from] threemf::Error),

    /// OBJ exporter error whilst exporting to OBJ file
    #[error("obj error whilst exporting to OBJ file")]
    OBJ,
}