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