Add design persistence, world rendering, metrics overlay and logs
Some checks failed
ci / check (macos-latest) (push) Has been cancelled
ci / check (ubuntu-latest) (push) Has been cancelled
ci / check (windows-latest) (push) Has been cancelled

M3: STL/OBJ import with mesh validation, mass/COM/inertia, material database, RON scene with content-addressed blobs and v0->v1 migration. M4: deterministic heightmap terrain, trimesh colliders, wgpu renderer with instancing and depth, winit app with 1 kHz physics, fly camera, on-screen metrics overlay and per-frame CSV/dev logs. Docs: UI, logging, network and headless CLI plans.
This commit is contained in:
Loki 2026-11-16 23:34:05 +01:00
parent 79928b645b
commit 93075ab1fd
Signed by: boba
GPG key ID: 6CDE87BC9A778D97
107 changed files with 14785 additions and 46 deletions

View file

@ -13,6 +13,8 @@ workspace = true
fabrilis-core = { path = "../core" }
fabrilis-materials = { path = "../materials" }
fabrilis-storage = { path = "../storage" }
serde = { version = "1", features = ["derive"] }
ron = "0.12"
[build-dependencies]
fabrilis-limits = { path = "../../tools/limits" }

View file

@ -0,0 +1,275 @@
//! Indexed triangle mesh and its validation rules.
//!
//! The mesh is the common result of the STL and OBJ importers. Neither format
//! stores units, so positions are in metres only after the caller applies
//! [`Mesh::scaled`] with the source unit factor (see docs/COORDINATES.md).
use core::fmt;
use fabrilis_core::units::CubicMeters;
use fabrilis_core::vec::Vec3;
use std::collections::BTreeMap;
/// A closed, indexed triangle mesh in metres.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Mesh {
/// Vertex positions, metres.
pub positions: Vec<Vec3>,
/// Triangles as three indices into [`Self::positions`].
pub indices: Vec<[u32; 3]>,
}
impl Mesh {
/// Builds a mesh, rejecting triangles that reference a missing vertex.
pub fn new(positions: Vec<Vec3>, indices: Vec<[u32; 3]>) -> Result<Self, MeshError> {
let mesh = Self { positions, indices };
mesh.check_indices()?;
Ok(mesh)
}
/// Every triangle as a position triple.
///
/// Triangles whose indices point outside the position list are skipped; a
/// mesh built through [`Self::new`] never has any.
pub fn triangles(&self) -> impl Iterator<Item = [Vec3; 3]> + '_ {
self.indices
.iter()
.filter_map(|triangle| self.triangle(*triangle))
}
/// Scales every position by `factor`.
///
/// Use `0.001` for millimetres, `0.01` for centimetres and `1.0` for metres
/// (see docs/COORDINATES.md).
#[must_use]
pub fn scaled(self, factor: f64) -> Self {
Self {
positions: self
.positions
.into_iter()
.map(|point| point * factor)
.collect(),
indices: self.indices,
}
}
/// Signed volume, m³, from the divergence theorem: `Σ a·(b×c)/6`.
///
/// `None` for an empty mesh, a triangle with a missing vertex or a non-finite
/// sum. A positive value means outward winding; see [`Self::validate`].
#[must_use]
pub fn signed_volume(&self) -> Option<f64> {
if self.indices.is_empty() {
return None;
}
let mut six_volume = 0.0;
for triangle in &self.indices {
let [a, b, c] = self.triangle(*triangle)?;
six_volume += a.dot(b.cross(c));
}
let volume = six_volume / 6.0;
volume.is_finite().then_some(volume)
}
/// Total surface area, m².
#[must_use]
pub fn area(&self) -> f64 {
self.triangles()
.map(|[a, b, c]| (b - a).cross(c - a).length() * 0.5)
.sum()
}
/// Checks that the mesh is a closed surface with outward winding.
///
/// Every coordinate must be finite, every triangle must have area, every
/// undirected edge must be shared by exactly two triangles and traversed in
/// opposite directions, and the signed volume must be positive. This is the
/// check docs/TESTING.md requires before mass and inertia are computed.
pub fn validate(&self) -> Result<MeshReport, MeshError> {
if self.indices.is_empty() {
return Err(MeshError::Empty);
}
self.check_indices()?;
self.check_triangles()?;
self.check_edges()?;
let volume = self
.signed_volume()
.ok_or(MeshError::NonFinite { triangle: 0 })?;
if volume <= 0.0 {
return Err(MeshError::Inverted { volume });
}
Ok(MeshReport {
vertices: self.positions.len(),
triangles: self.indices.len(),
volume: CubicMeters::new(volume),
degenerate: 0,
})
}
/// The three positions of a triangle, or `None` when an index is missing.
fn triangle(&self, [a, b, c]: [u32; 3]) -> Option<[Vec3; 3]> {
let a = *self.positions.get(a as usize)?;
let b = *self.positions.get(b as usize)?;
let c = *self.positions.get(c as usize)?;
Some([a, b, c])
}
fn check_indices(&self) -> Result<(), MeshError> {
for (triangle, corners) in self.indices.iter().enumerate() {
for &corner in corners {
if corner as usize >= self.positions.len() {
return Err(MeshError::BadIndex { triangle });
}
}
}
Ok(())
}
fn check_triangles(&self) -> Result<(), MeshError> {
for (index, triangle) in self.indices.iter().enumerate() {
let [a, b, c] = self
.triangle(*triangle)
.ok_or(MeshError::BadIndex { triangle: index })?;
if [a, b, c].iter().any(|point| !point.is_finite()) {
return Err(MeshError::NonFinite { triangle: index });
}
if (b - a).cross(c - a).length_squared() == 0.0 {
return Err(MeshError::Degenerate { triangle: index });
}
}
Ok(())
}
fn check_edges(&self) -> Result<(), MeshError> {
let mut edges: BTreeMap<(u32, u32), EdgeUse> = BTreeMap::new();
for triangle in &self.indices {
let [a, b, c] = *triangle;
for (start, end) in [(a, b), (b, c), (c, a)] {
let key = if start < end {
(start, end)
} else {
(end, start)
};
let edge = edges.entry(key).or_default();
if start < end {
edge.forward += 1;
} else {
edge.backward += 1;
}
}
}
let broken = edges
.values()
.filter(|edge| edge.forward + edge.backward != 2)
.count();
if broken > 0 {
return Err(MeshError::NotWatertight {
undirected_edges: broken,
});
}
if let Some((edge, _)) = edges.iter().find(|(_, edge)| edge.forward != 1) {
return Err(MeshError::InconsistentWinding { edge: *edge });
}
Ok(())
}
}
/// How many triangles traverse an undirected edge in each direction.
#[derive(Default)]
struct EdgeUse {
/// Triangles going from the smaller index to the larger one.
forward: usize,
/// Triangles going from the larger index to the smaller one.
backward: usize,
}
/// What [`Mesh::validate`] measured on a valid mesh.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MeshReport {
/// Number of vertices, including unused ones.
pub vertices: usize,
/// Number of triangles.
pub triangles: usize,
/// Enclosed volume, m³.
pub volume: CubicMeters,
/// Degenerate triangles found; always zero for a valid mesh.
pub degenerate: usize,
}
/// Why a mesh or an imported file was rejected.
#[derive(Debug, Clone, PartialEq)]
pub enum MeshError {
/// The input has no triangles.
Empty,
/// A triangle references a vertex outside the position list.
BadIndex {
/// Zero-based triangle number.
triangle: usize,
},
/// A triangle has a non-finite coordinate.
NonFinite {
/// Zero-based triangle number.
triangle: usize,
},
/// A triangle has zero area.
Degenerate {
/// Zero-based triangle number.
triangle: usize,
},
/// Edges are not shared by exactly two triangles.
NotWatertight {
/// Number of undirected edges with the wrong number of uses.
undirected_edges: usize,
},
/// An edge is traversed twice in the same direction.
InconsistentWinding {
/// The undirected edge, smaller index first.
edge: (u32, u32),
},
/// The signed volume is not positive, so the winding points inward.
Inverted {
/// The measured signed volume, m³.
volume: f64,
},
/// A line of the source file could not be parsed.
///
/// For binary STL `line` is the one-based triangle number.
Malformed {
/// One-based line number in the text, or triangle number in binary STL.
line: usize,
/// What went wrong.
reason: String,
},
}
impl fmt::Display for MeshError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Empty => write!(formatter, "mesh has no triangles"),
Self::BadIndex { triangle } => {
write!(formatter, "triangle {triangle} references a missing vertex")
}
Self::NonFinite { triangle } => {
write!(formatter, "triangle {triangle} has a non-finite coordinate")
}
Self::Degenerate { triangle } => {
write!(formatter, "triangle {triangle} has zero area")
}
Self::NotWatertight { undirected_edges } => write!(
formatter,
"mesh is not watertight: {undirected_edges} undirected edges are not shared by exactly two triangles"
),
Self::InconsistentWinding { edge } => write!(
formatter,
"edge ({}, {}) is traversed twice in the same direction",
edge.0, edge.1
),
Self::Inverted { volume } => write!(
formatter,
"signed volume {volume} is not positive; the winding points inward"
),
Self::Malformed { line, reason } => write!(formatter, "line {line}: {reason}"),
}
}
}
impl std::error::Error for MeshError {}

