1 // Generated from vec.rs.tera template. Edit the template, not the generated file.
2 
3 use crate::{f32::math, BVec2, Vec3};
4 
5 #[cfg(not(target_arch = "spirv"))]
6 use core::fmt;
7 use core::iter::{Product, Sum};
8 use core::{f32, ops::*};
9 
10 /// Creates a 2-dimensional vector.
11 #[inline(always)]
12 #[must_use]
vec2(x: f32, y: f32) -> Vec213 pub const fn vec2(x: f32, y: f32) -> Vec2 {
14     Vec2::new(x, y)
15 }
16 
17 /// A 2-dimensional vector.
18 #[derive(Clone, Copy, PartialEq)]
19 #[cfg_attr(feature = "cuda", repr(align(8)))]
20 #[cfg_attr(not(target_arch = "spirv"), repr(C))]
21 #[cfg_attr(target_arch = "spirv", repr(simd))]
22 pub struct Vec2 {
23     pub x: f32,
24     pub y: f32,
25 }
26 
27 impl Vec2 {
28     /// All zeroes.
29     pub const ZERO: Self = Self::splat(0.0);
30 
31     /// All ones.
32     pub const ONE: Self = Self::splat(1.0);
33 
34     /// All negative ones.
35     pub const NEG_ONE: Self = Self::splat(-1.0);
36 
37     /// All `f32::MIN`.
38     pub const MIN: Self = Self::splat(f32::MIN);
39 
40     /// All `f32::MAX`.
41     pub const MAX: Self = Self::splat(f32::MAX);
42 
43     /// All `f32::NAN`.
44     pub const NAN: Self = Self::splat(f32::NAN);
45 
46     /// All `f32::INFINITY`.
47     pub const INFINITY: Self = Self::splat(f32::INFINITY);
48 
49     /// All `f32::NEG_INFINITY`.
50     pub const NEG_INFINITY: Self = Self::splat(f32::NEG_INFINITY);
51 
52     /// A unit vector pointing along the positive X axis.
53     pub const X: Self = Self::new(1.0, 0.0);
54 
55     /// A unit vector pointing along the positive Y axis.
56     pub const Y: Self = Self::new(0.0, 1.0);
57 
58     /// A unit vector pointing along the negative X axis.
59     pub const NEG_X: Self = Self::new(-1.0, 0.0);
60 
61     /// A unit vector pointing along the negative Y axis.
62     pub const NEG_Y: Self = Self::new(0.0, -1.0);
63 
64     /// The unit axes.
65     pub const AXES: [Self; 2] = [Self::X, Self::Y];
66 
67     /// Creates a new vector.
68     #[inline(always)]
69     #[must_use]
new(x: f32, y: f32) -> Self70     pub const fn new(x: f32, y: f32) -> Self {
71         Self { x, y }
72     }
73 
74     /// Creates a vector with all elements set to `v`.
75     #[inline]
76     #[must_use]
splat(v: f32) -> Self77     pub const fn splat(v: f32) -> Self {
78         Self { x: v, y: v }
79     }
80 
81     /// Creates a vector from the elements in `if_true` and `if_false`, selecting which to use
82     /// for each element of `self`.
83     ///
84     /// A true element in the mask uses the corresponding element from `if_true`, and false
85     /// uses the element from `if_false`.
86     #[inline]
87     #[must_use]
select(mask: BVec2, if_true: Self, if_false: Self) -> Self88     pub fn select(mask: BVec2, if_true: Self, if_false: Self) -> Self {
89         Self {
90             x: if mask.test(0) { if_true.x } else { if_false.x },
91             y: if mask.test(1) { if_true.y } else { if_false.y },
92         }
93     }
94 
95     /// Creates a new vector from an array.
96     #[inline]
97     #[must_use]
from_array(a: [f32; 2]) -> Self98     pub const fn from_array(a: [f32; 2]) -> Self {
99         Self::new(a[0], a[1])
100     }
101 
102     /// `[x, y]`
103     #[inline]
104     #[must_use]
to_array(&self) -> [f32; 2]105     pub const fn to_array(&self) -> [f32; 2] {
106         [self.x, self.y]
107     }
108 
109     /// Creates a vector from the first 2 values in `slice`.
110     ///
111     /// # Panics
112     ///
113     /// Panics if `slice` is less than 2 elements long.
114     #[inline]
115     #[must_use]
from_slice(slice: &[f32]) -> Self116     pub const fn from_slice(slice: &[f32]) -> Self {
117         Self::new(slice[0], slice[1])
118     }
119 
120     /// Writes the elements of `self` to the first 2 elements in `slice`.
121     ///
122     /// # Panics
123     ///
124     /// Panics if `slice` is less than 2 elements long.
125     #[inline]
write_to_slice(self, slice: &mut [f32])126     pub fn write_to_slice(self, slice: &mut [f32]) {
127         slice[0] = self.x;
128         slice[1] = self.y;
129     }
130 
131     /// Creates a 3D vector from `self` and the given `z` value.
132     #[inline]
133     #[must_use]
extend(self, z: f32) -> Vec3134     pub const fn extend(self, z: f32) -> Vec3 {
135         Vec3::new(self.x, self.y, z)
136     }
137 
138     /// Computes the dot product of `self` and `rhs`.
139     #[inline]
140     #[must_use]
dot(self, rhs: Self) -> f32141     pub fn dot(self, rhs: Self) -> f32 {
142         (self.x * rhs.x) + (self.y * rhs.y)
143     }
144 
145     /// Returns a vector where every component is the dot product of `self` and `rhs`.
146     #[inline]
147     #[must_use]
dot_into_vec(self, rhs: Self) -> Self148     pub fn dot_into_vec(self, rhs: Self) -> Self {
149         Self::splat(self.dot(rhs))
150     }
151 
152     /// Returns a vector containing the minimum values for each element of `self` and `rhs`.
153     ///
154     /// In other words this computes `[self.x.min(rhs.x), self.y.min(rhs.y), ..]`.
155     #[inline]
156     #[must_use]
min(self, rhs: Self) -> Self157     pub fn min(self, rhs: Self) -> Self {
158         Self {
159             x: self.x.min(rhs.x),
160             y: self.y.min(rhs.y),
161         }
162     }
163 
164     /// Returns a vector containing the maximum values for each element of `self` and `rhs`.
165     ///
166     /// In other words this computes `[self.x.max(rhs.x), self.y.max(rhs.y), ..]`.
167     #[inline]
168     #[must_use]
max(self, rhs: Self) -> Self169     pub fn max(self, rhs: Self) -> Self {
170         Self {
171             x: self.x.max(rhs.x),
172             y: self.y.max(rhs.y),
173         }
174     }
175 
176     /// Component-wise clamping of values, similar to [`f32::clamp`].
177     ///
178     /// Each element in `min` must be less-or-equal to the corresponding element in `max`.
179     ///
180     /// # Panics
181     ///
182     /// Will panic if `min` is greater than `max` when `glam_assert` is enabled.
183     #[inline]
184     #[must_use]
clamp(self, min: Self, max: Self) -> Self185     pub fn clamp(self, min: Self, max: Self) -> Self {
186         glam_assert!(min.cmple(max).all(), "clamp: expected min <= max");
187         self.max(min).min(max)
188     }
189 
190     /// Returns the horizontal minimum of `self`.
191     ///
192     /// In other words this computes `min(x, y, ..)`.
193     #[inline]
194     #[must_use]
min_element(self) -> f32195     pub fn min_element(self) -> f32 {
196         self.x.min(self.y)
197     }
198 
199     /// Returns the horizontal maximum of `self`.
200     ///
201     /// In other words this computes `max(x, y, ..)`.
202     #[inline]
203     #[must_use]
max_element(self) -> f32204     pub fn max_element(self) -> f32 {
205         self.x.max(self.y)
206     }
207 
208     /// Returns a vector mask containing the result of a `==` comparison for each element of
209     /// `self` and `rhs`.
210     ///
211     /// In other words, this computes `[self.x == rhs.x, self.y == rhs.y, ..]` for all
212     /// elements.
213     #[inline]
214     #[must_use]
cmpeq(self, rhs: Self) -> BVec2215     pub fn cmpeq(self, rhs: Self) -> BVec2 {
216         BVec2::new(self.x.eq(&rhs.x), self.y.eq(&rhs.y))
217     }
218 
219     /// Returns a vector mask containing the result of a `!=` comparison for each element of
220     /// `self` and `rhs`.
221     ///
222     /// In other words this computes `[self.x != rhs.x, self.y != rhs.y, ..]` for all
223     /// elements.
224     #[inline]
225     #[must_use]
cmpne(self, rhs: Self) -> BVec2226     pub fn cmpne(self, rhs: Self) -> BVec2 {
227         BVec2::new(self.x.ne(&rhs.x), self.y.ne(&rhs.y))
228     }
229 
230     /// Returns a vector mask containing the result of a `>=` comparison for each element of
231     /// `self` and `rhs`.
232     ///
233     /// In other words this computes `[self.x >= rhs.x, self.y >= rhs.y, ..]` for all
234     /// elements.
235     #[inline]
236     #[must_use]
cmpge(self, rhs: Self) -> BVec2237     pub fn cmpge(self, rhs: Self) -> BVec2 {
238         BVec2::new(self.x.ge(&rhs.x), self.y.ge(&rhs.y))
239     }
240 
241     /// Returns a vector mask containing the result of a `>` comparison for each element of
242     /// `self` and `rhs`.
243     ///
244     /// In other words this computes `[self.x > rhs.x, self.y > rhs.y, ..]` for all
245     /// elements.
246     #[inline]
247     #[must_use]
cmpgt(self, rhs: Self) -> BVec2248     pub fn cmpgt(self, rhs: Self) -> BVec2 {
249         BVec2::new(self.x.gt(&rhs.x), self.y.gt(&rhs.y))
250     }
251 
252     /// Returns a vector mask containing the result of a `<=` comparison for each element of
253     /// `self` and `rhs`.
254     ///
255     /// In other words this computes `[self.x <= rhs.x, self.y <= rhs.y, ..]` for all
256     /// elements.
257     #[inline]
258     #[must_use]
cmple(self, rhs: Self) -> BVec2259     pub fn cmple(self, rhs: Self) -> BVec2 {
260         BVec2::new(self.x.le(&rhs.x), self.y.le(&rhs.y))
261     }
262 
263     /// Returns a vector mask containing the result of a `<` comparison for each element of
264     /// `self` and `rhs`.
265     ///
266     /// In other words this computes `[self.x < rhs.x, self.y < rhs.y, ..]` for all
267     /// elements.
268     #[inline]
269     #[must_use]
cmplt(self, rhs: Self) -> BVec2270     pub fn cmplt(self, rhs: Self) -> BVec2 {
271         BVec2::new(self.x.lt(&rhs.x), self.y.lt(&rhs.y))
272     }
273 
274     /// Returns a vector containing the absolute value of each element of `self`.
275     #[inline]
276     #[must_use]
abs(self) -> Self277     pub fn abs(self) -> Self {
278         Self {
279             x: math::abs(self.x),
280             y: math::abs(self.y),
281         }
282     }
283 
284     /// Returns a vector with elements representing the sign of `self`.
285     ///
286     /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
287     /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
288     /// - `NAN` if the number is `NAN`
289     #[inline]
290     #[must_use]
signum(self) -> Self291     pub fn signum(self) -> Self {
292         Self {
293             x: math::signum(self.x),
294             y: math::signum(self.y),
295         }
296     }
297 
298     /// Returns a vector with signs of `rhs` and the magnitudes of `self`.
299     #[inline]
300     #[must_use]
copysign(self, rhs: Self) -> Self301     pub fn copysign(self, rhs: Self) -> Self {
302         Self {
303             x: math::copysign(self.x, rhs.x),
304             y: math::copysign(self.y, rhs.y),
305         }
306     }
307 
308     /// Returns a bitmask with the lowest 2 bits set to the sign bits from the elements of `self`.
309     ///
310     /// A negative element results in a `1` bit and a positive element in a `0` bit.  Element `x` goes
311     /// into the first lowest bit, element `y` into the second, etc.
312     #[inline]
313     #[must_use]
is_negative_bitmask(self) -> u32314     pub fn is_negative_bitmask(self) -> u32 {
315         (self.x.is_sign_negative() as u32) | (self.y.is_sign_negative() as u32) << 1
316     }
317 
318     /// Returns `true` if, and only if, all elements are finite.  If any element is either
319     /// `NaN`, positive or negative infinity, this will return `false`.
320     #[inline]
321     #[must_use]
is_finite(self) -> bool322     pub fn is_finite(self) -> bool {
323         self.x.is_finite() && self.y.is_finite()
324     }
325 
326     /// Returns `true` if any elements are `NaN`.
327     #[inline]
328     #[must_use]
is_nan(self) -> bool329     pub fn is_nan(self) -> bool {
330         self.x.is_nan() || self.y.is_nan()
331     }
332 
333     /// Performs `is_nan` on each element of self, returning a vector mask of the results.
334     ///
335     /// In other words, this computes `[x.is_nan(), y.is_nan(), z.is_nan(), w.is_nan()]`.
336     #[inline]
337     #[must_use]
is_nan_mask(self) -> BVec2338     pub fn is_nan_mask(self) -> BVec2 {
339         BVec2::new(self.x.is_nan(), self.y.is_nan())
340     }
341 
342     /// Computes the length of `self`.
343     #[doc(alias = "magnitude")]
344     #[inline]
345     #[must_use]
length(self) -> f32346     pub fn length(self) -> f32 {
347         math::sqrt(self.dot(self))
348     }
349 
350     /// Computes the squared length of `self`.
351     ///
352     /// This is faster than `length()` as it avoids a square root operation.
353     #[doc(alias = "magnitude2")]
354     #[inline]
355     #[must_use]
length_squared(self) -> f32356     pub fn length_squared(self) -> f32 {
357         self.dot(self)
358     }
359 
360     /// Computes `1.0 / length()`.
361     ///
362     /// For valid results, `self` must _not_ be of length zero.
363     #[inline]
364     #[must_use]
length_recip(self) -> f32365     pub fn length_recip(self) -> f32 {
366         self.length().recip()
367     }
368 
369     /// Computes the Euclidean distance between two points in space.
370     #[inline]
371     #[must_use]
distance(self, rhs: Self) -> f32372     pub fn distance(self, rhs: Self) -> f32 {
373         (self - rhs).length()
374     }
375 
376     /// Compute the squared euclidean distance between two points in space.
377     #[inline]
378     #[must_use]
distance_squared(self, rhs: Self) -> f32379     pub fn distance_squared(self, rhs: Self) -> f32 {
380         (self - rhs).length_squared()
381     }
382 
383     /// Returns the element-wise quotient of [Euclidean division] of `self` by `rhs`.
384     #[inline]
385     #[must_use]
div_euclid(self, rhs: Self) -> Self386     pub fn div_euclid(self, rhs: Self) -> Self {
387         Self::new(
388             math::div_euclid(self.x, rhs.x),
389             math::div_euclid(self.y, rhs.y),
390         )
391     }
392 
393     /// Returns the element-wise remainder of [Euclidean division] of `self` by `rhs`.
394     ///
395     /// [Euclidean division]: f32::rem_euclid
396     #[inline]
397     #[must_use]
rem_euclid(self, rhs: Self) -> Self398     pub fn rem_euclid(self, rhs: Self) -> Self {
399         Self::new(
400             math::rem_euclid(self.x, rhs.x),
401             math::rem_euclid(self.y, rhs.y),
402         )
403     }
404 
405     /// Returns `self` normalized to length 1.0.
406     ///
407     /// For valid results, `self` must _not_ be of length zero, nor very close to zero.
408     ///
409     /// See also [`Self::try_normalize()`] and [`Self::normalize_or_zero()`].
410     ///
411     /// Panics
412     ///
413     /// Will panic if `self` is zero length when `glam_assert` is enabled.
414     #[inline]
415     #[must_use]
normalize(self) -> Self416     pub fn normalize(self) -> Self {
417         #[allow(clippy::let_and_return)]
418         let normalized = self.mul(self.length_recip());
419         glam_assert!(normalized.is_finite());
420         normalized
421     }
422 
423     /// Returns `self` normalized to length 1.0 if possible, else returns `None`.
424     ///
425     /// In particular, if the input is zero (or very close to zero), or non-finite,
426     /// the result of this operation will be `None`.
427     ///
428     /// See also [`Self::normalize_or_zero()`].
429     #[inline]
430     #[must_use]
try_normalize(self) -> Option<Self>431     pub fn try_normalize(self) -> Option<Self> {
432         let rcp = self.length_recip();
433         if rcp.is_finite() && rcp > 0.0 {
434             Some(self * rcp)
435         } else {
436             None
437         }
438     }
439 
440     /// Returns `self` normalized to length 1.0 if possible, else returns zero.
441     ///
442     /// In particular, if the input is zero (or very close to zero), or non-finite,
443     /// the result of this operation will be zero.
444     ///
445     /// See also [`Self::try_normalize()`].
446     #[inline]
447     #[must_use]
normalize_or_zero(self) -> Self448     pub fn normalize_or_zero(self) -> Self {
449         let rcp = self.length_recip();
450         if rcp.is_finite() && rcp > 0.0 {
451             self * rcp
452         } else {
453             Self::ZERO
454         }
455     }
456 
457     /// Returns whether `self` is length `1.0` or not.
458     ///
459     /// Uses a precision threshold of `1e-6`.
460     #[inline]
461     #[must_use]
is_normalized(self) -> bool462     pub fn is_normalized(self) -> bool {
463         // TODO: do something with epsilon
464         math::abs(self.length_squared() - 1.0) <= 1e-4
465     }
466 
467     /// Returns the vector projection of `self` onto `rhs`.
468     ///
469     /// `rhs` must be of non-zero length.
470     ///
471     /// # Panics
472     ///
473     /// Will panic if `rhs` is zero length when `glam_assert` is enabled.
474     #[inline]
475     #[must_use]
project_onto(self, rhs: Self) -> Self476     pub fn project_onto(self, rhs: Self) -> Self {
477         let other_len_sq_rcp = rhs.dot(rhs).recip();
478         glam_assert!(other_len_sq_rcp.is_finite());
479         rhs * self.dot(rhs) * other_len_sq_rcp
480     }
481 
482     /// Returns the vector rejection of `self` from `rhs`.
483     ///
484     /// The vector rejection is the vector perpendicular to the projection of `self` onto
485     /// `rhs`, in rhs words the result of `self - self.project_onto(rhs)`.
486     ///
487     /// `rhs` must be of non-zero length.
488     ///
489     /// # Panics
490     ///
491     /// Will panic if `rhs` has a length of zero when `glam_assert` is enabled.
492     #[inline]
493     #[must_use]
reject_from(self, rhs: Self) -> Self494     pub fn reject_from(self, rhs: Self) -> Self {
495         self - self.project_onto(rhs)
496     }
497 
498     /// Returns the vector projection of `self` onto `rhs`.
499     ///
500     /// `rhs` must be normalized.
501     ///
502     /// # Panics
503     ///
504     /// Will panic if `rhs` is not normalized when `glam_assert` is enabled.
505     #[inline]
506     #[must_use]
project_onto_normalized(self, rhs: Self) -> Self507     pub fn project_onto_normalized(self, rhs: Self) -> Self {
508         glam_assert!(rhs.is_normalized());
509         rhs * self.dot(rhs)
510     }
511 
512     /// Returns the vector rejection of `self` from `rhs`.
513     ///
514     /// The vector rejection is the vector perpendicular to the projection of `self` onto
515     /// `rhs`, in rhs words the result of `self - self.project_onto(rhs)`.
516     ///
517     /// `rhs` must be normalized.
518     ///
519     /// # Panics
520     ///
521     /// Will panic if `rhs` is not normalized when `glam_assert` is enabled.
522     #[inline]
523     #[must_use]
reject_from_normalized(self, rhs: Self) -> Self524     pub fn reject_from_normalized(self, rhs: Self) -> Self {
525         self - self.project_onto_normalized(rhs)
526     }
527 
528     /// Returns a vector containing the nearest integer to a number for each element of `self`.
529     /// Round half-way cases away from 0.0.
530     #[inline]
531     #[must_use]
round(self) -> Self532     pub fn round(self) -> Self {
533         Self {
534             x: math::round(self.x),
535             y: math::round(self.y),
536         }
537     }
538 
539     /// Returns a vector containing the largest integer less than or equal to a number for each
540     /// element of `self`.
541     #[inline]
542     #[must_use]
floor(self) -> Self543     pub fn floor(self) -> Self {
544         Self {
545             x: math::floor(self.x),
546             y: math::floor(self.y),
547         }
548     }
549 
550     /// Returns a vector containing the smallest integer greater than or equal to a number for
551     /// each element of `self`.
552     #[inline]
553     #[must_use]
ceil(self) -> Self554     pub fn ceil(self) -> Self {
555         Self {
556             x: math::ceil(self.x),
557             y: math::ceil(self.y),
558         }
559     }
560 
561     /// Returns a vector containing the integer part each element of `self`. This means numbers are
562     /// always truncated towards zero.
563     #[inline]
564     #[must_use]
trunc(self) -> Self565     pub fn trunc(self) -> Self {
566         Self {
567             x: math::trunc(self.x),
568             y: math::trunc(self.y),
569         }
570     }
571 
572     /// Returns a vector containing the fractional part of the vector, e.g. `self -
573     /// self.floor()`.
574     ///
575     /// Note that this is fast but not precise for large numbers.
576     #[inline]
577     #[must_use]
fract(self) -> Self578     pub fn fract(self) -> Self {
579         self - self.floor()
580     }
581 
582     /// Returns a vector containing `e^self` (the exponential function) for each element of
583     /// `self`.
584     #[inline]
585     #[must_use]
exp(self) -> Self586     pub fn exp(self) -> Self {
587         Self::new(math::exp(self.x), math::exp(self.y))
588     }
589 
590     /// Returns a vector containing each element of `self` raised to the power of `n`.
591     #[inline]
592     #[must_use]
powf(self, n: f32) -> Self593     pub fn powf(self, n: f32) -> Self {
594         Self::new(math::powf(self.x, n), math::powf(self.y, n))
595     }
596 
597     /// Returns a vector containing the reciprocal `1.0/n` of each element of `self`.
598     #[inline]
599     #[must_use]
recip(self) -> Self600     pub fn recip(self) -> Self {
601         Self {
602             x: 1.0 / self.x,
603             y: 1.0 / self.y,
604         }
605     }
606 
607     /// Performs a linear interpolation between `self` and `rhs` based on the value `s`.
608     ///
609     /// When `s` is `0.0`, the result will be equal to `self`.  When `s` is `1.0`, the result
610     /// will be equal to `rhs`. When `s` is outside of range `[0, 1]`, the result is linearly
611     /// extrapolated.
612     #[doc(alias = "mix")]
613     #[inline]
614     #[must_use]
lerp(self, rhs: Self, s: f32) -> Self615     pub fn lerp(self, rhs: Self, s: f32) -> Self {
616         self + ((rhs - self) * s)
617     }
618 
619     /// Returns true if the absolute difference of all elements between `self` and `rhs` is
620     /// less than or equal to `max_abs_diff`.
621     ///
622     /// This can be used to compare if two vectors contain similar elements. It works best when
623     /// comparing with a known value. The `max_abs_diff` that should be used used depends on
624     /// the values being compared against.
625     ///
626     /// For more see
627     /// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
628     #[inline]
629     #[must_use]
abs_diff_eq(self, rhs: Self, max_abs_diff: f32) -> bool630     pub fn abs_diff_eq(self, rhs: Self, max_abs_diff: f32) -> bool {
631         self.sub(rhs).abs().cmple(Self::splat(max_abs_diff)).all()
632     }
633 
634     /// Returns a vector with a length no less than `min` and no more than `max`
635     ///
636     /// # Panics
637     ///
638     /// Will panic if `min` is greater than `max` when `glam_assert` is enabled.
639     #[inline]
640     #[must_use]
clamp_length(self, min: f32, max: f32) -> Self641     pub fn clamp_length(self, min: f32, max: f32) -> Self {
642         glam_assert!(min <= max);
643         let length_sq = self.length_squared();
644         if length_sq < min * min {
645             min * (self / math::sqrt(length_sq))
646         } else if length_sq > max * max {
647             max * (self / math::sqrt(length_sq))
648         } else {
649             self
650         }
651     }
652 
653     /// Returns a vector with a length no more than `max`
654     #[inline]
655     #[must_use]
clamp_length_max(self, max: f32) -> Self656     pub fn clamp_length_max(self, max: f32) -> Self {
657         let length_sq = self.length_squared();
658         if length_sq > max * max {
659             max * (self / math::sqrt(length_sq))
660         } else {
661             self
662         }
663     }
664 
665     /// Returns a vector with a length no less than `min`
666     #[inline]
667     #[must_use]
clamp_length_min(self, min: f32) -> Self668     pub fn clamp_length_min(self, min: f32) -> Self {
669         let length_sq = self.length_squared();
670         if length_sq < min * min {
671             min * (self / math::sqrt(length_sq))
672         } else {
673             self
674         }
675     }
676 
677     /// Fused multiply-add. Computes `(self * a) + b` element-wise with only one rounding
678     /// error, yielding a more accurate result than an unfused multiply-add.
679     ///
680     /// Using `mul_add` *may* be more performant than an unfused multiply-add if the target
681     /// architecture has a dedicated fma CPU instruction. However, this is not always true,
682     /// and will be heavily dependant on designing algorithms with specific target hardware in
683     /// mind.
684     #[inline]
685     #[must_use]
mul_add(self, a: Self, b: Self) -> Self686     pub fn mul_add(self, a: Self, b: Self) -> Self {
687         Self::new(
688             math::mul_add(self.x, a.x, b.x),
689             math::mul_add(self.y, a.y, b.y),
690         )
691     }
692 
693     /// Creates a 2D vector containing `[angle.cos(), angle.sin()]`. This can be used in
694     /// conjunction with the [`rotate()`][Self::rotate()] method, e.g.
695     /// `Vec2::from_angle(PI).rotate(Vec2::Y)` will create the vector `[-1, 0]`
696     /// and rotate [`Vec2::Y`] around it returning `-Vec2::Y`.
697     #[inline]
698     #[must_use]
from_angle(angle: f32) -> Self699     pub fn from_angle(angle: f32) -> Self {
700         let (sin, cos) = math::sin_cos(angle);
701         Self { x: cos, y: sin }
702     }
703 
704     /// Returns the angle (in radians) of this vector in the range `[-π, +π]`.
705     ///
706     /// The input does not need to be a unit vector however it must be non-zero.
707     #[inline]
708     #[must_use]
to_angle(self) -> f32709     pub fn to_angle(self) -> f32 {
710         math::atan2(self.y, self.x)
711     }
712 
713     /// Returns the angle (in radians) between `self` and `rhs` in the range `[-π, +π]`.
714     ///
715     /// The inputs do not need to be unit vectors however they must be non-zero.
716     #[inline]
717     #[must_use]
angle_between(self, rhs: Self) -> f32718     pub fn angle_between(self, rhs: Self) -> f32 {
719         let angle = math::acos_approx(
720             self.dot(rhs) / math::sqrt(self.length_squared() * rhs.length_squared()),
721         );
722 
723         angle * math::signum(self.perp_dot(rhs))
724     }
725 
726     /// Returns a vector that is equal to `self` rotated by 90 degrees.
727     #[inline]
728     #[must_use]
perp(self) -> Self729     pub fn perp(self) -> Self {
730         Self {
731             x: -self.y,
732             y: self.x,
733         }
734     }
735 
736     /// The perpendicular dot product of `self` and `rhs`.
737     /// Also known as the wedge product, 2D cross product, and determinant.
738     #[doc(alias = "wedge")]
739     #[doc(alias = "cross")]
740     #[doc(alias = "determinant")]
741     #[inline]
742     #[must_use]
perp_dot(self, rhs: Self) -> f32743     pub fn perp_dot(self, rhs: Self) -> f32 {
744         (self.x * rhs.y) - (self.y * rhs.x)
745     }
746 
747     /// Returns `rhs` rotated by the angle of `self`. If `self` is normalized,
748     /// then this just rotation. This is what you usually want. Otherwise,
749     /// it will be like a rotation with a multiplication by `self`'s length.
750     #[inline]
751     #[must_use]
rotate(self, rhs: Self) -> Self752     pub fn rotate(self, rhs: Self) -> Self {
753         Self {
754             x: self.x * rhs.x - self.y * rhs.y,
755             y: self.y * rhs.x + self.x * rhs.y,
756         }
757     }
758 
759     /// Casts all elements of `self` to `f64`.
760     #[inline]
761     #[must_use]
as_dvec2(&self) -> crate::DVec2762     pub fn as_dvec2(&self) -> crate::DVec2 {
763         crate::DVec2::new(self.x as f64, self.y as f64)
764     }
765 
766     /// Casts all elements of `self` to `i16`.
767     #[inline]
768     #[must_use]
as_i16vec2(&self) -> crate::I16Vec2769     pub fn as_i16vec2(&self) -> crate::I16Vec2 {
770         crate::I16Vec2::new(self.x as i16, self.y as i16)
771     }
772 
773     /// Casts all elements of `self` to `u16`.
774     #[inline]
775     #[must_use]
as_u16vec2(&self) -> crate::U16Vec2776     pub fn as_u16vec2(&self) -> crate::U16Vec2 {
777         crate::U16Vec2::new(self.x as u16, self.y as u16)
778     }
779 
780     /// Casts all elements of `self` to `i32`.
781     #[inline]
782     #[must_use]
as_ivec2(&self) -> crate::IVec2783     pub fn as_ivec2(&self) -> crate::IVec2 {
784         crate::IVec2::new(self.x as i32, self.y as i32)
785     }
786 
787     /// Casts all elements of `self` to `u32`.
788     #[inline]
789     #[must_use]
as_uvec2(&self) -> crate::UVec2790     pub fn as_uvec2(&self) -> crate::UVec2 {
791         crate::UVec2::new(self.x as u32, self.y as u32)
792     }
793 
794     /// Casts all elements of `self` to `i64`.
795     #[inline]
796     #[must_use]
as_i64vec2(&self) -> crate::I64Vec2797     pub fn as_i64vec2(&self) -> crate::I64Vec2 {
798         crate::I64Vec2::new(self.x as i64, self.y as i64)
799     }
800 
801     /// Casts all elements of `self` to `u64`.
802     #[inline]
803     #[must_use]
as_u64vec2(&self) -> crate::U64Vec2804     pub fn as_u64vec2(&self) -> crate::U64Vec2 {
805         crate::U64Vec2::new(self.x as u64, self.y as u64)
806     }
807 }
808 
809 impl Default for Vec2 {
810     #[inline(always)]
default() -> Self811     fn default() -> Self {
812         Self::ZERO
813     }
814 }
815 
816 impl Div<Vec2> for Vec2 {
817     type Output = Self;
818     #[inline]
div(self, rhs: Self) -> Self819     fn div(self, rhs: Self) -> Self {
820         Self {
821             x: self.x.div(rhs.x),
822             y: self.y.div(rhs.y),
823         }
824     }
825 }
826 
827 impl DivAssign<Vec2> for Vec2 {
828     #[inline]
div_assign(&mut self, rhs: Self)829     fn div_assign(&mut self, rhs: Self) {
830         self.x.div_assign(rhs.x);
831         self.y.div_assign(rhs.y);
832     }
833 }
834 
835 impl Div<f32> for Vec2 {
836     type Output = Self;
837     #[inline]
div(self, rhs: f32) -> Self838     fn div(self, rhs: f32) -> Self {
839         Self {
840             x: self.x.div(rhs),
841             y: self.y.div(rhs),
842         }
843     }
844 }
845 
846 impl DivAssign<f32> for Vec2 {
847     #[inline]
div_assign(&mut self, rhs: f32)848     fn div_assign(&mut self, rhs: f32) {
849         self.x.div_assign(rhs);
850         self.y.div_assign(rhs);
851     }
852 }
853 
854 impl Div<Vec2> for f32 {
855     type Output = Vec2;
856     #[inline]
div(self, rhs: Vec2) -> Vec2857     fn div(self, rhs: Vec2) -> Vec2 {
858         Vec2 {
859             x: self.div(rhs.x),
860             y: self.div(rhs.y),
861         }
862     }
863 }
864 
865 impl Mul<Vec2> for Vec2 {
866     type Output = Self;
867     #[inline]
mul(self, rhs: Self) -> Self868     fn mul(self, rhs: Self) -> Self {
869         Self {
870             x: self.x.mul(rhs.x),
871             y: self.y.mul(rhs.y),
872         }
873     }
874 }
875 
876 impl MulAssign<Vec2> for Vec2 {
877     #[inline]
mul_assign(&mut self, rhs: Self)878     fn mul_assign(&mut self, rhs: Self) {
879         self.x.mul_assign(rhs.x);
880         self.y.mul_assign(rhs.y);
881     }
882 }
883 
884 impl Mul<f32> for Vec2 {
885     type Output = Self;
886     #[inline]
mul(self, rhs: f32) -> Self887     fn mul(self, rhs: f32) -> Self {
888         Self {
889             x: self.x.mul(rhs),
890             y: self.y.mul(rhs),
891         }
892     }
893 }
894 
895 impl MulAssign<f32> for Vec2 {
896     #[inline]
mul_assign(&mut self, rhs: f32)897     fn mul_assign(&mut self, rhs: f32) {
898         self.x.mul_assign(rhs);
899         self.y.mul_assign(rhs);
900     }
901 }
902 
903 impl Mul<Vec2> for f32 {
904     type Output = Vec2;
905     #[inline]
mul(self, rhs: Vec2) -> Vec2906     fn mul(self, rhs: Vec2) -> Vec2 {
907         Vec2 {
908             x: self.mul(rhs.x),
909             y: self.mul(rhs.y),
910         }
911     }
912 }
913 
914 impl Add<Vec2> for Vec2 {
915     type Output = Self;
916     #[inline]
add(self, rhs: Self) -> Self917     fn add(self, rhs: Self) -> Self {
918         Self {
919             x: self.x.add(rhs.x),
920             y: self.y.add(rhs.y),
921         }
922     }
923 }
924 
925 impl AddAssign<Vec2> for Vec2 {
926     #[inline]
add_assign(&mut self, rhs: Self)927     fn add_assign(&mut self, rhs: Self) {
928         self.x.add_assign(rhs.x);
929         self.y.add_assign(rhs.y);
930     }
931 }
932 
933 impl Add<f32> for Vec2 {
934     type Output = Self;
935     #[inline]
add(self, rhs: f32) -> Self936     fn add(self, rhs: f32) -> Self {
937         Self {
938             x: self.x.add(rhs),
939             y: self.y.add(rhs),
940         }
941     }
942 }
943 
944 impl AddAssign<f32> for Vec2 {
945     #[inline]
add_assign(&mut self, rhs: f32)946     fn add_assign(&mut self, rhs: f32) {
947         self.x.add_assign(rhs);
948         self.y.add_assign(rhs);
949     }
950 }
951 
952 impl Add<Vec2> for f32 {
953     type Output = Vec2;
954     #[inline]
add(self, rhs: Vec2) -> Vec2955     fn add(self, rhs: Vec2) -> Vec2 {
956         Vec2 {
957             x: self.add(rhs.x),
958             y: self.add(rhs.y),
959         }
960     }
961 }
962 
963 impl Sub<Vec2> for Vec2 {
964     type Output = Self;
965     #[inline]
sub(self, rhs: Self) -> Self966     fn sub(self, rhs: Self) -> Self {
967         Self {
968             x: self.x.sub(rhs.x),
969             y: self.y.sub(rhs.y),
970         }
971     }
972 }
973 
974 impl SubAssign<Vec2> for Vec2 {
975     #[inline]
sub_assign(&mut self, rhs: Vec2)976     fn sub_assign(&mut self, rhs: Vec2) {
977         self.x.sub_assign(rhs.x);
978         self.y.sub_assign(rhs.y);
979     }
980 }
981 
982 impl Sub<f32> for Vec2 {
983     type Output = Self;
984     #[inline]
sub(self, rhs: f32) -> Self985     fn sub(self, rhs: f32) -> Self {
986         Self {
987             x: self.x.sub(rhs),
988             y: self.y.sub(rhs),
989         }
990     }
991 }
992 
993 impl SubAssign<f32> for Vec2 {
994     #[inline]
sub_assign(&mut self, rhs: f32)995     fn sub_assign(&mut self, rhs: f32) {
996         self.x.sub_assign(rhs);
997         self.y.sub_assign(rhs);
998     }
999 }
1000 
1001 impl Sub<Vec2> for f32 {
1002     type Output = Vec2;
1003     #[inline]
sub(self, rhs: Vec2) -> Vec21004     fn sub(self, rhs: Vec2) -> Vec2 {
1005         Vec2 {
1006             x: self.sub(rhs.x),
1007             y: self.sub(rhs.y),
1008         }
1009     }
1010 }
1011 
1012 impl Rem<Vec2> for Vec2 {
1013     type Output = Self;
1014     #[inline]
rem(self, rhs: Self) -> Self1015     fn rem(self, rhs: Self) -> Self {
1016         Self {
1017             x: self.x.rem(rhs.x),
1018             y: self.y.rem(rhs.y),
1019         }
1020     }
1021 }
1022 
1023 impl RemAssign<Vec2> for Vec2 {
1024     #[inline]
rem_assign(&mut self, rhs: Self)1025     fn rem_assign(&mut self, rhs: Self) {
1026         self.x.rem_assign(rhs.x);
1027         self.y.rem_assign(rhs.y);
1028     }
1029 }
1030 
1031 impl Rem<f32> for Vec2 {
1032     type Output = Self;
1033     #[inline]
rem(self, rhs: f32) -> Self1034     fn rem(self, rhs: f32) -> Self {
1035         Self {
1036             x: self.x.rem(rhs),
1037             y: self.y.rem(rhs),
1038         }
1039     }
1040 }
1041 
1042 impl RemAssign<f32> for Vec2 {
1043     #[inline]
rem_assign(&mut self, rhs: f32)1044     fn rem_assign(&mut self, rhs: f32) {
1045         self.x.rem_assign(rhs);
1046         self.y.rem_assign(rhs);
1047     }
1048 }
1049 
1050 impl Rem<Vec2> for f32 {
1051     type Output = Vec2;
1052     #[inline]
rem(self, rhs: Vec2) -> Vec21053     fn rem(self, rhs: Vec2) -> Vec2 {
1054         Vec2 {
1055             x: self.rem(rhs.x),
1056             y: self.rem(rhs.y),
1057         }
1058     }
1059 }
1060 
1061 #[cfg(not(target_arch = "spirv"))]
1062 impl AsRef<[f32; 2]> for Vec2 {
1063     #[inline]
as_ref(&self) -> &[f32; 2]1064     fn as_ref(&self) -> &[f32; 2] {
1065         unsafe { &*(self as *const Vec2 as *const [f32; 2]) }
1066     }
1067 }
1068 
1069 #[cfg(not(target_arch = "spirv"))]
1070 impl AsMut<[f32; 2]> for Vec2 {
1071     #[inline]
as_mut(&mut self) -> &mut [f32; 2]1072     fn as_mut(&mut self) -> &mut [f32; 2] {
1073         unsafe { &mut *(self as *mut Vec2 as *mut [f32; 2]) }
1074     }
1075 }
1076 
1077 impl Sum for Vec2 {
1078     #[inline]
sum<I>(iter: I) -> Self where I: Iterator<Item = Self>,1079     fn sum<I>(iter: I) -> Self
1080     where
1081         I: Iterator<Item = Self>,
1082     {
1083         iter.fold(Self::ZERO, Self::add)
1084     }
1085 }
1086 
1087 impl<'a> Sum<&'a Self> for Vec2 {
1088     #[inline]
sum<I>(iter: I) -> Self where I: Iterator<Item = &'a Self>,1089     fn sum<I>(iter: I) -> Self
1090     where
1091         I: Iterator<Item = &'a Self>,
1092     {
1093         iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
1094     }
1095 }
1096 
1097 impl Product for Vec2 {
1098     #[inline]
product<I>(iter: I) -> Self where I: Iterator<Item = Self>,1099     fn product<I>(iter: I) -> Self
1100     where
1101         I: Iterator<Item = Self>,
1102     {
1103         iter.fold(Self::ONE, Self::mul)
1104     }
1105 }
1106 
1107 impl<'a> Product<&'a Self> for Vec2 {
1108     #[inline]
product<I>(iter: I) -> Self where I: Iterator<Item = &'a Self>,1109     fn product<I>(iter: I) -> Self
1110     where
1111         I: Iterator<Item = &'a Self>,
1112     {
1113         iter.fold(Self::ONE, |a, &b| Self::mul(a, b))
1114     }
1115 }
1116 
1117 impl Neg for Vec2 {
1118     type Output = Self;
1119     #[inline]
neg(self) -> Self1120     fn neg(self) -> Self {
1121         Self {
1122             x: self.x.neg(),
1123             y: self.y.neg(),
1124         }
1125     }
1126 }
1127 
1128 impl Index<usize> for Vec2 {
1129     type Output = f32;
1130     #[inline]
index(&self, index: usize) -> &Self::Output1131     fn index(&self, index: usize) -> &Self::Output {
1132         match index {
1133             0 => &self.x,
1134             1 => &self.y,
1135             _ => panic!("index out of bounds"),
1136         }
1137     }
1138 }
1139 
1140 impl IndexMut<usize> for Vec2 {
1141     #[inline]
index_mut(&mut self, index: usize) -> &mut Self::Output1142     fn index_mut(&mut self, index: usize) -> &mut Self::Output {
1143         match index {
1144             0 => &mut self.x,
1145             1 => &mut self.y,
1146             _ => panic!("index out of bounds"),
1147         }
1148     }
1149 }
1150 
1151 #[cfg(not(target_arch = "spirv"))]
1152 impl fmt::Display for Vec2 {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result1153     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1154         write!(f, "[{}, {}]", self.x, self.y)
1155     }
1156 }
1157 
1158 #[cfg(not(target_arch = "spirv"))]
1159 impl fmt::Debug for Vec2 {
fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result1160     fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1161         fmt.debug_tuple(stringify!(Vec2))
1162             .field(&self.x)
1163             .field(&self.y)
1164             .finish()
1165     }
1166 }
1167 
1168 impl From<[f32; 2]> for Vec2 {
1169     #[inline]
from(a: [f32; 2]) -> Self1170     fn from(a: [f32; 2]) -> Self {
1171         Self::new(a[0], a[1])
1172     }
1173 }
1174 
1175 impl From<Vec2> for [f32; 2] {
1176     #[inline]
from(v: Vec2) -> Self1177     fn from(v: Vec2) -> Self {
1178         [v.x, v.y]
1179     }
1180 }
1181 
1182 impl From<(f32, f32)> for Vec2 {
1183     #[inline]
from(t: (f32, f32)) -> Self1184     fn from(t: (f32, f32)) -> Self {
1185         Self::new(t.0, t.1)
1186     }
1187 }
1188 
1189 impl From<Vec2> for (f32, f32) {
1190     #[inline]
from(v: Vec2) -> Self1191     fn from(v: Vec2) -> Self {
1192         (v.x, v.y)
1193     }
1194 }
1195