fey_math/
polygon.rs

1use crate::{Float, Line, Num, Numeric, Quad, Rect, Triangle, Vec2, line};
2use serde::{Deserialize, Serialize};
3
4pub type PolygonF = Polygon<f32>;
5pub type PolygonI = Polygon<i32>;
6
7/// A convex polygon.
8///
9/// The `N` represents how many points the polygon can have before it needs
10/// to allocate onto the heap. If you know your shapes will never have more
11/// than `N` edges, you can set it to that value and avoid heap allocations.
12#[repr(transparent)]
13#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
14pub struct Polygon<T>(Vec<Vec2<T>>);
15
16impl<T: Num> Polygon<T> {
17    /// Creates a new empty polygon.
18    #[inline]
19    pub fn new() -> Self {
20        Self(Vec::new())
21    }
22
23    /// Creates a new empty polygon with at least the specified `capacity`.
24    #[inline]
25    pub fn with_capacity(capacity: usize) -> Self {
26        Self(Vec::with_capacity(capacity))
27    }
28
29    /// Create a new polygon using the array of points.
30    #[inline]
31    pub fn from_arr<const LEN: usize>(arr: [Vec2<T>; LEN]) -> Self {
32        Self(Vec::from(arr))
33    }
34
35    /// Create a new polygon using the slice of points.
36    #[inline]
37    pub fn from_slice<const LEN: usize>(slice: &[Vec2<T>]) -> Self {
38        Self(Vec::from(slice))
39    }
40
41    /// Create a new polygon using the array of points.
42    #[inline]
43    pub fn from_vec(vec: Vec<Vec2<T>>) -> Self {
44        Self(vec)
45    }
46
47    // Create a polygon representation of the provided rect.
48    #[inline]
49    pub fn from_rect(rect: Rect<T>) -> Self {
50        Self::from_arr(rect.corners())
51    }
52
53    /// Create a polygon representation of the provided triangle.
54    #[inline]
55    pub fn from_tri(tri: Triangle<T>) -> Self {
56        Self::from_arr(tri.0)
57    }
58
59    /// Create a polygon representation of the provided quad.
60    #[inline]
61    pub fn from_quad(quad: Quad<T>) -> Self {
62        Self::from_arr(quad.0)
63    }
64
65    /// How many points the polygon has.
66    #[inline]
67    pub fn len(&self) -> usize {
68        self.0.len()
69    }
70
71    /// If the polygon has no points.
72    #[inline]
73    pub fn is_empty(&self) -> bool {
74        self.0.is_empty()
75    }
76
77    /// The polygon's allocated capacity.
78    #[inline]
79    pub fn capacity(&self) -> usize {
80        self.0.capacity()
81    }
82
83    /// Add a point to the polygon.
84    #[inline]
85    pub fn push(&mut self, p: Vec2<T>) {
86        self.0.push(p);
87    }
88
89    /// Remove the last point from the polygon and return it.
90    #[inline]
91    pub fn pop(&mut self) -> Option<Vec2<T>> {
92        self.0.pop()
93    }
94
95    /// Reserve enough space for at least `capacity` points.
96    #[inline]
97    pub fn reserve(&mut self, capacity: usize) {
98        if let Some(add) = capacity.checked_sub(self.capacity()) {
99            self.0.reserve(add);
100        }
101    }
102
103    /// Reference to the polygon's points.
104    #[inline]
105    pub fn points(&self) -> &[Vec2<T>] {
106        self.0.as_slice()
107    }
108
109    /// Mutable reference to the polygon's points.
110    #[inline]
111    pub fn points_mut(&mut self) -> &mut [Vec2<T>] {
112        self.0.as_mut_slice()
113    }
114
115    /// Remove all points from the polygon.
116    #[inline]
117    pub fn clear(&mut self) {
118        self.0.clear();
119    }
120
121    /// Remove the point at `index`.
122    #[inline]
123    pub fn remove(&mut self, index: usize) -> Vec2<T> {
124        self.0.remove(index)
125    }
126
127    /// Insert a point at `index`.
128    #[inline]
129    pub fn insert(&mut self, index: usize, p: Vec2<T>) {
130        self.0.insert(index, p);
131    }
132
133    /// Convert the polygon into a `Vec` of points.
134    #[inline]
135    pub fn to_vec(self) -> Vec<Vec2<T>> {
136        self.0
137    }
138
139    /// Resize the polygon, using the provided function to create new points.
140    #[inline]
141    pub fn resize_with<F: FnMut() -> Vec2<T>>(&mut self, new_size: usize, f: F) {
142        self.0.resize_with(new_size, f);
143    }
144
145    /// Translate all points in the polygon.
146    #[inline]
147    pub fn translate(&mut self, amount: Vec2<T>) {
148        for p in self.points_mut() {
149            *p += amount;
150        }
151    }
152
153    /// Get the *nth* edge of the polygon. A polygon has the
154    /// same amount of edges as vertices, so if this index exceeds
155    /// `len()`, then `None` will be returned.
156    #[inline]
157    pub fn edge(&self, index: usize) -> Option<Line<T>> {
158        let points = self.points();
159        (index < points.len()).then(|| line(points[index], points[(index + 1) % self.len()]))
160    }
161
162    /// An iterator over all the polygon's edges.
163    #[inline]
164    pub fn edges(&self) -> impl Iterator<Item = Line<T>> + '_ {
165        let len = self.len();
166        let points = self.points();
167        (0..len).map(move |i| {
168            let j = (i + 1) % len;
169            line(points[i], points[j])
170        })
171    }
172}
173
174impl<T: Float> Polygon<T> {
175    #[inline]
176    pub fn transform_in_place_by(&mut self, mut f: impl FnMut(Vec2<T>) -> Vec2<T>) {
177        for p in self.points_mut() {
178            *p = f(*p);
179        }
180    }
181
182    #[inline]
183    pub fn transform_by_into(&self, into: &mut Self, f: impl FnMut(Vec2<T>) -> Vec2<T>) {
184        into.clear();
185        into.extend(self.points().iter().copied().map(f));
186    }
187
188    #[inline]
189    pub fn transform_by(&self, f: impl FnMut(Vec2<T>) -> Vec2<T>) -> Self {
190        let mut poly = Self::new();
191        self.transform_by_into(&mut poly, f);
192        poly
193    }
194
195    // /// Transform the polygon by the matrix.
196    // #[inline]
197    // pub fn transform_in_place(&mut self, mat: &Affine2<T>) {
198    //     for p in self.points_mut() {
199    //         *p = mat.transform_pos2(*p);
200    //     }
201    // }
202    //
203    // /// Transform the polygon, storing the results in the provided one.
204    // #[inline]
205    // pub fn transform_into(&mut self, mat: &Affine2<T>, into: &mut Self) {
206    //     into.clear();
207    //     into.reserve(self.len());
208    //     for p in self.points() {
209    //         into.push(mat.transform_pos2(*p));
210    //     }
211    // }
212}
213
214impl<T: Num> FromIterator<Vec2<T>> for Polygon<T> {
215    #[inline]
216    fn from_iter<I: IntoIterator<Item = Vec2<T>>>(iter: I) -> Self {
217        Self(Vec::from_iter(iter))
218    }
219}
220
221impl<T: Num> Extend<Vec2<T>> for Polygon<T> {
222    #[inline]
223    fn extend<I: IntoIterator<Item = Vec2<T>>>(&mut self, iter: I) {
224        self.0.extend(iter);
225    }
226}
227
228impl<T> IntoIterator for Polygon<T> {
229    type Item = Vec2<T>;
230    type IntoIter = std::vec::IntoIter<Vec2<T>>;
231
232    #[inline]
233    fn into_iter(self) -> Self::IntoIter {
234        self.0.into_iter()
235    }
236}
237
238impl<T> AsRef<[Vec2<T>]> for Polygon<T> {
239    #[inline]
240    fn as_ref(&self) -> &[Vec2<T>] {
241        self.0.as_ref()
242    }
243}
244
245impl<T> AsMut<[Vec2<T>]> for Polygon<T> {
246    #[inline]
247    fn as_mut(&mut self) -> &mut [Vec2<T>] {
248        self.0.as_mut()
249    }
250}
251
252impl<T: Num, const S: usize> From<[Vec2<T>; S]> for Polygon<T> {
253    #[inline]
254    fn from(value: [Vec2<T>; S]) -> Self {
255        Self::from_arr(value)
256    }
257}
258
259impl<T: Num> From<Vec<Vec2<T>>> for Polygon<T> {
260    #[inline]
261    fn from(value: Vec<Vec2<T>>) -> Self {
262        Self::from_vec(value)
263    }
264}
265
266impl<T: Num> From<Rect<T>> for Polygon<T> {
267    #[inline]
268    fn from(value: Rect<T>) -> Self {
269        Self::from_rect(value)
270    }
271}
272
273impl<T: Num> From<Triangle<T>> for Polygon<T> {
274    #[inline]
275    fn from(value: Triangle<T>) -> Self {
276        Self::from_tri(value)
277    }
278}
279
280impl<T: Num> From<Quad<T>> for Polygon<T> {
281    #[inline]
282    fn from(value: Quad<T>) -> Self {
283        Self::from_quad(value)
284    }
285}
286
287impl<T: Num> Numeric for Polygon<T> {
288    type AsU8 = Polygon<u8>;
289    type AsU16 = Polygon<u16>;
290    type AsU32 = Polygon<u32>;
291    type AsU64 = Polygon<u64>;
292    type AsU128 = Polygon<u128>;
293    type AsUSize = Polygon<usize>;
294    type AsI8 = Polygon<i8>;
295    type AsI16 = Polygon<i16>;
296    type AsI32 = Polygon<i32>;
297    type AsI64 = Polygon<i64>;
298    type AsI128 = Polygon<i128>;
299    type AsISize = Polygon<isize>;
300    type AsF32 = Polygon<f32>;
301    type AsF64 = Polygon<f64>;
302
303    #[inline]
304    fn to_u8(self) -> Self::AsU8 {
305        self.into_iter().map(Vec2::to_u8).collect()
306    }
307
308    #[inline]
309    fn to_u16(self) -> Self::AsU16 {
310        self.into_iter().map(Vec2::to_u16).collect()
311    }
312
313    #[inline]
314    fn to_u32(self) -> Self::AsU32 {
315        self.into_iter().map(Vec2::to_u32).collect()
316    }
317
318    #[inline]
319    fn to_u64(self) -> Self::AsU64 {
320        self.into_iter().map(Vec2::to_u64).collect()
321    }
322
323    #[inline]
324    fn to_u128(self) -> Self::AsU128 {
325        self.into_iter().map(Vec2::to_u128).collect()
326    }
327
328    #[inline]
329    fn to_usize(self) -> Self::AsUSize {
330        self.into_iter().map(Vec2::to_usize).collect()
331    }
332
333    #[inline]
334    fn to_i8(self) -> Self::AsI8 {
335        self.into_iter().map(Vec2::to_i8).collect()
336    }
337
338    #[inline]
339    fn to_i16(self) -> Self::AsI16 {
340        self.into_iter().map(Vec2::to_i16).collect()
341    }
342
343    #[inline]
344    fn to_i32(self) -> Self::AsI32 {
345        self.into_iter().map(Vec2::to_i32).collect()
346    }
347
348    #[inline]
349    fn to_i64(self) -> Self::AsI64 {
350        self.into_iter().map(Vec2::to_i64).collect()
351    }
352
353    #[inline]
354    fn to_i128(self) -> Self::AsI128 {
355        self.into_iter().map(Vec2::to_i128).collect()
356    }
357
358    #[inline]
359    fn to_isize(self) -> Self::AsISize {
360        self.into_iter().map(Vec2::to_isize).collect()
361    }
362
363    #[inline]
364    fn to_f32(self) -> Self::AsF32 {
365        self.into_iter().map(Vec2::to_f32).collect()
366    }
367
368    #[inline]
369    fn to_f64(self) -> Self::AsF64 {
370        self.into_iter().map(Vec2::to_f64).collect()
371    }
372}