reda_geometry/shape/
path.rs

1// Copyright (c) 2018-2020 Thomas Kramer.
2// SPDX-FileCopyrightText: 2018-2022 Thomas Kramer
3//
4// SPDX-License-Identifier: AGPL-3.0-or-later
5
6//! A point string is a finite sequence of points.
7
8use crate::base::Vec2;
9use crate::shape::Edge;
10use crate::shape::Point;
11pub use crate::traits::DType;
12use crate::traits::TryBoundingBox;
13use std::iter::FromIterator;
14use std::slice::Iter;
15
16use num_traits::Num;
17use num_traits::{Float, NumCast};
18use std::ops::Sub;
19
20use super::Rect;
21
22/// `Path` is essentially a chain of line segments but with a possibly a non-zero width.
23/// It can be thought of the shape resulting by a stroke of a thick pen along the line segments.
24#[derive(Clone, PartialEq, Eq, Hash, Debug)]
25#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
26pub struct Path<T> {
27    /// The vertices of the path which define the sequence of line segments.
28    pub points: PointList<T>,
29    /// Width of the path.
30    pub width: T,
31    /// Type of the path endings.
32    pub path_type: PathEndType<T>,
33}
34
35/// Encoding for the type of the beginning and end of the path.
36#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
37#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
38pub enum PathEndType<T> {
39    Flat,
40    Extended(T, T),
41    Round,
42}
43
44#[derive(Clone, Debug, PartialEq, Eq, Hash)]
45#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
46pub struct PointList<T> {
47    /// The points defining this point string.
48    pub points: Vec<Point<T>>,
49}
50
51impl<T> PointList<T> {
52    /// Get the number of vertices.
53    pub fn len(&self) -> usize {
54        self.points.len()
55    }
56
57    /// Check if string has zero length.
58    pub fn is_empty(&self) -> bool {
59        self.points.is_empty()
60    }
61}
62
63impl<T: Copy> PointList<T> {
64    /// Create new point string by taking vertices from a type that implements `Into<PointList<T>>`.
65    pub fn new<I>(i: I) -> Self
66    where
67        I: Into<Self>,
68    {
69        i.into()
70    }
71
72    /// Shortcut for `self.points.iter()`.
73    pub fn iter(&self) -> Iter<Point<T>> {
74        self.points.iter()
75    }
76
77    /// Get the sequence of edges of the point string starting from the first point to the last.
78    /// # Examples
79    ///
80    /// ```
81    /// use reda_geometry::shape::PointList;
82    /// use reda_geometry::shape::Edge;
83    /// let coords = vec![(0, 0), (1, 0), (2, 0)];
84    ///
85    /// let point_string = PointList::new(coords);
86    ///
87    /// let edges: Vec<_> = point_string.edges().collect();
88    ///
89    /// assert_eq!(edges, vec![Edge::new((0, 0), (1, 0)), Edge::new((1, 0), (2, 0))]);
90    /// ```
91    pub fn edges(&self) -> impl Iterator<Item = Edge<T>> + '_ {
92        self.iter()
93            .zip(self.iter().skip(1))
94            .map(|(a, b)| Edge::new(a, b))
95    }
96
97    /// Same as `edges` but in reverse order.
98    /// Get the sequence of edges of the point string starting from the last point to the first.
99    /// # Examples
100    ///
101    /// ```
102    /// use reda_geometry::shape::PointList;
103    /// use reda_geometry::shape::Edge;
104    /// let coords = vec![(0, 0), (1, 0), (2, 0)];
105    ///
106    /// let point_string = PointList::new(coords);
107    ///
108    /// let edges: Vec<_> = point_string.edges_reversed().collect();
109    ///
110    /// assert_eq!(edges, vec![Edge::new((2, 0), (1, 0)), Edge::new((1, 0), (0, 0))]);
111    /// ```
112    pub fn edges_reversed(&self) -> impl Iterator<Item = Edge<T>> + '_ {
113        self.iter()
114            .rev()
115            .zip(self.iter().rev().skip(1))
116            .map(|(a, b)| Edge::new(a, b))
117    }
118}
119
120impl<T: Copy + Sub<Output = T> + NumCast> PointList<T> {
121    /// Compute geometrical length of the path defined by the point string.
122    /// # Examples
123    ///
124    /// ```
125    /// use reda_geometry::shape::PointList;
126    /// let coords = vec![(0, 0), (1, 0), (2, 0)];
127    ///
128    /// let point_string = PointList::new(coords);
129    ///
130    /// assert_eq!(point_string.path_length::<f64>(), 2.0);
131    /// ```
132    pub fn path_length<F: Float>(&self) -> F {
133        self.iter()
134            .zip(self.iter().skip(1))
135            .map(|(a, b)| a.distance(b))
136            .fold(F::zero(), |a, b| a + b)
137    }
138}
139
140/// Create a point string from something that can be turned into an iterator of values convertible to [`Point`]s.
141impl<I, T, P> From<I> for PointList<T>
142where
143    T: Copy,
144    I: IntoIterator<Item = P>,
145    Point<T>: From<P>,
146{
147    fn from(iter: I) -> Self {
148        let points: Vec<Point<T>> = iter.into_iter().map(|x| x.into()).collect();
149
150        PointList { points }
151    }
152}
153
154/// Create a point string from a iterator of values convertible to [`Point`]s.
155impl<T, P> FromIterator<P> for PointList<T>
156where
157    T: Copy,
158    P: Into<Point<T>>,
159{
160    fn from_iter<I>(iter: I) -> Self
161    where
162        I: IntoIterator<Item = P>,
163    {
164        let points: Vec<Point<T>> = iter.into_iter().map(|x| x.into()).collect();
165
166        PointList { points }
167    }
168}
169
170impl<T: Copy + PartialOrd + Num> TryBoundingBox<T> for Path<T>
171where
172    T: Copy + PartialOrd,
173{
174    fn try_bounding_box(&self) -> Option<Rect<T>> {
175        let bbox = self.points.try_bounding_box();
176        let _1 = T::one();
177        let _2 = _1 + _1;
178        bbox.map(|bbox| {
179            // Enlarge it by width/2 in all directions to make sure the path is fully contained
180            // in the bounding box.
181            let (p1, p2) = (bbox.lower_left(), bbox.upper_right());
182            let w_half = (self.width + _1) / _2;
183            let width = Vec2::new(w_half, w_half);
184            Rect::new(p1 - width, p2 + width)
185        })
186    }
187}
188
189impl<T> TryBoundingBox<T> for PointList<T>
190where
191    T: Copy + PartialOrd,
192{
193    fn try_bounding_box(&self) -> Option<Rect<T>> {
194        if self.points.is_empty() {
195            None
196        } else {
197            let mut x_min = self.points[0].x;
198            let mut x_max = x_min;
199            let mut y_min = self.points[0].y;
200            let mut y_max = y_min;
201
202            for p in self.iter().skip(1) {
203                let (x, y) = p.into();
204                if x < x_min {
205                    x_min = x;
206                }
207                if x > x_max {
208                    x_max = x;
209                }
210                if y < y_min {
211                    y_min = y;
212                }
213                if y > y_max {
214                    y_max = y;
215                }
216            }
217
218            Some(Rect::new((x_min, y_min), (x_max, y_max)))
219        }
220    }
221}