euclid/
vector.rs

1// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution.
3//
4// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7// option. This file may not be copied, modified, or distributed
8// except according to those terms.
9
10use super::UnknownUnit;
11use crate::approxeq::ApproxEq;
12use crate::approxord::{max, min};
13use crate::length::Length;
14use crate::num::*;
15use crate::point::{point2, point3, Point2D, Point3D};
16use crate::scale::Scale;
17use crate::size::{size2, size3, Size2D, Size3D};
18use crate::transform2d::Transform2D;
19use crate::transform3d::Transform3D;
20use crate::trig::Trig;
21use crate::Angle;
22use core::cmp::{Eq, PartialEq};
23use core::fmt;
24use core::hash::Hash;
25use core::iter::Sum;
26use core::marker::PhantomData;
27use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
28#[cfg(feature = "mint")]
29use mint;
30use num_traits::real::Real;
31use num_traits::{Float, NumCast, Signed};
32#[cfg(feature = "serde")]
33use serde;
34
35#[cfg(feature = "bytemuck")]
36use bytemuck::{Pod, Zeroable};
37
38/// A 2d Vector tagged with a unit.
39#[repr(C)]
40pub struct Vector2D<T, U> {
41    /// The `x` (traditionally, horizontal) coordinate.
42    pub x: T,
43    /// The `y` (traditionally, vertical) coordinate.
44    pub y: T,
45    #[doc(hidden)]
46    pub _unit: PhantomData<U>,
47}
48
49mint_vec!(Vector2D[x, y] = Vector2);
50
51impl<T: Copy, U> Copy for Vector2D<T, U> {}
52
53impl<T: Clone, U> Clone for Vector2D<T, U> {
54    fn clone(&self) -> Self {
55        Vector2D {
56            x: self.x.clone(),
57            y: self.y.clone(),
58            _unit: PhantomData,
59        }
60    }
61}
62
63#[cfg(feature = "serde")]
64impl<'de, T, U> serde::Deserialize<'de> for Vector2D<T, U>
65where
66    T: serde::Deserialize<'de>,
67{
68    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
69    where
70        D: serde::Deserializer<'de>,
71    {
72        let (x, y) = serde::Deserialize::deserialize(deserializer)?;
73        Ok(Vector2D {
74            x,
75            y,
76            _unit: PhantomData,
77        })
78    }
79}
80
81#[cfg(feature = "serde")]
82impl<T, U> serde::Serialize for Vector2D<T, U>
83where
84    T: serde::Serialize,
85{
86    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
87    where
88        S: serde::Serializer,
89    {
90        (&self.x, &self.y).serialize(serializer)
91    }
92}
93
94#[cfg(feature = "arbitrary")]
95impl<'a, T, U> arbitrary::Arbitrary<'a> for Vector2D<T, U>
96where
97    T: arbitrary::Arbitrary<'a>,
98{
99    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
100        let (x, y) = arbitrary::Arbitrary::arbitrary(u)?;
101        Ok(Vector2D {
102            x,
103            y,
104            _unit: PhantomData,
105        })
106    }
107}
108
109#[cfg(feature = "bytemuck")]
110unsafe impl<T: Zeroable, U> Zeroable for Vector2D<T, U> {}
111
112#[cfg(feature = "bytemuck")]
113unsafe impl<T: Pod, U: 'static> Pod for Vector2D<T, U> {}
114
115impl<T: Eq, U> Eq for Vector2D<T, U> {}
116
117impl<T: PartialEq, U> PartialEq for Vector2D<T, U> {
118    fn eq(&self, other: &Self) -> bool {
119        self.x == other.x && self.y == other.y
120    }
121}
122
123impl<T: Hash, U> Hash for Vector2D<T, U> {
124    fn hash<H: core::hash::Hasher>(&self, h: &mut H) {
125        self.x.hash(h);
126        self.y.hash(h);
127    }
128}
129
130impl<T: Zero, U> Zero for Vector2D<T, U> {
131    /// Constructor, setting all components to zero.
132    #[inline]
133    fn zero() -> Self {
134        Vector2D::new(Zero::zero(), Zero::zero())
135    }
136}
137
138impl<T: fmt::Debug, U> fmt::Debug for Vector2D<T, U> {
139    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
140        f.debug_tuple("").field(&self.x).field(&self.y).finish()
141    }
142}
143
144impl<T: Default, U> Default for Vector2D<T, U> {
145    fn default() -> Self {
146        Vector2D::new(Default::default(), Default::default())
147    }
148}
149
150impl<T, U> Vector2D<T, U> {
151    /// Constructor, setting all components to zero.
152    #[inline]
153    pub fn zero() -> Self
154    where
155        T: Zero,
156    {
157        Vector2D::new(Zero::zero(), Zero::zero())
158    }
159
160    /// Constructor, setting all components to one.
161    #[inline]
162    pub fn one() -> Self
163    where
164        T: One,
165    {
166        Vector2D::new(One::one(), One::one())
167    }
168
169    /// Constructor taking scalar values directly.
170    #[inline]
171    pub const fn new(x: T, y: T) -> Self {
172        Vector2D {
173            x,
174            y,
175            _unit: PhantomData,
176        }
177    }
178
179    /// Constructor setting all components to the same value.
180    #[inline]
181    pub fn splat(v: T) -> Self
182    where
183        T: Clone,
184    {
185        Vector2D {
186            x: v.clone(),
187            y: v,
188            _unit: PhantomData,
189        }
190    }
191
192    /// Constructor taking angle and length
193    pub fn from_angle_and_length(angle: Angle<T>, length: T) -> Self
194    where
195        T: Trig + Mul<Output = T> + Copy,
196    {
197        vec2(length * angle.radians.cos(), length * angle.radians.sin())
198    }
199
200    /// Constructor taking properly  Lengths instead of scalar values.
201    #[inline]
202    pub fn from_lengths(x: Length<T, U>, y: Length<T, U>) -> Self {
203        vec2(x.0, y.0)
204    }
205
206    /// Tag a unit-less value with units.
207    #[inline]
208    pub fn from_untyped(p: Vector2D<T, UnknownUnit>) -> Self {
209        vec2(p.x, p.y)
210    }
211
212    /// Apply the function `f` to each component of this vector.
213    ///
214    /// # Example
215    ///
216    /// This may be used to perform unusual arithmetic which is not already offered as methods.
217    ///
218    /// ```
219    /// use euclid::default::Vector2D;
220    ///
221    /// let p = Vector2D::<u32>::new(5, 11);
222    /// assert_eq!(p.map(|coord| coord.saturating_sub(10)), Vector2D::new(0, 1));
223    /// ```
224    #[inline]
225    pub fn map<V, F: FnMut(T) -> V>(self, mut f: F) -> Vector2D<V, U> {
226        vec2(f(self.x), f(self.y))
227    }
228
229    /// Apply the function `f` to each pair of components of this point and `rhs`.
230    ///
231    /// # Example
232    ///
233    /// This may be used to perform unusual arithmetic which is not already offered as methods.
234    ///
235    /// ```
236    /// use euclid::default::Vector2D;
237    ///
238    /// let a: Vector2D<u8> = Vector2D::new(50, 200);
239    /// let b: Vector2D<u8> = Vector2D::new(100, 100);
240    /// assert_eq!(a.zip(b, u8::saturating_add), Vector2D::new(150, 255));
241    /// ```
242    #[inline]
243    pub fn zip<V, F: FnMut(T, T) -> V>(self, rhs: Self, mut f: F) -> Vector2D<V, U> {
244        vec2(f(self.x, rhs.x), f(self.y, rhs.y))
245    }
246
247    /// Computes the vector with absolute values of each component.
248    ///
249    /// # Example
250    ///
251    /// ```rust
252    /// # use std::{i32, f32};
253    /// # use euclid::vec2;
254    /// enum U {}
255    ///
256    /// assert_eq!(vec2::<_, U>(-1, 2).abs(), vec2(1, 2));
257    ///
258    /// let vec = vec2::<_, U>(f32::NAN, -f32::MAX).abs();
259    /// assert!(vec.x.is_nan());
260    /// assert_eq!(vec.y, f32::MAX);
261    /// ```
262    ///
263    /// # Panics
264    ///
265    /// The behavior for each component follows the scalar type's implementation of
266    /// `num_traits::Signed::abs`.
267    pub fn abs(self) -> Self
268    where
269        T: Signed,
270    {
271        vec2(self.x.abs(), self.y.abs())
272    }
273
274    /// Dot product.
275    #[inline]
276    pub fn dot(self, other: Self) -> T
277    where
278        T: Add<Output = T> + Mul<Output = T>,
279    {
280        self.x * other.x + self.y * other.y
281    }
282
283    /// Returns the norm of the cross product [self.x, self.y, 0] x [other.x, other.y, 0].
284    #[inline]
285    pub fn cross(self, other: Self) -> T
286    where
287        T: Sub<Output = T> + Mul<Output = T>,
288    {
289        self.x * other.y - self.y * other.x
290    }
291
292    /// Returns the component-wise multiplication of the two vectors.
293    #[inline]
294    pub fn component_mul(self, other: Self) -> Self
295    where
296        T: Mul<Output = T>,
297    {
298        vec2(self.x * other.x, self.y * other.y)
299    }
300
301    /// Returns the component-wise division of the two vectors.
302    #[inline]
303    pub fn component_div(self, other: Self) -> Self
304    where
305        T: Div<Output = T>,
306    {
307        vec2(self.x / other.x, self.y / other.y)
308    }
309}
310
311impl<T: Copy, U> Vector2D<T, U> {
312    /// Create a 3d vector from this one, using the specified z value.
313    #[inline]
314    pub fn extend(self, z: T) -> Vector3D<T, U> {
315        vec3(self.x, self.y, z)
316    }
317
318    /// Cast this vector into a point.
319    ///
320    /// Equivalent to adding this vector to the origin.
321    #[inline]
322    pub fn to_point(self) -> Point2D<T, U> {
323        Point2D {
324            x: self.x,
325            y: self.y,
326            _unit: PhantomData,
327        }
328    }
329
330    /// Swap x and y.
331    #[inline]
332    pub fn yx(self) -> Self {
333        vec2(self.y, self.x)
334    }
335
336    /// Cast this vector into a size.
337    #[inline]
338    pub fn to_size(self) -> Size2D<T, U> {
339        size2(self.x, self.y)
340    }
341
342    /// Drop the units, preserving only the numeric value.
343    #[inline]
344    pub fn to_untyped(self) -> Vector2D<T, UnknownUnit> {
345        vec2(self.x, self.y)
346    }
347
348    /// Cast the unit.
349    #[inline]
350    pub fn cast_unit<V>(self) -> Vector2D<T, V> {
351        vec2(self.x, self.y)
352    }
353
354    /// Cast into an array with x and y.
355    #[inline]
356    pub fn to_array(self) -> [T; 2] {
357        [self.x, self.y]
358    }
359
360    /// Cast into a tuple with x and y.
361    #[inline]
362    pub fn to_tuple(self) -> (T, T) {
363        (self.x, self.y)
364    }
365
366    /// Convert into a 3d vector with `z` coordinate equals to `T::zero()`.
367    #[inline]
368    pub fn to_3d(self) -> Vector3D<T, U>
369    where
370        T: Zero,
371    {
372        vec3(self.x, self.y, Zero::zero())
373    }
374
375    /// Rounds each component to the nearest integer value.
376    ///
377    /// This behavior is preserved for negative values (unlike the basic cast).
378    ///
379    /// ```rust
380    /// # use euclid::vec2;
381    /// enum Mm {}
382    ///
383    /// assert_eq!(vec2::<_, Mm>(-0.1, -0.8).round(), vec2::<_, Mm>(0.0, -1.0))
384    /// ```
385    #[inline]
386    #[must_use]
387    pub fn round(self) -> Self
388    where
389        T: Round,
390    {
391        vec2(self.x.round(), self.y.round())
392    }
393
394    /// Rounds each component to the smallest integer equal or greater than the original value.
395    ///
396    /// This behavior is preserved for negative values (unlike the basic cast).
397    ///
398    /// ```rust
399    /// # use euclid::vec2;
400    /// enum Mm {}
401    ///
402    /// assert_eq!(vec2::<_, Mm>(-0.1, -0.8).ceil(), vec2::<_, Mm>(0.0, 0.0))
403    /// ```
404    #[inline]
405    #[must_use]
406    pub fn ceil(self) -> Self
407    where
408        T: Ceil,
409    {
410        vec2(self.x.ceil(), self.y.ceil())
411    }
412
413    /// Rounds each component to the biggest integer equal or lower than the original value.
414    ///
415    /// This behavior is preserved for negative values (unlike the basic cast).
416    ///
417    /// ```rust
418    /// # use euclid::vec2;
419    /// enum Mm {}
420    ///
421    /// assert_eq!(vec2::<_, Mm>(-0.1, -0.8).floor(), vec2::<_, Mm>(-1.0, -1.0))
422    /// ```
423    #[inline]
424    #[must_use]
425    pub fn floor(self) -> Self
426    where
427        T: Floor,
428    {
429        vec2(self.x.floor(), self.y.floor())
430    }
431
432    /// Returns the signed angle between this vector and the x axis.
433    /// Positive values counted counterclockwise, where 0 is `+x` axis, `PI/2`
434    /// is `+y` axis.
435    ///
436    /// The returned angle is between -PI and PI.
437    pub fn angle_from_x_axis(self) -> Angle<T>
438    where
439        T: Trig,
440    {
441        Angle::radians(Trig::fast_atan2(self.y, self.x))
442    }
443
444    /// Creates translation by this vector in vector units.
445    #[inline]
446    pub fn to_transform(self) -> Transform2D<T, U, U>
447    where
448        T: Zero + One,
449    {
450        Transform2D::translation(self.x, self.y)
451    }
452}
453
454impl<T, U> Vector2D<T, U>
455where
456    T: Copy + Mul<T, Output = T> + Add<T, Output = T>,
457{
458    /// Returns the vector's length squared.
459    #[inline]
460    pub fn square_length(self) -> T {
461        self.x * self.x + self.y * self.y
462    }
463
464    /// Returns this vector projected onto another one.
465    ///
466    /// Projecting onto a nil vector will cause a division by zero.
467    #[inline]
468    pub fn project_onto_vector(self, onto: Self) -> Self
469    where
470        T: Sub<T, Output = T> + Div<T, Output = T>,
471    {
472        onto * (self.dot(onto) / onto.square_length())
473    }
474
475    /// Returns the signed angle between this vector and another vector.
476    ///
477    /// The returned angle is between -PI and PI.
478    pub fn angle_to(self, other: Self) -> Angle<T>
479    where
480        T: Sub<Output = T> + Trig,
481    {
482        Angle::radians(Trig::fast_atan2(self.cross(other), self.dot(other)))
483    }
484}
485
486impl<T: Float, U> Vector2D<T, U> {
487    /// Return the normalized vector even if the length is larger than the max value of Float.
488    #[inline]
489    #[must_use]
490    pub fn robust_normalize(self) -> Self {
491        let length = self.length();
492        if length.is_infinite() {
493            let scaled = self / T::max_value();
494            scaled / scaled.length()
495        } else {
496            self / length
497        }
498    }
499
500    /// Returns `true` if all members are finite.
501    #[inline]
502    pub fn is_finite(self) -> bool {
503        self.x.is_finite() && self.y.is_finite()
504    }
505}
506
507impl<T: Real, U> Vector2D<T, U> {
508    /// Returns the vector length.
509    #[inline]
510    pub fn length(self) -> T {
511        self.square_length().sqrt()
512    }
513
514    /// Returns the vector with length of one unit.
515    #[inline]
516    #[must_use]
517    pub fn normalize(self) -> Self {
518        self / self.length()
519    }
520
521    /// Returns the vector with length of one unit.
522    ///
523    /// Unlike [`Vector2D::normalize`], this returns `None` in the case that the
524    /// length of the vector is zero.
525    #[inline]
526    #[must_use]
527    pub fn try_normalize(self) -> Option<Self> {
528        let len = self.length();
529        if len == T::zero() {
530            None
531        } else {
532            Some(self / len)
533        }
534    }
535
536    /// Return this vector scaled to fit the provided length.
537    #[inline]
538    pub fn with_length(self, length: T) -> Self {
539        self.normalize() * length
540    }
541
542    /// Return this vector capped to a maximum length.
543    #[inline]
544    pub fn with_max_length(self, max_length: T) -> Self {
545        let square_length = self.square_length();
546        if square_length > max_length * max_length {
547            return self * (max_length / square_length.sqrt());
548        }
549
550        self
551    }
552
553    /// Return this vector with a minimum length applied.
554    #[inline]
555    pub fn with_min_length(self, min_length: T) -> Self {
556        let square_length = self.square_length();
557        if square_length < min_length * min_length {
558            return self * (min_length / square_length.sqrt());
559        }
560
561        self
562    }
563
564    /// Return this vector with minimum and maximum lengths applied.
565    #[inline]
566    pub fn clamp_length(self, min: T, max: T) -> Self {
567        debug_assert!(min <= max);
568        self.with_min_length(min).with_max_length(max)
569    }
570}
571
572impl<T, U> Vector2D<T, U>
573where
574    T: Copy + One + Add<Output = T> + Sub<Output = T> + Mul<Output = T>,
575{
576    /// Linearly interpolate each component between this vector and another vector.
577    ///
578    /// # Example
579    ///
580    /// ```rust
581    /// use euclid::vec2;
582    /// use euclid::default::Vector2D;
583    ///
584    /// let from: Vector2D<_> = vec2(0.0, 10.0);
585    /// let to:  Vector2D<_> = vec2(8.0, -4.0);
586    ///
587    /// assert_eq!(from.lerp(to, -1.0), vec2(-8.0,  24.0));
588    /// assert_eq!(from.lerp(to,  0.0), vec2( 0.0,  10.0));
589    /// assert_eq!(from.lerp(to,  0.5), vec2( 4.0,   3.0));
590    /// assert_eq!(from.lerp(to,  1.0), vec2( 8.0,  -4.0));
591    /// assert_eq!(from.lerp(to,  2.0), vec2(16.0, -18.0));
592    /// ```
593    #[inline]
594    pub fn lerp(self, other: Self, t: T) -> Self {
595        let one_t = T::one() - t;
596        self * one_t + other * t
597    }
598
599    /// Returns a reflection vector using an incident ray and a surface normal.
600    #[inline]
601    pub fn reflect(self, normal: Self) -> Self {
602        let two = T::one() + T::one();
603        self - normal * two * self.dot(normal)
604    }
605}
606
607impl<T: PartialOrd, U> Vector2D<T, U> {
608    /// Returns the vector each component of which are minimum of this vector and another.
609    #[inline]
610    pub fn min(self, other: Self) -> Self {
611        vec2(min(self.x, other.x), min(self.y, other.y))
612    }
613
614    /// Returns the vector each component of which are maximum of this vector and another.
615    #[inline]
616    pub fn max(self, other: Self) -> Self {
617        vec2(max(self.x, other.x), max(self.y, other.y))
618    }
619
620    /// Returns the vector each component of which is clamped by corresponding
621    /// components of `start` and `end`.
622    ///
623    /// Shortcut for `self.max(start).min(end)`.
624    #[inline]
625    pub fn clamp(self, start: Self, end: Self) -> Self
626    where
627        T: Copy,
628    {
629        self.max(start).min(end)
630    }
631
632    /// Returns vector with results of "greater than" operation on each component.
633    #[inline]
634    pub fn greater_than(self, other: Self) -> BoolVector2D {
635        BoolVector2D {
636            x: self.x > other.x,
637            y: self.y > other.y,
638        }
639    }
640
641    /// Returns vector with results of "lower than" operation on each component.
642    #[inline]
643    pub fn lower_than(self, other: Self) -> BoolVector2D {
644        BoolVector2D {
645            x: self.x < other.x,
646            y: self.y < other.y,
647        }
648    }
649}
650
651impl<T: PartialEq, U> Vector2D<T, U> {
652    /// Returns vector with results of "equal" operation on each component.
653    #[inline]
654    pub fn equal(self, other: Self) -> BoolVector2D {
655        BoolVector2D {
656            x: self.x == other.x,
657            y: self.y == other.y,
658        }
659    }
660
661    /// Returns vector with results of "not equal" operation on each component.
662    #[inline]
663    pub fn not_equal(self, other: Self) -> BoolVector2D {
664        BoolVector2D {
665            x: self.x != other.x,
666            y: self.y != other.y,
667        }
668    }
669}
670
671impl<T: NumCast + Copy, U> Vector2D<T, U> {
672    /// Cast from one numeric representation to another, preserving the units.
673    ///
674    /// When casting from floating vector to integer coordinates, the decimals are truncated
675    /// as one would expect from a simple cast, but this behavior does not always make sense
676    /// geometrically. Consider using `round()`, `ceil()` or `floor()` before casting.
677    #[inline]
678    pub fn cast<NewT: NumCast>(self) -> Vector2D<NewT, U> {
679        self.try_cast().unwrap()
680    }
681
682    /// Fallible cast from one numeric representation to another, preserving the units.
683    ///
684    /// When casting from floating vector to integer coordinates, the decimals are truncated
685    /// as one would expect from a simple cast, but this behavior does not always make sense
686    /// geometrically. Consider using `round()`, `ceil()` or `floor()` before casting.
687    pub fn try_cast<NewT: NumCast>(self) -> Option<Vector2D<NewT, U>> {
688        match (NumCast::from(self.x), NumCast::from(self.y)) {
689            (Some(x), Some(y)) => Some(Vector2D::new(x, y)),
690            _ => None,
691        }
692    }
693
694    // Convenience functions for common casts.
695
696    /// Cast into an `f32` vector.
697    #[inline]
698    pub fn to_f32(self) -> Vector2D<f32, U> {
699        self.cast()
700    }
701
702    /// Cast into an `f64` vector.
703    #[inline]
704    pub fn to_f64(self) -> Vector2D<f64, U> {
705        self.cast()
706    }
707
708    /// Cast into an `usize` vector, truncating decimals if any.
709    ///
710    /// When casting from floating vector vectors, it is worth considering whether
711    /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain
712    /// the desired conversion behavior.
713    #[inline]
714    pub fn to_usize(self) -> Vector2D<usize, U> {
715        self.cast()
716    }
717
718    /// Cast into an `u32` vector, truncating decimals if any.
719    ///
720    /// When casting from floating vector vectors, it is worth considering whether
721    /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain
722    /// the desired conversion behavior.
723    #[inline]
724    pub fn to_u32(self) -> Vector2D<u32, U> {
725        self.cast()
726    }
727
728    /// Cast into an i32 vector, truncating decimals if any.
729    ///
730    /// When casting from floating vector vectors, it is worth considering whether
731    /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain
732    /// the desired conversion behavior.
733    #[inline]
734    pub fn to_i32(self) -> Vector2D<i32, U> {
735        self.cast()
736    }
737
738    /// Cast into an i64 vector, truncating decimals if any.
739    ///
740    /// When casting from floating vector vectors, it is worth considering whether
741    /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain
742    /// the desired conversion behavior.
743    #[inline]
744    pub fn to_i64(self) -> Vector2D<i64, U> {
745        self.cast()
746    }
747}
748
749impl<T: Neg, U> Neg for Vector2D<T, U> {
750    type Output = Vector2D<T::Output, U>;
751
752    #[inline]
753    fn neg(self) -> Self::Output {
754        vec2(-self.x, -self.y)
755    }
756}
757
758impl<T: Add, U> Add for Vector2D<T, U> {
759    type Output = Vector2D<T::Output, U>;
760
761    #[inline]
762    fn add(self, other: Self) -> Self::Output {
763        Vector2D::new(self.x + other.x, self.y + other.y)
764    }
765}
766
767impl<T: Add + Copy, U> Add<&Self> for Vector2D<T, U> {
768    type Output = Vector2D<T::Output, U>;
769
770    #[inline]
771    fn add(self, other: &Self) -> Self::Output {
772        Vector2D::new(self.x + other.x, self.y + other.y)
773    }
774}
775
776impl<T: Add<Output = T> + Zero, U> Sum for Vector2D<T, U> {
777    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
778        iter.fold(Self::zero(), Add::add)
779    }
780}
781
782impl<'a, T: 'a + Add<Output = T> + Copy + Zero, U: 'a> Sum<&'a Self> for Vector2D<T, U> {
783    fn sum<I: Iterator<Item = &'a Self>>(iter: I) -> Self {
784        iter.fold(Self::zero(), Add::add)
785    }
786}
787
788impl<T: Copy + Add<T, Output = T>, U> AddAssign for Vector2D<T, U> {
789    #[inline]
790    fn add_assign(&mut self, other: Self) {
791        *self = *self + other
792    }
793}
794
795impl<T: Sub, U> Sub for Vector2D<T, U> {
796    type Output = Vector2D<T::Output, U>;
797
798    #[inline]
799    fn sub(self, other: Self) -> Self::Output {
800        vec2(self.x - other.x, self.y - other.y)
801    }
802}
803
804impl<T: Copy + Sub<T, Output = T>, U> SubAssign<Vector2D<T, U>> for Vector2D<T, U> {
805    #[inline]
806    fn sub_assign(&mut self, other: Self) {
807        *self = *self - other
808    }
809}
810
811impl<T: Copy + Mul, U> Mul<T> for Vector2D<T, U> {
812    type Output = Vector2D<T::Output, U>;
813
814    #[inline]
815    fn mul(self, scale: T) -> Self::Output {
816        vec2(self.x * scale, self.y * scale)
817    }
818}
819
820impl<T: Copy + Mul<T, Output = T>, U> MulAssign<T> for Vector2D<T, U> {
821    #[inline]
822    fn mul_assign(&mut self, scale: T) {
823        *self = *self * scale
824    }
825}
826
827impl<T: Copy + Mul, U1, U2> Mul<Scale<T, U1, U2>> for Vector2D<T, U1> {
828    type Output = Vector2D<T::Output, U2>;
829
830    #[inline]
831    fn mul(self, scale: Scale<T, U1, U2>) -> Self::Output {
832        vec2(self.x * scale.0, self.y * scale.0)
833    }
834}
835
836impl<T: Copy + MulAssign, U> MulAssign<Scale<T, U, U>> for Vector2D<T, U> {
837    #[inline]
838    fn mul_assign(&mut self, scale: Scale<T, U, U>) {
839        self.x *= scale.0;
840        self.y *= scale.0;
841    }
842}
843
844impl<T: Copy + Div, U> Div<T> for Vector2D<T, U> {
845    type Output = Vector2D<T::Output, U>;
846
847    #[inline]
848    fn div(self, scale: T) -> Self::Output {
849        vec2(self.x / scale, self.y / scale)
850    }
851}
852
853impl<T: Copy + Div<T, Output = T>, U> DivAssign<T> for Vector2D<T, U> {
854    #[inline]
855    fn div_assign(&mut self, scale: T) {
856        *self = *self / scale
857    }
858}
859
860impl<T: Copy + Div, U1, U2> Div<Scale<T, U1, U2>> for Vector2D<T, U2> {
861    type Output = Vector2D<T::Output, U1>;
862
863    #[inline]
864    fn div(self, scale: Scale<T, U1, U2>) -> Self::Output {
865        vec2(self.x / scale.0, self.y / scale.0)
866    }
867}
868
869impl<T: Copy + DivAssign, U> DivAssign<Scale<T, U, U>> for Vector2D<T, U> {
870    #[inline]
871    fn div_assign(&mut self, scale: Scale<T, U, U>) {
872        self.x /= scale.0;
873        self.y /= scale.0;
874    }
875}
876
877impl<T: Round, U> Round for Vector2D<T, U> {
878    /// See [`Vector2D::round`].
879    #[inline]
880    fn round(self) -> Self {
881        self.round()
882    }
883}
884
885impl<T: Ceil, U> Ceil for Vector2D<T, U> {
886    /// See [`Vector2D::ceil`].
887    #[inline]
888    fn ceil(self) -> Self {
889        self.ceil()
890    }
891}
892
893impl<T: Floor, U> Floor for Vector2D<T, U> {
894    /// See [`Vector2D::floor`].
895    #[inline]
896    fn floor(self) -> Self {
897        self.floor()
898    }
899}
900
901impl<T: ApproxEq<T>, U> ApproxEq<Vector2D<T, U>> for Vector2D<T, U> {
902    #[inline]
903    fn approx_epsilon() -> Self {
904        vec2(T::approx_epsilon(), T::approx_epsilon())
905    }
906
907    #[inline]
908    fn approx_eq_eps(&self, other: &Self, eps: &Self) -> bool {
909        self.x.approx_eq_eps(&other.x, &eps.x) && self.y.approx_eq_eps(&other.y, &eps.y)
910    }
911}
912
913impl<T, U> From<Vector2D<T, U>> for [T; 2] {
914    fn from(v: Vector2D<T, U>) -> Self {
915        [v.x, v.y]
916    }
917}
918
919impl<T, U> From<[T; 2]> for Vector2D<T, U> {
920    fn from([x, y]: [T; 2]) -> Self {
921        vec2(x, y)
922    }
923}
924
925impl<T, U> From<Vector2D<T, U>> for (T, T) {
926    fn from(v: Vector2D<T, U>) -> Self {
927        (v.x, v.y)
928    }
929}
930
931impl<T, U> From<(T, T)> for Vector2D<T, U> {
932    fn from(tuple: (T, T)) -> Self {
933        vec2(tuple.0, tuple.1)
934    }
935}
936
937impl<T, U> From<Size2D<T, U>> for Vector2D<T, U> {
938    fn from(s: Size2D<T, U>) -> Self {
939        vec2(s.width, s.height)
940    }
941}
942
943/// A 3d Vector tagged with a unit.
944#[repr(C)]
945pub struct Vector3D<T, U> {
946    /// The `x` (traditionally, horizontal) coordinate.
947    pub x: T,
948    /// The `y` (traditionally, vertical) coordinate.
949    pub y: T,
950    /// The `z` (traditionally, depth) coordinate.
951    pub z: T,
952    #[doc(hidden)]
953    pub _unit: PhantomData<U>,
954}
955
956mint_vec!(Vector3D[x, y, z] = Vector3);
957
958impl<T: Copy, U> Copy for Vector3D<T, U> {}
959
960impl<T: Clone, U> Clone for Vector3D<T, U> {
961    fn clone(&self) -> Self {
962        Vector3D {
963            x: self.x.clone(),
964            y: self.y.clone(),
965            z: self.z.clone(),
966            _unit: PhantomData,
967        }
968    }
969}
970
971#[cfg(feature = "serde")]
972impl<'de, T, U> serde::Deserialize<'de> for Vector3D<T, U>
973where
974    T: serde::Deserialize<'de>,
975{
976    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
977    where
978        D: serde::Deserializer<'de>,
979    {
980        let (x, y, z) = serde::Deserialize::deserialize(deserializer)?;
981        Ok(Vector3D {
982            x,
983            y,
984            z,
985            _unit: PhantomData,
986        })
987    }
988}
989
990#[cfg(feature = "serde")]
991impl<T, U> serde::Serialize for Vector3D<T, U>
992where
993    T: serde::Serialize,
994{
995    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
996    where
997        S: serde::Serializer,
998    {
999        (&self.x, &self.y, &self.z).serialize(serializer)
1000    }
1001}
1002
1003#[cfg(feature = "arbitrary")]
1004impl<'a, T, U> arbitrary::Arbitrary<'a> for Vector3D<T, U>
1005where
1006    T: arbitrary::Arbitrary<'a>,
1007{
1008    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
1009        let (x, y, z) = arbitrary::Arbitrary::arbitrary(u)?;
1010        Ok(Vector3D {
1011            x,
1012            y,
1013            z,
1014            _unit: PhantomData,
1015        })
1016    }
1017}
1018
1019#[cfg(feature = "bytemuck")]
1020unsafe impl<T: Zeroable, U> Zeroable for Vector3D<T, U> {}
1021
1022#[cfg(feature = "bytemuck")]
1023unsafe impl<T: Pod, U: 'static> Pod for Vector3D<T, U> {}
1024
1025impl<T: Eq, U> Eq for Vector3D<T, U> {}
1026
1027impl<T: PartialEq, U> PartialEq for Vector3D<T, U> {
1028    fn eq(&self, other: &Self) -> bool {
1029        self.x == other.x && self.y == other.y && self.z == other.z
1030    }
1031}
1032
1033impl<T: Hash, U> Hash for Vector3D<T, U> {
1034    fn hash<H: core::hash::Hasher>(&self, h: &mut H) {
1035        self.x.hash(h);
1036        self.y.hash(h);
1037        self.z.hash(h);
1038    }
1039}
1040
1041impl<T: Zero, U> Zero for Vector3D<T, U> {
1042    /// Constructor, setting all components to zero.
1043    #[inline]
1044    fn zero() -> Self {
1045        vec3(Zero::zero(), Zero::zero(), Zero::zero())
1046    }
1047}
1048
1049impl<T: fmt::Debug, U> fmt::Debug for Vector3D<T, U> {
1050    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1051        f.debug_tuple("")
1052            .field(&self.x)
1053            .field(&self.y)
1054            .field(&self.z)
1055            .finish()
1056    }
1057}
1058
1059impl<T: Default, U> Default for Vector3D<T, U> {
1060    fn default() -> Self {
1061        Vector3D::new(Default::default(), Default::default(), Default::default())
1062    }
1063}
1064
1065impl<T, U> Vector3D<T, U> {
1066    /// Constructor, setting all components to zero.
1067    #[inline]
1068    pub fn zero() -> Self
1069    where
1070        T: Zero,
1071    {
1072        vec3(Zero::zero(), Zero::zero(), Zero::zero())
1073    }
1074
1075    /// Constructor, setting all components to one.
1076    #[inline]
1077    pub fn one() -> Self
1078    where
1079        T: One,
1080    {
1081        vec3(One::one(), One::one(), One::one())
1082    }
1083
1084    /// Constructor taking scalar values directly.
1085    #[inline]
1086    pub const fn new(x: T, y: T, z: T) -> Self {
1087        Vector3D {
1088            x,
1089            y,
1090            z,
1091            _unit: PhantomData,
1092        }
1093    }
1094    /// Constructor setting all components to the same value.
1095    #[inline]
1096    pub fn splat(v: T) -> Self
1097    where
1098        T: Clone,
1099    {
1100        Vector3D {
1101            x: v.clone(),
1102            y: v.clone(),
1103            z: v,
1104            _unit: PhantomData,
1105        }
1106    }
1107
1108    /// Constructor taking properly  Lengths instead of scalar values.
1109    #[inline]
1110    pub fn from_lengths(x: Length<T, U>, y: Length<T, U>, z: Length<T, U>) -> Vector3D<T, U> {
1111        vec3(x.0, y.0, z.0)
1112    }
1113
1114    /// Tag a unitless value with units.
1115    #[inline]
1116    pub fn from_untyped(p: Vector3D<T, UnknownUnit>) -> Self {
1117        vec3(p.x, p.y, p.z)
1118    }
1119
1120    /// Apply the function `f` to each component of this vector.
1121    ///
1122    /// # Example
1123    ///
1124    /// This may be used to perform unusual arithmetic which is not already offered as methods.
1125    ///
1126    /// ```
1127    /// use euclid::default::Vector3D;
1128    ///
1129    /// let p = Vector3D::<u32>::new(5, 11, 15);
1130    /// assert_eq!(p.map(|coord| coord.saturating_sub(10)), Vector3D::new(0, 1, 5));
1131    /// ```
1132    #[inline]
1133    pub fn map<V, F: FnMut(T) -> V>(self, mut f: F) -> Vector3D<V, U> {
1134        vec3(f(self.x), f(self.y), f(self.z))
1135    }
1136
1137    /// Apply the function `f` to each pair of components of this point and `rhs`.
1138    ///
1139    /// # Example
1140    ///
1141    /// This may be used to perform unusual arithmetic which is not already offered as methods.
1142    ///
1143    /// ```
1144    /// use euclid::default::Vector3D;
1145    ///
1146    /// let a: Vector3D<u8> = Vector3D::new(50, 200, 10);
1147    /// let b: Vector3D<u8> = Vector3D::new(100, 100, 0);
1148    /// assert_eq!(a.zip(b, u8::saturating_add), Vector3D::new(150, 255, 10));
1149    /// ```
1150    #[inline]
1151    pub fn zip<V, F: FnMut(T, T) -> V>(self, rhs: Self, mut f: F) -> Vector3D<V, U> {
1152        vec3(f(self.x, rhs.x), f(self.y, rhs.y), f(self.z, rhs.z))
1153    }
1154
1155    /// Computes the vector with absolute values of each component.
1156    ///
1157    /// # Example
1158    ///
1159    /// ```rust
1160    /// # use std::{i32, f32};
1161    /// # use euclid::vec3;
1162    /// enum U {}
1163    ///
1164    /// assert_eq!(vec3::<_, U>(-1, 0, 2).abs(), vec3(1, 0, 2));
1165    ///
1166    /// let vec = vec3::<_, U>(f32::NAN, 0.0, -f32::MAX).abs();
1167    /// assert!(vec.x.is_nan());
1168    /// assert_eq!(vec.y, 0.0);
1169    /// assert_eq!(vec.z, f32::MAX);
1170    /// ```
1171    ///
1172    /// # Panics
1173    ///
1174    /// The behavior for each component follows the scalar type's implementation of
1175    /// `num_traits::Signed::abs`.
1176    pub fn abs(self) -> Self
1177    where
1178        T: Signed,
1179    {
1180        vec3(self.x.abs(), self.y.abs(), self.z.abs())
1181    }
1182
1183    /// Dot product.
1184    #[inline]
1185    pub fn dot(self, other: Self) -> T
1186    where
1187        T: Add<Output = T> + Mul<Output = T>,
1188    {
1189        self.x * other.x + self.y * other.y + self.z * other.z
1190    }
1191}
1192
1193impl<T: Copy, U> Vector3D<T, U> {
1194    /// Cross product.
1195    #[inline]
1196    pub fn cross(self, other: Self) -> Self
1197    where
1198        T: Sub<Output = T> + Mul<Output = T>,
1199    {
1200        vec3(
1201            self.y * other.z - self.z * other.y,
1202            self.z * other.x - self.x * other.z,
1203            self.x * other.y - self.y * other.x,
1204        )
1205    }
1206
1207    /// Returns the component-wise multiplication of the two vectors.
1208    #[inline]
1209    pub fn component_mul(self, other: Self) -> Self
1210    where
1211        T: Mul<Output = T>,
1212    {
1213        vec3(self.x * other.x, self.y * other.y, self.z * other.z)
1214    }
1215
1216    /// Returns the component-wise division of the two vectors.
1217    #[inline]
1218    pub fn component_div(self, other: Self) -> Self
1219    where
1220        T: Div<Output = T>,
1221    {
1222        vec3(self.x / other.x, self.y / other.y, self.z / other.z)
1223    }
1224
1225    /// Cast this vector into a point.
1226    ///
1227    /// Equivalent to adding this vector to the origin.
1228    #[inline]
1229    pub fn to_point(self) -> Point3D<T, U> {
1230        point3(self.x, self.y, self.z)
1231    }
1232
1233    /// Returns a 2d vector using this vector's x and y coordinates
1234    #[inline]
1235    pub fn xy(self) -> Vector2D<T, U> {
1236        vec2(self.x, self.y)
1237    }
1238
1239    /// Returns a 2d vector using this vector's x and z coordinates
1240    #[inline]
1241    pub fn xz(self) -> Vector2D<T, U> {
1242        vec2(self.x, self.z)
1243    }
1244
1245    /// Returns a 2d vector using this vector's x and z coordinates
1246    #[inline]
1247    pub fn yz(self) -> Vector2D<T, U> {
1248        vec2(self.y, self.z)
1249    }
1250
1251    /// Cast into an array with x, y and z.
1252    #[inline]
1253    pub fn to_array(self) -> [T; 3] {
1254        [self.x, self.y, self.z]
1255    }
1256
1257    /// Cast into an array with x, y, z and 0.
1258    #[inline]
1259    pub fn to_array_4d(self) -> [T; 4]
1260    where
1261        T: Zero,
1262    {
1263        [self.x, self.y, self.z, Zero::zero()]
1264    }
1265
1266    /// Cast into a tuple with x, y and z.
1267    #[inline]
1268    pub fn to_tuple(self) -> (T, T, T) {
1269        (self.x, self.y, self.z)
1270    }
1271
1272    /// Cast into a tuple with x, y, z and 0.
1273    #[inline]
1274    pub fn to_tuple_4d(self) -> (T, T, T, T)
1275    where
1276        T: Zero,
1277    {
1278        (self.x, self.y, self.z, Zero::zero())
1279    }
1280
1281    /// Drop the units, preserving only the numeric value.
1282    #[inline]
1283    pub fn to_untyped(self) -> Vector3D<T, UnknownUnit> {
1284        vec3(self.x, self.y, self.z)
1285    }
1286
1287    /// Cast the unit.
1288    #[inline]
1289    pub fn cast_unit<V>(self) -> Vector3D<T, V> {
1290        vec3(self.x, self.y, self.z)
1291    }
1292
1293    /// Convert into a 2d vector.
1294    #[inline]
1295    pub fn to_2d(self) -> Vector2D<T, U> {
1296        self.xy()
1297    }
1298
1299    /// Rounds each component to the nearest integer value.
1300    ///
1301    /// This behavior is preserved for negative values (unlike the basic cast).
1302    ///
1303    /// ```rust
1304    /// # use euclid::vec3;
1305    /// enum Mm {}
1306    ///
1307    /// assert_eq!(vec3::<_, Mm>(-0.1, -0.8, 0.4).round(), vec3::<_, Mm>(0.0, -1.0, 0.0))
1308    /// ```
1309    #[inline]
1310    #[must_use]
1311    pub fn round(self) -> Self
1312    where
1313        T: Round,
1314    {
1315        vec3(self.x.round(), self.y.round(), self.z.round())
1316    }
1317
1318    /// Rounds each component to the smallest integer equal or greater than the original value.
1319    ///
1320    /// This behavior is preserved for negative values (unlike the basic cast).
1321    ///
1322    /// ```rust
1323    /// # use euclid::vec3;
1324    /// enum Mm {}
1325    ///
1326    /// assert_eq!(vec3::<_, Mm>(-0.1, -0.8, 0.4).ceil(), vec3::<_, Mm>(0.0, 0.0, 1.0))
1327    /// ```
1328    #[inline]
1329    #[must_use]
1330    pub fn ceil(self) -> Self
1331    where
1332        T: Ceil,
1333    {
1334        vec3(self.x.ceil(), self.y.ceil(), self.z.ceil())
1335    }
1336
1337    /// Rounds each component to the biggest integer equal or lower than the original value.
1338    ///
1339    /// This behavior is preserved for negative values (unlike the basic cast).
1340    ///
1341    /// ```rust
1342    /// # use euclid::vec3;
1343    /// enum Mm {}
1344    ///
1345    /// assert_eq!(vec3::<_, Mm>(-0.1, -0.8, 0.4).floor(), vec3::<_, Mm>(-1.0, -1.0, 0.0))
1346    /// ```
1347    #[inline]
1348    #[must_use]
1349    pub fn floor(self) -> Self
1350    where
1351        T: Floor,
1352    {
1353        vec3(self.x.floor(), self.y.floor(), self.z.floor())
1354    }
1355
1356    /// Creates translation by this vector in vector units
1357    #[inline]
1358    pub fn to_transform(self) -> Transform3D<T, U, U>
1359    where
1360        T: Zero + One,
1361    {
1362        Transform3D::translation(self.x, self.y, self.z)
1363    }
1364}
1365
1366impl<T, U> Vector3D<T, U>
1367where
1368    T: Copy + Mul<T, Output = T> + Add<T, Output = T>,
1369{
1370    /// Returns the vector's length squared.
1371    #[inline]
1372    pub fn square_length(self) -> T {
1373        self.x * self.x + self.y * self.y + self.z * self.z
1374    }
1375
1376    /// Returns this vector projected onto another one.
1377    ///
1378    /// Projecting onto a nil vector will cause a division by zero.
1379    #[inline]
1380    pub fn project_onto_vector(self, onto: Self) -> Self
1381    where
1382        T: Sub<T, Output = T> + Div<T, Output = T>,
1383    {
1384        onto * (self.dot(onto) / onto.square_length())
1385    }
1386}
1387
1388impl<T: Float, U> Vector3D<T, U> {
1389    /// Return the normalized vector even if the length is larger than the max value of Float.
1390    #[inline]
1391    #[must_use]
1392    pub fn robust_normalize(self) -> Self {
1393        let length = self.length();
1394        if length.is_infinite() {
1395            let scaled = self / T::max_value();
1396            scaled / scaled.length()
1397        } else {
1398            self / length
1399        }
1400    }
1401
1402    /// Returns `true` if all members are finite.
1403    #[inline]
1404    pub fn is_finite(self) -> bool {
1405        self.x.is_finite() && self.y.is_finite() && self.z.is_finite()
1406    }
1407}
1408
1409impl<T: Real, U> Vector3D<T, U> {
1410    /// Returns the positive angle between this vector and another vector.
1411    ///
1412    /// The returned angle is between 0 and PI.
1413    pub fn angle_to(self, other: Self) -> Angle<T>
1414    where
1415        T: Trig,
1416    {
1417        Angle::radians(Trig::fast_atan2(
1418            self.cross(other).length(),
1419            self.dot(other),
1420        ))
1421    }
1422
1423    /// Returns the vector length.
1424    #[inline]
1425    pub fn length(self) -> T {
1426        self.square_length().sqrt()
1427    }
1428
1429    /// Returns the vector with length of one unit
1430    #[inline]
1431    #[must_use]
1432    pub fn normalize(self) -> Self {
1433        self / self.length()
1434    }
1435
1436    /// Returns the vector with length of one unit.
1437    ///
1438    /// Unlike [`Vector2D::normalize`], this returns `None` in the case that the
1439    /// length of the vector is zero.
1440    #[inline]
1441    #[must_use]
1442    pub fn try_normalize(self) -> Option<Self> {
1443        let len = self.length();
1444        if len == T::zero() {
1445            None
1446        } else {
1447            Some(self / len)
1448        }
1449    }
1450
1451    /// Return this vector capped to a maximum length.
1452    #[inline]
1453    pub fn with_max_length(self, max_length: T) -> Self {
1454        let square_length = self.square_length();
1455        if square_length > max_length * max_length {
1456            return self * (max_length / square_length.sqrt());
1457        }
1458
1459        self
1460    }
1461
1462    /// Return this vector with a minimum length applied.
1463    #[inline]
1464    pub fn with_min_length(self, min_length: T) -> Self {
1465        let square_length = self.square_length();
1466        if square_length < min_length * min_length {
1467            return self * (min_length / square_length.sqrt());
1468        }
1469
1470        self
1471    }
1472
1473    /// Return this vector with minimum and maximum lengths applied.
1474    #[inline]
1475    pub fn clamp_length(self, min: T, max: T) -> Self {
1476        debug_assert!(min <= max);
1477        self.with_min_length(min).with_max_length(max)
1478    }
1479}
1480
1481impl<T, U> Vector3D<T, U>
1482where
1483    T: Copy + One + Add<Output = T> + Sub<Output = T> + Mul<Output = T>,
1484{
1485    /// Linearly interpolate each component between this vector and another vector.
1486    ///
1487    /// # Example
1488    ///
1489    /// ```rust
1490    /// use euclid::vec3;
1491    /// use euclid::default::Vector3D;
1492    ///
1493    /// let from: Vector3D<_> = vec3(0.0, 10.0, -1.0);
1494    /// let to:  Vector3D<_> = vec3(8.0, -4.0,  0.0);
1495    ///
1496    /// assert_eq!(from.lerp(to, -1.0), vec3(-8.0,  24.0, -2.0));
1497    /// assert_eq!(from.lerp(to,  0.0), vec3( 0.0,  10.0, -1.0));
1498    /// assert_eq!(from.lerp(to,  0.5), vec3( 4.0,   3.0, -0.5));
1499    /// assert_eq!(from.lerp(to,  1.0), vec3( 8.0,  -4.0,  0.0));
1500    /// assert_eq!(from.lerp(to,  2.0), vec3(16.0, -18.0,  1.0));
1501    /// ```
1502    #[inline]
1503    pub fn lerp(self, other: Self, t: T) -> Self {
1504        let one_t = T::one() - t;
1505        self * one_t + other * t
1506    }
1507
1508    /// Returns a reflection vector using an incident ray and a surface normal.
1509    #[inline]
1510    pub fn reflect(self, normal: Self) -> Self {
1511        let two = T::one() + T::one();
1512        self - normal * two * self.dot(normal)
1513    }
1514}
1515
1516impl<T: PartialOrd, U> Vector3D<T, U> {
1517    /// Returns the vector each component of which are minimum of this vector and another.
1518    #[inline]
1519    pub fn min(self, other: Self) -> Self {
1520        vec3(
1521            min(self.x, other.x),
1522            min(self.y, other.y),
1523            min(self.z, other.z),
1524        )
1525    }
1526
1527    /// Returns the vector each component of which are maximum of this vector and another.
1528    #[inline]
1529    pub fn max(self, other: Self) -> Self {
1530        vec3(
1531            max(self.x, other.x),
1532            max(self.y, other.y),
1533            max(self.z, other.z),
1534        )
1535    }
1536
1537    /// Returns the vector each component of which is clamped by corresponding
1538    /// components of `start` and `end`.
1539    ///
1540    /// Shortcut for `self.max(start).min(end)`.
1541    #[inline]
1542    pub fn clamp(self, start: Self, end: Self) -> Self
1543    where
1544        T: Copy,
1545    {
1546        self.max(start).min(end)
1547    }
1548
1549    /// Returns vector with results of "greater than" operation on each component.
1550    #[inline]
1551    pub fn greater_than(self, other: Self) -> BoolVector3D {
1552        BoolVector3D {
1553            x: self.x > other.x,
1554            y: self.y > other.y,
1555            z: self.z > other.z,
1556        }
1557    }
1558
1559    /// Returns vector with results of "lower than" operation on each component.
1560    #[inline]
1561    pub fn lower_than(self, other: Self) -> BoolVector3D {
1562        BoolVector3D {
1563            x: self.x < other.x,
1564            y: self.y < other.y,
1565            z: self.z < other.z,
1566        }
1567    }
1568}
1569
1570impl<T: PartialEq, U> Vector3D<T, U> {
1571    /// Returns vector with results of "equal" operation on each component.
1572    #[inline]
1573    pub fn equal(self, other: Self) -> BoolVector3D {
1574        BoolVector3D {
1575            x: self.x == other.x,
1576            y: self.y == other.y,
1577            z: self.z == other.z,
1578        }
1579    }
1580
1581    /// Returns vector with results of "not equal" operation on each component.
1582    #[inline]
1583    pub fn not_equal(self, other: Self) -> BoolVector3D {
1584        BoolVector3D {
1585            x: self.x != other.x,
1586            y: self.y != other.y,
1587            z: self.z != other.z,
1588        }
1589    }
1590}
1591
1592impl<T: NumCast + Copy, U> Vector3D<T, U> {
1593    /// Cast from one numeric representation to another, preserving the units.
1594    ///
1595    /// When casting from floating vector to integer coordinates, the decimals are truncated
1596    /// as one would expect from a simple cast, but this behavior does not always make sense
1597    /// geometrically. Consider using `round()`, `ceil()` or `floor()` before casting.
1598    #[inline]
1599    pub fn cast<NewT: NumCast>(self) -> Vector3D<NewT, U> {
1600        self.try_cast().unwrap()
1601    }
1602
1603    /// Fallible cast from one numeric representation to another, preserving the units.
1604    ///
1605    /// When casting from floating vector to integer coordinates, the decimals are truncated
1606    /// as one would expect from a simple cast, but this behavior does not always make sense
1607    /// geometrically. Consider using `round()`, `ceil()` or `floor()` before casting.
1608    pub fn try_cast<NewT: NumCast>(self) -> Option<Vector3D<NewT, U>> {
1609        match (
1610            NumCast::from(self.x),
1611            NumCast::from(self.y),
1612            NumCast::from(self.z),
1613        ) {
1614            (Some(x), Some(y), Some(z)) => Some(vec3(x, y, z)),
1615            _ => None,
1616        }
1617    }
1618
1619    // Convenience functions for common casts.
1620
1621    /// Cast into an `f32` vector.
1622    #[inline]
1623    pub fn to_f32(self) -> Vector3D<f32, U> {
1624        self.cast()
1625    }
1626
1627    /// Cast into an `f64` vector.
1628    #[inline]
1629    pub fn to_f64(self) -> Vector3D<f64, U> {
1630        self.cast()
1631    }
1632
1633    /// Cast into an `usize` vector, truncating decimals if any.
1634    ///
1635    /// When casting from floating vector vectors, it is worth considering whether
1636    /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain
1637    /// the desired conversion behavior.
1638    #[inline]
1639    pub fn to_usize(self) -> Vector3D<usize, U> {
1640        self.cast()
1641    }
1642
1643    /// Cast into an `u32` vector, truncating decimals if any.
1644    ///
1645    /// When casting from floating vector vectors, it is worth considering whether
1646    /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain
1647    /// the desired conversion behavior.
1648    #[inline]
1649    pub fn to_u32(self) -> Vector3D<u32, U> {
1650        self.cast()
1651    }
1652
1653    /// Cast into an `i32` vector, truncating decimals if any.
1654    ///
1655    /// When casting from floating vector vectors, it is worth considering whether
1656    /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain
1657    /// the desired conversion behavior.
1658    #[inline]
1659    pub fn to_i32(self) -> Vector3D<i32, U> {
1660        self.cast()
1661    }
1662
1663    /// Cast into an `i64` vector, truncating decimals if any.
1664    ///
1665    /// When casting from floating vector vectors, it is worth considering whether
1666    /// to `round()`, `ceil()` or `floor()` before the cast in order to obtain
1667    /// the desired conversion behavior.
1668    #[inline]
1669    pub fn to_i64(self) -> Vector3D<i64, U> {
1670        self.cast()
1671    }
1672}
1673
1674impl<T: Neg, U> Neg for Vector3D<T, U> {
1675    type Output = Vector3D<T::Output, U>;
1676
1677    #[inline]
1678    fn neg(self) -> Self::Output {
1679        vec3(-self.x, -self.y, -self.z)
1680    }
1681}
1682
1683impl<T: Add, U> Add for Vector3D<T, U> {
1684    type Output = Vector3D<T::Output, U>;
1685
1686    #[inline]
1687    fn add(self, other: Self) -> Self::Output {
1688        vec3(self.x + other.x, self.y + other.y, self.z + other.z)
1689    }
1690}
1691
1692impl<'a, T: 'a + Add + Copy, U: 'a> Add<&Self> for Vector3D<T, U> {
1693    type Output = Vector3D<T::Output, U>;
1694
1695    #[inline]
1696    fn add(self, other: &Self) -> Self::Output {
1697        vec3(self.x + other.x, self.y + other.y, self.z + other.z)
1698    }
1699}
1700
1701impl<T: Add<Output = T> + Zero, U> Sum for Vector3D<T, U> {
1702    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
1703        iter.fold(Self::zero(), Add::add)
1704    }
1705}
1706
1707impl<'a, T: 'a + Add<Output = T> + Copy + Zero, U: 'a> Sum<&'a Self> for Vector3D<T, U> {
1708    fn sum<I: Iterator<Item = &'a Self>>(iter: I) -> Self {
1709        iter.fold(Self::zero(), Add::add)
1710    }
1711}
1712
1713impl<T: Copy + Add<T, Output = T>, U> AddAssign for Vector3D<T, U> {
1714    #[inline]
1715    fn add_assign(&mut self, other: Self) {
1716        *self = *self + other
1717    }
1718}
1719
1720impl<T: Sub, U> Sub for Vector3D<T, U> {
1721    type Output = Vector3D<T::Output, U>;
1722
1723    #[inline]
1724    fn sub(self, other: Self) -> Self::Output {
1725        vec3(self.x - other.x, self.y - other.y, self.z - other.z)
1726    }
1727}
1728
1729impl<T: Copy + Sub<T, Output = T>, U> SubAssign<Vector3D<T, U>> for Vector3D<T, U> {
1730    #[inline]
1731    fn sub_assign(&mut self, other: Self) {
1732        *self = *self - other
1733    }
1734}
1735
1736impl<T: Copy + Mul, U> Mul<T> for Vector3D<T, U> {
1737    type Output = Vector3D<T::Output, U>;
1738
1739    #[inline]
1740    fn mul(self, scale: T) -> Self::Output {
1741        vec3(self.x * scale, self.y * scale, self.z * scale)
1742    }
1743}
1744
1745impl<T: Copy + Mul<T, Output = T>, U> MulAssign<T> for Vector3D<T, U> {
1746    #[inline]
1747    fn mul_assign(&mut self, scale: T) {
1748        *self = *self * scale
1749    }
1750}
1751
1752impl<T: Copy + Mul, U1, U2> Mul<Scale<T, U1, U2>> for Vector3D<T, U1> {
1753    type Output = Vector3D<T::Output, U2>;
1754
1755    #[inline]
1756    fn mul(self, scale: Scale<T, U1, U2>) -> Self::Output {
1757        vec3(self.x * scale.0, self.y * scale.0, self.z * scale.0)
1758    }
1759}
1760
1761impl<T: Copy + MulAssign, U> MulAssign<Scale<T, U, U>> for Vector3D<T, U> {
1762    #[inline]
1763    fn mul_assign(&mut self, scale: Scale<T, U, U>) {
1764        self.x *= scale.0;
1765        self.y *= scale.0;
1766        self.z *= scale.0;
1767    }
1768}
1769
1770impl<T: Copy + Div, U> Div<T> for Vector3D<T, U> {
1771    type Output = Vector3D<T::Output, U>;
1772
1773    #[inline]
1774    fn div(self, scale: T) -> Self::Output {
1775        vec3(self.x / scale, self.y / scale, self.z / scale)
1776    }
1777}
1778
1779impl<T: Copy + Div<T, Output = T>, U> DivAssign<T> for Vector3D<T, U> {
1780    #[inline]
1781    fn div_assign(&mut self, scale: T) {
1782        *self = *self / scale
1783    }
1784}
1785
1786impl<T: Copy + Div, U1, U2> Div<Scale<T, U1, U2>> for Vector3D<T, U2> {
1787    type Output = Vector3D<T::Output, U1>;
1788
1789    #[inline]
1790    fn div(self, scale: Scale<T, U1, U2>) -> Self::Output {
1791        vec3(self.x / scale.0, self.y / scale.0, self.z / scale.0)
1792    }
1793}
1794
1795impl<T: Copy + DivAssign, U> DivAssign<Scale<T, U, U>> for Vector3D<T, U> {
1796    #[inline]
1797    fn div_assign(&mut self, scale: Scale<T, U, U>) {
1798        self.x /= scale.0;
1799        self.y /= scale.0;
1800        self.z /= scale.0;
1801    }
1802}
1803
1804impl<T: Round, U> Round for Vector3D<T, U> {
1805    /// See [`Vector3D::round`].
1806    #[inline]
1807    fn round(self) -> Self {
1808        self.round()
1809    }
1810}
1811
1812impl<T: Ceil, U> Ceil for Vector3D<T, U> {
1813    /// See [`Vector3D::ceil`].
1814    #[inline]
1815    fn ceil(self) -> Self {
1816        self.ceil()
1817    }
1818}
1819
1820impl<T: Floor, U> Floor for Vector3D<T, U> {
1821    /// See [`Vector3D::floor`].
1822    #[inline]
1823    fn floor(self) -> Self {
1824        self.floor()
1825    }
1826}
1827
1828impl<T: ApproxEq<T>, U> ApproxEq<Vector3D<T, U>> for Vector3D<T, U> {
1829    #[inline]
1830    fn approx_epsilon() -> Self {
1831        vec3(
1832            T::approx_epsilon(),
1833            T::approx_epsilon(),
1834            T::approx_epsilon(),
1835        )
1836    }
1837
1838    #[inline]
1839    fn approx_eq_eps(&self, other: &Self, eps: &Self) -> bool {
1840        self.x.approx_eq_eps(&other.x, &eps.x)
1841            && self.y.approx_eq_eps(&other.y, &eps.y)
1842            && self.z.approx_eq_eps(&other.z, &eps.z)
1843    }
1844}
1845
1846impl<T, U> From<Vector3D<T, U>> for [T; 3] {
1847    fn from(v: Vector3D<T, U>) -> Self {
1848        [v.x, v.y, v.z]
1849    }
1850}
1851
1852impl<T, U> From<[T; 3]> for Vector3D<T, U> {
1853    fn from([x, y, z]: [T; 3]) -> Self {
1854        vec3(x, y, z)
1855    }
1856}
1857
1858impl<T, U> From<Vector3D<T, U>> for (T, T, T) {
1859    fn from(v: Vector3D<T, U>) -> Self {
1860        (v.x, v.y, v.z)
1861    }
1862}
1863
1864impl<T, U> From<(T, T, T)> for Vector3D<T, U> {
1865    fn from(tuple: (T, T, T)) -> Self {
1866        vec3(tuple.0, tuple.1, tuple.2)
1867    }
1868}
1869
1870/// A 2d vector of booleans, useful for component-wise logic operations.
1871#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1872pub struct BoolVector2D {
1873    pub x: bool,
1874    pub y: bool,
1875}
1876
1877/// A 3d vector of booleans, useful for component-wise logic operations.
1878#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
1879pub struct BoolVector3D {
1880    pub x: bool,
1881    pub y: bool,
1882    pub z: bool,
1883}
1884
1885impl BoolVector2D {
1886    /// Returns `true` if all components are `true` and `false` otherwise.
1887    #[inline]
1888    pub fn all(self) -> bool {
1889        self.x && self.y
1890    }
1891
1892    /// Returns `true` if any component are `true` and `false` otherwise.
1893    #[inline]
1894    pub fn any(self) -> bool {
1895        self.x || self.y
1896    }
1897
1898    /// Returns `true` if all components are `false` and `false` otherwise. Negation of `any()`.
1899    #[inline]
1900    pub fn none(self) -> bool {
1901        !self.any()
1902    }
1903
1904    /// Returns new vector with by-component AND operation applied.
1905    #[inline]
1906    pub fn and(self, other: Self) -> Self {
1907        BoolVector2D {
1908            x: self.x && other.x,
1909            y: self.y && other.y,
1910        }
1911    }
1912
1913    /// Returns new vector with by-component OR operation applied.
1914    #[inline]
1915    pub fn or(self, other: Self) -> Self {
1916        BoolVector2D {
1917            x: self.x || other.x,
1918            y: self.y || other.y,
1919        }
1920    }
1921
1922    /// Returns new vector with results of negation operation on each component.
1923    #[inline]
1924    pub fn not(self) -> Self {
1925        BoolVector2D {
1926            x: !self.x,
1927            y: !self.y,
1928        }
1929    }
1930
1931    /// Returns point, each component of which or from `a`, or from `b` depending on truly value
1932    /// of corresponding vector component. `true` selects value from `a` and `false` from `b`.
1933    #[inline]
1934    pub fn select_point<T, U>(self, a: Point2D<T, U>, b: Point2D<T, U>) -> Point2D<T, U> {
1935        point2(
1936            if self.x { a.x } else { b.x },
1937            if self.y { a.y } else { b.y },
1938        )
1939    }
1940
1941    /// Returns vector, each component of which or from `a`, or from `b` depending on truly value
1942    /// of corresponding vector component. `true` selects value from `a` and `false` from `b`.
1943    #[inline]
1944    pub fn select_vector<T, U>(self, a: Vector2D<T, U>, b: Vector2D<T, U>) -> Vector2D<T, U> {
1945        vec2(
1946            if self.x { a.x } else { b.x },
1947            if self.y { a.y } else { b.y },
1948        )
1949    }
1950
1951    /// Returns size, each component of which or from `a`, or from `b` depending on truly value
1952    /// of corresponding vector component. `true` selects value from `a` and `false` from `b`.
1953    #[inline]
1954    pub fn select_size<T, U>(self, a: Size2D<T, U>, b: Size2D<T, U>) -> Size2D<T, U> {
1955        size2(
1956            if self.x { a.width } else { b.width },
1957            if self.y { a.height } else { b.height },
1958        )
1959    }
1960}
1961
1962impl BoolVector3D {
1963    /// Returns `true` if all components are `true` and `false` otherwise.
1964    #[inline]
1965    pub fn all(self) -> bool {
1966        self.x && self.y && self.z
1967    }
1968
1969    /// Returns `true` if any component are `true` and `false` otherwise.
1970    #[inline]
1971    pub fn any(self) -> bool {
1972        self.x || self.y || self.z
1973    }
1974
1975    /// Returns `true` if all components are `false` and `false` otherwise. Negation of `any()`.
1976    #[inline]
1977    pub fn none(self) -> bool {
1978        !self.any()
1979    }
1980
1981    /// Returns new vector with by-component AND operation applied.
1982    #[inline]
1983    pub fn and(self, other: Self) -> Self {
1984        BoolVector3D {
1985            x: self.x && other.x,
1986            y: self.y && other.y,
1987            z: self.z && other.z,
1988        }
1989    }
1990
1991    /// Returns new vector with by-component OR operation applied.
1992    #[inline]
1993    pub fn or(self, other: Self) -> Self {
1994        BoolVector3D {
1995            x: self.x || other.x,
1996            y: self.y || other.y,
1997            z: self.z || other.z,
1998        }
1999    }
2000
2001    /// Returns new vector with results of negation operation on each component.
2002    #[inline]
2003    pub fn not(self) -> Self {
2004        BoolVector3D {
2005            x: !self.x,
2006            y: !self.y,
2007            z: !self.z,
2008        }
2009    }
2010
2011    /// Returns point, each component of which or from `a`, or from `b` depending on truly value
2012    /// of corresponding vector component. `true` selects value from `a` and `false` from `b`.
2013    #[inline]
2014    pub fn select_point<T, U>(self, a: Point3D<T, U>, b: Point3D<T, U>) -> Point3D<T, U> {
2015        point3(
2016            if self.x { a.x } else { b.x },
2017            if self.y { a.y } else { b.y },
2018            if self.z { a.z } else { b.z },
2019        )
2020    }
2021
2022    /// Returns vector, each component of which or from `a`, or from `b` depending on truly value
2023    /// of corresponding vector component. `true` selects value from `a` and `false` from `b`.
2024    #[inline]
2025    pub fn select_vector<T, U>(self, a: Vector3D<T, U>, b: Vector3D<T, U>) -> Vector3D<T, U> {
2026        vec3(
2027            if self.x { a.x } else { b.x },
2028            if self.y { a.y } else { b.y },
2029            if self.z { a.z } else { b.z },
2030        )
2031    }
2032
2033    /// Returns size, each component of which or from `a`, or from `b` depending on truly value
2034    /// of corresponding vector component. `true` selects value from `a` and `false` from `b`.
2035    #[inline]
2036    #[must_use]
2037    pub fn select_size<T, U>(self, a: Size3D<T, U>, b: Size3D<T, U>) -> Size3D<T, U> {
2038        size3(
2039            if self.x { a.width } else { b.width },
2040            if self.y { a.height } else { b.height },
2041            if self.z { a.depth } else { b.depth },
2042        )
2043    }
2044
2045    /// Returns a 2d vector using this vector's x and y coordinates.
2046    #[inline]
2047    pub fn xy(self) -> BoolVector2D {
2048        BoolVector2D {
2049            x: self.x,
2050            y: self.y,
2051        }
2052    }
2053
2054    /// Returns a 2d vector using this vector's x and z coordinates.
2055    #[inline]
2056    pub fn xz(self) -> BoolVector2D {
2057        BoolVector2D {
2058            x: self.x,
2059            y: self.z,
2060        }
2061    }
2062
2063    /// Returns a 2d vector using this vector's y and z coordinates.
2064    #[inline]
2065    pub fn yz(self) -> BoolVector2D {
2066        BoolVector2D {
2067            x: self.y,
2068            y: self.z,
2069        }
2070    }
2071}
2072
2073#[cfg(feature = "arbitrary")]
2074impl<'a> arbitrary::Arbitrary<'a> for BoolVector2D {
2075    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
2076        Ok(BoolVector2D {
2077            x: arbitrary::Arbitrary::arbitrary(u)?,
2078            y: arbitrary::Arbitrary::arbitrary(u)?,
2079        })
2080    }
2081}
2082
2083#[cfg(feature = "arbitrary")]
2084impl<'a> arbitrary::Arbitrary<'a> for BoolVector3D {
2085    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
2086        Ok(BoolVector3D {
2087            x: arbitrary::Arbitrary::arbitrary(u)?,
2088            y: arbitrary::Arbitrary::arbitrary(u)?,
2089            z: arbitrary::Arbitrary::arbitrary(u)?,
2090        })
2091    }
2092}
2093
2094/// Convenience constructor.
2095#[inline]
2096pub const fn vec2<T, U>(x: T, y: T) -> Vector2D<T, U> {
2097    Vector2D {
2098        x,
2099        y,
2100        _unit: PhantomData,
2101    }
2102}
2103
2104/// Convenience constructor.
2105#[inline]
2106pub const fn vec3<T, U>(x: T, y: T, z: T) -> Vector3D<T, U> {
2107    Vector3D {
2108        x,
2109        y,
2110        z,
2111        _unit: PhantomData,
2112    }
2113}
2114
2115/// Shorthand for `BoolVector2D { x, y }`.
2116#[inline]
2117pub const fn bvec2(x: bool, y: bool) -> BoolVector2D {
2118    BoolVector2D { x, y }
2119}
2120
2121/// Shorthand for `BoolVector3D { x, y, z }`.
2122#[inline]
2123pub const fn bvec3(x: bool, y: bool, z: bool) -> BoolVector3D {
2124    BoolVector3D { x, y, z }
2125}
2126
2127#[cfg(test)]
2128mod vector2d {
2129    use crate::scale::Scale;
2130    use crate::{default, vec2};
2131
2132    #[cfg(feature = "mint")]
2133    use mint;
2134    type Vec2 = default::Vector2D<f32>;
2135
2136    #[test]
2137    pub fn test_scalar_mul() {
2138        let p1: Vec2 = vec2(3.0, 5.0);
2139
2140        let result = p1 * 5.0;
2141
2142        assert_eq!(result, Vec2::new(15.0, 25.0));
2143    }
2144
2145    #[test]
2146    pub fn test_dot() {
2147        let p1: Vec2 = vec2(2.0, 7.0);
2148        let p2: Vec2 = vec2(13.0, 11.0);
2149        assert_eq!(p1.dot(p2), 103.0);
2150    }
2151
2152    #[test]
2153    pub fn test_cross() {
2154        let p1: Vec2 = vec2(4.0, 7.0);
2155        let p2: Vec2 = vec2(13.0, 8.0);
2156        let r = p1.cross(p2);
2157        assert_eq!(r, -59.0);
2158    }
2159
2160    #[test]
2161    pub fn test_normalize() {
2162        use std::f32;
2163
2164        let p0: Vec2 = Vec2::zero();
2165        let p1: Vec2 = vec2(4.0, 0.0);
2166        let p2: Vec2 = vec2(3.0, -4.0);
2167        assert!(p0.normalize().x.is_nan() && p0.normalize().y.is_nan());
2168        assert_eq!(p1.normalize(), vec2(1.0, 0.0));
2169        assert_eq!(p2.normalize(), vec2(0.6, -0.8));
2170
2171        let p3: Vec2 = vec2(::std::f32::MAX, ::std::f32::MAX);
2172        assert_ne!(
2173            p3.normalize(),
2174            vec2(1.0 / 2.0f32.sqrt(), 1.0 / 2.0f32.sqrt())
2175        );
2176        assert_eq!(
2177            p3.robust_normalize(),
2178            vec2(1.0 / 2.0f32.sqrt(), 1.0 / 2.0f32.sqrt())
2179        );
2180
2181        let p4: Vec2 = Vec2::zero();
2182        assert!(p4.try_normalize().is_none());
2183        let p5: Vec2 = Vec2::new(f32::MIN_POSITIVE, f32::MIN_POSITIVE);
2184        assert!(p5.try_normalize().is_none());
2185
2186        let p6: Vec2 = vec2(4.0, 0.0);
2187        let p7: Vec2 = vec2(3.0, -4.0);
2188        assert_eq!(p6.try_normalize().unwrap(), vec2(1.0, 0.0));
2189        assert_eq!(p7.try_normalize().unwrap(), vec2(0.6, -0.8));
2190    }
2191
2192    #[test]
2193    pub fn test_min() {
2194        let p1: Vec2 = vec2(1.0, 3.0);
2195        let p2: Vec2 = vec2(2.0, 2.0);
2196
2197        let result = p1.min(p2);
2198
2199        assert_eq!(result, vec2(1.0, 2.0));
2200    }
2201
2202    #[test]
2203    pub fn test_max() {
2204        let p1: Vec2 = vec2(1.0, 3.0);
2205        let p2: Vec2 = vec2(2.0, 2.0);
2206
2207        let result = p1.max(p2);
2208
2209        assert_eq!(result, vec2(2.0, 3.0));
2210    }
2211
2212    #[test]
2213    pub fn test_angle_from_x_axis() {
2214        use crate::approxeq::ApproxEq;
2215        use core::f32::consts::FRAC_PI_2;
2216
2217        let right: Vec2 = vec2(10.0, 0.0);
2218        let down: Vec2 = vec2(0.0, 4.0);
2219        let up: Vec2 = vec2(0.0, -1.0);
2220
2221        assert!(right.angle_from_x_axis().get().approx_eq(&0.0));
2222        assert!(down.angle_from_x_axis().get().approx_eq(&FRAC_PI_2));
2223        assert!(up.angle_from_x_axis().get().approx_eq(&-FRAC_PI_2));
2224    }
2225
2226    #[test]
2227    pub fn test_angle_to() {
2228        use crate::approxeq::ApproxEq;
2229        use core::f32::consts::FRAC_PI_2;
2230
2231        let right: Vec2 = vec2(10.0, 0.0);
2232        let right2: Vec2 = vec2(1.0, 0.0);
2233        let up: Vec2 = vec2(0.0, -1.0);
2234        let up_left: Vec2 = vec2(-1.0, -1.0);
2235
2236        assert!(right.angle_to(right2).get().approx_eq(&0.0));
2237        assert!(right.angle_to(up).get().approx_eq(&-FRAC_PI_2));
2238        assert!(up.angle_to(right).get().approx_eq(&FRAC_PI_2));
2239        assert!(up_left
2240            .angle_to(up)
2241            .get()
2242            .approx_eq_eps(&(0.5 * FRAC_PI_2), &0.0005));
2243    }
2244
2245    #[test]
2246    pub fn test_with_max_length() {
2247        use crate::approxeq::ApproxEq;
2248
2249        let v1: Vec2 = vec2(0.5, 0.5);
2250        let v2: Vec2 = vec2(1.0, 0.0);
2251        let v3: Vec2 = vec2(0.1, 0.2);
2252        let v4: Vec2 = vec2(2.0, -2.0);
2253        let v5: Vec2 = vec2(1.0, 2.0);
2254        let v6: Vec2 = vec2(-1.0, 3.0);
2255
2256        assert_eq!(v1.with_max_length(1.0), v1);
2257        assert_eq!(v2.with_max_length(1.0), v2);
2258        assert_eq!(v3.with_max_length(1.0), v3);
2259        assert_eq!(v4.with_max_length(10.0), v4);
2260        assert_eq!(v5.with_max_length(10.0), v5);
2261        assert_eq!(v6.with_max_length(10.0), v6);
2262
2263        let v4_clamped = v4.with_max_length(1.0);
2264        assert!(v4_clamped.length().approx_eq(&1.0));
2265        assert!(v4_clamped.normalize().approx_eq(&v4.normalize()));
2266
2267        let v5_clamped = v5.with_max_length(1.5);
2268        assert!(v5_clamped.length().approx_eq(&1.5));
2269        assert!(v5_clamped.normalize().approx_eq(&v5.normalize()));
2270
2271        let v6_clamped = v6.with_max_length(2.5);
2272        assert!(v6_clamped.length().approx_eq(&2.5));
2273        assert!(v6_clamped.normalize().approx_eq(&v6.normalize()));
2274    }
2275
2276    #[test]
2277    pub fn test_project_onto_vector() {
2278        use crate::approxeq::ApproxEq;
2279
2280        let v1: Vec2 = vec2(1.0, 2.0);
2281        let x: Vec2 = vec2(1.0, 0.0);
2282        let y: Vec2 = vec2(0.0, 1.0);
2283
2284        assert!(v1.project_onto_vector(x).approx_eq(&vec2(1.0, 0.0)));
2285        assert!(v1.project_onto_vector(y).approx_eq(&vec2(0.0, 2.0)));
2286        assert!(v1.project_onto_vector(-x).approx_eq(&vec2(1.0, 0.0)));
2287        assert!(v1.project_onto_vector(x * 10.0).approx_eq(&vec2(1.0, 0.0)));
2288        assert!(v1.project_onto_vector(v1 * 2.0).approx_eq(&v1));
2289        assert!(v1.project_onto_vector(-v1).approx_eq(&v1));
2290    }
2291
2292    #[cfg(feature = "mint")]
2293    #[test]
2294    pub fn test_mint() {
2295        let v1 = Vec2::new(1.0, 3.0);
2296        let vm: mint::Vector2<_> = v1.into();
2297        let v2 = Vec2::from(vm);
2298
2299        assert_eq!(v1, v2);
2300    }
2301
2302    pub enum Mm {}
2303    pub enum Cm {}
2304
2305    pub type Vector2DMm<T> = super::Vector2D<T, Mm>;
2306    pub type Vector2DCm<T> = super::Vector2D<T, Cm>;
2307
2308    #[test]
2309    pub fn test_add() {
2310        let p1 = Vector2DMm::new(1.0, 2.0);
2311        let p2 = Vector2DMm::new(3.0, 4.0);
2312
2313        assert_eq!(p1 + p2, vec2(4.0, 6.0));
2314        assert_eq!(p1 + &p2, vec2(4.0, 6.0));
2315    }
2316
2317    #[test]
2318    pub fn test_sum() {
2319        let vecs = [
2320            Vector2DMm::new(1.0, 2.0),
2321            Vector2DMm::new(3.0, 4.0),
2322            Vector2DMm::new(5.0, 6.0),
2323        ];
2324        let sum = Vector2DMm::new(9.0, 12.0);
2325        assert_eq!(vecs.iter().sum::<Vector2DMm<_>>(), sum);
2326    }
2327
2328    #[test]
2329    pub fn test_add_assign() {
2330        let mut p1 = Vector2DMm::new(1.0, 2.0);
2331        p1 += vec2(3.0, 4.0);
2332
2333        assert_eq!(p1, vec2(4.0, 6.0));
2334    }
2335
2336    #[test]
2337    pub fn test_typed_scalar_mul() {
2338        let p1 = Vector2DMm::new(1.0, 2.0);
2339        let cm_per_mm = Scale::<f32, Mm, Cm>::new(0.1);
2340
2341        let result: Vector2DCm<f32> = p1 * cm_per_mm;
2342
2343        assert_eq!(result, vec2(0.1, 0.2));
2344    }
2345
2346    #[test]
2347    pub fn test_swizzling() {
2348        let p: default::Vector2D<i32> = vec2(1, 2);
2349        assert_eq!(p.yx(), vec2(2, 1));
2350    }
2351
2352    #[test]
2353    pub fn test_reflect() {
2354        use crate::approxeq::ApproxEq;
2355        let a: Vec2 = vec2(1.0, 3.0);
2356        let n1: Vec2 = vec2(0.0, -1.0);
2357        let n2: Vec2 = vec2(1.0, -1.0).normalize();
2358
2359        assert!(a.reflect(n1).approx_eq(&vec2(1.0, -3.0)));
2360        assert!(a.reflect(n2).approx_eq(&vec2(3.0, 1.0)));
2361    }
2362}
2363
2364#[cfg(test)]
2365mod vector3d {
2366    use crate::scale::Scale;
2367    use crate::{default, vec2, vec3};
2368    #[cfg(feature = "mint")]
2369    use mint;
2370
2371    type Vec3 = default::Vector3D<f32>;
2372
2373    #[test]
2374    pub fn test_add() {
2375        let p1 = Vec3::new(1.0, 2.0, 3.0);
2376        let p2 = Vec3::new(4.0, 5.0, 6.0);
2377
2378        assert_eq!(p1 + p2, vec3(5.0, 7.0, 9.0));
2379        assert_eq!(p1 + &p2, vec3(5.0, 7.0, 9.0));
2380    }
2381
2382    #[test]
2383    pub fn test_sum() {
2384        let vecs = [
2385            Vec3::new(1.0, 2.0, 3.0),
2386            Vec3::new(4.0, 5.0, 6.0),
2387            Vec3::new(7.0, 8.0, 9.0),
2388        ];
2389        let sum = Vec3::new(12.0, 15.0, 18.0);
2390        assert_eq!(vecs.iter().sum::<Vec3>(), sum);
2391    }
2392
2393    #[test]
2394    pub fn test_dot() {
2395        let p1: Vec3 = vec3(7.0, 21.0, 32.0);
2396        let p2: Vec3 = vec3(43.0, 5.0, 16.0);
2397        assert_eq!(p1.dot(p2), 918.0);
2398    }
2399
2400    #[test]
2401    pub fn test_cross() {
2402        let p1: Vec3 = vec3(4.0, 7.0, 9.0);
2403        let p2: Vec3 = vec3(13.0, 8.0, 3.0);
2404        let p3 = p1.cross(p2);
2405        assert_eq!(p3, vec3(-51.0, 105.0, -59.0));
2406    }
2407
2408    #[test]
2409    pub fn test_normalize() {
2410        use std::f32;
2411
2412        let p0: Vec3 = Vec3::zero();
2413        let p1: Vec3 = vec3(0.0, -6.0, 0.0);
2414        let p2: Vec3 = vec3(1.0, 2.0, -2.0);
2415        assert!(
2416            p0.normalize().x.is_nan() && p0.normalize().y.is_nan() && p0.normalize().z.is_nan()
2417        );
2418        assert_eq!(p1.normalize(), vec3(0.0, -1.0, 0.0));
2419        assert_eq!(p2.normalize(), vec3(1.0 / 3.0, 2.0 / 3.0, -2.0 / 3.0));
2420
2421        let p3: Vec3 = vec3(::std::f32::MAX, ::std::f32::MAX, 0.0);
2422        assert_ne!(
2423            p3.normalize(),
2424            vec3(1.0 / 2.0f32.sqrt(), 1.0 / 2.0f32.sqrt(), 0.0)
2425        );
2426        assert_eq!(
2427            p3.robust_normalize(),
2428            vec3(1.0 / 2.0f32.sqrt(), 1.0 / 2.0f32.sqrt(), 0.0)
2429        );
2430
2431        let p4: Vec3 = Vec3::zero();
2432        assert!(p4.try_normalize().is_none());
2433        let p5: Vec3 = Vec3::new(f32::MIN_POSITIVE, f32::MIN_POSITIVE, f32::MIN_POSITIVE);
2434        assert!(p5.try_normalize().is_none());
2435
2436        let p6: Vec3 = vec3(4.0, 0.0, 3.0);
2437        let p7: Vec3 = vec3(3.0, -4.0, 0.0);
2438        assert_eq!(p6.try_normalize().unwrap(), vec3(0.8, 0.0, 0.6));
2439        assert_eq!(p7.try_normalize().unwrap(), vec3(0.6, -0.8, 0.0));
2440    }
2441
2442    #[test]
2443    pub fn test_min() {
2444        let p1: Vec3 = vec3(1.0, 3.0, 5.0);
2445        let p2: Vec3 = vec3(2.0, 2.0, -1.0);
2446
2447        let result = p1.min(p2);
2448
2449        assert_eq!(result, vec3(1.0, 2.0, -1.0));
2450    }
2451
2452    #[test]
2453    pub fn test_max() {
2454        let p1: Vec3 = vec3(1.0, 3.0, 5.0);
2455        let p2: Vec3 = vec3(2.0, 2.0, -1.0);
2456
2457        let result = p1.max(p2);
2458
2459        assert_eq!(result, vec3(2.0, 3.0, 5.0));
2460    }
2461
2462    #[test]
2463    pub fn test_clamp() {
2464        let p1: Vec3 = vec3(1.0, -1.0, 5.0);
2465        let p2: Vec3 = vec3(2.0, 5.0, 10.0);
2466        let p3: Vec3 = vec3(-1.0, 2.0, 20.0);
2467
2468        let result = p3.clamp(p1, p2);
2469
2470        assert_eq!(result, vec3(1.0, 2.0, 10.0));
2471    }
2472
2473    #[test]
2474    pub fn test_typed_scalar_mul() {
2475        enum Mm {}
2476        enum Cm {}
2477
2478        let p1 = super::Vector3D::<f32, Mm>::new(1.0, 2.0, 3.0);
2479        let cm_per_mm = Scale::<f32, Mm, Cm>::new(0.1);
2480
2481        let result: super::Vector3D<f32, Cm> = p1 * cm_per_mm;
2482
2483        assert_eq!(result, vec3(0.1, 0.2, 0.3));
2484    }
2485
2486    #[test]
2487    pub fn test_swizzling() {
2488        let p: Vec3 = vec3(1.0, 2.0, 3.0);
2489        assert_eq!(p.xy(), vec2(1.0, 2.0));
2490        assert_eq!(p.xz(), vec2(1.0, 3.0));
2491        assert_eq!(p.yz(), vec2(2.0, 3.0));
2492    }
2493
2494    #[cfg(feature = "mint")]
2495    #[test]
2496    pub fn test_mint() {
2497        let v1 = Vec3::new(1.0, 3.0, 5.0);
2498        let vm: mint::Vector3<_> = v1.into();
2499        let v2 = Vec3::from(vm);
2500
2501        assert_eq!(v1, v2);
2502    }
2503
2504    #[test]
2505    pub fn test_reflect() {
2506        use crate::approxeq::ApproxEq;
2507        let a: Vec3 = vec3(1.0, 3.0, 2.0);
2508        let n1: Vec3 = vec3(0.0, -1.0, 0.0);
2509        let n2: Vec3 = vec3(0.0, 1.0, 1.0).normalize();
2510
2511        assert!(a.reflect(n1).approx_eq(&vec3(1.0, -3.0, 2.0)));
2512        assert!(a.reflect(n2).approx_eq(&vec3(1.0, -2.0, -3.0)));
2513    }
2514
2515    #[test]
2516    pub fn test_angle_to() {
2517        use crate::approxeq::ApproxEq;
2518        use core::f32::consts::FRAC_PI_2;
2519
2520        let right: Vec3 = vec3(10.0, 0.0, 0.0);
2521        let right2: Vec3 = vec3(1.0, 0.0, 0.0);
2522        let up: Vec3 = vec3(0.0, -1.0, 0.0);
2523        let up_left: Vec3 = vec3(-1.0, -1.0, 0.0);
2524
2525        assert!(right.angle_to(right2).get().approx_eq(&0.0));
2526        assert!(right.angle_to(up).get().approx_eq(&FRAC_PI_2));
2527        assert!(up.angle_to(right).get().approx_eq(&FRAC_PI_2));
2528        assert!(up_left
2529            .angle_to(up)
2530            .get()
2531            .approx_eq_eps(&(0.5 * FRAC_PI_2), &0.0005));
2532    }
2533
2534    #[test]
2535    pub fn test_with_max_length() {
2536        use crate::approxeq::ApproxEq;
2537
2538        let v1: Vec3 = vec3(0.5, 0.5, 0.0);
2539        let v2: Vec3 = vec3(1.0, 0.0, 0.0);
2540        let v3: Vec3 = vec3(0.1, 0.2, 0.3);
2541        let v4: Vec3 = vec3(2.0, -2.0, 2.0);
2542        let v5: Vec3 = vec3(1.0, 2.0, -3.0);
2543        let v6: Vec3 = vec3(-1.0, 3.0, 2.0);
2544
2545        assert_eq!(v1.with_max_length(1.0), v1);
2546        assert_eq!(v2.with_max_length(1.0), v2);
2547        assert_eq!(v3.with_max_length(1.0), v3);
2548        assert_eq!(v4.with_max_length(10.0), v4);
2549        assert_eq!(v5.with_max_length(10.0), v5);
2550        assert_eq!(v6.with_max_length(10.0), v6);
2551
2552        let v4_clamped = v4.with_max_length(1.0);
2553        assert!(v4_clamped.length().approx_eq(&1.0));
2554        assert!(v4_clamped.normalize().approx_eq(&v4.normalize()));
2555
2556        let v5_clamped = v5.with_max_length(1.5);
2557        assert!(v5_clamped.length().approx_eq(&1.5));
2558        assert!(v5_clamped.normalize().approx_eq(&v5.normalize()));
2559
2560        let v6_clamped = v6.with_max_length(2.5);
2561        assert!(v6_clamped.length().approx_eq(&2.5));
2562        assert!(v6_clamped.normalize().approx_eq(&v6.normalize()));
2563    }
2564
2565    #[test]
2566    pub fn test_project_onto_vector() {
2567        use crate::approxeq::ApproxEq;
2568
2569        let v1: Vec3 = vec3(1.0, 2.0, 3.0);
2570        let x: Vec3 = vec3(1.0, 0.0, 0.0);
2571        let y: Vec3 = vec3(0.0, 1.0, 0.0);
2572        let z: Vec3 = vec3(0.0, 0.0, 1.0);
2573
2574        assert!(v1.project_onto_vector(x).approx_eq(&vec3(1.0, 0.0, 0.0)));
2575        assert!(v1.project_onto_vector(y).approx_eq(&vec3(0.0, 2.0, 0.0)));
2576        assert!(v1.project_onto_vector(z).approx_eq(&vec3(0.0, 0.0, 3.0)));
2577        assert!(v1.project_onto_vector(-x).approx_eq(&vec3(1.0, 0.0, 0.0)));
2578        assert!(v1
2579            .project_onto_vector(x * 10.0)
2580            .approx_eq(&vec3(1.0, 0.0, 0.0)));
2581        assert!(v1.project_onto_vector(v1 * 2.0).approx_eq(&v1));
2582        assert!(v1.project_onto_vector(-v1).approx_eq(&v1));
2583    }
2584}
2585
2586#[cfg(test)]
2587mod bool_vector {
2588    use super::*;
2589    use crate::default;
2590    type Vec2 = default::Vector2D<f32>;
2591    type Vec3 = default::Vector3D<f32>;
2592
2593    #[test]
2594    fn test_bvec2() {
2595        assert_eq!(
2596            Vec2::new(1.0, 2.0).greater_than(Vec2::new(2.0, 1.0)),
2597            bvec2(false, true),
2598        );
2599
2600        assert_eq!(
2601            Vec2::new(1.0, 2.0).lower_than(Vec2::new(2.0, 1.0)),
2602            bvec2(true, false),
2603        );
2604
2605        assert_eq!(
2606            Vec2::new(1.0, 2.0).equal(Vec2::new(1.0, 3.0)),
2607            bvec2(true, false),
2608        );
2609
2610        assert_eq!(
2611            Vec2::new(1.0, 2.0).not_equal(Vec2::new(1.0, 3.0)),
2612            bvec2(false, true),
2613        );
2614
2615        assert!(bvec2(true, true).any());
2616        assert!(bvec2(false, true).any());
2617        assert!(bvec2(true, false).any());
2618        assert!(!bvec2(false, false).any());
2619        assert!(bvec2(false, false).none());
2620        assert!(bvec2(true, true).all());
2621        assert!(!bvec2(false, true).all());
2622        assert!(!bvec2(true, false).all());
2623        assert!(!bvec2(false, false).all());
2624
2625        assert_eq!(bvec2(true, false).not(), bvec2(false, true));
2626        assert_eq!(
2627            bvec2(true, false).and(bvec2(true, true)),
2628            bvec2(true, false)
2629        );
2630        assert_eq!(bvec2(true, false).or(bvec2(true, true)), bvec2(true, true));
2631
2632        assert_eq!(
2633            bvec2(true, false).select_vector(Vec2::new(1.0, 2.0), Vec2::new(3.0, 4.0)),
2634            Vec2::new(1.0, 4.0),
2635        );
2636    }
2637
2638    #[test]
2639    fn test_bvec3() {
2640        assert_eq!(
2641            Vec3::new(1.0, 2.0, 3.0).greater_than(Vec3::new(3.0, 2.0, 1.0)),
2642            bvec3(false, false, true),
2643        );
2644
2645        assert_eq!(
2646            Vec3::new(1.0, 2.0, 3.0).lower_than(Vec3::new(3.0, 2.0, 1.0)),
2647            bvec3(true, false, false),
2648        );
2649
2650        assert_eq!(
2651            Vec3::new(1.0, 2.0, 3.0).equal(Vec3::new(3.0, 2.0, 1.0)),
2652            bvec3(false, true, false),
2653        );
2654
2655        assert_eq!(
2656            Vec3::new(1.0, 2.0, 3.0).not_equal(Vec3::new(3.0, 2.0, 1.0)),
2657            bvec3(true, false, true),
2658        );
2659
2660        assert!(bvec3(true, true, false).any());
2661        assert!(bvec3(false, true, false).any());
2662        assert!(bvec3(true, false, false).any());
2663        assert!(!bvec3(false, false, false).any());
2664        assert!(bvec3(false, false, false).none());
2665        assert!(bvec3(true, true, true).all());
2666        assert!(!bvec3(false, true, false).all());
2667        assert!(!bvec3(true, false, false).all());
2668        assert!(!bvec3(false, false, false).all());
2669
2670        assert_eq!(bvec3(true, false, true).not(), bvec3(false, true, false));
2671        assert_eq!(
2672            bvec3(true, false, true).and(bvec3(true, true, false)),
2673            bvec3(true, false, false)
2674        );
2675        assert_eq!(
2676            bvec3(true, false, false).or(bvec3(true, true, false)),
2677            bvec3(true, true, false)
2678        );
2679
2680        assert_eq!(
2681            bvec3(true, false, true)
2682                .select_vector(Vec3::new(1.0, 2.0, 3.0), Vec3::new(4.0, 5.0, 6.0)),
2683            Vec3::new(1.0, 5.0, 3.0),
2684        );
2685    }
2686}