View file

@ -1 +1,18 @@
//! fabrilis-scene :: import - stub (see docs/ARCHITECTURE.md)
//! Mesh import and validation: STL (binary and ASCII) and OBJ.
//!
//! Both formats store triangles without units or axes, so the caller records the
//! source units and converts with [`Mesh::scaled`] (docs/COORDINATES.md).
//! Validation is separate from parsing: an importer returns a mesh, and
//! [`Mesh::validate`] proves it is closed, has outward winding and a positive
//! volume before mass and inertia are computed (docs/TESTING.md).
pub mod mesh;
pub mod obj;
pub mod stl;
pub use mesh::{Mesh, MeshError, MeshReport};
pub use obj::from_obj;
pub use stl::from_stl;
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,134 @@
//! OBJ import: the `v` and `f` subset needed for rigid parts.
//!
//! Supported statements:
//!
//! - `v x y z` — vertex position; extra components such as `w` are ignored;
//! - `f ...` — a polygon with three or more corners, fan-triangulated; a corner
//! may be written as `v`, `v/vt`, `v//vn` or `v/vt/vn`, and the vertex index
//! may be positive (one-based) or negative (relative to the vertices seen so
//! far).
//!
//! Comments and the `vt`, `vn`, `o`, `g`, `s`, `usemtl` and `mtllib` statements
//! are ignored. Any other statement is rejected as unsupported: this is a
//! documented subset, not a full OBJ reader. Units and axes are not stored in
//! OBJ; apply [`Mesh::scaled`] with the project factor (docs/COORDINATES.md).
use core::str::SplitWhitespace;
use fabrilis_core::vec::Vec3;
use super::mesh::{Mesh, MeshError};
/// Imports the vertex and face subset of a Wavefront OBJ file.
pub fn from_obj(text: &str) -> Result<Mesh, MeshError> {
let mut positions = Vec::new();
let mut indices = Vec::new();
for (index, line) in text.lines().enumerate() {
parse_line(line, index + 1, &mut positions, &mut indices)?;
}
if indices.is_empty() {
return Err(MeshError::Empty);
}
Mesh::new(positions, indices)
}
fn parse_line(
line: &str,
number: usize,
positions: &mut Vec<Vec3>,
indices: &mut Vec<[u32; 3]>,
) -> Result<(), MeshError> {
let content = line.split('#').next().unwrap_or_default();
let mut words = content.split_whitespace();
let Some(keyword) = words.next() else {
return Ok(());
};
match keyword {
"v" => parse_vertex(words, number, positions),
"f" => parse_face(words, number, positions.len(), indices),
"vt" | "vn" | "o" | "g" | "s" | "usemtl" | "mtllib" => Ok(()),
other => Err(malformed(
number,
format!("unsupported OBJ statement `{other}`"),
)),
}
}
fn parse_vertex(
mut words: SplitWhitespace<'_>,
number: usize,
positions: &mut Vec<Vec3>,
) -> Result<(), MeshError> {
let x = coordinate(&mut words, number)?;
let y = coordinate(&mut words, number)?;
let z = coordinate(&mut words, number)?;
positions.push(Vec3::new(x, y, z));
Ok(())
}
fn parse_face(
words: SplitWhitespace<'_>,
number: usize,
vertex_count: usize,
indices: &mut Vec<[u32; 3]>,
) -> Result<(), MeshError> {
let mut corners = Vec::new();
for word in words {
corners.push(parse_corner(word, number, vertex_count)?);
}
let Some((&first, rest)) = corners.split_first() else {
return Err(short_face(number));
};
if rest.len() < 2 {
return Err(short_face(number));
}
for pair in rest.windows(2) {
if let [a, b] = pair {
indices.push([first, *a, *b]);
}
}
Ok(())
}
/// Resolves one face corner such as `7`, `7/2`, `7//3` or `7/2/3`.
fn parse_corner(word: &str, number: usize, vertex_count: usize) -> Result<u32, MeshError> {
let mut parts = word.split('/');
let vertex = parts.next().unwrap_or_default();
if vertex.is_empty() || parts.count() > 2 {
return Err(bad_corner(word, number));
}
let Ok(raw) = vertex.parse::<i64>() else {
return Err(bad_corner(word, number));
};
let resolved = match raw {
0 => return Err(malformed(number, "OBJ vertex indices are one-based")),
relative if relative < 0 => vertex_count as i64 + relative,
absolute => absolute - 1,
};
if resolved < 0 {
return Err(bad_corner(word, number));
}
u32::try_from(resolved).map_err(|_| bad_corner(word, number))
}
fn coordinate(words: &mut SplitWhitespace<'_>, line: usize) -> Result<f64, MeshError> {
let Some(word) = words.next() else {
return Err(malformed(line, "missing vertex coordinate"));
};
word.parse()
.map_err(|_| malformed(line, format!("`{word}` is not a valid coordinate")))
}
fn short_face(line: usize) -> MeshError {
malformed(line, "face needs at least three vertices".to_string())
}
fn bad_corner(word: &str, line: usize) -> MeshError {
malformed(line, format!("`{word}` is not a valid face corner"))
}
fn malformed(line: usize, reason: impl Into<String>) -> MeshError {
MeshError::Malformed {
line,
reason: reason.into(),
}
}

View file

