Debian Codegraph @

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

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