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