Skip to main content

reda_geometry/shape/
polygon.rs

1use itertools::Itertools;
2use num_traits::NumCast;
3
4use crate::traits::{Cast, MapPoint, TryBoundingBox};
5
6use super::{CoordType, Edge, Point, Polyline, Rect};
7
8#[derive(Clone, Hash, Debug, Eq, PartialEq)]
9pub struct Polygon<T> {
10    pub exterior: Polyline<T>,
11    pub interiors: Vec<Polyline<T>>, 
12}
13
14impl<T> Polygon<T> {
15    pub fn new<E, I>(exterior: E, holes: Vec<I>) -> Self 
16    where 
17        E: Into<Polyline<T>>,
18        I: Into<Polyline<T>>,
19    {
20        Self {
21            exterior: exterior.into(),
22            interiors: holes.into_iter().map(|i| i.into()).collect()
23        }
24    }
25
26    pub fn new_exterior(exterior: impl Into<Vec<Point<T>>>) -> Self {
27        Self {
28            exterior: Polyline::from_points(exterior),
29            interiors: Vec::new(),
30        }
31    }
32
33    pub fn empty() -> Self {
34        Self {
35            exterior: Polyline::empty(),
36            interiors: Vec::new(),
37        }
38    }
39
40    pub fn len(&self) -> usize {
41        self.exterior.len()
42    }
43
44    pub fn is_empty(&self) -> bool {
45        self.exterior.is_empty()
46    }
47}   
48
49impl<T: Copy> Polygon<T> {
50    pub fn exterior_edges(&self) -> Vec<Edge<T>> {
51        self.exterior.edges()
52    }
53
54    pub fn exterior_edges_iter(&self) -> impl Iterator<Item = Edge<T>> + '_ {
55        self.exterior.edges_iter()
56    }
57
58    pub fn all_edges(&self) -> Vec<Edge<T>> {
59        self.all_edges_iter().collect()
60    }
61
62    pub fn all_edges_iter(&self) -> impl Iterator<Item = Edge<T>> + '_ {
63        self.exterior.edges_iter().chain(
64            self.interiors
65                .iter()
66                .flat_map(|interior| interior.edges_iter())
67        )
68    }
69}
70
71impl<T: PartialOrd> Polygon<T> {
72    pub fn new_normalized<E, I>(exterior: E, holes: Vec<I>) -> Self 
73    where 
74        E: Into<Polyline<T>>,
75        I: Into<Polyline<T>>,
76    {
77        Self::new(exterior, holes).normalized()
78    }
79    
80    pub fn new_exterior_normalized(exterior: impl Into<Vec<Point<T>>>) -> Self {
81        Self::new_exterior(exterior).normalized()
82    }
83
84    /// Reorder vertices and holes to get the lexicographically smallest representation of this polygon.
85    /// Does not change the orientations.
86    pub fn normalize(&mut self) {
87        self.exterior.normalize();
88        self.interiors.iter_mut().for_each(|p| p.normalize());
89        self.interiors.sort_by(|a, b| {
90            a.points()
91                .partial_cmp(b.points())
92                .unwrap_or(std::cmp::Ordering::Less)
93        })
94    }
95
96    /// Reorder vertices and holes to get the lexicographically smallest representation of this polygon.
97    /// Does not change the orientations.
98    pub fn normalized(mut self) -> Self {
99        self.normalize();
100        self
101    }
102}
103
104impl<'a, T, P> From<&'a [P]> for Polygon<T>
105where
106    T: CoordType,
107    Point<T>: From<&'a P>,
108{
109    fn from(vec: &'a [P]) -> Self {
110        Self {
111            exterior: vec.into(),
112            interiors: Vec::new(),
113        }
114    }
115}
116
117impl<T, P> From<Vec<P>> for Polygon<T>
118where
119    T: Copy + PartialOrd,
120    Point<T>: From<P>,
121{
122    fn from(vec: Vec<P>) -> Self {
123        Self {
124            exterior: vec.into(),
125            interiors: Vec::new(),
126        }
127    }
128}
129
130impl<T> From<Polyline<T>> for Polygon<T> {
131    fn from(polyline: Polyline<T>) -> Self {
132        Self {
133            exterior: polyline,
134            interiors: Vec::new(),
135        }
136    }
137}
138
139impl<T> From<&Polyline<T>> for Polygon<T> 
140where 
141    T: Clone
142{
143    fn from(polyline: &Polyline<T>) -> Self {
144        Self {
145            exterior: polyline.clone(),
146            interiors: Vec::new(),
147        }
148    }
149}
150
151impl<T> From<Rect<T>> for Polygon<T>
152where
153    T: Copy,
154{
155    fn from(rect: Rect<T>) -> Self {
156        Self::from(&rect)
157    }
158}
159
160impl<T> From<&Rect<T>> for Polygon<T>
161where
162    T: Copy,
163{
164    fn from(rect: &Rect<T>) -> Self {
165        Polyline::from_rect(rect).into()
166    }
167}
168
169impl<T: Copy> MapPoint<T> for Polygon<T> {
170    fn transform<F>(&self, transformate: F) -> Self
171    where 
172        F: Fn(Point<T>) -> Point<T> 
173    {
174        Self {
175            exterior: self.exterior.transform(&transformate),
176            interiors: self.interiors.iter().map(|p| p.transform(&transformate)).collect(),
177        }    
178    }
179}
180
181impl<T: Copy + PartialOrd> TryBoundingBox<T> for Polygon<T> {
182    fn try_bounding_box(&self) -> Option<Rect<T>> {
183        self.exterior.try_bounding_box()  
184    }
185}
186
187impl<T: CoordType + NumCast, Dst: CoordType + NumCast> Cast<T, Dst>
188    for Polygon<T>
189{
190    type Output = Polygon<Dst>;
191
192    fn try_cast(&self) -> Option<Self::Output> {
193        if let Some(new_hull) = self.exterior.try_cast() {
194            let new_holes: Vec<_> = self
195                .interiors
196                .iter()
197                .map(|hole| hole.try_cast())
198                .while_some()
199                .collect();
200            if new_holes.len() == self.interiors.len() {
201                Some(Polygon::new(new_hull, new_holes))
202            } else {
203                None
204            }
205        } else {
206            None
207        }
208    }
209}