Debian Codegraph @

debian/missing-sources/glam-0.27.0/src/f32/scalar/vec4.rs

raw
1 // Generated from vec.rs.tera template. Edit the template, not the generated file.
2
3 #[cfg(feature = "scalar-math")]
4 use crate::BVec4 as BVec4A;
5
6 #[cfg(not(feature = "scalar-math"))]
7 use crate::BVec4A;
8 use crate::{f32::math, BVec4, Vec2, Vec3, Vec3A};
9
10 #[cfg(not(target_arch = "spirv"))]
11 use core::fmt;
12 use core::iter::{Product, Sum};
13 use core::{f32, ops::*};
14
15 /// Creates a 4-dimensional vector.
16 #[inline(always)]
17 #[must_use]
18 pub const fn vec4(x: f32, y: f32, z: f32, w: f32) -> Vec4 {
19 Vec4::new(x, y, z, w)
20 }
21
22 /// A 4-dimensional vector.
23 #[derive(Clone, Copy, PartialEq)]
24 #[cfg_attr(
25 any(
26 not(any(feature = "scalar-math", target_arch = "spirv")),
27 feature = "cuda"
28 ),
29 repr(align(16))
30 )]
31 #[cfg_attr(not(target_arch = "spirv"), repr(C))]
32 #[cfg_attr(target_arch = "spirv", repr(simd))]
33 pub struct Vec4 {
34 pub x: f32,
35 pub y: f32,
36 pub z: f32,
37 pub w: f32,
38 }
39
40 impl Vec4 {
41 /// All zeroes.
42 pub const ZERO: Self = Self::splat(0.0);
43
44 /// All ones.
45 pub const ONE: Self = Self::splat(1.0);
46
47 /// All negative ones.
48 pub const NEG_ONE: Self = Self::splat(-1.0);
49
50 /// All `f32::MIN`.
51 pub const MIN: Self = Self::splat(f32::MIN);
52
53 /// All `f32::MAX`.
54 pub const MAX: Self = Self::splat(f32::MAX);
55
56 /// All `f32::NAN`.
57 pub const NAN: Self = Self::splat(f32::NAN);
58
59 /// All `f32::INFINITY`.
60 pub const INFINITY: Self = Self::splat(f32::INFINITY);
61
62 /// All `f32::NEG_INFINITY`.
63 pub const NEG_INFINITY: Self = Self::splat(f32::NEG_INFINITY);
64
65 /// A unit vector pointing along the positive X axis.
66 pub const X: Self = Self::new(1.0, 0.0, 0.0, 0.0);
67
68 /// A unit vector pointing along the positive Y axis.
69 pub const Y: Self = Self::new(0.0, 1.0, 0.0, 0.0);
70
71 /// A unit vector pointing along the positive Z axis.
72 pub const Z: Self = Self::new(0.0, 0.0, 1.0, 0.0);
73
74 /// A unit vector pointing along the positive W axis.
75 pub const W: Self = Self::new(0.0, 0.0, 0.0, 1.0);
76
77 /// A unit vector pointing along the negative X axis.
78 pub const NEG_X: Self = Self::new(-1.0, 0.0, 0.0, 0.0);
79
80 /// A unit vector pointing along the negative Y axis.
81 pub const NEG_Y: Self = Self::new(0.0, -1.0, 0.0, 0.0);
82
83 /// A unit vector pointing along the negative Z axis.
84 pub const NEG_Z: Self = Self::new(0.0, 0.0, -1.0, 0.0);
85
86 /// A unit vector pointing along the negative W axis.
87 pub const NEG_W: Self = Self::new(0.0, 0.0, 0.0, -1.0);
88
89 /// The unit axes.
90 pub const AXES: [Self; 4] = [Self::X, Self::Y, Self::Z, Self::W];
91
92 /// Creates a new vector.
93 #[inline(always)]
94 #[must_use]
95 pub const fn new(x: f32, y: f32, z: f32, w: f32) -> Self {
96 Self { x, y, z, w }
97 }
98
99 /// Creates a vector with all elements set to `v`.
100 #[inline]
101 #[must_use]
102 pub const fn splat(v: f32) -> Self {
103 Self {
104 x: v,
105
106 y: v,
107
108 z: v,
109
110 w: v,
111 }
112 }
113
114 /// Creates a vector from the elements in `if_true` and `if_false`, selecting which to use
115 /// for each element of `self`.
116 ///
117 /// A true element in the mask uses the corresponding element from `if_true`, and false
118 /// uses the element from `if_false`.
119 #[inline]
120 #[must_use]
121 pub fn select(mask: BVec4A, if_true: Self, if_false: Self) -> Self {
122 Self {
123 x: if mask.test(0) { if_true.x } else { if_false.x },
124 y: if mask.test(1) { if_true.y } else { if_false.y },
125 z: if mask.test(2) { if_true.z } else { if_false.z },
126 w: if mask.test(3) { if_true.w } else { if_false.w },
127 }
128 }
129
130 /// Creates a new vector from an array.
131 #[inline]
132 #[must_use]
133 pub const fn from_array(a: [f32; 4]) -> Self {
134 Self::new(a[0], a[1], a[2], a[3])
135 }
136
137 /// `[x, y, z, w]`
138 #[inline]
139 #[must_use]
140 pub const fn to_array(&self) -> [f32; 4] {
141 [self.x, self.y, self.z, self.w]
142 }
143
144 /// Creates a vector from the first 4 values in `slice`.
145 ///
146 /// # Panics
147 ///
148 /// Panics if `slice` is less than 4 elements long.
149 #[inline]
150 #[must_use]
151 pub const fn from_slice(slice: &[f32]) -> Self {
152 Self::new(slice[0], slice[1], slice[2], slice[3])
153 }
154
155 /// Writes the elements of `self` to the first 4 elements in `slice`.
156 ///
157 /// # Panics
158 ///
159 /// Panics if `slice` is less than 4 elements long.
160 #[inline]
161 pub fn write_to_slice(self, slice: &mut [f32]) {
162 slice[0] = self.x;
163 slice[1] = self.y;
164 slice[2] = self.z;
165 slice[3] = self.w;
166 }
167
168 /// Creates a 3D vector from the `x`, `y` and `z` elements of `self`, discarding `w`.
169 ///
170 /// Truncation to [`Vec3`] may also be performed by using [`self.xyz()`][crate::swizzles::Vec4Swizzles::xyz()].
171 ///
172 /// To truncate to [`Vec3A`] use [`Vec3A::from()`].
173 #[inline]
174 #[must_use]
175 pub fn truncate(self) -> Vec3 {
176 use crate::swizzles::Vec4Swizzles;
177 self.xyz()
178 }
179
180 /// Creates a 4D vector from `self` with the given value of `x`.
181 #[inline]
182 #[must_use]
183 pub fn with_x(mut self, x: f32) -> Self {
184 self.x = x;
185 self
186 }
187
188 /// Creates a 4D vector from `self` with the given value of `y`.
189 #[inline]
190 #[must_use]
191 pub fn with_y(mut self, y: f32) -> Self {
192 self.y = y;
193 self
194 }
195
196 /// Creates a 4D vector from `self` with the given value of `z`.
197 #[inline]
198 #[must_use]
199 pub fn with_z(mut self, z: f32) -> Self {
200 self.z = z;
201 self
202 }
203
204 /// Creates a 4D vector from `self` with the given value of `w`.
205 #[inline]
206 #[must_use]
207 pub fn with_w(mut self, w: f32) -> Self {
208 self.w = w;
209 self
210 }
211
212 /// Computes the dot product of `self` and `rhs`.
213 #[inline]
214 #[must_use]
215 pub fn dot(self, rhs: Self) -> f32 {
216 (self.x * rhs.x) + (self.y * rhs.y) + (self.z * rhs.z) + (self.w * rhs.w)
217 }
218
219 /// Returns a vector where every component is the dot product of `self` and `rhs`.
220 #[inline]
221 #[must_use]
222 pub fn dot_into_vec(self, rhs: Self) -> Self {
223 Self::splat(self.dot(rhs))
224 }
225
226 /// Returns a vector containing the minimum values for each element of `self` and `rhs`.
227 ///
228 /// In other words this computes `[self.x.min(rhs.x), self.y.min(rhs.y), ..]`.
229 #[inline]
230 #[must_use]
231 pub fn min(self, rhs: Self) -> Self {
232 Self {
233 x: self.x.min(rhs.x),
234 y: self.y.min(rhs.y),
235 z: self.z.min(rhs.z),
236 w: self.w.min(rhs.w),
237 }
238 }
239
240 /// Returns a vector containing the maximum values for each element of `self` and `rhs`.
241 ///
242 /// In other words this computes `[self.x.max(rhs.x), self.y.max(rhs.y), ..]`.
243 #[inline]
244 #[must_use]
245 pub fn max(self, rhs: Self) -> Self {
246 Self {
247 x: self.x.max(rhs.x),
248 y: self.y.max(rhs.y),
249 z: self.z.max(rhs.z),
250 w: self.w.max(rhs.w),
251 }
252 }
253
254 /// Component-wise clamping of values, similar to [`f32::clamp`].
255 ///
256 /// Each element in `min` must be less-or-equal to the corresponding element in `max`.
257 ///
258 /// # Panics
259 ///
260 /// Will panic if `min` is greater than `max` when `glam_assert` is enabled.
261 #[inline]
262 #[must_use]
263 pub fn clamp(self, min: Self, max: Self) -> Self {
264 glam_assert!(min.cmple(max).all(), "clamp: expected min <= max");
265 self.max(min).min(max)
266 }
267
268 /// Returns the horizontal minimum of `self`.
269 ///
270 /// In other words this computes `min(x, y, ..)`.
271 #[inline]
272 #[must_use]
273 pub fn min_element(self) -> f32 {
274 self.x.min(self.y.min(self.z.min(self.w)))
275 }
276
277 /// Returns the horizontal maximum of `self`.
278 ///
279 /// In other words this computes `max(x, y, ..)`.
280 #[inline]
281 #[must_use]
282 pub fn max_element(self) -> f32 {
283 self.x.max(self.y.max(self.z.max(self.w)))
284 }
285
286 /// Returns the sum of all elements of `self`.
287 ///
288 /// In other words, this computes `self.x + self.y + ..`.
289 #[inline]
290 #[must_use]
291 pub fn element_sum(self) -> f32 {
292 self.x + self.y + self.z + self.w
293 }
294
295 /// Returns the product of all elements of `self`.
296 ///
297 /// In other words, this computes `self.x * self.y * ..`.
298 #[inline]
299 #[must_use]
300 pub fn element_product(self) -> f32 {
301 self.x * self.y * self.z * self.w
302 }
303
304 /// Returns a vector mask containing the result of a `==` comparison for each element of
305 /// `self` and `rhs`.
306 ///
307 /// In other words, this computes `[self.x == rhs.x, self.y == rhs.y, ..]` for all
308 /// elements.
309 #[inline]
310 #[must_use]
311 pub fn cmpeq(self, rhs: Self) -> BVec4A {
312 BVec4A::new(
313 self.x.eq(&rhs.x),
314 self.y.eq(&rhs.y),
315 self.z.eq(&rhs.z),
316 self.w.eq(&rhs.w),
317 )
318 }
319
320 /// Returns a vector mask containing the result of a `!=` comparison for each element of
321 /// `self` and `rhs`.
322 ///
323 /// In other words this computes `[self.x != rhs.x, self.y != rhs.y, ..]` for all
324 /// elements.
325 #[inline]
326 #[must_use]
327 pub fn cmpne(self, rhs: Self) -> BVec4A {
328 BVec4A::new(
329 self.x.ne(&rhs.x),
330 self.y.ne(&rhs.y),
331 self.z.ne(&rhs.z),
332 self.w.ne(&rhs.w),
333 )
334 }
335
336 /// Returns a vector mask containing the result of a `>=` comparison for each element of
337 /// `self` and `rhs`.
338 ///
339 /// In other words this computes `[self.x >= rhs.x, self.y >= rhs.y, ..]` for all
340 /// elements.
341 #[inline]
342 #[must_use]
343 pub fn cmpge(self, rhs: Self) -> BVec4A {
344 BVec4A::new(
345 self.x.ge(&rhs.x),
346 self.y.ge(&rhs.y),
347 self.z.ge(&rhs.z),
348 self.w.ge(&rhs.w),
349 )
350 }
351
352 /// Returns a vector mask containing the result of a `>` comparison for each element of
353 /// `self` and `rhs`.
354 ///
355 /// In other words this computes `[self.x > rhs.x, self.y > rhs.y, ..]` for all
356 /// elements.
357 #[inline]
358 #[must_use]
359 pub fn cmpgt(self, rhs: Self) -> BVec4A {
360 BVec4A::new(
361 self.x.gt(&rhs.x),
362 self.y.gt(&rhs.y),
363 self.z.gt(&rhs.z),
364 self.w.gt(&rhs.w),
365 )
366 }
367
368 /// Returns a vector mask containing the result of a `<=` comparison for each element of
369 /// `self` and `rhs`.
370 ///
371 /// In other words this computes `[self.x <= rhs.x, self.y <= rhs.y, ..]` for all
372 /// elements.
373 #[inline]
374 #[must_use]
375 pub fn cmple(self, rhs: Self) -> BVec4A {
376 BVec4A::new(
377 self.x.le(&rhs.x),
378 self.y.le(&rhs.y),
379 self.z.le(&rhs.z),
380 self.w.le(&rhs.w),
381 )
382 }
383
384 /// Returns a vector mask containing the result of a `<` comparison for each element of
385 /// `self` and `rhs`.
386 ///
387 /// In other words this computes `[self.x < rhs.x, self.y < rhs.y, ..]` for all
388 /// elements.
389 #[inline]
390 #[must_use]
391 pub fn cmplt(self, rhs: Self) -> BVec4A {
392 BVec4A::new(
393 self.x.lt(&rhs.x),
394 self.y.lt(&rhs.y),
395 self.z.lt(&rhs.z),
396 self.w.lt(&rhs.w),
397 )
398 }
399
400 /// Returns a vector containing the absolute value of each element of `self`.
401 #[inline]
402 #[must_use]
403 pub fn abs(self) -> Self {
404 Self {
405 x: math::abs(self.x),
406 y: math::abs(self.y),
407 z: math::abs(self.z),
408 w: math::abs(self.w),
409 }
410 }
411
412 /// Returns a vector with elements representing the sign of `self`.
413 ///
414 /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
415 /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
416 /// - `NAN` if the number is `NAN`
417 #[inline]
418 #[must_use]
419 pub fn signum(self) -> Self {
420 Self {
421 x: math::signum(self.x),
422 y: math::signum(self.y),
423 z: math::signum(self.z),
424 w: math::signum(self.w),
425 }
426 }
427
428 /// Returns a vector with signs of `rhs` and the magnitudes of `self`.
429 #[inline]
430 #[must_use]
431 pub fn copysign(self, rhs: Self) -> Self {
432 Self {
433 x: math::copysign(self.x, rhs.x),
434 y: math::copysign(self.y, rhs.y),
435 z: math::copysign(self.z, rhs.z),
436 w: math::copysign(self.w, rhs.w),
437 }
438 }
439
440 /// Returns a bitmask with the lowest 4 bits set to the sign bits from the elements of `self`.
441 ///
442 /// A negative element results in a `1` bit and a positive element in a `0` bit. Element `x` goes
443 /// into the first lowest bit, element `y` into the second, etc.
444 #[inline]
445 #[must_use]
446 pub fn is_negative_bitmask(self) -> u32 {
447 (self.x.is_sign_negative() as u32)
448 | (self.y.is_sign_negative() as u32) << 1
449 | (self.z.is_sign_negative() as u32) << 2
450 | (self.w.is_sign_negative() as u32) << 3
451 }
452
453 /// Returns `true` if, and only if, all elements are finite. If any element is either
454 /// `NaN`, positive or negative infinity, this will return `false`.
455 #[inline]
456 #[must_use]
457 pub fn is_finite(self) -> bool {
458 self.x.is_finite() && self.y.is_finite() && self.z.is_finite() && self.w.is_finite()
459 }
460
461 /// Returns `true` if any elements are `NaN`.
462 #[inline]
463 #[must_use]
464 pub fn is_nan(self) -> bool {
465 self.x.is_nan() || self.y.is_nan() || self.z.is_nan() || self.w.is_nan()
466 }
467
468 /// Performs `is_nan` on each element of self, returning a vector mask of the results.
469 ///
470 /// In other words, this computes `[x.is_nan(), y.is_nan(), z.is_nan(), w.is_nan()]`.
471 #[inline]
472 #[must_use]
473 pub fn is_nan_mask(self) -> BVec4A {
474 BVec4A::new(
475 self.x.is_nan(),
476 self.y.is_nan(),
477 self.z.is_nan(),
478 self.w.is_nan(),
479 )
480 }
481
482 /// Computes the length of `self`.
483 #[doc(alias = "magnitude")]
484 #[inline]
485 #[must_use]
486 pub fn length(self) -> f32 {
487 math::sqrt(self.dot(self))
488 }
489
490 /// Computes the squared length of `self`.
491 ///
492 /// This is faster than `length()` as it avoids a square root operation.
493 #[doc(alias = "magnitude2")]
494 #[inline]
495 #[must_use]
496 pub fn length_squared(self) -> f32 {
497 self.dot(self)
498 }
499
500 /// Computes `1.0 / length()`.
501 ///
502 /// For valid results, `self` must _not_ be of length zero.
503 #[inline]
504 #[must_use]
505 pub fn length_recip(self) -> f32 {
506 self.length().recip()
507 }
508
509 /// Computes the Euclidean distance between two points in space.
510 #[inline]
511 #[must_use]
512 pub fn distance(self, rhs: Self) -> f32 {
513 (self - rhs).length()
514 }
515
516 /// Compute the squared euclidean distance between two points in space.
517 #[inline]
518 #[must_use]
519 pub fn distance_squared(self, rhs: Self) -> f32 {
520 (self - rhs).length_squared()
521 }
522
523 /// Returns the element-wise quotient of [Euclidean division] of `self` by `rhs`.
524 #[inline]
525 #[must_use]
526 pub fn div_euclid(self, rhs: Self) -> Self {
527 Self::new(
528 math::div_euclid(self.x, rhs.x),
529 math::div_euclid(self.y, rhs.y),
530 math::div_euclid(self.z, rhs.z),
531 math::div_euclid(self.w, rhs.w),
532 )
533 }
534
535 /// Returns the element-wise remainder of [Euclidean division] of `self` by `rhs`.
536 ///
537 /// [Euclidean division]: f32::rem_euclid
538 #[inline]
539 #[must_use]
540 pub fn rem_euclid(self, rhs: Self) -> Self {
541 Self::new(
542 math::rem_euclid(self.x, rhs.x),
543 math::rem_euclid(self.y, rhs.y),
544 math::rem_euclid(self.z, rhs.z),
545 math::rem_euclid(self.w, rhs.w),
546 )
547 }
548
549 /// Returns `self` normalized to length 1.0.
550 ///
551 /// For valid results, `self` must _not_ be of length zero, nor very close to zero.
552 ///
553 /// See also [`Self::try_normalize()`] and [`Self::normalize_or_zero()`].
554 ///
555 /// Panics
556 ///
557 /// Will panic if `self` is zero length when `glam_assert` is enabled.
558 #[inline]
559 #[must_use]
560 pub fn normalize(self) -> Self {
561 #[allow(clippy::let_and_return)]
562 let normalized = self.mul(self.length_recip());
563 glam_assert!(normalized.is_finite());
564 normalized
565 }
566
567 /// Returns `self` normalized to length 1.0 if possible, else returns `None`.
568 ///
569 /// In particular, if the input is zero (or very close to zero), or non-finite,
570 /// the result of this operation will be `None`.
571 ///
572 /// See also [`Self::normalize_or_zero()`].
573 #[inline]
574 #[must_use]
575 pub fn try_normalize(self) -> Option<Self> {
576 let rcp = self.length_recip();
577 if rcp.is_finite() && rcp > 0.0 {
578 Some(self * rcp)
579 } else {
580 None
581 }
582 }
583
584 /// Returns `self` normalized to length 1.0 if possible, else returns a
585 /// fallback value.
586 ///
587 /// In particular, if the input is zero (or very close to zero), or non-finite,
588 /// the result of this operation will be the fallback value.
589 ///
590 /// See also [`Self::try_normalize()`].
591 #[inline]
592 #[must_use]
593 pub fn normalize_or(self, fallback: Self) -> Self {
594 let rcp = self.length_recip();
595 if rcp.is_finite() && rcp > 0.0 {
596 self * rcp
597 } else {
598 fallback
599 }
600 }
601
602 /// Returns `self` normalized to length 1.0 if possible, else returns zero.
603 ///
604 /// In particular, if the input is zero (or very close to zero), or non-finite,
605 /// the result of this operation will be zero.
606 ///
607 /// See also [`Self::try_normalize()`].
608 #[inline]
609 #[must_use]
610 pub fn normalize_or_zero(self) -> Self {
611 self.normalize_or(Self::ZERO)
612 }
613
614 /// Returns whether `self` is length `1.0` or not.
615 ///
616 /// Uses a precision threshold of approximately `1e-4`.
617 #[inline]
618 #[must_use]
619 pub fn is_normalized(self) -> bool {
620 math::abs(self.length_squared() - 1.0) <= 2e-4
621 }
622
623 /// Returns the vector projection of `self` onto `rhs`.
624 ///
625 /// `rhs` must be of non-zero length.
626 ///
627 /// # Panics
628 ///
629 /// Will panic if `rhs` is zero length when `glam_assert` is enabled.
630 #[inline]
631 #[must_use]
632 pub fn project_onto(self, rhs: Self) -> Self {
633 let other_len_sq_rcp = rhs.dot(rhs).recip();
634 glam_assert!(other_len_sq_rcp.is_finite());
635 rhs * self.dot(rhs) * other_len_sq_rcp
636 }
637
638 /// Returns the vector rejection of `self` from `rhs`.
639 ///
640 /// The vector rejection is the vector perpendicular to the projection of `self` onto
641 /// `rhs`, in rhs words the result of `self - self.project_onto(rhs)`.
642 ///
643 /// `rhs` must be of non-zero length.
644 ///
645 /// # Panics
646 ///
647 /// Will panic if `rhs` has a length of zero when `glam_assert` is enabled.
648 #[inline]
649 #[must_use]
650 pub fn reject_from(self, rhs: Self) -> Self {
651 self - self.project_onto(rhs)
652 }
653
654 /// Returns the vector projection of `self` onto `rhs`.
655 ///
656 /// `rhs` must be normalized.
657 ///
658 /// # Panics
659 ///
660 /// Will panic if `rhs` is not normalized when `glam_assert` is enabled.
661 #[inline]
662 #[must_use]
663 pub fn project_onto_normalized(self, rhs: Self) -> Self {
664 glam_assert!(rhs.is_normalized());
665 rhs * self.dot(rhs)
666 }
667
668 /// Returns the vector rejection of `self` from `rhs`.
669 ///
670 /// The vector rejection is the vector perpendicular to the projection of `self` onto
671 /// `rhs`, in rhs words the result of `self - self.project_onto(rhs)`.
672 ///
673 /// `rhs` must be normalized.
674 ///
675 /// # Panics
676 ///
677 /// Will panic if `rhs` is not normalized when `glam_assert` is enabled.
678 #[inline]
679 #[must_use]
680 pub fn reject_from_normalized(self, rhs: Self) -> Self {
681 self - self.project_onto_normalized(rhs)
682 }
683
684 /// Returns a vector containing the nearest integer to a number for each element of `self`.
685 /// Round half-way cases away from 0.0.
686 #[inline]
687 #[must_use]
688 pub fn round(self) -> Self {
689 Self {
690 x: math::round(self.x),
691 y: math::round(self.y),
692 z: math::round(self.z),
693 w: math::round(self.w),
694 }
695 }
696
697 /// Returns a vector containing the largest integer less than or equal to a number for each
698 /// element of `self`.
699 #[inline]
700 #[must_use]
701 pub fn floor(self) -> Self {
702 Self {
703 x: math::floor(self.x),
704 y: math::floor(self.y),
705 z: math::floor(self.z),
706 w: math::floor(self.w),
707 }
708 }
709
710 /// Returns a vector containing the smallest integer greater than or equal to a number for
711 /// each element of `self`.
712 #[inline]
713 #[must_use]
714 pub fn ceil(self) -> Self {
715 Self {
716 x: math::ceil(self.x),
717 y: math::ceil(self.y),
718 z: math::ceil(self.z),
719 w: math::ceil(self.w),
720 }
721 }
722
723 /// Returns a vector containing the integer part each element of `self`. This means numbers are
724 /// always truncated towards zero.
725 #[inline]
726 #[must_use]
727 pub fn trunc(self) -> Self {
728 Self {
729 x: math::trunc(self.x),
730 y: math::trunc(self.y),
731 z: math::trunc(self.z),
732 w: math::trunc(self.w),
733 }
734 }
735
736 /// Returns a vector containing the fractional part of the vector as `self - self.trunc()`.
737 ///
738 /// Note that this differs from the GLSL implementation of `fract` which returns
739 /// `self - self.floor()`.
740 ///
741 /// Note that this is fast but not precise for large numbers.
742 #[inline]
743 #[must_use]
744 pub fn fract(self) -> Self {
745 self - self.trunc()
746 }
747
748 /// Returns a vector containing the fractional part of the vector as `self - self.floor()`.
749 ///
750 /// Note that this differs from the Rust implementation of `fract` which returns
751 /// `self - self.trunc()`.
752 ///
753 /// Note that this is fast but not precise for large numbers.
754 #[inline]
755 #[must_use]
756 pub fn fract_gl(self) -> Self {
757 self - self.floor()
758 }
759
760 /// Returns a vector containing `e^self` (the exponential function) for each element of
761 /// `self`.
762 #[inline]
763 #[must_use]
764 pub fn exp(self) -> Self {
765 Self::new(
766 math::exp(self.x),
767 math::exp(self.y),
768 math::exp(self.z),
769 math::exp(self.w),
770 )
771 }
772
773 /// Returns a vector containing each element of `self` raised to the power of `n`.
774 #[inline]
775 #[must_use]
776 pub fn powf(self, n: f32) -> Self {
777 Self::new(
778 math::powf(self.x, n),
779 math::powf(self.y, n),
780 math::powf(self.z, n),
781 math::powf(self.w, n),
782 )
783 }
784
785 /// Returns a vector containing the reciprocal `1.0/n` of each element of `self`.
786 #[inline]
787 #[must_use]
788 pub fn recip(self) -> Self {
789 Self {
790 x: 1.0 / self.x,
791 y: 1.0 / self.y,
792 z: 1.0 / self.z,
793 w: 1.0 / self.w,
794 }
795 }
796
797 /// Performs a linear interpolation between `self` and `rhs` based on the value `s`.
798 ///
799 /// When `s` is `0.0`, the result will be equal to `self`. When `s` is `1.0`, the result
800 /// will be equal to `rhs`. When `s` is outside of range `[0, 1]`, the result is linearly
801 /// extrapolated.
802 #[doc(alias = "mix")]
803 #[inline]
804 #[must_use]
805 pub fn lerp(self, rhs: Self, s: f32) -> Self {
806 self + ((rhs - self) * s)
807 }
808
809 /// Moves towards `rhs` based on the value `d`.
810 ///
811 /// When `d` is `0.0`, the result will be equal to `self`. When `d` is equal to
812 /// `self.distance(rhs)`, the result will be equal to `rhs`. Will not go past `rhs`.
813 #[inline]
814 #[must_use]
815 pub fn move_towards(&self, rhs: Self, d: f32) -> Self {
816 let a = rhs - *self;
817 let len = a.length();
818 if len <= d || len <= 1e-4 {
819 return rhs;
820 }
821 *self + a / len * d
822 }
823
824 /// Calculates the midpoint between `self` and `rhs`.
825 ///
826 /// The midpoint is the average of, or halfway point between, two vectors.
827 /// `a.midpoint(b)` should yield the same result as `a.lerp(b, 0.5)`
828 /// while being slightly cheaper to compute.
829 #[inline]
830 pub fn midpoint(self, rhs: Self) -> Self {
831 (self + rhs) * 0.5
832 }
833
834 /// Returns true if the absolute difference of all elements between `self` and `rhs` is
835 /// less than or equal to `max_abs_diff`.
836 ///
837 /// This can be used to compare if two vectors contain similar elements. It works best when
838 /// comparing with a known value. The `max_abs_diff` that should be used used depends on
839 /// the values being compared against.
840 ///
841 /// For more see
842 /// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
843 #[inline]
844 #[must_use]
845 pub fn abs_diff_eq(self, rhs: Self, max_abs_diff: f32) -> bool {
846 self.sub(rhs).abs().cmple(Self::splat(max_abs_diff)).all()
847 }
848
849 /// Returns a vector with a length no less than `min` and no more than `max`
850 ///
851 /// # Panics
852 ///
853 /// Will panic if `min` is greater than `max` when `glam_assert` is enabled.
854 #[inline]
855 #[must_use]
856 pub fn clamp_length(self, min: f32, max: f32) -> Self {
857 glam_assert!(min <= max);
858 let length_sq = self.length_squared();
859 if length_sq < min * min {
860 min * (self / math::sqrt(length_sq))
861 } else if length_sq > max * max {
862 max * (self / math::sqrt(length_sq))
863 } else {
864 self
865 }
866 }
867
868 /// Returns a vector with a length no more than `max`
869 #[inline]
870 #[must_use]
871 pub fn clamp_length_max(self, max: f32) -> Self {
872 let length_sq = self.length_squared();
873 if length_sq > max * max {
874 max * (self / math::sqrt(length_sq))
875 } else {
876 self
877 }
878 }
879
880 /// Returns a vector with a length no less than `min`
881 #[inline]
882 #[must_use]
883 pub fn clamp_length_min(self, min: f32) -> Self {
884 let length_sq = self.length_squared();
885 if length_sq < min * min {
886 min * (self / math::sqrt(length_sq))
887 } else {
888 self
889 }
890 }
891
892 /// Fused multiply-add. Computes `(self * a) + b` element-wise with only one rounding
893 /// error, yielding a more accurate result than an unfused multiply-add.
894 ///
895 /// Using `mul_add` *may* be more performant than an unfused multiply-add if the target
896 /// architecture has a dedicated fma CPU instruction. However, this is not always true,
897 /// and will be heavily dependant on designing algorithms with specific target hardware in
898 /// mind.
899 #[inline]
900 #[must_use]
901 pub fn mul_add(self, a: Self, b: Self) -> Self {
902 Self::new(
903 math::mul_add(self.x, a.x, b.x),
904 math::mul_add(self.y, a.y, b.y),
905 math::mul_add(self.z, a.z, b.z),
906 math::mul_add(self.w, a.w, b.w),
907 )
908 }
909
910 /// Casts all elements of `self` to `f64`.
911 #[inline]
912 #[must_use]
913 pub fn as_dvec4(&self) -> crate::DVec4 {
914 crate::DVec4::new(self.x as f64, self.y as f64, self.z as f64, self.w as f64)
915 }
916
917 /// Casts all elements of `self` to `i16`.
918 #[inline]
919 #[must_use]
920 pub fn as_i16vec4(&self) -> crate::I16Vec4 {
921 crate::I16Vec4::new(self.x as i16, self.y as i16, self.z as i16, self.w as i16)
922 }
923
924 /// Casts all elements of `self` to `u16`.
925 #[inline]
926 #[must_use]
927 pub fn as_u16vec4(&self) -> crate::U16Vec4 {
928 crate::U16Vec4::new(self.x as u16, self.y as u16, self.z as u16, self.w as u16)
929 }
930
931 /// Casts all elements of `self` to `i32`.
932 #[inline]
933 #[must_use]
934 pub fn as_ivec4(&self) -> crate::IVec4 {
935 crate::IVec4::new(self.x as i32, self.y as i32, self.z as i32, self.w as i32)
936 }
937
938 /// Casts all elements of `self` to `u32`.
939 #[inline]
940 #[must_use]
941 pub fn as_uvec4(&self) -> crate::UVec4 {
942 crate::UVec4::new(self.x as u32, self.y as u32, self.z as u32, self.w as u32)
943 }
944
945 /// Casts all elements of `self` to `i64`.
946 #[inline]
947 #[must_use]
948 pub fn as_i64vec4(&self) -> crate::I64Vec4 {
949 crate::I64Vec4::new(self.x as i64, self.y as i64, self.z as i64, self.w as i64)
950 }
951
952 /// Casts all elements of `self` to `u64`.
953 #[inline]
954 #[must_use]
955 pub fn as_u64vec4(&self) -> crate::U64Vec4 {
956 crate::U64Vec4::new(self.x as u64, self.y as u64, self.z as u64, self.w as u64)
957 }
958 }
959
960 impl Default for Vec4 {
961 #[inline(always)]
962 fn default() -> Self {
963 Self::ZERO
964 }
965 }
966
967 impl Div<Vec4> for Vec4 {
968 type Output = Self;
969 #[inline]
970 fn div(self, rhs: Self) -> Self {
971 Self {
972 x: self.x.div(rhs.x),
973 y: self.y.div(rhs.y),
974 z: self.z.div(rhs.z),
975 w: self.w.div(rhs.w),
976 }
977 }
978 }
979
980 impl DivAssign<Vec4> for Vec4 {
981 #[inline]
982 fn div_assign(&mut self, rhs: Self) {
983 self.x.div_assign(rhs.x);
984 self.y.div_assign(rhs.y);
985 self.z.div_assign(rhs.z);
986 self.w.div_assign(rhs.w);
987 }
988 }
989
990 impl Div<f32> for Vec4 {
991 type Output = Self;
992 #[inline]
993 fn div(self, rhs: f32) -> Self {
994 Self {
995 x: self.x.div(rhs),
996 y: self.y.div(rhs),
997 z: self.z.div(rhs),
998 w: self.w.div(rhs),
999 }
1000 }
1001 }
1002
1003 impl DivAssign<f32> for Vec4 {
1004 #[inline]
1005 fn div_assign(&mut self, rhs: f32) {
1006 self.x.div_assign(rhs);
1007 self.y.div_assign(rhs);
1008 self.z.div_assign(rhs);
1009 self.w.div_assign(rhs);
1010 }
1011 }
1012
1013 impl Div<Vec4> for f32 {
1014 type Output = Vec4;
1015 #[inline]
1016 fn div(self, rhs: Vec4) -> Vec4 {
1017 Vec4 {
1018 x: self.div(rhs.x),
1019 y: self.div(rhs.y),
1020 z: self.div(rhs.z),
1021 w: self.div(rhs.w),
1022 }
1023 }
1024 }
1025
1026 impl Mul<Vec4> for Vec4 {
1027 type Output = Self;
1028 #[inline]
1029 fn mul(self, rhs: Self) -> Self {
1030 Self {
1031 x: self.x.mul(rhs.x),
1032 y: self.y.mul(rhs.y),
1033 z: self.z.mul(rhs.z),
1034 w: self.w.mul(rhs.w),
1035 }
1036 }
1037 }
1038
1039 impl MulAssign<Vec4> for Vec4 {
1040 #[inline]
1041 fn mul_assign(&mut self, rhs: Self) {
1042 self.x.mul_assign(rhs.x);
1043 self.y.mul_assign(rhs.y);
1044 self.z.mul_assign(rhs.z);
1045 self.w.mul_assign(rhs.w);
1046 }
1047 }
1048
1049 impl Mul<f32> for Vec4 {
1050 type Output = Self;
1051 #[inline]
1052 fn mul(self, rhs: f32) -> Self {
1053 Self {
1054 x: self.x.mul(rhs),
1055 y: self.y.mul(rhs),
1056 z: self.z.mul(rhs),
1057 w: self.w.mul(rhs),
1058 }
1059 }
1060 }
1061
1062 impl MulAssign<f32> for Vec4 {
1063 #[inline]
1064 fn mul_assign(&mut self, rhs: f32) {
1065 self.x.mul_assign(rhs);
1066 self.y.mul_assign(rhs);
1067 self.z.mul_assign(rhs);
1068 self.w.mul_assign(rhs);
1069 }
1070 }
1071
1072 impl Mul<Vec4> for f32 {
1073 type Output = Vec4;
1074 #[inline]
1075 fn mul(self, rhs: Vec4) -> Vec4 {
1076 Vec4 {
1077 x: self.mul(rhs.x),
1078 y: self.mul(rhs.y),
1079 z: self.mul(rhs.z),
1080 w: self.mul(rhs.w),
1081 }
1082 }
1083 }
1084
1085 impl Add<Vec4> for Vec4 {
1086 type Output = Self;
1087 #[inline]
1088 fn add(self, rhs: Self) -> Self {
1089 Self {
1090 x: self.x.add(rhs.x),
1091 y: self.y.add(rhs.y),
1092 z: self.z.add(rhs.z),
1093 w: self.w.add(rhs.w),
1094 }
1095 }
1096 }
1097
1098 impl AddAssign<Vec4> for Vec4 {
1099 #[inline]
1100 fn add_assign(&mut self, rhs: Self) {
1101 self.x.add_assign(rhs.x);
1102 self.y.add_assign(rhs.y);
1103 self.z.add_assign(rhs.z);
1104 self.w.add_assign(rhs.w);
1105 }
1106 }
1107
1108 impl Add<f32> for Vec4 {
1109 type Output = Self;
1110 #[inline]
1111 fn add(self, rhs: f32) -> Self {
1112 Self {
1113 x: self.x.add(rhs),
1114 y: self.y.add(rhs),
1115 z: self.z.add(rhs),
1116 w: self.w.add(rhs),
1117 }
1118 }
1119 }
1120
1121 impl AddAssign<f32> for Vec4 {
1122 #[inline]
1123 fn add_assign(&mut self, rhs: f32) {
1124 self.x.add_assign(rhs);
1125 self.y.add_assign(rhs);
1126 self.z.add_assign(rhs);
1127 self.w.add_assign(rhs);
1128 }
1129 }
1130
1131 impl Add<Vec4> for f32 {
1132 type Output = Vec4;
1133 #[inline]
1134 fn add(self, rhs: Vec4) -> Vec4 {
1135 Vec4 {
1136 x: self.add(rhs.x),
1137 y: self.add(rhs.y),
1138 z: self.add(rhs.z),
1139 w: self.add(rhs.w),
1140 }
1141 }
1142 }
1143
1144 impl Sub<Vec4> for Vec4 {
1145 type Output = Self;
1146 #[inline]
1147 fn sub(self, rhs: Self) -> Self {
1148 Self {
1149 x: self.x.sub(rhs.x),
1150 y: self.y.sub(rhs.y),
1151 z: self.z.sub(rhs.z),
1152 w: self.w.sub(rhs.w),
1153 }
1154 }
1155 }
1156
1157 impl SubAssign<Vec4> for Vec4 {
1158 #[inline]
1159 fn sub_assign(&mut self, rhs: Vec4) {
1160 self.x.sub_assign(rhs.x);
1161 self.y.sub_assign(rhs.y);
1162 self.z.sub_assign(rhs.z);
1163 self.w.sub_assign(rhs.w);
1164 }
1165 }
1166
1167 impl Sub<f32> for Vec4 {
1168 type Output = Self;
1169 #[inline]
1170 fn sub(self, rhs: f32) -> Self {
1171 Self {
1172 x: self.x.sub(rhs),
1173 y: self.y.sub(rhs),
1174 z: self.z.sub(rhs),
1175 w: self.w.sub(rhs),
1176 }
1177 }
1178 }
1179
1180 impl SubAssign<f32> for Vec4 {
1181 #[inline]
1182 fn sub_assign(&mut self, rhs: f32) {
1183 self.x.sub_assign(rhs);
1184 self.y.sub_assign(rhs);
1185 self.z.sub_assign(rhs);
1186 self.w.sub_assign(rhs);
1187 }
1188 }
1189
1190 impl Sub<Vec4> for f32 {
1191 type Output = Vec4;
1192 #[inline]
1193 fn sub(self, rhs: Vec4) -> Vec4 {
1194 Vec4 {
1195 x: self.sub(rhs.x),
1196 y: self.sub(rhs.y),
1197 z: self.sub(rhs.z),
1198 w: self.sub(rhs.w),
1199 }
1200 }
1201 }
1202
1203 impl Rem<Vec4> for Vec4 {
1204 type Output = Self;
1205 #[inline]
1206 fn rem(self, rhs: Self) -> Self {
1207 Self {
1208 x: self.x.rem(rhs.x),
1209 y: self.y.rem(rhs.y),
1210 z: self.z.rem(rhs.z),
1211 w: self.w.rem(rhs.w),
1212 }
1213 }
1214 }
1215
1216 impl RemAssign<Vec4> for Vec4 {
1217 #[inline]
1218 fn rem_assign(&mut self, rhs: Self) {
1219 self.x.rem_assign(rhs.x);
1220 self.y.rem_assign(rhs.y);
1221 self.z.rem_assign(rhs.z);
1222 self.w.rem_assign(rhs.w);
1223 }
1224 }
1225
1226 impl Rem<f32> for Vec4 {
1227 type Output = Self;
1228 #[inline]
1229 fn rem(self, rhs: f32) -> Self {
1230 Self {
1231 x: self.x.rem(rhs),
1232 y: self.y.rem(rhs),
1233 z: self.z.rem(rhs),
1234 w: self.w.rem(rhs),
1235 }
1236 }
1237 }
1238
1239 impl RemAssign<f32> for Vec4 {
1240 #[inline]
1241 fn rem_assign(&mut self, rhs: f32) {
1242 self.x.rem_assign(rhs);
1243 self.y.rem_assign(rhs);
1244 self.z.rem_assign(rhs);
1245 self.w.rem_assign(rhs);
1246 }
1247 }
1248
1249 impl Rem<Vec4> for f32 {
1250 type Output = Vec4;
1251 #[inline]
1252 fn rem(self, rhs: Vec4) -> Vec4 {
1253 Vec4 {
1254 x: self.rem(rhs.x),
1255 y: self.rem(rhs.y),
1256 z: self.rem(rhs.z),
1257 w: self.rem(rhs.w),
1258 }
1259 }
1260 }
1261
1262 #[cfg(not(target_arch = "spirv"))]
1263 impl AsRef<[f32; 4]> for Vec4 {
1264 #[inline]
1265 fn as_ref(&self) -> &[f32; 4] {
1266 unsafe { &*(self as *const Vec4 as *const [f32; 4]) }
1267 }
1268 }
1269
1270 #[cfg(not(target_arch = "spirv"))]
1271 impl AsMut<[f32; 4]> for Vec4 {
1272 #[inline]
1273 fn as_mut(&mut self) -> &mut [f32; 4] {
1274 unsafe { &mut *(self as *mut Vec4 as *mut [f32; 4]) }
1275 }
1276 }
1277
1278 impl Sum for Vec4 {
1279 #[inline]
1280 fn sum<I>(iter: I) -> Self
1281 where
1282 I: Iterator<Item = Self>,
1283 {
1284 iter.fold(Self::ZERO, Self::add)
1285 }
1286 }
1287
1288 impl<'a> Sum<&'a Self> for Vec4 {
1289 #[inline]
1290 fn sum<I>(iter: I) -> Self
1291 where
1292 I: Iterator<Item = &'a Self>,
1293 {
1294 iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
1295 }
1296 }
1297
1298 impl Product for Vec4 {
1299 #[inline]
1300 fn product<I>(iter: I) -> Self
1301 where
1302 I: Iterator<Item = Self>,
1303 {
1304 iter.fold(Self::ONE, Self::mul)
1305 }
1306 }
1307
1308 impl<'a> Product<&'a Self> for Vec4 {
1309 #[inline]
1310 fn product<I>(iter: I) -> Self
1311 where
1312 I: Iterator<Item = &'a Self>,
1313 {
1314 iter.fold(Self::ONE, |a, &b| Self::mul(a, b))
1315 }
1316 }
1317
1318 impl Neg for Vec4 {
1319 type Output = Self;
1320 #[inline]
1321 fn neg(self) -> Self {
1322 Self {
1323 x: self.x.neg(),
1324 y: self.y.neg(),
1325 z: self.z.neg(),
1326 w: self.w.neg(),
1327 }
1328 }
1329 }
1330
1331 impl Index<usize> for Vec4 {
1332 type Output = f32;
1333 #[inline]
1334 fn index(&self, index: usize) -> &Self::Output {
1335 match index {
1336 0 => &self.x,
1337 1 => &self.y,
1338 2 => &self.z,
1339 3 => &self.w,
1340 _ => panic!("index out of bounds"),
1341 }
1342 }
1343 }
1344
1345 impl IndexMut<usize> for Vec4 {
1346 #[inline]
1347 fn index_mut(&mut self, index: usize) -> &mut Self::Output {
1348 match index {
1349 0 => &mut self.x,
1350 1 => &mut self.y,
1351 2 => &mut self.z,
1352 3 => &mut self.w,
1353 _ => panic!("index out of bounds"),
1354 }
1355 }
1356 }
1357
1358 #[cfg(not(target_arch = "spirv"))]
1359 impl fmt::Display for Vec4 {
1360 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1361 if let Some(p) = f.precision() {
1362 write!(
1363 f,
1364 "[{:.*}, {:.*}, {:.*}, {:.*}]",
1365 p, self.x, p, self.y, p, self.z, p, self.w
1366 )
1367 } else {
1368 write!(f, "[{}, {}, {}, {}]", self.x, self.y, self.z, self.w)
1369 }
1370 }
1371 }
1372
1373 #[cfg(not(target_arch = "spirv"))]
1374 impl fmt::Debug for Vec4 {
1375 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1376 fmt.debug_tuple(stringify!(Vec4))
1377 .field(&self.x)
1378 .field(&self.y)
1379 .field(&self.z)
1380 .field(&self.w)
1381 .finish()
1382 }
1383 }
1384
1385 impl From<[f32; 4]> for Vec4 {
1386 #[inline]
1387 fn from(a: [f32; 4]) -> Self {
1388 Self::new(a[0], a[1], a[2], a[3])
1389 }
1390 }
1391
1392 impl From<Vec4> for [f32; 4] {
1393 #[inline]
1394 fn from(v: Vec4) -> Self {
1395 [v.x, v.y, v.z, v.w]
1396 }
1397 }
1398
1399 impl From<(f32, f32, f32, f32)> for Vec4 {
1400 #[inline]
1401 fn from(t: (f32, f32, f32, f32)) -> Self {
1402 Self::new(t.0, t.1, t.2, t.3)
1403 }
1404 }
1405
1406 impl From<Vec4> for (f32, f32, f32, f32) {
1407 #[inline]
1408 fn from(v: Vec4) -> Self {
1409 (v.x, v.y, v.z, v.w)
1410 }
1411 }
1412
1413 impl From<(Vec3A, f32)> for Vec4 {
1414 #[inline]
1415 fn from((v, w): (Vec3A, f32)) -> Self {
1416 v.extend(w)
1417 }
1418 }
1419
1420 impl From<(f32, Vec3A)> for Vec4 {
1421 #[inline]
1422 fn from((x, v): (f32, Vec3A)) -> Self {
1423 Self::new(x, v.x, v.y, v.z)
1424 }
1425 }
1426
1427 impl From<(Vec3, f32)> for Vec4 {
1428 #[inline]
1429 fn from((v, w): (Vec3, f32)) -> Self {
1430 Self::new(v.x, v.y, v.z, w)
1431 }
1432 }
1433
1434 impl From<(f32, Vec3)> for Vec4 {
1435 #[inline]
1436 fn from((x, v): (f32, Vec3)) -> Self {
1437 Self::new(x, v.x, v.y, v.z)
1438 }
1439 }
1440
1441 impl From<(Vec2, f32, f32)> for Vec4 {
1442 #[inline]
1443 fn from((v, z, w): (Vec2, f32, f32)) -> Self {
1444 Self::new(v.x, v.y, z, w)
1445 }
1446 }
1447
1448 impl From<(Vec2, Vec2)> for Vec4 {
1449 #[inline]
1450 fn from((v, u): (Vec2, Vec2)) -> Self {
1451 Self::new(v.x, v.y, u.x, u.y)
1452 }
1453 }
1454
1455 impl From<BVec4> for Vec4 {
1456 #[inline]
1457 fn from(v: BVec4) -> Self {
1458 Self::new(
1459 f32::from(v.x),
1460 f32::from(v.y),
1461 f32::from(v.z),
1462 f32::from(v.w),
1463 )
1464 }
1465 }
1466
1467 #[cfg(not(feature = "scalar-math"))]
1468
1469 impl From<BVec4A> for Vec4 {
1470 #[inline]
1471 fn from(v: BVec4A) -> Self {
1472 let bool_array: [bool; 4] = v.into();
1473 Self::new(
1474 f32::from(bool_array[0]),
1475 f32::from(bool_array[1]),
1476 f32::from(bool_array[2]),
1477 f32::from(bool_array[3]),
1478 )
1479 }
1480 }