@ -0,0 +1,256 @@
//! STL import for binary and ASCII files.
//!
//! STL stores a triangle soup without shared vertices and without units. Import
//! welds vertices whose coordinates are bitwise equal after the `f32` → `f64`
//! conversion, so a well-formed file becomes a watertight indexed mesh. Welding
//! uses the bit pattern, so `-0.0` and `0.0` stay distinct: a file that mixes
//! signed zero can keep a seam and fail [`Mesh::validate`]. Normals are ignored;
//! the winding of the `vertex` lines is authoritative and validation checks it.
//!
//! Units are not stored either, so apply [`Mesh::scaled`] with the project unit
//! factor (millimetres by default, see docs/COORDINATES.md).
use core::str::SplitWhitespace;
use fabrilis_core::vec::Vec3;
use std::collections::BTreeMap;
use super::mesh::{Mesh, MeshError};
/// Bytes before the triangle count in a binary STL file.
const HEADER: usize = 80;
/// Bytes in one binary STL triangle record: one normal and three vertices.
const RECORD: usize = 50;
/// Bytes occupied by the normal at the start of a record; the normal is ignored.
const NORMAL: usize = 12;
/// Imports a binary or ASCII STL file.
///
/// Binary detection requires at least 84 bytes and an exact match between the
/// file length and `84 + 50 × triangle count`; anything else is parsed as ASCII.
pub fn from_stl(bytes: &[u8]) -> Result<Mesh, MeshError> {
if let Some(count) = binary_triangles(bytes) {
return from_binary(bytes, count);
}
from_ascii(bytes)
}
/// The declared triangle count when `bytes` is a binary STL file.
fn binary_triangles(bytes: &[u8]) -> Option<usize> {
let count = u32::from_le_bytes(four_bytes(bytes, HEADER)?) as usize;
let expected = (HEADER + 4).checked_add(RECORD.checked_mul(count)?)?;
(expected == bytes.len()).then_some(count)
}
fn from_binary(bytes: &[u8], count: usize) -> Result<Mesh, MeshError> {
if count == 0 {
return Err(MeshError::Empty);
}
let mut welder = Welder::default();
let mut indices = Vec::with_capacity(count);
for triangle in 0..count {
let start = HEADER + 4 + triangle * RECORD;
let points = binary_triangle(bytes, start).ok_or_else(|| truncated(triangle + 1))?;
indices.push(points.map(|point| welder.index(point)));
}
Mesh::new(welder.positions, indices)
}
/// Three vertices of one binary record; the normal at `start` is skipped.
fn binary_triangle(bytes: &[u8], start: usize) -> Option<[Vec3; 3]> {
let mut points = [Vec3::ZERO; 3];
for (index, slot) in points.iter_mut().enumerate() {
let base = start + NORMAL + index * 12;
let x = f32::from_le_bytes(four_bytes(bytes, base)?);
let y = f32::from_le_bytes(four_bytes(bytes, base + 4)?);
let z = f32::from_le_bytes(four_bytes(bytes, base + 8)?);
*slot = Vec3::new(f64::from(x), f64::from(y), f64::from(z));
}
Some(points)
}
fn four_bytes(bytes: &[u8], offset: usize) -> Option<[u8; 4]> {
let end = offset.checked_add(4)?;
bytes.get(offset..end)?.try_into().ok()
}
fn truncated(line: usize) -> MeshError {
MeshError::Malformed {
line,
reason: "truncated binary STL triangle".to_string(),
}
}
fn from_ascii(bytes: &[u8]) -> Result<Mesh, MeshError> {
let text = core::str::from_utf8(bytes).map_err(|error| MeshError::Malformed {
line: line_at(bytes, error.valid_up_to()),
reason: "STL text is not valid UTF-8".to_string(),
})?;
let mut parser = Ascii::default();
for (index, line) in text.lines().enumerate() {
parser.line(line, index + 1)?;
}
parser.finish()
}
fn line_at(bytes: &[u8], offset: usize) -> usize {
bytes.get(..offset).map_or(1, |prefix| {
1 + prefix.iter().filter(|byte| **byte == b'\n').count()
})
}
/// State of the ASCII facet grammar.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
enum Stage {
/// Between facets.
#[default]
Idle,
/// After `facet normal`, before `outer loop`.
Facet,
/// Inside `outer loop`.
Loop,
/// After `endloop`, before `endfacet`.
Closed,
}
/// A small state machine over ASCII STL keywords.
#[derive(Default)]
struct Ascii {
welder: Welder,
indices: Vec<[u32; 3]>,
stage: Stage,
loop_vertices: Vec<u32>,
last_line: usize,
}
impl Ascii {
fn line(&mut self, text: &str, number: usize) -> Result<(), MeshError> {
self.last_line = number;
let mut words = text.split_whitespace();
let Some(keyword) = words.next() else {
return Ok(());
};
match keyword.to_ascii_lowercase().as_str() {
"solid" | "endsolid" => Ok(()),
"facet" => self.facet(words, number),
"outer" => self.outer(words, number),
"vertex" => self.vertex(words, number),
"endloop" => self.end_loop(number),
"endfacet" => self.end_facet(number),
other => Err(malformed(
number,
format!("unexpected STL keyword `{other}`"),
)),
}
}
fn facet(&mut self, mut words: SplitWhitespace<'_>, number: usize) -> Result<(), MeshError> {
if self.stage != Stage::Idle {
return Err(malformed(number, "`facet` without `endfacet`"));
}
let kind = words.next().unwrap_or_default();
if !kind.eq_ignore_ascii_case("normal") {
return Err(malformed(number, "expected `facet normal`"));
}
for _ in 0..3 {
number_value(&mut words, number, "normal component")?;
}
self.stage = Stage::Facet;
Ok(())
}
fn outer(&mut self, mut words: SplitWhitespace<'_>, number: usize) -> Result<(), MeshError> {
let kind = words.next().unwrap_or_default();
if self.stage != Stage::Facet || !kind.eq_ignore_ascii_case("loop") {
return Err(malformed(number, "expected `outer loop` after `facet`"));
}
self.loop_vertices.clear();
self.stage = Stage::Loop;
Ok(())
}
fn vertex(&mut self, mut words: SplitWhitespace<'_>, number: usize) -> Result<(), MeshError> {
if self.stage != Stage::Loop {
return Err(malformed(number, "`vertex` outside `outer loop`"));
}
let x = number_value(&mut words, number, "vertex coordinate")?;
let y = number_value(&mut words, number, "vertex coordinate")?;
let z = number_value(&mut words, number, "vertex coordinate")?;
let index = self.welder.index(Vec3::new(x, y, z));
self.loop_vertices.push(index);
Ok(())
}
fn end_loop(&mut self, number: usize) -> Result<(), MeshError> {
if self.stage != Stage::Loop {
return Err(malformed(number, "`endloop` outside a loop"));
}
let corners: [u32; 3] = self.loop_vertices.as_slice().try_into().map_err(|_| {
malformed(
number,
"an STL facet must have exactly three vertices".to_string(),
)
})?;
self.indices.push(corners);
self.loop_vertices.clear();
self.stage = Stage::Closed;
Ok(())
}
fn end_facet(&mut self, number: usize) -> Result<(), MeshError> {
if self.stage != Stage::Closed {
return Err(malformed(number, "`endfacet` without a complete facet"));
}
self.stage = Stage::Idle;
Ok(())
}
fn finish(self) -> Result<Mesh, MeshError> {
if self.stage != Stage::Idle {
return Err(malformed(self.last_line, "unterminated STL facet"));
}
if self.indices.is_empty() {
return Err(MeshError::Empty);
}
Mesh::new(self.welder.positions, self.indices)
}
}
/// One floating-point token, with a line number for the error.
fn number_value(
words: &mut SplitWhitespace<'_>,
line: usize,
what: &str,
) -> Result<f64, MeshError> {
let Some(word) = words.next() else {
return Err(malformed(line, format!("missing {what}")));
};
word.parse()
.map_err(|_| malformed(line, format!("`{word}` is not a valid {what}")))
}
fn malformed(line: usize, reason: impl Into<String>) -> MeshError {
MeshError::Malformed {
line,
reason: reason.into(),
}
}
/// Interns vertices by the bit pattern of their coordinates.
#[derive(Default)]
struct Welder {
positions: Vec<Vec3>,
lookup: BTreeMap<(u64, u64, u64), u32>,
}
impl Welder {
fn index(&mut self, point: Vec3) -> u32 {
let key = (point.x.to_bits(), point.y.to_bits(), point.z.to_bits());
if let Some(&index) = self.lookup.get(&key) {
return index;
}
let index = self.positions.len() as u32;
self.positions.push(point);
self.lookup.insert(key, index);
index
}
}

View file

