Skip to main content

lib_jsl_geometry/dim_2/
mesh2d.rs

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