glam/f32/
vec3.rs

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