@ -0,0 +1,283 @@
use super::*;
use fabrilis_core::vec::Vec3;
fn close(actual: f64, expected: f64) -> bool {
(actual - expected).abs() <= 1e-9 * expected.abs().max(1.0)
}
fn cube_positions() -> Vec<Vec3> {
vec![
Vec3::new(0.0, 0.0, 0.0),
Vec3::new(1.0, 0.0, 0.0),
Vec3::new(1.0, 1.0, 0.0),
Vec3::new(0.0, 1.0, 0.0),
Vec3::new(0.0, 0.0, 1.0),
Vec3::new(1.0, 0.0, 1.0),
Vec3::new(1.0, 1.0, 1.0),
Vec3::new(0.0, 1.0, 1.0),
]
}
/// The unit cube with outward winding, two triangles per side.
const UNIT_CUBE: [[u32; 3]; 12] = [
[0, 2, 1],
[0, 3, 2],
[4, 5, 6],
[4, 6, 7],
[0, 1, 5],
[0, 5, 4],
[2, 3, 7],
[2, 7, 6],
[0, 4, 7],
[0, 7, 3],
[1, 2, 6],
[1, 6, 5],
];
fn cube_mesh() -> Mesh {
Mesh::new(cube_positions(), UNIT_CUBE.to_vec()).expect("the unit cube has in-range indices")
}
fn cube_triangles() -> Vec<[Vec3; 3]> {
cube_mesh().triangles().collect()
}
fn ascii_stl(triangles: &[[Vec3; 3]]) -> String {
let mut text = String::from("solid cube\n");
for [a, b, c] in triangles {
text.push_str(" facet normal 0 0 0\n outer loop\n");
for point in [a, b, c] {
text.push_str(&format!(
" vertex {} {} {}\n",
point.x, point.y, point.z
));
}
text.push_str(" endloop\n endfacet\n");
}
text.push_str("endsolid cube\n");
text
}
fn binary_stl(triangles: &[[Vec3; 3]]) -> Vec<u8> {
let mut bytes = vec![0u8; 80];
bytes.extend_from_slice(&(triangles.len() as u32).to_le_bytes());
for [a, b, c] in triangles {
for _ in 0..3 {
bytes.extend_from_slice(&0f32.to_le_bytes());
}
for point in [a, b, c] {
for value in [point.x, point.y, point.z] {
bytes.extend_from_slice(&(value as f32).to_le_bytes());
}
}
bytes.extend_from_slice(&0u16.to_le_bytes());
}
bytes
}
const OBJ_CUBE: &str = "\
v 0 0 0
v 1 0 0
v 1 1 0
v 0 1 0
v 0 0 1
v 1 0 1
v 1 1 1
v 0 1 1
f 1 4 3 2
f 5 6 7 8
f 1 2 6 5
f 3 4 8 7
f 1 5 8 4
f 2 3 7 6
";
const OBJ_TETRA_RELATIVE: &str = "\
v 0 0 0
v 1 0 0
v 0 1 0
v 0 0 1
f -4 -2 -3
f -4 -3 -1
f -3 -2 -1
f -4 -1 -2
";
#[test]
fn ascii_stl_cube_validates_and_welds_vertices() {
let text = ascii_stl(&cube_triangles());
let mesh = from_stl(text.as_bytes()).expect("the ASCII cube imports");
assert_eq!(mesh.positions.len(), 8, "36 facet vertices weld into 8");
assert_eq!(mesh.triangles().count(), 12);
let report = mesh.validate().expect("the cube is watertight");
assert_eq!(report.vertices, 8);
assert_eq!(report.triangles, 12);
assert_eq!(report.degenerate, 0);
assert!(close(report.volume.get(), 1.0), "volume {report:?}");
assert!(close(mesh.area(), 6.0), "area {}", mesh.area());
}
#[test]
fn binary_stl_cube_matches_the_ascii_result() {
let bytes = binary_stl(&cube_triangles());
assert_eq!(bytes.len(), 84 + 50 * 12);
let mesh = from_stl(&bytes).expect("the binary cube imports");
assert_eq!(mesh.positions.len(), 8);
assert_eq!(mesh.triangles().count(), 12);
let report = mesh.validate().expect("the cube is watertight");
assert!(close(report.volume.get(), 1.0), "volume {report:?}");
assert!(close(mesh.area(), 6.0), "area {}", mesh.area());
}
#[test]
fn obj_quad_faces_are_fan_triangulated() {
let mesh = from_obj(OBJ_CUBE).expect("the OBJ cube imports");
assert_eq!(mesh.positions.len(), 8);
assert_eq!(
mesh.triangles().count(),
12,
"six quads become 12 triangles"
);
let report = mesh.validate().expect("the cube is watertight");
assert_eq!(report.vertices, 8);
assert_eq!(report.triangles, 12);
assert!(close(report.volume.get(), 1.0), "volume {report:?}");
assert!(close(mesh.area(), 6.0), "area {}", mesh.area());
}
#[test]
fn obj_negative_indices_resolve_relative_to_the_end() {
let mesh = from_obj(OBJ_TETRA_RELATIVE).expect("relative indices resolve");
assert_eq!(mesh.positions.len(), 4);
assert_eq!(mesh.triangles().count(), 4);
let report = mesh.validate().expect("the tetrahedron is watertight");
assert!(close(report.volume.get(), 1.0 / 6.0), "volume {report:?}");
}
#[test]
fn open_mesh_is_not_watertight() {
let indices = UNIT_CUBE.iter().take(11).copied().collect();
let mesh = Mesh::new(cube_positions(), indices).expect("indices are in range");
let error = mesh
.validate()
.expect_err("a missing triangle opens the surface");
assert!(
matches!(
error,
MeshError::NotWatertight {
undirected_edges: 3
}
),
"unexpected error {error:?}"
);
}
#[test]
fn reversed_triangle_breaks_the_winding() {
let mut indices = UNIT_CUBE.to_vec();
if let Some(last) = indices.last_mut() {
*last = [1, 5, 6];
}
let mesh = Mesh::new(cube_positions(), indices).expect("indices are in range");
let error = mesh
.validate()
.expect_err("one reversed triangle breaks winding");
assert!(
matches!(error, MeshError::InconsistentWinding { .. }),
"unexpected error {error:?}"
);
}
#[test]
fn fully_reversed_cube_is_inverted() {
let indices = UNIT_CUBE.iter().map(|&[a, b, c]| [a, c, b]).collect();
let mesh = Mesh::new(cube_positions(), indices).expect("indices are in range");
match mesh
.validate()
.expect_err("inward winding has negative volume")
{
MeshError::Inverted { volume } => assert!(close(volume, -1.0), "volume {volume}"),
other => panic!("expected Inverted, got {other:?}"),
}
}
#[test]
fn out_of_range_index_is_rejected() {
let error = Mesh::new(vec![Vec3::ZERO], vec![[0, 1, 2]]).expect_err("one vertex is not enough");
assert_eq!(error, MeshError::BadIndex { triangle: 0 });
let text = "v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 4\n";
let error = from_obj(text).expect_err("the face names a missing vertex");
assert_eq!(error, MeshError::BadIndex { triangle: 0 });
}
#[test]
fn empty_input_is_rejected() {
assert!(matches!(from_obj(""), Err(MeshError::Empty)));
assert!(matches!(
from_obj("# only a comment\n"),
Err(MeshError::Empty)
));
assert!(matches!(from_stl(b""), Err(MeshError::Empty)));
}
#[test]
fn scaled_converts_millimetres_to_metres() {
let millimetres = cube_mesh().scaled(1000.0);
let triangles: Vec<_> = millimetres.triangles().collect();
let imported = from_stl(&binary_stl(&triangles)).expect("the millimetre cube imports");
let cubic_millimetres = imported.signed_volume().expect("closed mesh");
assert!(
close(cubic_millimetres, 1.0e9),
"volume {cubic_millimetres}"
);
let metres = imported.scaled(0.001);
assert_eq!(metres.indices.len(), 12);
let report = metres.validate().expect("the metre cube is valid");
assert!(close(report.volume.get(), 1.0), "volume {report:?}");
}
#[test]
fn degenerate_triangle_is_rejected() {
let positions = vec![Vec3::ZERO, Vec3::X, Vec3::Y];
let mesh = Mesh::new(positions, vec![[0, 0, 1]]).expect("indices are in range");
assert_eq!(
mesh.validate().expect_err("a repeated corner has no area"),
MeshError::Degenerate { triangle: 0 }
);
}
#[test]
fn non_finite_vertex_is_rejected() {
let positions = vec![Vec3::new(f64::NAN, 0.0, 0.0), Vec3::Y, Vec3::Z];
let mesh = Mesh::new(positions, vec![[0, 1, 2]]).expect("indices are in range");
assert_eq!(
mesh.validate().expect_err("NaN is not a coordinate"),
MeshError::NonFinite { triangle: 0 }
);
}
#[test]
fn malformed_obj_face_reports_its_line() {
let text = "v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 nope\n";
let error = from_obj(text).expect_err("the face corner is not a number");
assert!(
matches!(error, MeshError::Malformed { line: 4, .. }),
"unexpected error {error:?}"
);
}
#[test]
fn malformed_stl_line_reports_its_line() {
let text = "solid cube\n nonsense here\nendsolid cube\n";
let error = from_stl(text.as_bytes()).expect_err("the keyword is unknown");
assert!(
matches!(error, MeshError::Malformed { line: 2, .. }),
"unexpected error {error:?}"
);
}

