reda_geometry/base/
vec2.rs

1use std::{fmt, ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign}};
2use num_traits::{Float, NumCast, Zero};
3use crate::base::Orientation;
4
5#[derive(Copy, Clone, Default, PartialEq, Eq, Hash)]
6#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
7pub struct Vec2<T> {
8    pub x: T,
9    pub y: T,
10}
11
12impl<T: Zero> Vec2<T> {
13    pub fn zero() -> Self {
14        Self {
15            x: T::zero(),
16            y: T::zero(),
17        }
18    }
19
20    pub fn is_zero(&self) -> bool {
21        self.x.is_zero() && self.y.is_zero()
22    }
23}
24
25#[macro_export]
26macro_rules! vec2 {
27    ($x:expr, $y:expr) => {
28        Vec2::new($x, $y)
29    };
30}
31
32impl<T: Copy> From<Vec2<T>> for (T, T) {
33    #[inline]
34    fn from(v: Vec2<T>) -> Self {
35        (v.x, v.y)
36    }
37}
38
39impl<T: Copy> From<&Vec2<T>> for (T, T) {
40    #[inline]
41    fn from(v: &Vec2<T>) -> Self {
42        (v.x, v.y)
43    }
44}
45
46impl<T> Vec2<T> {
47    /// Create a new vec2 with `x` and `y` coordinates.
48    /// # Examples
49    /// ```
50    /// use reda_geometry::base::Vec2;
51    /// let a = Vec2::new(2, 3);
52    /// assert_eq!(a.x, 2);
53    /// assert_eq!(a.y, 3);
54    /// ```
55    pub fn new(x: T, y: T) -> Self {
56        Vec2 { x, y }
57    }
58}
59
60impl<T: Copy + Zero + PartialOrd + Sub<Output = T>> Vec2<T> {
61    /// Get 1-norm of vec2, i.e. the sum of the absolute values of its components.
62    ///
63    /// # Examples
64    /// ```
65    /// use reda_geometry::base::Vec2;
66    /// let a = Vec2::new(-2, 3);
67    /// assert_eq!(a.norm1(), 5);
68    /// ```
69    pub fn norm1(&self) -> T {
70        let xabs = if self.x < T::zero() {
71            T::zero() - self.x
72        } else {
73            self.x
74        };
75
76        let yabs = if self.y < T::zero() {
77            T::zero() - self.y
78        } else {
79            self.y
80        };
81
82        xabs + yabs
83    }
84}
85
86impl<T: Copy + Zero + PartialOrd + Mul<Output = T> + Sub<Output = T>> Vec2<T> {
87    /// Check if `other` is oriented clockwise or counter-clockwise respective to `self`.
88    ///
89    /// # Examples
90    ///
91    /// ```
92    /// use reda_geometry::base::Vec2;
93    /// use reda_geometry::base::Orientation;
94    ///
95    /// let a = Vec2::new(1, 0);
96    /// let b = Vec2::new(1, 1);
97    /// let c = Vec2::new(1, -1);
98    /// let d = Vec2::new(2, 0);
99    ///
100    /// assert_eq!(a.orientation_of(b), Orientation::CounterClockWise);
101    /// assert_eq!(a.orientation_of(c), Orientation::ClockWise);
102    /// assert_eq!(a.orientation_of(d), Orientation::Straight);
103    /// ```
104    pub fn orientation_of(&self, other: Self) -> Orientation {
105        let p = self.cross_prod(other);
106
107        if p < T::zero() {
108            Orientation::ClockWise
109        } else if p > T::zero() {
110            Orientation::CounterClockWise
111        } else {
112            Orientation::Straight
113        }
114    }
115}
116
117impl<T: Copy + Mul<Output = T> + Sub<Output = T>> Vec2<T> {
118    /// Calculate cross product.
119    ///
120    /// # Examples
121    ///
122    /// ```
123    /// use reda_geometry::base::Vec2;
124    ///
125    /// let a = Vec2::new(2, 0);
126    /// let b = Vec2::new(0, 2);
127    ///
128    /// assert_eq!(a.cross_prod(b), 4);
129    /// assert_eq!(b.cross_prod(a), -4);
130    /// ```
131    #[inline]
132    pub fn cross_prod(&self, other: Self) -> T {
133        self.x * other.y - other.x * self.y
134    }
135}
136
137impl<T: Copy + Mul<Output = T> + Add<Output = T>> Vec2<T> {
138    /// Get squared 2-norm of vec2.
139    ///
140    /// # Examples
141    /// ```
142    /// use reda_geometry::base::Vec2;
143    /// let a = Vec2::new(2, 3);
144    /// assert_eq!(a.norm2_squared(), 2*2+3*3);
145    /// ```
146    #[inline]
147    pub fn norm2_squared(&self) -> T {
148        self.x * self.x + self.y * self.y
149    }
150
151    /// Calculate scalar product.
152    ///
153    /// # Examples
154    ///
155    /// ```
156    /// use reda_geometry::base::Vec2;
157    ///
158    /// let a = Vec2::new(1, 2);
159    /// let b = Vec2::new(3, 4);
160    ///
161    /// assert_eq!(a.dot(b), 1*3 + 2*4);
162    /// ```
163    pub fn dot(&self, other: Self) -> T {
164        self.x * other.x + self.y * other.y
165    }
166}
167
168
169impl<T> Vec2<T>
170where
171    T: Copy + Float + Mul<Output = T> + Add<Output = T>,
172{
173    /// Get 2-norm of vec2 (length of vec2).
174    ///
175    /// # Examples
176    /// ```
177    /// use reda_geometry::base::Vec2;
178    /// let a = Vec2::new(2.0, 3.0);
179    /// let norm2 = a.norm2();
180    /// let norm2_sq = norm2 * norm2;
181    /// let expected = a.norm2_squared();
182    /// assert!(norm2_sq < expected + 1e-12);
183    /// assert!(norm2_sq > expected - 1e-12);
184    /// ```
185    #[inline]
186    pub fn norm2(&self) -> T {
187        (self.norm2_squared()).sqrt()
188    }
189
190    /// Return a vec2 with the same direction but length 1.
191    ///
192    /// # Panics
193    /// Panics if the vec2 has length 0.
194    #[inline]
195    pub fn normalized(&self) -> Self {
196        *self / self.norm2()
197    }
198}
199
200impl<T: Copy + NumCast> Vec2<T> {
201    /// Calculate length of vec2.
202    ///
203    /// Similar to `Vec2::norm2` but does potentially return another data type for the length.
204    ///
205    /// # Examples
206    /// ```
207    /// use reda_geometry::base::Vec2;
208    /// let a = Vec2::new(2.0, 3.0);
209    /// let length: f64 = a.length();
210    /// let norm2_sq = length * length;
211    /// let expected = a.norm2_squared();
212    /// assert!(norm2_sq < expected + 1e-12);
213    /// assert!(norm2_sq > expected - 1e-12);
214    /// ```
215    #[inline]
216    pub fn length<F: Float>(&self) -> F {
217        let x = F::from(self.x).unwrap();
218        let y = F::from(self.y).unwrap();
219
220        x.hypot(y)
221    }
222}
223
224impl<T> Vec2<T>
225where
226    T: Copy + NumCast,
227{
228    /// Convert vec2 into a vec2 with floating point data type.
229    #[inline]
230    pub fn to_float<F>(&self) -> Vec2<F>
231    where
232        F: Float + NumCast,
233    {
234        Vec2 {
235            x: F::from(self.x).unwrap(),
236            y: F::from(self.y).unwrap(),
237        }
238    }
239}
240
241impl<T> Add for Vec2<T>
242where
243    T: Add<Output = T>,
244{
245    type Output = Self;
246
247    #[inline]
248    fn add(self, rhs: Self) -> Self {
249        Vec2 {
250            x: self.x + rhs.x,
251            y: self.y + rhs.y,
252        }
253    }
254}
255
256impl<T> AddAssign for Vec2<T>
257where
258    T: AddAssign,
259{
260    #[inline]
261    fn add_assign(&mut self, rhs: Self) {
262        self.x += rhs.x;
263        self.y += rhs.y;
264    }
265}
266
267/// Vec2 subtraction.
268impl<T> Sub for Vec2<T>
269where
270    T: Sub<Output = T>,
271{
272    type Output = Self;
273
274    #[inline]
275    fn sub(self, rhs: Self) -> Self {
276        Vec2 {
277            x: self.x - rhs.x,
278            y: self.y - rhs.y,
279        }
280    }
281}
282
283impl<T> SubAssign for Vec2<T>
284where
285    T: SubAssign,
286{
287    #[inline]
288    fn sub_assign(&mut self, rhs: Self) {
289        self.x -= rhs.x;
290        self.y -= rhs.y;
291    }
292}
293
294impl<T> Neg for Vec2<T>
295where
296    T: Neg<Output = T>,
297{
298    type Output = Self;
299
300    #[inline]
301    fn neg(self) -> Self {
302        Vec2 {
303            x: -self.x,
304            y: -self.y,
305        }
306    }
307}
308
309/// Scalar multiplication.
310impl<T, M> Mul<M> for Vec2<T>
311where
312    T: Mul<M, Output = T>,
313    M: Copy,
314{
315    type Output = Self;
316
317    fn mul(self, rhs: M) -> Self {
318        Vec2 {
319            x: self.x * rhs,
320            y: self.y * rhs,
321        }
322    }
323}
324
325/// In-place scalar multiplication.
326impl<T, M> MulAssign<M> for Vec2<T>
327where
328    T: Copy + MulAssign<M>,
329    M: Copy,
330{
331    #[inline]
332    fn mul_assign(&mut self, rhs: M) {
333        self.x *= rhs;
334        self.y *= rhs;
335    }
336}
337
338/// Scalar division.
339impl<T, D> Div<D> for Vec2<T>
340where
341    T: Copy + Div<D, Output = T>,
342    D: Copy,
343{
344    type Output = Self;
345
346    #[inline]
347    fn div(self, rhs: D) -> Self {
348        Vec2 {
349            x: self.x / rhs,
350            y: self.y / rhs,
351        }
352    }
353}
354
355/// Assigning scalar division.
356impl<T, D> DivAssign<D> for Vec2<T>
357where
358    T: Copy + DivAssign<D>,
359    D: Copy,
360{
361    #[inline]
362    fn div_assign(&mut self, rhs: D) {
363        self.x /= rhs;
364        self.y /= rhs;
365    }
366}
367
368/// Compute the sum of all vec2s in the iterator.
369/// If the iterator is empty, (0, 0) is returned.
370impl<T> std::iter::Sum for Vec2<T>
371where
372    T: Zero + Add<Output = T>,
373{
374    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
375        iter.fold(Self::zero(), |acc, v| acc + v)
376    }
377}
378
379
380impl<T: Copy> From<(T, T)> for Vec2<T> {
381    #[inline]
382    fn from(coords: (T, T)) -> Self {
383        Vec2::new(coords.0, coords.1)
384    }
385}
386
387impl<'a, T: Copy> From<&'a (T, T)> for Vec2<T> {
388    #[inline]
389    fn from(coords: &'a (T, T)) -> Self {
390        Vec2::new(coords.0, coords.1)
391    }
392}
393
394impl<'a, T: Copy> From<&'a Vec2<T>> for Vec2<T> {
395    #[inline]
396    fn from(v: &'a Vec2<T>) -> Self {
397        Vec2::new(v.x, v.y)
398    }
399}
400
401impl<T: Copy> From<[T; 2]> for Vec2<T> {
402    #[inline]
403    fn from(coords: [T; 2]) -> Self {
404        Vec2::new(coords[0], coords[1])
405    }
406}
407
408
409impl<T> fmt::Debug for Vec2<T>
410where
411    T: fmt::Debug,
412{
413    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
414        write!(f, "({:?}, {:?})", &self.x, &self.y)
415    }
416}
417
418impl<T> fmt::Display for Vec2<T>
419where
420    T: fmt::Display + Copy,
421{
422    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
423        write!(f, "({}, {})", self.x, self.y)
424    }
425}
426