pub mod algorithms;
mod collisions;
mod conformal;
pub mod data;
pub(crate) mod edges;
mod editor;
pub mod filtering;
mod flat_domain;
pub(crate) mod measurement;
mod nav_structure;
mod outline;
pub mod patches;
mod queries;
pub mod sampling;
mod section;
mod transverse;
mod view;
pub mod voxelize;
use crate::common::{IndexMask, PCoords};
use crate::geom3::attributes3::{FaceAttrSet3, PointAttrSet3};
use crate::na::SVector;
use crate::{Iso3, Point2, Point3, Result, SurfacePoint3, UnitVec3, Vector3};
pub use collisions::MeshCollisionSet;
pub use data::{Attr3, MeshData3};
pub use edges::MeshEdges;
pub use editor::{EditReport, MeshEditor};
pub use flat_domain::FlatDomain;
pub use measurement::SurfaceDeviation;
pub use nav_structure::MeshNav;
use parry3d_f64::bounding_volume::Aabb;
use parry3d_f64::shape::{TriMesh, TriMeshFlags};
use parry3d_f64::transformation;
pub use patches::{PatchFilter, PatchLabels, PatchStats};
pub use section::PlanarSection;
pub use transverse::{TransverseOptions, TransversePlane};
pub use view::MeshView3;
use crate::io::write_tc_mesh_file;
#[cfg(feature = "ply")]
use crate::io::{PlyWriteOpts, write_ply_mesh};
#[cfg(feature = "stl")]
use crate::io::{StlWriteOpts, write_stl_mesh};
use std::path::Path;
#[derive(Debug, Clone, Copy)]
pub struct MeshSurfPoint {
pub face_index: u32,
pub bc: [f64; 3],
pub sp: SurfacePoint3,
}
impl MeshSurfPoint {
pub fn new(face_index: u32, bc: [f64; 3], sp: SurfacePoint3) -> Self {
Self { face_index, bc, sp }
}
pub fn point(&self) -> Point3 {
self.sp.point
}
pub fn normal(&self) -> UnitVec3 {
self.sp.normal
}
pub fn new_transformed_by(&self, iso: &Iso3) -> Self {
Self {
face_index: self.face_index,
bc: self.bc,
sp: iso * self.sp,
}
}
}
impl Default for MeshSurfPoint {
fn default() -> Self {
Self {
face_index: 0,
bc: [0.0, 0.0, 0.0],
sp: SurfacePoint3::default(),
}
}
}
impl PCoords<3> for MeshSurfPoint {
fn coords(&self) -> SVector<f64, 3> {
self.sp.point.coords
}
}
#[derive(Clone)]
pub struct Mesh3 {
shape: TriMesh,
point_attrs: PointAttrSet3,
face_attrs: FaceAttrSet3,
is_solid: bool,
}
impl Mesh3 {
pub fn aabb(&self) -> Aabb {
self.shape.local_aabb()
}
pub fn tri_mesh(&self) -> &TriMesh {
&self.shape
}
pub fn is_solid(&self) -> bool {
self.is_solid
}
pub fn points(&self) -> &[Point3] {
self.shape.vertices()
}
pub fn faces(&self) -> &[[u32; 3]] {
self.shape.indices()
}
pub fn point_count(&self) -> usize {
self.shape.vertices().len()
}
pub fn face_count(&self) -> usize {
self.shape.indices().len()
}
}
impl Mesh3 {
pub fn point_attrs(&self) -> &PointAttrSet3 {
&self.point_attrs
}
pub fn face_attrs(&self) -> &FaceAttrSet3 {
&self.face_attrs
}
pub fn has_attrs(&self) -> bool {
!self.point_attrs.is_empty() || !self.face_attrs.is_empty()
}
pub fn point_normals(&self) -> Option<&[UnitVec3]> {
self.point_attrs.normals()
}
pub fn point_colors(&self) -> Option<&[[u8; 3]]> {
self.point_attrs.colors()
}
pub fn point_stdev(&self) -> Option<&[f64]> {
self.point_attrs.stdev()
}
pub fn point_flat(&self) -> Option<&[Point2]> {
self.point_attrs.flat()
}
pub fn face_colors(&self) -> Option<&[[u8; 3]]> {
self.face_attrs.colors()
}
pub fn face_labels(&self) -> Option<&[u32]> {
self.face_attrs.labels()
}
pub fn point_attr(&self, name: &str) -> Option<&Attr3> {
self.point_attrs.attr(name)
}
pub fn face_attr(&self, name: &str) -> Option<&Attr3> {
self.face_attrs.attr(name)
}
}
impl Mesh3 {
pub fn set_point_normals(&mut self, values: Option<Vec<UnitVec3>>) -> Result<()> {
self.point_attrs.set_normals(values, self.point_count())
}
pub fn set_point_colors(&mut self, values: Option<Vec<[u8; 3]>>) -> Result<()> {
self.point_attrs.set_colors(values, self.point_count())
}
pub fn set_point_stdev(&mut self, values: Option<Vec<f64>>) -> Result<()> {
self.point_attrs.set_stdev(values, self.point_count())
}
pub fn set_point_flat(&mut self, values: Option<Vec<Point2>>) -> Result<()> {
self.point_attrs.set_flat(values, self.point_count())
}
pub fn set_face_colors(&mut self, values: Option<Vec<[u8; 3]>>) -> Result<()> {
self.face_attrs.set_colors(values, self.face_count())
}
pub fn set_face_labels(&mut self, values: Option<Vec<u32>>) -> Result<()> {
self.face_attrs.set_labels(values, self.face_count())
}
pub fn insert_point_attr(&mut self, name: &str, attr: Attr3) -> Result<()> {
self.point_attrs.insert_attr(name, attr, self.point_count())
}
pub fn insert_face_attr(&mut self, name: &str, attr: Attr3) -> Result<()> {
self.face_attrs.insert_attr(name, attr, self.face_count())
}
pub fn remove_point_attr(&mut self, name: &str) -> Option<Attr3> {
self.point_attrs.remove_attr(name)
}
pub fn remove_face_attr(&mut self, name: &str) -> Option<Attr3> {
self.face_attrs.remove_attr(name)
}
pub fn set_point_attrs(&mut self, attrs: PointAttrSet3) -> Result<()> {
attrs.validate(self.point_count())?;
self.point_attrs = attrs;
Ok(())
}
pub fn set_face_attrs(&mut self, attrs: FaceAttrSet3) -> Result<()> {
attrs.validate(self.face_count())?;
self.face_attrs = attrs;
Ok(())
}
pub fn take_point_attrs(&mut self) -> PointAttrSet3 {
std::mem::take(&mut self.point_attrs)
}
pub fn take_face_attrs(&mut self) -> FaceAttrSet3 {
std::mem::take(&mut self.face_attrs)
}
}
impl Mesh3 {
pub fn new_with_options(
vertices: Vec<Point3>,
triangles: Vec<[u32; 3]>,
is_solid: bool,
merge_duplicates: bool,
delete_degenerate: bool,
) -> Result<Self> {
let mut flags = TriMeshFlags::empty();
if merge_duplicates {
flags |= TriMeshFlags::MERGE_DUPLICATE_VERTICES;
flags |= TriMeshFlags::DELETE_DUPLICATE_TRIANGLES;
}
if delete_degenerate {
flags |= TriMeshFlags::DELETE_BAD_TOPOLOGY_TRIANGLES;
flags |= TriMeshFlags::DELETE_DEGENERATE_TRIANGLES;
}
let shape = TriMesh::with_flags(vertices, triangles, flags)?;
Ok(Self {
shape,
point_attrs: PointAttrSet3::empty(),
face_attrs: FaceAttrSet3::empty(),
is_solid,
})
}
pub fn new(vertices: Vec<Point3>, triangles: Vec<[u32; 3]>, is_solid: bool) -> Self {
let shape = TriMesh::new(vertices, triangles).expect("Failed to create TriMesh");
Self {
shape,
point_attrs: PointAttrSet3::empty(),
face_attrs: FaceAttrSet3::empty(),
is_solid,
}
}
pub fn from_trimesh(shape: TriMesh, is_solid: bool) -> Self {
Self {
shape,
point_attrs: PointAttrSet3::empty(),
face_attrs: FaceAttrSet3::empty(),
is_solid,
}
}
}
impl Mesh3 {
#[cfg(feature = "ply")]
pub fn load_ply(path: &Path, is_solid: bool) -> Result<Self> {
Self::from_data(MeshData3::load_ply(path)?, is_solid)
}
#[cfg(feature = "ply")]
pub fn save_ply(&self, path: &Path, opts: &PlyWriteOpts) -> Result<()> {
write_ply_mesh(path, self, opts)
}
#[cfg(feature = "stl")]
pub fn load_stl(
path: &Path,
is_solid: bool,
merge_duplicates: bool,
delete_degenerate: bool,
) -> Result<Self> {
let (points, faces, _, _) = MeshData3::load_stl(path)?.into_parts();
Self::new_with_options(points, faces, is_solid, merge_duplicates, delete_degenerate)
}
#[cfg(feature = "stl")]
pub fn save_stl(&self, path: &Path, opts: &StlWriteOpts) -> Result<()> {
write_stl_mesh(path, self, opts)
}
pub fn load_g3d(path: &Path, is_solid: bool) -> Result<Self> {
Self::from_data(MeshData3::load_g3d(path)?, is_solid)
}
pub fn load_tcmesh(path: &Path, is_solid: bool) -> Result<Self> {
Self::from_data(MeshData3::load_tcmesh(path)?, is_solid)
}
pub fn save_tcmesh(&self, path: &Path, tol: f64) -> Result<()> {
write_tc_mesh_file(path, self, tol)
}
}
impl Mesh3 {
pub fn from_data(data: MeshData3, is_solid: bool) -> Result<Self> {
let (points, faces, point_attrs, face_attrs) = data.into_parts();
if faces.is_empty() {
return Err(
"Cannot build a Mesh3 from mesh data with no faces. A MeshData3 is allowed \
to hold points without faces, but there is nothing for an acceleration \
structure to be built over."
.into(),
);
}
let shape = TriMesh::new(points, faces)?;
Ok(Self {
shape,
point_attrs,
face_attrs,
is_solid,
})
}
pub fn to_data(&self) -> MeshData3 {
MeshData3::new_with_attrs(
self.points().to_vec(),
self.faces().to_vec(),
self.point_attrs.clone(),
self.face_attrs.clone(),
)
.expect(
"A Mesh3's attributes are validated against its point and face counts on every \
operation which can change them, so rebuilding a MeshData3 from them cannot fail",
)
}
pub fn into_data(self) -> MeshData3 {
self.to_data()
}
}
impl TryFrom<MeshData3> for Mesh3 {
type Error = Box<dyn std::error::Error>;
fn try_from(value: MeshData3) -> Result<Self> {
Mesh3::from_data(value, false)
}
}
impl From<Mesh3> for MeshData3 {
fn from(value: Mesh3) -> Self {
value.into_data()
}
}
impl Mesh3 {
pub fn transform_in_place(&mut self, transform: &Iso3) {
self.shape.transform_vertices(transform);
self.point_attrs.transform_in_place(transform);
self.face_attrs.transform_in_place(transform);
}
pub fn transform_copy(&self, transform: &Iso3) -> Self {
let mut result = self.clone();
result.transform_in_place(transform);
result
}
pub fn scale_copy(&self, scale: f64) -> Result<Self> {
if !scale.is_finite() || scale == 0.0 {
return Err(format!(
"A scale factor must be finite and non-zero, but {scale} was given. Scaling by zero \
would collapse the mesh to a point irrecoverably."
)
.into());
}
let new_shape = self
.shape
.clone()
.scaled(&Vector3::new(scale, scale, scale));
let mut result = Mesh3::from_trimesh(new_shape, self.is_solid);
result.point_attrs = self.point_attrs.clone();
result.face_attrs = self.face_attrs.clone();
result.point_attrs.scale_in_place(scale);
if scale < 0.0 {
result.flip_normals_in_place();
}
Ok(result)
}
pub fn offset_points_copy(&self, offset: f64) -> Result<Self> {
let normals = self.compute_point_normals()?;
let updated = self
.points()
.iter()
.zip(normals.iter())
.map(|(v, n)| v + offset * n.into_inner())
.collect();
Ok(Self::new(updated, self.faces().to_vec(), self.is_solid))
}
pub fn flip_normals_in_place(&mut self) {
self.shape.reverse();
self.point_attrs.flip_in_place();
}
}
impl Mesh3 {
pub fn compute_edges(&self) -> Result<MeshEdges<'_>> {
MeshEdges::new(self)
}
pub fn convex_hull(&self, allow_attribute_loss: bool) -> Result<Self> {
self.check_attribute_loss("a convex hull", allow_attribute_loss)?;
let (vertices, faces) = transformation::convex_hull(self.shape.vertices());
Ok(Self::new(vertices, faces, true))
}
pub fn append_in_place(&mut self, other: &Mesh3) -> Result<()> {
self.point_attrs.check_extend_from(&other.point_attrs)?;
self.face_attrs.check_extend_from(&other.face_attrs)?;
self.point_attrs.apply_extend_from(&other.point_attrs)?;
self.face_attrs.apply_extend_from(&other.face_attrs)?;
self.shape.append(&other.shape);
Ok(())
}
pub fn check_attribute_loss(&self, operation: &str, allow_loss: bool) -> Result<()> {
if allow_loss || !self.has_attrs() {
return Ok(());
}
Err(format!(
"Taking {} would discard the attributes on this mesh ({}), because it produces \
topology with no index mapping back to the original. Pass `allow_attribute_loss` to \
accept this.",
operation,
self.view().attr_labels().join(", ")
)
.into())
}
pub fn view(&self) -> MeshView3<'_> {
MeshView3::from(self)
}
pub fn compute_nav(&self) -> MeshNav<'_> {
MeshNav::new(self)
}
pub fn compute_patch_labels(&self, mask: Option<&IndexMask>) -> Result<PatchLabels> {
let nav = self.compute_nav();
nav.patch_labels(mask)
}
pub fn patch_mask(&self, filter: &PatchFilter) -> Result<IndexMask> {
let nav = self.compute_nav();
nav.patch_mask(filter, None)
}
pub fn remove_small_patches(&self, filter: &PatchFilter) -> Result<Self> {
let mask = self.patch_mask(filter)?;
let kept = mask.count_true();
if kept == 0 {
return Err(
"Every patch was discarded by the filter, which would leave an empty mesh".into(),
);
}
if kept == self.faces().len() {
return Ok(self.clone());
}
self.extract_subset_faces(&mask)
}
pub fn compute_patch_boundary_points(&self) -> Result<Vec<Vec<Point3>>> {
let edges = MeshEdges::new(self)?;
let mut b_loops = Vec::new();
for b_loop in edges.boundary_loops.iter() {
b_loops.push(
b_loop
.iter()
.map(|vi| self.points()[*vi as usize])
.collect(),
);
}
Ok(b_loops)
}
pub fn compute_face_normals(&self) -> Result<Vec<UnitVec3>> {
algorithms::compute_face_normals(self.points(), self.faces())
}
pub fn compute_face_areas(&self) -> Result<Vec<f64>> {
algorithms::compute_face_areas(self.points(), self.faces())
}
pub fn compute_face_centers(&self) -> Result<Vec<Point3>> {
algorithms::compute_face_centers(self.points(), self.faces())
}
pub fn compute_point_normals(&self) -> Result<Vec<UnitVec3>> {
algorithms::compute_point_normals(self.points(), self.faces())
}
}
impl Mesh3 {
pub fn create_box(length: f64, width: f64, height: f64, is_solid: bool) -> Self {
Self::from_primitive(MeshData3::create_box(length, width, height), is_solid)
}
pub fn create_sphere(radius: f64, tol: f64) -> Result<Self> {
Ok(Self::from_primitive(
MeshData3::create_sphere(radius, tol)?,
true,
))
}
pub fn create_cylinder(radius: f64, height: f64, tol: f64) -> Result<Self> {
Ok(Self::from_primitive(
MeshData3::create_cylinder(radius, height, tol)?,
true,
))
}
pub fn create_cone(radius: f64, height: f64, tol: f64) -> Result<Self> {
Ok(Self::from_primitive(
MeshData3::create_cone(radius, height, tol)?,
true,
))
}
pub fn create_circle(radius: f64, tol: f64) -> Result<Self> {
Ok(Self::from_primitive(
MeshData3::create_circle(radius, tol)?,
false,
))
}
pub fn create_capsule(p0: &Point3, p1: &Point3, radius: f64, tol: f64) -> Result<Self> {
Ok(Self::from_primitive(
MeshData3::create_capsule(p0, p1, radius, tol)?,
true,
))
}
pub fn create_cylinder_between(
p0: &Point3,
p1: &Point3,
radius: f64,
tol: f64,
) -> Result<Self> {
Ok(Self::from_primitive(
MeshData3::create_cylinder_between(p0, p1, radius, tol)?,
true,
))
}
pub fn create_rect_beam_between(
p0: &Point3,
p1: &Point3,
width: f64,
height: f64,
up: &Vector3,
) -> Result<Self> {
let data = MeshData3::create_rect_beam_between(p0, p1, width, height, up)?;
Ok(Self::from_primitive(data, true))
}
pub fn stanford_bunny_res4() -> Self {
Self::from_primitive(MeshData3::stanford_bunny_res4(), false)
}
pub fn stanford_bunny_res3() -> Self {
Self::from_primitive(MeshData3::stanford_bunny_res3(), false)
}
pub fn stanford_bunny_res2() -> Self {
Self::from_primitive(MeshData3::stanford_bunny_res2(), false)
}
fn from_primitive(data: MeshData3, is_solid: bool) -> Self {
Self::from_data(data, is_solid)
.expect("A primitive tessellation always has at least one face")
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Plane3;
use crate::tests::stanford_bun_4;
use approx::assert_relative_eq;
use parry3d_f64::query::SplitResult;
use std::f64::consts::FRAC_PI_2;
#[test]
fn a_tcmesh_round_trips_and_is_solid_comes_from_the_caller() -> Result<()> {
let mesh = Mesh3::create_sphere(1.0, 0.025)?;
let tol = 1e-5;
let file = TempFile::new("tcmesh-round-trip", "tcmesh");
mesh.save_tcmesh(file.path(), tol)?;
let recovered = Mesh3::load_tcmesh(file.path(), true)?;
assert_eq!(recovered.point_count(), mesh.point_count());
assert_eq!(recovered.face_count(), mesh.face_count());
assert!(recovered.is_solid());
assert!(!Mesh3::load_tcmesh(file.path(), false)?.is_solid());
Ok(())
}
#[test]
fn saving_a_tcmesh_refuses_a_mesh_carrying_attributes() -> Result<()> {
let mesh = Mesh3::from_data(attributed_data(), false)?;
let file = TempFile::new("tcmesh-refused", "tcmesh");
assert!(mesh.save_tcmesh(file.path(), 1e-5).is_err());
Ok(())
}
#[test]
fn point_normals_match_point_count() -> Result<()> {
let mesh = Mesh3::create_sphere(1.0, 6.0e-3)?;
let normals = mesh.compute_point_normals()?;
assert_eq!(normals.len(), mesh.points().len());
Ok(())
}
#[test]
fn point_normals_report_the_bunny_asset_defect() {
let mesh = stanford_bun_4();
let err = mesh.compute_point_normals().unwrap_err();
assert!(
err.to_string().starts_with("Point 128 has no well-defined"),
"unexpected error: {err}"
);
}
#[test]
fn visual_outline_survives_a_point_with_no_normal() -> Result<()> {
let mesh = stanford_bun_4();
let outline =
mesh.compute_visual_outline(UnitVec3::new_normalize(Vector3::z()), 1.0, None)?;
assert!(!outline.is_empty());
Ok(())
}
#[test]
fn point_normals_agree_with_mesh_data() -> Result<()> {
let mesh = Mesh3::create_sphere(1.0, 6.0e-3)?;
let from_mesh = mesh.compute_point_normals()?;
let from_data = mesh.to_data().compute_point_normals()?;
assert_eq!(from_mesh.len(), from_data.len());
for (a, b) in from_mesh.iter().zip(from_data.iter()) {
assert_relative_eq!(a.into_inner(), b.into_inner(), epsilon = 1.0e-15);
}
Ok(())
}
#[test]
fn point_normals_of_a_box_point_along_the_diagonals() -> Result<()> {
let mesh = Mesh3::create_box(2.0, 2.0, 2.0, true);
let normals = mesh.compute_point_normals()?;
let diagonal = 1.0 / 3.0_f64.sqrt();
for (point, normal) in mesh.points().iter().zip(normals.iter()) {
let expected = Vector3::new(
point.x.signum() * diagonal,
point.y.signum() * diagonal,
point.z.signum() * diagonal,
);
assert_relative_eq!(normal.into_inner(), &expected, epsilon = 1.0e-12);
}
Ok(())
}
#[test]
fn scale_copy_scales_spherical_radius() -> Result<()> {
let radius = 1.0;
let scale = 2.5;
let mesh = Mesh3::create_sphere(radius, radius * 1.0e-3)?;
let scaled = mesh.scale_copy(scale)?;
assert_eq!(mesh.points().len(), scaled.points().len());
for vertex in scaled.points() {
assert_relative_eq!(vertex.coords.norm(), radius * scale, epsilon = 1.0e-12);
}
Ok(())
}
#[test]
fn offset_points_copy_preserves_spherical_radius() -> Result<()> {
let radius = 1.0;
let offset = 0.1;
let mesh = Mesh3::create_sphere(radius, radius * 1.0e-3)?;
let offset_mesh = mesh.offset_points_copy(offset)?;
assert_eq!(mesh.points().len(), offset_mesh.points().len());
for vertex in offset_mesh.points() {
assert_relative_eq!(vertex.coords.norm(), radius + offset, epsilon = 1.0e-5);
}
Ok(())
}
fn attributed_data() -> MeshData3 {
let mut data = MeshData3::new(
vec![
Point3::new(0.0, 0.0, 0.0),
Point3::new(1.0, 0.0, 0.0),
Point3::new(0.0, 1.0, 0.0),
],
vec![[0, 1, 2]],
)
.unwrap();
data.set_point_normals(Some(vec![UnitVec3::new_normalize(Vector3::z()); 3]))
.unwrap();
data.set_point_stdev(Some(vec![0.1, 0.2, 0.3])).unwrap();
data.set_point_flat(Some(vec![
Point2::new(0.0, 0.0),
Point2::new(2.0, 0.0),
Point2::new(0.0, 2.0),
]))
.unwrap();
data.set_face_labels(Some(vec![7])).unwrap();
data.insert_point_attr("confidence", Attr3::Scalar(vec![0.5, 0.6, 0.7]))
.unwrap();
data.insert_point_attr("principal_dir", Attr3::Vector(vec![Vector3::x(); 3]))
.unwrap();
data
}
#[test]
fn round_trip_through_mesh_data_preserves_everything() -> Result<()> {
let before = attributed_data();
let mesh = Mesh3::from_data(before.clone(), true)?;
assert!(mesh.is_solid());
assert_eq!(mesh.point_count(), 3);
assert_eq!(mesh.face_count(), 1);
let after = mesh.to_data();
assert_eq!(after.points(), before.points());
assert_eq!(after.faces(), before.faces());
assert_eq!(after.point_attrs(), before.point_attrs());
assert_eq!(after.face_attrs(), before.face_attrs());
Ok(())
}
#[test]
fn from_data_does_not_renumber_the_buffers() -> Result<()> {
let data = stanford_bun_4().to_data();
let mesh = Mesh3::from_data(data.clone(), false)?;
assert_eq!(mesh.points(), data.points());
assert_eq!(mesh.faces(), data.faces());
Ok(())
}
#[test]
fn from_data_rejects_a_mesh_with_no_faces() -> Result<()> {
let data = MeshData3::new(
vec![Point3::origin(), Point3::new(1.0, 0.0, 0.0)],
Vec::new(),
)?;
assert!(Mesh3::from_data(data, false).is_err());
Ok(())
}
#[test]
fn conversion_traits_agree_with_the_named_methods() -> Result<()> {
let mesh = Mesh3::try_from(attributed_data())?;
assert!(!mesh.is_solid());
let data: MeshData3 = mesh.into();
assert_eq!(data.point_attrs(), attributed_data().point_attrs());
assert_eq!(data.face_attrs(), attributed_data().face_attrs());
Ok(())
}
#[test]
fn transform_rotates_the_direction_attributes() -> Result<()> {
let mut mesh = Mesh3::from_data(attributed_data(), false)?;
mesh.insert_face_attr("face_dir", Attr3::Vector(vec![Vector3::x()]))?;
let iso = Iso3::new(Vector3::new(10.0, 0.0, 0.0), Vector3::z() * FRAC_PI_2);
mesh.transform_in_place(&iso);
assert_relative_eq!(
mesh.points()[1],
Point3::new(10.0, 1.0, 0.0),
epsilon = 1.0e-12
);
assert_relative_eq!(
mesh.point_normals().unwrap()[0].into_inner(),
Vector3::z(),
epsilon = 1.0e-12
);
assert_relative_eq!(
mesh.point_attr("principal_dir")
.unwrap()
.as_vector()
.unwrap()[0],
Vector3::y(),
epsilon = 1.0e-12
);
assert_relative_eq!(
mesh.face_attr("face_dir").unwrap().as_vector().unwrap()[0],
Vector3::y(),
epsilon = 1.0e-12
);
assert_eq!(mesh.point_stdev().unwrap(), &[0.1, 0.2, 0.3]);
Ok(())
}
#[test]
fn a_face_only_attribute_counts_as_having_attrs() -> Result<()> {
let mut mesh = Mesh3::create_box(1.0, 1.0, 1.0, false);
assert!(!mesh.has_attrs());
mesh.set_face_labels(Some(vec![0; mesh.face_count()]))?;
assert!(mesh.has_attrs());
assert!(mesh.point_attrs().is_empty());
assert!(mesh.check_attribute_loss("a test", false).is_err());
Ok(())
}
#[test]
fn scaling_scales_the_standard_deviations_and_flat_coordinates() -> Result<()> {
let mesh = Mesh3::from_data(attributed_data(), false)?;
let scaled = mesh.scale_copy(25.4)?;
assert_relative_eq!(
scaled.point_flat().unwrap()[1].coords,
Point2::new(2.0 * 25.4, 0.0).coords,
epsilon = 1.0e-12
);
for (actual, expected) in scaled
.point_stdev()
.unwrap()
.iter()
.zip([0.1, 0.2, 0.3].iter())
{
assert_relative_eq!(*actual, expected * 25.4, epsilon = 1.0e-12);
}
assert_relative_eq!(
scaled.point_normals().unwrap()[0].into_inner(),
Vector3::z(),
epsilon = 1.0e-12
);
Ok(())
}
#[test]
fn flipping_negates_the_stored_normals() -> Result<()> {
let mut mesh = Mesh3::from_data(attributed_data(), false)?;
mesh.flip_normals_in_place();
assert_relative_eq!(
mesh.point_normals().unwrap()[0].into_inner(),
-Vector3::z(),
epsilon = 1.0e-12
);
Ok(())
}
#[test]
fn append_unions_the_attributes() -> Result<()> {
let mut mesh = Mesh3::from_data(attributed_data(), false)?;
let other = Mesh3::from_data(attributed_data(), false)?;
mesh.append_in_place(&other)?;
assert_eq!(mesh.point_count(), 6);
assert_eq!(mesh.face_count(), 2);
assert_eq!(mesh.faces()[1], [3, 4, 5]);
assert_eq!(mesh.point_stdev().unwrap(), &[0.1, 0.2, 0.3, 0.1, 0.2, 0.3]);
assert_eq!(mesh.face_labels().unwrap(), &[7, 7]);
assert_eq!(mesh.point_attr("confidence").unwrap().len(), 6);
let flat = mesh.point_flat().unwrap();
assert_eq!(flat.len(), 6);
assert_eq!(flat[4], Point2::new(2.0, 0.0));
mesh.point_attrs().validate(mesh.point_count())?;
mesh.face_attrs().validate(mesh.face_count())?;
Ok(())
}
#[test]
fn append_rejects_a_mismatch_without_modifying_the_target() -> Result<()> {
let mut mesh = Mesh3::from_data(attributed_data(), false)?;
let mut bare_data = attributed_data();
bare_data.set_point_stdev(None)?;
let other = Mesh3::from_data(bare_data, false)?;
assert!(mesh.append_in_place(&other).is_err());
assert_eq!(mesh.point_count(), 3);
assert_eq!(mesh.face_count(), 1);
assert_eq!(mesh.point_stdev().unwrap(), &[0.1, 0.2, 0.3]);
Ok(())
}
#[test]
fn a_face_domain_rejection_leaves_the_point_domain_untouched() -> Result<()> {
let mut mesh = Mesh3::from_data(attributed_data(), false)?;
let mut unlabeled = attributed_data();
unlabeled.set_face_labels(None)?;
let other = Mesh3::from_data(unlabeled, false)?;
assert!(mesh.append_in_place(&other).is_err());
assert_eq!(mesh.point_count(), 3);
assert_eq!(mesh.face_count(), 1);
assert_eq!(mesh.point_stdev().unwrap(), &[0.1, 0.2, 0.3]);
assert_eq!(mesh.point_attr("confidence").unwrap().len(), 3);
assert_eq!(mesh.face_labels().unwrap(), &[7]);
Ok(())
}
#[test]
fn appending_two_bare_meshes_works() -> Result<()> {
let mut mesh = Mesh3::create_box(1.0, 1.0, 1.0, false);
let other = Mesh3::create_box(1.0, 1.0, 1.0, false);
let n = mesh.point_count();
mesh.append_in_place(&other)?;
assert_eq!(mesh.point_count(), n * 2);
Ok(())
}
fn labeled_box() -> Result<Mesh3> {
let mut mesh = Mesh3::create_box(1.0, 1.0, 1.0, false);
let stdev = (0..mesh.point_count()).map(|i| i as f64).collect();
let flat = mesh
.points()
.iter()
.map(|p| Point2::new(p.x, p.y))
.collect();
let labels = (0..mesh.face_count() as u32).collect();
mesh.set_point_stdev(Some(stdev))?;
mesh.set_point_flat(Some(flat))?;
mesh.set_face_labels(Some(labels))?;
Ok(mesh)
}
#[test]
fn extract_subset_faces_carries_the_attributes() -> Result<()> {
let mesh = labeled_box()?;
let mask = IndexMask::try_from_indices(&[0, 1], mesh.face_count())?;
let sub = mesh.extract_subset_faces(&mask)?;
assert_eq!(sub.face_count(), 2);
assert_eq!(sub.face_labels().unwrap(), &[0, 1]);
assert_eq!(sub.point_stdev().unwrap().len(), sub.point_count());
sub.point_attrs().validate(sub.point_count())?;
sub.face_attrs().validate(sub.face_count())?;
let kept: Vec<f64> = mesh
.compute_unique_point_mask(&mask)?
.iter_true()
.map(|i| mesh.point_stdev().unwrap()[i])
.collect();
assert_eq!(sub.point_stdev().unwrap(), kept.as_slice());
let kept_flat: Vec<Point2> = mesh
.compute_unique_point_mask(&mask)?
.iter_true()
.map(|i| mesh.point_flat().unwrap()[i])
.collect();
assert_eq!(sub.point_flat().unwrap(), kept_flat.as_slice());
Ok(())
}
#[test]
fn extract_subset_faces_from_indices_carries_the_attributes() -> Result<()> {
let mesh = labeled_box()?;
let sub = mesh.extract_subset_faces_from_indices(&[2, 3])?;
assert_eq!(sub.face_count(), 2);
assert_eq!(sub.face_labels().unwrap(), &[2, 3]);
sub.point_attrs().validate(sub.point_count())?;
sub.face_attrs().validate(sub.face_count())?;
Ok(())
}
#[test]
fn extract_subset_faces_from_indices_normalizes_the_selection() -> Result<()> {
let mesh = labeled_box()?;
let ordered = mesh.extract_subset_faces_from_indices(&[1, 3])?;
let reversed = mesh.extract_subset_faces_from_indices(&[3, 1])?;
let repeated = mesh.extract_subset_faces_from_indices(&[3, 1, 3])?;
assert_eq!(ordered.faces(), reversed.faces());
assert_eq!(ordered.faces(), repeated.faces());
assert_eq!(ordered.face_labels().unwrap(), &[1, 3]);
assert_eq!(repeated.face_count(), 2);
Ok(())
}
#[test]
fn extract_subset_faces_from_indices_rejects_an_out_of_range_index() -> Result<()> {
let mesh = labeled_box()?;
assert!(
mesh.extract_subset_faces_from_indices(&[0, mesh.face_count()])
.is_err()
);
Ok(())
}
#[test]
fn split_refuses_an_attributed_mesh_unless_the_loss_is_accepted() -> Result<()> {
let mesh = labeled_box()?;
let plane = Plane3::yz();
assert!(mesh.split(&plane, false).is_err());
let message = match mesh.split(&plane, false) {
Err(e) => e.to_string(),
Ok(_) => panic!("expected the split to be refused"),
};
assert!(message.contains("point_stdev"), "{message}");
assert!(message.contains("face_labels"), "{message}");
match mesh.split(&plane, true)? {
SplitResult::Pair(a, b) => {
assert!(!a.has_attrs());
assert!(!b.has_attrs());
}
_ => panic!("expected the plane to cut the box in two"),
}
let bare = Mesh3::create_box(1.0, 1.0, 1.0, false);
assert!(bare.split(&plane, false).is_ok());
Ok(())
}
#[test]
fn convex_hull_refuses_an_attributed_mesh_unless_the_loss_is_accepted() -> Result<()> {
let mesh = labeled_box()?;
assert!(mesh.convex_hull(false).is_err());
assert!(!mesh.convex_hull(true)?.has_attrs());
let bare = Mesh3::create_box(1.0, 1.0, 1.0, false);
assert!(bare.convex_hull(false).is_ok());
Ok(())
}
#[test]
fn a_negative_scale_reverses_the_winding_like_mesh_data_does() -> Result<()> {
let mesh = Mesh3::from_data(attributed_data(), false)?;
let through_mesh = mesh.scale_copy(-1.0)?;
let through_data = mesh.to_data().scale_copy(-1.0)?;
assert_eq!(through_mesh.faces(), through_data.faces());
assert_eq!(
through_mesh.point_normals().unwrap(),
through_data.point_normals().unwrap()
);
assert_eq!(through_mesh.face_attrs(), through_data.face_attrs());
assert_eq!(through_mesh.face_labels().unwrap(), &[7]);
assert_eq!(
through_mesh.point_attr("confidence"),
through_data.point_attr("confidence")
);
let p = through_mesh.points();
let f = through_mesh.faces()[0];
let normal = (p[f[1] as usize] - p[f[0] as usize])
.cross(&(p[f[2] as usize] - p[f[0] as usize]))
.normalize();
assert_relative_eq!(normal, -Vector3::z(), epsilon = 1.0e-12);
Ok(())
}
#[test]
fn scale_copy_rejects_zero_and_non_finite_factors() -> Result<()> {
let mesh = Mesh3::from_data(attributed_data(), false)?;
assert!(mesh.scale_copy(0.0).is_err());
assert!(mesh.scale_copy(f64::NAN).is_err());
assert!(mesh.scale_copy(f64::INFINITY).is_err());
Ok(())
}
struct TempFile {
path: std::path::PathBuf,
}
impl TempFile {
fn new(name: &str, ext: &str) -> Self {
let path = std::env::temp_dir().join(format!(
"engeom-mesh3-{}-{}.{}",
name,
std::process::id(),
ext
));
Self { path }
}
fn path(&self) -> &Path {
&self.path
}
}
impl Drop for TempFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.path);
}
}
#[cfg(feature = "ply")]
#[test]
fn a_ply_round_trip_keeps_the_attributes_and_the_solid_flag() -> Result<()> {
let before = Mesh3::from_data(attributed_data(), false)?;
let file = TempFile::new("round-trip", "ply");
before.save_ply(file.path(), &PlyWriteOpts::default())?;
let after = Mesh3::load_ply(file.path(), true)?;
assert!(after.is_solid());
assert_eq!(after.points(), before.points());
assert_eq!(after.faces(), before.faces());
assert_eq!(after.point_stdev(), before.point_stdev());
assert_eq!(after.face_labels(), before.face_labels());
assert_eq!(
after.point_attr("confidence"),
before.point_attr("confidence")
);
Ok(())
}
#[cfg(feature = "ply")]
#[test]
fn loading_a_point_cloud_ply_as_a_mesh_is_refused() -> Result<()> {
use crate::geom3::PointCloud3;
let cloud = PointCloud3::new(vec![Point3::origin(), Point3::new(1.0, 0.0, 0.0)]);
let file = TempFile::new("is-a-cloud", "ply");
cloud.save_ply(file.path(), &PlyWriteOpts::default())?;
assert!(Mesh3::load_ply(file.path(), false).is_err());
Ok(())
}
#[cfg(feature = "stl")]
#[test]
fn an_stl_round_trip_carries_the_geometry() -> Result<()> {
let before = Mesh3::create_box(1.0, 2.0, 3.0, false);
let file = TempFile::new("round-trip", "stl");
before.save_stl(file.path(), &StlWriteOpts::default())?;
let after = Mesh3::load_stl(file.path(), false, true, false)?;
assert_eq!(after.face_count(), before.face_count());
assert_relative_eq!(after.aabb().maxs, before.aabb().maxs, epsilon = 1.0e-6);
Ok(())
}
#[cfg(feature = "stl")]
#[test]
fn saving_stl_refuses_to_drop_attributes_silently() -> Result<()> {
let mesh = Mesh3::from_data(attributed_data(), false)?;
let file = TempFile::new("lossy", "stl");
assert!(
mesh.save_stl(file.path(), &StlWriteOpts::default())
.is_err()
);
let opts = StlWriteOpts {
allow_attribute_loss: true,
..Default::default()
};
mesh.save_stl(file.path(), &opts)?;
Ok(())
}
#[test]
fn attribute_setters_supply_the_counts() -> Result<()> {
let mut mesh = Mesh3::create_box(1.0, 1.0, 1.0, false);
let n_points = mesh.point_count();
let n_faces = mesh.face_count();
mesh.set_point_stdev(Some(vec![0.5; n_points]))?;
mesh.set_face_labels(Some(vec![3; n_faces]))?;
assert_eq!(mesh.point_stdev().unwrap().len(), n_points);
assert_eq!(mesh.face_labels().unwrap().len(), n_faces);
assert!(mesh.set_point_stdev(Some(vec![0.5; n_points + 1])).is_err());
assert!(mesh.set_face_labels(Some(vec![3; n_faces - 1])).is_err());
assert_eq!(mesh.point_stdev().unwrap().len(), n_points);
Ok(())
}
#[test]
fn set_attrs_validates_against_the_current_counts() -> Result<()> {
let mut mesh = Mesh3::from_data(attributed_data(), false)?;
let mut bad = FaceAttrSet3::empty();
bad.set_labels(Some(vec![1, 2, 3]), 3)?;
assert!(mesh.set_face_attrs(bad).is_err());
let mut bad = PointAttrSet3::empty();
bad.set_stdev(Some(vec![0.1]), 1)?;
assert!(mesh.set_point_attrs(bad).is_err());
assert_eq!(mesh.face_labels().unwrap(), &[7]);
assert_eq!(mesh.point_stdev().unwrap(), &[0.1, 0.2, 0.3]);
let taken = mesh.take_face_attrs();
assert_eq!(taken.labels().unwrap(), &[7]);
assert!(mesh.face_labels().is_none());
assert!(mesh.point_stdev().is_some());
let taken = mesh.take_point_attrs();
assert_eq!(taken.stdev().unwrap(), &[0.1, 0.2, 0.3]);
assert!(!mesh.has_attrs());
Ok(())
}
}