Skip to main content

glam/f32/
vec3.rs

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