View file

@ -0,0 +1,114 @@
//! Mass properties of a part and of a whole design.
//!
//! A part's result already has its centre of mass and inertia in the design frame:
//! the mesh is measured in its own axes and then moved by the pose. Aggregating
//! parts therefore needs only the parallel-axis theorem, with `d` measured from
//! the assembly centre of mass.
use fabrilis_core::units::{CubicMeters, Kilograms};
use fabrilis_core::vec::{Mat3, Vec3};
use fabrilis_materials::db::MaterialDb;
use fabrilis_materials::massprops::{MassProperties, from_triangles};
use fabrilis_storage::blob::BlobStore;
use super::{Design, Part, SceneError, load_mesh};
impl Part {
/// Mass, centre of mass and inertia of this part in the design frame.
///
/// The centre of mass is moved by the pose, and the inertia about the part's
/// centre of mass is rotated into design axes (`R I Rᵀ`).
pub fn mass(
&self,
materials: &MaterialDb,
store: &BlobStore,
) -> Result<MassProperties, SceneError> {
let transform = self.pose.to_transform().ok_or(SceneError::BadPose)?;
let mesh = load_mesh(store, self.mesh)?;
let material = materials
.get(&self.material)
.ok_or_else(|| SceneError::UnknownMaterial(self.material.clone()))?;
let triangles: Vec<[Vec3; 3]> = mesh.triangles().collect();
let local = from_triangles(&triangles, material.density).ok_or(SceneError::BadMass)?;
let rotation = transform.rotation.to_mat3();
Ok(MassProperties {
volume: local.volume,
mass: local.mass,
center_of_mass: transform.transform_point(local.center_of_mass),
inertia: rotation * local.inertia * rotation.transpose(),
})
}
}
impl Design {
/// Mass, centre of mass and inertia of the assembly.
///
/// Total mass is the sum of the parts, the centre of mass is mass-weighted,
/// and each part's inertia is shifted to the assembly centre with the
/// parallel-axis theorem. An empty design is an error, not a zero mass.
pub fn mass_properties(
&self,
materials: &MaterialDb,
store: &BlobStore,
) -> Result<MassProperties, SceneError> {
let parts: Vec<MassProperties> = self
.parts
.iter()
.map(|part| part.mass(materials, store))
.collect::<Result<_, SceneError>>()?;
if parts.is_empty() {
return Err(SceneError::EmptyDesign);
}
let total_mass: f64 = parts.iter().map(|part| part.mass.get()).sum();
let weighted = parts.iter().fold(Vec3::ZERO, |sum, part| {
sum + part.center_of_mass * part.mass.get()
});
let center_of_mass = weighted / total_mass;
if !total_mass.is_finite() || total_mass <= 0.0 || !center_of_mass.is_finite() {
return Err(SceneError::BadMass);
}
let mut inertia = Mat3::from_diagonal(Vec3::ZERO);
for part in &parts {
let offset = part.center_of_mass - center_of_mass;
inertia = sum_matrices(
inertia,
parallel_axis(part.inertia, part.mass.get(), offset),
);
}
let volume: f64 = parts.iter().map(|part| part.volume.get()).sum();
if !inertia_is_finite(inertia) || !volume.is_finite() {
return Err(SceneError::BadMass);
}
Ok(MassProperties {
volume: CubicMeters::new(volume),
mass: Kilograms::new(total_mass),
center_of_mass,
inertia,
})
}
}
/// Adds `m (|d|² I − d dᵀ)` to `inertia`.
fn parallel_axis(inertia: Mat3, mass: f64, offset: Vec3) -> Mat3 {
let (x, y, z) = (offset.x, offset.y, offset.z);
let square = offset.length_squared();
let shift = Mat3::from_cols(
Vec3::new(mass * (square - x * x), -mass * x * y, -mass * x * z),
Vec3::new(-mass * y * x, mass * (square - y * y), -mass * y * z),
Vec3::new(-mass * z * x, -mass * z * y, mass * (square - z * z)),
);
sum_matrices(inertia, shift)
}
fn sum_matrices(left: Mat3, right: Mat3) -> Mat3 {
let [lx, ly, lz] = left.cols();
let [rx, ry, rz] = right.cols();
Mat3::from_cols(lx + rx, ly + ry, lz + rz)
}
fn inertia_is_finite(inertia: Mat3) -> bool {
inertia
.cols()
.iter()
.all(|column| column.x.is_finite() && column.y.is_finite() && column.z.is_finite())
}

View file

@ -0,0 +1,84 @@
//! Mesh blobs: the RON form stored in a content-addressed blob store.
//!
//! The mesh is stored once per distinct geometry; parts reference it by
//! [`BlobHash`](fabrilis_storage::blob::BlobHash) (docs/STORAGE.md).
use fabrilis_core::vec::Vec3;
use fabrilis_storage::blob::{BlobHash, BlobStore};
use serde::{Deserialize, Serialize};
use crate::import::{Mesh, from_stl};
use super::{Part, Pose, SceneError};
/// The on-disk mesh form: arrays instead of core math types, which have no serde.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct StoredMesh {
positions: Vec<[f64; 3]>,
indices: Vec<[u32; 3]>,
}
/// Serialises the mesh as RON and stores it, returning its content hash.
///
/// Storing identical geometry twice is a no-op: the hash, and therefore the file,
/// is the same.
pub fn store_mesh(store: &mut BlobStore, mesh: &Mesh) -> Result<BlobHash, SceneError> {
let stored = StoredMesh {
positions: mesh
.positions
.iter()
.map(|point| [point.x, point.y, point.z])
.collect(),
indices: mesh.indices.clone(),
};
let text = ron::ser::to_string_pretty(&stored, ron::ser::PrettyConfig::default())
.map_err(|error| SceneError::MeshBlob(error.to_string()))?;
Ok(store.put(text.as_bytes())?)
}
/// Reads a stored mesh and validates it as a closed, outward-wound surface.
pub fn load_mesh(store: &BlobStore, hash: BlobHash) -> Result<Mesh, SceneError> {
let bytes = store.get(hash)?;
let text =
core::str::from_utf8(&bytes).map_err(|error| SceneError::MeshBlob(error.to_string()))?;
let stored: StoredMesh =
ron::from_str(text).map_err(|error| SceneError::MeshBlob(error.to_string()))?;
let positions = stored
.positions
.iter()
.map(|&[x, y, z]| Vec3::new(x, y, z))
.collect();
let mesh = Mesh::new(positions, stored.indices)?;
mesh.validate()?;
Ok(mesh)
}
/// Imports an STL part: parse, scale to metres, validate, then store the mesh.
///
/// STL carries neither units nor axes, so `unit_scale` is the source unit factor
/// (`0.001` for millimetres, `1.0` for metres); see docs/COORDINATES.md.
#[allow(
clippy::too_many_arguments,
reason = "the STL import inputs are independent scalars; a group struct would obscure the call site"
)]
pub fn add_part_from_stl(
store: &mut BlobStore,
name: &str,
stl: &[u8],
unit_scale: f64,
material: &str,
pose: Pose,
) -> Result<Part, SceneError> {
if !unit_scale.is_finite() || unit_scale <= 0.0 {
return Err(SceneError::BadScale(unit_scale));
}
let mesh = from_stl(stl)?.scaled(unit_scale);
mesh.validate()?;
let hash = store_mesh(store, &mesh)?;
Ok(Part {
name: name.to_string(),
mesh: hash,
material: material.to_string(),
pose,
})
}

