Debian Codegraph @

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

raw
1 // Generated from vec.rs.tera template. Edit the template, not the generated file.
2
3 use crate::{f32::math, neon::*, 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::aarch64::*;
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) float32x4_t);
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 unsafe { UnionCast { a: [x, y, z, w] }.v }
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(unsafe { vbslq_f32(mask.0, if_true.0, if_false.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 assert!(slice.len() >= 4);
144 unsafe {
145 vst1q_f32(slice.as_mut_ptr(), self.0);
146 }
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 unsafe { 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(unsafe { dot4_into_f32x4(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(unsafe { vminq_f32(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(unsafe { vmaxq_f32(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 unsafe { vminnmvq_f32(self.0) }
246 }
247
248 /// Returns the horizontal maximum of `self`.
249 ///
250 /// In other words this computes `max(x, y, ..)`.
251 #[inline]
252 #[must_use]
253 pub fn max_element(self) -> f32 {
254 unsafe { vmaxnmvq_f32(self.0) }
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 unsafe { vaddvq_f32(self.0) }
264 }
265
266 /// Returns the product of all elements of `self`.
267 ///
268 /// In other words, this computes `self.x * self.y * ..`.
269 #[inline]
270 #[must_use]
271 pub fn element_product(self) -> f32 {
272 unsafe {
273 let s = vmuls_laneq_f32(vgetq_lane_f32(self.0, 0), self.0, 1);
274 let s = vmuls_laneq_f32(s, self.0, 2);
275 vmuls_laneq_f32(s, self.0, 3)
276 }
277 }
278
279 /// Returns a vector mask containing the result of a `==` comparison for each element of
280 /// `self` and `rhs`.
281 ///
282 /// In other words, this computes `[self.x == rhs.x, self.y == rhs.y, ..]` for all
283 /// elements.
284 #[inline]
285 #[must_use]
286 pub fn cmpeq(self, rhs: Self) -> BVec4A {
287 BVec4A(unsafe { vceqq_f32(self.0, rhs.0) })
288 }
289
290 /// Returns a vector mask containing the result of a `!=` comparison for each element of
291 /// `self` and `rhs`.
292 ///
293 /// In other words this computes `[self.x != rhs.x, self.y != rhs.y, ..]` for all
294 /// elements.
295 #[inline]
296 #[must_use]
297 pub fn cmpne(self, rhs: Self) -> BVec4A {
298 BVec4A(unsafe { vmvnq_u32(vceqq_f32(self.0, rhs.0)) })
299 }
300
301 /// Returns a vector mask containing the result of a `>=` comparison for each element of
302 /// `self` and `rhs`.
303 ///
304 /// In other words this computes `[self.x >= rhs.x, self.y >= rhs.y, ..]` for all
305 /// elements.
306 #[inline]
307 #[must_use]
308 pub fn cmpge(self, rhs: Self) -> BVec4A {
309 BVec4A(unsafe { vcgeq_f32(self.0, rhs.0) })
310 }
311
312 /// Returns a vector mask containing the result of a `>` comparison for each element of
313 /// `self` and `rhs`.
314 ///
315 /// In other words this computes `[self.x > rhs.x, self.y > rhs.y, ..]` for all
316 /// elements.
317 #[inline]
318 #[must_use]
319 pub fn cmpgt(self, rhs: Self) -> BVec4A {
320 BVec4A(unsafe { vcgtq_f32(self.0, rhs.0) })
321 }
322
323 /// Returns a vector mask containing the result of a `<=` comparison for each element of
324 /// `self` and `rhs`.
325 ///
326 /// In other words this computes `[self.x <= rhs.x, self.y <= rhs.y, ..]` for all
327 /// elements.
328 #[inline]
329 #[must_use]
330 pub fn cmple(self, rhs: Self) -> BVec4A {
331 BVec4A(unsafe { vcleq_f32(self.0, rhs.0) })
332 }
333
334 /// Returns a vector mask containing the result of a `<` comparison for each element of
335 /// `self` and `rhs`.
336 ///
337 /// In other words this computes `[self.x < rhs.x, self.y < rhs.y, ..]` for all
338 /// elements.
339 #[inline]
340 #[must_use]
341 pub fn cmplt(self, rhs: Self) -> BVec4A {
342 BVec4A(unsafe { vcltq_f32(self.0, rhs.0) })
343 }
344
345 /// Returns a vector containing the absolute value of each element of `self`.
346 #[inline]
347 #[must_use]
348 pub fn abs(self) -> Self {
349 Self(unsafe { vabsq_f32(self.0) })
350 }
351
352 /// Returns a vector with elements representing the sign of `self`.
353 ///
354 /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
355 /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
356 /// - `NAN` if the number is `NAN`
357 #[inline]
358 #[must_use]
359 pub fn signum(self) -> Self {
360 let result = Self(unsafe {
361 vreinterpretq_f32_u32(vorrq_u32(
362 vandq_u32(
363 vreinterpretq_u32_f32(self.0),
364 vreinterpretq_u32_f32(Self::NEG_ONE.0),
365 ),
366 vreinterpretq_u32_f32(Self::ONE.0),
367 ))
368 });
369 let mask = self.is_nan_mask();
370 Self::select(mask, self, result)
371 }
372
373 /// Returns a vector with signs of `rhs` and the magnitudes of `self`.
374 #[inline]
375 #[must_use]
376 pub fn copysign(self, rhs: Self) -> Self {
377 let mask = Self::splat(-0.0);
378 Self(unsafe {
379 vreinterpretq_f32_u32(vorrq_u32(
380 vandq_u32(vreinterpretq_u32_f32(rhs.0), vreinterpretq_u32_f32(mask.0)),
381 vandq_u32(
382 vreinterpretq_u32_f32(self.0),
383 vmvnq_u32(vreinterpretq_u32_f32(mask.0)),
384 ),
385 ))
386 })
387 }
388
389 /// Returns a bitmask with the lowest 4 bits set to the sign bits from the elements of `self`.
390 ///
391 /// A negative element results in a `1` bit and a positive element in a `0` bit. Element `x` goes
392 /// into the first lowest bit, element `y` into the second, etc.
393 #[inline]
394 #[must_use]
395 pub fn is_negative_bitmask(self) -> u32 {
396 unsafe {
397 let nmask = vreinterpretq_u32_f32(vdupq_n_f32(-0.0));
398 let m = vandq_u32(vreinterpretq_u32_f32(self.0), nmask);
399 let x = vgetq_lane_u32(m, 0) >> 31;
400 let y = vgetq_lane_u32(m, 1) >> 31;
401 let z = vgetq_lane_u32(m, 2) >> 31;
402
403 let w = vgetq_lane_u32(m, 3) >> 31;
404 x | y << 1 | z << 2 | w << 3
405 }
406 }
407
408 /// Returns `true` if, and only if, all elements are finite. If any element is either
409 /// `NaN`, positive or negative infinity, this will return `false`.
410 #[inline]
411 #[must_use]
412 pub fn is_finite(self) -> bool {
413 self.x.is_finite() && self.y.is_finite() && self.z.is_finite() && self.w.is_finite()
414 }
415
416 /// Returns `true` if any elements are `NaN`.
417 #[inline]
418 #[must_use]
419 pub fn is_nan(self) -> bool {
420 self.is_nan_mask().any()
421 }
422
423 /// Performs `is_nan` on each element of self, returning a vector mask of the results.
424 ///
425 /// In other words, this computes `[x.is_nan(), y.is_nan(), z.is_nan(), w.is_nan()]`.
426 #[inline]
427 #[must_use]
428 pub fn is_nan_mask(self) -> BVec4A {
429 BVec4A(unsafe { vmvnq_u32(vceqq_f32(self.0, self.0)) })
430 }
431
432 /// Computes the length of `self`.
433 #[doc(alias = "magnitude")]
434 #[inline]
435 #[must_use]
436 pub fn length(self) -> f32 {
437 math::sqrt(self.dot(self))
438 }
439
440 /// Computes the squared length of `self`.
441 ///
442 /// This is faster than `length()` as it avoids a square root operation.
443 #[doc(alias = "magnitude2")]
444 #[inline]
445 #[must_use]
446 pub fn length_squared(self) -> f32 {
447 self.dot(self)
448 }
449
450 /// Computes `1.0 / length()`.
451 ///
452 /// For valid results, `self` must _not_ be of length zero.
453 #[inline]
454 #[must_use]
455 pub fn length_recip(self) -> f32 {
456 self.length().recip()
457 }
458
459 /// Computes the Euclidean distance between two points in space.
460 #[inline]
461 #[must_use]
462 pub fn distance(self, rhs: Self) -> f32 {
463 (self - rhs).length()
464 }
465
466 /// Compute the squared euclidean distance between two points in space.
467 #[inline]
468 #[must_use]
469 pub fn distance_squared(self, rhs: Self) -> f32 {
470 (self - rhs).length_squared()
471 }
472
473 /// Returns the element-wise quotient of [Euclidean division] of `self` by `rhs`.
474 #[inline]
475 #[must_use]
476 pub fn div_euclid(self, rhs: Self) -> Self {
477 Self::new(
478 math::div_euclid(self.x, rhs.x),
479 math::div_euclid(self.y, rhs.y),
480 math::div_euclid(self.z, rhs.z),
481 math::div_euclid(self.w, rhs.w),
482 )
483 }
484
485 /// Returns the element-wise remainder of [Euclidean division] of `self` by `rhs`.
486 ///
487 /// [Euclidean division]: f32::rem_euclid
488 #[inline]
489 #[must_use]
490 pub fn rem_euclid(self, rhs: Self) -> Self {
491 Self::new(
492 math::rem_euclid(self.x, rhs.x),
493 math::rem_euclid(self.y, rhs.y),
494 math::rem_euclid(self.z, rhs.z),
495 math::rem_euclid(self.w, rhs.w),
496 )
497 }
498
499 /// Returns `self` normalized to length 1.0.
500 ///
501 /// For valid results, `self` must _not_ be of length zero, nor very close to zero.
502 ///
503 /// See also [`Self::try_normalize()`] and [`Self::normalize_or_zero()`].
504 ///
505 /// Panics
506 ///
507 /// Will panic if `self` is zero length when `glam_assert` is enabled.
508 #[inline]
509 #[must_use]
510 pub fn normalize(self) -> Self {
511 #[allow(clippy::let_and_return)]
512 let normalized = self.mul(self.length_recip());
513 glam_assert!(normalized.is_finite());
514 normalized
515 }
516
517 /// Returns `self` normalized to length 1.0 if possible, else returns `None`.
518 ///
519 /// In particular, if the input is zero (or very close to zero), or non-finite,
520 /// the result of this operation will be `None`.
521 ///
522 /// See also [`Self::normalize_or_zero()`].
523 #[inline]
524 #[must_use]
525 pub fn try_normalize(self) -> Option<Self> {
526 let rcp = self.length_recip();
527 if rcp.is_finite() && rcp > 0.0 {
528 Some(self * rcp)
529 } else {
530 None
531 }
532 }
533
534 /// Returns `self` normalized to length 1.0 if possible, else returns a
535 /// fallback value.
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 the fallback value.
539 ///
540 /// See also [`Self::try_normalize()`].
541 #[inline]
542 #[must_use]
543 pub fn normalize_or(self, fallback: Self) -> Self {
544 let rcp = self.length_recip();
545 if rcp.is_finite() && rcp > 0.0 {
546 self * rcp
547 } else {
548 fallback
549 }
550 }
551
552 /// Returns `self` normalized to length 1.0 if possible, else returns zero.
553 ///
554 /// In particular, if the input is zero (or very close to zero), or non-finite,
555 /// the result of this operation will be zero.
556 ///
557 /// See also [`Self::try_normalize()`].
558 #[inline]
559 #[must_use]
560 pub fn normalize_or_zero(self) -> Self {
561 self.normalize_or(Self::ZERO)
562 }
563
564 /// Returns whether `self` is length `1.0` or not.
565 ///
566 /// Uses a precision threshold of approximately `1e-4`.
567 #[inline]
568 #[must_use]
569 pub fn is_normalized(self) -> bool {
570 math::abs(self.length_squared() - 1.0) <= 2e-4
571 }
572
573 /// Returns the vector projection of `self` onto `rhs`.
574 ///
575 /// `rhs` must be of non-zero length.
576 ///
577 /// # Panics
578 ///
579 /// Will panic if `rhs` is zero length when `glam_assert` is enabled.
580 #[inline]
581 #[must_use]
582 pub fn project_onto(self, rhs: Self) -> Self {
583 let other_len_sq_rcp = rhs.dot(rhs).recip();
584 glam_assert!(other_len_sq_rcp.is_finite());
585 rhs * self.dot(rhs) * other_len_sq_rcp
586 }
587
588 /// Returns the vector rejection of `self` from `rhs`.
589 ///
590 /// The vector rejection is the vector perpendicular to the projection of `self` onto
591 /// `rhs`, in rhs words the result of `self - self.project_onto(rhs)`.
592 ///
593 /// `rhs` must be of non-zero length.
594 ///
595 /// # Panics
596 ///
597 /// Will panic if `rhs` has a length of zero when `glam_assert` is enabled.
598 #[inline]
599 #[must_use]
600 pub fn reject_from(self, rhs: Self) -> Self {
601 self - self.project_onto(rhs)
602 }
603
604 /// Returns the vector projection of `self` 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 project_onto_normalized(self, rhs: Self) -> Self {
614 glam_assert!(rhs.is_normalized());
615 rhs * self.dot(rhs)
616 }
617
618 /// Returns the vector rejection of `self` from `rhs`.
619 ///
620 /// The vector rejection is the vector perpendicular to the projection of `self` onto
621 /// `rhs`, in rhs words the result of `self - self.project_onto(rhs)`.
622 ///
623 /// `rhs` must be normalized.
624 ///
625 /// # Panics
626 ///
627 /// Will panic if `rhs` is not normalized when `glam_assert` is enabled.
628 #[inline]
629 #[must_use]
630 pub fn reject_from_normalized(self, rhs: Self) -> Self {
631 self - self.project_onto_normalized(rhs)
632 }
633
634 /// Returns a vector containing the nearest integer to a number for each element of `self`.
635 /// Round half-way cases away from 0.0.
636 #[inline]
637 #[must_use]
638 pub fn round(self) -> Self {
639 Self(unsafe { vrndnq_f32(self.0) })
640 }
641
642 /// Returns a vector containing the largest integer less than or equal to a number for each
643 /// element of `self`.
644 #[inline]
645 #[must_use]
646 pub fn floor(self) -> Self {
647 Self(unsafe { vrndmq_f32(self.0) })
648 }
649
650 /// Returns a vector containing the smallest integer greater than or equal to a number for
651 /// each element of `self`.
652 #[inline]
653 #[must_use]
654 pub fn ceil(self) -> Self {
655 Self(unsafe { vrndpq_f32(self.0) })
656 }
657
658 /// Returns a vector containing the integer part each element of `self`. This means numbers are
659 /// always truncated towards zero.
660 #[inline]
661 #[must_use]
662 pub fn trunc(self) -> Self {
663 Self(unsafe { vrndq_f32(self.0) })
664 }
665
666 /// Returns a vector containing the fractional part of the vector as `self - self.trunc()`.
667 ///
668 /// Note that this differs from the GLSL implementation of `fract` which returns
669 /// `self - self.floor()`.
670 ///
671 /// Note that this is fast but not precise for large numbers.
672 #[inline]
673 #[must_use]
674 pub fn fract(self) -> Self {
675 self - self.trunc()
676 }
677
678 /// Returns a vector containing the fractional part of the vector as `self - self.floor()`.
679 ///
680 /// Note that this differs from the Rust implementation of `fract` which returns
681 /// `self - self.trunc()`.
682 ///
683 /// Note that this is fast but not precise for large numbers.
684 #[inline]
685 #[must_use]
686 pub fn fract_gl(self) -> Self {
687 self - self.floor()
688 }
689
690 /// Returns a vector containing `e^self` (the exponential function) for each element of
691 /// `self`.
692 #[inline]
693 #[must_use]
694 pub fn exp(self) -> Self {
695 Self::new(
696 math::exp(self.x),
697 math::exp(self.y),
698 math::exp(self.z),
699 math::exp(self.w),
700 )
701 }
702
703 /// Returns a vector containing each element of `self` raised to the power of `n`.
704 #[inline]
705 #[must_use]
706 pub fn powf(self, n: f32) -> Self {
707 Self::new(
708 math::powf(self.x, n),
709 math::powf(self.y, n),
710 math::powf(self.z, n),
711 math::powf(self.w, n),
712 )
713 }
714
715 /// Returns a vector containing the reciprocal `1.0/n` of each element of `self`.
716 #[inline]
717 #[must_use]
718 pub fn recip(self) -> Self {
719 Self(unsafe { vdivq_f32(Self::ONE.0, self.0) })
720 }
721
722 /// Performs a linear interpolation between `self` and `rhs` based on the value `s`.
723 ///
724 /// When `s` is `0.0`, the result will be equal to `self`. When `s` is `1.0`, the result
725 /// will be equal to `rhs`. When `s` is outside of range `[0, 1]`, the result is linearly
726 /// extrapolated.
727 #[doc(alias = "mix")]
728 #[inline]
729 #[must_use]
730 pub fn lerp(self, rhs: Self, s: f32) -> Self {
731 self + ((rhs - self) * s)
732 }
733
734 /// Moves towards `rhs` based on the value `d`.
735 ///
736 /// When `d` is `0.0`, the result will be equal to `self`. When `d` is equal to
737 /// `self.distance(rhs)`, the result will be equal to `rhs`. Will not go past `rhs`.
738 #[inline]
739 #[must_use]
740 pub fn move_towards(&self, rhs: Self, d: f32) -> Self {
741 let a = rhs - *self;
742 let len = a.length();
743 if len <= d || len <= 1e-4 {
744 return rhs;
745 }
746 *self + a / len * d
747 }
748
749 /// Calculates the midpoint between `self` and `rhs`.
750 ///
751 /// The midpoint is the average of, or halfway point between, two vectors.
752 /// `a.midpoint(b)` should yield the same result as `a.lerp(b, 0.5)`
753 /// while being slightly cheaper to compute.
754 #[inline]
755 pub fn midpoint(self, rhs: Self) -> Self {
756 (self + rhs) * 0.5
757 }
758
759 /// Returns true if the absolute difference of all elements between `self` and `rhs` is
760 /// less than or equal to `max_abs_diff`.
761 ///
762 /// This can be used to compare if two vectors contain similar elements. It works best when
763 /// comparing with a known value. The `max_abs_diff` that should be used used depends on
764 /// the values being compared against.
765 ///
766 /// For more see
767 /// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
768 #[inline]
769 #[must_use]
770 pub fn abs_diff_eq(self, rhs: Self, max_abs_diff: f32) -> bool {
771 self.sub(rhs).abs().cmple(Self::splat(max_abs_diff)).all()
772 }
773
774 /// Returns a vector with a length no less than `min` and no more than `max`.
775 ///
776 /// # Panics
777 ///
778 /// Will panic if `min` is greater than `max`, or if either `min` or `max` is negative, when `glam_assert` is enabled.
779 #[inline]
780 #[must_use]
781 pub fn clamp_length(self, min: f32, max: f32) -> Self {
782 glam_assert!(0.0 <= min);
783 glam_assert!(min <= max);
784 let length_sq = self.length_squared();
785 if length_sq < min * min {
786 min * (self / math::sqrt(length_sq))
787 } else 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 more than `max`.
795 ///
796 /// # Panics
797 ///
798 /// Will panic if `max` is negative when `glam_assert` is enabled.
799 #[inline]
800 #[must_use]
801 pub fn clamp_length_max(self, max: f32) -> Self {
802 glam_assert!(0.0 <= max);
803 let length_sq = self.length_squared();
804 if length_sq > max * max {
805 max * (self / math::sqrt(length_sq))
806 } else {
807 self
808 }
809 }
810
811 /// Returns a vector with a length no less than `min`.
812 ///
813 /// # Panics
814 ///
815 /// Will panic if `min` is negative when `glam_assert` is enabled.
816 #[inline]
817 #[must_use]
818 pub fn clamp_length_min(self, min: f32) -> Self {
819 glam_assert!(0.0 <= min);
820 let length_sq = self.length_squared();
821 if length_sq < min * min {
822 min * (self / math::sqrt(length_sq))
823 } else {
824 self
825 }
826 }
827
828 /// Fused multiply-add. Computes `(self * a) + b` element-wise with only one rounding
829 /// error, yielding a more accurate result than an unfused multiply-add.
830 ///
831 /// Using `mul_add` *may* be more performant than an unfused multiply-add if the target
832 /// architecture has a dedicated fma CPU instruction. However, this is not always true,
833 /// and will be heavily dependant on designing algorithms with specific target hardware in
834 /// mind.
835 #[inline]
836 #[must_use]
837 pub fn mul_add(self, a: Self, b: Self) -> Self {
838 Self(unsafe { vfmaq_f32(b.0, self.0, a.0) })
839 }
840
841 /// Casts all elements of `self` to `f64`.
842 #[inline]
843 #[must_use]
844 pub fn as_dvec4(&self) -> crate::DVec4 {
845 crate::DVec4::new(self.x as f64, self.y as f64, self.z as f64, self.w as f64)
846 }
847
848 /// Casts all elements of `self` to `i16`.
849 #[inline]
850 #[must_use]
851 pub fn as_i16vec4(&self) -> crate::I16Vec4 {
852 crate::I16Vec4::new(self.x as i16, self.y as i16, self.z as i16, self.w as i16)
853 }
854
855 /// Casts all elements of `self` to `u16`.
856 #[inline]
857 #[must_use]
858 pub fn as_u16vec4(&self) -> crate::U16Vec4 {
859 crate::U16Vec4::new(self.x as u16, self.y as u16, self.z as u16, self.w as u16)
860 }
861
862 /// Casts all elements of `self` to `i32`.
863 #[inline]
864 #[must_use]
865 pub fn as_ivec4(&self) -> crate::IVec4 {
866 crate::IVec4::new(self.x as i32, self.y as i32, self.z as i32, self.w as i32)
867 }
868
869 /// Casts all elements of `self` to `u32`.
870 #[inline]
871 #[must_use]
872 pub fn as_uvec4(&self) -> crate::UVec4 {
873 crate::UVec4::new(self.x as u32, self.y as u32, self.z as u32, self.w as u32)
874 }
875
876 /// Casts all elements of `self` to `i64`.
877 #[inline]
878 #[must_use]
879 pub fn as_i64vec4(&self) -> crate::I64Vec4 {
880 crate::I64Vec4::new(self.x as i64, self.y as i64, self.z as i64, self.w as i64)
881 }
882
883 /// Casts all elements of `self` to `u64`.
884 #[inline]
885 #[must_use]
886 pub fn as_u64vec4(&self) -> crate::U64Vec4 {
887 crate::U64Vec4::new(self.x as u64, self.y as u64, self.z as u64, self.w as u64)
888 }
889 }
890
891 impl Default for Vec4 {
892 #[inline(always)]
893 fn default() -> Self {
894 Self::ZERO
895 }
896 }
897
898 impl PartialEq for Vec4 {
899 #[inline]
900 fn eq(&self, rhs: &Self) -> bool {
901 self.cmpeq(*rhs).all()
902 }
903 }
904
905 impl Div<Vec4> for Vec4 {
906 type Output = Self;
907 #[inline]
908 fn div(self, rhs: Self) -> Self {
909 Self(unsafe { vdivq_f32(self.0, rhs.0) })
910 }
911 }
912
913 impl DivAssign<Vec4> for Vec4 {
914 #[inline]
915 fn div_assign(&mut self, rhs: Self) {
916 self.0 = unsafe { vdivq_f32(self.0, rhs.0) };
917 }
918 }
919
920 impl Div<f32> for Vec4 {
921 type Output = Self;
922 #[inline]
923 fn div(self, rhs: f32) -> Self {
924 Self(unsafe { vdivq_f32(self.0, vld1q_dup_f32(&rhs)) })
925 }
926 }
927
928 impl DivAssign<f32> for Vec4 {
929 #[inline]
930 fn div_assign(&mut self, rhs: f32) {
931 self.0 = unsafe { vdivq_f32(self.0, vld1q_dup_f32(&rhs)) };
932 }
933 }
934
935 impl Div<Vec4> for f32 {
936 type Output = Vec4;
937 #[inline]
938 fn div(self, rhs: Vec4) -> Vec4 {
939 Vec4(unsafe { vdivq_f32(vld1q_dup_f32(&self), rhs.0) })
940 }
941 }
942
943 impl Mul<Vec4> for Vec4 {
944 type Output = Self;
945 #[inline]
946 fn mul(self, rhs: Self) -> Self {
947 Self(unsafe { vmulq_f32(self.0, rhs.0) })
948 }
949 }
950
951 impl MulAssign<Vec4> for Vec4 {
952 #[inline]
953 fn mul_assign(&mut self, rhs: Self) {
954 self.0 = unsafe { vmulq_f32(self.0, rhs.0) };
955 }
956 }
957
958 impl Mul<f32> for Vec4 {
959 type Output = Self;
960 #[inline]
961 fn mul(self, rhs: f32) -> Self {
962 Self(unsafe { vmulq_n_f32(self.0, rhs) })
963 }
964 }
965
966 impl MulAssign<f32> for Vec4 {
967 #[inline]
968 fn mul_assign(&mut self, rhs: f32) {
969 self.0 = unsafe { vmulq_n_f32(self.0, rhs) };
970 }
971 }
972
973 impl Mul<Vec4> for f32 {
974 type Output = Vec4;
975 #[inline]
976 fn mul(self, rhs: Vec4) -> Vec4 {
977 Vec4(unsafe { vmulq_n_f32(rhs.0, self) })
978 }
979 }
980
981 impl Add<Vec4> for Vec4 {
982 type Output = Self;
983 #[inline]
984 fn add(self, rhs: Self) -> Self {
985 Self(unsafe { vaddq_f32(self.0, rhs.0) })
986 }
987 }
988
989 impl AddAssign<Vec4> for Vec4 {
990 #[inline]
991 fn add_assign(&mut self, rhs: Self) {
992 self.0 = unsafe { vaddq_f32(self.0, rhs.0) };
993 }
994 }
995
996 impl Add<f32> for Vec4 {
997 type Output = Self;
998 #[inline]
999 fn add(self, rhs: f32) -> Self {
1000 Self(unsafe { vaddq_f32(self.0, vld1q_dup_f32(&rhs)) })
1001 }
1002 }
1003
1004 impl AddAssign<f32> for Vec4 {
1005 #[inline]
1006 fn add_assign(&mut self, rhs: f32) {
1007 self.0 = unsafe { vaddq_f32(self.0, vld1q_dup_f32(&rhs)) };
1008 }
1009 }
1010
1011 impl Add<Vec4> for f32 {
1012 type Output = Vec4;
1013 #[inline]
1014 fn add(self, rhs: Vec4) -> Vec4 {
1015 Vec4(unsafe { vaddq_f32(vld1q_dup_f32(&self), rhs.0) })
1016 }
1017 }
1018
1019 impl Sub<Vec4> for Vec4 {
1020 type Output = Self;
1021 #[inline]
1022 fn sub(self, rhs: Self) -> Self {
1023 Self(unsafe { vsubq_f32(self.0, rhs.0) })
1024 }
1025 }
1026
1027 impl SubAssign<Vec4> for Vec4 {
1028 #[inline]
1029 fn sub_assign(&mut self, rhs: Vec4) {
1030 self.0 = unsafe { vsubq_f32(self.0, rhs.0) };
1031 }
1032 }
1033
1034 impl Sub<f32> for Vec4 {
1035 type Output = Self;
1036 #[inline]
1037 fn sub(self, rhs: f32) -> Self {
1038 Self(unsafe { vsubq_f32(self.0, vld1q_dup_f32(&rhs)) })
1039 }
1040 }
1041
1042 impl SubAssign<f32> for Vec4 {
1043 #[inline]
1044 fn sub_assign(&mut self, rhs: f32) {
1045 self.0 = unsafe { vsubq_f32(self.0, vld1q_dup_f32(&rhs)) };
1046 }
1047 }
1048
1049 impl Sub<Vec4> for f32 {
1050 type Output = Vec4;
1051 #[inline]
1052 fn sub(self, rhs: Vec4) -> Vec4 {
1053 Vec4(unsafe { vsubq_f32(vld1q_dup_f32(&self), rhs.0) })
1054 }
1055 }
1056
1057 impl Rem<Vec4> for Vec4 {
1058 type Output = Self;
1059 #[inline]
1060 fn rem(self, rhs: Self) -> Self {
1061 unsafe {
1062 let n = vrndmq_f32(vdivq_f32(self.0, rhs.0));
1063 Self(vsubq_f32(self.0, vmulq_f32(n, rhs.0)))
1064 }
1065 }
1066 }
1067
1068 impl RemAssign<Vec4> for Vec4 {
1069 #[inline]
1070 fn rem_assign(&mut self, rhs: Self) {
1071 *self = self.rem(rhs);
1072 }
1073 }
1074
1075 impl Rem<f32> for Vec4 {
1076 type Output = Self;
1077 #[inline]
1078 fn rem(self, rhs: f32) -> Self {
1079 self.rem(Self::splat(rhs))
1080 }
1081 }
1082
1083 impl RemAssign<f32> for Vec4 {
1084 #[inline]
1085 fn rem_assign(&mut self, rhs: f32) {
1086 *self = self.rem(Self::splat(rhs));
1087 }
1088 }
1089
1090 impl Rem<Vec4> for f32 {
1091 type Output = Vec4;
1092 #[inline]
1093 fn rem(self, rhs: Vec4) -> Vec4 {
1094 Vec4::splat(self).rem(rhs)
1095 }
1096 }
1097
1098 #[cfg(not(target_arch = "spirv"))]
1099 impl AsRef<[f32; 4]> for Vec4 {
1100 #[inline]
1101 fn as_ref(&self) -> &[f32; 4] {
1102 unsafe { &*(self as *const Vec4 as *const [f32; 4]) }
1103 }
1104 }
1105
1106 #[cfg(not(target_arch = "spirv"))]
1107 impl AsMut<[f32; 4]> for Vec4 {
1108 #[inline]
1109 fn as_mut(&mut self) -> &mut [f32; 4] {
1110 unsafe { &mut *(self as *mut Vec4 as *mut [f32; 4]) }
1111 }
1112 }
1113
1114 impl Sum for Vec4 {
1115 #[inline]
1116 fn sum<I>(iter: I) -> Self
1117 where
1118 I: Iterator<Item = Self>,
1119 {
1120 iter.fold(Self::ZERO, Self::add)
1121 }
1122 }
1123
1124 impl<'a> Sum<&'a Self> for Vec4 {
1125 #[inline]
1126 fn sum<I>(iter: I) -> Self
1127 where
1128 I: Iterator<Item = &'a Self>,
1129 {
1130 iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
1131 }
1132 }
1133
1134 impl Product for Vec4 {
1135 #[inline]
1136 fn product<I>(iter: I) -> Self
1137 where
1138 I: Iterator<Item = Self>,
1139 {
1140 iter.fold(Self::ONE, Self::mul)
1141 }
1142 }
1143
1144 impl<'a> Product<&'a Self> for Vec4 {
1145 #[inline]
1146 fn product<I>(iter: I) -> Self
1147 where
1148 I: Iterator<Item = &'a Self>,
1149 {
1150 iter.fold(Self::ONE, |a, &b| Self::mul(a, b))
1151 }
1152 }
1153
1154 impl Neg for Vec4 {
1155 type Output = Self;
1156 #[inline]
1157 fn neg(self) -> Self {
1158 Self(unsafe { vnegq_f32(self.0) })
1159 }
1160 }
1161
1162 impl Index<usize> for Vec4 {
1163 type Output = f32;
1164 #[inline]
1165 fn index(&self, index: usize) -> &Self::Output {
1166 match index {
1167 0 => &self.x,
1168 1 => &self.y,
1169 2 => &self.z,
1170 3 => &self.w,
1171 _ => panic!("index out of bounds"),
1172 }
1173 }
1174 }
1175
1176 impl IndexMut<usize> for Vec4 {
1177 #[inline]
1178 fn index_mut(&mut self, index: usize) -> &mut Self::Output {
1179 match index {
1180 0 => &mut self.x,
1181 1 => &mut self.y,
1182 2 => &mut self.z,
1183 3 => &mut self.w,
1184 _ => panic!("index out of bounds"),
1185 }
1186 }
1187 }
1188
1189 #[cfg(not(target_arch = "spirv"))]
1190 impl fmt::Display for Vec4 {
1191 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1192 if let Some(p) = f.precision() {
1193 write!(
1194 f,
1195 "[{:.*}, {:.*}, {:.*}, {:.*}]",
1196 p, self.x, p, self.y, p, self.z, p, self.w
1197 )
1198 } else {
1199 write!(f, "[{}, {}, {}, {}]", self.x, self.y, self.z, self.w)
1200 }
1201 }
1202 }
1203
1204 #[cfg(not(target_arch = "spirv"))]
1205 impl fmt::Debug for Vec4 {
1206 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1207 fmt.debug_tuple(stringify!(Vec4))
1208 .field(&self.x)
1209 .field(&self.y)
1210 .field(&self.z)
1211 .field(&self.w)
1212 .finish()
1213 }
1214 }
1215
1216 impl From<Vec4> for float32x4_t {
1217 #[inline(always)]
1218 fn from(t: Vec4) -> Self {
1219 t.0
1220 }
1221 }
1222
1223 impl From<float32x4_t> for Vec4 {
1224 #[inline(always)]
1225 fn from(t: float32x4_t) -> Self {
1226 Self(t)
1227 }
1228 }
1229
1230 impl From<[f32; 4]> for Vec4 {
1231 #[inline]
1232 fn from(a: [f32; 4]) -> Self {
1233 Self(unsafe { vld1q_f32(a.as_ptr()) })
1234 }
1235 }
1236
1237 impl From<Vec4> for [f32; 4] {
1238 #[inline]
1239 fn from(v: Vec4) -> Self {
1240 use crate::align16::Align16;
1241 use core::mem::MaybeUninit;
1242 let mut out: MaybeUninit<Align16<Self>> = MaybeUninit::uninit();
1243 unsafe {
1244 vst1q_f32(out.as_mut_ptr().cast(), v.0);
1245 out.assume_init().0
1246 }
1247 }
1248 }
1249
1250 impl From<(f32, f32, f32, f32)> for Vec4 {
1251 #[inline]
1252 fn from(t: (f32, f32, f32, f32)) -> Self {
1253 Self::new(t.0, t.1, t.2, t.3)
1254 }
1255 }
1256
1257 impl From<Vec4> for (f32, f32, f32, f32) {
1258 #[inline]
1259 fn from(v: Vec4) -> Self {
1260 use crate::align16::Align16;
1261 use core::mem::MaybeUninit;
1262 let mut out: MaybeUninit<Align16<Self>> = MaybeUninit::uninit();
1263 unsafe {
1264 vst1q_f32(out.as_mut_ptr().cast(), v.0);
1265 out.assume_init().0
1266 }
1267 }
1268 }
1269
1270 impl From<(Vec3A, f32)> for Vec4 {
1271 #[inline]
1272 fn from((v, w): (Vec3A, f32)) -> Self {
1273 v.extend(w)
1274 }
1275 }
1276
1277 impl From<(f32, Vec3A)> for Vec4 {
1278 #[inline]
1279 fn from((x, v): (f32, Vec3A)) -> Self {
1280 Self::new(x, v.x, v.y, v.z)
1281 }
1282 }
1283
1284 impl From<(Vec3, f32)> for Vec4 {
1285 #[inline]
1286 fn from((v, w): (Vec3, f32)) -> Self {
1287 Self::new(v.x, v.y, v.z, w)
1288 }
1289 }
1290
1291 impl From<(f32, Vec3)> for Vec4 {
1292 #[inline]
1293 fn from((x, v): (f32, Vec3)) -> Self {
1294 Self::new(x, v.x, v.y, v.z)
1295 }
1296 }
1297
1298 impl From<(Vec2, f32, f32)> for Vec4 {
1299 #[inline]
1300 fn from((v, z, w): (Vec2, f32, f32)) -> Self {
1301 Self::new(v.x, v.y, z, w)
1302 }
1303 }
1304
1305 impl From<(Vec2, Vec2)> for Vec4 {
1306 #[inline]
1307 fn from((v, u): (Vec2, Vec2)) -> Self {
1308 Self::new(v.x, v.y, u.x, u.y)
1309 }
1310 }
1311
1312 impl Deref for Vec4 {
1313 type Target = crate::deref::Vec4<f32>;
1314 #[inline]
1315 fn deref(&self) -> &Self::Target {
1316 unsafe { &*(self as *const Self).cast() }
1317 }
1318 }
1319
1320 impl DerefMut for Vec4 {
1321 #[inline]
1322 fn deref_mut(&mut self) -> &mut Self::Target {
1323 unsafe { &mut *(self as *mut Self).cast() }
1324 }
1325 }
1326
1327 impl From<BVec4> for Vec4 {
1328 #[inline]
1329 fn from(v: BVec4) -> Self {
1330 Self::new(
1331 f32::from(v.x),
1332 f32::from(v.y),
1333 f32::from(v.z),
1334 f32::from(v.w),
1335 )
1336 }
1337 }
1338
1339 #[cfg(not(feature = "scalar-math"))]
1340
1341 impl From<BVec4A> for Vec4 {
1342 #[inline]
1343 fn from(v: BVec4A) -> Self {
1344 let bool_array: [bool; 4] = v.into();
1345 Self::new(
1346 f32::from(bool_array[0]),
1347 f32::from(bool_array[1]),
1348 f32::from(bool_array[2]),
1349 f32::from(bool_array[3]),
1350 )
1351 }
1352 }