shape_core/elements/triangles/
convert.rs

1use super::*;
2use crate::utils::{max3, min3};
3use std::vec::IntoIter;
4
5impl<T, P> TryFrom<(P, P, P)> for Triangle<T>
6where
7    Point<T>: From<P>,
8    T: Num + Clone + PartialOrd,
9{
10    type Error = ();
11
12    fn try_from(value: (P, P, P)) -> Result<Self, Self::Error> {
13        let tri = Self { a: value.0.into(), b: value.1.into(), c: value.2.into() };
14        match tri.is_valid() {
15            true => Ok(tri),
16            false => Err(()),
17        }
18    }
19}
20
21impl<T> TryFrom<&Polygon<T>> for Triangle<T>
22where
23    T: Clone,
24{
25    type Error = ();
26
27    fn try_from(value: &Polygon<T>) -> Result<Self, Self::Error> {
28        match value.points_set.points.as_slice() {
29            [a, b, c] => Ok(Triangle { a: a.clone(), b: b.clone(), c: c.clone() }),
30            _ => Err(()),
31        }
32    }
33}
34
35impl<T> Shape2D for Triangle<T>
36where
37    T: Clone + PartialOrd + Num,
38{
39    type Value = T;
40    type VertexIterator<'a>
41
42    = IntoIter<Point<T>>where
43        T: 'a;
44    type LineIterator<'a>
45
46    = IntoIter<Line<T>>where
47        T: 'a;
48
49    fn is_valid(&self) -> bool {
50        let a = Vector::from_2_points(self.a.clone(), self.b.clone());
51        let b = Vector::from_2_points(self.b.clone(), self.c.clone());
52        a.dx * b.dy < a.dy * b.dx
53    }
54
55    fn boundary(&self) -> Rectangle<Self::Value> {
56        let min_x = min3(&self.a.x, &self.b.x, &self.c.x).clone();
57        let min_y = min3(&self.a.y, &self.b.y, &self.c.y).clone();
58        let max_x = max3(&self.a.x, &self.b.x, &self.c.x).clone();
59        let max_y = max3(&self.a.y, &self.b.y, &self.c.y).clone();
60        Rectangle::from_min_max(Point::new(min_x, min_y), Point::new(max_x, max_y))
61    }
62
63    fn vertices<'a>(&'a self, _: usize) -> Self::VertexIterator<'a> {
64        vec![self.a.clone(), self.b.clone(), self.c.clone()].into_iter()
65    }
66
67    fn edges<'a>(&'a self, _: usize) -> Self::LineIterator<'a> {
68        vec![
69            Line::new(self.a.clone(), self.b.clone()),
70            Line::new(self.b.clone(), self.c.clone()),
71            Line::new(self.c.clone(), self.a.clone()),
72        ]
73        .into_iter()
74    }
75}