View file

@ -1 +1,193 @@
//! fabrilis-scene :: model - stub (see docs/ARCHITECTURE.md)
//! Design model: named rigid parts and their mass properties.
//!
//! A part references its mesh by content hash, so one copy of a mesh serves every
//! part that uses it (docs/STORAGE.md). Poses are plain arrays because the core
//! math types intentionally do not depend on serde; conversion to [`Transform`]
//! normalises the quaternion and rejects degenerate input.
mod mass;
mod mesh;
mod persist;
use core::fmt;
use std::io;
use fabrilis_core::vec::{Quat, Transform, Vec3};
use fabrilis_storage::blob::BlobHash;
use fabrilis_storage::format::FormatError;
use serde::{Deserialize, Serialize};
use crate::import::MeshError;
pub use mesh::{add_part_from_stl, load_mesh, store_mesh};
pub use persist::DESIGN_FILE;
/// A serialisable rigid pose: position in metres and a `wxyz` quaternion.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Pose {
/// Position, m.
pub position: [f64; 3],
/// Rotation as a `wxyz` quaternion; not necessarily unit length.
pub rotation: [f64; 4],
}
impl Default for Pose {
fn default() -> Self {
Self {
position: [0.0; 3],
rotation: [1.0, 0.0, 0.0, 0.0],
}
}
}
impl Pose {
/// The corresponding [`Transform`], or `None` for a non-finite position or a
/// zero/non-finite quaternion.
#[must_use]
pub fn to_transform(self) -> Option<Transform> {
let position = Vec3::new(self.position[0], self.position[1], self.position[2]);
if !position.is_finite() {
return None;
}
let rotation = Quat::new(
self.rotation[0],
self.rotation[1],
self.rotation[2],
self.rotation[3],
)
.normalize()?;
Some(Transform::new(position, rotation))
}
/// The pose that places a transform, keeping its quaternion as given.
#[must_use]
pub fn from_transform(transform: Transform) -> Self {
Self {
position: [
transform.position.x,
transform.position.y,
transform.position.z,
],
rotation: [
transform.rotation.w,
transform.rotation.x,
transform.rotation.y,
transform.rotation.z,
],
}
}
}
/// One rigid part: a mesh, a material and a pose in the design's frame.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Part {
/// Name, unique within the design by convention.
pub name: String,
/// Content hash of the stored mesh.
pub mesh: BlobHash,
/// Material name in a [`fabrilis_materials::db::MaterialDb`].
pub material: String,
/// Placement of the part's mesh in the design frame.
pub pose: Pose,
}
/// A named collection of parts.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Design {
/// Design name.
pub name: String,
/// Parts in insertion order.
pub parts: Vec<Part>,
}
impl Design {
/// An empty design.
#[must_use]
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
parts: Vec::new(),
}
}
/// Appends a part.
pub fn push(&mut self, part: Part) {
self.parts.push(part);
}
}
/// Why a design, a mesh blob or a mass computation failed.
#[derive(Debug)]
pub enum SceneError {
/// Reading or writing a project file failed.
Io(io::Error),
/// The versioned scene envelope is invalid.
Format(FormatError),
/// The mesh itself is invalid before it is stored.
Mesh(MeshError),
/// A stored mesh blob cannot be decoded.
MeshBlob(String),
/// The material name is not in the database.
UnknownMaterial(String),
/// The pose has a non-finite position or a zero/non-finite rotation.
BadPose,
/// The unit scale must be finite and positive.
BadScale(f64),
/// There is nothing to aggregate.
EmptyDesign,
/// Aggregated mass properties are not finite.
BadMass,
}
impl fmt::Display for SceneError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Io(error) => write!(formatter, "project I/O failed: {error}"),
Self::Format(error) => write!(formatter, "scene format error: {error}"),
Self::Mesh(error) => write!(formatter, "mesh error: {error}"),
Self::MeshBlob(reason) => write!(formatter, "stored mesh is invalid: {reason}"),
Self::UnknownMaterial(name) => write!(formatter, "unknown material `{name}`"),
Self::BadPose => write!(
formatter,
"pose has a non-finite position or a zero/non-finite rotation"
),
Self::BadScale(scale) => {
write!(formatter, "unit scale {scale} must be finite and positive")
}
Self::EmptyDesign => write!(formatter, "design has no parts"),
Self::BadMass => write!(formatter, "aggregated mass properties are not finite"),
}
}
}
impl std::error::Error for SceneError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Io(error) => Some(error),
Self::Format(error) => Some(error),
Self::Mesh(error) => Some(error),
_ => None,
}
}
}
impl From<io::Error> for SceneError {
fn from(error: io::Error) -> Self {
Self::Io(error)
}
}
impl From<FormatError> for SceneError {
fn from(error: FormatError) -> Self {
Self::Format(error)
}
}
impl From<MeshError> for SceneError {
fn from(error: MeshError) -> Self {
Self::Mesh(error)
}
}
#[cfg(test)]
mod tests;

View file

@ -0,0 +1,76 @@
//! Reading and writing `scene.ron` in a project folder.
//!
//! Version 0 of the scene format had no per-part `pose`; the migration below fills
//! in the identity pose, so an old cart opens without edits.
use std::collections::BTreeMap;
use fabrilis_storage::format::{from_ron_with_migrations, to_ron};
use fabrilis_storage::migrate::{MigrateError, Migration};
use fabrilis_storage::project::Project;
use super::{Design, Pose, SceneError};
/// File name of the design inside a project.
pub const DESIGN_FILE: &str = "scene.ron";
impl Design {
/// Writes the design as a versioned RON envelope in the project.
pub fn save(&self, project: &Project) -> Result<(), SceneError> {
let text = to_ron(self)?;
project.write_text(DESIGN_FILE, &text)?;
Ok(())
}
/// Reads the design, migrating older scene versions forward.
pub fn load(project: &Project) -> Result<Self, SceneError> {
let text = project.read_text(DESIGN_FILE)?;
Ok(from_ron_with_migrations(&text, &migrations())?)
}
}
fn migrations() -> BTreeMap<u32, Migration> {
let mut steps = BTreeMap::new();
let _previous = steps.insert(0, add_identity_pose as Migration);
steps
}
/// Version 0 → 1: every part gains the identity pose.
fn add_identity_pose(mut value: ron::Value) -> Result<ron::Value, MigrateError> {
let ron::Value::Map(ref mut design) = value else {
return Err(MigrateError::step(0, "scene payload is not a map"));
};
let Some(parts) = design.get_mut(&ron::Value::from("parts")) else {
return Err(MigrateError::step(0, "scene payload has no parts"));
};
let ron::Value::Seq(parts) = parts else {
return Err(MigrateError::step(0, "scene parts are not a list"));
};
for part in parts.iter_mut() {
let ron::Value::Map(part) = part else {
return Err(MigrateError::step(0, "a scene part is not a map"));
};
if part.get(&ron::Value::from("pose")).is_none() {
let _previous = part.insert("pose", pose_value(Pose::default()));
}
}
Ok(value)
}
/// The RON form of a pose, for migrations over [`ron::Value`].
fn pose_value(pose: Pose) -> ron::Value {
let position = pose
.position
.iter()
.map(|&value| ron::Value::from(value))
.collect();
let rotation = pose
.rotation
.iter()
.map(|&value| ron::Value::from(value))
.collect();
let mut map = ron::Map::new();
let _previous = map.insert("position", ron::Value::Seq(position));
let _previous = map.insert("rotation", ron::Value::Seq(rotation));
ron::Value::Map(map)
}

View file

