reda_geometry/shape/
polyline.rs

1use num_traits::NumCast;
2
3use crate::traits::{Cast, MapPoint, TryBoundingBox};
4
5use super::{DType, Edge, Point, Rect};
6use std::cmp::PartialEq;
7use std::slice::Iter;
8
9#[derive(Clone, Debug, Hash, Eq, PartialEq)]
10#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11pub struct Polyline<T> {
12    pub points: Vec<Point<T>>,
13    pub normalized: bool,
14}
15
16#[macro_export]
17macro_rules! polyline {
18    ($($x:expr),*) => {  };
19}
20
21impl<T> Polyline<T> {
22    pub fn from_points(points: impl Into<Vec<Point<T>>>) -> Self {
23        Self {
24            points: points.into(),
25            normalized: false,
26        }
27    }
28
29    pub fn empty() -> Self {
30        Self {
31            points: Vec::new(),
32            normalized: false,
33        }
34    }
35
36    pub fn len(&self) -> usize {
37        self.points.len()
38    }
39
40    pub fn is_empty(&self) -> bool {
41        self.points.is_empty()
42    }
43
44    pub fn iter(&self) -> Iter<Point<T>> {
45        self.points.iter()
46    }
47
48    pub fn points(&self) -> &[Point<T>] {
49        &self.points
50    }
51
52    /// Get index of previous vertex.
53    pub fn prev_index(&self, i: usize) -> usize {
54        match i {
55            0 => self.points.len() - 1,
56            x => x - 1,
57        }
58    }
59
60    /// Get index of next vertex.
61    pub fn next_index(&self, i: usize) -> usize {
62        match i {
63            _ if i == self.points.len() - 1 => 0,
64            x => x + 1,
65        }
66    }
67}
68
69impl<T: PartialOrd> Polyline<T> {
70    pub fn new(points: Vec<Point<T>>) -> Self {
71        Self::from_points(points).normalized()
72    }
73
74    /// Rotate the vertices to get the lexicographically smallest polygon.
75    /// Does not change the orientation.
76    pub fn normalize(&mut self) {
77        if !self.normalized {
78            let rotated = 
79                |rot: usize| self.points.iter()
80                    .cycle()
81                    .skip(rot)
82                    .take(self.points.len());
83            
84            let best_rot = (0..self.points.len()).skip(1).fold(0, |best_rot, rot| {
85                if rotated(rot).lt(rotated(best_rot)) {
86                    rot
87                } else {
88                    best_rot
89                }
90            });
91            self.points.rotate_left(best_rot);
92        }
93        self.normalized = true;
94    }
95
96    pub fn normalized(mut self) -> Self {
97        self.normalize();
98        self
99    }
100}
101
102impl<T: Copy> Polyline<T> {
103    pub fn iter_cycle(&self) -> impl Iterator<Item = &Point<T>> {
104        self.points.iter().cycle().take(self.points.len() + 1)
105    }
106
107    pub fn edges_iter(&self) -> impl Iterator<Item = Edge<T>> + '_ {
108        self.iter()
109            .zip(self.iter_cycle().skip(1))
110            .map(|(a, b)| Edge::new(a, b))
111    }
112
113    pub fn edges(&self) -> Vec<Edge<T>> {
114        self.edges_iter().collect()
115    }
116
117    pub fn from_rect(rect: &Rect<T>) -> Self {
118        Self {
119            points: vec![
120                rect.lower_left(),
121                rect.lower_right(),
122                rect.upper_right(),
123                rect.upper_left(),
124            ],
125            normalized: true,
126        }
127    }
128}
129
130impl<T, P> FromIterator<P> for Polyline<T> 
131where 
132    T: Copy,
133    P: Into<Point<T>>
134{
135    fn from_iter<I: IntoIterator<Item = P>>(iter: I) -> Self {
136        let points: Vec<Point<T>> = iter.into_iter().map(|x| x.into()).collect();
137        assert!(
138            points.len() >= 2,
139            "A polygon needs to have at least two points."
140        );
141        Self::from_points(points)
142    }
143}
144
145impl<'a, T> IntoIterator for &'a Polyline<T> {
146    type Item = &'a Point<T>;
147    type IntoIter = std::slice::Iter<'a, Point<T>>;
148
149    fn into_iter(self) -> Self::IntoIter {
150        self.points.iter()
151    }
152}
153
154impl<I, T, P> From<I> for Polyline<T> 
155where 
156    T: Copy + PartialOrd,
157    I: IntoIterator<Item = P>,
158    Point<T>: From<P>,
159{
160    fn from(iter: I) -> Self {
161        let points: Vec<Point<T>> = iter.into_iter().map(|x| x.into()).collect();
162        Polyline::from_points(points)
163    }
164}
165
166impl<T: Copy> MapPoint<T> for Polyline<T> {
167    fn transform<F>(&self, transformate: F) -> Self
168    where 
169        F: Fn(Point<T>) -> Point<T> 
170    {
171        let points: Vec<_> = self.points.iter().map(|&p| transformate(p)).collect();
172        Self::from_points(points)    
173    }
174}
175
176impl<T: Copy + PartialOrd> TryBoundingBox<T> for Polyline<T> {
177    fn try_bounding_box(&self) -> Option<Rect<T>> {
178        if !self.is_empty() {
179            let mut x_min = self.points[0].x;
180            let mut x_max = x_min;
181            let mut y_min = self.points[0].y;
182            let mut y_max = y_min;
183
184            for p in self.iter().skip(1) {
185                if p.x < x_min {
186                    x_min = p.x;
187                }
188                if p.x > x_max {
189                    x_max = p.x;
190                }
191                if p.y < y_min {
192                    y_min = p.y;
193                }
194                if p.y > y_max {
195                    y_max = p.y;
196                }
197            }
198
199            Some(Rect::new((x_min, y_min), (x_max, y_max)))
200        } else {
201            None
202        }
203    }
204}
205
206impl<T: DType + NumCast, Dst: DType + NumCast> Cast<T, Dst> for Polyline<T> {
207    type Output = Polyline<Dst>;
208
209    fn try_cast(&self) -> Option<Self::Output> {
210        let new_points: Option<Vec<_>> = self.points.iter().map(|p| p.try_cast()).collect();
211        new_points.map(|p| Polyline::new(p))
212    }
213}