Skip to main content

lib_jsl_geometry/dim_3/
surface_mesh3d.rs

1//! Concrete surface mesh type built from three-dimensional polygon faces.
2//!
3//! [`SurfaceMesh3D`] is the current top-level three-dimensional concrete aggregate primitive for
4//! polygonal surface meshes. It does not represent a volumetric cell complex. The type stores face
5//! ids into a shared face table and resolves those faces against the same point table used by the
6//! rest of the geometry graph.
7
8use lib_jsl_core::ErrorsJSL;
9use crate::common::{
10    FaceId, GeometricPrimitive, GeometricPrimitive3D, GeometryMeasure, HasEdges, HasFaces,
11    HasVertices, PointId,
12};
13use crate::one_d::IsLine;
14use crate::tables::SharedGeometryTable;
15use crate::three_d::{IsMesh, Line3D, CoordinateVector3D, PolygonFace3D, UnitVector3D};
16use crate::two_d::IsPolygon;
17use std::collections::HashSet;
18use std::fmt::{self, Display, Formatter};
19use std::hash::{Hash, Hasher};
20
21/// Concrete 3D surface mesh implementation referencing polygon faces through ids.
22#[derive(Debug, Clone)]
23#[cfg_attr(feature = "serde", derive(serde::Serialize))]
24pub struct SurfaceMesh3D {
25    face_ids: Vec<FaceId>,
26    #[cfg_attr(feature = "serde", serde(skip_serializing))]
27    vertex_table: SharedGeometryTable<PointId, CoordinateVector3D>,
28    #[cfg_attr(feature = "serde", serde(skip_serializing))]
29    face_table: SharedGeometryTable<FaceId, PolygonFace3D>,
30}
31
32impl PartialEq for SurfaceMesh3D {
33    fn eq(&self, other: &Self) -> bool {
34        self.face_ids == other.face_ids
35    }
36}
37
38impl Eq for SurfaceMesh3D {}
39
40impl Hash for SurfaceMesh3D {
41    fn hash<H: Hasher>(&self, state: &mut H) {
42        self.face_ids.hash(state);
43    }
44}
45
46impl SurfaceMesh3D {
47    /// Creates a surface mesh from ordered face ids and shared point and face tables.
48    ///
49    /// Faces are resolved lazily through `face_table`, and each face in turn resolves its vertices
50    /// through `vertex_table`. This concrete type assumes the faces describe the boundary surface.
51    pub fn new(
52        face_ids: Vec<FaceId>,
53        vertex_table: SharedGeometryTable<PointId, CoordinateVector3D>,
54        face_table: SharedGeometryTable<FaceId, PolygonFace3D>,
55    ) -> Self {
56        Self {
57            face_ids,
58            vertex_table,
59            face_table,
60        }
61    }
62
63    fn resolved_edges(&self) -> Vec<Line3D> {
64        let mut seen = HashSet::new();
65        let mut edges = Vec::new();
66        for face_id in &self.face_ids {
67            if let Some(face) = self.get_face(face_id) {
68                for edge_index in 0..face.edge_count() {
69                    if let Some(edge) = face.edge(edge_index) {
70                        let head = edge.head_id().0.min(edge.tail_id().0);
71                        let tail = edge.head_id().0.max(edge.tail_id().0);
72                        if seen.insert((head, tail)) {
73                            edges.push(edge);
74                        }
75                    }
76                }
77            }
78        }
79        edges
80    }
81}
82
83impl Display for SurfaceMesh3D {
84    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
85        write!(f, "SurfaceMesh3D(faces={:?})", self.face_ids)
86    }
87}
88
89impl GeometricPrimitive for SurfaceMesh3D {}
90impl GeometricPrimitive3D for SurfaceMesh3D {}
91
92impl<'a> HasVertices<'a> for SurfaceMesh3D {
93    type Vertex = CoordinateVector3D;
94    type VertexTable = SharedGeometryTable<PointId, CoordinateVector3D>;
95
96    fn vertex_table(&self) -> &Self::VertexTable {
97        &self.vertex_table
98    }
99
100    fn vertex_table_mut(&mut self) -> &mut Self::VertexTable {
101        &mut self.vertex_table
102    }
103
104    fn set_vertex_table(&mut self, table: &'a mut Self::VertexTable) {
105        self.vertex_table = table.clone();
106    }
107}
108
109impl<'a> HasFaces<'a> for SurfaceMesh3D {
110    type Point = CoordinateVector3D;
111    type Normal = UnitVector3D;
112    type Face = PolygonFace3D;
113    type FaceTable = SharedGeometryTable<FaceId, PolygonFace3D>;
114
115    fn face_table(&self) -> &Self::FaceTable {
116        &self.face_table
117    }
118
119    fn face_table_mut(&mut self) -> &mut Self::FaceTable {
120        &mut self.face_table
121    }
122
123    fn set_face_table(&mut self, table: &'a mut Self::FaceTable) {
124        self.face_table = table.clone();
125    }
126}
127
128impl HasEdges for SurfaceMesh3D {
129    type Edge = Line3D;
130
131    fn edge_count(&self) -> usize {
132        self.resolved_edges().len()
133    }
134
135    fn edge(&self, index: usize) -> Option<Self::Edge> {
136        self.resolved_edges().into_iter().nth(index)
137    }
138}
139
140impl<'a> IsMesh<'a, CoordinateVector3D, UnitVector3D> for SurfaceMesh3D {
141    fn face_ids(&self) -> Box<dyn Iterator<Item = FaceId> + '_> {
142        Box::new(self.face_ids.iter().copied())
143    }
144
145    fn set_face_id(&mut self, index: usize, face_id: FaceId) -> Result<(), ErrorsJSL> {
146        if let Some(slot) = self.face_ids.get_mut(index) {
147            *slot = face_id;
148            Ok(())
149        } else {
150            Err(ErrorsJSL::Message(format!("face index {} is out of bounds", index)))
151        }
152    }
153
154    fn surface_area(&self) -> GeometryMeasure {
155        self.face_ids
156            .iter()
157            .filter_map(|face_id| self.get_face(face_id))
158            .map(|face| face.area())
159            .sum()
160    }
161}