Skip to main content

lib_jsl_geometry/dim_2/
triangle2d.rs

1//! Concrete triangle type built from two-dimensional points.
2
3use lib_jsl_core::ErrorsJSL;
4use crate::common::{
5    GeometricPrimitive, GeometricPrimitive2D, GeometryMeasure, HasCentroid, HasEdges, HasMeasure,
6    HasVertices, IsPlane, PointId,
7};
8use crate::tables::SharedGeometryTable;
9use crate::transformation_traits::{CanMirror, CanRotate, CanShear, CanTranslate};
10use crate::two_d::{
11    HasOrientation, IsPolygon, IsTriangle, Line2D, Plane2D, CoordinateVector2D, PolygonFace2D, UnitVector2D,
12    Orientation2D,
13};
14use std::fmt::{self, Display, Formatter};
15use std::hash::{Hash, Hasher};
16
17/// Concrete 2D triangle implementation backed by three point ids.
18#[derive(Debug, Clone)]
19#[cfg_attr(feature = "serde", derive(serde::Serialize))]
20pub struct Triangle2D {
21    a_id: PointId,
22    b_id: PointId,
23    c_id: PointId,
24    #[cfg_attr(feature = "serde", serde(skip_serializing))]
25    vertex_table: SharedGeometryTable<PointId, CoordinateVector2D>,
26}
27
28impl PartialEq for Triangle2D {
29    fn eq(&self, other: &Self) -> bool {
30        self.a_id == other.a_id && self.b_id == other.b_id && self.c_id == other.c_id
31    }
32}
33
34impl Eq for Triangle2D {}
35
36impl Hash for Triangle2D {
37    fn hash<H: Hasher>(&self, state: &mut H) {
38        self.a_id.hash(state);
39        self.b_id.hash(state);
40        self.c_id.hash(state);
41    }
42}
43
44impl Triangle2D {
45    /// Creates a triangle from three point ids and a shared point table.
46    pub fn new(
47        a_id: PointId,
48        b_id: PointId,
49        c_id: PointId,
50        vertex_table: SharedGeometryTable<PointId, CoordinateVector2D>,
51    ) -> Self {
52        Self {
53            a_id,
54            b_id,
55            c_id,
56            vertex_table,
57        }
58    }
59}
60
61impl Display for Triangle2D {
62    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
63        write!(f, "Triangle2D({:?}, {:?}, {:?})", self.a_id, self.b_id, self.c_id)
64    }
65}
66
67impl GeometricPrimitive for Triangle2D {}
68impl GeometricPrimitive2D for Triangle2D {}
69
70impl<'a> HasVertices<'a> for Triangle2D {
71    type Vertex = CoordinateVector2D;
72    type VertexTable = SharedGeometryTable<PointId, CoordinateVector2D>;
73
74    fn vertex_table(&self) -> &Self::VertexTable {
75        &self.vertex_table
76    }
77
78    fn vertex_table_mut(&mut self) -> &mut Self::VertexTable {
79        &mut self.vertex_table
80    }
81
82    fn set_vertex_table(&mut self, table: &'a mut Self::VertexTable) {
83        self.vertex_table = table.clone();
84    }
85}
86
87impl HasEdges for Triangle2D {
88    type Edge = Line2D;
89
90    fn edge_count(&self) -> usize {
91        3
92    }
93
94    fn edge(&self, index: usize) -> Option<Self::Edge> {
95        let (head, tail) = match index {
96            0 => (self.a_id, self.b_id),
97            1 => (self.b_id, self.c_id),
98            2 => (self.c_id, self.a_id),
99            _ => return None,
100        };
101        Some(Line2D::new(head, tail, self.vertex_table.clone()))
102    }
103}
104
105impl HasCentroid for Triangle2D {
106    type Point = CoordinateVector2D;
107
108    fn centroid(&self) -> Self::Point {
109        let a = self.a().unwrap_or(CoordinateVector2D::new(0.0, 0.0));
110        let b = self.b().unwrap_or(CoordinateVector2D::new(0.0, 0.0));
111        let c = self.c().unwrap_or(CoordinateVector2D::new(0.0, 0.0));
112        CoordinateVector2D::new((a.x() + b.x() + c.x()) / 3.0, (a.y() + b.y() + c.y()) / 3.0)
113    }
114}
115
116impl HasMeasure for Triangle2D {
117    fn measure(&self) -> GeometryMeasure {
118        self.area()
119    }
120}
121
122impl HasOrientation for Triangle2D {
123    fn orientation(&self) -> Orientation2D {
124        match (self.a(), self.b(), self.c()) {
125            (Some(a), Some(b), Some(c)) => {
126                let cross = (b.x() - a.x()) * (c.y() - a.y()) - (b.y() - a.y()) * (c.x() - a.x());
127                if cross > 0.0 {
128                    Orientation2D::CounterClockwise
129                } else if cross < 0.0 {
130                    Orientation2D::Clockwise
131                } else {
132                    Orientation2D::Collinear
133                }
134            }
135            _ => Orientation2D::Collinear,
136        }
137    }
138}
139
140impl CanTranslate for Triangle2D {
141    type Point = CoordinateVector2D;
142
143    fn translate<'a, L>(&mut self, translation_vector: &L)
144    where
145        L: crate::one_d::IsLine<'a, Self::Point>,
146    {
147        let mut polygon = PolygonFace2D::new(vec![self.a_id, self.b_id, self.c_id], self.vertex_table.clone());
148        polygon.translate(translation_vector);
149    }
150}
151
152impl CanRotate for Triangle2D {
153    type Point = CoordinateVector2D;
154
155    fn rotate<'a, L>(&mut self, axis: &L, angle_radians: GeometryMeasure)
156    where
157        L: crate::one_d::IsLine<'a, Self::Point>,
158    {
159        let mut polygon = PolygonFace2D::new(vec![self.a_id, self.b_id, self.c_id], self.vertex_table.clone());
160        polygon.rotate(axis, angle_radians);
161    }
162}
163
164impl CanShear for Triangle2D {
165    type Point = CoordinateVector2D;
166
167    fn shear<'a, L>(&mut self, shear_line: &L)
168    where
169        L: crate::one_d::IsLine<'a, Self::Point>,
170    {
171        let mut polygon = PolygonFace2D::new(vec![self.a_id, self.b_id, self.c_id], self.vertex_table.clone());
172        polygon.shear(shear_line);
173    }
174}
175
176impl CanMirror for Triangle2D {
177    type Point = CoordinateVector2D;
178    type Normal = UnitVector2D;
179
180    fn mirror<P>(&mut self, mirror_plane: &P)
181    where
182        P: IsPlane<Point = Self::Point, Normal = Self::Normal>,
183    {
184        let mut polygon = PolygonFace2D::new(vec![self.a_id, self.b_id, self.c_id], self.vertex_table.clone());
185        polygon.mirror(mirror_plane);
186    }
187}
188
189impl<'a> IsPolygon<'a, CoordinateVector2D, UnitVector2D> for Triangle2D {
190    fn vertex_ids(&self) -> Box<dyn Iterator<Item = PointId> + '_> {
191        Box::new([self.a_id, self.b_id, self.c_id].into_iter())
192    }
193
194    fn set_vertex_id(&mut self, index: usize, point_id: PointId) -> Result<(), ErrorsJSL> {
195        match index {
196            0 => self.a_id = point_id,
197            1 => self.b_id = point_id,
198            2 => self.c_id = point_id,
199            _ => return Err(ErrorsJSL::Message(format!("vertex index {} is out of bounds", index))),
200        }
201        Ok(())
202    }
203
204    fn normal(&self) -> UnitVector2D {
205        PolygonFace2D::new(vec![self.a_id, self.b_id, self.c_id], self.vertex_table.clone()).normal()
206    }
207
208    fn perimeter(&self) -> GeometryMeasure {
209        PolygonFace2D::new(vec![self.a_id, self.b_id, self.c_id], self.vertex_table.clone()).perimeter()
210    }
211
212    fn area(&self) -> GeometryMeasure {
213        PolygonFace2D::new(vec![self.a_id, self.b_id, self.c_id], self.vertex_table.clone()).area()
214    }
215
216    fn plane(&self) -> impl IsPlane<Point = CoordinateVector2D, Normal = UnitVector2D> {
217        Plane2D::new(self.centroid(), self.normal())
218    }
219}
220
221impl<'a> IsTriangle<'a, CoordinateVector2D, UnitVector2D> for Triangle2D {
222    fn a_id(&self) -> PointId {
223        self.a_id
224    }
225
226    fn set_a_id(&mut self, point_id: PointId) -> Result<(), ErrorsJSL> {
227        self.a_id = point_id;
228        Ok(())
229    }
230
231    fn b_id(&self) -> PointId {
232        self.b_id
233    }
234
235    fn set_b_id(&mut self, point_id: PointId) -> Result<(), ErrorsJSL> {
236        self.b_id = point_id;
237        Ok(())
238    }
239
240    fn c_id(&self) -> PointId {
241        self.c_id
242    }
243
244    fn set_c_id(&mut self, point_id: PointId) -> Result<(), ErrorsJSL> {
245        self.c_id = point_id;
246        Ok(())
247    }
248}