From c1152ced5e821ab846a50f2cfa726b6a317db64a Mon Sep 17 00:00:00 2001 From: Taiki Endo Date: Thu, 10 Mar 2022 17:25:06 +0900 Subject: [PATCH] Implement STL parser --- .gitattributes | 1 + .github/dependabot.yml | 9 + .github/workflows/ci.yml | 35 +++ .github/workflows/release.yml | 35 +++ .gitignore | 2 + Cargo.toml | 41 +++ LICENSE | 201 +++++++++++++ example/Cargo.toml | 14 + example/examples/kiss3d.rs | 99 +++++++ src/common.rs | 11 + src/lib.rs | 17 ++ src/stl/mod.rs | 527 ++++++++++++++++++++++++++++++++++ 12 files changed, 992 insertions(+) create mode 100644 .gitattributes create mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/release.yml create mode 100644 .gitignore create mode 100644 Cargo.toml create mode 100644 LICENSE create mode 100644 example/Cargo.toml create mode 100644 example/examples/kiss3d.rs create mode 100644 src/common.rs create mode 100644 src/lib.rs create mode 100644 src/stl/mod.rs diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..6313b56 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text=auto eol=lf diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..8ffad3b --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,9 @@ +version: 2 +updates: + - package-ecosystem: cargo + directory: / + schedule: + interval: daily + commit-message: + prefix: '' + labels: [] diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..a047b8e --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,35 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + branches: [main] + +env: + CARGO_INCREMENTAL: 0 + CARGO_NET_RETRY: 10 + CARGO_TERM_COLOR: always + RUST_BACKTRACE: 1 + RUSTDOCFLAGS: -D warnings + RUSTFLAGS: -D warnings + RUSTUP_MAX_RETRIES: 10 + +defaults: + run: + shell: bash + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Install Rust + run: rustup update stable + - name: Install cargo-hack + uses: taiki-e/install-action@cargo-hack + - run: cargo fmt --all --check + - run: cargo clippy --workspace --all-features --all-targets + - run: cargo hack build --workspace --ignore-private --feature-powerset + - run: cargo test --workspace --all-features + - run: cargo doc --workspace --all-features diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..720a006 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,35 @@ +name: Release + +on: + push: + tags: ['v[0-9]+.*'] + +env: + CARGO_INCREMENTAL: 0 + CARGO_NET_RETRY: 10 + CARGO_TERM_COLOR: always + RUST_BACKTRACE: 1 + RUSTFLAGS: -D warnings + RUSTUP_MAX_RETRIES: 10 + +defaults: + run: + shell: bash + +jobs: + create-release: + if: github.repository_owner == 'openrr' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Install Rust + run: rustup update stable + - run: cargo package + - uses: taiki-e/create-gh-release-action@v1 + with: + branch: main + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - run: cargo publish + env: + CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a9d37c5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +target +Cargo.lock diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..893041c --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,41 @@ +[package] +name = "mesh-loader" +version = "0.1.0" +edition = "2021" +license = "Apache-2.0" +repository = "https://github.com/openrr/mesh-loader" +keywords = ["asset", "mesh", "stl"] # TODO: "collada", "obj" +categories = ["parser-implementations", "graphics"] +exclude = ["/.*", "/assets"] +description = """ +Fast parser for 3D-model-formats. +""" + +[workspace] +resolver = "2" +members = ["example"] + +[features] +default = ["stl"] + +# STL (.stl) +# https://en.wikipedia.org/wiki/STL_(file_format) +stl = ["rustc-hash"] +# TODO +# # COLLADA (.dae) +# # https://en.wikipedia.org/wiki/COLLADA +# collada = [] +# TODO +# # Wavefront OBJ (.obj) +# # https://en.wikipedia.org/wiki/Wavefront_.obj_file +# obj = [] + +[dependencies] +# Used in all formats. +fast-float = "0.2" +memchr = "2.4" + +# Used in STL parsing. +rustc-hash = { version = "1", optional = true } + +[dev-dependencies] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/example/Cargo.toml b/example/Cargo.toml new file mode 100644 index 0000000..d3d3a78 --- /dev/null +++ b/example/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "examples" +version = "0.0.0" +edition = "2021" +publish = false + +[dev-dependencies] +mesh-loader = { path = ".." } + +anyhow = "1" +clap = { version = "3", features = ["derive"] } +kiss3d = "0.33" +tracing = { version = "0.1", default-features = false, features = ["std"] } +tracing-subscriber = { version = "0.3", default-features = false, features = ["ansi", "env-filter"] } diff --git a/example/examples/kiss3d.rs b/example/examples/kiss3d.rs new file mode 100644 index 0000000..6e415fa --- /dev/null +++ b/example/examples/kiss3d.rs @@ -0,0 +1,99 @@ +use std::{ + cell::RefCell, + ffi::OsStr, + fs, io, + path::{Path, PathBuf}, + rc::Rc, + str::FromStr, +}; + +use anyhow::{bail, Result}; +use clap::Parser; +use kiss3d::{light::Light, nalgebra as na, scene::SceneNode, window::Window}; +use na::{Translation3, UnitQuaternion, Vector3}; +use tracing::debug; + +#[derive(Debug, Parser)] +struct Args { + #[clap(parse(from_os_str))] + path: PathBuf, + #[clap(long, value_name = "X,Y,Z", default_value = "0.1,0.1,0.1")] + scale: Scale, +} + +#[derive(Debug)] +struct Scale(f32, f32, f32); + +impl FromStr for Scale { + type Err = anyhow::Error; + + fn from_str(s: &str) -> Result { + let mut iter = s.trim().splitn(3, ','); + Ok(Scale( + iter.next().unwrap().parse()?, + iter.next().unwrap().parse()?, + iter.next().unwrap().parse()?, + )) + } +} + +fn main() -> Result<()> { + tracing_subscriber::fmt::init(); + let args = Args::parse(); + debug!(?args); + let path = &args.path; + let scale = Vector3::new(args.scale.0, args.scale.1, args.scale.2); + + let mut window = Window::new(&format!("{} ー Meshes Example", args.path.display())); + + let mut base = match path.extension().and_then(OsStr::to_str) { + Some("stl" | "STL") => add_stl(&mut window, path, scale)?, + // Some("dae" | "DAE") => add_collada(&mut window, path, scale)?, + // Some("obj" | "OBJ") => add_obj(&mut window, path, scale)?, + _ => bail!("unsupported file type {path:?}"), + }; + base.set_local_scale(args.scale.0, args.scale.1, args.scale.2); + + base.append_translation(&Translation3::new(0.0, -0.05, -0.2)); + + window.set_light(Light::StickToCamera); + + let rot_triangle = UnitQuaternion::from_axis_angle(&Vector3::z_axis(), 0.014); + + let eye = na::Point3::new(3.0f32, 1.0, 1.0); + let at = na::Point3::new(0.0f32, 0.0, 0.0); + let mut camera = kiss3d::camera::ArcBall::new(eye, at); + camera.set_up_axis(na::Vector3::z()); + camera.set_dist_step(0.5); + while window.render_with_camera(&mut camera) { + base.prepend_to_local_rotation(&rot_triangle); + } + + Ok(()) +} + +fn add_stl( + window: &mut Window, + path: impl AsRef, + scale: na::Vector3, +) -> io::Result { + let stl = mesh_loader::stl::from_slice(&fs::read(path)?)?; + let mesh = kiss3d::resource::Mesh::new( + stl.vertices.into_iter().map(Into::into).collect(), + stl.faces + .into_iter() + .map(|f| { + na::Point3::new( + f[0].try_into().unwrap(), + f[1].try_into().unwrap(), + f[2].try_into().unwrap(), + ) + }) + .collect(), + Some(stl.normals.into_iter().map(Into::into).collect()), + None, + false, + ); + let mesh = Rc::new(RefCell::new(mesh)); + Ok(window.add_mesh(mesh, scale)) +} diff --git a/src/common.rs b/src/common.rs new file mode 100644 index 0000000..c345c89 --- /dev/null +++ b/src/common.rs @@ -0,0 +1,11 @@ +pub(crate) type Vec3 = [f32; 3]; +pub(crate) type Face = [u32; 3]; + +/// Triangle mesh +#[derive(Debug, Default)] +#[non_exhaustive] +pub struct Mesh { + pub vertices: Vec, + pub normals: Vec, + pub faces: Vec, +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..411552d --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,17 @@ +#![warn( + missing_debug_implementations, + rust_2018_idioms, + single_use_lifetimes, + unreachable_pub +)] +#![warn(clippy::exhaustive_enums, clippy::exhaustive_structs)] + +mod common; +pub use common::*; + +// #[cfg(feature = "collada")] +// pub mod collada; +// #[cfg(feature = "obj")] +// pub mod obj; +#[cfg(feature = "stl")] +pub mod stl; diff --git a/src/stl/mod.rs b/src/stl/mod.rs new file mode 100644 index 0000000..213dc20 --- /dev/null +++ b/src/stl/mod.rs @@ -0,0 +1,527 @@ +//! [STL] parser. +//! +//! [STL]: https://en.wikipedia.org/wiki/STL_(file_format) + +use std::{fmt, io, mem, str}; + +use rustc_hash::FxHashMap; + +use crate::{Mesh, Vec3}; + +/// Parses a mesh from bytes of binary or ascii STL. +#[inline] +pub fn from_slice(bytes: &[u8]) -> io::Result { + from_slice_internal(bytes) +} + +#[inline] +fn from_slice_internal(bytes: &[u8]) -> io::Result +where + T: FromStl, +{ + match read_binary_header(bytes) { + Ok(header) => { + if !header.maybe_ascii || header.correct_triangle_count { + read_binary_stl(bytes, header) + } else if is_ascii_stl(bytes, Some(&header))? { + AsciiStlParser::new(bytes)?.read_contents() + } else { + read_binary_stl(bytes, header) + } + } + Err(_) => { + if is_ascii_stl(bytes, None)? { + AsciiStlParser::new(bytes)?.read_contents() + } else { + Err(invalid_data( + "failed to determine STL storage representation", + )) + } + } + } +} + +// An ascii STL buffer will begin with "solid NAME", where NAME is optional. +// Note: The "solid NAME" check is necessary, but not sufficient, to determine +// if the buffer is ASCII; a binary header could also begin with "solid NAME". +fn is_ascii_stl(bytes: &[u8], header: Option<&BinaryHeader>) -> io::Result { + let mut is_ascii = if let Some(header) = header { + header.maybe_ascii + } else { + bytes.get(..5).ok_or_else(|| invalid_data("too small"))? == b"solid" + }; + if is_ascii { + // A lot of importers are write solid even if the file is binary. + // So we have to check for ASCII-characters. + if !bytes[5..].iter().all(u8::is_ascii) { + is_ascii = false; + } + } + Ok(is_ascii) +} + +/* +https://en.wikipedia.org/wiki/STL_(file_format)#Binary_STL + +UINT8[80] – Header - 80 bytes +UINT32 – Number of triangles - 4 bytes + +foreach triangle - 50 bytes: + REAL32[3] – Normal vector - 12 bytes + REAL32[3] – Vertex 1 - 12 bytes + REAL32[3] – Vertex 2 - 12 bytes + REAL32[3] – Vertex 3 - 12 bytes + UINT16 – Attribute byte count - 2 bytes +end +*/ +const HEADER_SIZE: usize = 80; +const TRIANGLE_COUNT_SIZE: usize = 4; +const TRIANGLE_SIZE: usize = 50; + +struct BinaryHeader { + num_triangles: u32, + correct_triangle_count: bool, + maybe_ascii: bool, +} + +fn read_binary_header(bytes: &[u8]) -> io::Result { + let header = bytes + .get(..HEADER_SIZE) + .ok_or_else(|| invalid_data("too small"))?; + + let num_triangles = bytes + .get(HEADER_SIZE..HEADER_SIZE + TRIANGLE_COUNT_SIZE) + .ok_or_else(|| invalid_data("too small"))? + .try_into() + .unwrap(); + let mut num_triangles = u32::from_le_bytes(num_triangles); + + // Many STL files contain bogus count. + // So verify num_triangles with the length of the input. + let mut size = bytes.len() as u64; + size -= (HEADER_SIZE + TRIANGLE_COUNT_SIZE) as u64; + size /= TRIANGLE_SIZE as u64; + let size: u32 = size + .try_into() + .map_err(|_| invalid_data("number of triangles is greater than u32::MAX"))?; + + let correct_triangle_count = num_triangles == size; + if !correct_triangle_count { + num_triangles = size; + } + + // An ASCII STL will begin with "solid NAME", where NAME is optional. + // Note: The "solid NAME" check is necessary, but not sufficient, to determine + // if the input is ASCII; a binary header could also begin with "solid NAME". + let maybe_ascii = header.starts_with(b"solid"); + + Ok(BinaryHeader { + num_triangles, + correct_triangle_count, + maybe_ascii, + }) +} + +#[inline] +fn read_binary_stl(mut bytes: &[u8], header: BinaryHeader) -> io::Result +where + T: FromStl, +{ + bytes = &bytes[HEADER_SIZE + TRIANGLE_COUNT_SIZE..]; + + let mut cx = T::start(); + + T::reserve(&mut cx, header.num_triangles); + read_binary_triangles_from_slice::(&mut cx, bytes); + + Ok(T::end(cx)) +} + +#[inline] +fn read_binary_triangles_from_slice(cx: &mut T::Context, bytes: &[u8]) +where + T: FromStl, +{ + for chunk in bytes.chunks_exact(TRIANGLE_SIZE) { + let triangle = read_binary_triangle(chunk); + T::push_triangle(cx, triangle); + } +} + +#[inline] +fn read_binary_triangle(mut buf: &[u8]) -> Triangle { + #[inline] + fn f32le(buf: &mut &[u8]) -> f32 { + let f = f32::from_le_bytes(buf[..4].try_into().unwrap()); + *buf = &buf[4..]; + f + } + + let normal = [f32le(&mut buf), f32le(&mut buf), f32le(&mut buf)]; + let vertex1 = [f32le(&mut buf), f32le(&mut buf), f32le(&mut buf)]; + let vertex2 = [f32le(&mut buf), f32le(&mut buf), f32le(&mut buf)]; + let vertex3 = [f32le(&mut buf), f32le(&mut buf), f32le(&mut buf)]; + Triangle { + normal, + vertices: [vertex1, vertex2, vertex3], + } +} + +/* +https://en.wikipedia.org/wiki/STL_(file_format)#ASCII_STL + +solid name + +facet normal ni nj nk + outer loop + vertex v1x v1y v1z + vertex v2x v2y v2z + vertex v3x v3y v3z + endloop +endfacet + +endsolid name +*/ +struct AsciiStlParser<'a> { + lines: Lines<'a>, + column: usize, +} + +struct Lines<'a> { + bytes: &'a [u8], + iter: memchr::Memchr<'a>, + next_line_start: usize, + line_start: usize, + line_end: usize, +} + +impl<'a> Lines<'a> { + fn new(bytes: &'a [u8]) -> Self { + Self { + bytes, + iter: memchr::memchr_iter(b'\n', bytes), + next_line_start: 0, + line_start: 0, + line_end: 0, + } + } + + fn current_line(&self) -> &[u8] { + self.bytes + .get(self.line_start..self.line_end) + .unwrap_or_default() + } +} + +impl Iterator for Lines<'_> { + type Item = (); + + fn next(&mut self) -> Option { + let line_end = match self.iter.next() { + Some(line_end) => line_end, + None => { + self.bytes.get(self.next_line_start)?; + self.bytes.len() + } + }; + self.line_end = line_end; + self.line_start = mem::replace(&mut self.next_line_start, line_end + 1); + Some(()) + } +} + +impl<'a> AsciiStlParser<'a> { + fn new(bytes: &'a [u8]) -> io::Result { + Ok(Self { + lines: Lines::new(bytes), + column: 0, + }) + } + + fn read_line(&mut self) -> io::Result<()> { + self.column = 0; + while self.lines.next().is_some() { + self.skip_spaces(); + if !self.bytes().is_empty() { + return Ok(()); + } + } + Err(self.error("unexpected eof")) + } + + fn bytes(&mut self) -> &[u8] { + self.lines + .current_line() + .get(self.column..) + .unwrap_or_default() + } + + fn skip_spaces(&mut self) -> bool { + let prev = self.column; + while self.bytes().get(0).map_or(false, u8::is_ascii_whitespace) { + self.column += 1; + } + self.column != prev + } + + fn expected(&mut self, pat: &str) -> io::Result<()> { + if !self.bytes().starts_with(pat.as_bytes()) { + return Err(self.error(format!("expected `{}`", pat))); + } + self.column += pat.len(); + Ok(()) + } + + fn read_contents(mut self) -> io::Result + where + T: FromStl, + { + let mut cx = T::start(); + + // solid [name] + if self.lines.next().is_none() { + return Err(self.error("unexpected eof")); + } + self.expected("solid")?; + let has_space = self.skip_spaces(); + if !self.bytes().is_empty() { + if !has_space { + return Err(self.error("unexpected token after `solid`")); + } + let text = str::from_utf8(self.bytes()).map_err(invalid_data)?; + let mut text = text.splitn(2, |c: char| c.is_ascii_whitespace()); + if let Some(s) = text.next() { + T::set_name(&mut cx, s.trim()); + if let Some(s) = text.next() { + if !s.trim().is_empty() { + return Err(self.error("unexpected token after name")); + } + } + } + } + + loop { + self.read_line()?; + // endsolid [name] + if self.bytes().starts_with(b"endsolid") { + // TODO: check name + break; + } + + let triangle = self.read_triangle()?; + T::push_triangle(&mut cx, triangle); + } + + Ok(T::end(cx)) + } + + fn read_triangle(&mut self) -> io::Result { + // facet normal + self.expected("facet normal ")?; + self.skip_spaces(); + let normal = self.read_vec3d()?; + self.skip_spaces(); + if !self.bytes().is_empty() { + return Err(self.error("unexpected token after normal")); + } + + // outer loop + self.read_line()?; + self.expected("outer loop")?; + self.skip_spaces(); + if !self.bytes().is_empty() { + return Err(self.error("unexpected token after `outer loop`")); + } + + // vertex + self.read_line()?; + self.expected("vertex ")?; + self.skip_spaces(); + let vertex1 = self.read_vec3d()?; + self.skip_spaces(); + if !self.bytes().is_empty() { + return Err(self.error("unexpected token after vertex")); + } + + // vertex + self.read_line()?; + self.expected("vertex ")?; + self.skip_spaces(); + let vertex2 = self.read_vec3d()?; + self.skip_spaces(); + if !self.bytes().is_empty() { + return Err(self.error("unexpected token after vertex")); + } + + // vertex + self.read_line()?; + self.expected("vertex ")?; + self.skip_spaces(); + let vertex3 = self.read_vec3d()?; + self.skip_spaces(); + if !self.bytes().is_empty() { + return Err(self.error("unexpected token after vertex")); + } + + // endloop + self.read_line()?; + self.expected("endloop")?; + self.skip_spaces(); + if !self.bytes().is_empty() { + return Err(self.error("unexpected token after `endloop`")); + } + + // endfacet + self.read_line()?; + self.expected("endfacet")?; + self.skip_spaces(); + if !self.bytes().is_empty() { + return Err(self.error("unexpected token after `endfacet`")); + } + + Ok(Triangle { + normal, + vertices: [vertex1, vertex2, vertex3], + }) + } + + fn read_vec3d(&mut self) -> io::Result { + let x = self.read_float()?; + if !self.bytes().get(0).map_or(false, u8::is_ascii_whitespace) { + return Err(self.error("expected whitespace after float")); + } + self.skip_spaces(); + + let y = self.read_float()?; + if !self.bytes().get(0).map_or(false, u8::is_ascii_whitespace) { + return Err(self.error("expected whitespace after float")); + } + self.skip_spaces(); + + let z = self.read_float()?; + + Ok([x, y, z]) + } + + fn read_float(&mut self) -> io::Result { + let (f, n) = match fast_float::parse_partial::(self.bytes()) { + Ok(n) => n, + Err(e) => return Err(self.error(e)), + }; + self.column += n; + Ok(f) + } + + #[cold] + fn error(&self, e: impl fmt::Display) -> io::Error { + // TODO: get line number based on position + let msg = format!("{} (line: {}, column: {})", e, 0, self.column); + io::Error::new(io::ErrorKind::InvalidData, msg) + } +} + +#[cold] +fn invalid_data(e: impl Into>) -> io::Error { + let e = e.into(); + let kind = e + .downcast_ref::() + .map_or(io::ErrorKind::InvalidData, io::Error::kind); + io::Error::new(kind, e) +} + +trait FromStl: Sized { + type Context; + + fn start() -> Self::Context; + + fn end(cx: Self::Context) -> Self; + + /// Appends a triangle. + fn push_triangle(cx: &mut Self::Context, triangle: Triangle); + + /// Reserves capacity for at least `num_triangles` more triangles to be inserted. + /// + /// - If the format is ASCII STL, `num_triangles` is always 0. + /// - If the format is binary STL and the input is slice, `num_triangles` + /// is the exact number of triangles. + /// - If the format is binary STL and the input is IO stream, + /// `num_triangles` is normally exact, but if the size of the IO stream + /// is very large, this may result in a smaller number being passed to + /// protect against input with an incorrect `Seek` implementation. + fn reserve(cx: &mut Self::Context, num_triangles: u32) { + let _ = (cx, num_triangles); + } + + /// Sets the name. + fn set_name(cx: &mut Self::Context, name: S) + where + S: Into, + { + let _ = (cx, name); + } +} + +#[derive(Debug, Clone, Copy, PartialEq)] +struct Triangle { + normal: Vec3, + vertices: [Vec3; 3], +} + +#[derive(Default)] +struct MeshReadContext { + mesh: Mesh, + vertices_to_indices: FxHashMap<[u32; 3], usize>, + vertices_indices: [usize; 3], +} + +impl FromStl for Mesh { + type Context = MeshReadContext; + + fn start() -> Self::Context { + MeshReadContext::default() + } + + fn end(mut cx: Self::Context) -> Self { + cx.mesh.vertices.shrink_to_fit(); + cx.mesh.faces.shrink_to_fit(); + cx.mesh.normals.shrink_to_fit(); + cx.mesh + } + + fn push_triangle(cx: &mut Self::Context, triangle: Triangle) { + for (i, vertex) in triangle.vertices.iter().enumerate() { + let bits = [ + vertex[0].to_bits(), + vertex[1].to_bits(), + vertex[2].to_bits(), + ]; + + if let Some(&index) = cx.vertices_to_indices.get(&bits) { + cx.vertices_indices[i] = index; + } else { + let index = cx.mesh.vertices.len(); + cx.vertices_to_indices.insert(bits, index); + cx.vertices_indices[i] = index; + cx.mesh.vertices.push(*vertex); + } + } + + cx.mesh.normals.push(triangle.normal); + cx.mesh.faces.push([ + cx.vertices_indices[0].try_into().unwrap(), + cx.vertices_indices[1].try_into().unwrap(), + cx.vertices_indices[2].try_into().unwrap(), + ]); + } + + fn reserve(cx: &mut Self::Context, num_triangles: u32) { + // Use reserve_exact because binary stl has information on the exact number of triangles. + cx.mesh.faces.reserve_exact(num_triangles as _); + cx.mesh.normals.reserve_exact(num_triangles as _); + // The number of vertices can be up to three times the number of triangles, + // but is usually less than the number of triangles because of deduplication. + let cap = (num_triangles as f64 / 1.6) as usize; + cx.mesh.vertices.reserve(cap); + cx.vertices_to_indices.reserve(cap); + } +}