Debian Codegraph @

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

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