@ -0,0 +1,223 @@
//! Pose conversion, mesh blobs and per-part mass properties.
#![allow(
clippy::unwrap_used,
reason = "a test aborts on failure, which is the intent"
)]
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use fabrilis_core::vec::{Transform, Vec3};
use fabrilis_materials::db::MaterialDb;
use fabrilis_storage::blob::BlobStore;
use super::{Design, Pose, SceneError, add_part_from_stl, load_mesh, store_mesh};
use crate::import::from_stl;
/// A directory removed on drop.
struct TempDir {
path: PathBuf,
}
impl TempDir {
fn new(label: &str) -> Self {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let counter = COUNTER.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!(
"fabrilis-scene-{label}-{}-{counter}",
std::process::id()
));
std::fs::create_dir_all(&path).unwrap();
Self { path }
}
fn blobs(&self) -> BlobStore {
BlobStore::new(self.path.join("blobs"))
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
/// A box with the given full extents, centred at the origin, as an ASCII STL.
fn box_stl(x: f64, y: f64, z: f64) -> String {
let (hx, hy, hz) = (x * 0.5, y * 0.5, z * 0.5);
let vertices = [
(-hx, -hy, -hz),
(hx, -hy, -hz),
(hx, hy, -hz),
(-hx, hy, -hz),
(-hx, -hy, hz),
(hx, -hy, hz),
(hx, hy, hz),
(-hx, hy, hz),
];
let triangles = [
[0, 2, 1],
[0, 3, 2],
[4, 5, 6],
[4, 6, 7],
[0, 1, 5],
[0, 5, 4],
[3, 7, 6],
[3, 6, 2],
[0, 4, 7],
[0, 7, 3],
[1, 2, 6],
[1, 6, 5],
];
let mut text = String::from("solid box\n");
for triangle in triangles {
text.push_str("facet normal 0 0 0\nouter loop\n");
for index in triangle {
let (vx, vy, vz) = vertices[index];
text.push_str(&format!("vertex {vx} {vy} {vz}\n"));
}
text.push_str("endloop\nendfacet\n");
}
text.push_str("endsolid box\n");
text
}
#[test]
fn pose_identity_round_trips() {
let pose = Pose::default();
let transform = pose.to_transform().unwrap();
assert_eq!(transform, Transform::IDENTITY);
assert_eq!(Pose::from_transform(transform), pose);
}
#[test]
fn pose_normalises_the_quaternion() {
let pose = Pose {
position: [1.0, 2.0, 3.0],
rotation: [2.0, 0.0, 0.0, 0.0],
};
let transform = pose.to_transform().unwrap();
assert_eq!(transform.position, Vec3::new(1.0, 2.0, 3.0));
assert!((transform.rotation.norm_squared() - 1.0).abs() < 1e-12);
assert!((transform.rotation.w - 1.0).abs() < 1e-12);
}
#[test]
fn pose_rejects_degenerate_values() {
let zero_rotation = Pose {
position: [0.0; 3],
rotation: [0.0; 4],
};
assert!(zero_rotation.to_transform().is_none());
let non_finite = Pose {
position: [f64::NAN, 0.0, 0.0],
rotation: [1.0, 0.0, 0.0, 0.0],
};
assert!(non_finite.to_transform().is_none());
}
#[test]
fn cube_mass_matches_the_density() {
let temp = TempDir::new("cube-mass");
let mut store = temp.blobs();
let side = 0.1;
let stl = box_stl(side, side, side);
let part = add_part_from_stl(
&mut store,
"cube",
stl.as_bytes(),
1.0,
"steel",
Pose::default(),
)
.unwrap();
let properties = part.mass(&MaterialDb::with_builtins(), &store).unwrap();
let expected = 7_850.0 * side * side * side;
assert!((properties.mass.get() - expected).abs() / expected < 1e-5);
assert!(properties.center_of_mass.length() < 1e-12);
let diagonal = expected * side * side / 6.0;
assert!((properties.inertia.cols()[0].x - diagonal).abs() / diagonal < 1e-5);
}
#[test]
fn pose_translation_moves_the_center_of_mass() {
let temp = TempDir::new("pose-mass");
let mut store = temp.blobs();
let stl = box_stl(0.1, 0.1, 0.1);
let pose = Pose {
position: [1.0, -2.0, 3.5],
rotation: [1.0, 0.0, 0.0, 0.0],
};
let part = add_part_from_stl(&mut store, "cube", stl.as_bytes(), 1.0, "steel", pose).unwrap();
let properties = part.mass(&MaterialDb::with_builtins(), &store).unwrap();
assert!((properties.center_of_mass.x - 1.0).abs() < 1e-12);
assert!((properties.center_of_mass.y + 2.0).abs() < 1e-12);
assert!((properties.center_of_mass.z - 3.5).abs() < 1e-12);
}
#[test]
fn stored_meshes_are_content_addressed() {
let temp = TempDir::new("mesh-blob");
let mut store = temp.blobs();
let mesh = from_stl(box_stl(0.2, 0.3, 0.4).as_bytes()).unwrap();
let first = store_mesh(&mut store, &mesh).unwrap();
let second = store_mesh(&mut store, &mesh).unwrap();
assert_eq!(first, second);
let files = std::fs::read_dir(store.root()).unwrap().count();
assert_eq!(files, 1);
assert_eq!(load_mesh(&store, first).unwrap(), mesh);
}
#[test]
fn an_unknown_material_is_reported() {
let temp = TempDir::new("material");
let mut store = temp.blobs();
let stl = box_stl(0.1, 0.1, 0.1);
let part = add_part_from_stl(
&mut store,
"cube",
stl.as_bytes(),
1.0,
"unobtainium",
Pose::default(),
)
.unwrap();
let error = part.mass(&MaterialDb::new(), &store).unwrap_err();
assert!(matches!(error, SceneError::UnknownMaterial(name) if name == "unobtainium"));
}
#[test]
fn two_cubes_aggregate_by_the_parallel_axis_theorem() {
let temp = TempDir::new("aggregate");
let mut store = temp.blobs();
let side = 0.1;
let mass = 7_850.0 * side * side * side;
let stl = box_stl(side, side, side);
let offset = 0.2;
let mut design = Design::new("pair");
for (name, x) in [("left", -offset), ("right", offset)] {
let pose = Pose {
position: [x, 0.0, 0.0],
rotation: [1.0, 0.0, 0.0, 0.0],
};
design
.push(add_part_from_stl(&mut store, name, stl.as_bytes(), 1.0, "steel", pose).unwrap());
}
let properties = design
.mass_properties(&MaterialDb::with_builtins(), &store)
.unwrap();
let expected_mass = 2.0 * mass;
assert!((properties.mass.get() - expected_mass).abs() / expected_mass < 1e-5);
assert!(properties.center_of_mass.length() < 1e-12);
let own = mass * side * side / 6.0;
let expected_yy = 2.0 * (own + mass * offset * offset);
assert!((properties.inertia.cols()[0].x - 2.0 * own).abs() / (2.0 * own) < 1e-5);
assert!((properties.inertia.cols()[1].y - expected_yy).abs() / expected_yy < 1e-5);
}

View file

@ -0,0 +1,87 @@
//! M3 seam: an STL part is validated as a closed mesh and its mass is computed from
//! the material density.
#![allow(
clippy::unwrap_used,
reason = "test helper: a failure should abort the test"
)]
use fabrilis_core::units::KilogramsPerCubicMeter;
use fabrilis_materials::db::MaterialDb;
use fabrilis_materials::massprops::from_triangles;
use fabrilis_scene::import::{Mesh, from_stl};
/// A cube of the given side, centred at the origin, as an ASCII STL.
fn cube_stl(side: f64) -> String {
let h = side * 0.5;
let vertices = [
(-h, -h, -h),
(h, -h, -h),
(h, h, -h),
(-h, h, -h),
(-h, -h, h),
(h, -h, h),
(h, h, h),
(-h, h, h),
];
let triangles = [
[0, 2, 1],
[0, 3, 2],
[4, 5, 6],
[4, 6, 7],
[0, 1, 5],
[0, 5, 4],
[3, 7, 6],
[3, 6, 2],
[0, 4, 7],
[0, 7, 3],
[1, 2, 6],
[1, 6, 5],
];
let mut text = String::from("solid cube\n");
for triangle in triangles {
text.push_str(" facet normal 0 0 0\n outer loop\n");
for index in triangle {
let (x, y, z) = vertices[index];
text.push_str(&format!(" vertex {x} {y} {z}\n"));
}
text.push_str(" endloop\n endfacet\n");
}
text.push_str("endsolid cube\n");
text
}
#[test]
fn stl_cube_mass_matches_the_analytic_value() {
let mesh = from_stl(cube_stl(1.0).as_bytes()).expect("the cube parses");
let report = mesh.validate().expect("the cube is closed");
assert!((report.volume.get() - 1.0).abs() < 1e-12);
let steel = MaterialDb::with_builtins();
let density = steel.get("steel").expect("steel is built in").density;
let mass = from_triangles(&mesh.triangles().collect::<Vec<_>>(), density)
.expect("a closed cube has mass properties");
assert!((mass.mass.get() - 7_850.0).abs() < 1.0);
assert!(mass.center_of_mass.length() < 1e-12);
let inertia = mass.mass.get() / 6.0;
assert!((mass.inertia.cols()[0].x - inertia).abs() < 1e-6);
}
#[test]
fn millimetre_stl_scaled_to_metres_keeps_the_mass() {
let mesh = from_stl(cube_stl(1_000.0).as_bytes())
.expect("the cube parses")
.scaled(0.001);
let report = mesh.validate().expect("the cube is closed");
assert!((report.volume.get() - 1.0).abs() < 1e-9);
let density = KilogramsPerCubicMeter::new(2_700.0);
let mass = from_triangles(&mesh.triangles().collect::<Vec<_>>(), density)
.expect("a closed cube has mass properties");
assert!((mass.mass.get() - 2_700.0).abs() < 1.0);
}
#[test]
fn an_open_mesh_is_rejected_before_mass_is_computed() {
let mut mesh: Mesh = from_stl(cube_stl(1.0).as_bytes()).expect("the cube parses");
mesh.indices.pop();
assert!(mesh.validate().is_err());
}

