Skip to main content

lib_jsl_geometry/dim_3/
tetrahedron3d.rs

1//! Concrete tetrahedron type built from three-dimensional points.
2//!
3//! [`Tetrahedron3D`] represents a simple volumetric primitive defined by four point ids into a
4//! shared point table. Faces and edges are derived on demand from those vertices.
5
6use lib_jsl_core::ErrorsJSL;
7use crate::common::{
8    Canonicalize, GeometricPrimitive, GeometricPrimitive3D, GeometryMeasure, HasCentroid,
9    HasEdges, HasMeasure, HasVertices, IsPlane, IsValid, PointId, Repair,
10};
11use crate::one_d::IsLine;
12use crate::tables::SharedGeometryTable;
13use crate::three_d::transform_support::{reflect_point_across_plane, rotate_point_around_axis};
14use crate::three_d::{
15    FreeVector3D, IsTetrahedron, Line3D, CoordinateVector3D, Triangle3D, UnitVector3D,
16};
17use crate::transformation_traits::{CanMirror, CanRotate, CanShear, CanTranslate};
18use crate::two_d::IsPolygon;
19use std::collections::HashSet;
20use std::fmt::{self, Display, Formatter};
21use std::hash::{Hash, Hasher};
22
23/// Concrete 3D tetrahedron implementation backed by four point ids.
24#[derive(Debug, Clone)]
25#[cfg_attr(feature = "serde", derive(serde::Serialize))]
26pub struct Tetrahedron3D {
27    a_id: PointId,
28    b_id: PointId,
29    c_id: PointId,
30    d_id: PointId,
31    #[cfg_attr(feature = "serde", serde(skip_serializing))]
32    vertex_table: SharedGeometryTable<PointId, CoordinateVector3D>,
33}
34
35impl PartialEq for Tetrahedron3D {
36    fn eq(&self, other: &Self) -> bool {
37        self.a_id == other.a_id
38            && self.b_id == other.b_id
39            && self.c_id == other.c_id
40            && self.d_id == other.d_id
41    }
42}
43
44impl Eq for Tetrahedron3D {}
45
46impl Hash for Tetrahedron3D {
47    fn hash<H: Hasher>(&self, state: &mut H) {
48        self.a_id.hash(state);
49        self.b_id.hash(state);
50        self.c_id.hash(state);
51        self.d_id.hash(state);
52    }
53}
54
55impl Tetrahedron3D {
56    /// Creates a tetrahedron from four point ids and a shared point table.
57    pub fn new(
58        a_id: PointId,
59        b_id: PointId,
60        c_id: PointId,
61        d_id: PointId,
62        vertex_table: SharedGeometryTable<PointId, CoordinateVector3D>,
63    ) -> Self {
64        Self {
65            a_id,
66            b_id,
67            c_id,
68            d_id,
69            vertex_table,
70        }
71    }
72
73    /// Returns the first vertex id.
74    pub fn a_id(&self) -> PointId {
75        self.a_id
76    }
77
78    /// Returns the second vertex id.
79    pub fn b_id(&self) -> PointId {
80        self.b_id
81    }
82
83    /// Returns the third vertex id.
84    pub fn c_id(&self) -> PointId {
85        self.c_id
86    }
87
88    /// Returns the fourth vertex id.
89    pub fn d_id(&self) -> PointId {
90        self.d_id
91    }
92
93    /// Resolves the first vertex from the shared point table.
94    pub fn a(&self) -> Option<CoordinateVector3D> {
95        self.get_vertex(&self.a_id)
96    }
97
98    /// Resolves the second vertex from the shared point table.
99    pub fn b(&self) -> Option<CoordinateVector3D> {
100        self.get_vertex(&self.b_id)
101    }
102
103    /// Resolves the third vertex from the shared point table.
104    pub fn c(&self) -> Option<CoordinateVector3D> {
105        self.get_vertex(&self.c_id)
106    }
107
108    /// Resolves the fourth vertex from the shared point table.
109    pub fn d(&self) -> Option<CoordinateVector3D> {
110        self.get_vertex(&self.d_id)
111    }
112
113    /// Returns the four triangular boundary faces of the tetrahedron.
114    pub fn faces(&self) -> [Triangle3D; 4] {
115        [
116            Triangle3D::new(self.a_id, self.b_id, self.c_id, self.vertex_table.clone()),
117            Triangle3D::new(self.a_id, self.b_id, self.d_id, self.vertex_table.clone()),
118            Triangle3D::new(self.a_id, self.c_id, self.d_id, self.vertex_table.clone()),
119            Triangle3D::new(self.b_id, self.c_id, self.d_id, self.vertex_table.clone()),
120        ]
121    }
122
123    /// Returns the number of triangular faces.
124    pub fn face_count(&self) -> usize {
125        4
126    }
127
128    /// Returns the total surface area of the tetrahedron.
129    pub fn surface_area(&self) -> GeometryMeasure {
130        self.faces().iter().map(|face| face.area()).sum()
131    }
132
133    /// Returns the signed volume of the tetrahedron.
134    pub fn signed_volume(&self) -> GeometryMeasure {
135        let (Some(a), Some(b), Some(c), Some(d)) = (self.a(), self.b(), self.c(), self.d()) else {
136            return 0.0;
137        };
138        let ab = [b.x() - a.x(), b.y() - a.y(), b.z() - a.z()];
139        let ac = [c.x() - a.x(), c.y() - a.y(), c.z() - a.z()];
140        let ad = [d.x() - a.x(), d.y() - a.y(), d.z() - a.z()];
141        let cross = FreeVector3D::new(
142            ab[1] * ac[2] - ab[2] * ac[1],
143            ab[2] * ac[0] - ab[0] * ac[2],
144            ab[0] * ac[1] - ab[1] * ac[0],
145        );
146        (cross.x() * ad[0] + cross.y() * ad[1] + cross.z() * ad[2]) / 6.0
147    }
148
149    /// Returns the absolute tetrahedron volume.
150    pub fn volume(&self) -> GeometryMeasure {
151        self.signed_volume().abs()
152    }
153
154    fn unique_vertex_ids(&self) -> Vec<PointId> {
155        let mut seen = HashSet::new();
156        [self.a_id, self.b_id, self.c_id, self.d_id]
157            .into_iter()
158            .filter(|id| seen.insert(*id))
159            .collect()
160    }
161}
162
163impl Display for Tetrahedron3D {
164    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
165        write!(
166            f,
167            "Tetrahedron3D({:?}, {:?}, {:?}, {:?})",
168            self.a_id, self.b_id, self.c_id, self.d_id
169        )
170    }
171}
172
173impl GeometricPrimitive for Tetrahedron3D {}
174impl GeometricPrimitive3D for Tetrahedron3D {}
175
176impl<'a> HasVertices<'a> for Tetrahedron3D {
177    type Vertex = CoordinateVector3D;
178    type VertexTable = SharedGeometryTable<PointId, CoordinateVector3D>;
179
180    fn vertex_table(&self) -> &Self::VertexTable {
181        &self.vertex_table
182    }
183
184    fn vertex_table_mut(&mut self) -> &mut Self::VertexTable {
185        &mut self.vertex_table
186    }
187
188    fn set_vertex_table(&mut self, table: &'a mut Self::VertexTable) {
189        self.vertex_table = table.clone();
190    }
191}
192
193impl HasEdges for Tetrahedron3D {
194    type Edge = Line3D;
195
196    fn edge_count(&self) -> usize {
197        6
198    }
199
200    fn edge(&self, index: usize) -> Option<Self::Edge> {
201        let (head, tail) = match index {
202            0 => (self.a_id, self.b_id),
203            1 => (self.a_id, self.c_id),
204            2 => (self.a_id, self.d_id),
205            3 => (self.b_id, self.c_id),
206            4 => (self.b_id, self.d_id),
207            5 => (self.c_id, self.d_id),
208            _ => return None,
209        };
210        Some(Line3D::new(head, tail, self.vertex_table.clone()))
211    }
212}
213
214impl HasCentroid for Tetrahedron3D {
215    type Point = CoordinateVector3D;
216
217    fn centroid(&self) -> Self::Point {
218        let a = self.a().unwrap_or(CoordinateVector3D::new(0.0, 0.0, 0.0));
219        let b = self.b().unwrap_or(CoordinateVector3D::new(0.0, 0.0, 0.0));
220        let c = self.c().unwrap_or(CoordinateVector3D::new(0.0, 0.0, 0.0));
221        let d = self.d().unwrap_or(CoordinateVector3D::new(0.0, 0.0, 0.0));
222        CoordinateVector3D::new(
223            (a.x() + b.x() + c.x() + d.x()) / 4.0,
224            (a.y() + b.y() + c.y() + d.y()) / 4.0,
225            (a.z() + b.z() + c.z() + d.z()) / 4.0,
226        )
227    }
228}
229
230impl HasMeasure for Tetrahedron3D {
231    fn measure(&self) -> GeometryMeasure {
232        self.volume()
233    }
234}
235
236impl<'a> IsTetrahedron<'a, CoordinateVector3D, UnitVector3D> for Tetrahedron3D {
237    fn a_id(&self) -> PointId {
238        self.a_id
239    }
240
241    fn set_a_id(&mut self, point_id: PointId) -> Result<(), ErrorsJSL> {
242        self.a_id = point_id;
243        Ok(())
244    }
245
246    fn b_id(&self) -> PointId {
247        self.b_id
248    }
249
250    fn set_b_id(&mut self, point_id: PointId) -> Result<(), ErrorsJSL> {
251        self.b_id = point_id;
252        Ok(())
253    }
254
255    fn c_id(&self) -> PointId {
256        self.c_id
257    }
258
259    fn set_c_id(&mut self, point_id: PointId) -> Result<(), ErrorsJSL> {
260        self.c_id = point_id;
261        Ok(())
262    }
263
264    fn d_id(&self) -> PointId {
265        self.d_id
266    }
267
268    fn set_d_id(&mut self, point_id: PointId) -> Result<(), ErrorsJSL> {
269        self.d_id = point_id;
270        Ok(())
271    }
272
273    fn faces(&self) -> [Triangle3D; 4] {
274        Tetrahedron3D::faces(self)
275    }
276
277    fn face_count(&self) -> usize {
278        Tetrahedron3D::face_count(self)
279    }
280
281    fn surface_area(&self) -> GeometryMeasure {
282        Tetrahedron3D::surface_area(self)
283    }
284
285    fn signed_volume(&self) -> GeometryMeasure {
286        Tetrahedron3D::signed_volume(self)
287    }
288
289    fn volume(&self) -> GeometryMeasure {
290        Tetrahedron3D::volume(self)
291    }
292}
293
294impl IsValid for Tetrahedron3D {
295    fn is_valid(&self) -> bool {
296        self.unique_vertex_ids().len() == 4 && self.volume() > 1e-6
297    }
298}
299
300impl Repair for Tetrahedron3D {
301    fn repair(&mut self) -> Result<(), ErrorsJSL> {
302        if self.unique_vertex_ids().len() != 4 {
303            return Err(ErrorsJSL::Message("tetrahedron vertices must be distinct".to_string()));
304        }
305        if self.volume() <= 1e-6 {
306            return Err(ErrorsJSL::Message("degenerate tetrahedron volume cannot be repaired automatically".to_string()));
307        }
308        Ok(())
309    }
310}
311
312impl Canonicalize for Tetrahedron3D {
313    fn canonicalize(&mut self) {
314        let mut ids = [self.a_id, self.b_id, self.c_id, self.d_id];
315        ids.sort_by_key(|id| id.0);
316        self.a_id = ids[0];
317        self.b_id = ids[1];
318        self.c_id = ids[2];
319        self.d_id = ids[3];
320    }
321}
322
323impl CanTranslate for Tetrahedron3D {
324    type Point = CoordinateVector3D;
325
326    fn translate<'a, L>(&mut self, translation_vector: &L)
327    where
328        L: IsLine<'a, Self::Point>,
329    {
330        let (Some(head), Some(tail)) = (translation_vector.head(), translation_vector.tail()) else {
331            return;
332        };
333        let delta = FreeVector3D::new(tail.x() - head.x(), tail.y() - head.y(), tail.z() - head.z());
334        for point_id in self.unique_vertex_ids() {
335            if let Some(mut point) = self.get_vertex(&point_id) {
336                point = point + delta;
337                let _ = self.insert_vertex(point_id, point);
338            }
339        }
340    }
341}
342
343impl CanRotate for Tetrahedron3D {
344    type Point = CoordinateVector3D;
345
346    fn rotate<'a, L>(&mut self, axis: &L, angle_radians: GeometryMeasure)
347    where
348        L: IsLine<'a, Self::Point>,
349    {
350        let Some(origin) = axis.head() else {
351            return;
352        };
353        let direction = axis.direction();
354        for point_id in self.unique_vertex_ids() {
355            if let Some(point) = self.get_vertex(&point_id) {
356                let rotated = rotate_point_around_axis(point, origin, &direction, angle_radians);
357                let _ = self.insert_vertex(point_id, rotated);
358            }
359        }
360    }
361}
362
363impl CanShear for Tetrahedron3D {
364    type Point = CoordinateVector3D;
365
366    fn shear<'a, L>(&mut self, shear_line: &L)
367    where
368        L: IsLine<'a, Self::Point>,
369    {
370        let factor = shear_line.length();
371        for point_id in self.unique_vertex_ids() {
372            if let Some(mut point) = self.get_vertex(&point_id) {
373                let coords = point.cartesian_components();
374                point = CoordinateVector3D::from_cartesian_components(
375                    [coords[0] + factor * coords[1], coords[1], coords[2]],
376                    point.coordinate_system(),
377                );
378                let _ = self.insert_vertex(point_id, point);
379            }
380        }
381    }
382}
383
384impl CanMirror for Tetrahedron3D {
385    type Point = CoordinateVector3D;
386    type Normal = UnitVector3D;
387
388    fn mirror<P>(&mut self, mirror_plane: &P)
389    where
390        P: IsPlane<Point = Self::Point, Normal = Self::Normal>,
391    {
392        for point_id in self.unique_vertex_ids() {
393            if let Some(point) = self.get_vertex(&point_id) {
394                let reflected = reflect_point_across_plane(point, mirror_plane.point(), mirror_plane.normal());
395                let _ = self.insert_vertex(point_id, reflected);
396            }
397        }
398    }
399}