reda_geometry/shape/
point.rs

1use std::cmp::{Ord, Ordering};
2use std::fmt;
3pub use num_traits::Zero;
4use num_traits::{Float, NumCast};
5pub use std::ops::Deref;
6use std::ops::{Add, AddAssign, DerefMut, Div, Mul, MulAssign, Neg, Sub, SubAssign};
7use crate::base::{Orientation2D, Vec2};
8use crate::traits::{BoundingBox, Cast, MapPoint, TryBoundingBox};
9
10use super::Rect;
11
12#[macro_export]
13macro_rules! point {
14    ($x:expr, $y:expr) => {
15        Point::new($x, $y)
16    };
17}
18
19/// A point is defined by a x and y coordinate in the euclidean plane.
20#[derive(Copy, Clone, Default, Hash, PartialEq, Eq)]
21pub struct Point<T> {
22    /// Store the location as a translation from the origin.
23    location: Vec2<T>,
24}
25
26impl<T> Deref for Point<T> {
27    type Target = Vec2<T>;
28
29    #[inline]
30    fn deref(&self) -> &Self::Target {
31        &self.location
32    }
33}
34
35impl<T> DerefMut for Point<T> {
36    #[inline]
37    fn deref_mut(&mut self) -> &mut Self::Target {
38        &mut self.location
39    }
40}
41
42impl<T> From<Vec2<T>> for Point<T> {
43    #[inline]
44    fn from(v: Vec2<T>) -> Self {
45        Point { location: v }
46    }
47}
48
49impl<T: Copy> From<&Vec2<T>> for Point<T> {
50    #[inline]
51    fn from(v: &Vec2<T>) -> Self {
52        Self::from(*v)
53    }
54}
55
56impl<T> From<Point<T>> for Vec2<T> {
57    #[inline]
58    fn from(p: Point<T>) -> Self {
59        p.location
60    }
61}
62
63impl<T: Copy> From<&Point<T>> for Vec2<T> {
64    #[inline]
65    fn from(p: &Point<T>) -> Self {
66        p.location
67    }
68}
69
70impl<T> Point<T> {
71    /// Create a new point with `x` and `y` coordinates.
72    #[inline]
73    pub fn new(x: T, y: T) -> Self {
74        Point {
75            location: Vec2::new(x, y),
76        }
77    }
78}
79
80impl<T: Copy> Point<T> {
81    #[inline]
82    pub fn vec2(&self) -> Vec2<T> {
83        self.location
84    }
85
86    pub fn get(&self, coord: Orientation2D) -> T {
87        match coord {
88            Orientation2D::Horizontal => self.x,
89            Orientation2D::Vertical => self.y,
90        }
91    }
92
93    pub fn set(&mut self, coord: Orientation2D, value: T) {
94        match coord {
95            Orientation2D::Horizontal => self.x = value,
96            Orientation2D::Vertical => self.y = value,
97        }
98    }
99}
100
101impl<T: Zero> Point<T> {
102    /// Get zero-Point.
103    ///
104    /// # Examples
105    /// ```
106    /// use reda_geometry::shape::Point;
107    ///
108    /// let a = Point::zero();
109    /// let b = Point::new(0, 0);
110    ///
111    /// assert_eq!(a, b);
112    /// ```
113    #[inline]
114    pub fn zero() -> Self {
115        Vec2::zero().into()
116    }
117
118    /// Check if this is the zero-Point.
119    ///
120    /// # Examples
121    /// ```
122    /// use reda_geometry::shape::Point;
123    ///
124    /// assert!(Point::<usize>::zero().is_zero());
125    /// ```
126    #[inline]
127    pub fn is_zero(&self) -> bool {
128        self.x.is_zero() && self.y.is_zero()
129    }
130}
131
132impl<T: Copy + Mul<Output = T> + Add<Output = T> + Sub<Output = T>> Point<T> {
133    /// Compute the squared distance to the `other` point.
134    ///
135    /// # Examples
136    /// ```
137    /// use reda_geometry::shape::Point;
138    ///
139    /// let a = Point::new(0, 0);
140    /// let b = Point::new(2, 0);
141    /// assert_eq!(a.distance_sq(&b), 2*2);
142    /// ```
143    #[inline]
144    pub fn distance_sq(self, other: &Point<T>) -> T {
145        let diff = self - *other;
146        diff.norm2_squared()
147    }
148
149    /// Calculate the cross product of the two vec2s defined by three points.
150    ///
151    /// A positive value implies that `self` → `a` → `b` is counter-clockwise, negative implies
152    /// clockwise.
153    ///
154    /// (`b` - `self`) x (`c` - `b`)
155    ///
156    /// # Examples
157    ///
158    /// ```
159    /// use reda_geometry::shape::Point;
160    ///
161    /// let a = Point::new(1,0);
162    /// let b = Point::new(1,1);
163    /// let c = Point::new(0,1);
164    ///
165    /// let p = a.cross_prod3(b, c);
166    ///
167    /// assert_eq!(p, (b-a).cross_prod(c - b));
168    /// ```
169    #[inline]
170    pub fn cross_prod3(&self, b: Point<T>, c: Point<T>) -> T {
171        (b.x - self.x) * (c.y - b.y) - (b.y - self.y) * (c.x - b.x)
172    }
173}
174
175impl<T: Copy + Sub<Output = T> + NumCast> Point<T> {
176    /// Compute the Euclidean distance betwen two points.
177    #[inline]
178    pub fn distance<F: Float>(self, other: &Point<T>) -> F {
179        let diff = self - *other;
180        diff.length()
181    }
182}
183
184/// Compare points.
185///
186/// The ordering is determined by the x-coordinates. If it is the same
187/// for both points the y-coordinate is used.
188///
189/// Point `a` > Point `b` iff `a.x > b.x || (a.x == b.x && a.y > b.y)`.
190impl<T: PartialOrd> PartialOrd for Point<T> {
191    #[inline]
192    fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
193        match self.x.partial_cmp(&rhs.x) {
194            Some(Ordering::Equal) => self.y.partial_cmp(&rhs.y),
195            maybe_ordering => maybe_ordering,
196        }
197    }
198}
199
200/// Compare points.
201///
202/// The ordering is determined by the x-coordinates. If it is the same
203/// for both points the y-coordinate is used.
204///
205/// Point `a` > Point `b` iff `a.x > b.x || (a.x == b.x && a.y > b.y)`.
206impl<T: Ord> Ord for Point<T> {
207    fn cmp(&self, rhs: &Self) -> Ordering {
208        match self.x.cmp(&rhs.x) {
209            Ordering::Equal => self.y.cmp(&rhs.y),
210            ordering => ordering,
211        }
212    }
213}
214
215impl<T: Copy> From<Point<T>> for (T, T) {
216    #[inline]
217    fn from(p: Point<T>) -> Self {
218        (p.x, p.y)
219    }
220}
221
222impl<T: Copy> From<&Point<T>> for (T, T) {
223    #[inline]
224    fn from(p: &Point<T>) -> Self {
225        (p.x, p.y)
226    }
227}
228
229impl<T: Copy> From<(T, T)> for Point<T> {
230    #[inline]
231    fn from(coords: (T, T)) -> Self {
232        Point::new(coords.0, coords.1)
233    }
234}
235
236impl<'a, T: Copy> From<&'a (T, T)> for Point<T> {
237    #[inline]
238    fn from(coords: &'a (T, T)) -> Self {
239        Point::new(coords.0, coords.1)
240    }
241}
242
243impl<'a, T: Copy> From<&'a Point<T>> for Point<T> {
244    #[inline]
245    fn from(v: &'a Point<T>) -> Self {
246        Point::new(v.x, v.y)
247    }
248}
249
250impl<T: Copy> From<[T; 2]> for Point<T> {
251    #[inline]
252    fn from(coords: [T; 2]) -> Self {
253        Point::new(coords[0], coords[1])
254    }
255}
256
257impl<T: Copy> From<Point<T>> for [T; 2] {
258    #[inline]
259    fn from(p: Point<T>) -> Self {
260        [p.x, p.y]
261    }
262}
263
264impl<T> fmt::Debug for Point<T>
265where
266    T: fmt::Debug,
267{
268    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
269        write!(f, "Point({:?}, {:?})", self.x, self.y)
270    }
271}
272
273impl<T> fmt::Display for Point<T>
274where
275    T: fmt::Display,
276{
277    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
278        write!(f, "({}, {})", self.x, self.y)
279    }
280}
281
282impl<T: Copy + NumCast> Point<T> {
283    /// Convert Point into a Point with floating point data type.
284    #[inline]
285    pub fn cast_to_float<F: Float + NumCast>(&self) -> Point<F> {
286        // TODO: find conversion that does not panic for sure.
287        Point::new(F::from(self.x).unwrap(), F::from(self.y).unwrap())
288    }
289}
290
291impl<T, V> Add<V> for Point<T>
292where
293    T: Copy + Add<Output = T>,
294    V: Into<Point<T>>,
295{
296    type Output = Self;
297
298    #[inline]
299    fn add(self, rhs: V) -> Self {
300        let rhs = rhs.into();
301        Point::new(self.x + rhs.x, self.y + rhs.y)
302    }
303}
304
305impl<T, V> AddAssign<V> for Point<T>
306where
307    T: Copy + AddAssign<T>,
308    V: Into<Vec2<T>>,
309{
310    #[inline]
311    fn add_assign(&mut self, rhs: V) {
312        let rhs = rhs.into();
313        self.location += rhs;
314    }
315}
316
317impl<T> Sub<Point<T>> for Point<T>
318where
319    T: Copy + Sub<Output = T>,
320{
321    type Output = Vec2<T>;
322
323    #[inline]
324    fn sub(self, rhs: Point<T>) -> Self::Output {
325        Vec2::new(self.x - rhs.x, self.y - rhs.y)
326    }
327}
328
329impl<T> Sub<Vec2<T>> for Point<T>
330where
331    T: Copy + Sub<Output = T>,
332{
333    type Output = Point<T>;
334
335    #[inline]
336    fn sub(self, rhs: Vec2<T>) -> Self::Output {
337        Point::new(self.x - rhs.x, self.y - rhs.y)
338    }
339}
340
341impl<T, V> SubAssign<V> for Point<T>
342where
343    T: Copy + SubAssign<T>,
344    V: Into<Vec2<T>>,
345{
346    #[inline]
347    fn sub_assign(&mut self, rhs: V) {
348        let rhs = rhs.into();
349        self.location -= rhs;
350    }
351}
352
353impl<T> Neg for Point<T>
354where
355    T: Copy + Neg<Output = T>,
356{
357    type Output = Self;
358
359    #[inline]
360    fn neg(self) -> Self {
361        Point::new(-self.x, -self.y)
362    }
363}
364
365impl<T> Mul<T> for Point<T>
366where
367    T: Copy + Mul<Output = T>,
368{
369    type Output = Self;
370
371    #[inline]
372    fn mul(self, rhs: T) -> Self {
373        Point::new(self.x * rhs, self.y * rhs)
374    }
375}
376
377impl<T> MulAssign<T> for Point<T>
378where
379    T: Copy + MulAssign<T>,
380{
381    #[inline]
382    fn mul_assign(&mut self, rhs: T) {
383        self.location *= rhs;
384    }
385}
386
387/// Scalar division.
388impl<T> Div<T> for Point<T>
389where
390    T: Copy + Div<Output = T>,
391{
392    type Output = Self;
393
394    #[inline]
395    fn div(self, rhs: T) -> Self {
396        Point::new(self.x / rhs, self.y / rhs)
397    }
398}
399
400impl<T: Copy + Zero + Add<Output = T>> std::iter::Sum for Point<T> {
401    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
402        iter.fold(Self::zero(), |acc, p| acc + p)
403    }
404}
405
406impl<T: Copy> MapPoint<T> for Point<T> {
407    fn transform<F>(&self, transformate: F) -> Self
408        where 
409            F: Fn(Point<T>) -> Point<T> 
410    {
411        transformate(*self)
412    }
413}
414
415impl<T: Copy> BoundingBox<T> for Point<T> {
416    fn bounding_box(&self) -> Rect<T> {
417        Rect {
418            lower_left: *self,
419            upper_right: *self,
420        }
421    }
422}
423
424impl<T: Copy> TryBoundingBox<T> for Point<T> {
425    fn try_bounding_box(&self) -> Option<Rect<T>> {
426        Some(self.bounding_box())
427    }
428}
429
430impl<Src: Copy + NumCast, Dst: Copy + NumCast> Cast<Src, Dst> for Point<Src> {
431    type Output = Point<Dst>;
432
433    fn try_cast(&self) -> Option<Self::Output> {
434        match (Dst::from(self.x), Dst::from(self.y)) {
435            (Some(x), Some(y)) => Some(Point::new(x, y)),
436            _ => None,
437        }
438    }
439}