mod editing;
mod filtering;
mod operations;
mod primitives;
mod subsets;
pub use crate::geom3::attributes3::Attr3;
use crate::geom3::Mesh3;
use crate::geom3::attributes3::{FaceAttrSet3, PointAttrSet3};
use crate::geom3::mesh::MeshView3;
use crate::geom3::mesh::algorithms;
use crate::geom3::mesh::algorithms::{
OffsetOpts, compute_face_offset_points, compute_normal_displaced_points,
};
use crate::io::{load_g3d_mesh_data, read_tc_mesh_file, write_tc_mesh_file};
use crate::{Point2, Point3, Result, UnitVec3};
use std::fmt;
use std::path::Path;
#[cfg(feature = "ply")]
use crate::io::{PlyWriteOpts, load_ply_mesh_data, write_ply_mesh};
#[cfg(feature = "stl")]
use crate::io::{StlWriteOpts, load_stl_mesh_data, write_stl_mesh};
#[derive(Clone)]
pub struct MeshData3 {
points: Vec<Point3>,
faces: Vec<[u32; 3]>,
point_attrs: PointAttrSet3,
face_attrs: FaceAttrSet3,
}
impl MeshData3 {
pub fn new(points: Vec<Point3>, faces: Vec<[u32; 3]>) -> Result<Self> {
Self::new_with_attrs(points, faces, PointAttrSet3::empty(), FaceAttrSet3::empty())
}
pub fn new_with_attrs(
points: Vec<Point3>,
faces: Vec<[u32; 3]>,
point_attrs: PointAttrSet3,
face_attrs: FaceAttrSet3,
) -> Result<Self> {
check_face_indices(&faces, points.len())?;
point_attrs.validate(points.len())?;
face_attrs.validate(faces.len())?;
Ok(Self {
points,
faces,
point_attrs,
face_attrs,
})
}
pub fn empty() -> Self {
Self {
points: Vec::new(),
faces: Vec::new(),
point_attrs: PointAttrSet3::empty(),
face_attrs: FaceAttrSet3::empty(),
}
}
#[cfg(feature = "ply")]
pub fn load_ply(path: &Path) -> Result<Self> {
load_ply_mesh_data(path)
}
#[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) -> Result<Self> {
load_stl_mesh_data(path)
}
#[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) -> Result<Self> {
load_g3d_mesh_data(path)
}
pub fn load_tcmesh(path: &Path) -> Result<Self> {
read_tc_mesh_file(path)
}
pub fn save_tcmesh(&self, path: &Path, tol: f64) -> Result<()> {
write_tc_mesh_file(path, self, tol)
}
}
impl MeshData3 {
pub fn check_attribute_loss(&self, format: &str, allow_loss: bool) -> Result<()> {
MeshView3::from(self).check_attribute_loss(format, allow_loss)
}
pub fn view(&self) -> MeshView3<'_> {
MeshView3::from(self)
}
}
impl MeshData3 {
pub fn points(&self) -> &[Point3] {
&self.points
}
pub fn faces(&self) -> &[[u32; 3]] {
&self.faces
}
pub fn point_count(&self) -> usize {
self.points.len()
}
pub fn face_count(&self) -> usize {
self.faces.len()
}
pub fn is_empty(&self) -> bool {
self.points.is_empty() && self.faces.is_empty()
}
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()
}
}
impl MeshData3 {
pub fn compute_point_normals(&self) -> Result<Vec<UnitVec3>> {
algorithms::compute_point_normals(&self.points, &self.faces)
}
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 offset_faces_in_place(&mut self, distance: f64, opts: &OffsetOpts) -> Result<()> {
self.points = compute_face_offset_points(&self.points, &self.faces, distance, opts)?;
Ok(())
}
pub fn offset_faces_copy(&self, distance: f64, opts: &OffsetOpts) -> Result<Self> {
let mut clone = self.clone();
clone.offset_faces_in_place(distance, opts)?;
Ok(clone)
}
pub fn offset_points_copy(&self, distance: f64) -> Result<Self> {
let mut clone = self.clone();
clone.offset_points_in_place(distance)?;
Ok(clone)
}
pub fn offset_points_in_place(&mut self, distance: f64) -> Result<()> {
if let Some(normals) = self.point_attrs.normals() {
self.points = compute_normal_displaced_points(&self.points, normals, distance)?;
} else {
let local_normals = self.compute_point_normals()?;
self.points = compute_normal_displaced_points(&self.points, &local_normals, distance)?;
}
Ok(())
}
}
impl MeshData3 {
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 MeshData3 {
pub fn set_point_normals(&mut self, values: Option<Vec<UnitVec3>>) -> Result<()> {
self.point_attrs.set_normals(values, self.points.len())
}
pub fn set_point_colors(&mut self, values: Option<Vec<[u8; 3]>>) -> Result<()> {
self.point_attrs.set_colors(values, self.points.len())
}
pub fn set_point_stdev(&mut self, values: Option<Vec<f64>>) -> Result<()> {
self.point_attrs.set_stdev(values, self.points.len())
}
pub fn set_point_flat(&mut self, values: Option<Vec<Point2>>) -> Result<()> {
self.point_attrs.set_flat(values, self.points.len())
}
pub fn set_face_colors(&mut self, values: Option<Vec<[u8; 3]>>) -> Result<()> {
self.face_attrs.set_colors(values, self.faces.len())
}
pub fn set_face_labels(&mut self, values: Option<Vec<u32>>) -> Result<()> {
self.face_attrs.set_labels(values, self.faces.len())
}
pub fn insert_point_attr(&mut self, name: &str, attr: Attr3) -> Result<()> {
self.point_attrs.insert_attr(name, attr, self.points.len())
}
pub fn insert_face_attr(&mut self, name: &str, attr: Attr3) -> Result<()> {
self.face_attrs.insert_attr(name, attr, self.faces.len())
}
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.points.len())?;
self.point_attrs = attrs;
Ok(())
}
pub fn set_face_attrs(&mut self, attrs: FaceAttrSet3) -> Result<()> {
attrs.validate(self.faces.len())?;
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)
}
pub fn into_parts(self) -> (Vec<Point3>, Vec<[u32; 3]>, PointAttrSet3, FaceAttrSet3) {
(self.points, self.faces, self.point_attrs, self.face_attrs)
}
pub fn into_mesh(self, is_solid: bool) -> Result<Mesh3> {
Mesh3::from_data(self, is_solid)
}
}
impl fmt::Debug for MeshData3 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MeshData3")
.field("points", &self.points.len())
.field("faces", &self.faces.len())
.field("point_attrs", &self.point_attrs)
.field("face_attrs", &self.face_attrs)
.finish()
}
}
pub(crate) fn check_face_indices(faces: &[[u32; 3]], n_points: usize) -> Result<()> {
for (i, face) in faces.iter().enumerate() {
for index in face {
if *index as usize >= n_points {
return Err(format!(
"Face {i} refers to point {index}, but the mesh has only {n_points} points"
)
.into());
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Vector3;
use approx::assert_relative_eq;
fn unit_square() -> (Vec<Point3>, Vec<[u32; 3]>) {
let points = vec![
Point3::new(0.0, 0.0, 0.0),
Point3::new(1.0, 0.0, 0.0),
Point3::new(1.0, 1.0, 0.0),
Point3::new(0.0, 1.0, 0.0),
];
let faces = vec![[0, 1, 2], [0, 2, 3]];
(points, faces)
}
fn square_mesh() -> MeshData3 {
let (points, faces) = unit_square();
MeshData3::new(points, faces).unwrap()
}
#[test]
fn a_tcmesh_round_trips_through_the_container_methods() -> Result<()> {
let mesh = square_mesh();
let tol = 1e-5;
let path = std::env::temp_dir().join("engeom_mesh_data_tcmesh_round_trip.tcmesh");
mesh.save_tcmesh(&path, tol)?;
let recovered = MeshData3::load_tcmesh(&path)?;
assert_eq!(recovered.point_count(), mesh.point_count());
assert_eq!(recovered.face_count(), mesh.face_count());
for point in recovered.points() {
assert!(
mesh.points().iter().any(|p| (p - point).norm() <= tol),
"{point:?} is not within {tol} of any original point"
);
}
let _ = std::fs::remove_file(&path);
Ok(())
}
#[test]
fn saving_a_tcmesh_refuses_a_mesh_carrying_attributes() -> Result<()> {
let mut mesh = square_mesh();
mesh.set_point_stdev(Some(vec![0.0, 0.1, 0.2, 0.3]))?;
let path = std::env::temp_dir().join("engeom_mesh_data_tcmesh_refused.tcmesh");
let err = mesh.save_tcmesh(&path, 1e-5).unwrap_err().to_string();
assert!(
err.contains("stdev"),
"the error should name what would be lost: {err}"
);
Ok(())
}
#[test]
fn new_accepts_a_valid_mesh() {
let mesh = square_mesh();
assert_eq!(mesh.point_count(), 4);
assert_eq!(mesh.face_count(), 2);
assert!(!mesh.is_empty());
assert!(!mesh.has_attrs());
}
#[test]
fn new_rejects_an_out_of_range_face_index() {
let (points, _) = unit_square();
assert!(MeshData3::new(points, vec![[0, 1, 4]]).is_err());
}
#[test]
fn new_rejects_any_face_against_an_empty_point_buffer() {
assert!(MeshData3::new(Vec::new(), vec![[0, 0, 0]]).is_err());
}
#[test]
fn an_empty_mesh_is_legal() -> Result<()> {
let mesh = MeshData3::new(Vec::new(), Vec::new())?;
assert!(mesh.is_empty());
assert_eq!(mesh.point_count(), 0);
assert_eq!(mesh.face_count(), 0);
assert!(MeshData3::empty().is_empty());
Ok(())
}
#[test]
fn points_without_faces_are_legal() -> Result<()> {
let (points, _) = unit_square();
let mesh = MeshData3::new(points, Vec::new())?;
assert_eq!(mesh.point_count(), 4);
assert_eq!(mesh.face_count(), 0);
assert!(!mesh.is_empty());
Ok(())
}
#[test]
fn new_with_attrs_rejects_a_mismatched_attribute() {
let (points, faces) = unit_square();
let mut attrs = PointAttrSet3::empty();
attrs.set_colors(Some(vec![[0, 0, 0]]), 1).unwrap();
assert!(MeshData3::new_with_attrs(points, faces, attrs, FaceAttrSet3::empty()).is_err());
let (points, faces) = unit_square();
let mut attrs = FaceAttrSet3::empty();
attrs.set_labels(Some(vec![1, 2, 3]), 3).unwrap();
assert!(MeshData3::new_with_attrs(points, faces, PointAttrSet3::empty(), attrs).is_err());
}
#[test]
fn attribute_setters_supply_the_counts() -> Result<()> {
let mut mesh = square_mesh();
mesh.set_point_stdev(Some(vec![0.1, 0.2, 0.3, 0.4]))?;
mesh.set_face_labels(Some(vec![7, 8]))?;
mesh.insert_point_attr("confidence", Attr3::Scalar(vec![0.5; 4]))?;
mesh.insert_face_attr("material_index", Attr3::Label(vec![1, 2]))?;
assert_eq!(mesh.point_stdev().unwrap(), &[0.1, 0.2, 0.3, 0.4]);
assert_eq!(mesh.face_labels().unwrap(), &[7, 8]);
assert_eq!(mesh.point_attr("confidence").unwrap().len(), 4);
assert_eq!(mesh.face_attr("material_index").unwrap().len(), 2);
assert!(mesh.set_point_stdev(Some(vec![0.1, 0.2])).is_err());
assert!(mesh.set_face_labels(Some(vec![1, 2, 3])).is_err());
Ok(())
}
#[test]
fn set_attrs_validates_against_the_current_counts() -> Result<()> {
let mut mesh = square_mesh();
let mut good = PointAttrSet3::empty();
good.set_normals(
Some(vec![UnitVec3::new_normalize(Vector3::z()); 4]),
mesh.point_count(),
)?;
mesh.set_point_attrs(good)?;
assert!(mesh.point_normals().is_some());
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!(mesh.point_normals().is_some());
Ok(())
}
#[test]
fn a_face_only_attribute_counts_as_having_attrs() -> Result<()> {
let mut mesh = square_mesh();
assert!(!mesh.has_attrs());
mesh.set_face_labels(Some(vec![7, 8]))?;
assert!(mesh.has_attrs());
assert!(mesh.point_attrs().is_empty());
assert!(mesh.check_attribute_loss("a test", false).is_err());
Ok(())
}
#[test]
fn take_attrs_leaves_the_mesh_bare() -> Result<()> {
let mut mesh = square_mesh();
mesh.set_face_labels(Some(vec![7, 8]))?;
let taken = mesh.take_face_attrs();
assert_eq!(taken.labels().unwrap(), &[7, 8]);
assert!(!mesh.has_attrs());
assert!(mesh.face_labels().is_none());
Ok(())
}
#[test]
fn debug_summarizes_instead_of_dumping_buffers() {
let text = format!("{:?}", square_mesh());
assert!(text.contains("points: 4"), "{text}");
assert!(text.contains("faces: 2"), "{text}");
}
#[test]
fn offsetting_moves_the_points_and_keeps_the_attributes() -> Result<()> {
let mut mesh = square_mesh();
mesh.set_point_stdev(Some(vec![0.1, 0.2, 0.3, 0.4]))?;
mesh.set_face_labels(Some(vec![7, 9]))?;
let d = 2.0;
let moved = mesh.offset_faces_copy(d, &OffsetOpts::default())?;
for (before, after) in mesh.points().iter().zip(moved.points().iter()) {
assert_relative_eq!(
after.coords,
before.coords + Vector3::z() * d,
epsilon = 1.0e-12
);
}
assert_eq!(moved.faces(), mesh.faces());
assert_eq!(moved.point_stdev(), Some([0.1, 0.2, 0.3, 0.4].as_slice()));
assert_eq!(moved.face_labels(), Some([7, 9].as_slice()));
Ok(())
}
#[test]
fn the_consuming_conversions_round_trip() -> Result<()> {
let mut data = square_mesh();
let computed = data.compute_point_normals()?;
data.set_point_normals(Some(computed))?;
let points = data.points().to_vec();
let faces = data.faces().to_vec();
let normals = data.point_normals().map(|n| n.to_vec());
assert!(normals.is_some(), "the fixture must carry an attribute");
let mesh = data.into_mesh(true)?;
assert!(mesh.is_solid());
let back = mesh.into_data();
assert_eq!(back.points(), points.as_slice());
assert_eq!(back.faces(), faces.as_slice());
assert_eq!(back.point_normals().map(|n| n.to_vec()), normals);
Ok(())
}
#[test]
fn a_mesh_without_faces_cannot_become_an_accelerated_mesh() {
let data = MeshData3::new(vec![Point3::origin()], vec![]).unwrap();
assert!(data.into_mesh(false).is_err());
}
#[test]
fn a_failed_offset_leaves_the_mesh_untouched() {
let (mut points, faces) = unit_square();
points.push(Point3::new(9.0, 9.0, 9.0));
let mut mesh = MeshData3::new(points, faces).unwrap();
let before = mesh.points().to_vec();
assert!(
mesh.offset_faces_in_place(1.0, &OffsetOpts::default())
.is_err()
);
assert_eq!(mesh.points(), before.as_slice());
}
}