Debian Codegraph @

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