glam/f32/sse2/
vec3a.rs

1// Generated from vec.rs.tera template. Edit the template, not the generated file.
2
3use crate::{f32::math, sse2::*, BVec3, BVec3A, FloatExt, Quat, Vec2, Vec3, Vec4};
4
5use core::fmt;
6use core::iter::{Product, Sum};
7use core::{f32, ops::*};
8
9#[cfg(target_arch = "x86")]
10use core::arch::x86::*;
11#[cfg(target_arch = "x86_64")]
12use core::arch::x86_64::*;
13
14#[repr(C)]
15union UnionCast {
16    a: [f32; 4],
17    v: Vec3A,
18}
19
20/// Creates a 3-dimensional vector.
21#[inline(always)]
22#[must_use]
23pub const fn vec3a(x: f32, y: f32, z: f32) -> Vec3A {
24    Vec3A::new(x, y, z)
25}
26
27/// A 3-dimensional vector.
28///
29/// SIMD vector types are used for storage on supported platforms for better
30/// performance than the [`Vec3`] type.
31///
32/// It is possible to convert between [`Vec3`] and [`Vec3A`] types using [`From`]
33/// or [`Into`] trait implementations.
34///
35/// This type is 16 byte aligned.
36#[derive(Clone, Copy)]
37#[cfg_attr(feature = "bytemuck", derive(bytemuck::Pod, bytemuck::Zeroable))]
38#[repr(transparent)]
39pub struct Vec3A(pub(crate) __m128);
40
41impl Vec3A {
42    /// All zeroes.
43    pub const ZERO: Self = Self::splat(0.0);
44
45    /// All ones.
46    pub const ONE: Self = Self::splat(1.0);
47
48    /// All negative ones.
49    pub const NEG_ONE: Self = Self::splat(-1.0);
50
51    /// All `f32::MIN`.
52    pub const MIN: Self = Self::splat(f32::MIN);
53
54    /// All `f32::MAX`.
55    pub const MAX: Self = Self::splat(f32::MAX);
56
57    /// All `f32::NAN`.
58    pub const NAN: Self = Self::splat(f32::NAN);
59
60    /// All `f32::INFINITY`.
61    pub const INFINITY: Self = Self::splat(f32::INFINITY);
62
63    /// All `f32::NEG_INFINITY`.
64    pub const NEG_INFINITY: Self = Self::splat(f32::NEG_INFINITY);
65
66    /// A unit vector pointing along the positive X axis.
67    pub const X: Self = Self::new(1.0, 0.0, 0.0);
68
69    /// A unit vector pointing along the positive Y axis.
70    pub const Y: Self = Self::new(0.0, 1.0, 0.0);
71
72    /// A unit vector pointing along the positive Z axis.
73    pub const Z: Self = Self::new(0.0, 0.0, 1.0);
74
75    /// A unit vector pointing along the negative X axis.
76    pub const NEG_X: Self = Self::new(-1.0, 0.0, 0.0);
77
78    /// A unit vector pointing along the negative Y axis.
79    pub const NEG_Y: Self = Self::new(0.0, -1.0, 0.0);
80
81    /// A unit vector pointing along the negative Z axis.
82    pub const NEG_Z: Self = Self::new(0.0, 0.0, -1.0);
83
84    /// The unit axes.
85    pub const AXES: [Self; 3] = [Self::X, Self::Y, Self::Z];
86
87    /// Vec3A uses Rust Portable SIMD
88    pub const USES_CORE_SIMD: bool = false;
89    /// Vec3A uses Arm NEON
90    pub const USES_NEON: bool = false;
91    /// Vec3A uses scalar math
92    pub const USES_SCALAR_MATH: bool = false;
93    /// Vec3A uses Intel SSE2
94    pub const USES_SSE2: bool = true;
95    /// Vec3A uses WebAssembly 128-bit SIMD
96    pub const USES_WASM32_SIMD: bool = false;
97
98    /// Creates a new vector.
99    #[inline(always)]
100    #[must_use]
101    pub const fn new(x: f32, y: f32, z: f32) -> Self {
102        unsafe { UnionCast { a: [x, y, z, z] }.v }
103    }
104
105    /// Creates a vector with all elements set to `v`.
106    #[inline]
107    #[must_use]
108    pub const fn splat(v: f32) -> Self {
109        unsafe { UnionCast { a: [v; 4] }.v }
110    }
111
112    /// Returns a vector containing each element of `self` modified by a mapping function `f`.
113    #[inline]
114    #[must_use]
115    pub fn map<F>(self, f: F) -> Self
116    where
117        F: Fn(f32) -> f32,
118    {
119        Self::new(f(self.x), f(self.y), f(self.z))
120    }
121
122    /// Creates a vector from the elements in `if_true` and `if_false`, selecting which to use
123    /// for each element of `self`.
124    ///
125    /// A true element in the mask uses the corresponding element from `if_true`, and false
126    /// uses the element from `if_false`.
127    #[inline]
128    #[must_use]
129    pub fn select(mask: BVec3A, if_true: Self, if_false: Self) -> Self {
130        Self(unsafe {
131            _mm_or_ps(
132                _mm_andnot_ps(mask.0, if_false.0),
133                _mm_and_ps(if_true.0, mask.0),
134            )
135        })
136    }
137
138    /// Creates a new vector from an array.
139    #[inline]
140    #[must_use]
141    pub const fn from_array(a: [f32; 3]) -> Self {
142        Self::new(a[0], a[1], a[2])
143    }
144
145    /// Converts `self` to `[x, y, z]`
146    #[inline]
147    #[must_use]
148    pub const fn to_array(&self) -> [f32; 3] {
149        unsafe { *(self as *const Self as *const [f32; 3]) }
150    }
151
152    /// Creates a vector from the first 3 values in `slice`.
153    ///
154    /// # Panics
155    ///
156    /// Panics if `slice` is less than 3 elements long.
157    #[inline]
158    #[must_use]
159    pub const fn from_slice(slice: &[f32]) -> Self {
160        assert!(slice.len() >= 3);
161        Self::new(slice[0], slice[1], slice[2])
162    }
163
164    /// Writes the elements of `self` to the first 3 elements in `slice`.
165    ///
166    /// # Panics
167    ///
168    /// Panics if `slice` is less than 3 elements long.
169    #[inline]
170    pub fn write_to_slice(self, slice: &mut [f32]) {
171        slice[..3].copy_from_slice(&self.to_array());
172    }
173
174    /// Creates a [`Vec3A`] from the `x`, `y` and `z` elements of `self` discarding `w`.
175    ///
176    /// On architectures where SIMD is supported such as SSE2 on `x86_64` this conversion is a noop.
177    #[inline]
178    #[must_use]
179    pub fn from_vec4(v: Vec4) -> Self {
180        Self(v.0)
181    }
182
183    /// Creates a 4D vector from `self` and the given `w` value.
184    #[inline]
185    #[must_use]
186    pub fn extend(self, w: f32) -> Vec4 {
187        Vec4::new(self.x, self.y, self.z, w)
188    }
189
190    /// Creates a 2D vector from the `x` and `y` elements of `self`, discarding `z`.
191    ///
192    /// Truncation may also be performed by using [`self.xy()`][crate::swizzles::Vec3Swizzles::xy()].
193    #[inline]
194    #[must_use]
195    pub fn truncate(self) -> Vec2 {
196        use crate::swizzles::Vec3Swizzles;
197        self.xy()
198    }
199
200    // Converts `self` to a `Vec3`.
201    #[inline]
202    #[must_use]
203    pub fn to_vec3(self) -> Vec3 {
204        Vec3::from(self)
205    }
206
207    /// Creates a 3D vector from `self` with the given value of `x`.
208    #[inline]
209    #[must_use]
210    pub fn with_x(mut self, x: f32) -> Self {
211        self.x = x;
212        self
213    }
214
215    /// Creates a 3D vector from `self` with the given value of `y`.
216    #[inline]
217    #[must_use]
218    pub fn with_y(mut self, y: f32) -> Self {
219        self.y = y;
220        self
221    }
222
223    /// Creates a 3D vector from `self` with the given value of `z`.
224    #[inline]
225    #[must_use]
226    pub fn with_z(mut self, z: f32) -> Self {
227        self.z = z;
228        self
229    }
230
231    /// Computes the dot product of `self` and `rhs`.
232    #[inline]
233    #[must_use]
234    pub fn dot(self, rhs: Self) -> f32 {
235        unsafe { dot3(self.0, rhs.0) }
236    }
237
238    /// Returns a vector where every component is the dot product of `self` and `rhs`.
239    #[inline]
240    #[must_use]
241    pub fn dot_into_vec(self, rhs: Self) -> Self {
242        Self(unsafe { dot3_into_m128(self.0, rhs.0) })
243    }
244
245    /// Computes the cross product of `self` and `rhs`.
246    #[inline]
247    #[must_use]
248    pub fn cross(self, rhs: Self) -> Self {
249        unsafe {
250            // x  <-  a.y*b.z - a.z*b.y
251            // y  <-  a.z*b.x - a.x*b.z
252            // z  <-  a.x*b.y - a.y*b.x
253            // We can save a shuffle by grouping it in this wacky order:
254            // (self.zxy() * rhs - self * rhs.zxy()).zxy()
255            let lhszxy = _mm_shuffle_ps(self.0, self.0, 0b01_01_00_10);
256            let rhszxy = _mm_shuffle_ps(rhs.0, rhs.0, 0b01_01_00_10);
257            let lhszxy_rhs = _mm_mul_ps(lhszxy, rhs.0);
258            let rhszxy_lhs = _mm_mul_ps(rhszxy, self.0);
259            let sub = _mm_sub_ps(lhszxy_rhs, rhszxy_lhs);
260            Self(_mm_shuffle_ps(sub, sub, 0b01_01_00_10))
261        }
262    }
263
264    /// Returns a vector containing the minimum values for each element of `self` and `rhs`.
265    ///
266    /// In other words this computes `[min(x, rhs.x), min(self.y, rhs.y), ..]`.
267    ///
268    /// NaN propogation does not follow IEEE 754-2008 semantics for minNum and may differ on
269    /// different SIMD architectures.
270    #[inline]
271    #[must_use]
272    pub fn min(self, rhs: Self) -> Self {
273        Self(unsafe { _mm_min_ps(self.0, rhs.0) })
274    }
275
276    /// Returns a vector containing the maximum values for each element of `self` and `rhs`.
277    ///
278    /// In other words this computes `[max(self.x, rhs.x), max(self.y, rhs.y), ..]`.
279    ///
280    /// NaN propogation does not follow IEEE 754-2008 semantics for maxNum and may differ on
281    /// different SIMD architectures.
282    #[inline]
283    #[must_use]
284    pub fn max(self, rhs: Self) -> Self {
285        Self(unsafe { _mm_max_ps(self.0, rhs.0) })
286    }
287
288    /// Component-wise clamping of values, similar to [`f32::clamp`].
289    ///
290    /// Each element in `min` must be less-or-equal to the corresponding element in `max`.
291    ///
292    /// NaN propogation does not follow IEEE 754-2008 semantics and may differ on
293    /// different SIMD architectures.
294    ///
295    /// # Panics
296    ///
297    /// Will panic if `min` is greater than `max` when `glam_assert` is enabled.
298    #[inline]
299    #[must_use]
300    pub fn clamp(self, min: Self, max: Self) -> Self {
301        glam_assert!(min.cmple(max).all(), "clamp: expected min <= max");
302        self.max(min).min(max)
303    }
304
305    /// Returns the horizontal minimum of `self`.
306    ///
307    /// In other words this computes `min(x, y, ..)`.
308    ///
309    /// NaN propogation does not follow IEEE 754-2008 semantics and may differ on
310    /// different SIMD architectures.
311    #[inline]
312    #[must_use]
313    pub fn min_element(self) -> f32 {
314        unsafe {
315            let v = self.0;
316            let v = _mm_min_ps(v, _mm_shuffle_ps(v, v, 0b01_01_10_10));
317            let v = _mm_min_ps(v, _mm_shuffle_ps(v, v, 0b00_00_00_01));
318            _mm_cvtss_f32(v)
319        }
320    }
321
322    /// Returns the horizontal maximum of `self`.
323    ///
324    /// In other words this computes `max(x, y, ..)`.
325    ///
326    /// NaN propogation does not follow IEEE 754-2008 semantics and may differ on
327    /// different SIMD architectures.
328    #[inline]
329    #[must_use]
330    pub fn max_element(self) -> f32 {
331        unsafe {
332            let v = self.0;
333            let v = _mm_max_ps(v, _mm_shuffle_ps(v, v, 0b00_00_10_10));
334            let v = _mm_max_ps(v, _mm_shuffle_ps(v, v, 0b00_00_00_01));
335            _mm_cvtss_f32(v)
336        }
337    }
338
339    /// Returns the index of the first minimum element of `self`.
340    #[doc(alias = "argmin")]
341    #[inline]
342    #[must_use]
343    pub fn min_position(self) -> usize {
344        let mut min = self.x;
345        let mut index = 0;
346        if self.y < min {
347            min = self.y;
348            index = 1;
349        }
350        if self.z < min {
351            index = 2;
352        }
353        index
354    }
355
356    /// Returns the index of the first maximum element of `self`.
357    #[doc(alias = "argmax")]
358    #[inline]
359    #[must_use]
360    pub fn max_position(self) -> usize {
361        let mut max = self.x;
362        let mut index = 0;
363        if self.y > max {
364            max = self.y;
365            index = 1;
366        }
367        if self.z > max {
368            index = 2;
369        }
370        index
371    }
372
373    /// Returns the sum of all elements of `self`.
374    ///
375    /// In other words, this computes `self.x + self.y + ..`.
376    #[inline]
377    #[must_use]
378    pub fn element_sum(self) -> f32 {
379        unsafe {
380            let v = self.0;
381            let v = _mm_add_ps(v, _mm_shuffle_ps(v, Self::ZERO.0, 0b00_11_00_01));
382            let v = _mm_add_ps(v, _mm_shuffle_ps(v, v, 0b00_00_00_10));
383            _mm_cvtss_f32(v)
384        }
385    }
386
387    /// Returns the product of all elements of `self`.
388    ///
389    /// In other words, this computes `self.x * self.y * ..`.
390    #[inline]
391    #[must_use]
392    pub fn element_product(self) -> f32 {
393        unsafe {
394            let v = self.0;
395            let v = _mm_mul_ps(v, _mm_shuffle_ps(v, Self::ONE.0, 0b00_11_00_01));
396            let v = _mm_mul_ps(v, _mm_shuffle_ps(v, v, 0b00_00_00_10));
397            _mm_cvtss_f32(v)
398        }
399    }
400
401    /// Returns a vector mask containing the result of a `==` comparison for each element of
402    /// `self` and `rhs`.
403    ///
404    /// In other words, this computes `[self.x == rhs.x, self.y == rhs.y, ..]` for all
405    /// elements.
406    #[inline]
407    #[must_use]
408    pub fn cmpeq(self, rhs: Self) -> BVec3A {
409        BVec3A(unsafe { _mm_cmpeq_ps(self.0, rhs.0) })
410    }
411
412    /// Returns a vector mask containing the result of a `!=` comparison for each element of
413    /// `self` and `rhs`.
414    ///
415    /// In other words this computes `[self.x != rhs.x, self.y != rhs.y, ..]` for all
416    /// elements.
417    #[inline]
418    #[must_use]
419    pub fn cmpne(self, rhs: Self) -> BVec3A {
420        BVec3A(unsafe { _mm_cmpneq_ps(self.0, rhs.0) })
421    }
422
423    /// Returns a vector mask containing the result of a `>=` comparison for each element of
424    /// `self` and `rhs`.
425    ///
426    /// In other words this computes `[self.x >= rhs.x, self.y >= rhs.y, ..]` for all
427    /// elements.
428    #[inline]
429    #[must_use]
430    pub fn cmpge(self, rhs: Self) -> BVec3A {
431        BVec3A(unsafe { _mm_cmpge_ps(self.0, rhs.0) })
432    }
433
434    /// Returns a vector mask containing the result of a `>` comparison for each element of
435    /// `self` and `rhs`.
436    ///
437    /// In other words this computes `[self.x > rhs.x, self.y > rhs.y, ..]` for all
438    /// elements.
439    #[inline]
440    #[must_use]
441    pub fn cmpgt(self, rhs: Self) -> BVec3A {
442        BVec3A(unsafe { _mm_cmpgt_ps(self.0, rhs.0) })
443    }
444
445    /// Returns a vector mask containing the result of a `<=` comparison for each element of
446    /// `self` and `rhs`.
447    ///
448    /// In other words this computes `[self.x <= rhs.x, self.y <= rhs.y, ..]` for all
449    /// elements.
450    #[inline]
451    #[must_use]
452    pub fn cmple(self, rhs: Self) -> BVec3A {
453        BVec3A(unsafe { _mm_cmple_ps(self.0, rhs.0) })
454    }
455
456    /// Returns a vector mask containing the result of a `<` comparison for each element of
457    /// `self` and `rhs`.
458    ///
459    /// In other words this computes `[self.x < rhs.x, self.y < rhs.y, ..]` for all
460    /// elements.
461    #[inline]
462    #[must_use]
463    pub fn cmplt(self, rhs: Self) -> BVec3A {
464        BVec3A(unsafe { _mm_cmplt_ps(self.0, rhs.0) })
465    }
466
467    /// Returns a vector containing the absolute value of each element of `self`.
468    #[inline]
469    #[must_use]
470    pub fn abs(self) -> Self {
471        Self(unsafe { crate::sse2::m128_abs(self.0) })
472    }
473
474    /// Returns a vector with elements representing the sign of `self`.
475    ///
476    /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
477    /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
478    /// - `NAN` if the number is `NAN`
479    #[inline]
480    #[must_use]
481    pub fn signum(self) -> Self {
482        let result = Self(unsafe { _mm_or_ps(_mm_and_ps(self.0, Self::NEG_ONE.0), Self::ONE.0) });
483        let mask = self.is_nan_mask();
484        Self::select(mask, self, result)
485    }
486
487    /// Returns a vector with signs of `rhs` and the magnitudes of `self`.
488    #[inline]
489    #[must_use]
490    pub fn copysign(self, rhs: Self) -> Self {
491        let mask = Self::splat(-0.0);
492        Self(unsafe { _mm_or_ps(_mm_and_ps(rhs.0, mask.0), _mm_andnot_ps(mask.0, self.0)) })
493    }
494
495    /// Returns a bitmask with the lowest 3 bits set to the sign bits from the elements of `self`.
496    ///
497    /// A negative element results in a `1` bit and a positive element in a `0` bit.  Element `x` goes
498    /// into the first lowest bit, element `y` into the second, etc.
499    ///
500    /// An element is negative if it has a negative sign, including -0.0, NaNs with negative sign
501    /// bit and negative infinity.
502    #[inline]
503    #[must_use]
504    pub fn is_negative_bitmask(self) -> u32 {
505        unsafe { (_mm_movemask_ps(self.0) as u32) & 0x7 }
506    }
507
508    /// Returns `true` if, and only if, all elements are finite.  If any element is either
509    /// `NaN`, positive or negative infinity, this will return `false`.
510    #[inline]
511    #[must_use]
512    pub fn is_finite(self) -> bool {
513        self.is_finite_mask().all()
514    }
515
516    /// Performs `is_finite` on each element of self, returning a vector mask of the results.
517    ///
518    /// In other words, this computes `[x.is_finite(), y.is_finite(), ...]`.
519    #[inline]
520    #[must_use]
521    pub fn is_finite_mask(self) -> BVec3A {
522        BVec3A(unsafe { _mm_cmplt_ps(crate::sse2::m128_abs(self.0), Self::INFINITY.0) })
523    }
524
525    /// Returns `true` if any elements are `NaN`.
526    #[inline]
527    #[must_use]
528    pub fn is_nan(self) -> bool {
529        self.is_nan_mask().any()
530    }
531
532    /// Performs `is_nan` on each element of self, returning a vector mask of the results.
533    ///
534    /// In other words, this computes `[x.is_nan(), y.is_nan(), ...]`.
535    #[inline]
536    #[must_use]
537    pub fn is_nan_mask(self) -> BVec3A {
538        BVec3A(unsafe { _mm_cmpunord_ps(self.0, self.0) })
539    }
540
541    /// Computes the length of `self`.
542    #[doc(alias = "magnitude")]
543    #[inline]
544    #[must_use]
545    pub fn length(self) -> f32 {
546        unsafe {
547            let dot = dot3_in_x(self.0, self.0);
548            _mm_cvtss_f32(_mm_sqrt_ps(dot))
549        }
550    }
551
552    /// Computes the squared length of `self`.
553    ///
554    /// This is faster than `length()` as it avoids a square root operation.
555    #[doc(alias = "magnitude2")]
556    #[inline]
557    #[must_use]
558    pub fn length_squared(self) -> f32 {
559        self.dot(self)
560    }
561
562    /// Computes `1.0 / length()`.
563    ///
564    /// For valid results, `self` must _not_ be of length zero.
565    #[inline]
566    #[must_use]
567    pub fn length_recip(self) -> f32 {
568        unsafe {
569            let dot = dot3_in_x(self.0, self.0);
570            _mm_cvtss_f32(_mm_div_ps(Self::ONE.0, _mm_sqrt_ps(dot)))
571        }
572    }
573
574    /// Computes the Euclidean distance between two points in space.
575    #[inline]
576    #[must_use]
577    pub fn distance(self, rhs: Self) -> f32 {
578        (self - rhs).length()
579    }
580
581    /// Compute the squared euclidean distance between two points in space.
582    #[inline]
583    #[must_use]
584    pub fn distance_squared(self, rhs: Self) -> f32 {
585        (self - rhs).length_squared()
586    }
587
588    /// Returns the element-wise quotient of [Euclidean division] of `self` by `rhs`.
589    #[inline]
590    #[must_use]
591    pub fn div_euclid(self, rhs: Self) -> Self {
592        Self::new(
593            math::div_euclid(self.x, rhs.x),
594            math::div_euclid(self.y, rhs.y),
595            math::div_euclid(self.z, rhs.z),
596        )
597    }
598
599    /// Returns the element-wise remainder of [Euclidean division] of `self` by `rhs`.
600    ///
601    /// [Euclidean division]: f32::rem_euclid
602    #[inline]
603    #[must_use]
604    pub fn rem_euclid(self, rhs: Self) -> Self {
605        Self::new(
606            math::rem_euclid(self.x, rhs.x),
607            math::rem_euclid(self.y, rhs.y),
608            math::rem_euclid(self.z, rhs.z),
609        )
610    }
611
612    /// Returns `self` normalized to length 1.0.
613    ///
614    /// For valid results, `self` must be finite and _not_ of length zero, nor very close to zero.
615    ///
616    /// See also [`Self::try_normalize()`] and [`Self::normalize_or_zero()`].
617    ///
618    /// # Panics
619    ///
620    /// Will panic if the resulting normalized vector is not finite when `glam_assert` is enabled.
621    #[inline]
622    #[must_use]
623    pub fn normalize(self) -> Self {
624        unsafe {
625            let length = _mm_sqrt_ps(dot3_into_m128(self.0, self.0));
626            #[allow(clippy::let_and_return)]
627            let normalized = Self(_mm_div_ps(self.0, length));
628            glam_assert!(normalized.is_finite());
629            normalized
630        }
631    }
632
633    /// Returns `self` normalized to length 1.0 if possible, else returns `None`.
634    ///
635    /// In particular, if the input is zero (or very close to zero), or non-finite,
636    /// the result of this operation will be `None`.
637    ///
638    /// See also [`Self::normalize_or_zero()`].
639    #[inline]
640    #[must_use]
641    pub fn try_normalize(self) -> Option<Self> {
642        let rcp = self.length_recip();
643        if rcp.is_finite() && rcp > 0.0 {
644            Some(self * rcp)
645        } else {
646            None
647        }
648    }
649
650    /// Returns `self` normalized to length 1.0 if possible, else returns a
651    /// fallback value.
652    ///
653    /// In particular, if the input is zero (or very close to zero), or non-finite,
654    /// the result of this operation will be the fallback value.
655    ///
656    /// See also [`Self::try_normalize()`].
657    #[inline]
658    #[must_use]
659    pub fn normalize_or(self, fallback: Self) -> Self {
660        let rcp = self.length_recip();
661        if rcp.is_finite() && rcp > 0.0 {
662            self * rcp
663        } else {
664            fallback
665        }
666    }
667
668    /// Returns `self` normalized to length 1.0 if possible, else returns zero.
669    ///
670    /// In particular, if the input is zero (or very close to zero), or non-finite,
671    /// the result of this operation will be zero.
672    ///
673    /// See also [`Self::try_normalize()`].
674    #[inline]
675    #[must_use]
676    pub fn normalize_or_zero(self) -> Self {
677        self.normalize_or(Self::ZERO)
678    }
679
680    /// Returns `self` normalized to length 1.0 and the length of `self`.
681    ///
682    /// If `self` is zero length then `(Self::X, 0.0)` is returned.
683    #[inline]
684    #[must_use]
685    pub fn normalize_and_length(self) -> (Self, f32) {
686        let length = self.length();
687        let rcp = 1.0 / length;
688        if rcp.is_finite() && rcp > 0.0 {
689            (self * rcp, length)
690        } else {
691            (Self::X, 0.0)
692        }
693    }
694
695    /// Returns whether `self` is length `1.0` or not.
696    ///
697    /// Uses a precision threshold of approximately `1e-4`.
698    #[inline]
699    #[must_use]
700    pub fn is_normalized(self) -> bool {
701        math::abs(self.length_squared() - 1.0) <= 2e-4
702    }
703
704    /// Returns the vector projection of `self` onto `rhs`.
705    ///
706    /// `rhs` must be of non-zero length.
707    ///
708    /// # Panics
709    ///
710    /// Will panic if `rhs` is zero length when `glam_assert` is enabled.
711    #[inline]
712    #[must_use]
713    pub fn project_onto(self, rhs: Self) -> Self {
714        let other_len_sq_rcp = rhs.dot(rhs).recip();
715        glam_assert!(other_len_sq_rcp.is_finite());
716        rhs * self.dot(rhs) * other_len_sq_rcp
717    }
718
719    /// Returns the vector rejection of `self` from `rhs`.
720    ///
721    /// The vector rejection is the vector perpendicular to the projection of `self` onto
722    /// `rhs`, in rhs words the result of `self - self.project_onto(rhs)`.
723    ///
724    /// `rhs` must be of non-zero length.
725    ///
726    /// # Panics
727    ///
728    /// Will panic if `rhs` has a length of zero when `glam_assert` is enabled.
729    #[doc(alias("plane"))]
730    #[inline]
731    #[must_use]
732    pub fn reject_from(self, rhs: Self) -> Self {
733        self - self.project_onto(rhs)
734    }
735
736    /// Returns the vector projection of `self` onto `rhs`.
737    ///
738    /// `rhs` must be normalized.
739    ///
740    /// # Panics
741    ///
742    /// Will panic if `rhs` is not normalized when `glam_assert` is enabled.
743    #[inline]
744    #[must_use]
745    pub fn project_onto_normalized(self, rhs: Self) -> Self {
746        glam_assert!(rhs.is_normalized());
747        rhs * self.dot(rhs)
748    }
749
750    /// Returns the vector rejection of `self` from `rhs`.
751    ///
752    /// The vector rejection is the vector perpendicular to the projection of `self` onto
753    /// `rhs`, in rhs words the result of `self - self.project_onto(rhs)`.
754    ///
755    /// `rhs` must be normalized.
756    ///
757    /// # Panics
758    ///
759    /// Will panic if `rhs` is not normalized when `glam_assert` is enabled.
760    #[doc(alias("plane"))]
761    #[inline]
762    #[must_use]
763    pub fn reject_from_normalized(self, rhs: Self) -> Self {
764        self - self.project_onto_normalized(rhs)
765    }
766
767    /// Returns a vector containing the nearest integer to a number for each element of `self`.
768    /// Round half-way cases away from 0.0.
769    #[inline]
770    #[must_use]
771    pub fn round(self) -> Self {
772        Self(unsafe { m128_round(self.0) })
773    }
774
775    /// Returns a vector containing the largest integer less than or equal to a number for each
776    /// element of `self`.
777    #[inline]
778    #[must_use]
779    pub fn floor(self) -> Self {
780        Self(unsafe { m128_floor(self.0) })
781    }
782
783    /// Returns a vector containing the smallest integer greater than or equal to a number for
784    /// each element of `self`.
785    #[inline]
786    #[must_use]
787    pub fn ceil(self) -> Self {
788        Self(unsafe { m128_ceil(self.0) })
789    }
790
791    /// Returns a vector containing the integer part each element of `self`. This means numbers are
792    /// always truncated towards zero.
793    #[inline]
794    #[must_use]
795    pub fn trunc(self) -> Self {
796        Self(unsafe { m128_trunc(self.0) })
797    }
798
799    /// Returns a vector containing the fractional part of the vector as `self - self.trunc()`.
800    ///
801    /// Note that this differs from the GLSL implementation of `fract` which returns
802    /// `self - self.floor()`.
803    ///
804    /// Note that this is fast but not precise for large numbers.
805    #[inline]
806    #[must_use]
807    pub fn fract(self) -> Self {
808        self - self.trunc()
809    }
810
811    /// Returns a vector containing the fractional part of the vector as `self - self.floor()`.
812    ///
813    /// Note that this differs from the Rust implementation of `fract` which returns
814    /// `self - self.trunc()`.
815    ///
816    /// Note that this is fast but not precise for large numbers.
817    #[inline]
818    #[must_use]
819    pub fn fract_gl(self) -> Self {
820        self - self.floor()
821    }
822
823    /// Returns a vector containing `e^self` (the exponential function) for each element of
824    /// `self`.
825    #[inline]
826    #[must_use]
827    pub fn exp(self) -> Self {
828        Self::new(math::exp(self.x), math::exp(self.y), math::exp(self.z))
829    }
830
831    /// Returns a vector containing each element of `self` raised to the power of `n`.
832    #[inline]
833    #[must_use]
834    pub fn powf(self, n: f32) -> Self {
835        Self::new(
836            math::powf(self.x, n),
837            math::powf(self.y, n),
838            math::powf(self.z, n),
839        )
840    }
841
842    /// Returns a vector containing the reciprocal `1.0/n` of each element of `self`.
843    #[inline]
844    #[must_use]
845    pub fn recip(self) -> Self {
846        Self(unsafe { _mm_div_ps(Self::ONE.0, self.0) })
847    }
848
849    /// Performs a linear interpolation between `self` and `rhs` based on the value `s`.
850    ///
851    /// When `s` is `0.0`, the result will be equal to `self`.  When `s` is `1.0`, the result
852    /// will be equal to `rhs`. When `s` is outside of range `[0, 1]`, the result is linearly
853    /// extrapolated.
854    #[doc(alias = "mix")]
855    #[inline]
856    #[must_use]
857    pub fn lerp(self, rhs: Self, s: f32) -> Self {
858        self * (1.0 - s) + rhs * s
859    }
860
861    /// Moves towards `rhs` based on the value `d`.
862    ///
863    /// When `d` is `0.0`, the result will be equal to `self`. When `d` is equal to
864    /// `self.distance(rhs)`, the result will be equal to `rhs`. Will not go past `rhs`.
865    #[inline]
866    #[must_use]
867    pub fn move_towards(&self, rhs: Self, d: f32) -> Self {
868        let a = rhs - *self;
869        let len = a.length();
870        if len <= d || len <= 1e-4 {
871            return rhs;
872        }
873        *self + a / len * d
874    }
875
876    /// Calculates the midpoint between `self` and `rhs`.
877    ///
878    /// The midpoint is the average of, or halfway point between, two vectors.
879    /// `a.midpoint(b)` should yield the same result as `a.lerp(b, 0.5)`
880    /// while being slightly cheaper to compute.
881    #[inline]
882    pub fn midpoint(self, rhs: Self) -> Self {
883        (self + rhs) * 0.5
884    }
885
886    /// Returns true if the absolute difference of all elements between `self` and `rhs` is
887    /// less than or equal to `max_abs_diff`.
888    ///
889    /// This can be used to compare if two vectors contain similar elements. It works best when
890    /// comparing with a known value. The `max_abs_diff` that should be used used depends on
891    /// the values being compared against.
892    ///
893    /// For more see
894    /// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
895    #[inline]
896    #[must_use]
897    pub fn abs_diff_eq(self, rhs: Self, max_abs_diff: f32) -> bool {
898        self.sub(rhs).abs().cmple(Self::splat(max_abs_diff)).all()
899    }
900
901    /// Returns a vector with a length no less than `min` and no more than `max`.
902    ///
903    /// # Panics
904    ///
905    /// Will panic if `min` is greater than `max`, or if either `min` or `max` is negative, when `glam_assert` is enabled.
906    #[inline]
907    #[must_use]
908    pub fn clamp_length(self, min: f32, max: f32) -> Self {
909        glam_assert!(0.0 <= min);
910        glam_assert!(min <= max);
911        let length_sq = self.length_squared();
912        if length_sq < min * min {
913            min * (self / math::sqrt(length_sq))
914        } else if length_sq > max * max {
915            max * (self / math::sqrt(length_sq))
916        } else {
917            self
918        }
919    }
920
921    /// Returns a vector with a length no more than `max`.
922    ///
923    /// # Panics
924    ///
925    /// Will panic if `max` is negative when `glam_assert` is enabled.
926    #[inline]
927    #[must_use]
928    pub fn clamp_length_max(self, max: f32) -> Self {
929        glam_assert!(0.0 <= max);
930        let length_sq = self.length_squared();
931        if length_sq > max * max {
932            max * (self / math::sqrt(length_sq))
933        } else {
934            self
935        }
936    }
937
938    /// Returns a vector with a length no less than `min`.
939    ///
940    /// # Panics
941    ///
942    /// Will panic if `min` is negative when `glam_assert` is enabled.
943    #[inline]
944    #[must_use]
945    pub fn clamp_length_min(self, min: f32) -> Self {
946        glam_assert!(0.0 <= min);
947        let length_sq = self.length_squared();
948        if length_sq < min * min {
949            min * (self / math::sqrt(length_sq))
950        } else {
951            self
952        }
953    }
954
955    /// Fused multiply-add. Computes `(self * a) + b` element-wise with only one rounding
956    /// error, yielding a more accurate result than an unfused multiply-add.
957    ///
958    /// Using `mul_add` *may* be more performant than an unfused multiply-add if the target
959    /// architecture has a dedicated fma CPU instruction. However, this is not always true,
960    /// and will be heavily dependant on designing algorithms with specific target hardware in
961    /// mind.
962    #[inline]
963    #[must_use]
964    pub fn mul_add(self, a: Self, b: Self) -> Self {
965        #[cfg(target_feature = "fma")]
966        unsafe {
967            Self(_mm_fmadd_ps(self.0, a.0, b.0))
968        }
969        #[cfg(not(target_feature = "fma"))]
970        Self::new(
971            math::mul_add(self.x, a.x, b.x),
972            math::mul_add(self.y, a.y, b.y),
973            math::mul_add(self.z, a.z, b.z),
974        )
975    }
976
977    /// Returns the reflection vector for a given incident vector `self` and surface normal
978    /// `normal`.
979    ///
980    /// `normal` must be normalized.
981    ///
982    /// # Panics
983    ///
984    /// Will panic if `normal` is not normalized when `glam_assert` is enabled.
985    #[inline]
986    #[must_use]
987    pub fn reflect(self, normal: Self) -> Self {
988        glam_assert!(normal.is_normalized());
989        self - 2.0 * self.dot(normal) * normal
990    }
991
992    /// Returns the refraction direction for a given incident vector `self`, surface normal
993    /// `normal` and ratio of indices of refraction, `eta`. When total internal reflection occurs,
994    /// a zero vector will be returned.
995    ///
996    /// `self` and `normal` must be normalized.
997    ///
998    /// # Panics
999    ///
1000    /// Will panic if `self` or `normal` is not normalized when `glam_assert` is enabled.
1001    #[inline]
1002    #[must_use]
1003    pub fn refract(self, normal: Self, eta: f32) -> Self {
1004        glam_assert!(self.is_normalized());
1005        glam_assert!(normal.is_normalized());
1006        let n_dot_i = normal.dot(self);
1007        let k = 1.0 - eta * eta * (1.0 - n_dot_i * n_dot_i);
1008        if k >= 0.0 {
1009            eta * self - (eta * n_dot_i + math::sqrt(k)) * normal
1010        } else {
1011            Self::ZERO
1012        }
1013    }
1014
1015    /// Returns the angle (in radians) between two vectors in the range `[0, +Ï€]`.
1016    ///
1017    /// The inputs do not need to be unit vectors however they must be non-zero.
1018    #[inline]
1019    #[must_use]
1020    pub fn angle_between(self, rhs: Self) -> f32 {
1021        math::acos_approx(
1022            self.dot(rhs)
1023                .div(math::sqrt(self.length_squared().mul(rhs.length_squared()))),
1024        )
1025    }
1026
1027    /// Rotates towards `rhs` up to `max_angle` (in radians).
1028    ///
1029    /// When `max_angle` is `0.0`, the result will be equal to `self`. When `max_angle` is equal to
1030    /// `self.angle_between(rhs)`, the result will be parallel to `rhs`. If `max_angle` is negative,
1031    /// rotates towards the exact opposite of `rhs`. Will not go past the target.
1032    #[inline]
1033    #[must_use]
1034    pub fn rotate_towards(self, rhs: Self, max_angle: f32) -> Self {
1035        let angle_between = self.angle_between(rhs);
1036        // When `max_angle < 0`, rotate no further than `PI` radians away
1037        let angle = max_angle.clamp(angle_between - core::f32::consts::PI, angle_between);
1038        let axis = self
1039            .cross(rhs)
1040            .try_normalize()
1041            .unwrap_or_else(|| self.any_orthogonal_vector().normalize());
1042        Quat::from_axis_angle(axis.into(), angle) * self
1043    }
1044
1045    /// Returns some vector that is orthogonal to the given one.
1046    ///
1047    /// The input vector must be finite and non-zero.
1048    ///
1049    /// The output vector is not necessarily unit length. For that use
1050    /// [`Self::any_orthonormal_vector()`] instead.
1051    #[inline]
1052    #[must_use]
1053    pub fn any_orthogonal_vector(&self) -> Self {
1054        // This can probably be optimized
1055        if math::abs(self.x) > math::abs(self.y) {
1056            Self::new(-self.z, 0.0, self.x) // self.cross(Self::Y)
1057        } else {
1058            Self::new(0.0, self.z, -self.y) // self.cross(Self::X)
1059        }
1060    }
1061
1062    /// Returns any unit vector that is orthogonal to the given one.
1063    ///
1064    /// The input vector must be unit length.
1065    ///
1066    /// # Panics
1067    ///
1068    /// Will panic if `self` is not normalized when `glam_assert` is enabled.
1069    #[inline]
1070    #[must_use]
1071    pub fn any_orthonormal_vector(&self) -> Self {
1072        glam_assert!(self.is_normalized());
1073        // From https://graphics.pixar.com/library/OrthonormalB/paper.pdf
1074        let sign = math::signum(self.z);
1075        let a = -1.0 / (sign + self.z);
1076        let b = self.x * self.y * a;
1077        Self::new(b, sign + self.y * self.y * a, -self.y)
1078    }
1079
1080    /// Given a unit vector return two other vectors that together form an orthonormal
1081    /// basis. That is, all three vectors are orthogonal to each other and are normalized.
1082    ///
1083    /// # Panics
1084    ///
1085    /// Will panic if `self` is not normalized when `glam_assert` is enabled.
1086    #[inline]
1087    #[must_use]
1088    pub fn any_orthonormal_pair(&self) -> (Self, Self) {
1089        glam_assert!(self.is_normalized());
1090        // From https://graphics.pixar.com/library/OrthonormalB/paper.pdf
1091        let sign = math::signum(self.z);
1092        let a = -1.0 / (sign + self.z);
1093        let b = self.x * self.y * a;
1094        (
1095            Self::new(1.0 + sign * self.x * self.x * a, sign * b, -sign * self.x),
1096            Self::new(b, sign + self.y * self.y * a, -self.y),
1097        )
1098    }
1099
1100    /// Performs a spherical linear interpolation between `self` and `rhs` based on the value `s`.
1101    ///
1102    /// When `s` is `0.0`, the result will be equal to `self`.  When `s` is `1.0`, the result
1103    /// will be equal to `rhs`. When `s` is outside of range `[0, 1]`, the result is linearly
1104    /// extrapolated.
1105    #[inline]
1106    #[must_use]
1107    pub fn slerp(self, rhs: Self, s: f32) -> Self {
1108        let self_length = self.length();
1109        let rhs_length = rhs.length();
1110        // Cosine of the angle between the vectors [-1, 1], or NaN if either vector has a zero length
1111        let dot = self.dot(rhs) / (self_length * rhs_length);
1112        // If dot is close to 1 or -1, or is NaN the calculations for t1 and t2 break down
1113        if math::abs(dot) < 1.0 - 3e-7 {
1114            // Angle between the vectors [0, +Ï€]
1115            let theta = math::acos_approx(dot);
1116            // Sine of the angle between vectors [0, 1]
1117            let sin_theta = math::sin(theta);
1118            let t1 = math::sin(theta * (1. - s));
1119            let t2 = math::sin(theta * s);
1120
1121            // Interpolate vector lengths
1122            let result_length = self_length.lerp(rhs_length, s);
1123            // Scale the vectors to the target length and interpolate them
1124            return (self * (result_length / self_length) * t1
1125                + rhs * (result_length / rhs_length) * t2)
1126                * sin_theta.recip();
1127        }
1128        if dot < 0.0 {
1129            // Vectors are almost parallel in opposing directions
1130
1131            // Create a rotation from self to rhs along some axis
1132            let axis = self.any_orthogonal_vector().normalize().into();
1133            let rotation = Quat::from_axis_angle(axis, core::f32::consts::PI * s);
1134            // Interpolate vector lengths
1135            let result_length = self_length.lerp(rhs_length, s);
1136            rotation * self * (result_length / self_length)
1137        } else {
1138            // Vectors are almost parallel in the same direction, or dot was NaN
1139            self.lerp(rhs, s)
1140        }
1141    }
1142
1143    /// Casts all elements of `self` to `f64`.
1144    #[inline]
1145    #[must_use]
1146    pub fn as_dvec3(&self) -> crate::DVec3 {
1147        crate::DVec3::new(self.x as f64, self.y as f64, self.z as f64)
1148    }
1149
1150    /// Casts all elements of `self` to `i8`.
1151    #[inline]
1152    #[must_use]
1153    pub fn as_i8vec3(&self) -> crate::I8Vec3 {
1154        crate::I8Vec3::new(self.x as i8, self.y as i8, self.z as i8)
1155    }
1156
1157    /// Casts all elements of `self` to `u8`.
1158    #[inline]
1159    #[must_use]
1160    pub fn as_u8vec3(&self) -> crate::U8Vec3 {
1161        crate::U8Vec3::new(self.x as u8, self.y as u8, self.z as u8)
1162    }
1163
1164    /// Casts all elements of `self` to `i16`.
1165    #[inline]
1166    #[must_use]
1167    pub fn as_i16vec3(&self) -> crate::I16Vec3 {
1168        crate::I16Vec3::new(self.x as i16, self.y as i16, self.z as i16)
1169    }
1170
1171    /// Casts all elements of `self` to `u16`.
1172    #[inline]
1173    #[must_use]
1174    pub fn as_u16vec3(&self) -> crate::U16Vec3 {
1175        crate::U16Vec3::new(self.x as u16, self.y as u16, self.z as u16)
1176    }
1177
1178    /// Casts all elements of `self` to `i32`.
1179    #[inline]
1180    #[must_use]
1181    pub fn as_ivec3(&self) -> crate::IVec3 {
1182        crate::IVec3::new(self.x as i32, self.y as i32, self.z as i32)
1183    }
1184
1185    /// Casts all elements of `self` to `u32`.
1186    #[inline]
1187    #[must_use]
1188    pub fn as_uvec3(&self) -> crate::UVec3 {
1189        crate::UVec3::new(self.x as u32, self.y as u32, self.z as u32)
1190    }
1191
1192    /// Casts all elements of `self` to `i64`.
1193    #[inline]
1194    #[must_use]
1195    pub fn as_i64vec3(&self) -> crate::I64Vec3 {
1196        crate::I64Vec3::new(self.x as i64, self.y as i64, self.z as i64)
1197    }
1198
1199    /// Casts all elements of `self` to `u64`.
1200    #[inline]
1201    #[must_use]
1202    pub fn as_u64vec3(&self) -> crate::U64Vec3 {
1203        crate::U64Vec3::new(self.x as u64, self.y as u64, self.z as u64)
1204    }
1205
1206    /// Casts all elements of `self` to `usize`.
1207    #[inline]
1208    #[must_use]
1209    pub fn as_usizevec3(&self) -> crate::USizeVec3 {
1210        crate::USizeVec3::new(self.x as usize, self.y as usize, self.z as usize)
1211    }
1212}
1213
1214impl Default for Vec3A {
1215    #[inline(always)]
1216    fn default() -> Self {
1217        Self::ZERO
1218    }
1219}
1220
1221impl PartialEq for Vec3A {
1222    #[inline]
1223    fn eq(&self, rhs: &Self) -> bool {
1224        self.cmpeq(*rhs).all()
1225    }
1226}
1227
1228impl Div for Vec3A {
1229    type Output = Self;
1230    #[inline]
1231    fn div(self, rhs: Self) -> Self {
1232        Self(unsafe { _mm_div_ps(self.0, rhs.0) })
1233    }
1234}
1235
1236impl Div<&Self> for Vec3A {
1237    type Output = Self;
1238    #[inline]
1239    fn div(self, rhs: &Self) -> Self {
1240        self.div(*rhs)
1241    }
1242}
1243
1244impl Div<&Vec3A> for &Vec3A {
1245    type Output = Vec3A;
1246    #[inline]
1247    fn div(self, rhs: &Vec3A) -> Vec3A {
1248        (*self).div(*rhs)
1249    }
1250}
1251
1252impl Div<Vec3A> for &Vec3A {
1253    type Output = Vec3A;
1254    #[inline]
1255    fn div(self, rhs: Vec3A) -> Vec3A {
1256        (*self).div(rhs)
1257    }
1258}
1259
1260impl DivAssign for Vec3A {
1261    #[inline]
1262    fn div_assign(&mut self, rhs: Self) {
1263        self.0 = unsafe { _mm_div_ps(self.0, rhs.0) };
1264    }
1265}
1266
1267impl DivAssign<&Self> for Vec3A {
1268    #[inline]
1269    fn div_assign(&mut self, rhs: &Self) {
1270        self.div_assign(*rhs);
1271    }
1272}
1273
1274impl Div<f32> for Vec3A {
1275    type Output = Self;
1276    #[inline]
1277    fn div(self, rhs: f32) -> Self {
1278        Self(unsafe { _mm_div_ps(self.0, _mm_set1_ps(rhs)) })
1279    }
1280}
1281
1282impl Div<&f32> for Vec3A {
1283    type Output = Self;
1284    #[inline]
1285    fn div(self, rhs: &f32) -> Self {
1286        self.div(*rhs)
1287    }
1288}
1289
1290impl Div<&f32> for &Vec3A {
1291    type Output = Vec3A;
1292    #[inline]
1293    fn div(self, rhs: &f32) -> Vec3A {
1294        (*self).div(*rhs)
1295    }
1296}
1297
1298impl Div<f32> for &Vec3A {
1299    type Output = Vec3A;
1300    #[inline]
1301    fn div(self, rhs: f32) -> Vec3A {
1302        (*self).div(rhs)
1303    }
1304}
1305
1306impl DivAssign<f32> for Vec3A {
1307    #[inline]
1308    fn div_assign(&mut self, rhs: f32) {
1309        self.0 = unsafe { _mm_div_ps(self.0, _mm_set1_ps(rhs)) };
1310    }
1311}
1312
1313impl DivAssign<&f32> for Vec3A {
1314    #[inline]
1315    fn div_assign(&mut self, rhs: &f32) {
1316        self.div_assign(*rhs);
1317    }
1318}
1319
1320impl Div<Vec3A> for f32 {
1321    type Output = Vec3A;
1322    #[inline]
1323    fn div(self, rhs: Vec3A) -> Vec3A {
1324        Vec3A(unsafe { _mm_div_ps(_mm_set1_ps(self), rhs.0) })
1325    }
1326}
1327
1328impl Div<&Vec3A> for f32 {
1329    type Output = Vec3A;
1330    #[inline]
1331    fn div(self, rhs: &Vec3A) -> Vec3A {
1332        self.div(*rhs)
1333    }
1334}
1335
1336impl Div<&Vec3A> for &f32 {
1337    type Output = Vec3A;
1338    #[inline]
1339    fn div(self, rhs: &Vec3A) -> Vec3A {
1340        (*self).div(*rhs)
1341    }
1342}
1343
1344impl Div<Vec3A> for &f32 {
1345    type Output = Vec3A;
1346    #[inline]
1347    fn div(self, rhs: Vec3A) -> Vec3A {
1348        (*self).div(rhs)
1349    }
1350}
1351
1352impl Mul for Vec3A {
1353    type Output = Self;
1354    #[inline]
1355    fn mul(self, rhs: Self) -> Self {
1356        Self(unsafe { _mm_mul_ps(self.0, rhs.0) })
1357    }
1358}
1359
1360impl Mul<&Self> for Vec3A {
1361    type Output = Self;
1362    #[inline]
1363    fn mul(self, rhs: &Self) -> Self {
1364        self.mul(*rhs)
1365    }
1366}
1367
1368impl Mul<&Vec3A> for &Vec3A {
1369    type Output = Vec3A;
1370    #[inline]
1371    fn mul(self, rhs: &Vec3A) -> Vec3A {
1372        (*self).mul(*rhs)
1373    }
1374}
1375
1376impl Mul<Vec3A> for &Vec3A {
1377    type Output = Vec3A;
1378    #[inline]
1379    fn mul(self, rhs: Vec3A) -> Vec3A {
1380        (*self).mul(rhs)
1381    }
1382}
1383
1384impl MulAssign for Vec3A {
1385    #[inline]
1386    fn mul_assign(&mut self, rhs: Self) {
1387        self.0 = unsafe { _mm_mul_ps(self.0, rhs.0) };
1388    }
1389}
1390
1391impl MulAssign<&Self> for Vec3A {
1392    #[inline]
1393    fn mul_assign(&mut self, rhs: &Self) {
1394        self.mul_assign(*rhs);
1395    }
1396}
1397
1398impl Mul<f32> for Vec3A {
1399    type Output = Self;
1400    #[inline]
1401    fn mul(self, rhs: f32) -> Self {
1402        Self(unsafe { _mm_mul_ps(self.0, _mm_set1_ps(rhs)) })
1403    }
1404}
1405
1406impl Mul<&f32> for Vec3A {
1407    type Output = Self;
1408    #[inline]
1409    fn mul(self, rhs: &f32) -> Self {
1410        self.mul(*rhs)
1411    }
1412}
1413
1414impl Mul<&f32> for &Vec3A {
1415    type Output = Vec3A;
1416    #[inline]
1417    fn mul(self, rhs: &f32) -> Vec3A {
1418        (*self).mul(*rhs)
1419    }
1420}
1421
1422impl Mul<f32> for &Vec3A {
1423    type Output = Vec3A;
1424    #[inline]
1425    fn mul(self, rhs: f32) -> Vec3A {
1426        (*self).mul(rhs)
1427    }
1428}
1429
1430impl MulAssign<f32> for Vec3A {
1431    #[inline]
1432    fn mul_assign(&mut self, rhs: f32) {
1433        self.0 = unsafe { _mm_mul_ps(self.0, _mm_set1_ps(rhs)) };
1434    }
1435}
1436
1437impl MulAssign<&f32> for Vec3A {
1438    #[inline]
1439    fn mul_assign(&mut self, rhs: &f32) {
1440        self.mul_assign(*rhs);
1441    }
1442}
1443
1444impl Mul<Vec3A> for f32 {
1445    type Output = Vec3A;
1446    #[inline]
1447    fn mul(self, rhs: Vec3A) -> Vec3A {
1448        Vec3A(unsafe { _mm_mul_ps(_mm_set1_ps(self), rhs.0) })
1449    }
1450}
1451
1452impl Mul<&Vec3A> for f32 {
1453    type Output = Vec3A;
1454    #[inline]
1455    fn mul(self, rhs: &Vec3A) -> Vec3A {
1456        self.mul(*rhs)
1457    }
1458}
1459
1460impl Mul<&Vec3A> for &f32 {
1461    type Output = Vec3A;
1462    #[inline]
1463    fn mul(self, rhs: &Vec3A) -> Vec3A {
1464        (*self).mul(*rhs)
1465    }
1466}
1467
1468impl Mul<Vec3A> for &f32 {
1469    type Output = Vec3A;
1470    #[inline]
1471    fn mul(self, rhs: Vec3A) -> Vec3A {
1472        (*self).mul(rhs)
1473    }
1474}
1475
1476impl Add for Vec3A {
1477    type Output = Self;
1478    #[inline]
1479    fn add(self, rhs: Self) -> Self {
1480        Self(unsafe { _mm_add_ps(self.0, rhs.0) })
1481    }
1482}
1483
1484impl Add<&Self> for Vec3A {
1485    type Output = Self;
1486    #[inline]
1487    fn add(self, rhs: &Self) -> Self {
1488        self.add(*rhs)
1489    }
1490}
1491
1492impl Add<&Vec3A> for &Vec3A {
1493    type Output = Vec3A;
1494    #[inline]
1495    fn add(self, rhs: &Vec3A) -> Vec3A {
1496        (*self).add(*rhs)
1497    }
1498}
1499
1500impl Add<Vec3A> for &Vec3A {
1501    type Output = Vec3A;
1502    #[inline]
1503    fn add(self, rhs: Vec3A) -> Vec3A {
1504        (*self).add(rhs)
1505    }
1506}
1507
1508impl AddAssign for Vec3A {
1509    #[inline]
1510    fn add_assign(&mut self, rhs: Self) {
1511        self.0 = unsafe { _mm_add_ps(self.0, rhs.0) };
1512    }
1513}
1514
1515impl AddAssign<&Self> for Vec3A {
1516    #[inline]
1517    fn add_assign(&mut self, rhs: &Self) {
1518        self.add_assign(*rhs);
1519    }
1520}
1521
1522impl Add<f32> for Vec3A {
1523    type Output = Self;
1524    #[inline]
1525    fn add(self, rhs: f32) -> Self {
1526        Self(unsafe { _mm_add_ps(self.0, _mm_set1_ps(rhs)) })
1527    }
1528}
1529
1530impl Add<&f32> for Vec3A {
1531    type Output = Self;
1532    #[inline]
1533    fn add(self, rhs: &f32) -> Self {
1534        self.add(*rhs)
1535    }
1536}
1537
1538impl Add<&f32> for &Vec3A {
1539    type Output = Vec3A;
1540    #[inline]
1541    fn add(self, rhs: &f32) -> Vec3A {
1542        (*self).add(*rhs)
1543    }
1544}
1545
1546impl Add<f32> for &Vec3A {
1547    type Output = Vec3A;
1548    #[inline]
1549    fn add(self, rhs: f32) -> Vec3A {
1550        (*self).add(rhs)
1551    }
1552}
1553
1554impl AddAssign<f32> for Vec3A {
1555    #[inline]
1556    fn add_assign(&mut self, rhs: f32) {
1557        self.0 = unsafe { _mm_add_ps(self.0, _mm_set1_ps(rhs)) };
1558    }
1559}
1560
1561impl AddAssign<&f32> for Vec3A {
1562    #[inline]
1563    fn add_assign(&mut self, rhs: &f32) {
1564        self.add_assign(*rhs);
1565    }
1566}
1567
1568impl Add<Vec3A> for f32 {
1569    type Output = Vec3A;
1570    #[inline]
1571    fn add(self, rhs: Vec3A) -> Vec3A {
1572        Vec3A(unsafe { _mm_add_ps(_mm_set1_ps(self), rhs.0) })
1573    }
1574}
1575
1576impl Add<&Vec3A> for f32 {
1577    type Output = Vec3A;
1578    #[inline]
1579    fn add(self, rhs: &Vec3A) -> Vec3A {
1580        self.add(*rhs)
1581    }
1582}
1583
1584impl Add<&Vec3A> for &f32 {
1585    type Output = Vec3A;
1586    #[inline]
1587    fn add(self, rhs: &Vec3A) -> Vec3A {
1588        (*self).add(*rhs)
1589    }
1590}
1591
1592impl Add<Vec3A> for &f32 {
1593    type Output = Vec3A;
1594    #[inline]
1595    fn add(self, rhs: Vec3A) -> Vec3A {
1596        (*self).add(rhs)
1597    }
1598}
1599
1600impl Sub for Vec3A {
1601    type Output = Self;
1602    #[inline]
1603    fn sub(self, rhs: Self) -> Self {
1604        Self(unsafe { _mm_sub_ps(self.0, rhs.0) })
1605    }
1606}
1607
1608impl Sub<&Self> for Vec3A {
1609    type Output = Self;
1610    #[inline]
1611    fn sub(self, rhs: &Self) -> Self {
1612        self.sub(*rhs)
1613    }
1614}
1615
1616impl Sub<&Vec3A> for &Vec3A {
1617    type Output = Vec3A;
1618    #[inline]
1619    fn sub(self, rhs: &Vec3A) -> Vec3A {
1620        (*self).sub(*rhs)
1621    }
1622}
1623
1624impl Sub<Vec3A> for &Vec3A {
1625    type Output = Vec3A;
1626    #[inline]
1627    fn sub(self, rhs: Vec3A) -> Vec3A {
1628        (*self).sub(rhs)
1629    }
1630}
1631
1632impl SubAssign for Vec3A {
1633    #[inline]
1634    fn sub_assign(&mut self, rhs: Self) {
1635        self.0 = unsafe { _mm_sub_ps(self.0, rhs.0) };
1636    }
1637}
1638
1639impl SubAssign<&Self> for Vec3A {
1640    #[inline]
1641    fn sub_assign(&mut self, rhs: &Self) {
1642        self.sub_assign(*rhs);
1643    }
1644}
1645
1646impl Sub<f32> for Vec3A {
1647    type Output = Self;
1648    #[inline]
1649    fn sub(self, rhs: f32) -> Self {
1650        Self(unsafe { _mm_sub_ps(self.0, _mm_set1_ps(rhs)) })
1651    }
1652}
1653
1654impl Sub<&f32> for Vec3A {
1655    type Output = Self;
1656    #[inline]
1657    fn sub(self, rhs: &f32) -> Self {
1658        self.sub(*rhs)
1659    }
1660}
1661
1662impl Sub<&f32> for &Vec3A {
1663    type Output = Vec3A;
1664    #[inline]
1665    fn sub(self, rhs: &f32) -> Vec3A {
1666        (*self).sub(*rhs)
1667    }
1668}
1669
1670impl Sub<f32> for &Vec3A {
1671    type Output = Vec3A;
1672    #[inline]
1673    fn sub(self, rhs: f32) -> Vec3A {
1674        (*self).sub(rhs)
1675    }
1676}
1677
1678impl SubAssign<f32> for Vec3A {
1679    #[inline]
1680    fn sub_assign(&mut self, rhs: f32) {
1681        self.0 = unsafe { _mm_sub_ps(self.0, _mm_set1_ps(rhs)) };
1682    }
1683}
1684
1685impl SubAssign<&f32> for Vec3A {
1686    #[inline]
1687    fn sub_assign(&mut self, rhs: &f32) {
1688        self.sub_assign(*rhs);
1689    }
1690}
1691
1692impl Sub<Vec3A> for f32 {
1693    type Output = Vec3A;
1694    #[inline]
1695    fn sub(self, rhs: Vec3A) -> Vec3A {
1696        Vec3A(unsafe { _mm_sub_ps(_mm_set1_ps(self), rhs.0) })
1697    }
1698}
1699
1700impl Sub<&Vec3A> for f32 {
1701    type Output = Vec3A;
1702    #[inline]
1703    fn sub(self, rhs: &Vec3A) -> Vec3A {
1704        self.sub(*rhs)
1705    }
1706}
1707
1708impl Sub<&Vec3A> for &f32 {
1709    type Output = Vec3A;
1710    #[inline]
1711    fn sub(self, rhs: &Vec3A) -> Vec3A {
1712        (*self).sub(*rhs)
1713    }
1714}
1715
1716impl Sub<Vec3A> for &f32 {
1717    type Output = Vec3A;
1718    #[inline]
1719    fn sub(self, rhs: Vec3A) -> Vec3A {
1720        (*self).sub(rhs)
1721    }
1722}
1723
1724impl Rem for Vec3A {
1725    type Output = Self;
1726    #[inline]
1727    fn rem(self, rhs: Self) -> Self {
1728        unsafe {
1729            let n = m128_floor(_mm_div_ps(self.0, rhs.0));
1730            Self(_mm_sub_ps(self.0, _mm_mul_ps(n, rhs.0)))
1731        }
1732    }
1733}
1734
1735impl Rem<&Self> for Vec3A {
1736    type Output = Self;
1737    #[inline]
1738    fn rem(self, rhs: &Self) -> Self {
1739        self.rem(*rhs)
1740    }
1741}
1742
1743impl Rem<&Vec3A> for &Vec3A {
1744    type Output = Vec3A;
1745    #[inline]
1746    fn rem(self, rhs: &Vec3A) -> Vec3A {
1747        (*self).rem(*rhs)
1748    }
1749}
1750
1751impl Rem<Vec3A> for &Vec3A {
1752    type Output = Vec3A;
1753    #[inline]
1754    fn rem(self, rhs: Vec3A) -> Vec3A {
1755        (*self).rem(rhs)
1756    }
1757}
1758
1759impl RemAssign for Vec3A {
1760    #[inline]
1761    fn rem_assign(&mut self, rhs: Self) {
1762        *self = self.rem(rhs);
1763    }
1764}
1765
1766impl RemAssign<&Self> for Vec3A {
1767    #[inline]
1768    fn rem_assign(&mut self, rhs: &Self) {
1769        self.rem_assign(*rhs);
1770    }
1771}
1772
1773impl Rem<f32> for Vec3A {
1774    type Output = Self;
1775    #[inline]
1776    fn rem(self, rhs: f32) -> Self {
1777        self.rem(Self::splat(rhs))
1778    }
1779}
1780
1781impl Rem<&f32> for Vec3A {
1782    type Output = Self;
1783    #[inline]
1784    fn rem(self, rhs: &f32) -> Self {
1785        self.rem(*rhs)
1786    }
1787}
1788
1789impl Rem<&f32> for &Vec3A {
1790    type Output = Vec3A;
1791    #[inline]
1792    fn rem(self, rhs: &f32) -> Vec3A {
1793        (*self).rem(*rhs)
1794    }
1795}
1796
1797impl Rem<f32> for &Vec3A {
1798    type Output = Vec3A;
1799    #[inline]
1800    fn rem(self, rhs: f32) -> Vec3A {
1801        (*self).rem(rhs)
1802    }
1803}
1804
1805impl RemAssign<f32> for Vec3A {
1806    #[inline]
1807    fn rem_assign(&mut self, rhs: f32) {
1808        *self = self.rem(Self::splat(rhs));
1809    }
1810}
1811
1812impl RemAssign<&f32> for Vec3A {
1813    #[inline]
1814    fn rem_assign(&mut self, rhs: &f32) {
1815        self.rem_assign(*rhs);
1816    }
1817}
1818
1819impl Rem<Vec3A> for f32 {
1820    type Output = Vec3A;
1821    #[inline]
1822    fn rem(self, rhs: Vec3A) -> Vec3A {
1823        Vec3A::splat(self).rem(rhs)
1824    }
1825}
1826
1827impl Rem<&Vec3A> for f32 {
1828    type Output = Vec3A;
1829    #[inline]
1830    fn rem(self, rhs: &Vec3A) -> Vec3A {
1831        self.rem(*rhs)
1832    }
1833}
1834
1835impl Rem<&Vec3A> for &f32 {
1836    type Output = Vec3A;
1837    #[inline]
1838    fn rem(self, rhs: &Vec3A) -> Vec3A {
1839        (*self).rem(*rhs)
1840    }
1841}
1842
1843impl Rem<Vec3A> for &f32 {
1844    type Output = Vec3A;
1845    #[inline]
1846    fn rem(self, rhs: Vec3A) -> Vec3A {
1847        (*self).rem(rhs)
1848    }
1849}
1850
1851impl AsRef<[f32; 3]> for Vec3A {
1852    #[inline]
1853    fn as_ref(&self) -> &[f32; 3] {
1854        unsafe { &*(self as *const Self as *const [f32; 3]) }
1855    }
1856}
1857
1858impl AsMut<[f32; 3]> for Vec3A {
1859    #[inline]
1860    fn as_mut(&mut self) -> &mut [f32; 3] {
1861        unsafe { &mut *(self as *mut Self as *mut [f32; 3]) }
1862    }
1863}
1864
1865impl Sum for Vec3A {
1866    #[inline]
1867    fn sum<I>(iter: I) -> Self
1868    where
1869        I: Iterator<Item = Self>,
1870    {
1871        iter.fold(Self::ZERO, Self::add)
1872    }
1873}
1874
1875impl<'a> Sum<&'a Self> for Vec3A {
1876    #[inline]
1877    fn sum<I>(iter: I) -> Self
1878    where
1879        I: Iterator<Item = &'a Self>,
1880    {
1881        iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
1882    }
1883}
1884
1885impl Product for Vec3A {
1886    #[inline]
1887    fn product<I>(iter: I) -> Self
1888    where
1889        I: Iterator<Item = Self>,
1890    {
1891        iter.fold(Self::ONE, Self::mul)
1892    }
1893}
1894
1895impl<'a> Product<&'a Self> for Vec3A {
1896    #[inline]
1897    fn product<I>(iter: I) -> Self
1898    where
1899        I: Iterator<Item = &'a Self>,
1900    {
1901        iter.fold(Self::ONE, |a, &b| Self::mul(a, b))
1902    }
1903}
1904
1905impl Neg for Vec3A {
1906    type Output = Self;
1907    #[inline]
1908    fn neg(self) -> Self {
1909        Self(unsafe { _mm_xor_ps(_mm_set1_ps(-0.0), self.0) })
1910    }
1911}
1912
1913impl Neg for &Vec3A {
1914    type Output = Vec3A;
1915    #[inline]
1916    fn neg(self) -> Vec3A {
1917        (*self).neg()
1918    }
1919}
1920
1921impl Index<usize> for Vec3A {
1922    type Output = f32;
1923    #[inline]
1924    fn index(&self, index: usize) -> &Self::Output {
1925        match index {
1926            0 => &self.x,
1927            1 => &self.y,
1928            2 => &self.z,
1929            _ => panic!("index out of bounds"),
1930        }
1931    }
1932}
1933
1934impl IndexMut<usize> for Vec3A {
1935    #[inline]
1936    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
1937        match index {
1938            0 => &mut self.x,
1939            1 => &mut self.y,
1940            2 => &mut self.z,
1941            _ => panic!("index out of bounds"),
1942        }
1943    }
1944}
1945
1946impl fmt::Display for Vec3A {
1947    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1948        if let Some(p) = f.precision() {
1949            write!(f, "[{:.*}, {:.*}, {:.*}]", p, self.x, p, self.y, p, self.z)
1950        } else {
1951            write!(f, "[{}, {}, {}]", self.x, self.y, self.z)
1952        }
1953    }
1954}
1955
1956impl fmt::Debug for Vec3A {
1957    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1958        fmt.debug_tuple(stringify!(Vec3A))
1959            .field(&self.x)
1960            .field(&self.y)
1961            .field(&self.z)
1962            .finish()
1963    }
1964}
1965
1966impl From<Vec3A> for __m128 {
1967    #[inline(always)]
1968    fn from(t: Vec3A) -> Self {
1969        t.0
1970    }
1971}
1972
1973impl From<__m128> for Vec3A {
1974    #[inline(always)]
1975    fn from(t: __m128) -> Self {
1976        Self(t)
1977    }
1978}
1979
1980impl From<[f32; 3]> for Vec3A {
1981    #[inline]
1982    fn from(a: [f32; 3]) -> Self {
1983        Self::new(a[0], a[1], a[2])
1984    }
1985}
1986
1987impl From<Vec3A> for [f32; 3] {
1988    #[inline]
1989    fn from(v: Vec3A) -> Self {
1990        use crate::Align16;
1991        use core::mem::MaybeUninit;
1992        let mut out: MaybeUninit<Align16<Self>> = MaybeUninit::uninit();
1993        unsafe {
1994            _mm_store_ps(out.as_mut_ptr().cast(), v.0);
1995            out.assume_init().0
1996        }
1997    }
1998}
1999
2000impl From<(f32, f32, f32)> for Vec3A {
2001    #[inline]
2002    fn from(t: (f32, f32, f32)) -> Self {
2003        Self::new(t.0, t.1, t.2)
2004    }
2005}
2006
2007impl From<Vec3A> for (f32, f32, f32) {
2008    #[inline]
2009    fn from(v: Vec3A) -> Self {
2010        (v.x, v.y, v.z)
2011    }
2012}
2013
2014impl From<Vec3> for Vec3A {
2015    #[inline]
2016    fn from(v: Vec3) -> Self {
2017        Self::new(v.x, v.y, v.z)
2018    }
2019}
2020
2021impl From<Vec3A> for Vec3 {
2022    #[inline]
2023    fn from(v: Vec3A) -> Self {
2024        use crate::Align16;
2025        use core::mem::MaybeUninit;
2026        let mut out: MaybeUninit<Align16<Self>> = MaybeUninit::uninit();
2027        unsafe {
2028            _mm_store_ps(out.as_mut_ptr().cast(), v.0);
2029            out.assume_init().0
2030        }
2031    }
2032}
2033
2034impl From<(Vec2, f32)> for Vec3A {
2035    #[inline]
2036    fn from((v, z): (Vec2, f32)) -> Self {
2037        Self::new(v.x, v.y, z)
2038    }
2039}
2040
2041impl Deref for Vec3A {
2042    type Target = crate::deref::Vec3<f32>;
2043    #[inline]
2044    fn deref(&self) -> &Self::Target {
2045        unsafe { &*(self as *const Self).cast() }
2046    }
2047}
2048
2049impl DerefMut for Vec3A {
2050    #[inline]
2051    fn deref_mut(&mut self) -> &mut Self::Target {
2052        unsafe { &mut *(self as *mut Self).cast() }
2053    }
2054}
2055
2056impl From<BVec3> for Vec3A {
2057    #[inline]
2058    fn from(v: BVec3) -> Self {
2059        Self::new(f32::from(v.x), f32::from(v.y), f32::from(v.z))
2060    }
2061}
2062
2063impl From<BVec3A> for Vec3A {
2064    #[inline]
2065    fn from(v: BVec3A) -> Self {
2066        let bool_array: [bool; 3] = v.into();
2067        Self::new(
2068            f32::from(bool_array[0]),
2069            f32::from(bool_array[1]),
2070            f32::from(bool_array[2]),
2071        )
2072    }
2073}