Skip to main content

bread_format/
stl.rs

1/*
2 * SPDX-FileCopyrightText: 2026 SynrgStudio
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6//! STL in: binary and ASCII STL files read into a [`Mesh`], to be written as
7//! `.bread`.
8//!
9//! An STL is a list of triangles, each with its three corners written out in
10//! full. [`read_stl`] welds them into vertices: two corners are one vertex when
11//! their coordinates are equal bit for bit, and vertices are numbered by first
12//! use. Nothing is rounded or merged beyond that, so every corner of every
13//! triangle comes back from the mesh exactly, in the STL's order. Facet normals
14//! and attribute bytes are not kept: they are file data, not geometry.
15//!
16//! The text that comes with the triangles is kept as the mesh's metadata: an
17//! ASCII STL's solid name as its name, and a binary STL's 80-byte header as
18//! its comment, when they hold text.
19
20use std::collections::HashMap;
21use std::fmt;
22
23use crate::mesh::Mesh;
24use crate::meta::Meta;
25
26/// Bytes before a binary STL's triangles: an 80-byte header and a `u32`
27/// triangle count.
28const BINARY_HEADER: usize = 84;
29/// Bytes per triangle of a binary STL: normal, three corners, attribute.
30const BINARY_TRIANGLE: usize = 50;
31
32/// Why an STL could not be read.
33#[derive(Clone, Debug, PartialEq, Eq)]
34pub enum ReadStlError {
35    /// Neither a binary STL of the length its triangle count says, nor text
36    /// that starts with `solid`.
37    NotStl,
38    /// An ASCII STL that breaks its grammar on this line, counted from 1.
39    Ascii { line: usize },
40    /// More vertices than a mesh can number with a `u32`.
41    TooLarge,
42}
43
44impl fmt::Display for ReadStlError {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        match self {
47            Self::NotStl => f.write_str("not an STL file"),
48            Self::Ascii { line } => write!(f, "the ASCII STL is malformed on line {line}"),
49            Self::TooLarge => f.write_str("the STL has too many vertices"),
50        }
51    }
52}
53
54impl std::error::Error for ReadStlError {}
55
56/// Reads a binary or an ASCII STL, and welds its corners into a mesh.
57///
58/// A file is binary when its length is exactly what its triangle count says,
59/// even if its header starts with `solid`, as many binary headers do; else it
60/// is read as ASCII.
61pub fn read_stl(bytes: &[u8]) -> Result<Mesh, ReadStlError> {
62    let (corners, meta) = match binary_triangle_count(bytes) {
63        Some(count) => (binary_corners(bytes, count), binary_meta(bytes)),
64        None => ascii(bytes)?,
65    };
66    let mut mesh = weld(&corners)?;
67    mesh.meta = meta;
68    Ok(mesh)
69}
70
71/// The triangle count of a binary STL, when `bytes` has exactly the length it
72/// says.
73fn binary_triangle_count(bytes: &[u8]) -> Option<usize> {
74    let count = u32::from_le_bytes(bytes.get(80..BINARY_HEADER)?.try_into().ok()?);
75    let count = usize::try_from(count).ok()?;
76    let length = count
77        .checked_mul(BINARY_TRIANGLE)?
78        .checked_add(BINARY_HEADER)?;
79    (bytes.len() == length).then_some(count)
80}
81
82/// The corners of a binary STL of `count` triangles, as the bits of their
83/// coordinates: three per triangle, in order.
84fn binary_corners(bytes: &[u8], count: usize) -> Vec<[u32; 3]> {
85    let mut corners = Vec::with_capacity(3 * count);
86    for facet in bytes[BINARY_HEADER..].as_chunks::<BINARY_TRIANGLE>().0 {
87        for corner in 0..3 {
88            let at = 12 + 12 * corner;
89            corners.push(std::array::from_fn(|i| {
90                let b = &facet[at + 4 * i..at + 4 * i + 4];
91                u32::from_le_bytes([b[0], b[1], b[2], b[3]])
92            }));
93        }
94    }
95    corners
96}
97
98/// A binary STL's header as the mesh's comment, when it holds text: UTF-8,
99/// without control characters, once the NUL and space padding at its end is
100/// cut off.
101fn binary_meta(bytes: &[u8]) -> Option<Meta> {
102    let header = &bytes[..80];
103    let end = header
104        .iter()
105        .rposition(|&b| b != 0 && b != b' ')
106        .map_or(0, |i| i + 1);
107    let text = std::str::from_utf8(&header[..end]).ok()?;
108    if text.is_empty() || text.chars().any(char::is_control) {
109        return None;
110    }
111    Some(Meta {
112        name: None,
113        comment: Some(text.to_owned()),
114    })
115}
116
117/// The corners and solid name of an ASCII STL:
118///
119/// ```text
120/// solid [name]
121///   facet normal nx ny nz
122///     outer loop
123///       vertex x y z     (three times)
124///     endloop
125///   endfacet             (any number of facets)
126/// endsolid [name]
127/// ```
128///
129/// Keywords, in any case, and numbers are separated by any whitespace. Coordinates are read
130/// as the nearest `f32`. Anything after `endsolid` is ignored.
131fn ascii(bytes: &[u8]) -> Result<(Vec<[u32; 3]>, Option<Meta>), ReadStlError> {
132    let text = std::str::from_utf8(bytes).map_err(|_| ReadStlError::NotStl)?;
133    let mut lines = text.lines().enumerate().map(|(i, line)| (i + 1, line));
134    let name = loop {
135        let Some((_, line)) = lines.next() else {
136            return Err(ReadStlError::NotStl);
137        };
138        let line = line.trim();
139        if line.is_empty() {
140            continue;
141        }
142        let rest = strip_keyword(line, "solid").ok_or(ReadStlError::NotStl)?;
143        if !rest.is_empty() && !rest.starts_with(char::is_whitespace) {
144            return Err(ReadStlError::NotStl);
145        }
146        break rest.trim();
147    };
148
149    let mut corners = Vec::new();
150    // Where the parser is: 0 between facets, then after `facet`, `outer
151    // loop`, each `vertex`, and `endloop`.
152    let mut step = 0;
153    let mut ended = false;
154    for (number, line) in lines {
155        let bad = ReadStlError::Ascii { line: number };
156        let mut words = line.split_whitespace();
157        let Some(word) = words.next() else {
158            continue;
159        };
160        let word = word.to_ascii_lowercase();
161        step = match (step, word.as_str()) {
162            (0, "facet") => {
163                if !is(words.next(), "normal") {
164                    return Err(bad);
165                }
166                for _ in 0..3 {
167                    // Read so a damaged normal is caught, but not kept.
168                    words.next().and_then(coordinate).ok_or(bad.clone())?;
169                }
170                1
171            }
172            (0, "endsolid") => {
173                ended = true;
174                break;
175            }
176            (1, "outer") if is(words.next(), "loop") => 2,
177            (2..=4, "vertex") => {
178                let mut corner = [0; 3];
179                for value in &mut corner {
180                    *value = words.next().and_then(coordinate).ok_or(bad.clone())?;
181                }
182                corners.push(corner);
183                step + 1
184            }
185            (5, "endloop") => 6,
186            (6, "endfacet") => 0,
187            _ => return Err(bad),
188        };
189        if words.next().is_some() {
190            return Err(bad);
191        }
192    }
193    if !ended {
194        let last = text.lines().count().max(1);
195        return Err(ReadStlError::Ascii { line: last });
196    }
197    let meta = (!name.is_empty()).then(|| Meta {
198        name: Some(name.to_owned()),
199        comment: None,
200    });
201    Ok((corners, meta))
202}
203
204/// Whether `word` is `keyword`, in any case.
205fn is(word: Option<&str>, keyword: &str) -> bool {
206    word.is_some_and(|word| word.eq_ignore_ascii_case(keyword))
207}
208
209/// `line` past `keyword` at its start, in any case.
210fn strip_keyword<'a>(line: &'a str, keyword: &str) -> Option<&'a str> {
211    let head = line.get(..keyword.len())?;
212    head.eq_ignore_ascii_case(keyword)
213        .then(|| &line[keyword.len()..])
214}
215
216/// A coordinate of an ASCII STL, as the bits of the nearest `f32`.
217fn coordinate(word: &str) -> Option<u32> {
218    word.parse::<f32>().ok().map(f32::to_bits)
219}
220
221/// The corners welded into a mesh: equal bits, one vertex, numbered by first
222/// use. `corners` holds three per triangle.
223fn weld(corners: &[[u32; 3]]) -> Result<Mesh, ReadStlError> {
224    let mut index: HashMap<[u32; 3], u32> = HashMap::with_capacity(corners.len() / 2);
225    let mut vertices = Vec::new();
226    let mut ids = Vec::with_capacity(corners.len());
227    for corner in corners {
228        let id = match index.get(corner) {
229            Some(&id) => id,
230            None => {
231                let id = u32::try_from(vertices.len()).map_err(|_| ReadStlError::TooLarge)?;
232                vertices.push(corner.map(f32::from_bits));
233                index.insert(*corner, id);
234                id
235            }
236        };
237        ids.push(id);
238    }
239    let triangles = ids.as_chunks::<3>().0.to_vec();
240    Ok(Mesh {
241        meta: None,
242        vertices,
243        triangles,
244    })
245}