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