fabrilis/crates/scene/src/model/mass.rs
loki5512344 93075ab1fd
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
Add design persistence, world rendering, metrics overlay and logs
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.
2026-11-16 23:34:05 +01:00

114 lines
3.9 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! 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())
}