View file

@ -0,0 +1,229 @@
//! M3 seam: an STL cart is saved, loaded back and its mass is compared with the
//! analytic value.
#![allow(
clippy::unwrap_used,
reason = "a test aborts on failure, which is the intent"
)]
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use fabrilis_materials::db::MaterialDb;
use fabrilis_scene::model::{DESIGN_FILE, Design, Pose, add_part_from_stl};
use fabrilis_storage::project::Project;
/// A directory removed on drop.
struct TempDir {
path: PathBuf,
}
impl TempDir {
fn new(label: &str) -> Self {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let counter = COUNTER.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!(
"fabrilis-persistence-{label}-{}-{counter}",
std::process::id()
));
std::fs::create_dir_all(&path).unwrap();
Self { path }
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
/// A box with the given full extents, centred at the origin, as an ASCII STL.
fn box_stl(x: f64, y: f64, z: f64) -> String {
let (hx, hy, hz) = (x * 0.5, y * 0.5, z * 0.5);
let vertices = [
(-hx, -hy, -hz),
(hx, -hy, -hz),
(hx, hy, -hz),
(-hx, hy, -hz),
(-hx, -hy, hz),
(hx, -hy, hz),
(hx, hy, hz),
(-hx, hy, hz),
];
let triangles = [
[0, 2, 1],
[0, 3, 2],
[4, 5, 6],
[4, 6, 7],
[0, 1, 5],
[0, 5, 4],
[3, 7, 6],
[3, 6, 2],
[0, 4, 7],
[0, 7, 3],
[1, 2, 6],
[1, 6, 5],
];
let mut text = String::from("solid box\n");
for triangle in triangles {
text.push_str("facet normal 0 0 0\nouter loop\n");
for index in triangle {
let (vx, vy, vz) = vertices[index];
text.push_str(&format!("vertex {vx} {vy} {vz}\n"));
}
text.push_str("endloop\nendfacet\n");
}
text.push_str("endsolid box\n");
text
}
fn pose_at(x: f64, y: f64, z: f64) -> Pose {
Pose {
position: [x, y, z],
rotation: [1.0, 0.0, 0.0, 0.0],
}
}
#[test]
fn a_cart_round_trips_and_its_mass_matches_the_analytic_value() {
let temp = TempDir::new("cart");
let project = Project::create(&temp.path).unwrap();
let mut blobs = project.blobs();
let mut design = Design::new("cart");
let body = box_stl(0.4, 0.2, 0.1);
design.push(
add_part_from_stl(
&mut blobs,
"body",
body.as_bytes(),
1.0,
"steel",
pose_at(0.0, 0.0, 0.0),
)
.unwrap(),
);
let wheel = box_stl(0.1, 0.1, 0.1);
for (name, y) in [("left", 0.15), ("right", -0.15)] {
design.push(
add_part_from_stl(
&mut blobs,
name,
wheel.as_bytes(),
1.0,
"aluminium",
pose_at(0.0, y, -0.05),
)
.unwrap(),
);
}
design.save(&project).unwrap();
let text = project.read_text(DESIGN_FILE).unwrap();
assert!(text.contains("format_version: 1"));
assert!(text.contains("payload:"));
assert!(project.path(DESIGN_FILE).is_file());
let loaded = Design::load(&project).unwrap();
assert_eq!(loaded.name, design.name);
assert_eq!(loaded.parts, design.parts);
let materials = MaterialDb::with_builtins();
let properties = loaded.mass_properties(&materials, &blobs).unwrap();
let expected = 7_850.0 * 0.4 * 0.2 * 0.1 + 2.0 * 2_700.0 * 0.1 * 0.1 * 0.1;
let error = (properties.mass.get() - expected).abs() / expected;
assert!(error < 0.01, "mass error {error} exceeds 1 %");
assert!(properties.center_of_mass.is_finite());
assert!(
properties
.inertia
.cols()
.iter()
.all(|column| column.is_finite())
);
assert!(properties.inertia.determinant() > 0.0);
}
#[test]
fn identical_meshes_share_one_blob_and_one_table_entry() {
let temp = TempDir::new("dedup");
let project = Project::create(&temp.path).unwrap();
let mut blobs = project.blobs();
let wheel = box_stl(0.1, 0.1, 0.1);
let first = add_part_from_stl(
&mut blobs,
"left",
wheel.as_bytes(),
1.0,
"aluminium",
Pose::default(),
)
.unwrap();
let second = add_part_from_stl(
&mut blobs,
"right",
wheel.as_bytes(),
1.0,
"aluminium",
Pose::default(),
)
.unwrap();
assert_eq!(first.mesh, second.mesh);
let files = std::fs::read_dir(project.path("blobs")).unwrap().count();
assert_eq!(files, 1);
}
#[test]
fn a_version_zero_scene_is_migrated_to_identity_poses() {
let temp = TempDir::new("migrate");
let project = Project::create(&temp.path).unwrap();
let version_zero = "\
(
format_version: 0,
payload: (
name: \"cart\",
parts: [
(
name: \"body\",
mesh: \"0123456789abcdef\",
material: \"steel\",
),
],
),
)
";
project.write_text(DESIGN_FILE, version_zero).unwrap();
let design = Design::load(&project).unwrap();
assert_eq!(design.parts.len(), 1);
assert_eq!(design.parts[0].pose, Pose::default());
design.save(&project).unwrap();
let upgraded = project.read_text(DESIGN_FILE).unwrap();
assert!(upgraded.contains("format_version: 1"));
assert_eq!(Design::load(&project).unwrap().parts, design.parts);
}
#[test]
fn a_newer_scene_version_is_rejected() {
let temp = TempDir::new("future");
let project = Project::create(&temp.path).unwrap();
let version_two = "(format_version: 2, payload: (name: \"cart\", parts: []))";
project.write_text(DESIGN_FILE, version_two).unwrap();
assert!(Design::load(&project).is_err());
}
#[test]
fn a_missing_scene_file_is_a_not_found_error() {
let temp = TempDir::new("missing");
let project = Project::create(&temp.path).unwrap();
let error = Design::load(&project).unwrap_err();
let message = error.to_string();
assert!(
message.contains("No such file") || message.contains("os error 2"),
"{message}"
);
}