Debian Codegraph @

debian/missing-sources/glam-0.28.0/src/f32/wasm32/vec4.rs

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