Vendor dependencies for 0.3.0 release

This commit is contained in:
2025-09-27 20:53:56 -05:00
parent 0c8d39d483
commit 82ab7f317b
26803 changed files with 16134934 additions and 0 deletions
+27
View File
@@ -0,0 +1,27 @@
#[derive(Clone, Copy, Default, PartialEq, PartialOrd)]
#[repr(C, align(16))]
pub(crate) struct Align16<T>(pub T);
impl<T> Align16<T> {
#[allow(dead_code)]
pub fn as_ptr(&self) -> *const T {
&self.0
}
#[allow(dead_code)]
pub fn as_mut_ptr(&mut self) -> *mut T {
&mut self.0
}
}
#[test]
fn test_align16() {
use core::{mem, ptr};
let mut a = Align16::<f32>(1.0);
assert_eq!(mem::align_of_val(&a), 16);
unsafe {
assert_eq!(ptr::read(a.as_ptr()).to_bits(), f32::to_bits(1.0));
ptr::write(a.as_mut_ptr(), -1.0);
}
assert_eq!(a.0.to_bits(), f32::to_bits(-1.0));
}
+126
View File
@@ -0,0 +1,126 @@
mod bvec2;
mod bvec3;
mod bvec4;
#[cfg(all(feature = "core-simd", not(feature = "scalar-math")))]
mod coresimd;
#[cfg(all(
target_arch = "aarch64",
not(any(feature = "core-simd", feature = "scalar-math"))
))]
mod neon;
#[cfg(all(
target_feature = "sse2",
not(any(feature = "core-simd", feature = "scalar-math"))
))]
mod sse2;
#[cfg(all(
target_feature = "simd128",
not(any(feature = "core-simd", feature = "scalar-math"))
))]
mod wasm32;
#[cfg(any(
not(any(
feature = "core-simd",
target_arch = "aarch64",
target_feature = "sse2",
target_feature = "simd128"
)),
feature = "scalar-math"
))]
mod scalar;
pub use bvec2::{bvec2, BVec2};
pub use bvec3::{bvec3, BVec3};
pub use bvec4::{bvec4, BVec4};
#[cfg(all(
target_arch = "aarch64",
not(any(feature = "core-simd", feature = "scalar-math"))
))]
pub use neon::bvec3a::{bvec3a, BVec3A};
#[cfg(all(
target_arch = "aarch64",
not(any(feature = "core-simd", feature = "scalar-math"))
))]
pub use neon::bvec4a::{bvec4a, BVec4A};
#[cfg(all(
target_feature = "sse2",
not(any(feature = "core-simd", feature = "scalar-math"))
))]
pub use sse2::bvec3a::{bvec3a, BVec3A};
#[cfg(all(
target_feature = "sse2",
not(any(feature = "core-simd", feature = "scalar-math"))
))]
pub use sse2::bvec4a::{bvec4a, BVec4A};
#[cfg(all(
target_feature = "simd128",
not(any(feature = "core-simd", feature = "scalar-math"))
))]
pub use wasm32::bvec3a::{bvec3a, BVec3A};
#[cfg(all(
target_feature = "simd128",
not(any(feature = "core-simd", feature = "scalar-math"))
))]
pub use wasm32::bvec4a::{bvec4a, BVec4A};
#[cfg(all(feature = "core-simd", not(feature = "scalar-math")))]
pub use coresimd::bvec3a::{bvec3a, BVec3A};
#[cfg(all(feature = "core-simd", not(feature = "scalar-math")))]
pub use coresimd::bvec4a::{bvec4a, BVec4A};
#[cfg(any(
not(any(
feature = "core-simd",
target_arch = "aarch64",
target_feature = "sse2",
target_feature = "simd128"
)),
feature = "scalar-math"
))]
pub use scalar::bvec3a::{bvec3a, BVec3A};
#[cfg(any(
not(any(
feature = "core-simd",
target_arch = "aarch64",
target_feature = "sse2",
target_feature = "simd128"
)),
feature = "scalar-math"
))]
pub use scalar::bvec4a::{bvec4a, BVec4A};
mod const_test_bvec2 {
const_assert_eq!(1, core::mem::align_of::<super::BVec2>());
const_assert_eq!(2, core::mem::size_of::<super::BVec2>());
}
mod const_test_bvec3 {
const_assert_eq!(1, core::mem::align_of::<super::BVec3>());
const_assert_eq!(3, core::mem::size_of::<super::BVec3>());
}
mod const_test_bvec4 {
const_assert_eq!(1, core::mem::align_of::<super::BVec4>());
const_assert_eq!(4, core::mem::size_of::<super::BVec4>());
}
#[cfg(not(feature = "scalar-math"))]
mod const_test_bvec3a {
const_assert_eq!(16, core::mem::align_of::<super::BVec3A>());
const_assert_eq!(16, core::mem::size_of::<super::BVec3A>());
}
#[cfg(not(feature = "scalar-math"))]
mod const_test_bvec4a {
const_assert_eq!(16, core::mem::align_of::<super::BVec4A>());
const_assert_eq!(16, core::mem::size_of::<super::BVec4A>());
}
+218
View File
@@ -0,0 +1,218 @@
// Generated from vec_mask.rs.tera template. Edit the template, not the generated file.
use core::fmt;
use core::ops::*;
/// Creates a 2-dimensional `bool` vector mask.
#[inline(always)]
#[must_use]
pub const fn bvec2(x: bool, y: bool) -> BVec2 {
BVec2::new(x, y)
}
/// A 2-dimensional `bool` vector mask.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
#[repr(C, align(1))]
pub struct BVec2 {
pub x: bool,
pub y: bool,
}
const MASK: [u32; 2] = [0, 0xff_ff_ff_ff];
impl BVec2 {
/// All false.
pub const FALSE: Self = Self::splat(false);
/// All true.
pub const TRUE: Self = Self::splat(true);
/// Creates a new vector mask.
#[inline(always)]
#[must_use]
pub const fn new(x: bool, y: bool) -> Self {
Self { x, y }
}
/// Creates a vector mask with all elements set to `v`.
#[inline]
#[must_use]
pub const fn splat(v: bool) -> Self {
Self::new(v, v)
}
/// Creates a new vector mask from a bool array.
#[inline]
#[must_use]
pub const fn from_array(a: [bool; 2]) -> Self {
Self::new(a[0], a[1])
}
/// Returns a bitmask with the lowest 2 bits set from the elements of `self`.
///
/// A true element results in a `1` bit and a false element in a `0` bit. Element `x` goes
/// into the first lowest bit, element `y` into the second, etc.
#[inline]
#[must_use]
pub fn bitmask(self) -> u32 {
(self.x as u32) | ((self.y as u32) << 1)
}
/// Returns true if any of the elements are true, false otherwise.
#[inline]
#[must_use]
pub fn any(self) -> bool {
self.x || self.y
}
/// Returns true if all the elements are true, false otherwise.
#[inline]
#[must_use]
pub fn all(self) -> bool {
self.x && self.y
}
/// Tests the value at `index`.
///
/// Panics if `index` is greater than 1.
#[inline]
#[must_use]
pub fn test(&self, index: usize) -> bool {
match index {
0 => self.x,
1 => self.y,
_ => panic!("index out of bounds"),
}
}
/// Sets the element at `index`.
///
/// Panics if `index` is greater than 1.
#[inline]
pub fn set(&mut self, index: usize, value: bool) {
match index {
0 => self.x = value,
1 => self.y = value,
_ => panic!("index out of bounds"),
}
}
#[inline]
#[must_use]
fn into_bool_array(self) -> [bool; 2] {
[self.x, self.y]
}
#[inline]
#[must_use]
fn into_u32_array(self) -> [u32; 2] {
[MASK[self.x as usize], MASK[self.y as usize]]
}
}
impl Default for BVec2 {
#[inline]
fn default() -> Self {
Self::FALSE
}
}
impl BitAnd for BVec2 {
type Output = Self;
#[inline]
fn bitand(self, rhs: Self) -> Self {
Self {
x: self.x & rhs.x,
y: self.y & rhs.y,
}
}
}
impl BitAndAssign for BVec2 {
#[inline]
fn bitand_assign(&mut self, rhs: Self) {
*self = self.bitand(rhs);
}
}
impl BitOr for BVec2 {
type Output = Self;
#[inline]
fn bitor(self, rhs: Self) -> Self {
Self {
x: self.x | rhs.x,
y: self.y | rhs.y,
}
}
}
impl BitOrAssign for BVec2 {
#[inline]
fn bitor_assign(&mut self, rhs: Self) {
*self = self.bitor(rhs);
}
}
impl BitXor for BVec2 {
type Output = Self;
#[inline]
fn bitxor(self, rhs: Self) -> Self {
Self {
x: self.x ^ rhs.x,
y: self.y ^ rhs.y,
}
}
}
impl BitXorAssign for BVec2 {
#[inline]
fn bitxor_assign(&mut self, rhs: Self) {
*self = self.bitxor(rhs);
}
}
impl Not for BVec2 {
type Output = Self;
#[inline]
fn not(self) -> Self {
Self {
x: !self.x,
y: !self.y,
}
}
}
impl fmt::Debug for BVec2 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let arr = self.into_u32_array();
write!(f, "{}({:#x}, {:#x})", stringify!(BVec2), arr[0], arr[1])
}
}
impl fmt::Display for BVec2 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let arr = self.into_bool_array();
write!(f, "[{}, {}]", arr[0], arr[1])
}
}
impl From<[bool; 2]> for BVec2 {
#[inline]
fn from(a: [bool; 2]) -> Self {
Self::from_array(a)
}
}
impl From<BVec2> for [bool; 2] {
#[inline]
fn from(mask: BVec2) -> Self {
mask.into_bool_array()
}
}
impl From<BVec2> for [u32; 2] {
#[inline]
fn from(mask: BVec2) -> Self {
mask.into_u32_array()
}
}
+236
View File
@@ -0,0 +1,236 @@
// Generated from vec_mask.rs.tera template. Edit the template, not the generated file.
use core::fmt;
use core::ops::*;
/// Creates a 3-dimensional `bool` vector mask.
#[inline(always)]
#[must_use]
pub const fn bvec3(x: bool, y: bool, z: bool) -> BVec3 {
BVec3::new(x, y, z)
}
/// A 3-dimensional `bool` vector mask.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
#[repr(C, align(1))]
pub struct BVec3 {
pub x: bool,
pub y: bool,
pub z: bool,
}
const MASK: [u32; 2] = [0, 0xff_ff_ff_ff];
impl BVec3 {
/// All false.
pub const FALSE: Self = Self::splat(false);
/// All true.
pub const TRUE: Self = Self::splat(true);
/// Creates a new vector mask.
#[inline(always)]
#[must_use]
pub const fn new(x: bool, y: bool, z: bool) -> Self {
Self { x, y, z }
}
/// Creates a vector mask with all elements set to `v`.
#[inline]
#[must_use]
pub const fn splat(v: bool) -> Self {
Self::new(v, v, v)
}
/// Creates a new vector mask from a bool array.
#[inline]
#[must_use]
pub const fn from_array(a: [bool; 3]) -> Self {
Self::new(a[0], a[1], a[2])
}
/// Returns a bitmask with the lowest 3 bits set from the elements of `self`.
///
/// A true element results in a `1` bit and a false element in a `0` bit. Element `x` goes
/// into the first lowest bit, element `y` into the second, etc.
#[inline]
#[must_use]
pub fn bitmask(self) -> u32 {
(self.x as u32) | ((self.y as u32) << 1) | ((self.z as u32) << 2)
}
/// Returns true if any of the elements are true, false otherwise.
#[inline]
#[must_use]
pub fn any(self) -> bool {
self.x || self.y || self.z
}
/// Returns true if all the elements are true, false otherwise.
#[inline]
#[must_use]
pub fn all(self) -> bool {
self.x && self.y && self.z
}
/// Tests the value at `index`.
///
/// Panics if `index` is greater than 2.
#[inline]
#[must_use]
pub fn test(&self, index: usize) -> bool {
match index {
0 => self.x,
1 => self.y,
2 => self.z,
_ => panic!("index out of bounds"),
}
}
/// Sets the element at `index`.
///
/// Panics if `index` is greater than 2.
#[inline]
pub fn set(&mut self, index: usize, value: bool) {
match index {
0 => self.x = value,
1 => self.y = value,
2 => self.z = value,
_ => panic!("index out of bounds"),
}
}
#[inline]
#[must_use]
fn into_bool_array(self) -> [bool; 3] {
[self.x, self.y, self.z]
}
#[inline]
#[must_use]
fn into_u32_array(self) -> [u32; 3] {
[
MASK[self.x as usize],
MASK[self.y as usize],
MASK[self.z as usize],
]
}
}
impl Default for BVec3 {
#[inline]
fn default() -> Self {
Self::FALSE
}
}
impl BitAnd for BVec3 {
type Output = Self;
#[inline]
fn bitand(self, rhs: Self) -> Self {
Self {
x: self.x & rhs.x,
y: self.y & rhs.y,
z: self.z & rhs.z,
}
}
}
impl BitAndAssign for BVec3 {
#[inline]
fn bitand_assign(&mut self, rhs: Self) {
*self = self.bitand(rhs);
}
}
impl BitOr for BVec3 {
type Output = Self;
#[inline]
fn bitor(self, rhs: Self) -> Self {
Self {
x: self.x | rhs.x,
y: self.y | rhs.y,
z: self.z | rhs.z,
}
}
}
impl BitOrAssign for BVec3 {
#[inline]
fn bitor_assign(&mut self, rhs: Self) {
*self = self.bitor(rhs);
}
}
impl BitXor for BVec3 {
type Output = Self;
#[inline]
fn bitxor(self, rhs: Self) -> Self {
Self {
x: self.x ^ rhs.x,
y: self.y ^ rhs.y,
z: self.z ^ rhs.z,
}
}
}
impl BitXorAssign for BVec3 {
#[inline]
fn bitxor_assign(&mut self, rhs: Self) {
*self = self.bitxor(rhs);
}
}
impl Not for BVec3 {
type Output = Self;
#[inline]
fn not(self) -> Self {
Self {
x: !self.x,
y: !self.y,
z: !self.z,
}
}
}
impl fmt::Debug for BVec3 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let arr = self.into_u32_array();
write!(
f,
"{}({:#x}, {:#x}, {:#x})",
stringify!(BVec3),
arr[0],
arr[1],
arr[2]
)
}
}
impl fmt::Display for BVec3 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let arr = self.into_bool_array();
write!(f, "[{}, {}, {}]", arr[0], arr[1], arr[2])
}
}
impl From<[bool; 3]> for BVec3 {
#[inline]
fn from(a: [bool; 3]) -> Self {
Self::from_array(a)
}
}
impl From<BVec3> for [bool; 3] {
#[inline]
fn from(mask: BVec3) -> Self {
mask.into_bool_array()
}
}
impl From<BVec3> for [u32; 3] {
#[inline]
fn from(mask: BVec3) -> Self {
mask.into_u32_array()
}
}
+245
View File
@@ -0,0 +1,245 @@
// Generated from vec_mask.rs.tera template. Edit the template, not the generated file.
use core::fmt;
use core::ops::*;
/// Creates a 4-dimensional `bool` vector mask.
#[inline(always)]
#[must_use]
pub const fn bvec4(x: bool, y: bool, z: bool, w: bool) -> BVec4 {
BVec4::new(x, y, z, w)
}
/// A 4-dimensional `bool` vector mask.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
#[repr(C, align(1))]
pub struct BVec4 {
pub x: bool,
pub y: bool,
pub z: bool,
pub w: bool,
}
const MASK: [u32; 2] = [0, 0xff_ff_ff_ff];
impl BVec4 {
/// All false.
pub const FALSE: Self = Self::splat(false);
/// All true.
pub const TRUE: Self = Self::splat(true);
/// Creates a new vector mask.
#[inline(always)]
#[must_use]
pub const fn new(x: bool, y: bool, z: bool, w: bool) -> Self {
Self { x, y, z, w }
}
/// Creates a vector mask with all elements set to `v`.
#[inline]
#[must_use]
pub const fn splat(v: bool) -> Self {
Self::new(v, v, v, v)
}
/// Creates a new vector mask from a bool array.
#[inline]
#[must_use]
pub const fn from_array(a: [bool; 4]) -> Self {
Self::new(a[0], a[1], a[2], a[3])
}
/// Returns a bitmask with the lowest 4 bits set from the elements of `self`.
///
/// A true element results in a `1` bit and a false element in a `0` bit. Element `x` goes
/// into the first lowest bit, element `y` into the second, etc.
#[inline]
#[must_use]
pub fn bitmask(self) -> u32 {
(self.x as u32) | ((self.y as u32) << 1) | ((self.z as u32) << 2) | ((self.w as u32) << 3)
}
/// Returns true if any of the elements are true, false otherwise.
#[inline]
#[must_use]
pub fn any(self) -> bool {
self.x || self.y || self.z || self.w
}
/// Returns true if all the elements are true, false otherwise.
#[inline]
#[must_use]
pub fn all(self) -> bool {
self.x && self.y && self.z && self.w
}
/// Tests the value at `index`.
///
/// Panics if `index` is greater than 3.
#[inline]
#[must_use]
pub fn test(&self, index: usize) -> bool {
match index {
0 => self.x,
1 => self.y,
2 => self.z,
3 => self.w,
_ => panic!("index out of bounds"),
}
}
/// Sets the element at `index`.
///
/// Panics if `index` is greater than 3.
#[inline]
pub fn set(&mut self, index: usize, value: bool) {
match index {
0 => self.x = value,
1 => self.y = value,
2 => self.z = value,
3 => self.w = value,
_ => panic!("index out of bounds"),
}
}
#[inline]
#[must_use]
fn into_bool_array(self) -> [bool; 4] {
[self.x, self.y, self.z, self.w]
}
#[inline]
#[must_use]
fn into_u32_array(self) -> [u32; 4] {
[
MASK[self.x as usize],
MASK[self.y as usize],
MASK[self.z as usize],
MASK[self.w as usize],
]
}
}
impl Default for BVec4 {
#[inline]
fn default() -> Self {
Self::FALSE
}
}
impl BitAnd for BVec4 {
type Output = Self;
#[inline]
fn bitand(self, rhs: Self) -> Self {
Self {
x: self.x & rhs.x,
y: self.y & rhs.y,
z: self.z & rhs.z,
w: self.w & rhs.w,
}
}
}
impl BitAndAssign for BVec4 {
#[inline]
fn bitand_assign(&mut self, rhs: Self) {
*self = self.bitand(rhs);
}
}
impl BitOr for BVec4 {
type Output = Self;
#[inline]
fn bitor(self, rhs: Self) -> Self {
Self {
x: self.x | rhs.x,
y: self.y | rhs.y,
z: self.z | rhs.z,
w: self.w | rhs.w,
}
}
}
impl BitOrAssign for BVec4 {
#[inline]
fn bitor_assign(&mut self, rhs: Self) {
*self = self.bitor(rhs);
}
}
impl BitXor for BVec4 {
type Output = Self;
#[inline]
fn bitxor(self, rhs: Self) -> Self {
Self {
x: self.x ^ rhs.x,
y: self.y ^ rhs.y,
z: self.z ^ rhs.z,
w: self.w ^ rhs.w,
}
}
}
impl BitXorAssign for BVec4 {
#[inline]
fn bitxor_assign(&mut self, rhs: Self) {
*self = self.bitxor(rhs);
}
}
impl Not for BVec4 {
type Output = Self;
#[inline]
fn not(self) -> Self {
Self {
x: !self.x,
y: !self.y,
z: !self.z,
w: !self.w,
}
}
}
impl fmt::Debug for BVec4 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let arr = self.into_u32_array();
write!(
f,
"{}({:#x}, {:#x}, {:#x}, {:#x})",
stringify!(BVec4),
arr[0],
arr[1],
arr[2],
arr[3]
)
}
}
impl fmt::Display for BVec4 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let arr = self.into_bool_array();
write!(f, "[{}, {}, {}, {}]", arr[0], arr[1], arr[2], arr[3])
}
}
impl From<[bool; 4]> for BVec4 {
#[inline]
fn from(a: [bool; 4]) -> Self {
Self::from_array(a)
}
}
impl From<BVec4> for [bool; 4] {
#[inline]
fn from(mask: BVec4) -> Self {
mask.into_bool_array()
}
}
impl From<BVec4> for [u32; 4] {
#[inline]
fn from(mask: BVec4) -> Self {
mask.into_u32_array()
}
}
+2
View File
@@ -0,0 +1,2 @@
pub mod bvec3a;
pub mod bvec4a;
+246
View File
@@ -0,0 +1,246 @@
// Generated from vec_mask.rs.tera template. Edit the template, not the generated file.
use core::fmt;
use core::ops::*;
use core::simd::*;
#[repr(C)]
union UnionCast {
a: [u32; 4],
v: BVec3A,
}
/// Creates a 3-dimensional `bool` vector mask.
#[inline(always)]
#[must_use]
pub const fn bvec3a(x: bool, y: bool, z: bool) -> BVec3A {
BVec3A::new(x, y, z)
}
/// A 3-dimensional SIMD vector mask.
///
/// This type is 16 byte aligned.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct BVec3A(pub(crate) mask32x4);
const MASK: [u32; 2] = [0, 0xff_ff_ff_ff];
impl BVec3A {
/// All false.
pub const FALSE: Self = Self::splat(false);
/// All true.
pub const TRUE: Self = Self::splat(true);
/// Creates a new vector mask.
#[inline(always)]
#[must_use]
pub const fn new(x: bool, y: bool, z: bool) -> Self {
unsafe {
UnionCast {
a: [MASK[x as usize], MASK[y as usize], MASK[z as usize], 0],
}
.v
}
}
/// Creates a vector mask with all elements set to `v`.
#[inline]
#[must_use]
pub const fn splat(v: bool) -> Self {
Self::new(v, v, v)
}
/// Creates a new vector mask from a bool array.
#[inline]
#[must_use]
pub const fn from_array(a: [bool; 3]) -> Self {
Self::new(a[0], a[1], a[2])
}
/// Returns a bitmask with the lowest 3 bits set from the elements of `self`.
///
/// A true element results in a `1` bit and a false element in a `0` bit. Element `x` goes
/// into the first lowest bit, element `y` into the second, etc.
#[inline]
#[must_use]
pub fn bitmask(self) -> u32 {
(self.0.to_bitmask() & 0x7) as u32
}
/// Returns true if any of the elements are true, false otherwise.
#[inline]
#[must_use]
pub fn any(self) -> bool {
self.bitmask() != 0
}
/// Returns true if all the elements are true, false otherwise.
#[inline]
#[must_use]
pub fn all(self) -> bool {
self.bitmask() == 0x7
}
/// Tests the value at `index`.
///
/// Panics if `index` is greater than 2.
#[inline]
#[must_use]
pub fn test(&self, index: usize) -> bool {
self.0.test(index)
}
/// Sets the element at `index`.
///
/// Panics if `index` is greater than 2.
#[inline]
pub fn set(&mut self, index: usize, value: bool) {
self.0.set(index, value)
}
#[inline]
#[must_use]
fn into_bool_array(self) -> [bool; 3] {
let bitmask = self.bitmask();
[(bitmask & 1) != 0, (bitmask & 2) != 0, (bitmask & 4) != 0]
}
#[inline]
#[must_use]
fn into_u32_array(self) -> [u32; 3] {
let bitmask = self.bitmask();
[
MASK[(bitmask & 1) as usize],
MASK[((bitmask >> 1) & 1) as usize],
MASK[((bitmask >> 2) & 1) as usize],
]
}
}
impl Default for BVec3A {
#[inline]
fn default() -> Self {
Self::FALSE
}
}
impl PartialEq for BVec3A {
#[inline]
fn eq(&self, rhs: &Self) -> bool {
self.bitmask().eq(&rhs.bitmask())
}
}
impl Eq for BVec3A {}
impl core::hash::Hash for BVec3A {
#[inline]
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.bitmask().hash(state);
}
}
impl BitAnd for BVec3A {
type Output = Self;
#[inline]
fn bitand(self, rhs: Self) -> Self {
Self(self.0 & rhs.0)
}
}
impl BitAndAssign for BVec3A {
#[inline]
fn bitand_assign(&mut self, rhs: Self) {
*self = self.bitand(rhs);
}
}
impl BitOr for BVec3A {
type Output = Self;
#[inline]
fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}
impl BitOrAssign for BVec3A {
#[inline]
fn bitor_assign(&mut self, rhs: Self) {
*self = self.bitor(rhs);
}
}
impl BitXor for BVec3A {
type Output = Self;
#[inline]
fn bitxor(self, rhs: Self) -> Self {
Self(self.0 ^ rhs.0)
}
}
impl BitXorAssign for BVec3A {
#[inline]
fn bitxor_assign(&mut self, rhs: Self) {
*self = self.bitxor(rhs);
}
}
impl Not for BVec3A {
type Output = Self;
#[inline]
fn not(self) -> Self {
Self(!self.0)
}
}
impl From<BVec3A> for mask32x4 {
#[inline]
fn from(t: BVec3A) -> Self {
t.0
}
}
impl fmt::Debug for BVec3A {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let arr = self.into_u32_array();
write!(
f,
"{}({:#x}, {:#x}, {:#x})",
stringify!(BVec3A),
arr[0],
arr[1],
arr[2]
)
}
}
impl fmt::Display for BVec3A {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let arr = self.into_bool_array();
write!(f, "[{}, {}, {}]", arr[0], arr[1], arr[2])
}
}
impl From<[bool; 3]> for BVec3A {
#[inline]
fn from(a: [bool; 3]) -> Self {
Self::from_array(a)
}
}
impl From<BVec3A> for [bool; 3] {
#[inline]
fn from(mask: BVec3A) -> Self {
mask.into_bool_array()
}
}
impl From<BVec3A> for [u32; 3] {
#[inline]
fn from(mask: BVec3A) -> Self {
mask.into_u32_array()
}
}
+258
View File
@@ -0,0 +1,258 @@
// Generated from vec_mask.rs.tera template. Edit the template, not the generated file.
use core::fmt;
use core::ops::*;
use core::simd::*;
#[repr(C)]
union UnionCast {
a: [u32; 4],
v: BVec4A,
}
/// Creates a 4-dimensional `bool` vector mask.
#[inline(always)]
#[must_use]
pub const fn bvec4a(x: bool, y: bool, z: bool, w: bool) -> BVec4A {
BVec4A::new(x, y, z, w)
}
/// A 4-dimensional SIMD vector mask.
///
/// This type is 16 byte aligned.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct BVec4A(pub(crate) mask32x4);
const MASK: [u32; 2] = [0, 0xff_ff_ff_ff];
impl BVec4A {
/// All false.
pub const FALSE: Self = Self::splat(false);
/// All true.
pub const TRUE: Self = Self::splat(true);
/// Creates a new vector mask.
#[inline(always)]
#[must_use]
pub const fn new(x: bool, y: bool, z: bool, w: bool) -> Self {
unsafe {
UnionCast {
a: [
MASK[x as usize],
MASK[y as usize],
MASK[z as usize],
MASK[w as usize],
],
}
.v
}
}
/// Creates a vector mask with all elements set to `v`.
#[inline]
#[must_use]
pub const fn splat(v: bool) -> Self {
Self::new(v, v, v, v)
}
/// Creates a new vector mask from a bool array.
#[inline]
#[must_use]
pub const fn from_array(a: [bool; 4]) -> Self {
Self::new(a[0], a[1], a[2], a[3])
}
/// Returns a bitmask with the lowest 4 bits set from the elements of `self`.
///
/// A true element results in a `1` bit and a false element in a `0` bit. Element `x` goes
/// into the first lowest bit, element `y` into the second, etc.
#[inline]
#[must_use]
pub fn bitmask(self) -> u32 {
self.0.to_bitmask() as u32
}
/// Returns true if any of the elements are true, false otherwise.
#[inline]
#[must_use]
pub fn any(self) -> bool {
self.bitmask() != 0
}
/// Returns true if all the elements are true, false otherwise.
#[inline]
#[must_use]
pub fn all(self) -> bool {
self.bitmask() == 0xf
}
/// Tests the value at `index`.
///
/// Panics if `index` is greater than 3.
#[inline]
#[must_use]
pub fn test(&self, index: usize) -> bool {
self.0.test(index)
}
/// Sets the element at `index`.
///
/// Panics if `index` is greater than 3.
#[inline]
pub fn set(&mut self, index: usize, value: bool) {
self.0.set(index, value)
}
#[inline]
#[must_use]
fn into_bool_array(self) -> [bool; 4] {
let bitmask = self.bitmask();
[
(bitmask & 1) != 0,
(bitmask & 2) != 0,
(bitmask & 4) != 0,
(bitmask & 8) != 0,
]
}
#[inline]
#[must_use]
fn into_u32_array(self) -> [u32; 4] {
let bitmask = self.bitmask();
[
MASK[(bitmask & 1) as usize],
MASK[((bitmask >> 1) & 1) as usize],
MASK[((bitmask >> 2) & 1) as usize],
MASK[((bitmask >> 3) & 1) as usize],
]
}
}
impl Default for BVec4A {
#[inline]
fn default() -> Self {
Self::FALSE
}
}
impl PartialEq for BVec4A {
#[inline]
fn eq(&self, rhs: &Self) -> bool {
self.bitmask().eq(&rhs.bitmask())
}
}
impl Eq for BVec4A {}
impl core::hash::Hash for BVec4A {
#[inline]
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.bitmask().hash(state);
}
}
impl BitAnd for BVec4A {
type Output = Self;
#[inline]
fn bitand(self, rhs: Self) -> Self {
Self(self.0 & rhs.0)
}
}
impl BitAndAssign for BVec4A {
#[inline]
fn bitand_assign(&mut self, rhs: Self) {
*self = self.bitand(rhs);
}
}
impl BitOr for BVec4A {
type Output = Self;
#[inline]
fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}
impl BitOrAssign for BVec4A {
#[inline]
fn bitor_assign(&mut self, rhs: Self) {
*self = self.bitor(rhs);
}
}
impl BitXor for BVec4A {
type Output = Self;
#[inline]
fn bitxor(self, rhs: Self) -> Self {
Self(self.0 ^ rhs.0)
}
}
impl BitXorAssign for BVec4A {
#[inline]
fn bitxor_assign(&mut self, rhs: Self) {
*self = self.bitxor(rhs);
}
}
impl Not for BVec4A {
type Output = Self;
#[inline]
fn not(self) -> Self {
Self(!self.0)
}
}
impl From<BVec4A> for mask32x4 {
#[inline]
fn from(t: BVec4A) -> Self {
t.0
}
}
impl fmt::Debug for BVec4A {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let arr = self.into_u32_array();
write!(
f,
"{}({:#x}, {:#x}, {:#x}, {:#x})",
stringify!(BVec4A),
arr[0],
arr[1],
arr[2],
arr[3]
)
}
}
impl fmt::Display for BVec4A {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let arr = self.into_bool_array();
write!(f, "[{}, {}, {}, {}]", arr[0], arr[1], arr[2], arr[3])
}
}
impl From<[bool; 4]> for BVec4A {
#[inline]
fn from(a: [bool; 4]) -> Self {
Self::from_array(a)
}
}
impl From<BVec4A> for [bool; 4] {
#[inline]
fn from(mask: BVec4A) -> Self {
mask.into_bool_array()
}
}
impl From<BVec4A> for [u32; 4] {
#[inline]
fn from(mask: BVec4A) -> Self {
mask.into_u32_array()
}
}
+2
View File
@@ -0,0 +1,2 @@
pub mod bvec3a;
pub mod bvec4a;
+265
View File
@@ -0,0 +1,265 @@
// Generated from vec_mask.rs.tera template. Edit the template, not the generated file.
use core::fmt;
use core::ops::*;
use core::arch::aarch64::*;
#[repr(C)]
union UnionCast {
a: [u32; 4],
v: BVec3A,
}
/// Creates a 3-dimensional `bool` vector mask.
#[inline(always)]
#[must_use]
pub const fn bvec3a(x: bool, y: bool, z: bool) -> BVec3A {
BVec3A::new(x, y, z)
}
/// A 3-dimensional SIMD vector mask.
///
/// This type is 16 byte aligned.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct BVec3A(pub(crate) uint32x4_t);
const MASK: [u32; 2] = [0, 0xff_ff_ff_ff];
impl BVec3A {
/// All false.
pub const FALSE: Self = Self::splat(false);
/// All true.
pub const TRUE: Self = Self::splat(true);
/// Creates a new vector mask.
#[inline(always)]
#[must_use]
pub const fn new(x: bool, y: bool, z: bool) -> Self {
unsafe {
UnionCast {
a: [MASK[x as usize], MASK[y as usize], MASK[z as usize], 0],
}
.v
}
}
/// Creates a vector mask with all elements set to `v`.
#[inline]
#[must_use]
pub const fn splat(v: bool) -> Self {
Self::new(v, v, v)
}
/// Creates a new vector mask from a bool array.
#[inline]
#[must_use]
pub const fn from_array(a: [bool; 3]) -> Self {
Self::new(a[0], a[1], a[2])
}
/// Returns a bitmask with the lowest 3 bits set from the elements of `self`.
///
/// A true element results in a `1` bit and a false element in a `0` bit. Element `x` goes
/// into the first lowest bit, element `y` into the second, etc.
#[inline]
#[must_use]
pub fn bitmask(self) -> u32 {
let movemask = unsafe {
let mma = vandq_u32(self.0, vld1q_u32([1, 2, 4, 8].as_ptr())); // [0 1 2 3]
let mmb = vextq_u32(mma, mma, 2); // [2 3 0 1]
let mmc = vorrq_u32(mma, mmb); // [0+2 1+3 0+2 1+3]
let mmd = vextq_u32(mmc, mmc, 3); // [1+3 0+2 1+3 0+2]
let mme = vorrq_u32(mmc, mmd); // [0+1+2+3 ...]
vgetq_lane_u32(mme, 0)
};
movemask & 0x7
}
/// Returns true if any of the elements are true, false otherwise.
#[inline]
#[must_use]
pub fn any(self) -> bool {
self.bitmask() != 0
}
/// Returns true if all the elements are true, false otherwise.
#[inline]
#[must_use]
pub fn all(self) -> bool {
self.bitmask() == 0x7
}
/// Tests the value at `index`.
///
/// Panics if `index` is greater than 2.
#[inline]
#[must_use]
pub fn test(&self, index: usize) -> bool {
match index {
0 => (self.bitmask() & (1 << 0)) != 0,
1 => (self.bitmask() & (1 << 1)) != 0,
2 => (self.bitmask() & (1 << 2)) != 0,
_ => panic!("index out of bounds"),
}
}
/// Sets the element at `index`.
///
/// Panics if `index` is greater than 2.
#[inline]
pub fn set(&mut self, index: usize, value: bool) {
self.0 = match index {
0 => unsafe { vsetq_lane_u32(MASK[value as usize], self.0, 0) },
1 => unsafe { vsetq_lane_u32(MASK[value as usize], self.0, 1) },
2 => unsafe { vsetq_lane_u32(MASK[value as usize], self.0, 2) },
_ => panic!("index out of bounds"),
}
}
#[inline]
#[must_use]
fn into_bool_array(self) -> [bool; 3] {
let bitmask = self.bitmask();
[(bitmask & 1) != 0, (bitmask & 2) != 0, (bitmask & 4) != 0]
}
#[inline]
#[must_use]
fn into_u32_array(self) -> [u32; 3] {
let bitmask = self.bitmask();
[
MASK[(bitmask & 1) as usize],
MASK[((bitmask >> 1) & 1) as usize],
MASK[((bitmask >> 2) & 1) as usize],
]
}
}
impl Default for BVec3A {
#[inline]
fn default() -> Self {
Self::FALSE
}
}
impl PartialEq for BVec3A {
#[inline]
fn eq(&self, rhs: &Self) -> bool {
self.bitmask().eq(&rhs.bitmask())
}
}
impl Eq for BVec3A {}
impl core::hash::Hash for BVec3A {
#[inline]
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.bitmask().hash(state);
}
}
impl BitAnd for BVec3A {
type Output = Self;
#[inline]
fn bitand(self, rhs: Self) -> Self {
Self(unsafe { vandq_u32(self.0, rhs.0) })
}
}
impl BitAndAssign for BVec3A {
#[inline]
fn bitand_assign(&mut self, rhs: Self) {
*self = self.bitand(rhs);
}
}
impl BitOr for BVec3A {
type Output = Self;
#[inline]
fn bitor(self, rhs: Self) -> Self {
Self(unsafe { vorrq_u32(self.0, rhs.0) })
}
}
impl BitOrAssign for BVec3A {
#[inline]
fn bitor_assign(&mut self, rhs: Self) {
*self = self.bitor(rhs);
}
}
impl BitXor for BVec3A {
type Output = Self;
#[inline]
fn bitxor(self, rhs: Self) -> Self {
Self(unsafe { veorq_u32(self.0, rhs.0) })
}
}
impl BitXorAssign for BVec3A {
#[inline]
fn bitxor_assign(&mut self, rhs: Self) {
*self = self.bitxor(rhs);
}
}
impl Not for BVec3A {
type Output = Self;
#[inline]
fn not(self) -> Self {
Self(unsafe { vmvnq_u32(self.0) })
}
}
impl From<BVec3A> for uint32x4_t {
#[inline]
fn from(t: BVec3A) -> Self {
t.0
}
}
impl fmt::Debug for BVec3A {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let arr = self.into_u32_array();
write!(
f,
"{}({:#x}, {:#x}, {:#x})",
stringify!(BVec3A),
arr[0],
arr[1],
arr[2]
)
}
}
impl fmt::Display for BVec3A {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let arr = self.into_bool_array();
write!(f, "[{}, {}, {}]", arr[0], arr[1], arr[2])
}
}
impl From<[bool; 3]> for BVec3A {
#[inline]
fn from(a: [bool; 3]) -> Self {
Self::from_array(a)
}
}
impl From<BVec3A> for [bool; 3] {
#[inline]
fn from(mask: BVec3A) -> Self {
mask.into_bool_array()
}
}
impl From<BVec3A> for [u32; 3] {
#[inline]
fn from(mask: BVec3A) -> Self {
mask.into_u32_array()
}
}
+277
View File
@@ -0,0 +1,277 @@
// Generated from vec_mask.rs.tera template. Edit the template, not the generated file.
use core::fmt;
use core::ops::*;
use core::arch::aarch64::*;
#[repr(C)]
union UnionCast {
a: [u32; 4],
v: BVec4A,
}
/// Creates a 4-dimensional `bool` vector mask.
#[inline(always)]
#[must_use]
pub const fn bvec4a(x: bool, y: bool, z: bool, w: bool) -> BVec4A {
BVec4A::new(x, y, z, w)
}
/// A 4-dimensional SIMD vector mask.
///
/// This type is 16 byte aligned.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct BVec4A(pub(crate) uint32x4_t);
const MASK: [u32; 2] = [0, 0xff_ff_ff_ff];
impl BVec4A {
/// All false.
pub const FALSE: Self = Self::splat(false);
/// All true.
pub const TRUE: Self = Self::splat(true);
/// Creates a new vector mask.
#[inline(always)]
#[must_use]
pub const fn new(x: bool, y: bool, z: bool, w: bool) -> Self {
unsafe {
UnionCast {
a: [
MASK[x as usize],
MASK[y as usize],
MASK[z as usize],
MASK[w as usize],
],
}
.v
}
}
/// Creates a vector mask with all elements set to `v`.
#[inline]
#[must_use]
pub const fn splat(v: bool) -> Self {
Self::new(v, v, v, v)
}
/// Creates a new vector mask from a bool array.
#[inline]
#[must_use]
pub const fn from_array(a: [bool; 4]) -> Self {
Self::new(a[0], a[1], a[2], a[3])
}
/// Returns a bitmask with the lowest 4 bits set from the elements of `self`.
///
/// A true element results in a `1` bit and a false element in a `0` bit. Element `x` goes
/// into the first lowest bit, element `y` into the second, etc.
#[inline]
#[must_use]
pub fn bitmask(self) -> u32 {
unsafe {
let mma = vandq_u32(self.0, vld1q_u32([1, 2, 4, 8].as_ptr())); // [0 1 2 3]
let mmb = vextq_u32(mma, mma, 2); // [2 3 0 1]
let mmc = vorrq_u32(mma, mmb); // [0+2 1+3 0+2 1+3]
let mmd = vextq_u32(mmc, mmc, 3); // [1+3 0+2 1+3 0+2]
let mme = vorrq_u32(mmc, mmd); // [0+1+2+3 ...]
vgetq_lane_u32(mme, 0)
}
}
/// Returns true if any of the elements are true, false otherwise.
#[inline]
#[must_use]
pub fn any(self) -> bool {
self.bitmask() != 0
}
/// Returns true if all the elements are true, false otherwise.
#[inline]
#[must_use]
pub fn all(self) -> bool {
self.bitmask() == 0xf
}
/// Tests the value at `index`.
///
/// Panics if `index` is greater than 3.
#[inline]
#[must_use]
pub fn test(&self, index: usize) -> bool {
match index {
0 => (self.bitmask() & (1 << 0)) != 0,
1 => (self.bitmask() & (1 << 1)) != 0,
2 => (self.bitmask() & (1 << 2)) != 0,
3 => (self.bitmask() & (1 << 3)) != 0,
_ => panic!("index out of bounds"),
}
}
/// Sets the element at `index`.
///
/// Panics if `index` is greater than 3.
#[inline]
pub fn set(&mut self, index: usize, value: bool) {
self.0 = match index {
0 => unsafe { vsetq_lane_u32(MASK[value as usize], self.0, 0) },
1 => unsafe { vsetq_lane_u32(MASK[value as usize], self.0, 1) },
2 => unsafe { vsetq_lane_u32(MASK[value as usize], self.0, 2) },
3 => unsafe { vsetq_lane_u32(MASK[value as usize], self.0, 3) },
_ => panic!("index out of bounds"),
}
}
#[inline]
#[must_use]
fn into_bool_array(self) -> [bool; 4] {
let bitmask = self.bitmask();
[
(bitmask & 1) != 0,
(bitmask & 2) != 0,
(bitmask & 4) != 0,
(bitmask & 8) != 0,
]
}
#[inline]
#[must_use]
fn into_u32_array(self) -> [u32; 4] {
let bitmask = self.bitmask();
[
MASK[(bitmask & 1) as usize],
MASK[((bitmask >> 1) & 1) as usize],
MASK[((bitmask >> 2) & 1) as usize],
MASK[((bitmask >> 3) & 1) as usize],
]
}
}
impl Default for BVec4A {
#[inline]
fn default() -> Self {
Self::FALSE
}
}
impl PartialEq for BVec4A {
#[inline]
fn eq(&self, rhs: &Self) -> bool {
self.bitmask().eq(&rhs.bitmask())
}
}
impl Eq for BVec4A {}
impl core::hash::Hash for BVec4A {
#[inline]
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.bitmask().hash(state);
}
}
impl BitAnd for BVec4A {
type Output = Self;
#[inline]
fn bitand(self, rhs: Self) -> Self {
Self(unsafe { vandq_u32(self.0, rhs.0) })
}
}
impl BitAndAssign for BVec4A {
#[inline]
fn bitand_assign(&mut self, rhs: Self) {
*self = self.bitand(rhs);
}
}
impl BitOr for BVec4A {
type Output = Self;
#[inline]
fn bitor(self, rhs: Self) -> Self {
Self(unsafe { vorrq_u32(self.0, rhs.0) })
}
}
impl BitOrAssign for BVec4A {
#[inline]
fn bitor_assign(&mut self, rhs: Self) {
*self = self.bitor(rhs);
}
}
impl BitXor for BVec4A {
type Output = Self;
#[inline]
fn bitxor(self, rhs: Self) -> Self {
Self(unsafe { veorq_u32(self.0, rhs.0) })
}
}
impl BitXorAssign for BVec4A {
#[inline]
fn bitxor_assign(&mut self, rhs: Self) {
*self = self.bitxor(rhs);
}
}
impl Not for BVec4A {
type Output = Self;
#[inline]
fn not(self) -> Self {
Self(unsafe { vmvnq_u32(self.0) })
}
}
impl From<BVec4A> for uint32x4_t {
#[inline]
fn from(t: BVec4A) -> Self {
t.0
}
}
impl fmt::Debug for BVec4A {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let arr = self.into_u32_array();
write!(
f,
"{}({:#x}, {:#x}, {:#x}, {:#x})",
stringify!(BVec4A),
arr[0],
arr[1],
arr[2],
arr[3]
)
}
}
impl fmt::Display for BVec4A {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let arr = self.into_bool_array();
write!(f, "[{}, {}, {}, {}]", arr[0], arr[1], arr[2], arr[3])
}
}
impl From<[bool; 4]> for BVec4A {
#[inline]
fn from(a: [bool; 4]) -> Self {
Self::from_array(a)
}
}
impl From<BVec4A> for [bool; 4] {
#[inline]
fn from(mask: BVec4A) -> Self {
mask.into_bool_array()
}
}
impl From<BVec4A> for [u32; 4] {
#[inline]
fn from(mask: BVec4A) -> Self {
mask.into_u32_array()
}
}
+2
View File
@@ -0,0 +1,2 @@
pub mod bvec3a;
pub mod bvec4a;
+240
View File
@@ -0,0 +1,240 @@
// Generated from vec_mask.rs.tera template. Edit the template, not the generated file.
use core::fmt;
use core::ops::*;
/// Creates a 3-dimensional `bool` vector mask.
#[inline(always)]
#[must_use]
pub const fn bvec3a(x: bool, y: bool, z: bool) -> BVec3A {
BVec3A::new(x, y, z)
}
/// A 3-dimensional `u32` vector mask.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
#[repr(C, align(16))]
pub struct BVec3A {
pub x: u32,
pub y: u32,
pub z: u32,
}
const MASK: [u32; 2] = [0, 0xff_ff_ff_ff];
impl BVec3A {
/// All false.
pub const FALSE: Self = Self::splat(false);
/// All true.
pub const TRUE: Self = Self::splat(true);
/// Creates a new vector mask.
#[inline(always)]
#[must_use]
pub const fn new(x: bool, y: bool, z: bool) -> Self {
Self {
x: MASK[x as usize],
y: MASK[y as usize],
z: MASK[z as usize],
}
}
/// Creates a vector mask with all elements set to `v`.
#[inline]
#[must_use]
pub const fn splat(v: bool) -> Self {
Self::new(v, v, v)
}
/// Creates a new vector mask from a bool array.
#[inline]
#[must_use]
pub const fn from_array(a: [bool; 3]) -> Self {
Self::new(a[0], a[1], a[2])
}
/// Returns a bitmask with the lowest 3 bits set from the elements of `self`.
///
/// A true element results in a `1` bit and a false element in a `0` bit. Element `x` goes
/// into the first lowest bit, element `y` into the second, etc.
#[inline]
#[must_use]
pub fn bitmask(self) -> u32 {
(self.x & 0x1) | ((self.y & 0x1) << 1) | ((self.z & 0x1) << 2)
}
/// Returns true if any of the elements are true, false otherwise.
#[inline]
#[must_use]
pub fn any(self) -> bool {
((self.x | self.y | self.z) & 0x1) != 0
}
/// Returns true if all the elements are true, false otherwise.
#[inline]
#[must_use]
pub fn all(self) -> bool {
((self.x & self.y & self.z) & 0x1) != 0
}
/// Tests the value at `index`.
///
/// Panics if `index` is greater than 2.
#[inline]
#[must_use]
pub fn test(&self, index: usize) -> bool {
match index {
0 => (self.x & 0x1) != 0,
1 => (self.y & 0x1) != 0,
2 => (self.z & 0x1) != 0,
_ => panic!("index out of bounds"),
}
}
/// Sets the element at `index`.
///
/// Panics if `index` is greater than 2.
#[inline]
pub fn set(&mut self, index: usize, value: bool) {
match index {
0 => self.x = MASK[value as usize],
1 => self.y = MASK[value as usize],
2 => self.z = MASK[value as usize],
_ => panic!("index out of bounds"),
}
}
#[inline]
#[must_use]
fn into_bool_array(self) -> [bool; 3] {
[
(self.x & 0x1) != 0,
(self.y & 0x1) != 0,
(self.z & 0x1) != 0,
]
}
#[inline]
#[must_use]
fn into_u32_array(self) -> [u32; 3] {
[self.x, self.y, self.z]
}
}
impl Default for BVec3A {
#[inline]
fn default() -> Self {
Self::FALSE
}
}
impl BitAnd for BVec3A {
type Output = Self;
#[inline]
fn bitand(self, rhs: Self) -> Self {
Self {
x: self.x & rhs.x,
y: self.y & rhs.y,
z: self.z & rhs.z,
}
}
}
impl BitAndAssign for BVec3A {
#[inline]
fn bitand_assign(&mut self, rhs: Self) {
*self = self.bitand(rhs);
}
}
impl BitOr for BVec3A {
type Output = Self;
#[inline]
fn bitor(self, rhs: Self) -> Self {
Self {
x: self.x | rhs.x,
y: self.y | rhs.y,
z: self.z | rhs.z,
}
}
}
impl BitOrAssign for BVec3A {
#[inline]
fn bitor_assign(&mut self, rhs: Self) {
*self = self.bitor(rhs);
}
}
impl BitXor for BVec3A {
type Output = Self;
#[inline]
fn bitxor(self, rhs: Self) -> Self {
Self {
x: self.x ^ rhs.x,
y: self.y ^ rhs.y,
z: self.z ^ rhs.z,
}
}
}
impl BitXorAssign for BVec3A {
#[inline]
fn bitxor_assign(&mut self, rhs: Self) {
*self = self.bitxor(rhs);
}
}
impl Not for BVec3A {
type Output = Self;
#[inline]
fn not(self) -> Self {
Self {
x: !self.x,
y: !self.y,
z: !self.z,
}
}
}
impl fmt::Debug for BVec3A {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let arr = self.into_u32_array();
write!(
f,
"{}({:#x}, {:#x}, {:#x})",
stringify!(BVec3A),
arr[0],
arr[1],
arr[2]
)
}
}
impl fmt::Display for BVec3A {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let arr = self.into_bool_array();
write!(f, "[{}, {}, {}]", arr[0], arr[1], arr[2])
}
}
impl From<[bool; 3]> for BVec3A {
#[inline]
fn from(a: [bool; 3]) -> Self {
Self::from_array(a)
}
}
impl From<BVec3A> for [bool; 3] {
#[inline]
fn from(mask: BVec3A) -> Self {
mask.into_bool_array()
}
}
impl From<BVec3A> for [u32; 3] {
#[inline]
fn from(mask: BVec3A) -> Self {
mask.into_u32_array()
}
}
+250
View File
@@ -0,0 +1,250 @@
// Generated from vec_mask.rs.tera template. Edit the template, not the generated file.
use core::fmt;
use core::ops::*;
/// Creates a 4-dimensional `bool` vector mask.
#[inline(always)]
#[must_use]
pub const fn bvec4a(x: bool, y: bool, z: bool, w: bool) -> BVec4A {
BVec4A::new(x, y, z, w)
}
/// A 4-dimensional `u32` vector mask.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
#[repr(C, align(16))]
pub struct BVec4A {
pub x: u32,
pub y: u32,
pub z: u32,
pub w: u32,
}
const MASK: [u32; 2] = [0, 0xff_ff_ff_ff];
impl BVec4A {
/// All false.
pub const FALSE: Self = Self::splat(false);
/// All true.
pub const TRUE: Self = Self::splat(true);
/// Creates a new vector mask.
#[inline(always)]
#[must_use]
pub const fn new(x: bool, y: bool, z: bool, w: bool) -> Self {
Self {
x: MASK[x as usize],
y: MASK[y as usize],
z: MASK[z as usize],
w: MASK[w as usize],
}
}
/// Creates a vector mask with all elements set to `v`.
#[inline]
#[must_use]
pub const fn splat(v: bool) -> Self {
Self::new(v, v, v, v)
}
/// Creates a new vector mask from a bool array.
#[inline]
#[must_use]
pub const fn from_array(a: [bool; 4]) -> Self {
Self::new(a[0], a[1], a[2], a[3])
}
/// Returns a bitmask with the lowest 4 bits set from the elements of `self`.
///
/// A true element results in a `1` bit and a false element in a `0` bit. Element `x` goes
/// into the first lowest bit, element `y` into the second, etc.
#[inline]
#[must_use]
pub fn bitmask(self) -> u32 {
(self.x & 0x1) | ((self.y & 0x1) << 1) | ((self.z & 0x1) << 2) | ((self.w & 0x1) << 3)
}
/// Returns true if any of the elements are true, false otherwise.
#[inline]
#[must_use]
pub fn any(self) -> bool {
((self.x | self.y | self.z | self.w) & 0x1) != 0
}
/// Returns true if all the elements are true, false otherwise.
#[inline]
#[must_use]
pub fn all(self) -> bool {
((self.x & self.y & self.z & self.w) & 0x1) != 0
}
/// Tests the value at `index`.
///
/// Panics if `index` is greater than 3.
#[inline]
#[must_use]
pub fn test(&self, index: usize) -> bool {
match index {
0 => (self.x & 0x1) != 0,
1 => (self.y & 0x1) != 0,
2 => (self.z & 0x1) != 0,
3 => (self.w & 0x1) != 0,
_ => panic!("index out of bounds"),
}
}
/// Sets the element at `index`.
///
/// Panics if `index` is greater than 3.
#[inline]
pub fn set(&mut self, index: usize, value: bool) {
match index {
0 => self.x = MASK[value as usize],
1 => self.y = MASK[value as usize],
2 => self.z = MASK[value as usize],
3 => self.w = MASK[value as usize],
_ => panic!("index out of bounds"),
}
}
#[inline]
#[must_use]
fn into_bool_array(self) -> [bool; 4] {
[
(self.x & 0x1) != 0,
(self.y & 0x1) != 0,
(self.z & 0x1) != 0,
(self.w & 0x1) != 0,
]
}
#[inline]
#[must_use]
fn into_u32_array(self) -> [u32; 4] {
[self.x, self.y, self.z, self.w]
}
}
impl Default for BVec4A {
#[inline]
fn default() -> Self {
Self::FALSE
}
}
impl BitAnd for BVec4A {
type Output = Self;
#[inline]
fn bitand(self, rhs: Self) -> Self {
Self {
x: self.x & rhs.x,
y: self.y & rhs.y,
z: self.z & rhs.z,
w: self.w & rhs.w,
}
}
}
impl BitAndAssign for BVec4A {
#[inline]
fn bitand_assign(&mut self, rhs: Self) {
*self = self.bitand(rhs);
}
}
impl BitOr for BVec4A {
type Output = Self;
#[inline]
fn bitor(self, rhs: Self) -> Self {
Self {
x: self.x | rhs.x,
y: self.y | rhs.y,
z: self.z | rhs.z,
w: self.w | rhs.w,
}
}
}
impl BitOrAssign for BVec4A {
#[inline]
fn bitor_assign(&mut self, rhs: Self) {
*self = self.bitor(rhs);
}
}
impl BitXor for BVec4A {
type Output = Self;
#[inline]
fn bitxor(self, rhs: Self) -> Self {
Self {
x: self.x ^ rhs.x,
y: self.y ^ rhs.y,
z: self.z ^ rhs.z,
w: self.w ^ rhs.w,
}
}
}
impl BitXorAssign for BVec4A {
#[inline]
fn bitxor_assign(&mut self, rhs: Self) {
*self = self.bitxor(rhs);
}
}
impl Not for BVec4A {
type Output = Self;
#[inline]
fn not(self) -> Self {
Self {
x: !self.x,
y: !self.y,
z: !self.z,
w: !self.w,
}
}
}
impl fmt::Debug for BVec4A {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let arr = self.into_u32_array();
write!(
f,
"{}({:#x}, {:#x}, {:#x}, {:#x})",
stringify!(BVec4A),
arr[0],
arr[1],
arr[2],
arr[3]
)
}
}
impl fmt::Display for BVec4A {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let arr = self.into_bool_array();
write!(f, "[{}, {}, {}, {}]", arr[0], arr[1], arr[2], arr[3])
}
}
impl From<[bool; 4]> for BVec4A {
#[inline]
fn from(a: [bool; 4]) -> Self {
Self::from_array(a)
}
}
impl From<BVec4A> for [bool; 4] {
#[inline]
fn from(mask: BVec4A) -> Self {
mask.into_bool_array()
}
}
impl From<BVec4A> for [u32; 4] {
#[inline]
fn from(mask: BVec4A) -> Self {
mask.into_u32_array()
}
}
+2
View File
@@ -0,0 +1,2 @@
pub mod bvec3a;
pub mod bvec4a;
+257
View File
@@ -0,0 +1,257 @@
// Generated from vec_mask.rs.tera template. Edit the template, not the generated file.
use core::fmt;
use core::ops::*;
#[cfg(target_arch = "x86")]
use core::arch::x86::*;
#[cfg(target_arch = "x86_64")]
use core::arch::x86_64::*;
#[repr(C)]
union UnionCast {
a: [u32; 4],
v: BVec3A,
}
/// Creates a 3-dimensional `bool` vector mask.
#[inline(always)]
#[must_use]
pub const fn bvec3a(x: bool, y: bool, z: bool) -> BVec3A {
BVec3A::new(x, y, z)
}
/// A 3-dimensional SIMD vector mask.
///
/// This type is 16 byte aligned.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct BVec3A(pub(crate) __m128);
const MASK: [u32; 2] = [0, 0xff_ff_ff_ff];
impl BVec3A {
/// All false.
pub const FALSE: Self = Self::splat(false);
/// All true.
pub const TRUE: Self = Self::splat(true);
/// Creates a new vector mask.
#[inline(always)]
#[must_use]
pub const fn new(x: bool, y: bool, z: bool) -> Self {
unsafe {
UnionCast {
a: [MASK[x as usize], MASK[y as usize], MASK[z as usize], 0],
}
.v
}
}
/// Creates a vector mask with all elements set to `v`.
#[inline]
#[must_use]
pub const fn splat(v: bool) -> Self {
Self::new(v, v, v)
}
/// Creates a new vector mask from a bool array.
#[inline]
#[must_use]
pub const fn from_array(a: [bool; 3]) -> Self {
Self::new(a[0], a[1], a[2])
}
/// Returns a bitmask with the lowest 3 bits set from the elements of `self`.
///
/// A true element results in a `1` bit and a false element in a `0` bit. Element `x` goes
/// into the first lowest bit, element `y` into the second, etc.
#[inline]
#[must_use]
pub fn bitmask(self) -> u32 {
unsafe { (_mm_movemask_ps(self.0) as u32) & 0x7 }
}
/// Returns true if any of the elements are true, false otherwise.
#[inline]
#[must_use]
pub fn any(self) -> bool {
self.bitmask() != 0
}
/// Returns true if all the elements are true, false otherwise.
#[inline]
#[must_use]
pub fn all(self) -> bool {
self.bitmask() == 0x7
}
/// Tests the value at `index`.
///
/// Panics if `index` is greater than 2.
#[inline]
#[must_use]
pub fn test(&self, index: usize) -> bool {
match index {
0 => (self.bitmask() & (1 << 0)) != 0,
1 => (self.bitmask() & (1 << 1)) != 0,
2 => (self.bitmask() & (1 << 2)) != 0,
_ => panic!("index out of bounds"),
}
}
/// Sets the element at `index`.
///
/// Panics if `index` is greater than 2.
#[inline]
pub fn set(&mut self, index: usize, value: bool) {
use crate::Vec3A;
let mut v = Vec3A(self.0);
v[index] = f32::from_bits(MASK[value as usize]);
self.0 = v.0;
}
#[inline]
#[must_use]
fn into_bool_array(self) -> [bool; 3] {
let bitmask = self.bitmask();
[(bitmask & 1) != 0, (bitmask & 2) != 0, (bitmask & 4) != 0]
}
#[inline]
#[must_use]
fn into_u32_array(self) -> [u32; 3] {
let bitmask = self.bitmask();
[
MASK[(bitmask & 1) as usize],
MASK[((bitmask >> 1) & 1) as usize],
MASK[((bitmask >> 2) & 1) as usize],
]
}
}
impl Default for BVec3A {
#[inline]
fn default() -> Self {
Self::FALSE
}
}
impl PartialEq for BVec3A {
#[inline]
fn eq(&self, rhs: &Self) -> bool {
self.bitmask().eq(&rhs.bitmask())
}
}
impl Eq for BVec3A {}
impl core::hash::Hash for BVec3A {
#[inline]
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.bitmask().hash(state);
}
}
impl BitAnd for BVec3A {
type Output = Self;
#[inline]
fn bitand(self, rhs: Self) -> Self {
Self(unsafe { _mm_and_ps(self.0, rhs.0) })
}
}
impl BitAndAssign for BVec3A {
#[inline]
fn bitand_assign(&mut self, rhs: Self) {
*self = self.bitand(rhs);
}
}
impl BitOr for BVec3A {
type Output = Self;
#[inline]
fn bitor(self, rhs: Self) -> Self {
Self(unsafe { _mm_or_ps(self.0, rhs.0) })
}
}
impl BitOrAssign for BVec3A {
#[inline]
fn bitor_assign(&mut self, rhs: Self) {
*self = self.bitor(rhs);
}
}
impl BitXor for BVec3A {
type Output = Self;
#[inline]
fn bitxor(self, rhs: Self) -> Self {
Self(unsafe { _mm_xor_ps(self.0, rhs.0) })
}
}
impl BitXorAssign for BVec3A {
#[inline]
fn bitxor_assign(&mut self, rhs: Self) {
*self = self.bitxor(rhs);
}
}
impl Not for BVec3A {
type Output = Self;
#[inline]
fn not(self) -> Self {
Self(unsafe { _mm_andnot_ps(self.0, _mm_set_ps1(f32::from_bits(0xff_ff_ff_ff))) })
}
}
impl From<BVec3A> for __m128 {
#[inline]
fn from(t: BVec3A) -> Self {
t.0
}
}
impl fmt::Debug for BVec3A {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let arr = self.into_u32_array();
write!(
f,
"{}({:#x}, {:#x}, {:#x})",
stringify!(BVec3A),
arr[0],
arr[1],
arr[2]
)
}
}
impl fmt::Display for BVec3A {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let arr = self.into_bool_array();
write!(f, "[{}, {}, {}]", arr[0], arr[1], arr[2])
}
}
impl From<[bool; 3]> for BVec3A {
#[inline]
fn from(a: [bool; 3]) -> Self {
Self::from_array(a)
}
}
impl From<BVec3A> for [bool; 3] {
#[inline]
fn from(mask: BVec3A) -> Self {
mask.into_bool_array()
}
}
impl From<BVec3A> for [u32; 3] {
#[inline]
fn from(mask: BVec3A) -> Self {
mask.into_u32_array()
}
}
+270
View File
@@ -0,0 +1,270 @@
// Generated from vec_mask.rs.tera template. Edit the template, not the generated file.
use core::fmt;
use core::ops::*;
#[cfg(target_arch = "x86")]
use core::arch::x86::*;
#[cfg(target_arch = "x86_64")]
use core::arch::x86_64::*;
#[repr(C)]
union UnionCast {
a: [u32; 4],
v: BVec4A,
}
/// Creates a 4-dimensional `bool` vector mask.
#[inline(always)]
#[must_use]
pub const fn bvec4a(x: bool, y: bool, z: bool, w: bool) -> BVec4A {
BVec4A::new(x, y, z, w)
}
/// A 4-dimensional SIMD vector mask.
///
/// This type is 16 byte aligned.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct BVec4A(pub(crate) __m128);
const MASK: [u32; 2] = [0, 0xff_ff_ff_ff];
impl BVec4A {
/// All false.
pub const FALSE: Self = Self::splat(false);
/// All true.
pub const TRUE: Self = Self::splat(true);
/// Creates a new vector mask.
#[inline(always)]
#[must_use]
pub const fn new(x: bool, y: bool, z: bool, w: bool) -> Self {
unsafe {
UnionCast {
a: [
MASK[x as usize],
MASK[y as usize],
MASK[z as usize],
MASK[w as usize],
],
}
.v
}
}
/// Creates a vector mask with all elements set to `v`.
#[inline]
#[must_use]
pub const fn splat(v: bool) -> Self {
Self::new(v, v, v, v)
}
/// Creates a new vector mask from a bool array.
#[inline]
#[must_use]
pub const fn from_array(a: [bool; 4]) -> Self {
Self::new(a[0], a[1], a[2], a[3])
}
/// Returns a bitmask with the lowest 4 bits set from the elements of `self`.
///
/// A true element results in a `1` bit and a false element in a `0` bit. Element `x` goes
/// into the first lowest bit, element `y` into the second, etc.
#[inline]
#[must_use]
pub fn bitmask(self) -> u32 {
unsafe { _mm_movemask_ps(self.0) as u32 }
}
/// Returns true if any of the elements are true, false otherwise.
#[inline]
#[must_use]
pub fn any(self) -> bool {
self.bitmask() != 0
}
/// Returns true if all the elements are true, false otherwise.
#[inline]
#[must_use]
pub fn all(self) -> bool {
self.bitmask() == 0xf
}
/// Tests the value at `index`.
///
/// Panics if `index` is greater than 3.
#[inline]
#[must_use]
pub fn test(&self, index: usize) -> bool {
match index {
0 => (self.bitmask() & (1 << 0)) != 0,
1 => (self.bitmask() & (1 << 1)) != 0,
2 => (self.bitmask() & (1 << 2)) != 0,
3 => (self.bitmask() & (1 << 3)) != 0,
_ => panic!("index out of bounds"),
}
}
/// Sets the element at `index`.
///
/// Panics if `index` is greater than 3.
#[inline]
pub fn set(&mut self, index: usize, value: bool) {
use crate::Vec4;
let mut v = Vec4(self.0);
v[index] = f32::from_bits(MASK[value as usize]);
self.0 = v.0;
}
#[inline]
#[must_use]
fn into_bool_array(self) -> [bool; 4] {
let bitmask = self.bitmask();
[
(bitmask & 1) != 0,
(bitmask & 2) != 0,
(bitmask & 4) != 0,
(bitmask & 8) != 0,
]
}
#[inline]
#[must_use]
fn into_u32_array(self) -> [u32; 4] {
let bitmask = self.bitmask();
[
MASK[(bitmask & 1) as usize],
MASK[((bitmask >> 1) & 1) as usize],
MASK[((bitmask >> 2) & 1) as usize],
MASK[((bitmask >> 3) & 1) as usize],
]
}
}
impl Default for BVec4A {
#[inline]
fn default() -> Self {
Self::FALSE
}
}
impl PartialEq for BVec4A {
#[inline]
fn eq(&self, rhs: &Self) -> bool {
self.bitmask().eq(&rhs.bitmask())
}
}
impl Eq for BVec4A {}
impl core::hash::Hash for BVec4A {
#[inline]
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.bitmask().hash(state);
}
}
impl BitAnd for BVec4A {
type Output = Self;
#[inline]
fn bitand(self, rhs: Self) -> Self {
Self(unsafe { _mm_and_ps(self.0, rhs.0) })
}
}
impl BitAndAssign for BVec4A {
#[inline]
fn bitand_assign(&mut self, rhs: Self) {
*self = self.bitand(rhs);
}
}
impl BitOr for BVec4A {
type Output = Self;
#[inline]
fn bitor(self, rhs: Self) -> Self {
Self(unsafe { _mm_or_ps(self.0, rhs.0) })
}
}
impl BitOrAssign for BVec4A {
#[inline]
fn bitor_assign(&mut self, rhs: Self) {
*self = self.bitor(rhs);
}
}
impl BitXor for BVec4A {
type Output = Self;
#[inline]
fn bitxor(self, rhs: Self) -> Self {
Self(unsafe { _mm_xor_ps(self.0, rhs.0) })
}
}
impl BitXorAssign for BVec4A {
#[inline]
fn bitxor_assign(&mut self, rhs: Self) {
*self = self.bitxor(rhs);
}
}
impl Not for BVec4A {
type Output = Self;
#[inline]
fn not(self) -> Self {
Self(unsafe { _mm_andnot_ps(self.0, _mm_set_ps1(f32::from_bits(0xff_ff_ff_ff))) })
}
}
impl From<BVec4A> for __m128 {
#[inline]
fn from(t: BVec4A) -> Self {
t.0
}
}
impl fmt::Debug for BVec4A {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let arr = self.into_u32_array();
write!(
f,
"{}({:#x}, {:#x}, {:#x}, {:#x})",
stringify!(BVec4A),
arr[0],
arr[1],
arr[2],
arr[3]
)
}
}
impl fmt::Display for BVec4A {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let arr = self.into_bool_array();
write!(f, "[{}, {}, {}, {}]", arr[0], arr[1], arr[2], arr[3])
}
}
impl From<[bool; 4]> for BVec4A {
#[inline]
fn from(a: [bool; 4]) -> Self {
Self::from_array(a)
}
}
impl From<BVec4A> for [bool; 4] {
#[inline]
fn from(mask: BVec4A) -> Self {
mask.into_bool_array()
}
}
impl From<BVec4A> for [u32; 4] {
#[inline]
fn from(mask: BVec4A) -> Self {
mask.into_u32_array()
}
}
+2
View File
@@ -0,0 +1,2 @@
pub mod bvec3a;
pub mod bvec4a;
+248
View File
@@ -0,0 +1,248 @@
// Generated from vec_mask.rs.tera template. Edit the template, not the generated file.
use core::fmt;
use core::ops::*;
use core::arch::wasm32::*;
/// Creates a 3-dimensional `bool` vector mask.
#[inline(always)]
#[must_use]
pub const fn bvec3a(x: bool, y: bool, z: bool) -> BVec3A {
BVec3A::new(x, y, z)
}
/// A 3-dimensional SIMD vector mask.
///
/// This type is 16 byte aligned.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct BVec3A(pub(crate) v128);
const MASK: [u32; 2] = [0, 0xff_ff_ff_ff];
impl BVec3A {
/// All false.
pub const FALSE: Self = Self::splat(false);
/// All true.
pub const TRUE: Self = Self::splat(true);
/// Creates a new vector mask.
#[inline(always)]
#[must_use]
pub const fn new(x: bool, y: bool, z: bool) -> Self {
Self(u32x4(
MASK[x as usize],
MASK[y as usize],
MASK[z as usize],
0,
))
}
/// Creates a vector mask with all elements set to `v`.
#[inline]
#[must_use]
pub const fn splat(v: bool) -> Self {
Self::new(v, v, v)
}
/// Creates a new vector mask from a bool array.
#[inline]
#[must_use]
pub const fn from_array(a: [bool; 3]) -> Self {
Self::new(a[0], a[1], a[2])
}
/// Returns a bitmask with the lowest 3 bits set from the elements of `self`.
///
/// A true element results in a `1` bit and a false element in a `0` bit. Element `x` goes
/// into the first lowest bit, element `y` into the second, etc.
#[inline]
#[must_use]
pub fn bitmask(self) -> u32 {
(u32x4_bitmask(self.0) & 0x7) as u32
}
/// Returns true if any of the elements are true, false otherwise.
#[inline]
#[must_use]
pub fn any(self) -> bool {
self.bitmask() != 0
}
/// Returns true if all the elements are true, false otherwise.
#[inline]
#[must_use]
pub fn all(self) -> bool {
self.bitmask() == 0x7
}
/// Tests the value at `index`.
///
/// Panics if `index` is greater than 2.
#[inline]
#[must_use]
pub fn test(&self, index: usize) -> bool {
match index {
0 => (self.bitmask() & (1 << 0)) != 0,
1 => (self.bitmask() & (1 << 1)) != 0,
2 => (self.bitmask() & (1 << 2)) != 0,
_ => panic!("index out of bounds"),
}
}
/// Sets the element at `index`.
///
/// Panics if `index` is greater than 2.
#[inline]
pub fn set(&mut self, index: usize, value: bool) {
use crate::Vec3A;
let mut v = Vec3A(self.0);
v[index] = f32::from_bits(MASK[value as usize]);
self.0 = v.0;
}
#[inline]
#[must_use]
fn into_bool_array(self) -> [bool; 3] {
let bitmask = self.bitmask();
[(bitmask & 1) != 0, (bitmask & 2) != 0, (bitmask & 4) != 0]
}
#[inline]
#[must_use]
fn into_u32_array(self) -> [u32; 3] {
let bitmask = self.bitmask();
[
MASK[(bitmask & 1) as usize],
MASK[((bitmask >> 1) & 1) as usize],
MASK[((bitmask >> 2) & 1) as usize],
]
}
}
impl Default for BVec3A {
#[inline]
fn default() -> Self {
Self::FALSE
}
}
impl PartialEq for BVec3A {
#[inline]
fn eq(&self, rhs: &Self) -> bool {
self.bitmask().eq(&rhs.bitmask())
}
}
impl Eq for BVec3A {}
impl core::hash::Hash for BVec3A {
#[inline]
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.bitmask().hash(state);
}
}
impl BitAnd for BVec3A {
type Output = Self;
#[inline]
fn bitand(self, rhs: Self) -> Self {
Self(v128_and(self.0, rhs.0))
}
}
impl BitAndAssign for BVec3A {
#[inline]
fn bitand_assign(&mut self, rhs: Self) {
*self = self.bitand(rhs);
}
}
impl BitOr for BVec3A {
type Output = Self;
#[inline]
fn bitor(self, rhs: Self) -> Self {
Self(v128_or(self.0, rhs.0))
}
}
impl BitOrAssign for BVec3A {
#[inline]
fn bitor_assign(&mut self, rhs: Self) {
*self = self.bitor(rhs);
}
}
impl BitXor for BVec3A {
type Output = Self;
#[inline]
fn bitxor(self, rhs: Self) -> Self {
Self(v128_xor(self.0, rhs.0))
}
}
impl BitXorAssign for BVec3A {
#[inline]
fn bitxor_assign(&mut self, rhs: Self) {
*self = self.bitxor(rhs);
}
}
impl Not for BVec3A {
type Output = Self;
#[inline]
fn not(self) -> Self {
Self(v128_not(self.0))
}
}
impl From<BVec3A> for v128 {
#[inline]
fn from(t: BVec3A) -> Self {
t.0
}
}
impl fmt::Debug for BVec3A {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let arr = self.into_u32_array();
write!(
f,
"{}({:#x}, {:#x}, {:#x})",
stringify!(BVec3A),
arr[0],
arr[1],
arr[2]
)
}
}
impl fmt::Display for BVec3A {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let arr = self.into_bool_array();
write!(f, "[{}, {}, {}]", arr[0], arr[1], arr[2])
}
}
impl From<[bool; 3]> for BVec3A {
#[inline]
fn from(a: [bool; 3]) -> Self {
Self::from_array(a)
}
}
impl From<BVec3A> for [bool; 3] {
#[inline]
fn from(mask: BVec3A) -> Self {
mask.into_bool_array()
}
}
impl From<BVec3A> for [u32; 3] {
#[inline]
fn from(mask: BVec3A) -> Self {
mask.into_u32_array()
}
}
+256
View File
@@ -0,0 +1,256 @@
// Generated from vec_mask.rs.tera template. Edit the template, not the generated file.
use core::fmt;
use core::ops::*;
use core::arch::wasm32::*;
/// Creates a 4-dimensional `bool` vector mask.
#[inline(always)]
#[must_use]
pub const fn bvec4a(x: bool, y: bool, z: bool, w: bool) -> BVec4A {
BVec4A::new(x, y, z, w)
}
/// A 4-dimensional SIMD vector mask.
///
/// This type is 16 byte aligned.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct BVec4A(pub(crate) v128);
const MASK: [u32; 2] = [0, 0xff_ff_ff_ff];
impl BVec4A {
/// All false.
pub const FALSE: Self = Self::splat(false);
/// All true.
pub const TRUE: Self = Self::splat(true);
/// Creates a new vector mask.
#[inline(always)]
#[must_use]
pub const fn new(x: bool, y: bool, z: bool, w: bool) -> Self {
Self(u32x4(
MASK[x as usize],
MASK[y as usize],
MASK[z as usize],
MASK[w as usize],
))
}
/// Creates a vector mask with all elements set to `v`.
#[inline]
#[must_use]
pub const fn splat(v: bool) -> Self {
Self::new(v, v, v, v)
}
/// Creates a new vector mask from a bool array.
#[inline]
#[must_use]
pub const fn from_array(a: [bool; 4]) -> Self {
Self::new(a[0], a[1], a[2], a[3])
}
/// Returns a bitmask with the lowest 4 bits set from the elements of `self`.
///
/// A true element results in a `1` bit and a false element in a `0` bit. Element `x` goes
/// into the first lowest bit, element `y` into the second, etc.
#[inline]
#[must_use]
pub fn bitmask(self) -> u32 {
u32x4_bitmask(self.0) as u32
}
/// Returns true if any of the elements are true, false otherwise.
#[inline]
#[must_use]
pub fn any(self) -> bool {
self.bitmask() != 0
}
/// Returns true if all the elements are true, false otherwise.
#[inline]
#[must_use]
pub fn all(self) -> bool {
self.bitmask() == 0xf
}
/// Tests the value at `index`.
///
/// Panics if `index` is greater than 3.
#[inline]
#[must_use]
pub fn test(&self, index: usize) -> bool {
match index {
0 => (self.bitmask() & (1 << 0)) != 0,
1 => (self.bitmask() & (1 << 1)) != 0,
2 => (self.bitmask() & (1 << 2)) != 0,
3 => (self.bitmask() & (1 << 3)) != 0,
_ => panic!("index out of bounds"),
}
}
/// Sets the element at `index`.
///
/// Panics if `index` is greater than 3.
#[inline]
pub fn set(&mut self, index: usize, value: bool) {
use crate::Vec4;
let mut v = Vec4(self.0);
v[index] = f32::from_bits(MASK[value as usize]);
self.0 = v.0;
}
#[inline]
#[must_use]
fn into_bool_array(self) -> [bool; 4] {
let bitmask = self.bitmask();
[
(bitmask & 1) != 0,
(bitmask & 2) != 0,
(bitmask & 4) != 0,
(bitmask & 8) != 0,
]
}
#[inline]
#[must_use]
fn into_u32_array(self) -> [u32; 4] {
let bitmask = self.bitmask();
[
MASK[(bitmask & 1) as usize],
MASK[((bitmask >> 1) & 1) as usize],
MASK[((bitmask >> 2) & 1) as usize],
MASK[((bitmask >> 3) & 1) as usize],
]
}
}
impl Default for BVec4A {
#[inline]
fn default() -> Self {
Self::FALSE
}
}
impl PartialEq for BVec4A {
#[inline]
fn eq(&self, rhs: &Self) -> bool {
self.bitmask().eq(&rhs.bitmask())
}
}
impl Eq for BVec4A {}
impl core::hash::Hash for BVec4A {
#[inline]
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.bitmask().hash(state);
}
}
impl BitAnd for BVec4A {
type Output = Self;
#[inline]
fn bitand(self, rhs: Self) -> Self {
Self(v128_and(self.0, rhs.0))
}
}
impl BitAndAssign for BVec4A {
#[inline]
fn bitand_assign(&mut self, rhs: Self) {
*self = self.bitand(rhs);
}
}
impl BitOr for BVec4A {
type Output = Self;
#[inline]
fn bitor(self, rhs: Self) -> Self {
Self(v128_or(self.0, rhs.0))
}
}
impl BitOrAssign for BVec4A {
#[inline]
fn bitor_assign(&mut self, rhs: Self) {
*self = self.bitor(rhs);
}
}
impl BitXor for BVec4A {
type Output = Self;
#[inline]
fn bitxor(self, rhs: Self) -> Self {
Self(v128_xor(self.0, rhs.0))
}
}
impl BitXorAssign for BVec4A {
#[inline]
fn bitxor_assign(&mut self, rhs: Self) {
*self = self.bitxor(rhs);
}
}
impl Not for BVec4A {
type Output = Self;
#[inline]
fn not(self) -> Self {
Self(v128_not(self.0))
}
}
impl From<BVec4A> for v128 {
#[inline]
fn from(t: BVec4A) -> Self {
t.0
}
}
impl fmt::Debug for BVec4A {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let arr = self.into_u32_array();
write!(
f,
"{}({:#x}, {:#x}, {:#x}, {:#x})",
stringify!(BVec4A),
arr[0],
arr[1],
arr[2],
arr[3]
)
}
}
impl fmt::Display for BVec4A {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let arr = self.into_bool_array();
write!(f, "[{}, {}, {}, {}]", arr[0], arr[1], arr[2], arr[3])
}
}
impl From<[bool; 4]> for BVec4A {
#[inline]
fn from(a: [bool; 4]) -> Self {
Self::from_array(a)
}
}
impl From<BVec4A> for [bool; 4] {
#[inline]
fn from(mask: BVec4A) -> Self {
mask.into_bool_array()
}
}
impl From<BVec4A> for [u32; 4] {
#[inline]
fn from(mask: BVec4A) -> Self {
mask.into_u32_array()
}
}
+57
View File
@@ -0,0 +1,57 @@
use core::simd::{num::SimdFloat, *};
/// Calculates the vector 3 dot product and returns answer in x lane of f32x4.
#[inline(always)]
pub(crate) fn dot3_in_x(lhs: f32x4, rhs: f32x4) -> f32x4 {
let x2_y2_z2_w2 = lhs * rhs;
let y2_0_0_0 = simd_swizzle!(x2_y2_z2_w2, [1, 0, 0, 0]);
let z2_0_0_0 = simd_swizzle!(x2_y2_z2_w2, [2, 0, 0, 0]);
let x2y2_0_0_0 = x2_y2_z2_w2 + y2_0_0_0;
x2y2_0_0_0 + z2_0_0_0
}
/// Calculates the vector 4 dot product and returns answer in x lane of f32x4.
#[inline(always)]
pub(crate) fn dot4_in_x(lhs: f32x4, rhs: f32x4) -> f32x4 {
let x2_y2_z2_w2 = lhs * rhs;
let z2_w2_0_0 = simd_swizzle!(x2_y2_z2_w2, [2, 3, 0, 0]);
let x2z2_y2w2_0_0 = x2_y2_z2_w2 + z2_w2_0_0;
let y2w2_0_0_0 = simd_swizzle!(x2z2_y2w2_0_0, [1, 0, 0, 0]);
x2z2_y2w2_0_0 + y2w2_0_0_0
}
#[inline]
pub(crate) fn dot3(lhs: f32x4, rhs: f32x4) -> f32 {
dot3_in_x(lhs, rhs)[0]
}
#[inline]
pub(crate) fn dot3_into_f32x4(lhs: f32x4, rhs: f32x4) -> f32x4 {
let dot_in_x = dot3_in_x(lhs, rhs);
simd_swizzle!(dot_in_x, [0, 0, 0, 0])
}
#[inline]
pub(crate) fn dot4(lhs: f32x4, rhs: f32x4) -> f32 {
dot4_in_x(lhs, rhs)[0]
}
#[inline]
pub(crate) fn dot4_into_f32x4(lhs: f32x4, rhs: f32x4) -> f32x4 {
let dot_in_x = dot4_in_x(lhs, rhs);
simd_swizzle!(dot_in_x, [0, 0, 0, 0])
}
#[inline(always)]
pub(crate) fn f32x4_bitand(a: f32x4, b: f32x4) -> f32x4 {
let a = a.to_bits();
let b = b.to_bits();
f32x4::from_bits(a & b)
}
#[inline(always)]
pub(crate) fn f32x4_bitxor(a: f32x4, b: f32x4) -> f32x4 {
let a = a.to_bits();
let b = b.to_bits();
f32x4::from_bits(a ^ b)
}
+40
View File
@@ -0,0 +1,40 @@
#[cfg(not(feature = "scalar-math"))]
#[cfg_attr(target_arch = "spirv", repr(simd))]
#[cfg_attr(not(target_arch = "spirv"), repr(C))]
pub struct Vec3<T> {
pub x: T,
pub y: T,
pub z: T,
}
#[cfg(not(feature = "scalar-math"))]
#[cfg_attr(target_arch = "spirv", repr(simd))]
#[cfg_attr(not(target_arch = "spirv"), repr(C))]
pub struct Vec4<T> {
pub x: T,
pub y: T,
pub z: T,
pub w: T,
}
#[cfg(not(feature = "scalar-math"))]
#[cfg_attr(not(target_arch = "spirv"), repr(C))]
pub struct Cols2<V> {
pub x_axis: V,
pub y_axis: V,
}
#[cfg_attr(not(target_arch = "spirv"), repr(C))]
pub struct Cols3<V> {
pub x_axis: V,
pub y_axis: V,
pub z_axis: V,
}
#[cfg_attr(not(target_arch = "spirv"), repr(C))]
pub struct Cols4<V> {
pub x_axis: V,
pub y_axis: V,
pub z_axis: V,
pub w_axis: V,
}
+444
View File
@@ -0,0 +1,444 @@
// Based on Ken Shoemake. 1994. Euler angle conversion. Graphics gems IV. Academic Press
// Professional, Inc., USA, 222–229.
use crate::{DMat3, DMat4, DQuat, DVec3, Mat3, Mat3A, Mat4, Quat, Vec3, Vec3A, Vec3Swizzles};
/// Euler rotation sequences.
///
/// The three elemental rotations may be extrinsic (rotations about the axes xyz of the original
/// coordinate system, which is assumed to remain motionless), or intrinsic(rotations about the
/// axes of the rotating coordinate system XYZ, solidary with the moving body, which changes its
/// orientation after each elemental rotation).
///
/// ```
/// # use glam::{EulerRot, Mat3};
/// # let i = core::f32::consts::FRAC_PI_2;
/// # let j = core::f32::consts::FRAC_PI_4;
/// # let k = core::f32::consts::FRAC_PI_8;
/// let m_intrinsic = Mat3::from_rotation_x(i) * Mat3::from_rotation_y(j) * Mat3::from_rotation_z(k);
/// let n_intrinsic = Mat3::from_euler(EulerRot::XYZ, i, j, k);
/// assert!(m_intrinsic.abs_diff_eq(n_intrinsic, 2e-6));
///
/// let m_extrinsic = Mat3::from_rotation_z(k) * Mat3::from_rotation_y(j) * Mat3::from_rotation_x(i);
/// let n_extrinsic = Mat3::from_euler(EulerRot::XYZEx, i, j, k);
/// assert!(m_extrinsic.abs_diff_eq(n_extrinsic, 2e-6));
/// ```
///
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EulerRot {
/// Intrinsic three-axis rotation ZYX
ZYX,
/// Intrinsic three-axis rotation ZXY
ZXY,
/// Intrinsic three-axis rotation YXZ
YXZ,
/// Intrinsic three-axis rotation YZX
YZX,
/// Intrinsic three-axis rotation XYZ
XYZ,
/// Intrinsic three-axis rotation XZY
XZY,
/// Intrinsic two-axis rotation ZYZ
ZYZ,
/// Intrinsic two-axis rotation ZXZ
ZXZ,
/// Intrinsic two-axis rotation YXY
YXY,
/// Intrinsic two-axis rotation YZY
YZY,
/// Intrinsic two-axis rotation XYX
XYX,
/// Intrinsic two-axis rotation XZX
XZX,
/// Extrinsic three-axis rotation ZYX
ZYXEx,
/// Extrinsic three-axis rotation ZXY
ZXYEx,
/// Extrinsic three-axis rotation YXZ
YXZEx,
/// Extrinsic three-axis rotation YZX
YZXEx,
/// Extrinsic three-axis rotation XYZ
XYZEx,
/// Extrinsic three-axis rotation XZY
XZYEx,
/// Extrinsic two-axis rotation ZYZ
ZYZEx,
/// Extrinsic two-axis rotation ZXZ
ZXZEx,
/// Extrinsic two-axis rotation YXY
YXYEx,
/// Extrinsic two-axis rotation YZY
YZYEx,
/// Extrinsic two-axis rotation XYX
XYXEx,
/// Extrinsic two-axis rotation XZX
XZXEx,
}
impl Default for EulerRot {
/// Default `YXZ` as yaw (y-axis), pitch (x-axis), roll (z-axis).
fn default() -> Self {
Self::YXZ
}
}
pub(crate) trait ToEuler {
type Scalar;
fn to_euler_angles(self, order: EulerRot) -> (Self::Scalar, Self::Scalar, Self::Scalar);
}
pub(crate) trait FromEuler {
type Scalar;
fn from_euler_angles(
order: EulerRot,
i: Self::Scalar,
j: Self::Scalar,
k: Self::Scalar,
) -> Self;
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum Axis {
X = 0,
Y = 1,
Z = 2,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum Parity {
Odd = 0,
Even = 1,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum Repeated {
No = 0,
Yes = 1,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum Frame {
Relative = 0,
Static = 1,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
struct Order {
initial_axis: Axis,
parity_even: bool,
initial_repeated: bool,
frame_static: bool,
}
impl Order {
const fn new(
initial_axis: Axis,
parity: Parity,
initial_repeated: Repeated,
frame: Frame,
) -> Self {
Self {
initial_axis,
parity_even: parity as u32 == Parity::Even as u32,
initial_repeated: initial_repeated as u32 == Repeated::Yes as u32,
frame_static: frame as u32 == Frame::Static as u32,
}
}
const fn from_euler(euler: EulerRot) -> Self {
match euler {
EulerRot::XYZ => Self::new(Axis::X, Parity::Even, Repeated::No, Frame::Static),
EulerRot::XYX => Self::new(Axis::X, Parity::Even, Repeated::Yes, Frame::Static),
EulerRot::XZY => Self::new(Axis::X, Parity::Odd, Repeated::No, Frame::Static),
EulerRot::XZX => Self::new(Axis::X, Parity::Odd, Repeated::Yes, Frame::Static),
EulerRot::YZX => Self::new(Axis::Y, Parity::Even, Repeated::No, Frame::Static),
EulerRot::YZY => Self::new(Axis::Y, Parity::Even, Repeated::Yes, Frame::Static),
EulerRot::YXZ => Self::new(Axis::Y, Parity::Odd, Repeated::No, Frame::Static),
EulerRot::YXY => Self::new(Axis::Y, Parity::Odd, Repeated::Yes, Frame::Static),
EulerRot::ZXY => Self::new(Axis::Z, Parity::Even, Repeated::No, Frame::Static),
EulerRot::ZXZ => Self::new(Axis::Z, Parity::Even, Repeated::Yes, Frame::Static),
EulerRot::ZYX => Self::new(Axis::Z, Parity::Odd, Repeated::No, Frame::Static),
EulerRot::ZYZ => Self::new(Axis::Z, Parity::Odd, Repeated::Yes, Frame::Static),
EulerRot::ZYXEx => Self::new(Axis::X, Parity::Even, Repeated::No, Frame::Relative),
EulerRot::XYXEx => Self::new(Axis::X, Parity::Even, Repeated::Yes, Frame::Relative),
EulerRot::YZXEx => Self::new(Axis::X, Parity::Odd, Repeated::No, Frame::Relative),
EulerRot::XZXEx => Self::new(Axis::X, Parity::Odd, Repeated::Yes, Frame::Relative),
EulerRot::XZYEx => Self::new(Axis::Y, Parity::Even, Repeated::No, Frame::Relative),
EulerRot::YZYEx => Self::new(Axis::Y, Parity::Even, Repeated::Yes, Frame::Relative),
EulerRot::ZXYEx => Self::new(Axis::Y, Parity::Odd, Repeated::No, Frame::Relative),
EulerRot::YXYEx => Self::new(Axis::Y, Parity::Odd, Repeated::Yes, Frame::Relative),
EulerRot::YXZEx => Self::new(Axis::Z, Parity::Even, Repeated::No, Frame::Relative),
EulerRot::ZXZEx => Self::new(Axis::Z, Parity::Even, Repeated::Yes, Frame::Relative),
EulerRot::XYZEx => Self::new(Axis::Z, Parity::Odd, Repeated::No, Frame::Relative),
EulerRot::ZYZEx => Self::new(Axis::Z, Parity::Odd, Repeated::Yes, Frame::Relative),
}
}
const fn next_axis(i: usize) -> usize {
(i + 1) % 3
}
const fn prev_axis(i: usize) -> usize {
if i > 0 {
i - 1
} else {
2
}
}
const fn angle_order(self) -> (usize, usize, usize) {
let i = self.initial_axis as usize;
let j = if self.parity_even {
Order::next_axis(i)
} else {
Order::prev_axis(i)
};
let k = if self.parity_even {
Order::prev_axis(i)
} else {
Order::next_axis(i)
};
(i, j, k)
}
}
macro_rules! impl_mat3_from_euler {
($scalar:ident, $mat3:ident, $vec3:ident) => {
impl FromEuler for $mat3 {
type Scalar = $scalar;
fn from_euler_angles(
euler: EulerRot,
x: Self::Scalar,
y: Self::Scalar,
z: Self::Scalar,
) -> Self {
use crate::$scalar::math;
let order = Order::from_euler(euler);
let (i, j, k) = order.angle_order();
let mut angles = if order.frame_static {
$vec3::new(x, y, z)
} else {
$vec3::new(z, y, x)
};
// rotation direction is reverse from original paper
if order.parity_even {
angles = -angles;
}
let (si, ci) = math::sin_cos(angles.x);
let (sj, cj) = math::sin_cos(angles.y);
let (sh, ch) = math::sin_cos(angles.z);
let cc = ci * ch;
let cs = ci * sh;
let sc = si * ch;
let ss = si * sh;
let mut m = [[0.0; 3]; 3];
if order.initial_repeated {
m[i][i] = cj;
m[i][j] = sj * si;
m[i][k] = sj * ci;
m[j][i] = sj * sh;
m[j][j] = -cj * ss + cc;
m[j][k] = -cj * cs - sc;
m[k][i] = -sj * ch;
m[k][j] = cj * sc + cs;
m[k][k] = cj * cc - ss;
} else {
m[i][i] = cj * ch;
m[i][j] = sj * sc - cs;
m[i][k] = sj * cc + ss;
m[j][i] = cj * sh;
m[j][j] = sj * ss + cc;
m[j][k] = sj * cs - sc;
m[k][i] = -sj;
m[k][j] = cj * si;
m[k][k] = cj * ci;
}
$mat3::from_cols_array_2d(&m)
}
}
};
}
macro_rules! impl_mat4_from_euler {
($scalar:ident, $mat4:ident, $mat3:ident) => {
impl FromEuler for $mat4 {
type Scalar = $scalar;
fn from_euler_angles(
euler: EulerRot,
x: Self::Scalar,
y: Self::Scalar,
z: Self::Scalar,
) -> Self {
$mat4::from_mat3($mat3::from_euler_angles(euler, x, y, z))
}
}
};
}
macro_rules! impl_quat_from_euler {
($scalar:ident, $quat:ident, $vec3:ident) => {
impl FromEuler for $quat {
type Scalar = $scalar;
fn from_euler_angles(
euler: EulerRot,
x: Self::Scalar,
y: Self::Scalar,
z: Self::Scalar,
) -> Self {
use crate::$scalar::math;
let order = Order::from_euler(euler);
let (i, j, k) = order.angle_order();
let mut angles = if order.frame_static {
$vec3::new(x, y, z)
} else {
$vec3::new(z, y, x)
};
if order.parity_even {
angles.y = -angles.y;
}
let ti = angles.x * 0.5;
let tj = angles.y * 0.5;
let th = angles.z * 0.5;
let (si, ci) = math::sin_cos(ti);
let (sj, cj) = math::sin_cos(tj);
let (sh, ch) = math::sin_cos(th);
let cc = ci * ch;
let cs = ci * sh;
let sc = si * ch;
let ss = si * sh;
let parity = if !order.parity_even { 1.0 } else { -1.0 };
let mut a = [0.0; 4];
if order.initial_repeated {
a[i] = cj * (cs + sc);
a[j] = sj * (cc + ss) * parity;
a[k] = sj * (cs - sc);
a[3] = cj * (cc - ss);
} else {
a[i] = cj * sc - sj * cs;
a[j] = (cj * ss + sj * cc) * parity;
a[k] = cj * cs - sj * sc;
a[3] = cj * cc + sj * ss;
}
$quat::from_array(a)
}
}
};
}
macro_rules! impl_mat3_to_euler {
($scalar:ident, $mat3:ident, $vec3:ident) => {
impl ToEuler for $mat3 {
type Scalar = $scalar;
fn to_euler_angles(
self,
euler: EulerRot,
) -> (Self::Scalar, Self::Scalar, Self::Scalar) {
use crate::$scalar::math;
let order = Order::from_euler(euler);
let (i, j, k) = order.angle_order();
let mut ea = $vec3::ZERO;
if order.initial_repeated {
let sy = math::sqrt(
self.col(i)[j] * self.col(i)[j] + self.col(i)[k] * self.col(i)[k],
);
if (sy > 16.0 * $scalar::EPSILON) {
ea.x = math::atan2(self.col(i)[j], self.col(i)[k]);
ea.y = math::atan2(sy, self.col(i)[i]);
ea.z = math::atan2(self.col(j)[i], -self.col(k)[i]);
} else {
ea.x = math::atan2(-self.col(j)[k], self.col(j)[j]);
ea.y = math::atan2(sy, self.col(i)[i]);
}
} else {
let cy = math::sqrt(
self.col(i)[i] * self.col(i)[i] + self.col(j)[i] * self.col(j)[i],
);
if (cy > 16.0 * $scalar::EPSILON) {
ea.x = math::atan2(self.col(k)[j], self.col(k)[k]);
ea.y = math::atan2(-self.col(k)[i], cy);
ea.z = math::atan2(self.col(j)[i], self.col(i)[i]);
} else {
ea.x = math::atan2(-self.col(j)[k], self.col(j)[j]);
ea.y = math::atan2(-self.col(k)[i], cy);
}
}
// reverse rotation angle of original code
if order.parity_even {
ea = -ea;
}
if !order.frame_static {
ea = ea.zyx();
}
(ea.x, ea.y, ea.z)
}
}
};
}
macro_rules! impl_mat4_to_euler {
($scalar:ident, $mat4:ident, $mat3:ident) => {
impl ToEuler for $mat4 {
type Scalar = $scalar;
fn to_euler_angles(
self,
order: EulerRot,
) -> (Self::Scalar, Self::Scalar, Self::Scalar) {
$mat3::from_mat4(self).to_euler_angles(order)
}
}
};
}
macro_rules! impl_quat_to_euler {
($scalar:ident, $quat:ident, $mat3:ident) => {
impl ToEuler for $quat {
type Scalar = $scalar;
fn to_euler_angles(
self,
order: EulerRot,
) -> (Self::Scalar, Self::Scalar, Self::Scalar) {
$mat3::from_quat(self).to_euler_angles(order)
}
}
};
}
impl_mat3_to_euler!(f32, Mat3, Vec3);
impl_mat3_from_euler!(f32, Mat3, Vec3);
impl_mat3_to_euler!(f32, Mat3A, Vec3A);
impl_mat3_from_euler!(f32, Mat3A, Vec3A);
impl_mat4_from_euler!(f32, Mat4, Mat3);
impl_mat4_to_euler!(f32, Mat4, Mat3);
impl_quat_to_euler!(f32, Quat, Mat3);
impl_quat_from_euler!(f32, Quat, Vec3);
impl_mat3_to_euler!(f64, DMat3, DVec3);
impl_mat3_from_euler!(f64, DMat3, DVec3);
impl_mat4_to_euler!(f64, DMat4, DMat3);
impl_mat4_from_euler!(f64, DMat4, DMat3);
impl_quat_to_euler!(f64, DQuat, DMat3);
impl_quat_from_euler!(f64, DQuat, DVec3);
+181
View File
@@ -0,0 +1,181 @@
mod affine2;
mod affine3a;
mod float;
mod mat3;
pub(crate) mod math;
mod vec2;
mod vec3;
#[cfg(all(feature = "core-simd", not(feature = "scalar-math")))]
mod coresimd;
#[cfg(any(
not(any(
feature = "core-simd",
target_arch = "aarch64",
target_feature = "sse2",
target_feature = "simd128"
)),
feature = "scalar-math"
))]
mod scalar;
#[cfg(all(
target_arch = "aarch64",
not(any(feature = "core-simd", feature = "scalar-math"))
))]
mod neon;
#[cfg(all(
target_feature = "sse2",
not(any(feature = "core-simd", feature = "scalar-math"))
))]
mod sse2;
#[cfg(all(
target_feature = "simd128",
not(any(feature = "core-simd", feature = "scalar-math"))
))]
mod wasm32;
#[cfg(any(
not(any(
feature = "core-simd",
target_arch = "aarch64",
target_feature = "sse2",
target_feature = "simd128"
)),
feature = "scalar-math"
))]
use scalar::*;
#[cfg(all(
target_arch = "aarch64",
not(any(feature = "core-simd", feature = "scalar-math"))
))]
use neon::*;
#[cfg(all(
target_feature = "sse2",
not(any(feature = "core-simd", feature = "scalar-math"))
))]
use sse2::*;
#[cfg(all(
target_feature = "simd128",
not(any(feature = "core-simd", feature = "scalar-math"))
))]
use wasm32::*;
#[cfg(all(feature = "core-simd", not(feature = "scalar-math")))]
use coresimd::*;
pub use affine2::Affine2;
pub use affine3a::Affine3A;
pub use mat2::{mat2, Mat2};
pub use mat3::{mat3, Mat3};
pub use mat3a::{mat3a, Mat3A};
pub use mat4::{mat4, Mat4};
pub use quat::{quat, Quat};
pub use vec2::{vec2, Vec2};
pub use vec3::{vec3, Vec3};
pub use vec3a::{vec3a, Vec3A};
pub use vec4::{vec4, Vec4};
#[cfg(not(target_arch = "spirv"))]
mod test {
use super::*;
#[cfg(all(not(feature = "cuda"), feature = "scalar-math"))]
mod const_test_affine2 {
const_assert_eq!(
core::mem::align_of::<super::Vec2>(),
core::mem::align_of::<super::Affine2>()
);
const_assert_eq!(24, core::mem::size_of::<super::Affine2>());
}
#[cfg(not(feature = "scalar-math"))]
mod const_test_affine2 {
const_assert_eq!(16, core::mem::align_of::<super::Affine2>());
const_assert_eq!(32, core::mem::size_of::<super::Affine2>());
}
mod const_test_mat2 {
#[cfg(feature = "scalar-math")]
const_assert_eq!(
core::mem::align_of::<super::Vec2>(),
core::mem::align_of::<super::Mat2>()
);
#[cfg(not(any(feature = "scalar-math", target_arch = "spirv")))]
const_assert_eq!(16, core::mem::align_of::<super::Mat2>());
const_assert_eq!(16, core::mem::size_of::<super::Mat2>());
}
mod const_test_mat3 {
const_assert_eq!(
core::mem::align_of::<f32>(),
core::mem::align_of::<super::Mat3>()
);
const_assert_eq!(36, core::mem::size_of::<super::Mat3>());
}
mod const_test_mat3a {
const_assert_eq!(16, core::mem::align_of::<super::Mat3A>());
const_assert_eq!(48, core::mem::size_of::<super::Mat3A>());
}
mod const_test_mat4 {
const_assert_eq!(
core::mem::align_of::<super::Vec4>(),
core::mem::align_of::<super::Mat4>()
);
const_assert_eq!(64, core::mem::size_of::<super::Mat4>());
}
mod const_test_quat {
#[cfg(feature = "scalar-math")]
const_assert_eq!(
core::mem::align_of::<f32>(),
core::mem::align_of::<super::Quat>()
);
#[cfg(not(any(feature = "scalar-math", target_arch = "spirv")))]
const_assert_eq!(16, core::mem::align_of::<super::Quat>());
const_assert_eq!(16, core::mem::size_of::<super::Quat>());
}
mod const_test_vec2 {
#[cfg(not(feature = "cuda"))]
const_assert_eq!(
core::mem::align_of::<f32>(),
core::mem::align_of::<super::Vec2>()
);
#[cfg(feature = "cuda")]
const_assert_eq!(8, core::mem::align_of::<super::Vec2>());
const_assert_eq!(8, core::mem::size_of::<super::Vec2>());
}
mod const_test_vec3 {
const_assert_eq!(
core::mem::align_of::<f32>(),
core::mem::align_of::<super::Vec3>()
);
const_assert_eq!(12, core::mem::size_of::<super::Vec3>());
}
mod const_test_vec3a {
const_assert_eq!(16, core::mem::align_of::<super::Vec3A>());
const_assert_eq!(16, core::mem::size_of::<super::Vec3A>());
}
mod const_test_vec4 {
#[cfg(all(feature = "scalar-math", not(feature = "cuda")))]
const_assert_eq!(
core::mem::align_of::<f32>(),
core::mem::align_of::<super::Vec4>()
);
#[cfg(not(feature = "scalar-math"))]
const_assert_eq!(16, core::mem::align_of::<super::Vec4>());
const_assert_eq!(16, core::mem::size_of::<super::Vec4>());
}
}
+458
View File
@@ -0,0 +1,458 @@
// Generated from affine.rs.tera template. Edit the template, not the generated file.
use crate::{Mat2, Mat3, Mat3A, Vec2, Vec3A};
use core::ops::{Deref, DerefMut, Mul, MulAssign};
/// A 2D affine transform, which can represent translation, rotation, scaling and shear.
#[derive(Copy, Clone)]
#[repr(C)]
pub struct Affine2 {
pub matrix2: Mat2,
pub translation: Vec2,
}
impl Affine2 {
/// The degenerate zero transform.
///
/// This transforms any finite vector and point to zero.
/// The zero transform is non-invertible.
pub const ZERO: Self = Self {
matrix2: Mat2::ZERO,
translation: Vec2::ZERO,
};
/// The identity transform.
///
/// Multiplying a vector with this returns the same vector.
pub const IDENTITY: Self = Self {
matrix2: Mat2::IDENTITY,
translation: Vec2::ZERO,
};
/// All NAN:s.
pub const NAN: Self = Self {
matrix2: Mat2::NAN,
translation: Vec2::NAN,
};
/// Creates an affine transform from three column vectors.
#[inline(always)]
#[must_use]
pub const fn from_cols(x_axis: Vec2, y_axis: Vec2, z_axis: Vec2) -> Self {
Self {
matrix2: Mat2::from_cols(x_axis, y_axis),
translation: z_axis,
}
}
/// Creates an affine transform from a `[f32; 6]` array stored in column major order.
#[inline]
#[must_use]
pub fn from_cols_array(m: &[f32; 6]) -> Self {
Self {
matrix2: Mat2::from_cols_array(&[m[0], m[1], m[2], m[3]]),
translation: Vec2::from_array([m[4], m[5]]),
}
}
/// Creates a `[f32; 6]` array storing data in column major order.
#[inline]
#[must_use]
pub fn to_cols_array(&self) -> [f32; 6] {
let x = &self.matrix2.x_axis;
let y = &self.matrix2.y_axis;
let z = &self.translation;
[x.x, x.y, y.x, y.y, z.x, z.y]
}
/// Creates an affine transform from a `[[f32; 2]; 3]`
/// 2D array stored in column major order.
/// If your data is in row major order you will need to `transpose` the returned
/// matrix.
#[inline]
#[must_use]
pub fn from_cols_array_2d(m: &[[f32; 2]; 3]) -> Self {
Self {
matrix2: Mat2::from_cols(m[0].into(), m[1].into()),
translation: m[2].into(),
}
}
/// Creates a `[[f32; 2]; 3]` 2D array storing data in
/// column major order.
/// If you require data in row major order `transpose` the matrix first.
#[inline]
#[must_use]
pub fn to_cols_array_2d(&self) -> [[f32; 2]; 3] {
[
self.matrix2.x_axis.into(),
self.matrix2.y_axis.into(),
self.translation.into(),
]
}
/// Creates an affine transform from the first 6 values in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 6 elements long.
#[inline]
#[must_use]
pub fn from_cols_slice(slice: &[f32]) -> Self {
Self {
matrix2: Mat2::from_cols_slice(&slice[0..4]),
translation: Vec2::from_slice(&slice[4..6]),
}
}
/// Writes the columns of `self` to the first 6 elements in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 6 elements long.
#[inline]
pub fn write_cols_to_slice(self, slice: &mut [f32]) {
self.matrix2.write_cols_to_slice(&mut slice[0..4]);
self.translation.write_to_slice(&mut slice[4..6]);
}
/// Creates an affine transform that changes scale.
/// Note that if any scale is zero the transform will be non-invertible.
#[inline]
#[must_use]
pub fn from_scale(scale: Vec2) -> Self {
Self {
matrix2: Mat2::from_diagonal(scale),
translation: Vec2::ZERO,
}
}
/// Creates an affine transform from the given rotation `angle`.
#[inline]
#[must_use]
pub fn from_angle(angle: f32) -> Self {
Self {
matrix2: Mat2::from_angle(angle),
translation: Vec2::ZERO,
}
}
/// Creates an affine transformation from the given 2D `translation`.
#[inline]
#[must_use]
pub fn from_translation(translation: Vec2) -> Self {
Self {
matrix2: Mat2::IDENTITY,
translation,
}
}
/// Creates an affine transform from a 2x2 matrix (expressing scale, shear and rotation)
#[inline]
#[must_use]
pub fn from_mat2(matrix2: Mat2) -> Self {
Self {
matrix2,
translation: Vec2::ZERO,
}
}
/// Creates an affine transform from a 2x2 matrix (expressing scale, shear and rotation) and a
/// translation vector.
///
/// Equivalent to
/// `Affine2::from_translation(translation) * Affine2::from_mat2(mat2)`
#[inline]
#[must_use]
pub fn from_mat2_translation(matrix2: Mat2, translation: Vec2) -> Self {
Self {
matrix2,
translation,
}
}
/// Creates an affine transform from the given 2D `scale`, rotation `angle` (in radians) and
/// `translation`.
///
/// Equivalent to `Affine2::from_translation(translation) *
/// Affine2::from_angle(angle) * Affine2::from_scale(scale)`
#[inline]
#[must_use]
pub fn from_scale_angle_translation(scale: Vec2, angle: f32, translation: Vec2) -> Self {
let rotation = Mat2::from_angle(angle);
Self {
matrix2: Mat2::from_cols(rotation.x_axis * scale.x, rotation.y_axis * scale.y),
translation,
}
}
/// Creates an affine transform from the given 2D rotation `angle` (in radians) and
/// `translation`.
///
/// Equivalent to `Affine2::from_translation(translation) * Affine2::from_angle(angle)`
#[inline]
#[must_use]
pub fn from_angle_translation(angle: f32, translation: Vec2) -> Self {
Self {
matrix2: Mat2::from_angle(angle),
translation,
}
}
/// The given `Mat3` must be an affine transform,
#[inline]
#[must_use]
pub fn from_mat3(m: Mat3) -> Self {
use crate::swizzles::Vec3Swizzles;
Self {
matrix2: Mat2::from_cols(m.x_axis.xy(), m.y_axis.xy()),
translation: m.z_axis.xy(),
}
}
/// The given [`Mat3A`] must be an affine transform,
#[inline]
#[must_use]
pub fn from_mat3a(m: Mat3A) -> Self {
use crate::swizzles::Vec3Swizzles;
Self {
matrix2: Mat2::from_cols(m.x_axis.xy(), m.y_axis.xy()),
translation: m.z_axis.xy(),
}
}
/// Extracts `scale`, `angle` and `translation` from `self`.
///
/// The transform is expected to be non-degenerate and without shearing, or the output
/// will be invalid.
///
/// # Panics
///
/// Will panic if the determinant `self.matrix2` is zero or if the resulting scale
/// vector contains any zero elements when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn to_scale_angle_translation(self) -> (Vec2, f32, Vec2) {
use crate::f32::math;
let det = self.matrix2.determinant();
glam_assert!(det != 0.0);
let scale = Vec2::new(
self.matrix2.x_axis.length() * math::signum(det),
self.matrix2.y_axis.length(),
);
glam_assert!(scale.cmpne(Vec2::ZERO).all());
let angle = math::atan2(-self.matrix2.y_axis.x, self.matrix2.y_axis.y);
(scale, angle, self.translation)
}
/// Transforms the given 2D point, applying shear, scale, rotation and translation.
#[inline]
#[must_use]
pub fn transform_point2(&self, rhs: Vec2) -> Vec2 {
self.matrix2 * rhs + self.translation
}
/// Transforms the given 2D vector, applying shear, scale and rotation (but NOT
/// translation).
///
/// To also apply translation, use [`Self::transform_point2()`] instead.
#[inline]
pub fn transform_vector2(&self, rhs: Vec2) -> Vec2 {
self.matrix2 * rhs
}
/// Returns `true` if, and only if, all elements are finite.
///
/// If any element is either `NaN`, positive or negative infinity, this will return
/// `false`.
#[inline]
#[must_use]
pub fn is_finite(&self) -> bool {
self.matrix2.is_finite() && self.translation.is_finite()
}
/// Returns `true` if any elements are `NaN`.
#[inline]
#[must_use]
pub fn is_nan(&self) -> bool {
self.matrix2.is_nan() || self.translation.is_nan()
}
/// Returns true if the absolute difference of all elements between `self` and `rhs`
/// is less than or equal to `max_abs_diff`.
///
/// This can be used to compare if two 3x4 matrices contain similar elements. It works
/// best when comparing with a known value. The `max_abs_diff` that should be used used
/// depends on the values being compared against.
///
/// For more see
/// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
#[inline]
#[must_use]
pub fn abs_diff_eq(&self, rhs: Self, max_abs_diff: f32) -> bool {
self.matrix2.abs_diff_eq(rhs.matrix2, max_abs_diff)
&& self.translation.abs_diff_eq(rhs.translation, max_abs_diff)
}
/// Return the inverse of this transform.
///
/// Note that if the transform is not invertible the result will be invalid.
#[inline]
#[must_use]
pub fn inverse(&self) -> Self {
let matrix2 = self.matrix2.inverse();
// transform negative translation by the matrix inverse:
let translation = -(matrix2 * self.translation);
Self {
matrix2,
translation,
}
}
}
impl Default for Affine2 {
#[inline(always)]
fn default() -> Self {
Self::IDENTITY
}
}
impl Deref for Affine2 {
type Target = crate::deref::Cols3<Vec2>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*(self as *const Self as *const Self::Target) }
}
}
impl DerefMut for Affine2 {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { &mut *(self as *mut Self as *mut Self::Target) }
}
}
impl PartialEq for Affine2 {
#[inline]
fn eq(&self, rhs: &Self) -> bool {
self.matrix2.eq(&rhs.matrix2) && self.translation.eq(&rhs.translation)
}
}
impl core::fmt::Debug for Affine2 {
fn fmt(&self, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
fmt.debug_struct(stringify!(Affine2))
.field("matrix2", &self.matrix2)
.field("translation", &self.translation)
.finish()
}
}
impl core::fmt::Display for Affine2 {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
if let Some(p) = f.precision() {
write!(
f,
"[{:.*}, {:.*}, {:.*}]",
p, self.matrix2.x_axis, p, self.matrix2.y_axis, p, self.translation
)
} else {
write!(
f,
"[{}, {}, {}]",
self.matrix2.x_axis, self.matrix2.y_axis, self.translation
)
}
}
}
impl<'a> core::iter::Product<&'a Self> for Affine2 {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::IDENTITY, |a, &b| a * b)
}
}
impl Mul for Affine2 {
type Output = Affine2;
#[inline]
fn mul(self, rhs: Affine2) -> Self::Output {
Self {
matrix2: self.matrix2 * rhs.matrix2,
translation: self.matrix2 * rhs.translation + self.translation,
}
}
}
impl MulAssign for Affine2 {
#[inline]
fn mul_assign(&mut self, rhs: Affine2) {
*self = self.mul(rhs);
}
}
impl From<Affine2> for Mat3 {
#[inline]
fn from(m: Affine2) -> Mat3 {
Self::from_cols(
m.matrix2.x_axis.extend(0.0),
m.matrix2.y_axis.extend(0.0),
m.translation.extend(1.0),
)
}
}
impl Mul<Mat3> for Affine2 {
type Output = Mat3;
#[inline]
fn mul(self, rhs: Mat3) -> Self::Output {
Mat3::from(self) * rhs
}
}
impl Mul<Affine2> for Mat3 {
type Output = Mat3;
#[inline]
fn mul(self, rhs: Affine2) -> Self::Output {
self * Mat3::from(rhs)
}
}
impl From<Affine2> for Mat3A {
#[inline]
fn from(m: Affine2) -> Mat3A {
Self::from_cols(
Vec3A::from((m.matrix2.x_axis, 0.0)),
Vec3A::from((m.matrix2.y_axis, 0.0)),
Vec3A::from((m.translation, 1.0)),
)
}
}
impl Mul<Mat3A> for Affine2 {
type Output = Mat3A;
#[inline]
fn mul(self, rhs: Mat3A) -> Self::Output {
Mat3A::from(self) * rhs
}
}
impl Mul<Affine2> for Mat3A {
type Output = Mat3A;
#[inline]
fn mul(self, rhs: Affine2) -> Self::Output {
self * Mat3A::from(rhs)
}
}
+581
View File
@@ -0,0 +1,581 @@
// Generated from affine.rs.tera template. Edit the template, not the generated file.
use crate::{Mat3, Mat3A, Mat4, Quat, Vec3, Vec3A};
use core::ops::{Deref, DerefMut, Mul, MulAssign};
/// A 3D affine transform, which can represent translation, rotation, scaling and shear.
///
/// This type is 16 byte aligned.
#[derive(Copy, Clone)]
#[repr(C)]
pub struct Affine3A {
pub matrix3: Mat3A,
pub translation: Vec3A,
}
impl Affine3A {
/// The degenerate zero transform.
///
/// This transforms any finite vector and point to zero.
/// The zero transform is non-invertible.
pub const ZERO: Self = Self {
matrix3: Mat3A::ZERO,
translation: Vec3A::ZERO,
};
/// The identity transform.
///
/// Multiplying a vector with this returns the same vector.
pub const IDENTITY: Self = Self {
matrix3: Mat3A::IDENTITY,
translation: Vec3A::ZERO,
};
/// All NAN:s.
pub const NAN: Self = Self {
matrix3: Mat3A::NAN,
translation: Vec3A::NAN,
};
/// Creates an affine transform from three column vectors.
#[inline(always)]
#[must_use]
pub const fn from_cols(x_axis: Vec3A, y_axis: Vec3A, z_axis: Vec3A, w_axis: Vec3A) -> Self {
Self {
matrix3: Mat3A::from_cols(x_axis, y_axis, z_axis),
translation: w_axis,
}
}
/// Creates an affine transform from a `[f32; 12]` array stored in column major order.
#[inline]
#[must_use]
pub fn from_cols_array(m: &[f32; 12]) -> Self {
Self {
matrix3: Mat3A::from_cols_array(&[
m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8],
]),
translation: Vec3A::from_array([m[9], m[10], m[11]]),
}
}
/// Creates a `[f32; 12]` array storing data in column major order.
#[inline]
#[must_use]
pub fn to_cols_array(&self) -> [f32; 12] {
let x = &self.matrix3.x_axis;
let y = &self.matrix3.y_axis;
let z = &self.matrix3.z_axis;
let w = &self.translation;
[x.x, x.y, x.z, y.x, y.y, y.z, z.x, z.y, z.z, w.x, w.y, w.z]
}
/// Creates an affine transform from a `[[f32; 3]; 4]`
/// 3D array stored in column major order.
/// If your data is in row major order you will need to `transpose` the returned
/// matrix.
#[inline]
#[must_use]
pub fn from_cols_array_2d(m: &[[f32; 3]; 4]) -> Self {
Self {
matrix3: Mat3A::from_cols(m[0].into(), m[1].into(), m[2].into()),
translation: m[3].into(),
}
}
/// Creates a `[[f32; 3]; 4]` 3D array storing data in
/// column major order.
/// If you require data in row major order `transpose` the matrix first.
#[inline]
#[must_use]
pub fn to_cols_array_2d(&self) -> [[f32; 3]; 4] {
[
self.matrix3.x_axis.into(),
self.matrix3.y_axis.into(),
self.matrix3.z_axis.into(),
self.translation.into(),
]
}
/// Creates an affine transform from the first 12 values in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 12 elements long.
#[inline]
#[must_use]
pub fn from_cols_slice(slice: &[f32]) -> Self {
Self {
matrix3: Mat3A::from_cols_slice(&slice[0..9]),
translation: Vec3A::from_slice(&slice[9..12]),
}
}
/// Writes the columns of `self` to the first 12 elements in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 12 elements long.
#[inline]
pub fn write_cols_to_slice(self, slice: &mut [f32]) {
self.matrix3.write_cols_to_slice(&mut slice[0..9]);
self.translation.write_to_slice(&mut slice[9..12]);
}
/// Creates an affine transform that changes scale.
/// Note that if any scale is zero the transform will be non-invertible.
#[inline]
#[must_use]
pub fn from_scale(scale: Vec3) -> Self {
Self {
matrix3: Mat3A::from_diagonal(scale),
translation: Vec3A::ZERO,
}
}
/// Creates an affine transform from the given `rotation` quaternion.
#[inline]
#[must_use]
pub fn from_quat(rotation: Quat) -> Self {
Self {
matrix3: Mat3A::from_quat(rotation),
translation: Vec3A::ZERO,
}
}
/// Creates an affine transform containing a 3D rotation around a normalized
/// rotation `axis` of `angle` (in radians).
#[inline]
#[must_use]
pub fn from_axis_angle(axis: Vec3, angle: f32) -> Self {
Self {
matrix3: Mat3A::from_axis_angle(axis, angle),
translation: Vec3A::ZERO,
}
}
/// Creates an affine transform containing a 3D rotation around the x axis of
/// `angle` (in radians).
#[inline]
#[must_use]
pub fn from_rotation_x(angle: f32) -> Self {
Self {
matrix3: Mat3A::from_rotation_x(angle),
translation: Vec3A::ZERO,
}
}
/// Creates an affine transform containing a 3D rotation around the y axis of
/// `angle` (in radians).
#[inline]
#[must_use]
pub fn from_rotation_y(angle: f32) -> Self {
Self {
matrix3: Mat3A::from_rotation_y(angle),
translation: Vec3A::ZERO,
}
}
/// Creates an affine transform containing a 3D rotation around the z axis of
/// `angle` (in radians).
#[inline]
#[must_use]
pub fn from_rotation_z(angle: f32) -> Self {
Self {
matrix3: Mat3A::from_rotation_z(angle),
translation: Vec3A::ZERO,
}
}
/// Creates an affine transformation from the given 3D `translation`.
#[inline]
#[must_use]
pub fn from_translation(translation: Vec3) -> Self {
#[allow(clippy::useless_conversion)]
Self {
matrix3: Mat3A::IDENTITY,
translation: translation.into(),
}
}
/// Creates an affine transform from a 3x3 matrix (expressing scale, shear and
/// rotation)
#[inline]
#[must_use]
pub fn from_mat3(mat3: Mat3) -> Self {
#[allow(clippy::useless_conversion)]
Self {
matrix3: mat3.into(),
translation: Vec3A::ZERO,
}
}
/// Creates an affine transform from a 3x3 matrix (expressing scale, shear and rotation)
/// and a translation vector.
///
/// Equivalent to `Affine3A::from_translation(translation) * Affine3A::from_mat3(mat3)`
#[inline]
#[must_use]
pub fn from_mat3_translation(mat3: Mat3, translation: Vec3) -> Self {
#[allow(clippy::useless_conversion)]
Self {
matrix3: mat3.into(),
translation: translation.into(),
}
}
/// Creates an affine transform from the given 3D `scale`, `rotation` and
/// `translation`.
///
/// Equivalent to `Affine3A::from_translation(translation) *
/// Affine3A::from_quat(rotation) * Affine3A::from_scale(scale)`
#[inline]
#[must_use]
pub fn from_scale_rotation_translation(scale: Vec3, rotation: Quat, translation: Vec3) -> Self {
let rotation = Mat3A::from_quat(rotation);
#[allow(clippy::useless_conversion)]
Self {
matrix3: Mat3A::from_cols(
rotation.x_axis * scale.x,
rotation.y_axis * scale.y,
rotation.z_axis * scale.z,
),
translation: translation.into(),
}
}
/// Creates an affine transform from the given 3D `rotation` and `translation`.
///
/// Equivalent to `Affine3A::from_translation(translation) * Affine3A::from_quat(rotation)`
#[inline]
#[must_use]
pub fn from_rotation_translation(rotation: Quat, translation: Vec3) -> Self {
#[allow(clippy::useless_conversion)]
Self {
matrix3: Mat3A::from_quat(rotation),
translation: translation.into(),
}
}
/// The given `Mat4` must be an affine transform,
/// i.e. contain no perspective transform.
#[inline]
#[must_use]
pub fn from_mat4(m: Mat4) -> Self {
Self {
matrix3: Mat3A::from_cols(
Vec3A::from_vec4(m.x_axis),
Vec3A::from_vec4(m.y_axis),
Vec3A::from_vec4(m.z_axis),
),
translation: Vec3A::from_vec4(m.w_axis),
}
}
/// Extracts `scale`, `rotation` and `translation` from `self`.
///
/// The transform is expected to be non-degenerate and without shearing, or the output
/// will be invalid.
///
/// # Panics
///
/// Will panic if the determinant `self.matrix3` is zero or if the resulting scale
/// vector contains any zero elements when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn to_scale_rotation_translation(&self) -> (Vec3, Quat, Vec3) {
use crate::f32::math;
let det = self.matrix3.determinant();
glam_assert!(det != 0.0);
let scale = Vec3::new(
self.matrix3.x_axis.length() * math::signum(det),
self.matrix3.y_axis.length(),
self.matrix3.z_axis.length(),
);
glam_assert!(scale.cmpne(Vec3::ZERO).all());
let inv_scale = scale.recip();
#[allow(clippy::useless_conversion)]
let rotation = Quat::from_mat3(&Mat3::from_cols(
(self.matrix3.x_axis * inv_scale.x).into(),
(self.matrix3.y_axis * inv_scale.y).into(),
(self.matrix3.z_axis * inv_scale.z).into(),
));
#[allow(clippy::useless_conversion)]
(scale, rotation, self.translation.into())
}
/// Creates a left-handed view transform using a camera position, an up direction, and a facing
/// direction.
///
/// For a view coordinate system with `+X=right`, `+Y=up` and `+Z=forward`.
#[inline]
#[must_use]
pub fn look_to_lh(eye: Vec3, dir: Vec3, up: Vec3) -> Self {
Self::look_to_rh(eye, -dir, up)
}
/// Creates a right-handed view transform using a camera position, an up direction, and a facing
/// direction.
///
/// For a view coordinate system with `+X=right`, `+Y=up` and `+Z=back`.
#[inline]
#[must_use]
pub fn look_to_rh(eye: Vec3, dir: Vec3, up: Vec3) -> Self {
let f = dir.normalize();
let s = f.cross(up).normalize();
let u = s.cross(f);
Self {
matrix3: Mat3A::from_cols(
Vec3A::new(s.x, u.x, -f.x),
Vec3A::new(s.y, u.y, -f.y),
Vec3A::new(s.z, u.z, -f.z),
),
translation: Vec3A::new(-eye.dot(s), -eye.dot(u), eye.dot(f)),
}
}
/// Creates a left-handed view transform using a camera position, an up direction, and a focal
/// point.
/// For a view coordinate system with `+X=right`, `+Y=up` and `+Z=forward`.
///
/// # Panics
///
/// Will panic if `up` is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn look_at_lh(eye: Vec3, center: Vec3, up: Vec3) -> Self {
glam_assert!(up.is_normalized());
Self::look_to_lh(eye, center - eye, up)
}
/// Creates a right-handed view transform using a camera position, an up direction, and a focal
/// point.
/// For a view coordinate system with `+X=right`, `+Y=up` and `+Z=back`.
///
/// # Panics
///
/// Will panic if `up` is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn look_at_rh(eye: Vec3, center: Vec3, up: Vec3) -> Self {
glam_assert!(up.is_normalized());
Self::look_to_rh(eye, center - eye, up)
}
/// Transforms the given 3D points, applying shear, scale, rotation and translation.
#[inline]
pub fn transform_point3(&self, rhs: Vec3) -> Vec3 {
#[allow(clippy::useless_conversion)]
((self.matrix3.x_axis * rhs.x)
+ (self.matrix3.y_axis * rhs.y)
+ (self.matrix3.z_axis * rhs.z)
+ self.translation)
.into()
}
/// Transforms the given 3D vector, applying shear, scale and rotation (but NOT
/// translation).
///
/// To also apply translation, use [`Self::transform_point3()`] instead.
#[inline]
#[must_use]
pub fn transform_vector3(&self, rhs: Vec3) -> Vec3 {
#[allow(clippy::useless_conversion)]
((self.matrix3.x_axis * rhs.x)
+ (self.matrix3.y_axis * rhs.y)
+ (self.matrix3.z_axis * rhs.z))
.into()
}
/// Transforms the given [`Vec3A`], applying shear, scale, rotation and translation.
#[inline]
#[must_use]
pub fn transform_point3a(&self, rhs: Vec3A) -> Vec3A {
self.matrix3 * rhs + self.translation
}
/// Transforms the given [`Vec3A`], applying shear, scale and rotation (but NOT
/// translation).
///
/// To also apply translation, use [`Self::transform_point3a()`] instead.
#[inline]
#[must_use]
pub fn transform_vector3a(&self, rhs: Vec3A) -> Vec3A {
self.matrix3 * rhs
}
/// Returns `true` if, and only if, all elements are finite.
///
/// If any element is either `NaN`, positive or negative infinity, this will return
/// `false`.
#[inline]
#[must_use]
pub fn is_finite(&self) -> bool {
self.matrix3.is_finite() && self.translation.is_finite()
}
/// Returns `true` if any elements are `NaN`.
#[inline]
#[must_use]
pub fn is_nan(&self) -> bool {
self.matrix3.is_nan() || self.translation.is_nan()
}
/// Returns true if the absolute difference of all elements between `self` and `rhs`
/// is less than or equal to `max_abs_diff`.
///
/// This can be used to compare if two 3x4 matrices contain similar elements. It works
/// best when comparing with a known value. The `max_abs_diff` that should be used used
/// depends on the values being compared against.
///
/// For more see
/// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
#[inline]
#[must_use]
pub fn abs_diff_eq(&self, rhs: Self, max_abs_diff: f32) -> bool {
self.matrix3.abs_diff_eq(rhs.matrix3, max_abs_diff)
&& self.translation.abs_diff_eq(rhs.translation, max_abs_diff)
}
/// Return the inverse of this transform.
///
/// Note that if the transform is not invertible the result will be invalid.
#[inline]
#[must_use]
pub fn inverse(&self) -> Self {
let matrix3 = self.matrix3.inverse();
// transform negative translation by the matrix inverse:
let translation = -(matrix3 * self.translation);
Self {
matrix3,
translation,
}
}
}
impl Default for Affine3A {
#[inline(always)]
fn default() -> Self {
Self::IDENTITY
}
}
impl Deref for Affine3A {
type Target = crate::deref::Cols4<Vec3A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*(self as *const Self as *const Self::Target) }
}
}
impl DerefMut for Affine3A {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { &mut *(self as *mut Self as *mut Self::Target) }
}
}
impl PartialEq for Affine3A {
#[inline]
fn eq(&self, rhs: &Self) -> bool {
self.matrix3.eq(&rhs.matrix3) && self.translation.eq(&rhs.translation)
}
}
impl core::fmt::Debug for Affine3A {
fn fmt(&self, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
fmt.debug_struct(stringify!(Affine3A))
.field("matrix3", &self.matrix3)
.field("translation", &self.translation)
.finish()
}
}
impl core::fmt::Display for Affine3A {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
if let Some(p) = f.precision() {
write!(
f,
"[{:.*}, {:.*}, {:.*}, {:.*}]",
p,
self.matrix3.x_axis,
p,
self.matrix3.y_axis,
p,
self.matrix3.z_axis,
p,
self.translation
)
} else {
write!(
f,
"[{}, {}, {}, {}]",
self.matrix3.x_axis, self.matrix3.y_axis, self.matrix3.z_axis, self.translation
)
}
}
}
impl<'a> core::iter::Product<&'a Self> for Affine3A {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::IDENTITY, |a, &b| a * b)
}
}
impl Mul for Affine3A {
type Output = Affine3A;
#[inline]
fn mul(self, rhs: Affine3A) -> Self::Output {
Self {
matrix3: self.matrix3 * rhs.matrix3,
translation: self.matrix3 * rhs.translation + self.translation,
}
}
}
impl MulAssign for Affine3A {
#[inline]
fn mul_assign(&mut self, rhs: Affine3A) {
*self = self.mul(rhs);
}
}
impl From<Affine3A> for Mat4 {
#[inline]
fn from(m: Affine3A) -> Mat4 {
Mat4::from_cols(
m.matrix3.x_axis.extend(0.0),
m.matrix3.y_axis.extend(0.0),
m.matrix3.z_axis.extend(0.0),
m.translation.extend(1.0),
)
}
}
impl Mul<Mat4> for Affine3A {
type Output = Mat4;
#[inline]
fn mul(self, rhs: Mat4) -> Self::Output {
Mat4::from(self) * rhs
}
}
impl Mul<Affine3A> for Mat4 {
type Output = Mat4;
#[inline]
fn mul(self, rhs: Affine3A) -> Self::Output {
self * Mat4::from(rhs)
}
}
+6
View File
@@ -0,0 +1,6 @@
pub mod mat2;
pub mod mat3a;
pub mod mat4;
pub mod quat;
pub mod vec3a;
pub mod vec4;
+582
View File
@@ -0,0 +1,582 @@
// Generated from mat.rs.tera template. Edit the template, not the generated file.
use crate::{f32::math, swizzles::*, DMat2, Mat3, Mat3A, Vec2};
use core::fmt;
use core::iter::{Product, Sum};
use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
use core::simd::*;
/// Creates a 2x2 matrix from two column vectors.
#[inline(always)]
#[must_use]
pub const fn mat2(x_axis: Vec2, y_axis: Vec2) -> Mat2 {
Mat2::from_cols(x_axis, y_axis)
}
/// A 2x2 column major matrix.
///
/// SIMD vector types are used for storage on supported platforms.
///
/// This type is 16 byte aligned.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct Mat2(pub(crate) f32x4);
impl Mat2 {
/// A 2x2 matrix with all elements set to `0.0`.
pub const ZERO: Self = Self::from_cols(Vec2::ZERO, Vec2::ZERO);
/// A 2x2 identity matrix, where all diagonal elements are `1`, and all off-diagonal elements are `0`.
pub const IDENTITY: Self = Self::from_cols(Vec2::X, Vec2::Y);
/// All NAN:s.
pub const NAN: Self = Self::from_cols(Vec2::NAN, Vec2::NAN);
#[allow(clippy::too_many_arguments)]
#[inline(always)]
#[must_use]
const fn new(m00: f32, m01: f32, m10: f32, m11: f32) -> Self {
Self(f32x4::from_array([m00, m01, m10, m11]))
}
/// Creates a 2x2 matrix from two column vectors.
#[inline(always)]
#[must_use]
pub const fn from_cols(x_axis: Vec2, y_axis: Vec2) -> Self {
Self(f32x4::from_array([x_axis.x, x_axis.y, y_axis.x, y_axis.y]))
}
/// Creates a 2x2 matrix from a `[f32; 4]` array stored in column major order.
/// If your data is stored in row major you will need to `transpose` the returned
/// matrix.
#[inline]
#[must_use]
pub const fn from_cols_array(m: &[f32; 4]) -> Self {
Self(f32x4::from_array(*m))
}
/// Creates a `[f32; 4]` array storing data in column major order.
/// If you require data in row major order `transpose` the matrix first.
#[inline]
#[must_use]
pub const fn to_cols_array(&self) -> [f32; 4] {
unsafe { *(self as *const Self as *const [f32; 4]) }
}
/// Creates a 2x2 matrix from a `[[f32; 2]; 2]` 2D array stored in column major order.
/// If your data is in row major order you will need to `transpose` the returned
/// matrix.
#[inline]
#[must_use]
pub const fn from_cols_array_2d(m: &[[f32; 2]; 2]) -> Self {
Self::from_cols(Vec2::from_array(m[0]), Vec2::from_array(m[1]))
}
/// Creates a `[[f32; 2]; 2]` 2D array storing data in column major order.
/// If you require data in row major order `transpose` the matrix first.
#[inline]
#[must_use]
pub const fn to_cols_array_2d(&self) -> [[f32; 2]; 2] {
unsafe { *(self as *const Self as *const [[f32; 2]; 2]) }
}
/// Creates a 2x2 matrix with its diagonal set to `diagonal` and all other entries set to 0.
#[doc(alias = "scale")]
#[inline]
#[must_use]
pub const fn from_diagonal(diagonal: Vec2) -> Self {
Self::new(diagonal.x, 0.0, 0.0, diagonal.y)
}
/// Creates a 2x2 matrix containing the combining non-uniform `scale` and rotation of
/// `angle` (in radians).
#[inline]
#[must_use]
pub fn from_scale_angle(scale: Vec2, angle: f32) -> Self {
let (sin, cos) = math::sin_cos(angle);
Self::new(cos * scale.x, sin * scale.x, -sin * scale.y, cos * scale.y)
}
/// Creates a 2x2 matrix containing a rotation of `angle` (in radians).
#[inline]
#[must_use]
pub fn from_angle(angle: f32) -> Self {
let (sin, cos) = math::sin_cos(angle);
Self::new(cos, sin, -sin, cos)
}
/// Creates a 2x2 matrix from a 3x3 matrix, discarding the 2nd row and column.
#[inline]
#[must_use]
pub fn from_mat3(m: Mat3) -> Self {
Self::from_cols(m.x_axis.xy(), m.y_axis.xy())
}
/// Creates a 2x2 matrix from the minor of the given 3x3 matrix, discarding the `i`th column
/// and `j`th row.
///
/// # Panics
///
/// Panics if `i` or `j` is greater than 2.
#[inline]
#[must_use]
pub fn from_mat3_minor(m: Mat3, i: usize, j: usize) -> Self {
match (i, j) {
(0, 0) => Self::from_cols(m.y_axis.yz(), m.z_axis.yz()),
(0, 1) => Self::from_cols(m.y_axis.xz(), m.z_axis.xz()),
(0, 2) => Self::from_cols(m.y_axis.xy(), m.z_axis.xy()),
(1, 0) => Self::from_cols(m.x_axis.yz(), m.z_axis.yz()),
(1, 1) => Self::from_cols(m.x_axis.xz(), m.z_axis.xz()),
(1, 2) => Self::from_cols(m.x_axis.xy(), m.z_axis.xy()),
(2, 0) => Self::from_cols(m.x_axis.yz(), m.y_axis.yz()),
(2, 1) => Self::from_cols(m.x_axis.xz(), m.y_axis.xz()),
(2, 2) => Self::from_cols(m.x_axis.xy(), m.y_axis.xy()),
_ => panic!("index out of bounds"),
}
}
/// Creates a 2x2 matrix from a 3x3 matrix, discarding the 2nd row and column.
#[inline]
#[must_use]
pub fn from_mat3a(m: Mat3A) -> Self {
Self::from_cols(m.x_axis.xy(), m.y_axis.xy())
}
/// Creates a 2x2 matrix from the minor of the given 3x3 matrix, discarding the `i`th column
/// and `j`th row.
///
/// # Panics
///
/// Panics if `i` or `j` is greater than 2.
#[inline]
#[must_use]
pub fn from_mat3a_minor(m: Mat3A, i: usize, j: usize) -> Self {
match (i, j) {
(0, 0) => Self::from_cols(m.y_axis.yz(), m.z_axis.yz()),
(0, 1) => Self::from_cols(m.y_axis.xz(), m.z_axis.xz()),
(0, 2) => Self::from_cols(m.y_axis.xy(), m.z_axis.xy()),
(1, 0) => Self::from_cols(m.x_axis.yz(), m.z_axis.yz()),
(1, 1) => Self::from_cols(m.x_axis.xz(), m.z_axis.xz()),
(1, 2) => Self::from_cols(m.x_axis.xy(), m.z_axis.xy()),
(2, 0) => Self::from_cols(m.x_axis.yz(), m.y_axis.yz()),
(2, 1) => Self::from_cols(m.x_axis.xz(), m.y_axis.xz()),
(2, 2) => Self::from_cols(m.x_axis.xy(), m.y_axis.xy()),
_ => panic!("index out of bounds"),
}
}
/// Creates a 2x2 matrix from the first 4 values in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 4 elements long.
#[inline]
#[must_use]
pub const fn from_cols_slice(slice: &[f32]) -> Self {
Self::new(slice[0], slice[1], slice[2], slice[3])
}
/// Writes the columns of `self` to the first 4 elements in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 4 elements long.
#[inline]
pub fn write_cols_to_slice(self, slice: &mut [f32]) {
slice[0] = self.x_axis.x;
slice[1] = self.x_axis.y;
slice[2] = self.y_axis.x;
slice[3] = self.y_axis.y;
}
/// Returns the matrix column for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 1.
#[inline]
#[must_use]
pub fn col(&self, index: usize) -> Vec2 {
match index {
0 => self.x_axis,
1 => self.y_axis,
_ => panic!("index out of bounds"),
}
}
/// Returns a mutable reference to the matrix column for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 1.
#[inline]
pub fn col_mut(&mut self, index: usize) -> &mut Vec2 {
match index {
0 => &mut self.x_axis,
1 => &mut self.y_axis,
_ => panic!("index out of bounds"),
}
}
/// Returns the matrix row for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 1.
#[inline]
#[must_use]
pub fn row(&self, index: usize) -> Vec2 {
match index {
0 => Vec2::new(self.x_axis.x, self.y_axis.x),
1 => Vec2::new(self.x_axis.y, self.y_axis.y),
_ => panic!("index out of bounds"),
}
}
/// Returns `true` if, and only if, all elements are finite.
/// If any element is either `NaN`, positive or negative infinity, this will return `false`.
#[inline]
#[must_use]
pub fn is_finite(&self) -> bool {
self.x_axis.is_finite() && self.y_axis.is_finite()
}
/// Returns `true` if any elements are `NaN`.
#[inline]
#[must_use]
pub fn is_nan(&self) -> bool {
self.x_axis.is_nan() || self.y_axis.is_nan()
}
/// Returns the transpose of `self`.
#[inline]
#[must_use]
pub fn transpose(&self) -> Self {
Self(simd_swizzle!(self.0, [0, 2, 1, 3]))
}
/// Returns the determinant of `self`.
#[inline]
#[must_use]
pub fn determinant(&self) -> f32 {
let abcd = self.0;
let dcba = simd_swizzle!(abcd, [3, 2, 1, 0]);
let prod = abcd * dcba;
let det = prod - simd_swizzle!(prod, [1, 1, 1, 1]);
det[0]
}
/// Returns the inverse of `self`.
///
/// If the matrix is not invertible the returned matrix will be invalid.
///
/// # Panics
///
/// Will panic if the determinant of `self` is zero when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn inverse(&self) -> Self {
const SIGN: f32x4 = f32x4::from_array([1.0, -1.0, -1.0, 1.0]);
let abcd = self.0;
let dcba = simd_swizzle!(abcd, [3, 2, 1, 0]);
let prod = abcd * dcba;
let sub = prod - simd_swizzle!(prod, [1, 1, 1, 1]);
let det = simd_swizzle!(sub, [0, 0, 0, 0]);
let tmp = SIGN / det;
glam_assert!(Mat2(tmp).is_finite());
let dbca = simd_swizzle!(abcd, [3, 1, 2, 0]);
Self(dbca.mul(tmp))
}
/// Transforms a 2D vector.
#[inline]
#[must_use]
pub fn mul_vec2(&self, rhs: Vec2) -> Vec2 {
let abcd = self.0;
let xxyy = f32x4::from_array([rhs.x, rhs.x, rhs.y, rhs.y]);
let axbxcydy = abcd.mul(xxyy);
let cydyaxbx = simd_swizzle!(axbxcydy, [2, 3, 0, 1]);
let result = axbxcydy.add(cydyaxbx);
unsafe { *(&result as *const f32x4 as *const Vec2) }
}
/// Multiplies two 2x2 matrices.
#[inline]
#[must_use]
pub fn mul_mat2(&self, rhs: &Self) -> Self {
let abcd = self.0;
let xxyy0 = simd_swizzle!(rhs.0, [0, 0, 1, 1]);
let xxyy1 = simd_swizzle!(rhs.0, [2, 2, 3, 3]);
let axbxcydy0 = abcd * xxyy0;
let axbxcydy1 = abcd * xxyy1;
let cydyaxbx0 = simd_swizzle!(axbxcydy0, [2, 3, 0, 1]);
let cydyaxbx1 = simd_swizzle!(axbxcydy1, [2, 3, 0, 1]);
let result0 = axbxcydy0 + cydyaxbx0;
let result1 = axbxcydy1 + cydyaxbx1;
Self(simd_swizzle!(result0, result1, [0, 1, 4, 5]))
}
/// Adds two 2x2 matrices.
#[inline]
#[must_use]
pub fn add_mat2(&self, rhs: &Self) -> Self {
Self(self.0 + rhs.0)
}
/// Subtracts two 2x2 matrices.
#[inline]
#[must_use]
pub fn sub_mat2(&self, rhs: &Self) -> Self {
Self(self.0 - rhs.0)
}
/// Multiplies a 2x2 matrix by a scalar.
#[inline]
#[must_use]
pub fn mul_scalar(&self, rhs: f32) -> Self {
Self(self.0 * f32x4::splat(rhs))
}
/// Divides a 2x2 matrix by a scalar.
#[inline]
#[must_use]
pub fn div_scalar(&self, rhs: f32) -> Self {
Self(self.0 / f32x4::splat(rhs))
}
/// Returns true if the absolute difference of all elements between `self` and `rhs`
/// is less than or equal to `max_abs_diff`.
///
/// This can be used to compare if two matrices contain similar elements. It works best
/// when comparing with a known value. The `max_abs_diff` that should be used used
/// depends on the values being compared against.
///
/// For more see
/// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
#[inline]
#[must_use]
pub fn abs_diff_eq(&self, rhs: Self, max_abs_diff: f32) -> bool {
self.x_axis.abs_diff_eq(rhs.x_axis, max_abs_diff)
&& self.y_axis.abs_diff_eq(rhs.y_axis, max_abs_diff)
}
/// Takes the absolute value of each element in `self`
#[inline]
#[must_use]
pub fn abs(&self) -> Self {
Self::from_cols(self.x_axis.abs(), self.y_axis.abs())
}
#[inline]
pub fn as_dmat2(&self) -> DMat2 {
DMat2::from_cols(self.x_axis.as_dvec2(), self.y_axis.as_dvec2())
}
}
impl Default for Mat2 {
#[inline]
fn default() -> Self {
Self::IDENTITY
}
}
impl Add<Mat2> for Mat2 {
type Output = Self;
#[inline]
fn add(self, rhs: Self) -> Self::Output {
self.add_mat2(&rhs)
}
}
impl AddAssign<Mat2> for Mat2 {
#[inline]
fn add_assign(&mut self, rhs: Self) {
*self = self.add_mat2(&rhs);
}
}
impl Sub<Mat2> for Mat2 {
type Output = Self;
#[inline]
fn sub(self, rhs: Self) -> Self::Output {
self.sub_mat2(&rhs)
}
}
impl SubAssign<Mat2> for Mat2 {
#[inline]
fn sub_assign(&mut self, rhs: Self) {
*self = self.sub_mat2(&rhs);
}
}
impl Neg for Mat2 {
type Output = Self;
#[inline]
fn neg(self) -> Self::Output {
Self(-self.0)
}
}
impl Mul<Mat2> for Mat2 {
type Output = Self;
#[inline]
fn mul(self, rhs: Self) -> Self::Output {
self.mul_mat2(&rhs)
}
}
impl MulAssign<Mat2> for Mat2 {
#[inline]
fn mul_assign(&mut self, rhs: Self) {
*self = self.mul_mat2(&rhs);
}
}
impl Mul<Vec2> for Mat2 {
type Output = Vec2;
#[inline]
fn mul(self, rhs: Vec2) -> Self::Output {
self.mul_vec2(rhs)
}
}
impl Mul<Mat2> for f32 {
type Output = Mat2;
#[inline]
fn mul(self, rhs: Mat2) -> Self::Output {
rhs.mul_scalar(self)
}
}
impl Mul<f32> for Mat2 {
type Output = Self;
#[inline]
fn mul(self, rhs: f32) -> Self::Output {
self.mul_scalar(rhs)
}
}
impl MulAssign<f32> for Mat2 {
#[inline]
fn mul_assign(&mut self, rhs: f32) {
*self = self.mul_scalar(rhs);
}
}
impl Div<Mat2> for f32 {
type Output = Mat2;
#[inline]
fn div(self, rhs: Mat2) -> Self::Output {
rhs.div_scalar(self)
}
}
impl Div<f32> for Mat2 {
type Output = Self;
#[inline]
fn div(self, rhs: f32) -> Self::Output {
self.div_scalar(rhs)
}
}
impl DivAssign<f32> for Mat2 {
#[inline]
fn div_assign(&mut self, rhs: f32) {
*self = self.div_scalar(rhs);
}
}
impl Sum<Self> for Mat2 {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Self::ZERO, Self::add)
}
}
impl<'a> Sum<&'a Self> for Mat2 {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
}
}
impl Product for Mat2 {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Self::IDENTITY, Self::mul)
}
}
impl<'a> Product<&'a Self> for Mat2 {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::IDENTITY, |a, &b| Self::mul(a, b))
}
}
impl PartialEq for Mat2 {
#[inline]
fn eq(&self, rhs: &Self) -> bool {
self.x_axis.eq(&rhs.x_axis) && self.y_axis.eq(&rhs.y_axis)
}
}
#[cfg(not(target_arch = "spirv"))]
impl AsRef<[f32; 4]> for Mat2 {
#[inline]
fn as_ref(&self) -> &[f32; 4] {
unsafe { &*(self as *const Self as *const [f32; 4]) }
}
}
#[cfg(not(target_arch = "spirv"))]
impl AsMut<[f32; 4]> for Mat2 {
#[inline]
fn as_mut(&mut self) -> &mut [f32; 4] {
unsafe { &mut *(self as *mut Self as *mut [f32; 4]) }
}
}
impl core::ops::Deref for Mat2 {
type Target = crate::deref::Cols2<Vec2>;
#[inline]
fn deref(&self) -> &Self::Target {
unsafe { &*(self as *const Self as *const Self::Target) }
}
}
impl core::ops::DerefMut for Mat2 {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { &mut *(self as *mut Self as *mut Self::Target) }
}
}
impl fmt::Debug for Mat2 {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct(stringify!(Mat2))
.field("x_axis", &self.x_axis)
.field("y_axis", &self.y_axis)
.finish()
}
}
impl fmt::Display for Mat2 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(p) = f.precision() {
write!(f, "[{:.*}, {:.*}]", p, self.x_axis, p, self.y_axis)
} else {
write!(f, "[{}, {}]", self.x_axis, self.y_axis)
}
}
}
+926
View File
@@ -0,0 +1,926 @@
// Generated from mat.rs.tera template. Edit the template, not the generated file.
use crate::{
euler::{FromEuler, ToEuler},
f32::math,
swizzles::*,
DMat3, EulerRot, Mat2, Mat3, Mat4, Quat, Vec2, Vec3, Vec3A,
};
use core::fmt;
use core::iter::{Product, Sum};
use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
use core::simd::*;
/// Creates a 3x3 matrix from three column vectors.
#[inline(always)]
#[must_use]
pub const fn mat3a(x_axis: Vec3A, y_axis: Vec3A, z_axis: Vec3A) -> Mat3A {
Mat3A::from_cols(x_axis, y_axis, z_axis)
}
/// A 3x3 column major matrix.
///
/// This 3x3 matrix type features convenience methods for creating and using linear and
/// affine transformations. If you are primarily dealing with 2D affine transformations the
/// [`Affine2`](crate::Affine2) type is much faster and more space efficient than
/// using a 3x3 matrix.
///
/// Linear transformations including 3D rotation and scale can be created using methods
/// such as [`Self::from_diagonal()`], [`Self::from_quat()`], [`Self::from_axis_angle()`],
/// [`Self::from_rotation_x()`], [`Self::from_rotation_y()`], or
/// [`Self::from_rotation_z()`].
///
/// The resulting matrices can be use to transform 3D vectors using regular vector
/// multiplication.
///
/// Affine transformations including 2D translation, rotation and scale can be created
/// using methods such as [`Self::from_translation()`], [`Self::from_angle()`],
/// [`Self::from_scale()`] and [`Self::from_scale_angle_translation()`].
///
/// The [`Self::transform_point2()`] and [`Self::transform_vector2()`] convenience methods
/// are provided for performing affine transforms on 2D vectors and points. These multiply
/// 2D inputs as 3D vectors with an implicit `z` value of `1` for points and `0` for
/// vectors respectively. These methods assume that `Self` contains a valid affine
/// transform.
#[derive(Clone, Copy)]
#[repr(C)]
pub struct Mat3A {
pub x_axis: Vec3A,
pub y_axis: Vec3A,
pub z_axis: Vec3A,
}
impl Mat3A {
/// A 3x3 matrix with all elements set to `0.0`.
pub const ZERO: Self = Self::from_cols(Vec3A::ZERO, Vec3A::ZERO, Vec3A::ZERO);
/// A 3x3 identity matrix, where all diagonal elements are `1`, and all off-diagonal elements are `0`.
pub const IDENTITY: Self = Self::from_cols(Vec3A::X, Vec3A::Y, Vec3A::Z);
/// All NAN:s.
pub const NAN: Self = Self::from_cols(Vec3A::NAN, Vec3A::NAN, Vec3A::NAN);
#[allow(clippy::too_many_arguments)]
#[inline(always)]
#[must_use]
const fn new(
m00: f32,
m01: f32,
m02: f32,
m10: f32,
m11: f32,
m12: f32,
m20: f32,
m21: f32,
m22: f32,
) -> Self {
Self {
x_axis: Vec3A::new(m00, m01, m02),
y_axis: Vec3A::new(m10, m11, m12),
z_axis: Vec3A::new(m20, m21, m22),
}
}
/// Creates a 3x3 matrix from three column vectors.
#[inline(always)]
#[must_use]
pub const fn from_cols(x_axis: Vec3A, y_axis: Vec3A, z_axis: Vec3A) -> Self {
Self {
x_axis,
y_axis,
z_axis,
}
}
/// Creates a 3x3 matrix from a `[f32; 9]` array stored in column major order.
/// If your data is stored in row major you will need to `transpose` the returned
/// matrix.
#[inline]
#[must_use]
pub const fn from_cols_array(m: &[f32; 9]) -> Self {
Self::new(m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8])
}
/// Creates a `[f32; 9]` array storing data in column major order.
/// If you require data in row major order `transpose` the matrix first.
#[inline]
#[must_use]
pub const fn to_cols_array(&self) -> [f32; 9] {
let [x_axis_x, x_axis_y, x_axis_z] = self.x_axis.to_array();
let [y_axis_x, y_axis_y, y_axis_z] = self.y_axis.to_array();
let [z_axis_x, z_axis_y, z_axis_z] = self.z_axis.to_array();
[
x_axis_x, x_axis_y, x_axis_z, y_axis_x, y_axis_y, y_axis_z, z_axis_x, z_axis_y,
z_axis_z,
]
}
/// Creates a 3x3 matrix from a `[[f32; 3]; 3]` 3D array stored in column major order.
/// If your data is in row major order you will need to `transpose` the returned
/// matrix.
#[inline]
#[must_use]
pub const fn from_cols_array_2d(m: &[[f32; 3]; 3]) -> Self {
Self::from_cols(
Vec3A::from_array(m[0]),
Vec3A::from_array(m[1]),
Vec3A::from_array(m[2]),
)
}
/// Creates a `[[f32; 3]; 3]` 3D array storing data in column major order.
/// If you require data in row major order `transpose` the matrix first.
#[inline]
#[must_use]
pub const fn to_cols_array_2d(&self) -> [[f32; 3]; 3] {
[
self.x_axis.to_array(),
self.y_axis.to_array(),
self.z_axis.to_array(),
]
}
/// Creates a 3x3 matrix with its diagonal set to `diagonal` and all other entries set to 0.
#[doc(alias = "scale")]
#[inline]
#[must_use]
pub const fn from_diagonal(diagonal: Vec3) -> Self {
Self::new(
diagonal.x, 0.0, 0.0, 0.0, diagonal.y, 0.0, 0.0, 0.0, diagonal.z,
)
}
/// Creates a 3x3 matrix from a 4x4 matrix, discarding the 4th row and column.
#[inline]
#[must_use]
pub fn from_mat4(m: Mat4) -> Self {
Self::from_cols(
Vec3A::from_vec4(m.x_axis),
Vec3A::from_vec4(m.y_axis),
Vec3A::from_vec4(m.z_axis),
)
}
/// Creates a 3x3 matrix from the minor of the given 4x4 matrix, discarding the `i`th column
/// and `j`th row.
///
/// # Panics
///
/// Panics if `i` or `j` is greater than 3.
#[inline]
#[must_use]
pub fn from_mat4_minor(m: Mat4, i: usize, j: usize) -> Self {
match (i, j) {
(0, 0) => Self::from_cols(
Vec3A::from_vec4(m.y_axis.yzww()),
Vec3A::from_vec4(m.z_axis.yzww()),
Vec3A::from_vec4(m.w_axis.yzww()),
),
(0, 1) => Self::from_cols(
Vec3A::from_vec4(m.y_axis.xzww()),
Vec3A::from_vec4(m.z_axis.xzww()),
Vec3A::from_vec4(m.w_axis.xzww()),
),
(0, 2) => Self::from_cols(
Vec3A::from_vec4(m.y_axis.xyww()),
Vec3A::from_vec4(m.z_axis.xyww()),
Vec3A::from_vec4(m.w_axis.xyww()),
),
(0, 3) => Self::from_cols(
Vec3A::from_vec4(m.y_axis.xyzw()),
Vec3A::from_vec4(m.z_axis.xyzw()),
Vec3A::from_vec4(m.w_axis.xyzw()),
),
(1, 0) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.yzww()),
Vec3A::from_vec4(m.z_axis.yzww()),
Vec3A::from_vec4(m.w_axis.yzww()),
),
(1, 1) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xzww()),
Vec3A::from_vec4(m.z_axis.xzww()),
Vec3A::from_vec4(m.w_axis.xzww()),
),
(1, 2) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xyww()),
Vec3A::from_vec4(m.z_axis.xyww()),
Vec3A::from_vec4(m.w_axis.xyww()),
),
(1, 3) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xyzw()),
Vec3A::from_vec4(m.z_axis.xyzw()),
Vec3A::from_vec4(m.w_axis.xyzw()),
),
(2, 0) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.yzww()),
Vec3A::from_vec4(m.y_axis.yzww()),
Vec3A::from_vec4(m.w_axis.yzww()),
),
(2, 1) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xzww()),
Vec3A::from_vec4(m.y_axis.xzww()),
Vec3A::from_vec4(m.w_axis.xzww()),
),
(2, 2) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xyww()),
Vec3A::from_vec4(m.y_axis.xyww()),
Vec3A::from_vec4(m.w_axis.xyww()),
),
(2, 3) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xyzw()),
Vec3A::from_vec4(m.y_axis.xyzw()),
Vec3A::from_vec4(m.w_axis.xyzw()),
),
(3, 0) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.yzww()),
Vec3A::from_vec4(m.y_axis.yzww()),
Vec3A::from_vec4(m.z_axis.yzww()),
),
(3, 1) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xzww()),
Vec3A::from_vec4(m.y_axis.xzww()),
Vec3A::from_vec4(m.z_axis.xzww()),
),
(3, 2) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xyww()),
Vec3A::from_vec4(m.y_axis.xyww()),
Vec3A::from_vec4(m.z_axis.xyww()),
),
(3, 3) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xyzw()),
Vec3A::from_vec4(m.y_axis.xyzw()),
Vec3A::from_vec4(m.z_axis.xyzw()),
),
_ => panic!("index out of bounds"),
}
}
/// Creates a 3D rotation matrix from the given quaternion.
///
/// # Panics
///
/// Will panic if `rotation` is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn from_quat(rotation: Quat) -> Self {
glam_assert!(rotation.is_normalized());
let x2 = rotation.x + rotation.x;
let y2 = rotation.y + rotation.y;
let z2 = rotation.z + rotation.z;
let xx = rotation.x * x2;
let xy = rotation.x * y2;
let xz = rotation.x * z2;
let yy = rotation.y * y2;
let yz = rotation.y * z2;
let zz = rotation.z * z2;
let wx = rotation.w * x2;
let wy = rotation.w * y2;
let wz = rotation.w * z2;
Self::from_cols(
Vec3A::new(1.0 - (yy + zz), xy + wz, xz - wy),
Vec3A::new(xy - wz, 1.0 - (xx + zz), yz + wx),
Vec3A::new(xz + wy, yz - wx, 1.0 - (xx + yy)),
)
}
/// Creates a 3D rotation matrix from a normalized rotation `axis` and `angle` (in
/// radians).
///
/// # Panics
///
/// Will panic if `axis` is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn from_axis_angle(axis: Vec3, angle: f32) -> Self {
glam_assert!(axis.is_normalized());
let (sin, cos) = math::sin_cos(angle);
let (xsin, ysin, zsin) = axis.mul(sin).into();
let (x, y, z) = axis.into();
let (x2, y2, z2) = axis.mul(axis).into();
let omc = 1.0 - cos;
let xyomc = x * y * omc;
let xzomc = x * z * omc;
let yzomc = y * z * omc;
Self::from_cols(
Vec3A::new(x2 * omc + cos, xyomc + zsin, xzomc - ysin),
Vec3A::new(xyomc - zsin, y2 * omc + cos, yzomc + xsin),
Vec3A::new(xzomc + ysin, yzomc - xsin, z2 * omc + cos),
)
}
/// Creates a 3D rotation matrix from the given euler rotation sequence and the angles (in
/// radians).
#[inline]
#[must_use]
pub fn from_euler(order: EulerRot, a: f32, b: f32, c: f32) -> Self {
Self::from_euler_angles(order, a, b, c)
}
/// Extract Euler angles with the given Euler rotation order.
///
/// Note if the input matrix contains scales, shears, or other non-rotation transformations then
/// the resulting Euler angles will be ill-defined.
///
/// # Panics
///
/// Will panic if any input matrix column is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn to_euler(&self, order: EulerRot) -> (f32, f32, f32) {
glam_assert!(
self.x_axis.is_normalized()
&& self.y_axis.is_normalized()
&& self.z_axis.is_normalized()
);
self.to_euler_angles(order)
}
/// Creates a 3D rotation matrix from `angle` (in radians) around the x axis.
#[inline]
#[must_use]
pub fn from_rotation_x(angle: f32) -> Self {
let (sina, cosa) = math::sin_cos(angle);
Self::from_cols(
Vec3A::X,
Vec3A::new(0.0, cosa, sina),
Vec3A::new(0.0, -sina, cosa),
)
}
/// Creates a 3D rotation matrix from `angle` (in radians) around the y axis.
#[inline]
#[must_use]
pub fn from_rotation_y(angle: f32) -> Self {
let (sina, cosa) = math::sin_cos(angle);
Self::from_cols(
Vec3A::new(cosa, 0.0, -sina),
Vec3A::Y,
Vec3A::new(sina, 0.0, cosa),
)
}
/// Creates a 3D rotation matrix from `angle` (in radians) around the z axis.
#[inline]
#[must_use]
pub fn from_rotation_z(angle: f32) -> Self {
let (sina, cosa) = math::sin_cos(angle);
Self::from_cols(
Vec3A::new(cosa, sina, 0.0),
Vec3A::new(-sina, cosa, 0.0),
Vec3A::Z,
)
}
/// Creates an affine transformation matrix from the given 2D `translation`.
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
#[inline]
#[must_use]
pub fn from_translation(translation: Vec2) -> Self {
Self::from_cols(
Vec3A::X,
Vec3A::Y,
Vec3A::new(translation.x, translation.y, 1.0),
)
}
/// Creates an affine transformation matrix from the given 2D rotation `angle` (in
/// radians).
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
#[inline]
#[must_use]
pub fn from_angle(angle: f32) -> Self {
let (sin, cos) = math::sin_cos(angle);
Self::from_cols(
Vec3A::new(cos, sin, 0.0),
Vec3A::new(-sin, cos, 0.0),
Vec3A::Z,
)
}
/// Creates an affine transformation matrix from the given 2D `scale`, rotation `angle` (in
/// radians) and `translation`.
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
#[inline]
#[must_use]
pub fn from_scale_angle_translation(scale: Vec2, angle: f32, translation: Vec2) -> Self {
let (sin, cos) = math::sin_cos(angle);
Self::from_cols(
Vec3A::new(cos * scale.x, sin * scale.x, 0.0),
Vec3A::new(-sin * scale.y, cos * scale.y, 0.0),
Vec3A::new(translation.x, translation.y, 1.0),
)
}
/// Creates an affine transformation matrix from the given non-uniform 2D `scale`.
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
///
/// # Panics
///
/// Will panic if all elements of `scale` are zero when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn from_scale(scale: Vec2) -> Self {
// Do not panic as long as any component is non-zero
glam_assert!(scale.cmpne(Vec2::ZERO).any());
Self::from_cols(
Vec3A::new(scale.x, 0.0, 0.0),
Vec3A::new(0.0, scale.y, 0.0),
Vec3A::Z,
)
}
/// Creates an affine transformation matrix from the given 2x2 matrix.
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
#[inline]
pub fn from_mat2(m: Mat2) -> Self {
Self::from_cols((m.x_axis, 0.0).into(), (m.y_axis, 0.0).into(), Vec3A::Z)
}
/// Creates a 3x3 matrix from the first 9 values in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 9 elements long.
#[inline]
#[must_use]
pub const fn from_cols_slice(slice: &[f32]) -> Self {
Self::new(
slice[0], slice[1], slice[2], slice[3], slice[4], slice[5], slice[6], slice[7],
slice[8],
)
}
/// Writes the columns of `self` to the first 9 elements in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 9 elements long.
#[inline]
pub fn write_cols_to_slice(self, slice: &mut [f32]) {
slice[0] = self.x_axis.x;
slice[1] = self.x_axis.y;
slice[2] = self.x_axis.z;
slice[3] = self.y_axis.x;
slice[4] = self.y_axis.y;
slice[5] = self.y_axis.z;
slice[6] = self.z_axis.x;
slice[7] = self.z_axis.y;
slice[8] = self.z_axis.z;
}
/// Returns the matrix column for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 2.
#[inline]
#[must_use]
pub fn col(&self, index: usize) -> Vec3A {
match index {
0 => self.x_axis,
1 => self.y_axis,
2 => self.z_axis,
_ => panic!("index out of bounds"),
}
}
/// Returns a mutable reference to the matrix column for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 2.
#[inline]
pub fn col_mut(&mut self, index: usize) -> &mut Vec3A {
match index {
0 => &mut self.x_axis,
1 => &mut self.y_axis,
2 => &mut self.z_axis,
_ => panic!("index out of bounds"),
}
}
/// Returns the matrix row for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 2.
#[inline]
#[must_use]
pub fn row(&self, index: usize) -> Vec3A {
match index {
0 => Vec3A::new(self.x_axis.x, self.y_axis.x, self.z_axis.x),
1 => Vec3A::new(self.x_axis.y, self.y_axis.y, self.z_axis.y),
2 => Vec3A::new(self.x_axis.z, self.y_axis.z, self.z_axis.z),
_ => panic!("index out of bounds"),
}
}
/// Returns `true` if, and only if, all elements are finite.
/// If any element is either `NaN`, positive or negative infinity, this will return `false`.
#[inline]
#[must_use]
pub fn is_finite(&self) -> bool {
self.x_axis.is_finite() && self.y_axis.is_finite() && self.z_axis.is_finite()
}
/// Returns `true` if any elements are `NaN`.
#[inline]
#[must_use]
pub fn is_nan(&self) -> bool {
self.x_axis.is_nan() || self.y_axis.is_nan() || self.z_axis.is_nan()
}
/// Returns the transpose of `self`.
#[inline]
#[must_use]
pub fn transpose(&self) -> Self {
let tmp0 = simd_swizzle!(self.x_axis.0, self.y_axis.0, [0, 1, 4, 5]);
let tmp1 = simd_swizzle!(self.x_axis.0, self.y_axis.0, [2, 3, 6, 7]);
Self {
x_axis: Vec3A(simd_swizzle!(tmp0, self.z_axis.0, [0, 2, 4, 4])),
y_axis: Vec3A(simd_swizzle!(tmp0, self.z_axis.0, [1, 3, 5, 5])),
z_axis: Vec3A(simd_swizzle!(tmp1, self.z_axis.0, [0, 2, 6, 6])),
}
}
/// Returns the determinant of `self`.
#[inline]
#[must_use]
pub fn determinant(&self) -> f32 {
self.z_axis.dot(self.x_axis.cross(self.y_axis))
}
/// Returns the inverse of `self`.
///
/// If the matrix is not invertible the returned matrix will be invalid.
///
/// # Panics
///
/// Will panic if the determinant of `self` is zero when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn inverse(&self) -> Self {
let tmp0 = self.y_axis.cross(self.z_axis);
let tmp1 = self.z_axis.cross(self.x_axis);
let tmp2 = self.x_axis.cross(self.y_axis);
let det = self.z_axis.dot(tmp2);
glam_assert!(det != 0.0);
let inv_det = Vec3A::splat(det.recip());
Self::from_cols(tmp0.mul(inv_det), tmp1.mul(inv_det), tmp2.mul(inv_det)).transpose()
}
/// Transforms the given 2D vector as a point.
///
/// This is the equivalent of multiplying `rhs` as a 3D vector where `z` is `1`.
///
/// This method assumes that `self` contains a valid affine transform.
///
/// # Panics
///
/// Will panic if the 2nd row of `self` is not `(0, 0, 1)` when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn transform_point2(&self, rhs: Vec2) -> Vec2 {
glam_assert!(self.row(2).abs_diff_eq(Vec3A::Z, 1e-6));
Mat2::from_cols(self.x_axis.xy(), self.y_axis.xy()) * rhs + self.z_axis.xy()
}
/// Rotates the given 2D vector.
///
/// This is the equivalent of multiplying `rhs` as a 3D vector where `z` is `0`.
///
/// This method assumes that `self` contains a valid affine transform.
///
/// # Panics
///
/// Will panic if the 2nd row of `self` is not `(0, 0, 1)` when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn transform_vector2(&self, rhs: Vec2) -> Vec2 {
glam_assert!(self.row(2).abs_diff_eq(Vec3A::Z, 1e-6));
Mat2::from_cols(self.x_axis.xy(), self.y_axis.xy()) * rhs
}
/// Transforms a 3D vector.
#[inline]
#[must_use]
pub fn mul_vec3(&self, rhs: Vec3) -> Vec3 {
self.mul_vec3a(rhs.into()).into()
}
/// Transforms a [`Vec3A`].
#[inline]
#[must_use]
pub fn mul_vec3a(&self, rhs: Vec3A) -> Vec3A {
let mut res = self.x_axis.mul(rhs.xxx());
res = res.add(self.y_axis.mul(rhs.yyy()));
res = res.add(self.z_axis.mul(rhs.zzz()));
res
}
/// Multiplies two 3x3 matrices.
#[inline]
#[must_use]
pub fn mul_mat3(&self, rhs: &Self) -> Self {
Self::from_cols(
self.mul(rhs.x_axis),
self.mul(rhs.y_axis),
self.mul(rhs.z_axis),
)
}
/// Adds two 3x3 matrices.
#[inline]
#[must_use]
pub fn add_mat3(&self, rhs: &Self) -> Self {
Self::from_cols(
self.x_axis.add(rhs.x_axis),
self.y_axis.add(rhs.y_axis),
self.z_axis.add(rhs.z_axis),
)
}
/// Subtracts two 3x3 matrices.
#[inline]
#[must_use]
pub fn sub_mat3(&self, rhs: &Self) -> Self {
Self::from_cols(
self.x_axis.sub(rhs.x_axis),
self.y_axis.sub(rhs.y_axis),
self.z_axis.sub(rhs.z_axis),
)
}
/// Multiplies a 3x3 matrix by a scalar.
#[inline]
#[must_use]
pub fn mul_scalar(&self, rhs: f32) -> Self {
Self::from_cols(
self.x_axis.mul(rhs),
self.y_axis.mul(rhs),
self.z_axis.mul(rhs),
)
}
/// Divides a 3x3 matrix by a scalar.
#[inline]
#[must_use]
pub fn div_scalar(&self, rhs: f32) -> Self {
let rhs = Vec3A::splat(rhs);
Self::from_cols(
self.x_axis.div(rhs),
self.y_axis.div(rhs),
self.z_axis.div(rhs),
)
}
/// Returns true if the absolute difference of all elements between `self` and `rhs`
/// is less than or equal to `max_abs_diff`.
///
/// This can be used to compare if two matrices contain similar elements. It works best
/// when comparing with a known value. The `max_abs_diff` that should be used used
/// depends on the values being compared against.
///
/// For more see
/// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
#[inline]
#[must_use]
pub fn abs_diff_eq(&self, rhs: Self, max_abs_diff: f32) -> bool {
self.x_axis.abs_diff_eq(rhs.x_axis, max_abs_diff)
&& self.y_axis.abs_diff_eq(rhs.y_axis, max_abs_diff)
&& self.z_axis.abs_diff_eq(rhs.z_axis, max_abs_diff)
}
/// Takes the absolute value of each element in `self`
#[inline]
#[must_use]
pub fn abs(&self) -> Self {
Self::from_cols(self.x_axis.abs(), self.y_axis.abs(), self.z_axis.abs())
}
#[inline]
pub fn as_dmat3(&self) -> DMat3 {
DMat3::from_cols(
self.x_axis.as_dvec3(),
self.y_axis.as_dvec3(),
self.z_axis.as_dvec3(),
)
}
}
impl Default for Mat3A {
#[inline]
fn default() -> Self {
Self::IDENTITY
}
}
impl Add<Mat3A> for Mat3A {
type Output = Self;
#[inline]
fn add(self, rhs: Self) -> Self::Output {
self.add_mat3(&rhs)
}
}
impl AddAssign<Mat3A> for Mat3A {
#[inline]
fn add_assign(&mut self, rhs: Self) {
*self = self.add_mat3(&rhs);
}
}
impl Sub<Mat3A> for Mat3A {
type Output = Self;
#[inline]
fn sub(self, rhs: Self) -> Self::Output {
self.sub_mat3(&rhs)
}
}
impl SubAssign<Mat3A> for Mat3A {
#[inline]
fn sub_assign(&mut self, rhs: Self) {
*self = self.sub_mat3(&rhs);
}
}
impl Neg for Mat3A {
type Output = Self;
#[inline]
fn neg(self) -> Self::Output {
Self::from_cols(self.x_axis.neg(), self.y_axis.neg(), self.z_axis.neg())
}
}
impl Mul<Mat3A> for Mat3A {
type Output = Self;
#[inline]
fn mul(self, rhs: Self) -> Self::Output {
self.mul_mat3(&rhs)
}
}
impl MulAssign<Mat3A> for Mat3A {
#[inline]
fn mul_assign(&mut self, rhs: Self) {
*self = self.mul_mat3(&rhs);
}
}
impl Mul<Vec3A> for Mat3A {
type Output = Vec3A;
#[inline]
fn mul(self, rhs: Vec3A) -> Self::Output {
self.mul_vec3a(rhs)
}
}
impl Mul<Mat3A> for f32 {
type Output = Mat3A;
#[inline]
fn mul(self, rhs: Mat3A) -> Self::Output {
rhs.mul_scalar(self)
}
}
impl Mul<f32> for Mat3A {
type Output = Self;
#[inline]
fn mul(self, rhs: f32) -> Self::Output {
self.mul_scalar(rhs)
}
}
impl MulAssign<f32> for Mat3A {
#[inline]
fn mul_assign(&mut self, rhs: f32) {
*self = self.mul_scalar(rhs);
}
}
impl Div<Mat3A> for f32 {
type Output = Mat3A;
#[inline]
fn div(self, rhs: Mat3A) -> Self::Output {
rhs.div_scalar(self)
}
}
impl Div<f32> for Mat3A {
type Output = Self;
#[inline]
fn div(self, rhs: f32) -> Self::Output {
self.div_scalar(rhs)
}
}
impl DivAssign<f32> for Mat3A {
#[inline]
fn div_assign(&mut self, rhs: f32) {
*self = self.div_scalar(rhs);
}
}
impl Mul<Vec3> for Mat3A {
type Output = Vec3;
#[inline]
fn mul(self, rhs: Vec3) -> Vec3 {
self.mul_vec3a(rhs.into()).into()
}
}
impl From<Mat3> for Mat3A {
#[inline]
fn from(m: Mat3) -> Self {
Self {
x_axis: m.x_axis.into(),
y_axis: m.y_axis.into(),
z_axis: m.z_axis.into(),
}
}
}
impl Sum<Self> for Mat3A {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Self::ZERO, Self::add)
}
}
impl<'a> Sum<&'a Self> for Mat3A {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
}
}
impl Product for Mat3A {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Self::IDENTITY, Self::mul)
}
}
impl<'a> Product<&'a Self> for Mat3A {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::IDENTITY, |a, &b| Self::mul(a, b))
}
}
impl PartialEq for Mat3A {
#[inline]
fn eq(&self, rhs: &Self) -> bool {
self.x_axis.eq(&rhs.x_axis) && self.y_axis.eq(&rhs.y_axis) && self.z_axis.eq(&rhs.z_axis)
}
}
impl fmt::Debug for Mat3A {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct(stringify!(Mat3A))
.field("x_axis", &self.x_axis)
.field("y_axis", &self.y_axis)
.field("z_axis", &self.z_axis)
.finish()
}
}
impl fmt::Display for Mat3A {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(p) = f.precision() {
write!(
f,
"[{:.*}, {:.*}, {:.*}]",
p, self.x_axis, p, self.y_axis, p, self.z_axis
)
} else {
write!(f, "[{}, {}, {}]", self.x_axis, self.y_axis, self.z_axis)
}
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+21
View File
@@ -0,0 +1,21 @@
// Generated from float.rs.tera template. Edit the template, not the generated file.
use crate::float::FloatExt;
impl FloatExt for f32 {
#[inline]
fn lerp(self, rhs: f32, t: f32) -> f32 {
self + (rhs - self) * t
}
#[inline]
fn inverse_lerp(a: f32, b: f32, v: f32) -> f32 {
(v - a) / (b - a)
}
#[inline]
fn remap(self, in_start: f32, in_end: f32, out_start: f32, out_end: f32) -> f32 {
let t = f32::inverse_lerp(in_start, in_end, self);
f32::lerp(out_start, out_end, t)
}
}
+872
View File
@@ -0,0 +1,872 @@
// Generated from mat.rs.tera template. Edit the template, not the generated file.
use crate::{
euler::{FromEuler, ToEuler},
f32::math,
swizzles::*,
DMat3, EulerRot, Mat2, Mat3A, Mat4, Quat, Vec2, Vec3, Vec3A,
};
use core::fmt;
use core::iter::{Product, Sum};
use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
/// Creates a 3x3 matrix from three column vectors.
#[inline(always)]
#[must_use]
pub const fn mat3(x_axis: Vec3, y_axis: Vec3, z_axis: Vec3) -> Mat3 {
Mat3::from_cols(x_axis, y_axis, z_axis)
}
/// A 3x3 column major matrix.
///
/// This 3x3 matrix type features convenience methods for creating and using linear and
/// affine transformations. If you are primarily dealing with 2D affine transformations the
/// [`Affine2`](crate::Affine2) type is much faster and more space efficient than
/// using a 3x3 matrix.
///
/// Linear transformations including 3D rotation and scale can be created using methods
/// such as [`Self::from_diagonal()`], [`Self::from_quat()`], [`Self::from_axis_angle()`],
/// [`Self::from_rotation_x()`], [`Self::from_rotation_y()`], or
/// [`Self::from_rotation_z()`].
///
/// The resulting matrices can be use to transform 3D vectors using regular vector
/// multiplication.
///
/// Affine transformations including 2D translation, rotation and scale can be created
/// using methods such as [`Self::from_translation()`], [`Self::from_angle()`],
/// [`Self::from_scale()`] and [`Self::from_scale_angle_translation()`].
///
/// The [`Self::transform_point2()`] and [`Self::transform_vector2()`] convenience methods
/// are provided for performing affine transforms on 2D vectors and points. These multiply
/// 2D inputs as 3D vectors with an implicit `z` value of `1` for points and `0` for
/// vectors respectively. These methods assume that `Self` contains a valid affine
/// transform.
#[derive(Clone, Copy)]
#[repr(C)]
pub struct Mat3 {
pub x_axis: Vec3,
pub y_axis: Vec3,
pub z_axis: Vec3,
}
impl Mat3 {
/// A 3x3 matrix with all elements set to `0.0`.
pub const ZERO: Self = Self::from_cols(Vec3::ZERO, Vec3::ZERO, Vec3::ZERO);
/// A 3x3 identity matrix, where all diagonal elements are `1`, and all off-diagonal elements are `0`.
pub const IDENTITY: Self = Self::from_cols(Vec3::X, Vec3::Y, Vec3::Z);
/// All NAN:s.
pub const NAN: Self = Self::from_cols(Vec3::NAN, Vec3::NAN, Vec3::NAN);
#[allow(clippy::too_many_arguments)]
#[inline(always)]
#[must_use]
const fn new(
m00: f32,
m01: f32,
m02: f32,
m10: f32,
m11: f32,
m12: f32,
m20: f32,
m21: f32,
m22: f32,
) -> Self {
Self {
x_axis: Vec3::new(m00, m01, m02),
y_axis: Vec3::new(m10, m11, m12),
z_axis: Vec3::new(m20, m21, m22),
}
}
/// Creates a 3x3 matrix from three column vectors.
#[inline(always)]
#[must_use]
pub const fn from_cols(x_axis: Vec3, y_axis: Vec3, z_axis: Vec3) -> Self {
Self {
x_axis,
y_axis,
z_axis,
}
}
/// Creates a 3x3 matrix from a `[f32; 9]` array stored in column major order.
/// If your data is stored in row major you will need to `transpose` the returned
/// matrix.
#[inline]
#[must_use]
pub const fn from_cols_array(m: &[f32; 9]) -> Self {
Self::new(m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8])
}
/// Creates a `[f32; 9]` array storing data in column major order.
/// If you require data in row major order `transpose` the matrix first.
#[inline]
#[must_use]
pub const fn to_cols_array(&self) -> [f32; 9] {
[
self.x_axis.x,
self.x_axis.y,
self.x_axis.z,
self.y_axis.x,
self.y_axis.y,
self.y_axis.z,
self.z_axis.x,
self.z_axis.y,
self.z_axis.z,
]
}
/// Creates a 3x3 matrix from a `[[f32; 3]; 3]` 3D array stored in column major order.
/// If your data is in row major order you will need to `transpose` the returned
/// matrix.
#[inline]
#[must_use]
pub const fn from_cols_array_2d(m: &[[f32; 3]; 3]) -> Self {
Self::from_cols(
Vec3::from_array(m[0]),
Vec3::from_array(m[1]),
Vec3::from_array(m[2]),
)
}
/// Creates a `[[f32; 3]; 3]` 3D array storing data in column major order.
/// If you require data in row major order `transpose` the matrix first.
#[inline]
#[must_use]
pub const fn to_cols_array_2d(&self) -> [[f32; 3]; 3] {
[
self.x_axis.to_array(),
self.y_axis.to_array(),
self.z_axis.to_array(),
]
}
/// Creates a 3x3 matrix with its diagonal set to `diagonal` and all other entries set to 0.
#[doc(alias = "scale")]
#[inline]
#[must_use]
pub const fn from_diagonal(diagonal: Vec3) -> Self {
Self::new(
diagonal.x, 0.0, 0.0, 0.0, diagonal.y, 0.0, 0.0, 0.0, diagonal.z,
)
}
/// Creates a 3x3 matrix from a 4x4 matrix, discarding the 4th row and column.
#[inline]
#[must_use]
pub fn from_mat4(m: Mat4) -> Self {
Self::from_cols(
Vec3::from_vec4(m.x_axis),
Vec3::from_vec4(m.y_axis),
Vec3::from_vec4(m.z_axis),
)
}
/// Creates a 3x3 matrix from the minor of the given 4x4 matrix, discarding the `i`th column
/// and `j`th row.
///
/// # Panics
///
/// Panics if `i` or `j` is greater than 3.
#[inline]
#[must_use]
pub fn from_mat4_minor(m: Mat4, i: usize, j: usize) -> Self {
match (i, j) {
(0, 0) => Self::from_cols(m.y_axis.yzw(), m.z_axis.yzw(), m.w_axis.yzw()),
(0, 1) => Self::from_cols(m.y_axis.xzw(), m.z_axis.xzw(), m.w_axis.xzw()),
(0, 2) => Self::from_cols(m.y_axis.xyw(), m.z_axis.xyw(), m.w_axis.xyw()),
(0, 3) => Self::from_cols(m.y_axis.xyz(), m.z_axis.xyz(), m.w_axis.xyz()),
(1, 0) => Self::from_cols(m.x_axis.yzw(), m.z_axis.yzw(), m.w_axis.yzw()),
(1, 1) => Self::from_cols(m.x_axis.xzw(), m.z_axis.xzw(), m.w_axis.xzw()),
(1, 2) => Self::from_cols(m.x_axis.xyw(), m.z_axis.xyw(), m.w_axis.xyw()),
(1, 3) => Self::from_cols(m.x_axis.xyz(), m.z_axis.xyz(), m.w_axis.xyz()),
(2, 0) => Self::from_cols(m.x_axis.yzw(), m.y_axis.yzw(), m.w_axis.yzw()),
(2, 1) => Self::from_cols(m.x_axis.xzw(), m.y_axis.xzw(), m.w_axis.xzw()),
(2, 2) => Self::from_cols(m.x_axis.xyw(), m.y_axis.xyw(), m.w_axis.xyw()),
(2, 3) => Self::from_cols(m.x_axis.xyz(), m.y_axis.xyz(), m.w_axis.xyz()),
(3, 0) => Self::from_cols(m.x_axis.yzw(), m.y_axis.yzw(), m.z_axis.yzw()),
(3, 1) => Self::from_cols(m.x_axis.xzw(), m.y_axis.xzw(), m.z_axis.xzw()),
(3, 2) => Self::from_cols(m.x_axis.xyw(), m.y_axis.xyw(), m.z_axis.xyw()),
(3, 3) => Self::from_cols(m.x_axis.xyz(), m.y_axis.xyz(), m.z_axis.xyz()),
_ => panic!("index out of bounds"),
}
}
/// Creates a 3D rotation matrix from the given quaternion.
///
/// # Panics
///
/// Will panic if `rotation` is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn from_quat(rotation: Quat) -> Self {
glam_assert!(rotation.is_normalized());
let x2 = rotation.x + rotation.x;
let y2 = rotation.y + rotation.y;
let z2 = rotation.z + rotation.z;
let xx = rotation.x * x2;
let xy = rotation.x * y2;
let xz = rotation.x * z2;
let yy = rotation.y * y2;
let yz = rotation.y * z2;
let zz = rotation.z * z2;
let wx = rotation.w * x2;
let wy = rotation.w * y2;
let wz = rotation.w * z2;
Self::from_cols(
Vec3::new(1.0 - (yy + zz), xy + wz, xz - wy),
Vec3::new(xy - wz, 1.0 - (xx + zz), yz + wx),
Vec3::new(xz + wy, yz - wx, 1.0 - (xx + yy)),
)
}
/// Creates a 3D rotation matrix from a normalized rotation `axis` and `angle` (in
/// radians).
///
/// # Panics
///
/// Will panic if `axis` is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn from_axis_angle(axis: Vec3, angle: f32) -> Self {
glam_assert!(axis.is_normalized());
let (sin, cos) = math::sin_cos(angle);
let (xsin, ysin, zsin) = axis.mul(sin).into();
let (x, y, z) = axis.into();
let (x2, y2, z2) = axis.mul(axis).into();
let omc = 1.0 - cos;
let xyomc = x * y * omc;
let xzomc = x * z * omc;
let yzomc = y * z * omc;
Self::from_cols(
Vec3::new(x2 * omc + cos, xyomc + zsin, xzomc - ysin),
Vec3::new(xyomc - zsin, y2 * omc + cos, yzomc + xsin),
Vec3::new(xzomc + ysin, yzomc - xsin, z2 * omc + cos),
)
}
/// Creates a 3D rotation matrix from the given euler rotation sequence and the angles (in
/// radians).
#[inline]
#[must_use]
pub fn from_euler(order: EulerRot, a: f32, b: f32, c: f32) -> Self {
Self::from_euler_angles(order, a, b, c)
}
/// Extract Euler angles with the given Euler rotation order.
///
/// Note if the input matrix contains scales, shears, or other non-rotation transformations then
/// the resulting Euler angles will be ill-defined.
///
/// # Panics
///
/// Will panic if any input matrix column is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn to_euler(&self, order: EulerRot) -> (f32, f32, f32) {
glam_assert!(
self.x_axis.is_normalized()
&& self.y_axis.is_normalized()
&& self.z_axis.is_normalized()
);
self.to_euler_angles(order)
}
/// Creates a 3D rotation matrix from `angle` (in radians) around the x axis.
#[inline]
#[must_use]
pub fn from_rotation_x(angle: f32) -> Self {
let (sina, cosa) = math::sin_cos(angle);
Self::from_cols(
Vec3::X,
Vec3::new(0.0, cosa, sina),
Vec3::new(0.0, -sina, cosa),
)
}
/// Creates a 3D rotation matrix from `angle` (in radians) around the y axis.
#[inline]
#[must_use]
pub fn from_rotation_y(angle: f32) -> Self {
let (sina, cosa) = math::sin_cos(angle);
Self::from_cols(
Vec3::new(cosa, 0.0, -sina),
Vec3::Y,
Vec3::new(sina, 0.0, cosa),
)
}
/// Creates a 3D rotation matrix from `angle` (in radians) around the z axis.
#[inline]
#[must_use]
pub fn from_rotation_z(angle: f32) -> Self {
let (sina, cosa) = math::sin_cos(angle);
Self::from_cols(
Vec3::new(cosa, sina, 0.0),
Vec3::new(-sina, cosa, 0.0),
Vec3::Z,
)
}
/// Creates an affine transformation matrix from the given 2D `translation`.
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
#[inline]
#[must_use]
pub fn from_translation(translation: Vec2) -> Self {
Self::from_cols(
Vec3::X,
Vec3::Y,
Vec3::new(translation.x, translation.y, 1.0),
)
}
/// Creates an affine transformation matrix from the given 2D rotation `angle` (in
/// radians).
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
#[inline]
#[must_use]
pub fn from_angle(angle: f32) -> Self {
let (sin, cos) = math::sin_cos(angle);
Self::from_cols(Vec3::new(cos, sin, 0.0), Vec3::new(-sin, cos, 0.0), Vec3::Z)
}
/// Creates an affine transformation matrix from the given 2D `scale`, rotation `angle` (in
/// radians) and `translation`.
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
#[inline]
#[must_use]
pub fn from_scale_angle_translation(scale: Vec2, angle: f32, translation: Vec2) -> Self {
let (sin, cos) = math::sin_cos(angle);
Self::from_cols(
Vec3::new(cos * scale.x, sin * scale.x, 0.0),
Vec3::new(-sin * scale.y, cos * scale.y, 0.0),
Vec3::new(translation.x, translation.y, 1.0),
)
}
/// Creates an affine transformation matrix from the given non-uniform 2D `scale`.
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
///
/// # Panics
///
/// Will panic if all elements of `scale` are zero when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn from_scale(scale: Vec2) -> Self {
// Do not panic as long as any component is non-zero
glam_assert!(scale.cmpne(Vec2::ZERO).any());
Self::from_cols(
Vec3::new(scale.x, 0.0, 0.0),
Vec3::new(0.0, scale.y, 0.0),
Vec3::Z,
)
}
/// Creates an affine transformation matrix from the given 2x2 matrix.
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
#[inline]
pub fn from_mat2(m: Mat2) -> Self {
Self::from_cols((m.x_axis, 0.0).into(), (m.y_axis, 0.0).into(), Vec3::Z)
}
/// Creates a 3x3 matrix from the first 9 values in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 9 elements long.
#[inline]
#[must_use]
pub const fn from_cols_slice(slice: &[f32]) -> Self {
Self::new(
slice[0], slice[1], slice[2], slice[3], slice[4], slice[5], slice[6], slice[7],
slice[8],
)
}
/// Writes the columns of `self` to the first 9 elements in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 9 elements long.
#[inline]
pub fn write_cols_to_slice(self, slice: &mut [f32]) {
slice[0] = self.x_axis.x;
slice[1] = self.x_axis.y;
slice[2] = self.x_axis.z;
slice[3] = self.y_axis.x;
slice[4] = self.y_axis.y;
slice[5] = self.y_axis.z;
slice[6] = self.z_axis.x;
slice[7] = self.z_axis.y;
slice[8] = self.z_axis.z;
}
/// Returns the matrix column for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 2.
#[inline]
#[must_use]
pub fn col(&self, index: usize) -> Vec3 {
match index {
0 => self.x_axis,
1 => self.y_axis,
2 => self.z_axis,
_ => panic!("index out of bounds"),
}
}
/// Returns a mutable reference to the matrix column for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 2.
#[inline]
pub fn col_mut(&mut self, index: usize) -> &mut Vec3 {
match index {
0 => &mut self.x_axis,
1 => &mut self.y_axis,
2 => &mut self.z_axis,
_ => panic!("index out of bounds"),
}
}
/// Returns the matrix row for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 2.
#[inline]
#[must_use]
pub fn row(&self, index: usize) -> Vec3 {
match index {
0 => Vec3::new(self.x_axis.x, self.y_axis.x, self.z_axis.x),
1 => Vec3::new(self.x_axis.y, self.y_axis.y, self.z_axis.y),
2 => Vec3::new(self.x_axis.z, self.y_axis.z, self.z_axis.z),
_ => panic!("index out of bounds"),
}
}
/// Returns `true` if, and only if, all elements are finite.
/// If any element is either `NaN`, positive or negative infinity, this will return `false`.
#[inline]
#[must_use]
pub fn is_finite(&self) -> bool {
self.x_axis.is_finite() && self.y_axis.is_finite() && self.z_axis.is_finite()
}
/// Returns `true` if any elements are `NaN`.
#[inline]
#[must_use]
pub fn is_nan(&self) -> bool {
self.x_axis.is_nan() || self.y_axis.is_nan() || self.z_axis.is_nan()
}
/// Returns the transpose of `self`.
#[inline]
#[must_use]
pub fn transpose(&self) -> Self {
Self {
x_axis: Vec3::new(self.x_axis.x, self.y_axis.x, self.z_axis.x),
y_axis: Vec3::new(self.x_axis.y, self.y_axis.y, self.z_axis.y),
z_axis: Vec3::new(self.x_axis.z, self.y_axis.z, self.z_axis.z),
}
}
/// Returns the determinant of `self`.
#[inline]
#[must_use]
pub fn determinant(&self) -> f32 {
self.z_axis.dot(self.x_axis.cross(self.y_axis))
}
/// Returns the inverse of `self`.
///
/// If the matrix is not invertible the returned matrix will be invalid.
///
/// # Panics
///
/// Will panic if the determinant of `self` is zero when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn inverse(&self) -> Self {
let tmp0 = self.y_axis.cross(self.z_axis);
let tmp1 = self.z_axis.cross(self.x_axis);
let tmp2 = self.x_axis.cross(self.y_axis);
let det = self.z_axis.dot(tmp2);
glam_assert!(det != 0.0);
let inv_det = Vec3::splat(det.recip());
Self::from_cols(tmp0.mul(inv_det), tmp1.mul(inv_det), tmp2.mul(inv_det)).transpose()
}
/// Transforms the given 2D vector as a point.
///
/// This is the equivalent of multiplying `rhs` as a 3D vector where `z` is `1`.
///
/// This method assumes that `self` contains a valid affine transform.
///
/// # Panics
///
/// Will panic if the 2nd row of `self` is not `(0, 0, 1)` when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn transform_point2(&self, rhs: Vec2) -> Vec2 {
glam_assert!(self.row(2).abs_diff_eq(Vec3::Z, 1e-6));
Mat2::from_cols(self.x_axis.xy(), self.y_axis.xy()) * rhs + self.z_axis.xy()
}
/// Rotates the given 2D vector.
///
/// This is the equivalent of multiplying `rhs` as a 3D vector where `z` is `0`.
///
/// This method assumes that `self` contains a valid affine transform.
///
/// # Panics
///
/// Will panic if the 2nd row of `self` is not `(0, 0, 1)` when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn transform_vector2(&self, rhs: Vec2) -> Vec2 {
glam_assert!(self.row(2).abs_diff_eq(Vec3::Z, 1e-6));
Mat2::from_cols(self.x_axis.xy(), self.y_axis.xy()) * rhs
}
/// Transforms a 3D vector.
#[inline]
#[must_use]
pub fn mul_vec3(&self, rhs: Vec3) -> Vec3 {
let mut res = self.x_axis.mul(rhs.x);
res = res.add(self.y_axis.mul(rhs.y));
res = res.add(self.z_axis.mul(rhs.z));
res
}
/// Transforms a [`Vec3A`].
#[inline]
#[must_use]
pub fn mul_vec3a(&self, rhs: Vec3A) -> Vec3A {
self.mul_vec3(rhs.into()).into()
}
/// Multiplies two 3x3 matrices.
#[inline]
#[must_use]
pub fn mul_mat3(&self, rhs: &Self) -> Self {
Self::from_cols(
self.mul(rhs.x_axis),
self.mul(rhs.y_axis),
self.mul(rhs.z_axis),
)
}
/// Adds two 3x3 matrices.
#[inline]
#[must_use]
pub fn add_mat3(&self, rhs: &Self) -> Self {
Self::from_cols(
self.x_axis.add(rhs.x_axis),
self.y_axis.add(rhs.y_axis),
self.z_axis.add(rhs.z_axis),
)
}
/// Subtracts two 3x3 matrices.
#[inline]
#[must_use]
pub fn sub_mat3(&self, rhs: &Self) -> Self {
Self::from_cols(
self.x_axis.sub(rhs.x_axis),
self.y_axis.sub(rhs.y_axis),
self.z_axis.sub(rhs.z_axis),
)
}
/// Multiplies a 3x3 matrix by a scalar.
#[inline]
#[must_use]
pub fn mul_scalar(&self, rhs: f32) -> Self {
Self::from_cols(
self.x_axis.mul(rhs),
self.y_axis.mul(rhs),
self.z_axis.mul(rhs),
)
}
/// Divides a 3x3 matrix by a scalar.
#[inline]
#[must_use]
pub fn div_scalar(&self, rhs: f32) -> Self {
let rhs = Vec3::splat(rhs);
Self::from_cols(
self.x_axis.div(rhs),
self.y_axis.div(rhs),
self.z_axis.div(rhs),
)
}
/// Returns true if the absolute difference of all elements between `self` and `rhs`
/// is less than or equal to `max_abs_diff`.
///
/// This can be used to compare if two matrices contain similar elements. It works best
/// when comparing with a known value. The `max_abs_diff` that should be used used
/// depends on the values being compared against.
///
/// For more see
/// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
#[inline]
#[must_use]
pub fn abs_diff_eq(&self, rhs: Self, max_abs_diff: f32) -> bool {
self.x_axis.abs_diff_eq(rhs.x_axis, max_abs_diff)
&& self.y_axis.abs_diff_eq(rhs.y_axis, max_abs_diff)
&& self.z_axis.abs_diff_eq(rhs.z_axis, max_abs_diff)
}
/// Takes the absolute value of each element in `self`
#[inline]
#[must_use]
pub fn abs(&self) -> Self {
Self::from_cols(self.x_axis.abs(), self.y_axis.abs(), self.z_axis.abs())
}
#[inline]
pub fn as_dmat3(&self) -> DMat3 {
DMat3::from_cols(
self.x_axis.as_dvec3(),
self.y_axis.as_dvec3(),
self.z_axis.as_dvec3(),
)
}
}
impl Default for Mat3 {
#[inline]
fn default() -> Self {
Self::IDENTITY
}
}
impl Add<Mat3> for Mat3 {
type Output = Self;
#[inline]
fn add(self, rhs: Self) -> Self::Output {
self.add_mat3(&rhs)
}
}
impl AddAssign<Mat3> for Mat3 {
#[inline]
fn add_assign(&mut self, rhs: Self) {
*self = self.add_mat3(&rhs);
}
}
impl Sub<Mat3> for Mat3 {
type Output = Self;
#[inline]
fn sub(self, rhs: Self) -> Self::Output {
self.sub_mat3(&rhs)
}
}
impl SubAssign<Mat3> for Mat3 {
#[inline]
fn sub_assign(&mut self, rhs: Self) {
*self = self.sub_mat3(&rhs);
}
}
impl Neg for Mat3 {
type Output = Self;
#[inline]
fn neg(self) -> Self::Output {
Self::from_cols(self.x_axis.neg(), self.y_axis.neg(), self.z_axis.neg())
}
}
impl Mul<Mat3> for Mat3 {
type Output = Self;
#[inline]
fn mul(self, rhs: Self) -> Self::Output {
self.mul_mat3(&rhs)
}
}
impl MulAssign<Mat3> for Mat3 {
#[inline]
fn mul_assign(&mut self, rhs: Self) {
*self = self.mul_mat3(&rhs);
}
}
impl Mul<Vec3> for Mat3 {
type Output = Vec3;
#[inline]
fn mul(self, rhs: Vec3) -> Self::Output {
self.mul_vec3(rhs)
}
}
impl Mul<Mat3> for f32 {
type Output = Mat3;
#[inline]
fn mul(self, rhs: Mat3) -> Self::Output {
rhs.mul_scalar(self)
}
}
impl Mul<f32> for Mat3 {
type Output = Self;
#[inline]
fn mul(self, rhs: f32) -> Self::Output {
self.mul_scalar(rhs)
}
}
impl MulAssign<f32> for Mat3 {
#[inline]
fn mul_assign(&mut self, rhs: f32) {
*self = self.mul_scalar(rhs);
}
}
impl Div<Mat3> for f32 {
type Output = Mat3;
#[inline]
fn div(self, rhs: Mat3) -> Self::Output {
rhs.div_scalar(self)
}
}
impl Div<f32> for Mat3 {
type Output = Self;
#[inline]
fn div(self, rhs: f32) -> Self::Output {
self.div_scalar(rhs)
}
}
impl DivAssign<f32> for Mat3 {
#[inline]
fn div_assign(&mut self, rhs: f32) {
*self = self.div_scalar(rhs);
}
}
impl Mul<Vec3A> for Mat3 {
type Output = Vec3A;
#[inline]
fn mul(self, rhs: Vec3A) -> Vec3A {
self.mul_vec3a(rhs)
}
}
impl From<Mat3A> for Mat3 {
#[inline]
fn from(m: Mat3A) -> Self {
Self {
x_axis: m.x_axis.into(),
y_axis: m.y_axis.into(),
z_axis: m.z_axis.into(),
}
}
}
impl Sum<Self> for Mat3 {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Self::ZERO, Self::add)
}
}
impl<'a> Sum<&'a Self> for Mat3 {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
}
}
impl Product for Mat3 {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Self::IDENTITY, Self::mul)
}
}
impl<'a> Product<&'a Self> for Mat3 {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::IDENTITY, |a, &b| Self::mul(a, b))
}
}
impl PartialEq for Mat3 {
#[inline]
fn eq(&self, rhs: &Self) -> bool {
self.x_axis.eq(&rhs.x_axis) && self.y_axis.eq(&rhs.y_axis) && self.z_axis.eq(&rhs.z_axis)
}
}
#[cfg(not(target_arch = "spirv"))]
impl AsRef<[f32; 9]> for Mat3 {
#[inline]
fn as_ref(&self) -> &[f32; 9] {
unsafe { &*(self as *const Self as *const [f32; 9]) }
}
}
#[cfg(not(target_arch = "spirv"))]
impl AsMut<[f32; 9]> for Mat3 {
#[inline]
fn as_mut(&mut self) -> &mut [f32; 9] {
unsafe { &mut *(self as *mut Self as *mut [f32; 9]) }
}
}
impl fmt::Debug for Mat3 {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct(stringify!(Mat3))
.field("x_axis", &self.x_axis)
.field("y_axis", &self.y_axis)
.field("z_axis", &self.z_axis)
.finish()
}
}
impl fmt::Display for Mat3 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(p) = f.precision() {
write!(
f,
"[{:.*}, {:.*}, {:.*}]",
p, self.x_axis, p, self.y_axis, p, self.z_axis
)
} else {
write!(f, "[{}, {}, {}]", self.x_axis, self.y_axis, self.z_axis)
}
}
}
+241
View File
@@ -0,0 +1,241 @@
/// Returns a very close approximation of `self.clamp(-1.0, 1.0).acos()`.
#[inline]
fn acos_approx_f32(v: f32) -> f32 {
// Based on https://github.com/microsoft/DirectXMath `XMScalarAcos`
// Clamp input to [-1,1].
let nonnegative = v >= 0.0;
let x = abs(v);
let mut omx = 1.0 - x;
if omx < 0.0 {
omx = 0.0;
}
let root = sqrt(omx);
// 7-degree minimax approximation
#[allow(clippy::approx_constant)]
let mut result =
((((((-0.001_262_491_1 * x + 0.006_670_09) * x - 0.017_088_126) * x + 0.030_891_88) * x
- 0.050_174_303)
* x
+ 0.088_978_99)
* x
- 0.214_598_8)
* x
+ 1.570_796_3;
result *= root;
// acos(x) = pi - acos(-x) when x < 0
if nonnegative {
result
} else {
core::f32::consts::PI - result
}
}
#[cfg(any(feature = "libm", all(feature = "nostd-libm", not(feature = "std"))))]
mod libm_math {
#[inline(always)]
pub(crate) fn abs(f: f32) -> f32 {
libm::fabsf(f)
}
#[inline(always)]
pub(crate) fn acos_approx(f: f32) -> f32 {
super::acos_approx_f32(f)
}
#[inline(always)]
pub(crate) fn atan2(f: f32, other: f32) -> f32 {
libm::atan2f(f, other)
}
#[allow(unused)]
#[inline(always)]
pub(crate) fn sin(f: f32) -> f32 {
libm::sinf(f)
}
#[inline(always)]
pub(crate) fn sin_cos(f: f32) -> (f32, f32) {
libm::sincosf(f)
}
#[inline(always)]
pub(crate) fn tan(f: f32) -> f32 {
libm::tanf(f)
}
#[inline(always)]
pub(crate) fn sqrt(f: f32) -> f32 {
libm::sqrtf(f)
}
#[inline(always)]
pub(crate) fn copysign(f: f32, sign: f32) -> f32 {
libm::copysignf(f, sign)
}
#[inline(always)]
pub(crate) fn signum(f: f32) -> f32 {
if f.is_nan() {
f32::NAN
} else {
copysign(1.0, f)
}
}
#[inline(always)]
pub(crate) fn round(f: f32) -> f32 {
libm::roundf(f)
}
#[inline(always)]
pub(crate) fn trunc(f: f32) -> f32 {
libm::truncf(f)
}
#[inline(always)]
pub(crate) fn ceil(f: f32) -> f32 {
libm::ceilf(f)
}
#[inline(always)]
pub(crate) fn floor(f: f32) -> f32 {
libm::floorf(f)
}
#[inline(always)]
pub(crate) fn exp(f: f32) -> f32 {
libm::expf(f)
}
#[inline(always)]
pub(crate) fn powf(f: f32, n: f32) -> f32 {
libm::powf(f, n)
}
#[inline(always)]
pub(crate) fn mul_add(a: f32, b: f32, c: f32) -> f32 {
libm::fmaf(a, b, c)
}
#[inline]
pub fn div_euclid(a: f32, b: f32) -> f32 {
// Based on https://doc.rust-lang.org/src/std/f32.rs.html#293
let q = libm::truncf(a / b);
if a % b < 0.0 {
return if b > 0.0 { q - 1.0 } else { q + 1.0 };
}
q
}
#[inline]
pub fn rem_euclid(a: f32, b: f32) -> f32 {
let r = a % b;
if r < 0.0 {
r + abs(b)
} else {
r
}
}
}
#[cfg(all(not(feature = "libm"), feature = "std"))]
mod std_math {
#[inline(always)]
pub(crate) fn abs(f: f32) -> f32 {
f32::abs(f)
}
#[inline(always)]
pub(crate) fn acos_approx(f: f32) -> f32 {
super::acos_approx_f32(f)
}
#[inline(always)]
pub(crate) fn atan2(f: f32, other: f32) -> f32 {
f32::atan2(f, other)
}
#[allow(unused)]
#[inline(always)]
pub(crate) fn sin(f: f32) -> f32 {
f32::sin(f)
}
#[inline(always)]
pub(crate) fn sin_cos(f: f32) -> (f32, f32) {
f32::sin_cos(f)
}
#[inline(always)]
pub(crate) fn tan(f: f32) -> f32 {
f32::tan(f)
}
#[inline(always)]
pub(crate) fn sqrt(f: f32) -> f32 {
f32::sqrt(f)
}
#[inline(always)]
pub(crate) fn copysign(f: f32, sign: f32) -> f32 {
f32::copysign(f, sign)
}
#[inline(always)]
pub(crate) fn signum(f: f32) -> f32 {
f32::signum(f)
}
#[inline(always)]
pub(crate) fn round(f: f32) -> f32 {
f32::round(f)
}
#[inline(always)]
pub(crate) fn trunc(f: f32) -> f32 {
f32::trunc(f)
}
#[inline(always)]
pub(crate) fn ceil(f: f32) -> f32 {
f32::ceil(f)
}
#[inline(always)]
pub(crate) fn floor(f: f32) -> f32 {
f32::floor(f)
}
#[inline(always)]
pub(crate) fn exp(f: f32) -> f32 {
f32::exp(f)
}
#[inline(always)]
pub(crate) fn powf(f: f32, n: f32) -> f32 {
f32::powf(f, n)
}
#[inline(always)]
pub(crate) fn mul_add(a: f32, b: f32, c: f32) -> f32 {
f32::mul_add(a, b, c)
}
#[inline]
pub fn div_euclid(a: f32, b: f32) -> f32 {
f32::div_euclid(a, b)
}
#[inline]
pub fn rem_euclid(a: f32, b: f32) -> f32 {
f32::rem_euclid(a, b)
}
}
#[cfg(any(feature = "libm", all(feature = "nostd-libm", not(feature = "std"))))]
pub(crate) use libm_math::*;
#[cfg(all(not(feature = "libm"), feature = "std"))]
pub(crate) use std_math::*;
+6
View File
@@ -0,0 +1,6 @@
pub mod mat2;
pub mod mat3a;
pub mod mat4;
pub mod quat;
pub mod vec3a;
pub mod vec4;
+624
View File
@@ -0,0 +1,624 @@
// Generated from mat.rs.tera template. Edit the template, not the generated file.
use crate::{f32::math, swizzles::*, DMat2, Mat3, Mat3A, Vec2};
use core::fmt;
use core::iter::{Product, Sum};
use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
use core::arch::aarch64::*;
#[repr(C)]
union UnionCast {
a: [f32; 4],
v: Mat2,
}
/// Creates a 2x2 matrix from two column vectors.
#[inline(always)]
#[must_use]
pub const fn mat2(x_axis: Vec2, y_axis: Vec2) -> Mat2 {
Mat2::from_cols(x_axis, y_axis)
}
/// A 2x2 column major matrix.
///
/// SIMD vector types are used for storage on supported platforms.
///
/// This type is 16 byte aligned.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct Mat2(pub(crate) float32x4_t);
impl Mat2 {
/// A 2x2 matrix with all elements set to `0.0`.
pub const ZERO: Self = Self::from_cols(Vec2::ZERO, Vec2::ZERO);
/// A 2x2 identity matrix, where all diagonal elements are `1`, and all off-diagonal elements are `0`.
pub const IDENTITY: Self = Self::from_cols(Vec2::X, Vec2::Y);
/// All NAN:s.
pub const NAN: Self = Self::from_cols(Vec2::NAN, Vec2::NAN);
#[allow(clippy::too_many_arguments)]
#[inline(always)]
#[must_use]
const fn new(m00: f32, m01: f32, m10: f32, m11: f32) -> Self {
unsafe {
UnionCast {
a: [m00, m01, m10, m11],
}
.v
}
}
/// Creates a 2x2 matrix from two column vectors.
#[inline(always)]
#[must_use]
pub const fn from_cols(x_axis: Vec2, y_axis: Vec2) -> Self {
unsafe {
UnionCast {
a: [x_axis.x, x_axis.y, y_axis.x, y_axis.y],
}
.v
}
}
/// Creates a 2x2 matrix from a `[f32; 4]` array stored in column major order.
/// If your data is stored in row major you will need to `transpose` the returned
/// matrix.
#[inline]
#[must_use]
pub const fn from_cols_array(m: &[f32; 4]) -> Self {
Self::new(m[0], m[1], m[2], m[3])
}
/// Creates a `[f32; 4]` array storing data in column major order.
/// If you require data in row major order `transpose` the matrix first.
#[inline]
#[must_use]
pub const fn to_cols_array(&self) -> [f32; 4] {
unsafe { *(self as *const Self as *const [f32; 4]) }
}
/// Creates a 2x2 matrix from a `[[f32; 2]; 2]` 2D array stored in column major order.
/// If your data is in row major order you will need to `transpose` the returned
/// matrix.
#[inline]
#[must_use]
pub const fn from_cols_array_2d(m: &[[f32; 2]; 2]) -> Self {
Self::from_cols(Vec2::from_array(m[0]), Vec2::from_array(m[1]))
}
/// Creates a `[[f32; 2]; 2]` 2D array storing data in column major order.
/// If you require data in row major order `transpose` the matrix first.
#[inline]
#[must_use]
pub const fn to_cols_array_2d(&self) -> [[f32; 2]; 2] {
unsafe { *(self as *const Self as *const [[f32; 2]; 2]) }
}
/// Creates a 2x2 matrix with its diagonal set to `diagonal` and all other entries set to 0.
#[doc(alias = "scale")]
#[inline]
#[must_use]
pub const fn from_diagonal(diagonal: Vec2) -> Self {
Self::new(diagonal.x, 0.0, 0.0, diagonal.y)
}
/// Creates a 2x2 matrix containing the combining non-uniform `scale` and rotation of
/// `angle` (in radians).
#[inline]
#[must_use]
pub fn from_scale_angle(scale: Vec2, angle: f32) -> Self {
let (sin, cos) = math::sin_cos(angle);
Self::new(cos * scale.x, sin * scale.x, -sin * scale.y, cos * scale.y)
}
/// Creates a 2x2 matrix containing a rotation of `angle` (in radians).
#[inline]
#[must_use]
pub fn from_angle(angle: f32) -> Self {
let (sin, cos) = math::sin_cos(angle);
Self::new(cos, sin, -sin, cos)
}
/// Creates a 2x2 matrix from a 3x3 matrix, discarding the 2nd row and column.
#[inline]
#[must_use]
pub fn from_mat3(m: Mat3) -> Self {
Self::from_cols(m.x_axis.xy(), m.y_axis.xy())
}
/// Creates a 2x2 matrix from the minor of the given 3x3 matrix, discarding the `i`th column
/// and `j`th row.
///
/// # Panics
///
/// Panics if `i` or `j` is greater than 2.
#[inline]
#[must_use]
pub fn from_mat3_minor(m: Mat3, i: usize, j: usize) -> Self {
match (i, j) {
(0, 0) => Self::from_cols(m.y_axis.yz(), m.z_axis.yz()),
(0, 1) => Self::from_cols(m.y_axis.xz(), m.z_axis.xz()),
(0, 2) => Self::from_cols(m.y_axis.xy(), m.z_axis.xy()),
(1, 0) => Self::from_cols(m.x_axis.yz(), m.z_axis.yz()),
(1, 1) => Self::from_cols(m.x_axis.xz(), m.z_axis.xz()),
(1, 2) => Self::from_cols(m.x_axis.xy(), m.z_axis.xy()),
(2, 0) => Self::from_cols(m.x_axis.yz(), m.y_axis.yz()),
(2, 1) => Self::from_cols(m.x_axis.xz(), m.y_axis.xz()),
(2, 2) => Self::from_cols(m.x_axis.xy(), m.y_axis.xy()),
_ => panic!("index out of bounds"),
}
}
/// Creates a 2x2 matrix from a 3x3 matrix, discarding the 2nd row and column.
#[inline]
#[must_use]
pub fn from_mat3a(m: Mat3A) -> Self {
Self::from_cols(m.x_axis.xy(), m.y_axis.xy())
}
/// Creates a 2x2 matrix from the minor of the given 3x3 matrix, discarding the `i`th column
/// and `j`th row.
///
/// # Panics
///
/// Panics if `i` or `j` is greater than 2.
#[inline]
#[must_use]
pub fn from_mat3a_minor(m: Mat3A, i: usize, j: usize) -> Self {
match (i, j) {
(0, 0) => Self::from_cols(m.y_axis.yz(), m.z_axis.yz()),
(0, 1) => Self::from_cols(m.y_axis.xz(), m.z_axis.xz()),
(0, 2) => Self::from_cols(m.y_axis.xy(), m.z_axis.xy()),
(1, 0) => Self::from_cols(m.x_axis.yz(), m.z_axis.yz()),
(1, 1) => Self::from_cols(m.x_axis.xz(), m.z_axis.xz()),
(1, 2) => Self::from_cols(m.x_axis.xy(), m.z_axis.xy()),
(2, 0) => Self::from_cols(m.x_axis.yz(), m.y_axis.yz()),
(2, 1) => Self::from_cols(m.x_axis.xz(), m.y_axis.xz()),
(2, 2) => Self::from_cols(m.x_axis.xy(), m.y_axis.xy()),
_ => panic!("index out of bounds"),
}
}
/// Creates a 2x2 matrix from the first 4 values in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 4 elements long.
#[inline]
#[must_use]
pub const fn from_cols_slice(slice: &[f32]) -> Self {
Self::new(slice[0], slice[1], slice[2], slice[3])
}
/// Writes the columns of `self` to the first 4 elements in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 4 elements long.
#[inline]
pub fn write_cols_to_slice(self, slice: &mut [f32]) {
slice[0] = self.x_axis.x;
slice[1] = self.x_axis.y;
slice[2] = self.y_axis.x;
slice[3] = self.y_axis.y;
}
/// Returns the matrix column for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 1.
#[inline]
#[must_use]
pub fn col(&self, index: usize) -> Vec2 {
match index {
0 => self.x_axis,
1 => self.y_axis,
_ => panic!("index out of bounds"),
}
}
/// Returns a mutable reference to the matrix column for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 1.
#[inline]
pub fn col_mut(&mut self, index: usize) -> &mut Vec2 {
match index {
0 => &mut self.x_axis,
1 => &mut self.y_axis,
_ => panic!("index out of bounds"),
}
}
/// Returns the matrix row for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 1.
#[inline]
#[must_use]
pub fn row(&self, index: usize) -> Vec2 {
match index {
0 => Vec2::new(self.x_axis.x, self.y_axis.x),
1 => Vec2::new(self.x_axis.y, self.y_axis.y),
_ => panic!("index out of bounds"),
}
}
/// Returns `true` if, and only if, all elements are finite.
/// If any element is either `NaN`, positive or negative infinity, this will return `false`.
#[inline]
#[must_use]
pub fn is_finite(&self) -> bool {
self.x_axis.is_finite() && self.y_axis.is_finite()
}
/// Returns `true` if any elements are `NaN`.
#[inline]
#[must_use]
pub fn is_nan(&self) -> bool {
self.x_axis.is_nan() || self.y_axis.is_nan()
}
/// Returns the transpose of `self`.
#[inline]
#[must_use]
pub fn transpose(&self) -> Self {
Self(unsafe {
vsetq_lane_f32(
vgetq_lane_f32(self.0, 2),
vsetq_lane_f32(vgetq_lane_f32(self.0, 1), self.0, 2),
1,
)
})
}
/// Returns the determinant of `self`.
#[inline]
#[must_use]
pub fn determinant(&self) -> f32 {
unsafe {
let abcd = self.0;
let badc = vrev64q_f32(abcd);
let dcba = vextq_f32(badc, badc, 2);
let prod = vmulq_f32(abcd, dcba);
let det = vsubq_f32(prod, vdupq_laneq_f32(prod, 1));
vgetq_lane_f32(det, 0)
}
}
/// Returns the inverse of `self`.
///
/// If the matrix is not invertible the returned matrix will be invalid.
///
/// # Panics
///
/// Will panic if the determinant of `self` is zero when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn inverse(&self) -> Self {
unsafe {
const SIGN: float32x4_t = crate::neon::f32x4_from_array([1.0, -1.0, -1.0, 1.0]);
let abcd = self.0;
let badc = vrev64q_f32(abcd);
let dcba = vextq_f32(badc, badc, 2);
let prod = vmulq_f32(abcd, dcba);
let sub = vsubq_f32(prod, vdupq_laneq_f32(prod, 1));
let det = vdupq_laneq_f32(sub, 0);
let tmp = vdivq_f32(SIGN, det);
glam_assert!(Mat2(tmp).is_finite());
//let dbca = simd_swizzle!(abcd, [3, 1, 2, 0]);
let dbca = vsetq_lane_f32(
vgetq_lane_f32(abcd, 0),
vsetq_lane_f32(vgetq_lane_f32(abcd, 3), abcd, 0),
3,
);
Self(vmulq_f32(dbca, tmp))
}
}
/// Transforms a 2D vector.
#[inline]
#[must_use]
pub fn mul_vec2(&self, rhs: Vec2) -> Vec2 {
unsafe {
let abcd = self.0;
let xxyy = vld1q_f32([rhs.x, rhs.x, rhs.y, rhs.y].as_ptr());
let axbxcydy = vmulq_f32(abcd, xxyy);
// let cydyaxbx = simd_swizzle!(axbxcydy, [2, 3, 0, 1]);
let cydyaxbx = vextq_f32(axbxcydy, axbxcydy, 2);
let result = vaddq_f32(axbxcydy, cydyaxbx);
*(&result as *const float32x4_t as *const Vec2)
}
}
/// Multiplies two 2x2 matrices.
#[inline]
#[must_use]
pub fn mul_mat2(&self, rhs: &Self) -> Self {
unsafe {
let abcd = self.0;
let xxyy0 = vzip1q_f32(rhs.0, rhs.0);
let xxyy1 = vzip2q_f32(rhs.0, rhs.0);
let axbxcydy0 = vmulq_f32(abcd, xxyy0);
let axbxcydy1 = vmulq_f32(abcd, xxyy1);
let cydyaxbx0 = vextq_f32(axbxcydy0, axbxcydy0, 2);
let cydyaxbx1 = vextq_f32(axbxcydy1, axbxcydy1, 2);
let result0 = vaddq_f32(axbxcydy0, cydyaxbx0);
let result1 = vaddq_f32(axbxcydy1, cydyaxbx1);
Self(vreinterpretq_f32_u64(vsetq_lane_u64(
vgetq_lane_u64(vreinterpretq_u64_f32(result1), 0),
vreinterpretq_u64_f32(result0),
1,
)))
}
}
/// Adds two 2x2 matrices.
#[inline]
#[must_use]
pub fn add_mat2(&self, rhs: &Self) -> Self {
Self(unsafe { vaddq_f32(self.0, rhs.0) })
}
/// Subtracts two 2x2 matrices.
#[inline]
#[must_use]
pub fn sub_mat2(&self, rhs: &Self) -> Self {
Self(unsafe { vsubq_f32(self.0, rhs.0) })
}
/// Multiplies a 2x2 matrix by a scalar.
#[inline]
#[must_use]
pub fn mul_scalar(&self, rhs: f32) -> Self {
Self(unsafe { vmulq_f32(self.0, vld1q_dup_f32(&rhs)) })
}
/// Divides a 2x2 matrix by a scalar.
#[inline]
#[must_use]
pub fn div_scalar(&self, rhs: f32) -> Self {
Self(unsafe { vdivq_f32(self.0, vld1q_dup_f32(&rhs)) })
}
/// Returns true if the absolute difference of all elements between `self` and `rhs`
/// is less than or equal to `max_abs_diff`.
///
/// This can be used to compare if two matrices contain similar elements. It works best
/// when comparing with a known value. The `max_abs_diff` that should be used used
/// depends on the values being compared against.
///
/// For more see
/// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
#[inline]
#[must_use]
pub fn abs_diff_eq(&self, rhs: Self, max_abs_diff: f32) -> bool {
self.x_axis.abs_diff_eq(rhs.x_axis, max_abs_diff)
&& self.y_axis.abs_diff_eq(rhs.y_axis, max_abs_diff)
}
/// Takes the absolute value of each element in `self`
#[inline]
#[must_use]
pub fn abs(&self) -> Self {
Self::from_cols(self.x_axis.abs(), self.y_axis.abs())
}
#[inline]
pub fn as_dmat2(&self) -> DMat2 {
DMat2::from_cols(self.x_axis.as_dvec2(), self.y_axis.as_dvec2())
}
}
impl Default for Mat2 {
#[inline]
fn default() -> Self {
Self::IDENTITY
}
}
impl Add<Mat2> for Mat2 {
type Output = Self;
#[inline]
fn add(self, rhs: Self) -> Self::Output {
self.add_mat2(&rhs)
}
}
impl AddAssign<Mat2> for Mat2 {
#[inline]
fn add_assign(&mut self, rhs: Self) {
*self = self.add_mat2(&rhs);
}
}
impl Sub<Mat2> for Mat2 {
type Output = Self;
#[inline]
fn sub(self, rhs: Self) -> Self::Output {
self.sub_mat2(&rhs)
}
}
impl SubAssign<Mat2> for Mat2 {
#[inline]
fn sub_assign(&mut self, rhs: Self) {
*self = self.sub_mat2(&rhs);
}
}
impl Neg for Mat2 {
type Output = Self;
#[inline]
fn neg(self) -> Self::Output {
Self(unsafe { vnegq_f32(self.0) })
}
}
impl Mul<Mat2> for Mat2 {
type Output = Self;
#[inline]
fn mul(self, rhs: Self) -> Self::Output {
self.mul_mat2(&rhs)
}
}
impl MulAssign<Mat2> for Mat2 {
#[inline]
fn mul_assign(&mut self, rhs: Self) {
*self = self.mul_mat2(&rhs);
}
}
impl Mul<Vec2> for Mat2 {
type Output = Vec2;
#[inline]
fn mul(self, rhs: Vec2) -> Self::Output {
self.mul_vec2(rhs)
}
}
impl Mul<Mat2> for f32 {
type Output = Mat2;
#[inline]
fn mul(self, rhs: Mat2) -> Self::Output {
rhs.mul_scalar(self)
}
}
impl Mul<f32> for Mat2 {
type Output = Self;
#[inline]
fn mul(self, rhs: f32) -> Self::Output {
self.mul_scalar(rhs)
}
}
impl MulAssign<f32> for Mat2 {
#[inline]
fn mul_assign(&mut self, rhs: f32) {
*self = self.mul_scalar(rhs);
}
}
impl Div<Mat2> for f32 {
type Output = Mat2;
#[inline]
fn div(self, rhs: Mat2) -> Self::Output {
rhs.div_scalar(self)
}
}
impl Div<f32> for Mat2 {
type Output = Self;
#[inline]
fn div(self, rhs: f32) -> Self::Output {
self.div_scalar(rhs)
}
}
impl DivAssign<f32> for Mat2 {
#[inline]
fn div_assign(&mut self, rhs: f32) {
*self = self.div_scalar(rhs);
}
}
impl Sum<Self> for Mat2 {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Self::ZERO, Self::add)
}
}
impl<'a> Sum<&'a Self> for Mat2 {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
}
}
impl Product for Mat2 {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Self::IDENTITY, Self::mul)
}
}
impl<'a> Product<&'a Self> for Mat2 {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::IDENTITY, |a, &b| Self::mul(a, b))
}
}
impl PartialEq for Mat2 {
#[inline]
fn eq(&self, rhs: &Self) -> bool {
self.x_axis.eq(&rhs.x_axis) && self.y_axis.eq(&rhs.y_axis)
}
}
#[cfg(not(target_arch = "spirv"))]
impl AsRef<[f32; 4]> for Mat2 {
#[inline]
fn as_ref(&self) -> &[f32; 4] {
unsafe { &*(self as *const Self as *const [f32; 4]) }
}
}
#[cfg(not(target_arch = "spirv"))]
impl AsMut<[f32; 4]> for Mat2 {
#[inline]
fn as_mut(&mut self) -> &mut [f32; 4] {
unsafe { &mut *(self as *mut Self as *mut [f32; 4]) }
}
}
impl core::ops::Deref for Mat2 {
type Target = crate::deref::Cols2<Vec2>;
#[inline]
fn deref(&self) -> &Self::Target {
unsafe { &*(self as *const Self as *const Self::Target) }
}
}
impl core::ops::DerefMut for Mat2 {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { &mut *(self as *mut Self as *mut Self::Target) }
}
}
impl fmt::Debug for Mat2 {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct(stringify!(Mat2))
.field("x_axis", &self.x_axis)
.field("y_axis", &self.y_axis)
.finish()
}
}
impl fmt::Display for Mat2 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(p) = f.precision() {
write!(f, "[{:.*}, {:.*}]", p, self.x_axis, p, self.y_axis)
} else {
write!(f, "[{}, {}]", self.x_axis, self.y_axis)
}
}
}
+937
View File
@@ -0,0 +1,937 @@
// Generated from mat.rs.tera template. Edit the template, not the generated file.
use crate::{
euler::{FromEuler, ToEuler},
f32::math,
swizzles::*,
DMat3, EulerRot, Mat2, Mat3, Mat4, Quat, Vec2, Vec3, Vec3A,
};
use core::fmt;
use core::iter::{Product, Sum};
use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
use core::arch::aarch64::*;
/// Creates a 3x3 matrix from three column vectors.
#[inline(always)]
#[must_use]
pub const fn mat3a(x_axis: Vec3A, y_axis: Vec3A, z_axis: Vec3A) -> Mat3A {
Mat3A::from_cols(x_axis, y_axis, z_axis)
}
/// A 3x3 column major matrix.
///
/// This 3x3 matrix type features convenience methods for creating and using linear and
/// affine transformations. If you are primarily dealing with 2D affine transformations the
/// [`Affine2`](crate::Affine2) type is much faster and more space efficient than
/// using a 3x3 matrix.
///
/// Linear transformations including 3D rotation and scale can be created using methods
/// such as [`Self::from_diagonal()`], [`Self::from_quat()`], [`Self::from_axis_angle()`],
/// [`Self::from_rotation_x()`], [`Self::from_rotation_y()`], or
/// [`Self::from_rotation_z()`].
///
/// The resulting matrices can be use to transform 3D vectors using regular vector
/// multiplication.
///
/// Affine transformations including 2D translation, rotation and scale can be created
/// using methods such as [`Self::from_translation()`], [`Self::from_angle()`],
/// [`Self::from_scale()`] and [`Self::from_scale_angle_translation()`].
///
/// The [`Self::transform_point2()`] and [`Self::transform_vector2()`] convenience methods
/// are provided for performing affine transforms on 2D vectors and points. These multiply
/// 2D inputs as 3D vectors with an implicit `z` value of `1` for points and `0` for
/// vectors respectively. These methods assume that `Self` contains a valid affine
/// transform.
#[derive(Clone, Copy)]
#[repr(C)]
pub struct Mat3A {
pub x_axis: Vec3A,
pub y_axis: Vec3A,
pub z_axis: Vec3A,
}
impl Mat3A {
/// A 3x3 matrix with all elements set to `0.0`.
pub const ZERO: Self = Self::from_cols(Vec3A::ZERO, Vec3A::ZERO, Vec3A::ZERO);
/// A 3x3 identity matrix, where all diagonal elements are `1`, and all off-diagonal elements are `0`.
pub const IDENTITY: Self = Self::from_cols(Vec3A::X, Vec3A::Y, Vec3A::Z);
/// All NAN:s.
pub const NAN: Self = Self::from_cols(Vec3A::NAN, Vec3A::NAN, Vec3A::NAN);
#[allow(clippy::too_many_arguments)]
#[inline(always)]
#[must_use]
const fn new(
m00: f32,
m01: f32,
m02: f32,
m10: f32,
m11: f32,
m12: f32,
m20: f32,
m21: f32,
m22: f32,
) -> Self {
Self {
x_axis: Vec3A::new(m00, m01, m02),
y_axis: Vec3A::new(m10, m11, m12),
z_axis: Vec3A::new(m20, m21, m22),
}
}
/// Creates a 3x3 matrix from three column vectors.
#[inline(always)]
#[must_use]
pub const fn from_cols(x_axis: Vec3A, y_axis: Vec3A, z_axis: Vec3A) -> Self {
Self {
x_axis,
y_axis,
z_axis,
}
}
/// Creates a 3x3 matrix from a `[f32; 9]` array stored in column major order.
/// If your data is stored in row major you will need to `transpose` the returned
/// matrix.
#[inline]
#[must_use]
pub const fn from_cols_array(m: &[f32; 9]) -> Self {
Self::new(m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8])
}
/// Creates a `[f32; 9]` array storing data in column major order.
/// If you require data in row major order `transpose` the matrix first.
#[inline]
#[must_use]
pub const fn to_cols_array(&self) -> [f32; 9] {
let [x_axis_x, x_axis_y, x_axis_z] = self.x_axis.to_array();
let [y_axis_x, y_axis_y, y_axis_z] = self.y_axis.to_array();
let [z_axis_x, z_axis_y, z_axis_z] = self.z_axis.to_array();
[
x_axis_x, x_axis_y, x_axis_z, y_axis_x, y_axis_y, y_axis_z, z_axis_x, z_axis_y,
z_axis_z,
]
}
/// Creates a 3x3 matrix from a `[[f32; 3]; 3]` 3D array stored in column major order.
/// If your data is in row major order you will need to `transpose` the returned
/// matrix.
#[inline]
#[must_use]
pub const fn from_cols_array_2d(m: &[[f32; 3]; 3]) -> Self {
Self::from_cols(
Vec3A::from_array(m[0]),
Vec3A::from_array(m[1]),
Vec3A::from_array(m[2]),
)
}
/// Creates a `[[f32; 3]; 3]` 3D array storing data in column major order.
/// If you require data in row major order `transpose` the matrix first.
#[inline]
#[must_use]
pub const fn to_cols_array_2d(&self) -> [[f32; 3]; 3] {
[
self.x_axis.to_array(),
self.y_axis.to_array(),
self.z_axis.to_array(),
]
}
/// Creates a 3x3 matrix with its diagonal set to `diagonal` and all other entries set to 0.
#[doc(alias = "scale")]
#[inline]
#[must_use]
pub const fn from_diagonal(diagonal: Vec3) -> Self {
Self::new(
diagonal.x, 0.0, 0.0, 0.0, diagonal.y, 0.0, 0.0, 0.0, diagonal.z,
)
}
/// Creates a 3x3 matrix from a 4x4 matrix, discarding the 4th row and column.
#[inline]
#[must_use]
pub fn from_mat4(m: Mat4) -> Self {
Self::from_cols(
Vec3A::from_vec4(m.x_axis),
Vec3A::from_vec4(m.y_axis),
Vec3A::from_vec4(m.z_axis),
)
}
/// Creates a 3x3 matrix from the minor of the given 4x4 matrix, discarding the `i`th column
/// and `j`th row.
///
/// # Panics
///
/// Panics if `i` or `j` is greater than 3.
#[inline]
#[must_use]
pub fn from_mat4_minor(m: Mat4, i: usize, j: usize) -> Self {
match (i, j) {
(0, 0) => Self::from_cols(
Vec3A::from_vec4(m.y_axis.yzww()),
Vec3A::from_vec4(m.z_axis.yzww()),
Vec3A::from_vec4(m.w_axis.yzww()),
),
(0, 1) => Self::from_cols(
Vec3A::from_vec4(m.y_axis.xzww()),
Vec3A::from_vec4(m.z_axis.xzww()),
Vec3A::from_vec4(m.w_axis.xzww()),
),
(0, 2) => Self::from_cols(
Vec3A::from_vec4(m.y_axis.xyww()),
Vec3A::from_vec4(m.z_axis.xyww()),
Vec3A::from_vec4(m.w_axis.xyww()),
),
(0, 3) => Self::from_cols(
Vec3A::from_vec4(m.y_axis.xyzw()),
Vec3A::from_vec4(m.z_axis.xyzw()),
Vec3A::from_vec4(m.w_axis.xyzw()),
),
(1, 0) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.yzww()),
Vec3A::from_vec4(m.z_axis.yzww()),
Vec3A::from_vec4(m.w_axis.yzww()),
),
(1, 1) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xzww()),
Vec3A::from_vec4(m.z_axis.xzww()),
Vec3A::from_vec4(m.w_axis.xzww()),
),
(1, 2) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xyww()),
Vec3A::from_vec4(m.z_axis.xyww()),
Vec3A::from_vec4(m.w_axis.xyww()),
),
(1, 3) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xyzw()),
Vec3A::from_vec4(m.z_axis.xyzw()),
Vec3A::from_vec4(m.w_axis.xyzw()),
),
(2, 0) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.yzww()),
Vec3A::from_vec4(m.y_axis.yzww()),
Vec3A::from_vec4(m.w_axis.yzww()),
),
(2, 1) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xzww()),
Vec3A::from_vec4(m.y_axis.xzww()),
Vec3A::from_vec4(m.w_axis.xzww()),
),
(2, 2) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xyww()),
Vec3A::from_vec4(m.y_axis.xyww()),
Vec3A::from_vec4(m.w_axis.xyww()),
),
(2, 3) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xyzw()),
Vec3A::from_vec4(m.y_axis.xyzw()),
Vec3A::from_vec4(m.w_axis.xyzw()),
),
(3, 0) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.yzww()),
Vec3A::from_vec4(m.y_axis.yzww()),
Vec3A::from_vec4(m.z_axis.yzww()),
),
(3, 1) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xzww()),
Vec3A::from_vec4(m.y_axis.xzww()),
Vec3A::from_vec4(m.z_axis.xzww()),
),
(3, 2) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xyww()),
Vec3A::from_vec4(m.y_axis.xyww()),
Vec3A::from_vec4(m.z_axis.xyww()),
),
(3, 3) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xyzw()),
Vec3A::from_vec4(m.y_axis.xyzw()),
Vec3A::from_vec4(m.z_axis.xyzw()),
),
_ => panic!("index out of bounds"),
}
}
/// Creates a 3D rotation matrix from the given quaternion.
///
/// # Panics
///
/// Will panic if `rotation` is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn from_quat(rotation: Quat) -> Self {
glam_assert!(rotation.is_normalized());
let x2 = rotation.x + rotation.x;
let y2 = rotation.y + rotation.y;
let z2 = rotation.z + rotation.z;
let xx = rotation.x * x2;
let xy = rotation.x * y2;
let xz = rotation.x * z2;
let yy = rotation.y * y2;
let yz = rotation.y * z2;
let zz = rotation.z * z2;
let wx = rotation.w * x2;
let wy = rotation.w * y2;
let wz = rotation.w * z2;
Self::from_cols(
Vec3A::new(1.0 - (yy + zz), xy + wz, xz - wy),
Vec3A::new(xy - wz, 1.0 - (xx + zz), yz + wx),
Vec3A::new(xz + wy, yz - wx, 1.0 - (xx + yy)),
)
}
/// Creates a 3D rotation matrix from a normalized rotation `axis` and `angle` (in
/// radians).
///
/// # Panics
///
/// Will panic if `axis` is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn from_axis_angle(axis: Vec3, angle: f32) -> Self {
glam_assert!(axis.is_normalized());
let (sin, cos) = math::sin_cos(angle);
let (xsin, ysin, zsin) = axis.mul(sin).into();
let (x, y, z) = axis.into();
let (x2, y2, z2) = axis.mul(axis).into();
let omc = 1.0 - cos;
let xyomc = x * y * omc;
let xzomc = x * z * omc;
let yzomc = y * z * omc;
Self::from_cols(
Vec3A::new(x2 * omc + cos, xyomc + zsin, xzomc - ysin),
Vec3A::new(xyomc - zsin, y2 * omc + cos, yzomc + xsin),
Vec3A::new(xzomc + ysin, yzomc - xsin, z2 * omc + cos),
)
}
/// Creates a 3D rotation matrix from the given euler rotation sequence and the angles (in
/// radians).
#[inline]
#[must_use]
pub fn from_euler(order: EulerRot, a: f32, b: f32, c: f32) -> Self {
Self::from_euler_angles(order, a, b, c)
}
/// Extract Euler angles with the given Euler rotation order.
///
/// Note if the input matrix contains scales, shears, or other non-rotation transformations then
/// the resulting Euler angles will be ill-defined.
///
/// # Panics
///
/// Will panic if any input matrix column is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn to_euler(&self, order: EulerRot) -> (f32, f32, f32) {
glam_assert!(
self.x_axis.is_normalized()
&& self.y_axis.is_normalized()
&& self.z_axis.is_normalized()
);
self.to_euler_angles(order)
}
/// Creates a 3D rotation matrix from `angle` (in radians) around the x axis.
#[inline]
#[must_use]
pub fn from_rotation_x(angle: f32) -> Self {
let (sina, cosa) = math::sin_cos(angle);
Self::from_cols(
Vec3A::X,
Vec3A::new(0.0, cosa, sina),
Vec3A::new(0.0, -sina, cosa),
)
}
/// Creates a 3D rotation matrix from `angle` (in radians) around the y axis.
#[inline]
#[must_use]
pub fn from_rotation_y(angle: f32) -> Self {
let (sina, cosa) = math::sin_cos(angle);
Self::from_cols(
Vec3A::new(cosa, 0.0, -sina),
Vec3A::Y,
Vec3A::new(sina, 0.0, cosa),
)
}
/// Creates a 3D rotation matrix from `angle` (in radians) around the z axis.
#[inline]
#[must_use]
pub fn from_rotation_z(angle: f32) -> Self {
let (sina, cosa) = math::sin_cos(angle);
Self::from_cols(
Vec3A::new(cosa, sina, 0.0),
Vec3A::new(-sina, cosa, 0.0),
Vec3A::Z,
)
}
/// Creates an affine transformation matrix from the given 2D `translation`.
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
#[inline]
#[must_use]
pub fn from_translation(translation: Vec2) -> Self {
Self::from_cols(
Vec3A::X,
Vec3A::Y,
Vec3A::new(translation.x, translation.y, 1.0),
)
}
/// Creates an affine transformation matrix from the given 2D rotation `angle` (in
/// radians).
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
#[inline]
#[must_use]
pub fn from_angle(angle: f32) -> Self {
let (sin, cos) = math::sin_cos(angle);
Self::from_cols(
Vec3A::new(cos, sin, 0.0),
Vec3A::new(-sin, cos, 0.0),
Vec3A::Z,
)
}
/// Creates an affine transformation matrix from the given 2D `scale`, rotation `angle` (in
/// radians) and `translation`.
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
#[inline]
#[must_use]
pub fn from_scale_angle_translation(scale: Vec2, angle: f32, translation: Vec2) -> Self {
let (sin, cos) = math::sin_cos(angle);
Self::from_cols(
Vec3A::new(cos * scale.x, sin * scale.x, 0.0),
Vec3A::new(-sin * scale.y, cos * scale.y, 0.0),
Vec3A::new(translation.x, translation.y, 1.0),
)
}
/// Creates an affine transformation matrix from the given non-uniform 2D `scale`.
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
///
/// # Panics
///
/// Will panic if all elements of `scale` are zero when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn from_scale(scale: Vec2) -> Self {
// Do not panic as long as any component is non-zero
glam_assert!(scale.cmpne(Vec2::ZERO).any());
Self::from_cols(
Vec3A::new(scale.x, 0.0, 0.0),
Vec3A::new(0.0, scale.y, 0.0),
Vec3A::Z,
)
}
/// Creates an affine transformation matrix from the given 2x2 matrix.
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
#[inline]
pub fn from_mat2(m: Mat2) -> Self {
Self::from_cols((m.x_axis, 0.0).into(), (m.y_axis, 0.0).into(), Vec3A::Z)
}
/// Creates a 3x3 matrix from the first 9 values in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 9 elements long.
#[inline]
#[must_use]
pub const fn from_cols_slice(slice: &[f32]) -> Self {
Self::new(
slice[0], slice[1], slice[2], slice[3], slice[4], slice[5], slice[6], slice[7],
slice[8],
)
}
/// Writes the columns of `self` to the first 9 elements in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 9 elements long.
#[inline]
pub fn write_cols_to_slice(self, slice: &mut [f32]) {
slice[0] = self.x_axis.x;
slice[1] = self.x_axis.y;
slice[2] = self.x_axis.z;
slice[3] = self.y_axis.x;
slice[4] = self.y_axis.y;
slice[5] = self.y_axis.z;
slice[6] = self.z_axis.x;
slice[7] = self.z_axis.y;
slice[8] = self.z_axis.z;
}
/// Returns the matrix column for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 2.
#[inline]
#[must_use]
pub fn col(&self, index: usize) -> Vec3A {
match index {
0 => self.x_axis,
1 => self.y_axis,
2 => self.z_axis,
_ => panic!("index out of bounds"),
}
}
/// Returns a mutable reference to the matrix column for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 2.
#[inline]
pub fn col_mut(&mut self, index: usize) -> &mut Vec3A {
match index {
0 => &mut self.x_axis,
1 => &mut self.y_axis,
2 => &mut self.z_axis,
_ => panic!("index out of bounds"),
}
}
/// Returns the matrix row for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 2.
#[inline]
#[must_use]
pub fn row(&self, index: usize) -> Vec3A {
match index {
0 => Vec3A::new(self.x_axis.x, self.y_axis.x, self.z_axis.x),
1 => Vec3A::new(self.x_axis.y, self.y_axis.y, self.z_axis.y),
2 => Vec3A::new(self.x_axis.z, self.y_axis.z, self.z_axis.z),
_ => panic!("index out of bounds"),
}
}
/// Returns `true` if, and only if, all elements are finite.
/// If any element is either `NaN`, positive or negative infinity, this will return `false`.
#[inline]
#[must_use]
pub fn is_finite(&self) -> bool {
self.x_axis.is_finite() && self.y_axis.is_finite() && self.z_axis.is_finite()
}
/// Returns `true` if any elements are `NaN`.
#[inline]
#[must_use]
pub fn is_nan(&self) -> bool {
self.x_axis.is_nan() || self.y_axis.is_nan() || self.z_axis.is_nan()
}
/// Returns the transpose of `self`.
#[inline]
#[must_use]
pub fn transpose(&self) -> Self {
let x = self.x_axis.0;
let y = self.y_axis.0;
let z = self.z_axis.0;
unsafe {
let tmp0 = vreinterpretq_f32_u64(vsetq_lane_u64(
vgetq_lane_u64(vreinterpretq_u64_f32(y), 0),
vreinterpretq_u64_f32(x),
1,
));
let tmp1 = vreinterpretq_f32_u64(vzip2q_u64(
vreinterpretq_u64_f32(x),
vreinterpretq_u64_f32(y),
));
Mat3A::from_cols(
Vec3A::from(vsetq_lane_f32(vgetq_lane_f32(z, 0), vuzp1q_f32(tmp0, z), 3)),
Vec3A::from(vuzp2q_f32(tmp0, vdupq_laneq_f32(z, 1))),
Vec3A::from(vsetq_lane_f32(vgetq_lane_f32(z, 2), vuzp1q_f32(tmp1, z), 2)),
)
}
}
/// Returns the determinant of `self`.
#[inline]
#[must_use]
pub fn determinant(&self) -> f32 {
self.z_axis.dot(self.x_axis.cross(self.y_axis))
}
/// Returns the inverse of `self`.
///
/// If the matrix is not invertible the returned matrix will be invalid.
///
/// # Panics
///
/// Will panic if the determinant of `self` is zero when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn inverse(&self) -> Self {
let tmp0 = self.y_axis.cross(self.z_axis);
let tmp1 = self.z_axis.cross(self.x_axis);
let tmp2 = self.x_axis.cross(self.y_axis);
let det = self.z_axis.dot(tmp2);
glam_assert!(det != 0.0);
let inv_det = Vec3A::splat(det.recip());
Self::from_cols(tmp0.mul(inv_det), tmp1.mul(inv_det), tmp2.mul(inv_det)).transpose()
}
/// Transforms the given 2D vector as a point.
///
/// This is the equivalent of multiplying `rhs` as a 3D vector where `z` is `1`.
///
/// This method assumes that `self` contains a valid affine transform.
///
/// # Panics
///
/// Will panic if the 2nd row of `self` is not `(0, 0, 1)` when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn transform_point2(&self, rhs: Vec2) -> Vec2 {
glam_assert!(self.row(2).abs_diff_eq(Vec3A::Z, 1e-6));
Mat2::from_cols(self.x_axis.xy(), self.y_axis.xy()) * rhs + self.z_axis.xy()
}
/// Rotates the given 2D vector.
///
/// This is the equivalent of multiplying `rhs` as a 3D vector where `z` is `0`.
///
/// This method assumes that `self` contains a valid affine transform.
///
/// # Panics
///
/// Will panic if the 2nd row of `self` is not `(0, 0, 1)` when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn transform_vector2(&self, rhs: Vec2) -> Vec2 {
glam_assert!(self.row(2).abs_diff_eq(Vec3A::Z, 1e-6));
Mat2::from_cols(self.x_axis.xy(), self.y_axis.xy()) * rhs
}
/// Transforms a 3D vector.
#[inline]
#[must_use]
pub fn mul_vec3(&self, rhs: Vec3) -> Vec3 {
self.mul_vec3a(rhs.into()).into()
}
/// Transforms a [`Vec3A`].
#[inline]
#[must_use]
pub fn mul_vec3a(&self, rhs: Vec3A) -> Vec3A {
let mut res = self.x_axis.mul(rhs.xxx());
res = res.add(self.y_axis.mul(rhs.yyy()));
res = res.add(self.z_axis.mul(rhs.zzz()));
res
}
/// Multiplies two 3x3 matrices.
#[inline]
#[must_use]
pub fn mul_mat3(&self, rhs: &Self) -> Self {
Self::from_cols(
self.mul(rhs.x_axis),
self.mul(rhs.y_axis),
self.mul(rhs.z_axis),
)
}
/// Adds two 3x3 matrices.
#[inline]
#[must_use]
pub fn add_mat3(&self, rhs: &Self) -> Self {
Self::from_cols(
self.x_axis.add(rhs.x_axis),
self.y_axis.add(rhs.y_axis),
self.z_axis.add(rhs.z_axis),
)
}
/// Subtracts two 3x3 matrices.
#[inline]
#[must_use]
pub fn sub_mat3(&self, rhs: &Self) -> Self {
Self::from_cols(
self.x_axis.sub(rhs.x_axis),
self.y_axis.sub(rhs.y_axis),
self.z_axis.sub(rhs.z_axis),
)
}
/// Multiplies a 3x3 matrix by a scalar.
#[inline]
#[must_use]
pub fn mul_scalar(&self, rhs: f32) -> Self {
Self::from_cols(
self.x_axis.mul(rhs),
self.y_axis.mul(rhs),
self.z_axis.mul(rhs),
)
}
/// Divides a 3x3 matrix by a scalar.
#[inline]
#[must_use]
pub fn div_scalar(&self, rhs: f32) -> Self {
let rhs = Vec3A::splat(rhs);
Self::from_cols(
self.x_axis.div(rhs),
self.y_axis.div(rhs),
self.z_axis.div(rhs),
)
}
/// Returns true if the absolute difference of all elements between `self` and `rhs`
/// is less than or equal to `max_abs_diff`.
///
/// This can be used to compare if two matrices contain similar elements. It works best
/// when comparing with a known value. The `max_abs_diff` that should be used used
/// depends on the values being compared against.
///
/// For more see
/// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
#[inline]
#[must_use]
pub fn abs_diff_eq(&self, rhs: Self, max_abs_diff: f32) -> bool {
self.x_axis.abs_diff_eq(rhs.x_axis, max_abs_diff)
&& self.y_axis.abs_diff_eq(rhs.y_axis, max_abs_diff)
&& self.z_axis.abs_diff_eq(rhs.z_axis, max_abs_diff)
}
/// Takes the absolute value of each element in `self`
#[inline]
#[must_use]
pub fn abs(&self) -> Self {
Self::from_cols(self.x_axis.abs(), self.y_axis.abs(), self.z_axis.abs())
}
#[inline]
pub fn as_dmat3(&self) -> DMat3 {
DMat3::from_cols(
self.x_axis.as_dvec3(),
self.y_axis.as_dvec3(),
self.z_axis.as_dvec3(),
)
}
}
impl Default for Mat3A {
#[inline]
fn default() -> Self {
Self::IDENTITY
}
}
impl Add<Mat3A> for Mat3A {
type Output = Self;
#[inline]
fn add(self, rhs: Self) -> Self::Output {
self.add_mat3(&rhs)
}
}
impl AddAssign<Mat3A> for Mat3A {
#[inline]
fn add_assign(&mut self, rhs: Self) {
*self = self.add_mat3(&rhs);
}
}
impl Sub<Mat3A> for Mat3A {
type Output = Self;
#[inline]
fn sub(self, rhs: Self) -> Self::Output {
self.sub_mat3(&rhs)
}
}
impl SubAssign<Mat3A> for Mat3A {
#[inline]
fn sub_assign(&mut self, rhs: Self) {
*self = self.sub_mat3(&rhs);
}
}
impl Neg for Mat3A {
type Output = Self;
#[inline]
fn neg(self) -> Self::Output {
Self::from_cols(self.x_axis.neg(), self.y_axis.neg(), self.z_axis.neg())
}
}
impl Mul<Mat3A> for Mat3A {
type Output = Self;
#[inline]
fn mul(self, rhs: Self) -> Self::Output {
self.mul_mat3(&rhs)
}
}
impl MulAssign<Mat3A> for Mat3A {
#[inline]
fn mul_assign(&mut self, rhs: Self) {
*self = self.mul_mat3(&rhs);
}
}
impl Mul<Vec3A> for Mat3A {
type Output = Vec3A;
#[inline]
fn mul(self, rhs: Vec3A) -> Self::Output {
self.mul_vec3a(rhs)
}
}
impl Mul<Mat3A> for f32 {
type Output = Mat3A;
#[inline]
fn mul(self, rhs: Mat3A) -> Self::Output {
rhs.mul_scalar(self)
}
}
impl Mul<f32> for Mat3A {
type Output = Self;
#[inline]
fn mul(self, rhs: f32) -> Self::Output {
self.mul_scalar(rhs)
}
}
impl MulAssign<f32> for Mat3A {
#[inline]
fn mul_assign(&mut self, rhs: f32) {
*self = self.mul_scalar(rhs);
}
}
impl Div<Mat3A> for f32 {
type Output = Mat3A;
#[inline]
fn div(self, rhs: Mat3A) -> Self::Output {
rhs.div_scalar(self)
}
}
impl Div<f32> for Mat3A {
type Output = Self;
#[inline]
fn div(self, rhs: f32) -> Self::Output {
self.div_scalar(rhs)
}
}
impl DivAssign<f32> for Mat3A {
#[inline]
fn div_assign(&mut self, rhs: f32) {
*self = self.div_scalar(rhs);
}
}
impl Mul<Vec3> for Mat3A {
type Output = Vec3;
#[inline]
fn mul(self, rhs: Vec3) -> Vec3 {
self.mul_vec3a(rhs.into()).into()
}
}
impl From<Mat3> for Mat3A {
#[inline]
fn from(m: Mat3) -> Self {
Self {
x_axis: m.x_axis.into(),
y_axis: m.y_axis.into(),
z_axis: m.z_axis.into(),
}
}
}
impl Sum<Self> for Mat3A {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Self::ZERO, Self::add)
}
}
impl<'a> Sum<&'a Self> for Mat3A {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
}
}
impl Product for Mat3A {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Self::IDENTITY, Self::mul)
}
}
impl<'a> Product<&'a Self> for Mat3A {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::IDENTITY, |a, &b| Self::mul(a, b))
}
}
impl PartialEq for Mat3A {
#[inline]
fn eq(&self, rhs: &Self) -> bool {
self.x_axis.eq(&rhs.x_axis) && self.y_axis.eq(&rhs.y_axis) && self.z_axis.eq(&rhs.z_axis)
}
}
impl fmt::Debug for Mat3A {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct(stringify!(Mat3A))
.field("x_axis", &self.x_axis)
.field("y_axis", &self.y_axis)
.field("z_axis", &self.z_axis)
.finish()
}
}
impl fmt::Display for Mat3A {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(p) = f.precision() {
write!(
f,
"[{:.*}, {:.*}, {:.*}]",
p, self.x_axis, p, self.y_axis, p, self.z_axis
)
} else {
write!(f, "[{}, {}, {}]", self.x_axis, self.y_axis, self.z_axis)
}
}
}
+1541
View File
File diff suppressed because it is too large Load Diff
+1035
View File
File diff suppressed because it is too large Load Diff
+1917
View File
File diff suppressed because it is too large Load Diff
+1858
View File
File diff suppressed because it is too large Load Diff
+6
View File
@@ -0,0 +1,6 @@
pub mod mat2;
pub mod mat3a;
pub mod mat4;
pub mod quat;
pub mod vec3a;
pub mod vec4;
+563
View File
@@ -0,0 +1,563 @@
// Generated from mat.rs.tera template. Edit the template, not the generated file.
use crate::{f32::math, swizzles::*, DMat2, Mat3, Mat3A, Vec2};
use core::fmt;
use core::iter::{Product, Sum};
use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
/// Creates a 2x2 matrix from two column vectors.
#[inline(always)]
#[must_use]
pub const fn mat2(x_axis: Vec2, y_axis: Vec2) -> Mat2 {
Mat2::from_cols(x_axis, y_axis)
}
/// A 2x2 column major matrix.
#[derive(Clone, Copy)]
#[cfg_attr(
not(any(feature = "scalar-math", target_arch = "spirv")),
repr(align(16))
)]
#[cfg_attr(feature = "cuda", repr(align(8)))]
#[repr(C)]
pub struct Mat2 {
pub x_axis: Vec2,
pub y_axis: Vec2,
}
impl Mat2 {
/// A 2x2 matrix with all elements set to `0.0`.
pub const ZERO: Self = Self::from_cols(Vec2::ZERO, Vec2::ZERO);
/// A 2x2 identity matrix, where all diagonal elements are `1`, and all off-diagonal elements are `0`.
pub const IDENTITY: Self = Self::from_cols(Vec2::X, Vec2::Y);
/// All NAN:s.
pub const NAN: Self = Self::from_cols(Vec2::NAN, Vec2::NAN);
#[allow(clippy::too_many_arguments)]
#[inline(always)]
#[must_use]
const fn new(m00: f32, m01: f32, m10: f32, m11: f32) -> Self {
Self {
x_axis: Vec2::new(m00, m01),
y_axis: Vec2::new(m10, m11),
}
}
/// Creates a 2x2 matrix from two column vectors.
#[inline(always)]
#[must_use]
pub const fn from_cols(x_axis: Vec2, y_axis: Vec2) -> Self {
Self { x_axis, y_axis }
}
/// Creates a 2x2 matrix from a `[f32; 4]` array stored in column major order.
/// If your data is stored in row major you will need to `transpose` the returned
/// matrix.
#[inline]
#[must_use]
pub const fn from_cols_array(m: &[f32; 4]) -> Self {
Self::new(m[0], m[1], m[2], m[3])
}
/// Creates a `[f32; 4]` array storing data in column major order.
/// If you require data in row major order `transpose` the matrix first.
#[inline]
#[must_use]
pub const fn to_cols_array(&self) -> [f32; 4] {
[self.x_axis.x, self.x_axis.y, self.y_axis.x, self.y_axis.y]
}
/// Creates a 2x2 matrix from a `[[f32; 2]; 2]` 2D array stored in column major order.
/// If your data is in row major order you will need to `transpose` the returned
/// matrix.
#[inline]
#[must_use]
pub const fn from_cols_array_2d(m: &[[f32; 2]; 2]) -> Self {
Self::from_cols(Vec2::from_array(m[0]), Vec2::from_array(m[1]))
}
/// Creates a `[[f32; 2]; 2]` 2D array storing data in column major order.
/// If you require data in row major order `transpose` the matrix first.
#[inline]
#[must_use]
pub const fn to_cols_array_2d(&self) -> [[f32; 2]; 2] {
[self.x_axis.to_array(), self.y_axis.to_array()]
}
/// Creates a 2x2 matrix with its diagonal set to `diagonal` and all other entries set to 0.
#[doc(alias = "scale")]
#[inline]
#[must_use]
pub const fn from_diagonal(diagonal: Vec2) -> Self {
Self::new(diagonal.x, 0.0, 0.0, diagonal.y)
}
/// Creates a 2x2 matrix containing the combining non-uniform `scale` and rotation of
/// `angle` (in radians).
#[inline]
#[must_use]
pub fn from_scale_angle(scale: Vec2, angle: f32) -> Self {
let (sin, cos) = math::sin_cos(angle);
Self::new(cos * scale.x, sin * scale.x, -sin * scale.y, cos * scale.y)
}
/// Creates a 2x2 matrix containing a rotation of `angle` (in radians).
#[inline]
#[must_use]
pub fn from_angle(angle: f32) -> Self {
let (sin, cos) = math::sin_cos(angle);
Self::new(cos, sin, -sin, cos)
}
/// Creates a 2x2 matrix from a 3x3 matrix, discarding the 2nd row and column.
#[inline]
#[must_use]
pub fn from_mat3(m: Mat3) -> Self {
Self::from_cols(m.x_axis.xy(), m.y_axis.xy())
}
/// Creates a 2x2 matrix from the minor of the given 3x3 matrix, discarding the `i`th column
/// and `j`th row.
///
/// # Panics
///
/// Panics if `i` or `j` is greater than 2.
#[inline]
#[must_use]
pub fn from_mat3_minor(m: Mat3, i: usize, j: usize) -> Self {
match (i, j) {
(0, 0) => Self::from_cols(m.y_axis.yz(), m.z_axis.yz()),
(0, 1) => Self::from_cols(m.y_axis.xz(), m.z_axis.xz()),
(0, 2) => Self::from_cols(m.y_axis.xy(), m.z_axis.xy()),
(1, 0) => Self::from_cols(m.x_axis.yz(), m.z_axis.yz()),
(1, 1) => Self::from_cols(m.x_axis.xz(), m.z_axis.xz()),
(1, 2) => Self::from_cols(m.x_axis.xy(), m.z_axis.xy()),
(2, 0) => Self::from_cols(m.x_axis.yz(), m.y_axis.yz()),
(2, 1) => Self::from_cols(m.x_axis.xz(), m.y_axis.xz()),
(2, 2) => Self::from_cols(m.x_axis.xy(), m.y_axis.xy()),
_ => panic!("index out of bounds"),
}
}
/// Creates a 2x2 matrix from a 3x3 matrix, discarding the 2nd row and column.
#[inline]
#[must_use]
pub fn from_mat3a(m: Mat3A) -> Self {
Self::from_cols(m.x_axis.xy(), m.y_axis.xy())
}
/// Creates a 2x2 matrix from the minor of the given 3x3 matrix, discarding the `i`th column
/// and `j`th row.
///
/// # Panics
///
/// Panics if `i` or `j` is greater than 2.
#[inline]
#[must_use]
pub fn from_mat3a_minor(m: Mat3A, i: usize, j: usize) -> Self {
match (i, j) {
(0, 0) => Self::from_cols(m.y_axis.yz(), m.z_axis.yz()),
(0, 1) => Self::from_cols(m.y_axis.xz(), m.z_axis.xz()),
(0, 2) => Self::from_cols(m.y_axis.xy(), m.z_axis.xy()),
(1, 0) => Self::from_cols(m.x_axis.yz(), m.z_axis.yz()),
(1, 1) => Self::from_cols(m.x_axis.xz(), m.z_axis.xz()),
(1, 2) => Self::from_cols(m.x_axis.xy(), m.z_axis.xy()),
(2, 0) => Self::from_cols(m.x_axis.yz(), m.y_axis.yz()),
(2, 1) => Self::from_cols(m.x_axis.xz(), m.y_axis.xz()),
(2, 2) => Self::from_cols(m.x_axis.xy(), m.y_axis.xy()),
_ => panic!("index out of bounds"),
}
}
/// Creates a 2x2 matrix from the first 4 values in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 4 elements long.
#[inline]
#[must_use]
pub const fn from_cols_slice(slice: &[f32]) -> Self {
Self::new(slice[0], slice[1], slice[2], slice[3])
}
/// Writes the columns of `self` to the first 4 elements in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 4 elements long.
#[inline]
pub fn write_cols_to_slice(self, slice: &mut [f32]) {
slice[0] = self.x_axis.x;
slice[1] = self.x_axis.y;
slice[2] = self.y_axis.x;
slice[3] = self.y_axis.y;
}
/// Returns the matrix column for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 1.
#[inline]
#[must_use]
pub fn col(&self, index: usize) -> Vec2 {
match index {
0 => self.x_axis,
1 => self.y_axis,
_ => panic!("index out of bounds"),
}
}
/// Returns a mutable reference to the matrix column for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 1.
#[inline]
pub fn col_mut(&mut self, index: usize) -> &mut Vec2 {
match index {
0 => &mut self.x_axis,
1 => &mut self.y_axis,
_ => panic!("index out of bounds"),
}
}
/// Returns the matrix row for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 1.
#[inline]
#[must_use]
pub fn row(&self, index: usize) -> Vec2 {
match index {
0 => Vec2::new(self.x_axis.x, self.y_axis.x),
1 => Vec2::new(self.x_axis.y, self.y_axis.y),
_ => panic!("index out of bounds"),
}
}
/// Returns `true` if, and only if, all elements are finite.
/// If any element is either `NaN`, positive or negative infinity, this will return `false`.
#[inline]
#[must_use]
pub fn is_finite(&self) -> bool {
self.x_axis.is_finite() && self.y_axis.is_finite()
}
/// Returns `true` if any elements are `NaN`.
#[inline]
#[must_use]
pub fn is_nan(&self) -> bool {
self.x_axis.is_nan() || self.y_axis.is_nan()
}
/// Returns the transpose of `self`.
#[inline]
#[must_use]
pub fn transpose(&self) -> Self {
Self {
x_axis: Vec2::new(self.x_axis.x, self.y_axis.x),
y_axis: Vec2::new(self.x_axis.y, self.y_axis.y),
}
}
/// Returns the determinant of `self`.
#[inline]
#[must_use]
pub fn determinant(&self) -> f32 {
self.x_axis.x * self.y_axis.y - self.x_axis.y * self.y_axis.x
}
/// Returns the inverse of `self`.
///
/// If the matrix is not invertible the returned matrix will be invalid.
///
/// # Panics
///
/// Will panic if the determinant of `self` is zero when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn inverse(&self) -> Self {
let inv_det = {
let det = self.determinant();
glam_assert!(det != 0.0);
det.recip()
};
Self::new(
self.y_axis.y * inv_det,
self.x_axis.y * -inv_det,
self.y_axis.x * -inv_det,
self.x_axis.x * inv_det,
)
}
/// Transforms a 2D vector.
#[inline]
#[must_use]
pub fn mul_vec2(&self, rhs: Vec2) -> Vec2 {
#[allow(clippy::suspicious_operation_groupings)]
Vec2::new(
(self.x_axis.x * rhs.x) + (self.y_axis.x * rhs.y),
(self.x_axis.y * rhs.x) + (self.y_axis.y * rhs.y),
)
}
/// Multiplies two 2x2 matrices.
#[inline]
#[must_use]
pub fn mul_mat2(&self, rhs: &Self) -> Self {
Self::from_cols(self.mul(rhs.x_axis), self.mul(rhs.y_axis))
}
/// Adds two 2x2 matrices.
#[inline]
#[must_use]
pub fn add_mat2(&self, rhs: &Self) -> Self {
Self::from_cols(self.x_axis.add(rhs.x_axis), self.y_axis.add(rhs.y_axis))
}
/// Subtracts two 2x2 matrices.
#[inline]
#[must_use]
pub fn sub_mat2(&self, rhs: &Self) -> Self {
Self::from_cols(self.x_axis.sub(rhs.x_axis), self.y_axis.sub(rhs.y_axis))
}
/// Multiplies a 2x2 matrix by a scalar.
#[inline]
#[must_use]
pub fn mul_scalar(&self, rhs: f32) -> Self {
Self::from_cols(self.x_axis.mul(rhs), self.y_axis.mul(rhs))
}
/// Divides a 2x2 matrix by a scalar.
#[inline]
#[must_use]
pub fn div_scalar(&self, rhs: f32) -> Self {
let rhs = Vec2::splat(rhs);
Self::from_cols(self.x_axis.div(rhs), self.y_axis.div(rhs))
}
/// Returns true if the absolute difference of all elements between `self` and `rhs`
/// is less than or equal to `max_abs_diff`.
///
/// This can be used to compare if two matrices contain similar elements. It works best
/// when comparing with a known value. The `max_abs_diff` that should be used used
/// depends on the values being compared against.
///
/// For more see
/// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
#[inline]
#[must_use]
pub fn abs_diff_eq(&self, rhs: Self, max_abs_diff: f32) -> bool {
self.x_axis.abs_diff_eq(rhs.x_axis, max_abs_diff)
&& self.y_axis.abs_diff_eq(rhs.y_axis, max_abs_diff)
}
/// Takes the absolute value of each element in `self`
#[inline]
#[must_use]
pub fn abs(&self) -> Self {
Self::from_cols(self.x_axis.abs(), self.y_axis.abs())
}
#[inline]
pub fn as_dmat2(&self) -> DMat2 {
DMat2::from_cols(self.x_axis.as_dvec2(), self.y_axis.as_dvec2())
}
}
impl Default for Mat2 {
#[inline]
fn default() -> Self {
Self::IDENTITY
}
}
impl Add<Mat2> for Mat2 {
type Output = Self;
#[inline]
fn add(self, rhs: Self) -> Self::Output {
self.add_mat2(&rhs)
}
}
impl AddAssign<Mat2> for Mat2 {
#[inline]
fn add_assign(&mut self, rhs: Self) {
*self = self.add_mat2(&rhs);
}
}
impl Sub<Mat2> for Mat2 {
type Output = Self;
#[inline]
fn sub(self, rhs: Self) -> Self::Output {
self.sub_mat2(&rhs)
}
}
impl SubAssign<Mat2> for Mat2 {
#[inline]
fn sub_assign(&mut self, rhs: Self) {
*self = self.sub_mat2(&rhs);
}
}
impl Neg for Mat2 {
type Output = Self;
#[inline]
fn neg(self) -> Self::Output {
Self::from_cols(self.x_axis.neg(), self.y_axis.neg())
}
}
impl Mul<Mat2> for Mat2 {
type Output = Self;
#[inline]
fn mul(self, rhs: Self) -> Self::Output {
self.mul_mat2(&rhs)
}
}
impl MulAssign<Mat2> for Mat2 {
#[inline]
fn mul_assign(&mut self, rhs: Self) {
*self = self.mul_mat2(&rhs);
}
}
impl Mul<Vec2> for Mat2 {
type Output = Vec2;
#[inline]
fn mul(self, rhs: Vec2) -> Self::Output {
self.mul_vec2(rhs)
}
}
impl Mul<Mat2> for f32 {
type Output = Mat2;
#[inline]
fn mul(self, rhs: Mat2) -> Self::Output {
rhs.mul_scalar(self)
}
}
impl Mul<f32> for Mat2 {
type Output = Self;
#[inline]
fn mul(self, rhs: f32) -> Self::Output {
self.mul_scalar(rhs)
}
}
impl MulAssign<f32> for Mat2 {
#[inline]
fn mul_assign(&mut self, rhs: f32) {
*self = self.mul_scalar(rhs);
}
}
impl Div<Mat2> for f32 {
type Output = Mat2;
#[inline]
fn div(self, rhs: Mat2) -> Self::Output {
rhs.div_scalar(self)
}
}
impl Div<f32> for Mat2 {
type Output = Self;
#[inline]
fn div(self, rhs: f32) -> Self::Output {
self.div_scalar(rhs)
}
}
impl DivAssign<f32> for Mat2 {
#[inline]
fn div_assign(&mut self, rhs: f32) {
*self = self.div_scalar(rhs);
}
}
impl Sum<Self> for Mat2 {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Self::ZERO, Self::add)
}
}
impl<'a> Sum<&'a Self> for Mat2 {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
}
}
impl Product for Mat2 {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Self::IDENTITY, Self::mul)
}
}
impl<'a> Product<&'a Self> for Mat2 {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::IDENTITY, |a, &b| Self::mul(a, b))
}
}
impl PartialEq for Mat2 {
#[inline]
fn eq(&self, rhs: &Self) -> bool {
self.x_axis.eq(&rhs.x_axis) && self.y_axis.eq(&rhs.y_axis)
}
}
#[cfg(not(target_arch = "spirv"))]
impl AsRef<[f32; 4]> for Mat2 {
#[inline]
fn as_ref(&self) -> &[f32; 4] {
unsafe { &*(self as *const Self as *const [f32; 4]) }
}
}
#[cfg(not(target_arch = "spirv"))]
impl AsMut<[f32; 4]> for Mat2 {
#[inline]
fn as_mut(&mut self) -> &mut [f32; 4] {
unsafe { &mut *(self as *mut Self as *mut [f32; 4]) }
}
}
impl fmt::Debug for Mat2 {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct(stringify!(Mat2))
.field("x_axis", &self.x_axis)
.field("y_axis", &self.y_axis)
.finish()
}
}
impl fmt::Display for Mat2 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(p) = f.precision() {
write!(f, "[{:.*}, {:.*}]", p, self.x_axis, p, self.y_axis)
} else {
write!(f, "[{}, {}]", self.x_axis, self.y_axis)
}
}
}
+924
View File
@@ -0,0 +1,924 @@
// Generated from mat.rs.tera template. Edit the template, not the generated file.
use crate::{
euler::{FromEuler, ToEuler},
f32::math,
swizzles::*,
DMat3, EulerRot, Mat2, Mat3, Mat4, Quat, Vec2, Vec3, Vec3A,
};
use core::fmt;
use core::iter::{Product, Sum};
use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
/// Creates a 3x3 matrix from three column vectors.
#[inline(always)]
#[must_use]
pub const fn mat3a(x_axis: Vec3A, y_axis: Vec3A, z_axis: Vec3A) -> Mat3A {
Mat3A::from_cols(x_axis, y_axis, z_axis)
}
/// A 3x3 column major matrix.
///
/// This 3x3 matrix type features convenience methods for creating and using linear and
/// affine transformations. If you are primarily dealing with 2D affine transformations the
/// [`Affine2`](crate::Affine2) type is much faster and more space efficient than
/// using a 3x3 matrix.
///
/// Linear transformations including 3D rotation and scale can be created using methods
/// such as [`Self::from_diagonal()`], [`Self::from_quat()`], [`Self::from_axis_angle()`],
/// [`Self::from_rotation_x()`], [`Self::from_rotation_y()`], or
/// [`Self::from_rotation_z()`].
///
/// The resulting matrices can be use to transform 3D vectors using regular vector
/// multiplication.
///
/// Affine transformations including 2D translation, rotation and scale can be created
/// using methods such as [`Self::from_translation()`], [`Self::from_angle()`],
/// [`Self::from_scale()`] and [`Self::from_scale_angle_translation()`].
///
/// The [`Self::transform_point2()`] and [`Self::transform_vector2()`] convenience methods
/// are provided for performing affine transforms on 2D vectors and points. These multiply
/// 2D inputs as 3D vectors with an implicit `z` value of `1` for points and `0` for
/// vectors respectively. These methods assume that `Self` contains a valid affine
/// transform.
#[derive(Clone, Copy)]
#[repr(C)]
pub struct Mat3A {
pub x_axis: Vec3A,
pub y_axis: Vec3A,
pub z_axis: Vec3A,
}
impl Mat3A {
/// A 3x3 matrix with all elements set to `0.0`.
pub const ZERO: Self = Self::from_cols(Vec3A::ZERO, Vec3A::ZERO, Vec3A::ZERO);
/// A 3x3 identity matrix, where all diagonal elements are `1`, and all off-diagonal elements are `0`.
pub const IDENTITY: Self = Self::from_cols(Vec3A::X, Vec3A::Y, Vec3A::Z);
/// All NAN:s.
pub const NAN: Self = Self::from_cols(Vec3A::NAN, Vec3A::NAN, Vec3A::NAN);
#[allow(clippy::too_many_arguments)]
#[inline(always)]
#[must_use]
const fn new(
m00: f32,
m01: f32,
m02: f32,
m10: f32,
m11: f32,
m12: f32,
m20: f32,
m21: f32,
m22: f32,
) -> Self {
Self {
x_axis: Vec3A::new(m00, m01, m02),
y_axis: Vec3A::new(m10, m11, m12),
z_axis: Vec3A::new(m20, m21, m22),
}
}
/// Creates a 3x3 matrix from three column vectors.
#[inline(always)]
#[must_use]
pub const fn from_cols(x_axis: Vec3A, y_axis: Vec3A, z_axis: Vec3A) -> Self {
Self {
x_axis,
y_axis,
z_axis,
}
}
/// Creates a 3x3 matrix from a `[f32; 9]` array stored in column major order.
/// If your data is stored in row major you will need to `transpose` the returned
/// matrix.
#[inline]
#[must_use]
pub const fn from_cols_array(m: &[f32; 9]) -> Self {
Self::new(m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8])
}
/// Creates a `[f32; 9]` array storing data in column major order.
/// If you require data in row major order `transpose` the matrix first.
#[inline]
#[must_use]
pub const fn to_cols_array(&self) -> [f32; 9] {
[
self.x_axis.x,
self.x_axis.y,
self.x_axis.z,
self.y_axis.x,
self.y_axis.y,
self.y_axis.z,
self.z_axis.x,
self.z_axis.y,
self.z_axis.z,
]
}
/// Creates a 3x3 matrix from a `[[f32; 3]; 3]` 3D array stored in column major order.
/// If your data is in row major order you will need to `transpose` the returned
/// matrix.
#[inline]
#[must_use]
pub const fn from_cols_array_2d(m: &[[f32; 3]; 3]) -> Self {
Self::from_cols(
Vec3A::from_array(m[0]),
Vec3A::from_array(m[1]),
Vec3A::from_array(m[2]),
)
}
/// Creates a `[[f32; 3]; 3]` 3D array storing data in column major order.
/// If you require data in row major order `transpose` the matrix first.
#[inline]
#[must_use]
pub const fn to_cols_array_2d(&self) -> [[f32; 3]; 3] {
[
self.x_axis.to_array(),
self.y_axis.to_array(),
self.z_axis.to_array(),
]
}
/// Creates a 3x3 matrix with its diagonal set to `diagonal` and all other entries set to 0.
#[doc(alias = "scale")]
#[inline]
#[must_use]
pub const fn from_diagonal(diagonal: Vec3) -> Self {
Self::new(
diagonal.x, 0.0, 0.0, 0.0, diagonal.y, 0.0, 0.0, 0.0, diagonal.z,
)
}
/// Creates a 3x3 matrix from a 4x4 matrix, discarding the 4th row and column.
#[inline]
#[must_use]
pub fn from_mat4(m: Mat4) -> Self {
Self::from_cols(
Vec3A::from_vec4(m.x_axis),
Vec3A::from_vec4(m.y_axis),
Vec3A::from_vec4(m.z_axis),
)
}
/// Creates a 3x3 matrix from the minor of the given 4x4 matrix, discarding the `i`th column
/// and `j`th row.
///
/// # Panics
///
/// Panics if `i` or `j` is greater than 3.
#[inline]
#[must_use]
pub fn from_mat4_minor(m: Mat4, i: usize, j: usize) -> Self {
match (i, j) {
(0, 0) => Self::from_cols(
Vec3A::from_vec4(m.y_axis.yzww()),
Vec3A::from_vec4(m.z_axis.yzww()),
Vec3A::from_vec4(m.w_axis.yzww()),
),
(0, 1) => Self::from_cols(
Vec3A::from_vec4(m.y_axis.xzww()),
Vec3A::from_vec4(m.z_axis.xzww()),
Vec3A::from_vec4(m.w_axis.xzww()),
),
(0, 2) => Self::from_cols(
Vec3A::from_vec4(m.y_axis.xyww()),
Vec3A::from_vec4(m.z_axis.xyww()),
Vec3A::from_vec4(m.w_axis.xyww()),
),
(0, 3) => Self::from_cols(
Vec3A::from_vec4(m.y_axis.xyzw()),
Vec3A::from_vec4(m.z_axis.xyzw()),
Vec3A::from_vec4(m.w_axis.xyzw()),
),
(1, 0) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.yzww()),
Vec3A::from_vec4(m.z_axis.yzww()),
Vec3A::from_vec4(m.w_axis.yzww()),
),
(1, 1) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xzww()),
Vec3A::from_vec4(m.z_axis.xzww()),
Vec3A::from_vec4(m.w_axis.xzww()),
),
(1, 2) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xyww()),
Vec3A::from_vec4(m.z_axis.xyww()),
Vec3A::from_vec4(m.w_axis.xyww()),
),
(1, 3) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xyzw()),
Vec3A::from_vec4(m.z_axis.xyzw()),
Vec3A::from_vec4(m.w_axis.xyzw()),
),
(2, 0) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.yzww()),
Vec3A::from_vec4(m.y_axis.yzww()),
Vec3A::from_vec4(m.w_axis.yzww()),
),
(2, 1) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xzww()),
Vec3A::from_vec4(m.y_axis.xzww()),
Vec3A::from_vec4(m.w_axis.xzww()),
),
(2, 2) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xyww()),
Vec3A::from_vec4(m.y_axis.xyww()),
Vec3A::from_vec4(m.w_axis.xyww()),
),
(2, 3) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xyzw()),
Vec3A::from_vec4(m.y_axis.xyzw()),
Vec3A::from_vec4(m.w_axis.xyzw()),
),
(3, 0) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.yzww()),
Vec3A::from_vec4(m.y_axis.yzww()),
Vec3A::from_vec4(m.z_axis.yzww()),
),
(3, 1) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xzww()),
Vec3A::from_vec4(m.y_axis.xzww()),
Vec3A::from_vec4(m.z_axis.xzww()),
),
(3, 2) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xyww()),
Vec3A::from_vec4(m.y_axis.xyww()),
Vec3A::from_vec4(m.z_axis.xyww()),
),
(3, 3) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xyzw()),
Vec3A::from_vec4(m.y_axis.xyzw()),
Vec3A::from_vec4(m.z_axis.xyzw()),
),
_ => panic!("index out of bounds"),
}
}
/// Creates a 3D rotation matrix from the given quaternion.
///
/// # Panics
///
/// Will panic if `rotation` is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn from_quat(rotation: Quat) -> Self {
glam_assert!(rotation.is_normalized());
let x2 = rotation.x + rotation.x;
let y2 = rotation.y + rotation.y;
let z2 = rotation.z + rotation.z;
let xx = rotation.x * x2;
let xy = rotation.x * y2;
let xz = rotation.x * z2;
let yy = rotation.y * y2;
let yz = rotation.y * z2;
let zz = rotation.z * z2;
let wx = rotation.w * x2;
let wy = rotation.w * y2;
let wz = rotation.w * z2;
Self::from_cols(
Vec3A::new(1.0 - (yy + zz), xy + wz, xz - wy),
Vec3A::new(xy - wz, 1.0 - (xx + zz), yz + wx),
Vec3A::new(xz + wy, yz - wx, 1.0 - (xx + yy)),
)
}
/// Creates a 3D rotation matrix from a normalized rotation `axis` and `angle` (in
/// radians).
///
/// # Panics
///
/// Will panic if `axis` is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn from_axis_angle(axis: Vec3, angle: f32) -> Self {
glam_assert!(axis.is_normalized());
let (sin, cos) = math::sin_cos(angle);
let (xsin, ysin, zsin) = axis.mul(sin).into();
let (x, y, z) = axis.into();
let (x2, y2, z2) = axis.mul(axis).into();
let omc = 1.0 - cos;
let xyomc = x * y * omc;
let xzomc = x * z * omc;
let yzomc = y * z * omc;
Self::from_cols(
Vec3A::new(x2 * omc + cos, xyomc + zsin, xzomc - ysin),
Vec3A::new(xyomc - zsin, y2 * omc + cos, yzomc + xsin),
Vec3A::new(xzomc + ysin, yzomc - xsin, z2 * omc + cos),
)
}
/// Creates a 3D rotation matrix from the given euler rotation sequence and the angles (in
/// radians).
#[inline]
#[must_use]
pub fn from_euler(order: EulerRot, a: f32, b: f32, c: f32) -> Self {
Self::from_euler_angles(order, a, b, c)
}
/// Extract Euler angles with the given Euler rotation order.
///
/// Note if the input matrix contains scales, shears, or other non-rotation transformations then
/// the resulting Euler angles will be ill-defined.
///
/// # Panics
///
/// Will panic if any input matrix column is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn to_euler(&self, order: EulerRot) -> (f32, f32, f32) {
glam_assert!(
self.x_axis.is_normalized()
&& self.y_axis.is_normalized()
&& self.z_axis.is_normalized()
);
self.to_euler_angles(order)
}
/// Creates a 3D rotation matrix from `angle` (in radians) around the x axis.
#[inline]
#[must_use]
pub fn from_rotation_x(angle: f32) -> Self {
let (sina, cosa) = math::sin_cos(angle);
Self::from_cols(
Vec3A::X,
Vec3A::new(0.0, cosa, sina),
Vec3A::new(0.0, -sina, cosa),
)
}
/// Creates a 3D rotation matrix from `angle` (in radians) around the y axis.
#[inline]
#[must_use]
pub fn from_rotation_y(angle: f32) -> Self {
let (sina, cosa) = math::sin_cos(angle);
Self::from_cols(
Vec3A::new(cosa, 0.0, -sina),
Vec3A::Y,
Vec3A::new(sina, 0.0, cosa),
)
}
/// Creates a 3D rotation matrix from `angle` (in radians) around the z axis.
#[inline]
#[must_use]
pub fn from_rotation_z(angle: f32) -> Self {
let (sina, cosa) = math::sin_cos(angle);
Self::from_cols(
Vec3A::new(cosa, sina, 0.0),
Vec3A::new(-sina, cosa, 0.0),
Vec3A::Z,
)
}
/// Creates an affine transformation matrix from the given 2D `translation`.
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
#[inline]
#[must_use]
pub fn from_translation(translation: Vec2) -> Self {
Self::from_cols(
Vec3A::X,
Vec3A::Y,
Vec3A::new(translation.x, translation.y, 1.0),
)
}
/// Creates an affine transformation matrix from the given 2D rotation `angle` (in
/// radians).
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
#[inline]
#[must_use]
pub fn from_angle(angle: f32) -> Self {
let (sin, cos) = math::sin_cos(angle);
Self::from_cols(
Vec3A::new(cos, sin, 0.0),
Vec3A::new(-sin, cos, 0.0),
Vec3A::Z,
)
}
/// Creates an affine transformation matrix from the given 2D `scale`, rotation `angle` (in
/// radians) and `translation`.
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
#[inline]
#[must_use]
pub fn from_scale_angle_translation(scale: Vec2, angle: f32, translation: Vec2) -> Self {
let (sin, cos) = math::sin_cos(angle);
Self::from_cols(
Vec3A::new(cos * scale.x, sin * scale.x, 0.0),
Vec3A::new(-sin * scale.y, cos * scale.y, 0.0),
Vec3A::new(translation.x, translation.y, 1.0),
)
}
/// Creates an affine transformation matrix from the given non-uniform 2D `scale`.
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
///
/// # Panics
///
/// Will panic if all elements of `scale` are zero when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn from_scale(scale: Vec2) -> Self {
// Do not panic as long as any component is non-zero
glam_assert!(scale.cmpne(Vec2::ZERO).any());
Self::from_cols(
Vec3A::new(scale.x, 0.0, 0.0),
Vec3A::new(0.0, scale.y, 0.0),
Vec3A::Z,
)
}
/// Creates an affine transformation matrix from the given 2x2 matrix.
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
#[inline]
pub fn from_mat2(m: Mat2) -> Self {
Self::from_cols((m.x_axis, 0.0).into(), (m.y_axis, 0.0).into(), Vec3A::Z)
}
/// Creates a 3x3 matrix from the first 9 values in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 9 elements long.
#[inline]
#[must_use]
pub const fn from_cols_slice(slice: &[f32]) -> Self {
Self::new(
slice[0], slice[1], slice[2], slice[3], slice[4], slice[5], slice[6], slice[7],
slice[8],
)
}
/// Writes the columns of `self` to the first 9 elements in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 9 elements long.
#[inline]
pub fn write_cols_to_slice(self, slice: &mut [f32]) {
slice[0] = self.x_axis.x;
slice[1] = self.x_axis.y;
slice[2] = self.x_axis.z;
slice[3] = self.y_axis.x;
slice[4] = self.y_axis.y;
slice[5] = self.y_axis.z;
slice[6] = self.z_axis.x;
slice[7] = self.z_axis.y;
slice[8] = self.z_axis.z;
}
/// Returns the matrix column for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 2.
#[inline]
#[must_use]
pub fn col(&self, index: usize) -> Vec3A {
match index {
0 => self.x_axis,
1 => self.y_axis,
2 => self.z_axis,
_ => panic!("index out of bounds"),
}
}
/// Returns a mutable reference to the matrix column for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 2.
#[inline]
pub fn col_mut(&mut self, index: usize) -> &mut Vec3A {
match index {
0 => &mut self.x_axis,
1 => &mut self.y_axis,
2 => &mut self.z_axis,
_ => panic!("index out of bounds"),
}
}
/// Returns the matrix row for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 2.
#[inline]
#[must_use]
pub fn row(&self, index: usize) -> Vec3A {
match index {
0 => Vec3A::new(self.x_axis.x, self.y_axis.x, self.z_axis.x),
1 => Vec3A::new(self.x_axis.y, self.y_axis.y, self.z_axis.y),
2 => Vec3A::new(self.x_axis.z, self.y_axis.z, self.z_axis.z),
_ => panic!("index out of bounds"),
}
}
/// Returns `true` if, and only if, all elements are finite.
/// If any element is either `NaN`, positive or negative infinity, this will return `false`.
#[inline]
#[must_use]
pub fn is_finite(&self) -> bool {
self.x_axis.is_finite() && self.y_axis.is_finite() && self.z_axis.is_finite()
}
/// Returns `true` if any elements are `NaN`.
#[inline]
#[must_use]
pub fn is_nan(&self) -> bool {
self.x_axis.is_nan() || self.y_axis.is_nan() || self.z_axis.is_nan()
}
/// Returns the transpose of `self`.
#[inline]
#[must_use]
pub fn transpose(&self) -> Self {
Self {
x_axis: Vec3A::new(self.x_axis.x, self.y_axis.x, self.z_axis.x),
y_axis: Vec3A::new(self.x_axis.y, self.y_axis.y, self.z_axis.y),
z_axis: Vec3A::new(self.x_axis.z, self.y_axis.z, self.z_axis.z),
}
}
/// Returns the determinant of `self`.
#[inline]
#[must_use]
pub fn determinant(&self) -> f32 {
self.z_axis.dot(self.x_axis.cross(self.y_axis))
}
/// Returns the inverse of `self`.
///
/// If the matrix is not invertible the returned matrix will be invalid.
///
/// # Panics
///
/// Will panic if the determinant of `self` is zero when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn inverse(&self) -> Self {
let tmp0 = self.y_axis.cross(self.z_axis);
let tmp1 = self.z_axis.cross(self.x_axis);
let tmp2 = self.x_axis.cross(self.y_axis);
let det = self.z_axis.dot(tmp2);
glam_assert!(det != 0.0);
let inv_det = Vec3A::splat(det.recip());
Self::from_cols(tmp0.mul(inv_det), tmp1.mul(inv_det), tmp2.mul(inv_det)).transpose()
}
/// Transforms the given 2D vector as a point.
///
/// This is the equivalent of multiplying `rhs` as a 3D vector where `z` is `1`.
///
/// This method assumes that `self` contains a valid affine transform.
///
/// # Panics
///
/// Will panic if the 2nd row of `self` is not `(0, 0, 1)` when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn transform_point2(&self, rhs: Vec2) -> Vec2 {
glam_assert!(self.row(2).abs_diff_eq(Vec3A::Z, 1e-6));
Mat2::from_cols(self.x_axis.xy(), self.y_axis.xy()) * rhs + self.z_axis.xy()
}
/// Rotates the given 2D vector.
///
/// This is the equivalent of multiplying `rhs` as a 3D vector where `z` is `0`.
///
/// This method assumes that `self` contains a valid affine transform.
///
/// # Panics
///
/// Will panic if the 2nd row of `self` is not `(0, 0, 1)` when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn transform_vector2(&self, rhs: Vec2) -> Vec2 {
glam_assert!(self.row(2).abs_diff_eq(Vec3A::Z, 1e-6));
Mat2::from_cols(self.x_axis.xy(), self.y_axis.xy()) * rhs
}
/// Transforms a 3D vector.
#[inline]
#[must_use]
pub fn mul_vec3(&self, rhs: Vec3) -> Vec3 {
self.mul_vec3a(rhs.into()).into()
}
/// Transforms a [`Vec3A`].
#[inline]
#[must_use]
pub fn mul_vec3a(&self, rhs: Vec3A) -> Vec3A {
let mut res = self.x_axis.mul(rhs.xxx());
res = res.add(self.y_axis.mul(rhs.yyy()));
res = res.add(self.z_axis.mul(rhs.zzz()));
res
}
/// Multiplies two 3x3 matrices.
#[inline]
#[must_use]
pub fn mul_mat3(&self, rhs: &Self) -> Self {
Self::from_cols(
self.mul(rhs.x_axis),
self.mul(rhs.y_axis),
self.mul(rhs.z_axis),
)
}
/// Adds two 3x3 matrices.
#[inline]
#[must_use]
pub fn add_mat3(&self, rhs: &Self) -> Self {
Self::from_cols(
self.x_axis.add(rhs.x_axis),
self.y_axis.add(rhs.y_axis),
self.z_axis.add(rhs.z_axis),
)
}
/// Subtracts two 3x3 matrices.
#[inline]
#[must_use]
pub fn sub_mat3(&self, rhs: &Self) -> Self {
Self::from_cols(
self.x_axis.sub(rhs.x_axis),
self.y_axis.sub(rhs.y_axis),
self.z_axis.sub(rhs.z_axis),
)
}
/// Multiplies a 3x3 matrix by a scalar.
#[inline]
#[must_use]
pub fn mul_scalar(&self, rhs: f32) -> Self {
Self::from_cols(
self.x_axis.mul(rhs),
self.y_axis.mul(rhs),
self.z_axis.mul(rhs),
)
}
/// Divides a 3x3 matrix by a scalar.
#[inline]
#[must_use]
pub fn div_scalar(&self, rhs: f32) -> Self {
let rhs = Vec3A::splat(rhs);
Self::from_cols(
self.x_axis.div(rhs),
self.y_axis.div(rhs),
self.z_axis.div(rhs),
)
}
/// Returns true if the absolute difference of all elements between `self` and `rhs`
/// is less than or equal to `max_abs_diff`.
///
/// This can be used to compare if two matrices contain similar elements. It works best
/// when comparing with a known value. The `max_abs_diff` that should be used used
/// depends on the values being compared against.
///
/// For more see
/// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
#[inline]
#[must_use]
pub fn abs_diff_eq(&self, rhs: Self, max_abs_diff: f32) -> bool {
self.x_axis.abs_diff_eq(rhs.x_axis, max_abs_diff)
&& self.y_axis.abs_diff_eq(rhs.y_axis, max_abs_diff)
&& self.z_axis.abs_diff_eq(rhs.z_axis, max_abs_diff)
}
/// Takes the absolute value of each element in `self`
#[inline]
#[must_use]
pub fn abs(&self) -> Self {
Self::from_cols(self.x_axis.abs(), self.y_axis.abs(), self.z_axis.abs())
}
#[inline]
pub fn as_dmat3(&self) -> DMat3 {
DMat3::from_cols(
self.x_axis.as_dvec3(),
self.y_axis.as_dvec3(),
self.z_axis.as_dvec3(),
)
}
}
impl Default for Mat3A {
#[inline]
fn default() -> Self {
Self::IDENTITY
}
}
impl Add<Mat3A> for Mat3A {
type Output = Self;
#[inline]
fn add(self, rhs: Self) -> Self::Output {
self.add_mat3(&rhs)
}
}
impl AddAssign<Mat3A> for Mat3A {
#[inline]
fn add_assign(&mut self, rhs: Self) {
*self = self.add_mat3(&rhs);
}
}
impl Sub<Mat3A> for Mat3A {
type Output = Self;
#[inline]
fn sub(self, rhs: Self) -> Self::Output {
self.sub_mat3(&rhs)
}
}
impl SubAssign<Mat3A> for Mat3A {
#[inline]
fn sub_assign(&mut self, rhs: Self) {
*self = self.sub_mat3(&rhs);
}
}
impl Neg for Mat3A {
type Output = Self;
#[inline]
fn neg(self) -> Self::Output {
Self::from_cols(self.x_axis.neg(), self.y_axis.neg(), self.z_axis.neg())
}
}
impl Mul<Mat3A> for Mat3A {
type Output = Self;
#[inline]
fn mul(self, rhs: Self) -> Self::Output {
self.mul_mat3(&rhs)
}
}
impl MulAssign<Mat3A> for Mat3A {
#[inline]
fn mul_assign(&mut self, rhs: Self) {
*self = self.mul_mat3(&rhs);
}
}
impl Mul<Vec3A> for Mat3A {
type Output = Vec3A;
#[inline]
fn mul(self, rhs: Vec3A) -> Self::Output {
self.mul_vec3a(rhs)
}
}
impl Mul<Mat3A> for f32 {
type Output = Mat3A;
#[inline]
fn mul(self, rhs: Mat3A) -> Self::Output {
rhs.mul_scalar(self)
}
}
impl Mul<f32> for Mat3A {
type Output = Self;
#[inline]
fn mul(self, rhs: f32) -> Self::Output {
self.mul_scalar(rhs)
}
}
impl MulAssign<f32> for Mat3A {
#[inline]
fn mul_assign(&mut self, rhs: f32) {
*self = self.mul_scalar(rhs);
}
}
impl Div<Mat3A> for f32 {
type Output = Mat3A;
#[inline]
fn div(self, rhs: Mat3A) -> Self::Output {
rhs.div_scalar(self)
}
}
impl Div<f32> for Mat3A {
type Output = Self;
#[inline]
fn div(self, rhs: f32) -> Self::Output {
self.div_scalar(rhs)
}
}
impl DivAssign<f32> for Mat3A {
#[inline]
fn div_assign(&mut self, rhs: f32) {
*self = self.div_scalar(rhs);
}
}
impl Mul<Vec3> for Mat3A {
type Output = Vec3;
#[inline]
fn mul(self, rhs: Vec3) -> Vec3 {
self.mul_vec3a(rhs.into()).into()
}
}
impl From<Mat3> for Mat3A {
#[inline]
fn from(m: Mat3) -> Self {
Self {
x_axis: m.x_axis.into(),
y_axis: m.y_axis.into(),
z_axis: m.z_axis.into(),
}
}
}
impl Sum<Self> for Mat3A {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Self::ZERO, Self::add)
}
}
impl<'a> Sum<&'a Self> for Mat3A {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
}
}
impl Product for Mat3A {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Self::IDENTITY, Self::mul)
}
}
impl<'a> Product<&'a Self> for Mat3A {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::IDENTITY, |a, &b| Self::mul(a, b))
}
}
impl PartialEq for Mat3A {
#[inline]
fn eq(&self, rhs: &Self) -> bool {
self.x_axis.eq(&rhs.x_axis) && self.y_axis.eq(&rhs.y_axis) && self.z_axis.eq(&rhs.z_axis)
}
}
impl fmt::Debug for Mat3A {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct(stringify!(Mat3A))
.field("x_axis", &self.x_axis)
.field("y_axis", &self.y_axis)
.field("z_axis", &self.z_axis)
.finish()
}
}
impl fmt::Display for Mat3A {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(p) = f.precision() {
write!(
f,
"[{:.*}, {:.*}, {:.*}]",
p, self.x_axis, p, self.y_axis, p, self.z_axis
)
} else {
write!(f, "[{}, {}, {}]", self.x_axis, self.y_axis, self.z_axis)
}
}
}
+1444
View File
File diff suppressed because it is too large Load Diff
+973
View File
@@ -0,0 +1,973 @@
// Generated from quat.rs.tera template. Edit the template, not the generated file.
use crate::{
euler::{EulerRot, FromEuler, ToEuler},
f32::math,
DQuat, Mat3, Mat3A, Mat4, Vec2, Vec3, Vec3A, Vec4,
};
use core::fmt;
use core::iter::{Product, Sum};
use core::ops::{Add, Div, Mul, MulAssign, Neg, Sub};
/// Creates a quaternion from `x`, `y`, `z` and `w` values.
///
/// This should generally not be called manually unless you know what you are doing. Use
/// one of the other constructors instead such as `identity` or `from_axis_angle`.
#[inline]
#[must_use]
pub const fn quat(x: f32, y: f32, z: f32, w: f32) -> Quat {
Quat::from_xyzw(x, y, z, w)
}
/// A quaternion representing an orientation.
///
/// This quaternion is intended to be of unit length but may denormalize due to
/// floating point "error creep" which can occur when successive quaternion
/// operations are applied.
#[derive(Clone, Copy)]
#[cfg_attr(
not(any(feature = "scalar-math", target_arch = "spirv")),
repr(align(16))
)]
#[cfg_attr(not(target_arch = "spirv"), repr(C))]
#[cfg_attr(target_arch = "spirv", repr(simd))]
pub struct Quat {
pub x: f32,
pub y: f32,
pub z: f32,
pub w: f32,
}
impl Quat {
/// All zeros.
const ZERO: Self = Self::from_array([0.0; 4]);
/// The identity quaternion. Corresponds to no rotation.
pub const IDENTITY: Self = Self::from_xyzw(0.0, 0.0, 0.0, 1.0);
/// All NANs.
pub const NAN: Self = Self::from_array([f32::NAN; 4]);
/// Creates a new rotation quaternion.
///
/// This should generally not be called manually unless you know what you are doing.
/// Use one of the other constructors instead such as `identity` or `from_axis_angle`.
///
/// `from_xyzw` is mostly used by unit tests and `serde` deserialization.
///
/// # Preconditions
///
/// This function does not check if the input is normalized, it is up to the user to
/// provide normalized input or to normalized the resulting quaternion.
#[inline(always)]
#[must_use]
pub const fn from_xyzw(x: f32, y: f32, z: f32, w: f32) -> Self {
Self { x, y, z, w }
}
/// Creates a rotation quaternion from an array.
///
/// # Preconditions
///
/// This function does not check if the input is normalized, it is up to the user to
/// provide normalized input or to normalized the resulting quaternion.
#[inline]
#[must_use]
pub const fn from_array(a: [f32; 4]) -> Self {
Self::from_xyzw(a[0], a[1], a[2], a[3])
}
/// Creates a new rotation quaternion from a 4D vector.
///
/// # Preconditions
///
/// This function does not check if the input is normalized, it is up to the user to
/// provide normalized input or to normalized the resulting quaternion.
#[inline]
#[must_use]
pub const fn from_vec4(v: Vec4) -> Self {
Self {
x: v.x,
y: v.y,
z: v.z,
w: v.w,
}
}
/// Creates a rotation quaternion from a slice.
///
/// # Preconditions
///
/// This function does not check if the input is normalized, it is up to the user to
/// provide normalized input or to normalized the resulting quaternion.
///
/// # Panics
///
/// Panics if `slice` length is less than 4.
#[inline]
#[must_use]
pub fn from_slice(slice: &[f32]) -> Self {
Self::from_xyzw(slice[0], slice[1], slice[2], slice[3])
}
/// Writes the quaternion to an unaligned slice.
///
/// # Panics
///
/// Panics if `slice` length is less than 4.
#[inline]
pub fn write_to_slice(self, slice: &mut [f32]) {
slice[0] = self.x;
slice[1] = self.y;
slice[2] = self.z;
slice[3] = self.w;
}
/// Create a quaternion for a normalized rotation `axis` and `angle` (in radians).
///
/// The axis must be a unit vector.
///
/// # Panics
///
/// Will panic if `axis` is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn from_axis_angle(axis: Vec3, angle: f32) -> Self {
glam_assert!(axis.is_normalized());
let (s, c) = math::sin_cos(angle * 0.5);
let v = axis * s;
Self::from_xyzw(v.x, v.y, v.z, c)
}
/// Create a quaternion that rotates `v.length()` radians around `v.normalize()`.
///
/// `from_scaled_axis(Vec3::ZERO)` results in the identity quaternion.
#[inline]
#[must_use]
pub fn from_scaled_axis(v: Vec3) -> Self {
let length = v.length();
if length == 0.0 {
Self::IDENTITY
} else {
Self::from_axis_angle(v / length, length)
}
}
/// Creates a quaternion from the `angle` (in radians) around the x axis.
#[inline]
#[must_use]
pub fn from_rotation_x(angle: f32) -> Self {
let (s, c) = math::sin_cos(angle * 0.5);
Self::from_xyzw(s, 0.0, 0.0, c)
}
/// Creates a quaternion from the `angle` (in radians) around the y axis.
#[inline]
#[must_use]
pub fn from_rotation_y(angle: f32) -> Self {
let (s, c) = math::sin_cos(angle * 0.5);
Self::from_xyzw(0.0, s, 0.0, c)
}
/// Creates a quaternion from the `angle` (in radians) around the z axis.
#[inline]
#[must_use]
pub fn from_rotation_z(angle: f32) -> Self {
let (s, c) = math::sin_cos(angle * 0.5);
Self::from_xyzw(0.0, 0.0, s, c)
}
/// Creates a quaternion from the given Euler rotation sequence and the angles (in radians).
#[inline]
#[must_use]
pub fn from_euler(euler: EulerRot, a: f32, b: f32, c: f32) -> Self {
Self::from_euler_angles(euler, a, b, c)
}
/// From the columns of a 3x3 rotation matrix.
///
/// Note if the input axes contain scales, shears, or other non-rotation transformations then
/// the output of this function is ill-defined.
///
/// # Panics
///
/// Will panic if any axis is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub(crate) fn from_rotation_axes(x_axis: Vec3, y_axis: Vec3, z_axis: Vec3) -> Self {
glam_assert!(x_axis.is_normalized() && y_axis.is_normalized() && z_axis.is_normalized());
// Based on https://github.com/microsoft/DirectXMath `XMQuaternionRotationMatrix`
let (m00, m01, m02) = x_axis.into();
let (m10, m11, m12) = y_axis.into();
let (m20, m21, m22) = z_axis.into();
if m22 <= 0.0 {
// x^2 + y^2 >= z^2 + w^2
let dif10 = m11 - m00;
let omm22 = 1.0 - m22;
if dif10 <= 0.0 {
// x^2 >= y^2
let four_xsq = omm22 - dif10;
let inv4x = 0.5 / math::sqrt(four_xsq);
Self::from_xyzw(
four_xsq * inv4x,
(m01 + m10) * inv4x,
(m02 + m20) * inv4x,
(m12 - m21) * inv4x,
)
} else {
// y^2 >= x^2
let four_ysq = omm22 + dif10;
let inv4y = 0.5 / math::sqrt(four_ysq);
Self::from_xyzw(
(m01 + m10) * inv4y,
four_ysq * inv4y,
(m12 + m21) * inv4y,
(m20 - m02) * inv4y,
)
}
} else {
// z^2 + w^2 >= x^2 + y^2
let sum10 = m11 + m00;
let opm22 = 1.0 + m22;
if sum10 <= 0.0 {
// z^2 >= w^2
let four_zsq = opm22 - sum10;
let inv4z = 0.5 / math::sqrt(four_zsq);
Self::from_xyzw(
(m02 + m20) * inv4z,
(m12 + m21) * inv4z,
four_zsq * inv4z,
(m01 - m10) * inv4z,
)
} else {
// w^2 >= z^2
let four_wsq = opm22 + sum10;
let inv4w = 0.5 / math::sqrt(four_wsq);
Self::from_xyzw(
(m12 - m21) * inv4w,
(m20 - m02) * inv4w,
(m01 - m10) * inv4w,
four_wsq * inv4w,
)
}
}
}
/// Creates a quaternion from a 3x3 rotation matrix.
///
/// Note if the input matrix contain scales, shears, or other non-rotation transformations then
/// the resulting quaternion will be ill-defined.
///
/// # Panics
///
/// Will panic if any input matrix column is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn from_mat3(mat: &Mat3) -> Self {
Self::from_rotation_axes(mat.x_axis, mat.y_axis, mat.z_axis)
}
/// Creates a quaternion from a 3x3 SIMD aligned rotation matrix.
///
/// Note if the input matrix contain scales, shears, or other non-rotation transformations then
/// the resulting quaternion will be ill-defined.
///
/// # Panics
///
/// Will panic if any input matrix column is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn from_mat3a(mat: &Mat3A) -> Self {
Self::from_rotation_axes(mat.x_axis.into(), mat.y_axis.into(), mat.z_axis.into())
}
/// Creates a quaternion from the upper 3x3 rotation matrix inside a homogeneous 4x4 matrix.
///
/// Note if the upper 3x3 matrix contain scales, shears, or other non-rotation transformations
/// then the resulting quaternion will be ill-defined.
///
/// # Panics
///
/// Will panic if any column of the upper 3x3 rotation matrix is not normalized when
/// `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn from_mat4(mat: &Mat4) -> Self {
Self::from_rotation_axes(
mat.x_axis.truncate(),
mat.y_axis.truncate(),
mat.z_axis.truncate(),
)
}
/// Gets the minimal rotation for transforming `from` to `to`. The rotation is in the
/// plane spanned by the two vectors. Will rotate at most 180 degrees.
///
/// The inputs must be unit vectors.
///
/// `from_rotation_arc(from, to) * from ≈ to`.
///
/// For near-singular cases (from≈to and from≈-to) the current implementation
/// is only accurate to about 0.001 (for `f32`).
///
/// # Panics
///
/// Will panic if `from` or `to` are not normalized when `glam_assert` is enabled.
#[must_use]
pub fn from_rotation_arc(from: Vec3, to: Vec3) -> Self {
glam_assert!(from.is_normalized());
glam_assert!(to.is_normalized());
const ONE_MINUS_EPS: f32 = 1.0 - 2.0 * f32::EPSILON;
let dot = from.dot(to);
if dot > ONE_MINUS_EPS {
// 0° singularity: from ≈ to
Self::IDENTITY
} else if dot < -ONE_MINUS_EPS {
// 180° singularity: from ≈ -to
use core::f32::consts::PI; // half a turn = 𝛕/2 = 180°
Self::from_axis_angle(from.any_orthonormal_vector(), PI)
} else {
let c = from.cross(to);
Self::from_xyzw(c.x, c.y, c.z, 1.0 + dot).normalize()
}
}
/// Gets the minimal rotation for transforming `from` to either `to` or `-to`. This means
/// that the resulting quaternion will rotate `from` so that it is colinear with `to`.
///
/// The rotation is in the plane spanned by the two vectors. Will rotate at most 90
/// degrees.
///
/// The inputs must be unit vectors.
///
/// `to.dot(from_rotation_arc_colinear(from, to) * from).abs() ≈ 1`.
///
/// # Panics
///
/// Will panic if `from` or `to` are not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn from_rotation_arc_colinear(from: Vec3, to: Vec3) -> Self {
if from.dot(to) < 0.0 {
Self::from_rotation_arc(from, -to)
} else {
Self::from_rotation_arc(from, to)
}
}
/// Gets the minimal rotation for transforming `from` to `to`. The resulting rotation is
/// around the z axis. Will rotate at most 180 degrees.
///
/// The inputs must be unit vectors.
///
/// `from_rotation_arc_2d(from, to) * from ≈ to`.
///
/// For near-singular cases (from≈to and from≈-to) the current implementation
/// is only accurate to about 0.001 (for `f32`).
///
/// # Panics
///
/// Will panic if `from` or `to` are not normalized when `glam_assert` is enabled.
#[must_use]
pub fn from_rotation_arc_2d(from: Vec2, to: Vec2) -> Self {
glam_assert!(from.is_normalized());
glam_assert!(to.is_normalized());
const ONE_MINUS_EPSILON: f32 = 1.0 - 2.0 * f32::EPSILON;
let dot = from.dot(to);
if dot > ONE_MINUS_EPSILON {
// 0° singularity: from ≈ to
Self::IDENTITY
} else if dot < -ONE_MINUS_EPSILON {
// 180° singularity: from ≈ -to
const COS_FRAC_PI_2: f32 = 0.0;
const SIN_FRAC_PI_2: f32 = 1.0;
// rotation around z by PI radians
Self::from_xyzw(0.0, 0.0, SIN_FRAC_PI_2, COS_FRAC_PI_2)
} else {
// vector3 cross where z=0
let z = from.x * to.y - to.x * from.y;
let w = 1.0 + dot;
// calculate length with x=0 and y=0 to normalize
let len_rcp = 1.0 / math::sqrt(z * z + w * w);
Self::from_xyzw(0.0, 0.0, z * len_rcp, w * len_rcp)
}
}
/// Returns the rotation axis (normalized) and angle (in radians) of `self`.
#[inline]
#[must_use]
pub fn to_axis_angle(self) -> (Vec3, f32) {
const EPSILON: f32 = 1.0e-8;
let v = Vec3::new(self.x, self.y, self.z);
let length = v.length();
if length >= EPSILON {
let angle = 2.0 * math::atan2(length, self.w);
let axis = v / length;
(axis, angle)
} else {
(Vec3::X, 0.0)
}
}
/// Returns the rotation axis scaled by the rotation in radians.
#[inline]
#[must_use]
pub fn to_scaled_axis(self) -> Vec3 {
let (axis, angle) = self.to_axis_angle();
axis * angle
}
/// Returns the rotation angles for the given euler rotation sequence.
#[inline]
#[must_use]
pub fn to_euler(self, order: EulerRot) -> (f32, f32, f32) {
self.to_euler_angles(order)
}
/// `[x, y, z, w]`
#[inline]
#[must_use]
pub fn to_array(&self) -> [f32; 4] {
[self.x, self.y, self.z, self.w]
}
/// Returns the vector part of the quaternion.
#[inline]
#[must_use]
pub fn xyz(self) -> Vec3 {
Vec3::new(self.x, self.y, self.z)
}
/// Returns the quaternion conjugate of `self`. For a unit quaternion the
/// conjugate is also the inverse.
#[inline]
#[must_use]
pub fn conjugate(self) -> Self {
Self {
x: -self.x,
y: -self.y,
z: -self.z,
w: self.w,
}
}
/// Returns the inverse of a normalized quaternion.
///
/// Typically quaternion inverse returns the conjugate of a normalized quaternion.
/// Because `self` is assumed to already be unit length this method *does not* normalize
/// before returning the conjugate.
///
/// # Panics
///
/// Will panic if `self` is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn inverse(self) -> Self {
glam_assert!(self.is_normalized());
self.conjugate()
}
/// Computes the dot product of `self` and `rhs`. The dot product is
/// equal to the cosine of the angle between two quaternion rotations.
#[inline]
#[must_use]
pub fn dot(self, rhs: Self) -> f32 {
Vec4::from(self).dot(Vec4::from(rhs))
}
/// Computes the length of `self`.
#[doc(alias = "magnitude")]
#[inline]
#[must_use]
pub fn length(self) -> f32 {
Vec4::from(self).length()
}
/// Computes the squared length of `self`.
///
/// This is generally faster than `length()` as it avoids a square
/// root operation.
#[doc(alias = "magnitude2")]
#[inline]
#[must_use]
pub fn length_squared(self) -> f32 {
Vec4::from(self).length_squared()
}
/// Computes `1.0 / length()`.
///
/// For valid results, `self` must _not_ be of length zero.
#[inline]
#[must_use]
pub fn length_recip(self) -> f32 {
Vec4::from(self).length_recip()
}
/// Returns `self` normalized to length 1.0.
///
/// For valid results, `self` must _not_ be of length zero.
///
/// Panics
///
/// Will panic if `self` is zero length when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn normalize(self) -> Self {
Self::from_vec4(Vec4::from(self).normalize())
}
/// Returns `true` if, and only if, all elements are finite.
/// If any element is either `NaN`, positive or negative infinity, this will return `false`.
#[inline]
#[must_use]
pub fn is_finite(self) -> bool {
Vec4::from(self).is_finite()
}
/// Returns `true` if any elements are `NAN`.
#[inline]
#[must_use]
pub fn is_nan(self) -> bool {
Vec4::from(self).is_nan()
}
/// Returns whether `self` of length `1.0` or not.
///
/// Uses a precision threshold of `1e-6`.
#[inline]
#[must_use]
pub fn is_normalized(self) -> bool {
Vec4::from(self).is_normalized()
}
#[inline]
#[must_use]
pub fn is_near_identity(self) -> bool {
// Based on https://github.com/nfrechette/rtm `rtm::quat_near_identity`
let threshold_angle = 0.002_847_144_6;
// Because of floating point precision, we cannot represent very small rotations.
// The closest f32 to 1.0 that is not 1.0 itself yields:
// 0.99999994.acos() * 2.0 = 0.000690533954 rad
//
// An error threshold of 1.e-6 is used by default.
// (1.0 - 1.e-6).acos() * 2.0 = 0.00284714461 rad
// (1.0 - 1.e-7).acos() * 2.0 = 0.00097656250 rad
//
// We don't really care about the angle value itself, only if it's close to 0.
// This will happen whenever quat.w is close to 1.0.
// If the quat.w is close to -1.0, the angle will be near 2*PI which is close to
// a negative 0 rotation. By forcing quat.w to be positive, we'll end up with
// the shortest path.
let positive_w_angle = math::acos_approx(math::abs(self.w)) * 2.0;
positive_w_angle < threshold_angle
}
/// Returns the angle (in radians) for the minimal rotation
/// for transforming this quaternion into another.
///
/// Both quaternions must be normalized.
///
/// # Panics
///
/// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn angle_between(self, rhs: Self) -> f32 {
glam_assert!(self.is_normalized() && rhs.is_normalized());
math::acos_approx(math::abs(self.dot(rhs))) * 2.0
}
/// Rotates towards `rhs` up to `max_angle` (in radians).
///
/// When `max_angle` is `0.0`, the result will be equal to `self`. When `max_angle` is equal to
/// `self.angle_between(rhs)`, the result will be equal to `rhs`. If `max_angle` is negative,
/// rotates towards the exact opposite of `rhs`. Will not go past the target.
///
/// Both quaternions must be normalized.
///
/// # Panics
///
/// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn rotate_towards(&self, rhs: Self, max_angle: f32) -> Self {
glam_assert!(self.is_normalized() && rhs.is_normalized());
let angle = self.angle_between(rhs);
if angle <= 1e-4 {
return *self;
}
let s = (max_angle / angle).clamp(-1.0, 1.0);
self.slerp(rhs, s)
}
/// Returns true if the absolute difference of all elements between `self` and `rhs`
/// is less than or equal to `max_abs_diff`.
///
/// This can be used to compare if two quaternions contain similar elements. It works
/// best when comparing with a known value. The `max_abs_diff` that should be used used
/// depends on the values being compared against.
///
/// For more see
/// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
#[inline]
#[must_use]
pub fn abs_diff_eq(self, rhs: Self, max_abs_diff: f32) -> bool {
Vec4::from(self).abs_diff_eq(Vec4::from(rhs), max_abs_diff)
}
#[inline(always)]
#[must_use]
fn lerp_impl(self, end: Self, s: f32) -> Self {
(self * (1.0 - s) + end * s).normalize()
}
/// Performs a linear interpolation between `self` and `rhs` based on
/// the value `s`.
///
/// When `s` is `0.0`, the result will be equal to `self`. When `s`
/// is `1.0`, the result will be equal to `rhs`.
///
/// # Panics
///
/// Will panic if `self` or `end` are not normalized when `glam_assert` is enabled.
#[doc(alias = "mix")]
#[inline]
#[must_use]
pub fn lerp(self, end: Self, s: f32) -> Self {
glam_assert!(self.is_normalized());
glam_assert!(end.is_normalized());
let dot = self.dot(end);
let bias = if dot >= 0.0 { 1.0 } else { -1.0 };
self.lerp_impl(end * bias, s)
}
/// Performs a spherical linear interpolation between `self` and `end`
/// based on the value `s`.
///
/// When `s` is `0.0`, the result will be equal to `self`. When `s`
/// is `1.0`, the result will be equal to `end`.
///
/// # Panics
///
/// Will panic if `self` or `end` are not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn slerp(self, mut end: Self, s: f32) -> Self {
// http://number-none.com/product/Understanding%20Slerp,%20Then%20Not%20Using%20It/
glam_assert!(self.is_normalized());
glam_assert!(end.is_normalized());
// Note that a rotation can be represented by two quaternions: `q` and
// `-q`. The slerp path between `q` and `end` will be different from the
// path between `-q` and `end`. One path will take the long way around and
// one will take the short way. In order to correct for this, the `dot`
// product between `self` and `end` should be positive. If the `dot`
// product is negative, slerp between `self` and `-end`.
let mut dot = self.dot(end);
if dot < 0.0 {
end = -end;
dot = -dot;
}
const DOT_THRESHOLD: f32 = 1.0 - f32::EPSILON;
if dot > DOT_THRESHOLD {
// if above threshold perform linear interpolation to avoid divide by zero
self.lerp_impl(end, s)
} else {
let theta = math::acos_approx(dot);
let scale1 = math::sin(theta * (1.0 - s));
let scale2 = math::sin(theta * s);
let theta_sin = math::sin(theta);
((self * scale1) + (end * scale2)) * (1.0 / theta_sin)
}
}
/// Multiplies a quaternion and a 3D vector, returning the rotated vector.
///
/// # Panics
///
/// Will panic if `self` is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn mul_vec3(self, rhs: Vec3) -> Vec3 {
glam_assert!(self.is_normalized());
let w = self.w;
let b = Vec3::new(self.x, self.y, self.z);
let b2 = b.dot(b);
rhs.mul(w * w - b2)
.add(b.mul(rhs.dot(b) * 2.0))
.add(b.cross(rhs).mul(w * 2.0))
}
/// Multiplies two quaternions. If they each represent a rotation, the result will
/// represent the combined rotation.
///
/// Note that due to floating point rounding the result may not be perfectly normalized.
///
/// # Panics
///
/// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn mul_quat(self, rhs: Self) -> Self {
let (x0, y0, z0, w0) = self.into();
let (x1, y1, z1, w1) = rhs.into();
Self::from_xyzw(
w0 * x1 + x0 * w1 + y0 * z1 - z0 * y1,
w0 * y1 - x0 * z1 + y0 * w1 + z0 * x1,
w0 * z1 + x0 * y1 - y0 * x1 + z0 * w1,
w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1,
)
}
/// Creates a quaternion from a 3x3 rotation matrix inside a 3D affine transform.
///
/// Note if the input affine matrix contain scales, shears, or other non-rotation
/// transformations then the resulting quaternion will be ill-defined.
///
/// # Panics
///
/// Will panic if any input affine matrix column is not normalized when `glam_assert` is
/// enabled.
#[inline]
#[must_use]
pub fn from_affine3(a: &crate::Affine3A) -> Self {
#[allow(clippy::useless_conversion)]
Self::from_rotation_axes(
a.matrix3.x_axis.into(),
a.matrix3.y_axis.into(),
a.matrix3.z_axis.into(),
)
}
/// Multiplies a quaternion and a 3D vector, returning the rotated vector.
#[inline]
#[must_use]
pub fn mul_vec3a(self, rhs: Vec3A) -> Vec3A {
self.mul_vec3(rhs.into()).into()
}
#[inline]
#[must_use]
pub fn as_dquat(self) -> DQuat {
DQuat::from_xyzw(self.x as f64, self.y as f64, self.z as f64, self.w as f64)
}
}
impl fmt::Debug for Quat {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_tuple(stringify!(Quat))
.field(&self.x)
.field(&self.y)
.field(&self.z)
.field(&self.w)
.finish()
}
}
impl fmt::Display for Quat {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(p) = f.precision() {
write!(
f,
"[{:.*}, {:.*}, {:.*}, {:.*}]",
p, self.x, p, self.y, p, self.z, p, self.w
)
} else {
write!(f, "[{}, {}, {}, {}]", self.x, self.y, self.z, self.w)
}
}
}
impl Add<Quat> for Quat {
type Output = Self;
/// Adds two quaternions.
///
/// The sum is not guaranteed to be normalized.
///
/// Note that addition is not the same as combining the rotations represented by the
/// two quaternions! That corresponds to multiplication.
#[inline]
fn add(self, rhs: Self) -> Self {
Self::from_vec4(Vec4::from(self) + Vec4::from(rhs))
}
}
impl Sub<Quat> for Quat {
type Output = Self;
/// Subtracts the `rhs` quaternion from `self`.
///
/// The difference is not guaranteed to be normalized.
#[inline]
fn sub(self, rhs: Self) -> Self {
Self::from_vec4(Vec4::from(self) - Vec4::from(rhs))
}
}
impl Mul<f32> for Quat {
type Output = Self;
/// Multiplies a quaternion by a scalar value.
///
/// The product is not guaranteed to be normalized.
#[inline]
fn mul(self, rhs: f32) -> Self {
Self::from_vec4(Vec4::from(self) * rhs)
}
}
impl Div<f32> for Quat {
type Output = Self;
/// Divides a quaternion by a scalar value.
/// The quotient is not guaranteed to be normalized.
#[inline]
fn div(self, rhs: f32) -> Self {
Self::from_vec4(Vec4::from(self) / rhs)
}
}
impl Mul<Quat> for Quat {
type Output = Self;
/// Multiplies two quaternions. If they each represent a rotation, the result will
/// represent the combined rotation.
///
/// Note that due to floating point rounding the result may not be perfectly
/// normalized.
///
/// # Panics
///
/// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
#[inline]
fn mul(self, rhs: Self) -> Self {
self.mul_quat(rhs)
}
}
impl MulAssign<Quat> for Quat {
/// Multiplies two quaternions. If they each represent a rotation, the result will
/// represent the combined rotation.
///
/// Note that due to floating point rounding the result may not be perfectly
/// normalized.
///
/// # Panics
///
/// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
#[inline]
fn mul_assign(&mut self, rhs: Self) {
*self = self.mul_quat(rhs);
}
}
impl Mul<Vec3> for Quat {
type Output = Vec3;
/// Multiplies a quaternion and a 3D vector, returning the rotated vector.
///
/// # Panics
///
/// Will panic if `self` is not normalized when `glam_assert` is enabled.
#[inline]
fn mul(self, rhs: Vec3) -> Self::Output {
self.mul_vec3(rhs)
}
}
impl Neg for Quat {
type Output = Self;
#[inline]
fn neg(self) -> Self {
self * -1.0
}
}
impl Default for Quat {
#[inline]
fn default() -> Self {
Self::IDENTITY
}
}
impl PartialEq for Quat {
#[inline]
fn eq(&self, rhs: &Self) -> bool {
Vec4::from(*self).eq(&Vec4::from(*rhs))
}
}
#[cfg(not(target_arch = "spirv"))]
impl AsRef<[f32; 4]> for Quat {
#[inline]
fn as_ref(&self) -> &[f32; 4] {
unsafe { &*(self as *const Self as *const [f32; 4]) }
}
}
impl Sum<Self> for Quat {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Self::ZERO, Self::add)
}
}
impl<'a> Sum<&'a Self> for Quat {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
}
}
impl Product for Quat {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Self::IDENTITY, Self::mul)
}
}
impl<'a> Product<&'a Self> for Quat {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::IDENTITY, |a, &b| Self::mul(a, b))
}
}
impl Mul<Vec3A> for Quat {
type Output = Vec3A;
#[inline]
fn mul(self, rhs: Vec3A) -> Self::Output {
self.mul_vec3a(rhs)
}
}
impl From<Quat> for Vec4 {
#[inline]
fn from(q: Quat) -> Self {
Self::new(q.x, q.y, q.z, q.w)
}
}
impl From<Quat> for (f32, f32, f32, f32) {
#[inline]
fn from(q: Quat) -> Self {
(q.x, q.y, q.z, q.w)
}
}
impl From<Quat> for [f32; 4] {
#[inline]
fn from(q: Quat) -> Self {
[q.x, q.y, q.z, q.w]
}
}
File diff suppressed because it is too large Load Diff
+1999
View File
File diff suppressed because it is too large Load Diff
+6
View File
@@ -0,0 +1,6 @@
pub mod mat2;
pub mod mat3a;
pub mod mat4;
pub mod quat;
pub mod vec3a;
pub mod vec4;
+614
View File
@@ -0,0 +1,614 @@
// Generated from mat.rs.tera template. Edit the template, not the generated file.
use crate::{f32::math, swizzles::*, DMat2, Mat3, Mat3A, Vec2};
use core::fmt;
use core::iter::{Product, Sum};
use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
#[cfg(target_arch = "x86")]
use core::arch::x86::*;
#[cfg(target_arch = "x86_64")]
use core::arch::x86_64::*;
#[repr(C)]
union UnionCast {
a: [f32; 4],
v: Mat2,
}
/// Creates a 2x2 matrix from two column vectors.
#[inline(always)]
#[must_use]
pub const fn mat2(x_axis: Vec2, y_axis: Vec2) -> Mat2 {
Mat2::from_cols(x_axis, y_axis)
}
/// A 2x2 column major matrix.
///
/// SIMD vector types are used for storage on supported platforms.
///
/// This type is 16 byte aligned.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct Mat2(pub(crate) __m128);
impl Mat2 {
/// A 2x2 matrix with all elements set to `0.0`.
pub const ZERO: Self = Self::from_cols(Vec2::ZERO, Vec2::ZERO);
/// A 2x2 identity matrix, where all diagonal elements are `1`, and all off-diagonal elements are `0`.
pub const IDENTITY: Self = Self::from_cols(Vec2::X, Vec2::Y);
/// All NAN:s.
pub const NAN: Self = Self::from_cols(Vec2::NAN, Vec2::NAN);
#[allow(clippy::too_many_arguments)]
#[inline(always)]
#[must_use]
const fn new(m00: f32, m01: f32, m10: f32, m11: f32) -> Self {
unsafe {
UnionCast {
a: [m00, m01, m10, m11],
}
.v
}
}
/// Creates a 2x2 matrix from two column vectors.
#[inline(always)]
#[must_use]
pub const fn from_cols(x_axis: Vec2, y_axis: Vec2) -> Self {
unsafe {
UnionCast {
a: [x_axis.x, x_axis.y, y_axis.x, y_axis.y],
}
.v
}
}
/// Creates a 2x2 matrix from a `[f32; 4]` array stored in column major order.
/// If your data is stored in row major you will need to `transpose` the returned
/// matrix.
#[inline]
#[must_use]
pub const fn from_cols_array(m: &[f32; 4]) -> Self {
Self::new(m[0], m[1], m[2], m[3])
}
/// Creates a `[f32; 4]` array storing data in column major order.
/// If you require data in row major order `transpose` the matrix first.
#[inline]
#[must_use]
pub const fn to_cols_array(&self) -> [f32; 4] {
unsafe { *(self as *const Self as *const [f32; 4]) }
}
/// Creates a 2x2 matrix from a `[[f32; 2]; 2]` 2D array stored in column major order.
/// If your data is in row major order you will need to `transpose` the returned
/// matrix.
#[inline]
#[must_use]
pub const fn from_cols_array_2d(m: &[[f32; 2]; 2]) -> Self {
Self::from_cols(Vec2::from_array(m[0]), Vec2::from_array(m[1]))
}
/// Creates a `[[f32; 2]; 2]` 2D array storing data in column major order.
/// If you require data in row major order `transpose` the matrix first.
#[inline]
#[must_use]
pub const fn to_cols_array_2d(&self) -> [[f32; 2]; 2] {
unsafe { *(self as *const Self as *const [[f32; 2]; 2]) }
}
/// Creates a 2x2 matrix with its diagonal set to `diagonal` and all other entries set to 0.
#[doc(alias = "scale")]
#[inline]
#[must_use]
pub const fn from_diagonal(diagonal: Vec2) -> Self {
Self::new(diagonal.x, 0.0, 0.0, diagonal.y)
}
/// Creates a 2x2 matrix containing the combining non-uniform `scale` and rotation of
/// `angle` (in radians).
#[inline]
#[must_use]
pub fn from_scale_angle(scale: Vec2, angle: f32) -> Self {
let (sin, cos) = math::sin_cos(angle);
Self::new(cos * scale.x, sin * scale.x, -sin * scale.y, cos * scale.y)
}
/// Creates a 2x2 matrix containing a rotation of `angle` (in radians).
#[inline]
#[must_use]
pub fn from_angle(angle: f32) -> Self {
let (sin, cos) = math::sin_cos(angle);
Self::new(cos, sin, -sin, cos)
}
/// Creates a 2x2 matrix from a 3x3 matrix, discarding the 2nd row and column.
#[inline]
#[must_use]
pub fn from_mat3(m: Mat3) -> Self {
Self::from_cols(m.x_axis.xy(), m.y_axis.xy())
}
/// Creates a 2x2 matrix from the minor of the given 3x3 matrix, discarding the `i`th column
/// and `j`th row.
///
/// # Panics
///
/// Panics if `i` or `j` is greater than 2.
#[inline]
#[must_use]
pub fn from_mat3_minor(m: Mat3, i: usize, j: usize) -> Self {
match (i, j) {
(0, 0) => Self::from_cols(m.y_axis.yz(), m.z_axis.yz()),
(0, 1) => Self::from_cols(m.y_axis.xz(), m.z_axis.xz()),
(0, 2) => Self::from_cols(m.y_axis.xy(), m.z_axis.xy()),
(1, 0) => Self::from_cols(m.x_axis.yz(), m.z_axis.yz()),
(1, 1) => Self::from_cols(m.x_axis.xz(), m.z_axis.xz()),
(1, 2) => Self::from_cols(m.x_axis.xy(), m.z_axis.xy()),
(2, 0) => Self::from_cols(m.x_axis.yz(), m.y_axis.yz()),
(2, 1) => Self::from_cols(m.x_axis.xz(), m.y_axis.xz()),
(2, 2) => Self::from_cols(m.x_axis.xy(), m.y_axis.xy()),
_ => panic!("index out of bounds"),
}
}
/// Creates a 2x2 matrix from a 3x3 matrix, discarding the 2nd row and column.
#[inline]
#[must_use]
pub fn from_mat3a(m: Mat3A) -> Self {
Self::from_cols(m.x_axis.xy(), m.y_axis.xy())
}
/// Creates a 2x2 matrix from the minor of the given 3x3 matrix, discarding the `i`th column
/// and `j`th row.
///
/// # Panics
///
/// Panics if `i` or `j` is greater than 2.
#[inline]
#[must_use]
pub fn from_mat3a_minor(m: Mat3A, i: usize, j: usize) -> Self {
match (i, j) {
(0, 0) => Self::from_cols(m.y_axis.yz(), m.z_axis.yz()),
(0, 1) => Self::from_cols(m.y_axis.xz(), m.z_axis.xz()),
(0, 2) => Self::from_cols(m.y_axis.xy(), m.z_axis.xy()),
(1, 0) => Self::from_cols(m.x_axis.yz(), m.z_axis.yz()),
(1, 1) => Self::from_cols(m.x_axis.xz(), m.z_axis.xz()),
(1, 2) => Self::from_cols(m.x_axis.xy(), m.z_axis.xy()),
(2, 0) => Self::from_cols(m.x_axis.yz(), m.y_axis.yz()),
(2, 1) => Self::from_cols(m.x_axis.xz(), m.y_axis.xz()),
(2, 2) => Self::from_cols(m.x_axis.xy(), m.y_axis.xy()),
_ => panic!("index out of bounds"),
}
}
/// Creates a 2x2 matrix from the first 4 values in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 4 elements long.
#[inline]
#[must_use]
pub const fn from_cols_slice(slice: &[f32]) -> Self {
Self::new(slice[0], slice[1], slice[2], slice[3])
}
/// Writes the columns of `self` to the first 4 elements in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 4 elements long.
#[inline]
pub fn write_cols_to_slice(self, slice: &mut [f32]) {
slice[0] = self.x_axis.x;
slice[1] = self.x_axis.y;
slice[2] = self.y_axis.x;
slice[3] = self.y_axis.y;
}
/// Returns the matrix column for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 1.
#[inline]
#[must_use]
pub fn col(&self, index: usize) -> Vec2 {
match index {
0 => self.x_axis,
1 => self.y_axis,
_ => panic!("index out of bounds"),
}
}
/// Returns a mutable reference to the matrix column for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 1.
#[inline]
pub fn col_mut(&mut self, index: usize) -> &mut Vec2 {
match index {
0 => &mut self.x_axis,
1 => &mut self.y_axis,
_ => panic!("index out of bounds"),
}
}
/// Returns the matrix row for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 1.
#[inline]
#[must_use]
pub fn row(&self, index: usize) -> Vec2 {
match index {
0 => Vec2::new(self.x_axis.x, self.y_axis.x),
1 => Vec2::new(self.x_axis.y, self.y_axis.y),
_ => panic!("index out of bounds"),
}
}
/// Returns `true` if, and only if, all elements are finite.
/// If any element is either `NaN`, positive or negative infinity, this will return `false`.
#[inline]
#[must_use]
pub fn is_finite(&self) -> bool {
self.x_axis.is_finite() && self.y_axis.is_finite()
}
/// Returns `true` if any elements are `NaN`.
#[inline]
#[must_use]
pub fn is_nan(&self) -> bool {
self.x_axis.is_nan() || self.y_axis.is_nan()
}
/// Returns the transpose of `self`.
#[inline]
#[must_use]
pub fn transpose(&self) -> Self {
Self(unsafe { _mm_shuffle_ps(self.0, self.0, 0b11_01_10_00) })
}
/// Returns the determinant of `self`.
#[inline]
#[must_use]
pub fn determinant(&self) -> f32 {
unsafe {
let abcd = self.0;
let dcba = _mm_shuffle_ps(abcd, abcd, 0b00_01_10_11);
let prod = _mm_mul_ps(abcd, dcba);
let det = _mm_sub_ps(prod, _mm_shuffle_ps(prod, prod, 0b01_01_01_01));
_mm_cvtss_f32(det)
}
}
/// Returns the inverse of `self`.
///
/// If the matrix is not invertible the returned matrix will be invalid.
///
/// # Panics
///
/// Will panic if the determinant of `self` is zero when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn inverse(&self) -> Self {
unsafe {
const SIGN: __m128 = crate::sse2::m128_from_f32x4([1.0, -1.0, -1.0, 1.0]);
let abcd = self.0;
let dcba = _mm_shuffle_ps(abcd, abcd, 0b00_01_10_11);
let prod = _mm_mul_ps(abcd, dcba);
let sub = _mm_sub_ps(prod, _mm_shuffle_ps(prod, prod, 0b01_01_01_01));
let det = _mm_shuffle_ps(sub, sub, 0b00_00_00_00);
let tmp = _mm_div_ps(SIGN, det);
glam_assert!(Mat2(tmp).is_finite());
let dbca = _mm_shuffle_ps(abcd, abcd, 0b00_10_01_11);
Self(_mm_mul_ps(dbca, tmp))
}
}
/// Transforms a 2D vector.
#[inline]
#[must_use]
pub fn mul_vec2(&self, rhs: Vec2) -> Vec2 {
unsafe {
use crate::Align16;
use core::mem::MaybeUninit;
let abcd = self.0;
let xxyy = _mm_set_ps(rhs.y, rhs.y, rhs.x, rhs.x);
let axbxcydy = _mm_mul_ps(abcd, xxyy);
let cydyaxbx = _mm_shuffle_ps(axbxcydy, axbxcydy, 0b01_00_11_10);
let result = _mm_add_ps(axbxcydy, cydyaxbx);
let mut out: MaybeUninit<Align16<Vec2>> = MaybeUninit::uninit();
_mm_store_ps(out.as_mut_ptr().cast(), result);
out.assume_init().0
}
}
/// Multiplies two 2x2 matrices.
#[inline]
#[must_use]
pub fn mul_mat2(&self, rhs: &Self) -> Self {
unsafe {
let abcd = self.0;
let rhs = rhs.0;
let xxyy0 = _mm_shuffle_ps(rhs, rhs, 0b01_01_00_00);
let xxyy1 = _mm_shuffle_ps(rhs, rhs, 0b11_11_10_10);
let axbxcydy0 = _mm_mul_ps(abcd, xxyy0);
let axbxcydy1 = _mm_mul_ps(abcd, xxyy1);
let cydyaxbx0 = _mm_shuffle_ps(axbxcydy0, axbxcydy0, 0b01_00_11_10);
let cydyaxbx1 = _mm_shuffle_ps(axbxcydy1, axbxcydy1, 0b01_00_11_10);
let result0 = _mm_add_ps(axbxcydy0, cydyaxbx0);
let result1 = _mm_add_ps(axbxcydy1, cydyaxbx1);
Self(_mm_shuffle_ps(result0, result1, 0b01_00_01_00))
}
}
/// Adds two 2x2 matrices.
#[inline]
#[must_use]
pub fn add_mat2(&self, rhs: &Self) -> Self {
Self(unsafe { _mm_add_ps(self.0, rhs.0) })
}
/// Subtracts two 2x2 matrices.
#[inline]
#[must_use]
pub fn sub_mat2(&self, rhs: &Self) -> Self {
Self(unsafe { _mm_sub_ps(self.0, rhs.0) })
}
/// Multiplies a 2x2 matrix by a scalar.
#[inline]
#[must_use]
pub fn mul_scalar(&self, rhs: f32) -> Self {
Self(unsafe { _mm_mul_ps(self.0, _mm_set_ps1(rhs)) })
}
/// Divides a 2x2 matrix by a scalar.
#[inline]
#[must_use]
pub fn div_scalar(&self, rhs: f32) -> Self {
Self(unsafe { _mm_div_ps(self.0, _mm_set_ps1(rhs)) })
}
/// Returns true if the absolute difference of all elements between `self` and `rhs`
/// is less than or equal to `max_abs_diff`.
///
/// This can be used to compare if two matrices contain similar elements. It works best
/// when comparing with a known value. The `max_abs_diff` that should be used used
/// depends on the values being compared against.
///
/// For more see
/// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
#[inline]
#[must_use]
pub fn abs_diff_eq(&self, rhs: Self, max_abs_diff: f32) -> bool {
self.x_axis.abs_diff_eq(rhs.x_axis, max_abs_diff)
&& self.y_axis.abs_diff_eq(rhs.y_axis, max_abs_diff)
}
/// Takes the absolute value of each element in `self`
#[inline]
#[must_use]
pub fn abs(&self) -> Self {
Self::from_cols(self.x_axis.abs(), self.y_axis.abs())
}
#[inline]
pub fn as_dmat2(&self) -> DMat2 {
DMat2::from_cols(self.x_axis.as_dvec2(), self.y_axis.as_dvec2())
}
}
impl Default for Mat2 {
#[inline]
fn default() -> Self {
Self::IDENTITY
}
}
impl Add<Mat2> for Mat2 {
type Output = Self;
#[inline]
fn add(self, rhs: Self) -> Self::Output {
self.add_mat2(&rhs)
}
}
impl AddAssign<Mat2> for Mat2 {
#[inline]
fn add_assign(&mut self, rhs: Self) {
*self = self.add_mat2(&rhs);
}
}
impl Sub<Mat2> for Mat2 {
type Output = Self;
#[inline]
fn sub(self, rhs: Self) -> Self::Output {
self.sub_mat2(&rhs)
}
}
impl SubAssign<Mat2> for Mat2 {
#[inline]
fn sub_assign(&mut self, rhs: Self) {
*self = self.sub_mat2(&rhs);
}
}
impl Neg for Mat2 {
type Output = Self;
#[inline]
fn neg(self) -> Self::Output {
Self(unsafe { _mm_xor_ps(self.0, _mm_set1_ps(-0.0)) })
}
}
impl Mul<Mat2> for Mat2 {
type Output = Self;
#[inline]
fn mul(self, rhs: Self) -> Self::Output {
self.mul_mat2(&rhs)
}
}
impl MulAssign<Mat2> for Mat2 {
#[inline]
fn mul_assign(&mut self, rhs: Self) {
*self = self.mul_mat2(&rhs);
}
}
impl Mul<Vec2> for Mat2 {
type Output = Vec2;
#[inline]
fn mul(self, rhs: Vec2) -> Self::Output {
self.mul_vec2(rhs)
}
}
impl Mul<Mat2> for f32 {
type Output = Mat2;
#[inline]
fn mul(self, rhs: Mat2) -> Self::Output {
rhs.mul_scalar(self)
}
}
impl Mul<f32> for Mat2 {
type Output = Self;
#[inline]
fn mul(self, rhs: f32) -> Self::Output {
self.mul_scalar(rhs)
}
}
impl MulAssign<f32> for Mat2 {
#[inline]
fn mul_assign(&mut self, rhs: f32) {
*self = self.mul_scalar(rhs);
}
}
impl Div<Mat2> for f32 {
type Output = Mat2;
#[inline]
fn div(self, rhs: Mat2) -> Self::Output {
rhs.div_scalar(self)
}
}
impl Div<f32> for Mat2 {
type Output = Self;
#[inline]
fn div(self, rhs: f32) -> Self::Output {
self.div_scalar(rhs)
}
}
impl DivAssign<f32> for Mat2 {
#[inline]
fn div_assign(&mut self, rhs: f32) {
*self = self.div_scalar(rhs);
}
}
impl Sum<Self> for Mat2 {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Self::ZERO, Self::add)
}
}
impl<'a> Sum<&'a Self> for Mat2 {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
}
}
impl Product for Mat2 {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Self::IDENTITY, Self::mul)
}
}
impl<'a> Product<&'a Self> for Mat2 {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::IDENTITY, |a, &b| Self::mul(a, b))
}
}
impl PartialEq for Mat2 {
#[inline]
fn eq(&self, rhs: &Self) -> bool {
self.x_axis.eq(&rhs.x_axis) && self.y_axis.eq(&rhs.y_axis)
}
}
#[cfg(not(target_arch = "spirv"))]
impl AsRef<[f32; 4]> for Mat2 {
#[inline]
fn as_ref(&self) -> &[f32; 4] {
unsafe { &*(self as *const Self as *const [f32; 4]) }
}
}
#[cfg(not(target_arch = "spirv"))]
impl AsMut<[f32; 4]> for Mat2 {
#[inline]
fn as_mut(&mut self) -> &mut [f32; 4] {
unsafe { &mut *(self as *mut Self as *mut [f32; 4]) }
}
}
impl core::ops::Deref for Mat2 {
type Target = crate::deref::Cols2<Vec2>;
#[inline]
fn deref(&self) -> &Self::Target {
unsafe { &*(self as *const Self as *const Self::Target) }
}
}
impl core::ops::DerefMut for Mat2 {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { &mut *(self as *mut Self as *mut Self::Target) }
}
}
impl fmt::Debug for Mat2 {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct(stringify!(Mat2))
.field("x_axis", &self.x_axis)
.field("y_axis", &self.y_axis)
.finish()
}
}
impl fmt::Display for Mat2 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(p) = f.precision() {
write!(f, "[{:.*}, {:.*}]", p, self.x_axis, p, self.y_axis)
} else {
write!(f, "[{}, {}]", self.x_axis, self.y_axis)
}
}
}
+931
View File
@@ -0,0 +1,931 @@
// Generated from mat.rs.tera template. Edit the template, not the generated file.
use crate::{
euler::{FromEuler, ToEuler},
f32::math,
swizzles::*,
DMat3, EulerRot, Mat2, Mat3, Mat4, Quat, Vec2, Vec3, Vec3A,
};
use core::fmt;
use core::iter::{Product, Sum};
use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
#[cfg(target_arch = "x86")]
use core::arch::x86::*;
#[cfg(target_arch = "x86_64")]
use core::arch::x86_64::*;
/// Creates a 3x3 matrix from three column vectors.
#[inline(always)]
#[must_use]
pub const fn mat3a(x_axis: Vec3A, y_axis: Vec3A, z_axis: Vec3A) -> Mat3A {
Mat3A::from_cols(x_axis, y_axis, z_axis)
}
/// A 3x3 column major matrix.
///
/// This 3x3 matrix type features convenience methods for creating and using linear and
/// affine transformations. If you are primarily dealing with 2D affine transformations the
/// [`Affine2`](crate::Affine2) type is much faster and more space efficient than
/// using a 3x3 matrix.
///
/// Linear transformations including 3D rotation and scale can be created using methods
/// such as [`Self::from_diagonal()`], [`Self::from_quat()`], [`Self::from_axis_angle()`],
/// [`Self::from_rotation_x()`], [`Self::from_rotation_y()`], or
/// [`Self::from_rotation_z()`].
///
/// The resulting matrices can be use to transform 3D vectors using regular vector
/// multiplication.
///
/// Affine transformations including 2D translation, rotation and scale can be created
/// using methods such as [`Self::from_translation()`], [`Self::from_angle()`],
/// [`Self::from_scale()`] and [`Self::from_scale_angle_translation()`].
///
/// The [`Self::transform_point2()`] and [`Self::transform_vector2()`] convenience methods
/// are provided for performing affine transforms on 2D vectors and points. These multiply
/// 2D inputs as 3D vectors with an implicit `z` value of `1` for points and `0` for
/// vectors respectively. These methods assume that `Self` contains a valid affine
/// transform.
#[derive(Clone, Copy)]
#[repr(C)]
pub struct Mat3A {
pub x_axis: Vec3A,
pub y_axis: Vec3A,
pub z_axis: Vec3A,
}
impl Mat3A {
/// A 3x3 matrix with all elements set to `0.0`.
pub const ZERO: Self = Self::from_cols(Vec3A::ZERO, Vec3A::ZERO, Vec3A::ZERO);
/// A 3x3 identity matrix, where all diagonal elements are `1`, and all off-diagonal elements are `0`.
pub const IDENTITY: Self = Self::from_cols(Vec3A::X, Vec3A::Y, Vec3A::Z);
/// All NAN:s.
pub const NAN: Self = Self::from_cols(Vec3A::NAN, Vec3A::NAN, Vec3A::NAN);
#[allow(clippy::too_many_arguments)]
#[inline(always)]
#[must_use]
const fn new(
m00: f32,
m01: f32,
m02: f32,
m10: f32,
m11: f32,
m12: f32,
m20: f32,
m21: f32,
m22: f32,
) -> Self {
Self {
x_axis: Vec3A::new(m00, m01, m02),
y_axis: Vec3A::new(m10, m11, m12),
z_axis: Vec3A::new(m20, m21, m22),
}
}
/// Creates a 3x3 matrix from three column vectors.
#[inline(always)]
#[must_use]
pub const fn from_cols(x_axis: Vec3A, y_axis: Vec3A, z_axis: Vec3A) -> Self {
Self {
x_axis,
y_axis,
z_axis,
}
}
/// Creates a 3x3 matrix from a `[f32; 9]` array stored in column major order.
/// If your data is stored in row major you will need to `transpose` the returned
/// matrix.
#[inline]
#[must_use]
pub const fn from_cols_array(m: &[f32; 9]) -> Self {
Self::new(m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8])
}
/// Creates a `[f32; 9]` array storing data in column major order.
/// If you require data in row major order `transpose` the matrix first.
#[inline]
#[must_use]
pub const fn to_cols_array(&self) -> [f32; 9] {
let [x_axis_x, x_axis_y, x_axis_z] = self.x_axis.to_array();
let [y_axis_x, y_axis_y, y_axis_z] = self.y_axis.to_array();
let [z_axis_x, z_axis_y, z_axis_z] = self.z_axis.to_array();
[
x_axis_x, x_axis_y, x_axis_z, y_axis_x, y_axis_y, y_axis_z, z_axis_x, z_axis_y,
z_axis_z,
]
}
/// Creates a 3x3 matrix from a `[[f32; 3]; 3]` 3D array stored in column major order.
/// If your data is in row major order you will need to `transpose` the returned
/// matrix.
#[inline]
#[must_use]
pub const fn from_cols_array_2d(m: &[[f32; 3]; 3]) -> Self {
Self::from_cols(
Vec3A::from_array(m[0]),
Vec3A::from_array(m[1]),
Vec3A::from_array(m[2]),
)
}
/// Creates a `[[f32; 3]; 3]` 3D array storing data in column major order.
/// If you require data in row major order `transpose` the matrix first.
#[inline]
#[must_use]
pub const fn to_cols_array_2d(&self) -> [[f32; 3]; 3] {
[
self.x_axis.to_array(),
self.y_axis.to_array(),
self.z_axis.to_array(),
]
}
/// Creates a 3x3 matrix with its diagonal set to `diagonal` and all other entries set to 0.
#[doc(alias = "scale")]
#[inline]
#[must_use]
pub const fn from_diagonal(diagonal: Vec3) -> Self {
Self::new(
diagonal.x, 0.0, 0.0, 0.0, diagonal.y, 0.0, 0.0, 0.0, diagonal.z,
)
}
/// Creates a 3x3 matrix from a 4x4 matrix, discarding the 4th row and column.
#[inline]
#[must_use]
pub fn from_mat4(m: Mat4) -> Self {
Self::from_cols(
Vec3A::from_vec4(m.x_axis),
Vec3A::from_vec4(m.y_axis),
Vec3A::from_vec4(m.z_axis),
)
}
/// Creates a 3x3 matrix from the minor of the given 4x4 matrix, discarding the `i`th column
/// and `j`th row.
///
/// # Panics
///
/// Panics if `i` or `j` is greater than 3.
#[inline]
#[must_use]
pub fn from_mat4_minor(m: Mat4, i: usize, j: usize) -> Self {
match (i, j) {
(0, 0) => Self::from_cols(
Vec3A::from_vec4(m.y_axis.yzww()),
Vec3A::from_vec4(m.z_axis.yzww()),
Vec3A::from_vec4(m.w_axis.yzww()),
),
(0, 1) => Self::from_cols(
Vec3A::from_vec4(m.y_axis.xzww()),
Vec3A::from_vec4(m.z_axis.xzww()),
Vec3A::from_vec4(m.w_axis.xzww()),
),
(0, 2) => Self::from_cols(
Vec3A::from_vec4(m.y_axis.xyww()),
Vec3A::from_vec4(m.z_axis.xyww()),
Vec3A::from_vec4(m.w_axis.xyww()),
),
(0, 3) => Self::from_cols(
Vec3A::from_vec4(m.y_axis.xyzw()),
Vec3A::from_vec4(m.z_axis.xyzw()),
Vec3A::from_vec4(m.w_axis.xyzw()),
),
(1, 0) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.yzww()),
Vec3A::from_vec4(m.z_axis.yzww()),
Vec3A::from_vec4(m.w_axis.yzww()),
),
(1, 1) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xzww()),
Vec3A::from_vec4(m.z_axis.xzww()),
Vec3A::from_vec4(m.w_axis.xzww()),
),
(1, 2) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xyww()),
Vec3A::from_vec4(m.z_axis.xyww()),
Vec3A::from_vec4(m.w_axis.xyww()),
),
(1, 3) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xyzw()),
Vec3A::from_vec4(m.z_axis.xyzw()),
Vec3A::from_vec4(m.w_axis.xyzw()),
),
(2, 0) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.yzww()),
Vec3A::from_vec4(m.y_axis.yzww()),
Vec3A::from_vec4(m.w_axis.yzww()),
),
(2, 1) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xzww()),
Vec3A::from_vec4(m.y_axis.xzww()),
Vec3A::from_vec4(m.w_axis.xzww()),
),
(2, 2) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xyww()),
Vec3A::from_vec4(m.y_axis.xyww()),
Vec3A::from_vec4(m.w_axis.xyww()),
),
(2, 3) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xyzw()),
Vec3A::from_vec4(m.y_axis.xyzw()),
Vec3A::from_vec4(m.w_axis.xyzw()),
),
(3, 0) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.yzww()),
Vec3A::from_vec4(m.y_axis.yzww()),
Vec3A::from_vec4(m.z_axis.yzww()),
),
(3, 1) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xzww()),
Vec3A::from_vec4(m.y_axis.xzww()),
Vec3A::from_vec4(m.z_axis.xzww()),
),
(3, 2) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xyww()),
Vec3A::from_vec4(m.y_axis.xyww()),
Vec3A::from_vec4(m.z_axis.xyww()),
),
(3, 3) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xyzw()),
Vec3A::from_vec4(m.y_axis.xyzw()),
Vec3A::from_vec4(m.z_axis.xyzw()),
),
_ => panic!("index out of bounds"),
}
}
/// Creates a 3D rotation matrix from the given quaternion.
///
/// # Panics
///
/// Will panic if `rotation` is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn from_quat(rotation: Quat) -> Self {
glam_assert!(rotation.is_normalized());
let x2 = rotation.x + rotation.x;
let y2 = rotation.y + rotation.y;
let z2 = rotation.z + rotation.z;
let xx = rotation.x * x2;
let xy = rotation.x * y2;
let xz = rotation.x * z2;
let yy = rotation.y * y2;
let yz = rotation.y * z2;
let zz = rotation.z * z2;
let wx = rotation.w * x2;
let wy = rotation.w * y2;
let wz = rotation.w * z2;
Self::from_cols(
Vec3A::new(1.0 - (yy + zz), xy + wz, xz - wy),
Vec3A::new(xy - wz, 1.0 - (xx + zz), yz + wx),
Vec3A::new(xz + wy, yz - wx, 1.0 - (xx + yy)),
)
}
/// Creates a 3D rotation matrix from a normalized rotation `axis` and `angle` (in
/// radians).
///
/// # Panics
///
/// Will panic if `axis` is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn from_axis_angle(axis: Vec3, angle: f32) -> Self {
glam_assert!(axis.is_normalized());
let (sin, cos) = math::sin_cos(angle);
let (xsin, ysin, zsin) = axis.mul(sin).into();
let (x, y, z) = axis.into();
let (x2, y2, z2) = axis.mul(axis).into();
let omc = 1.0 - cos;
let xyomc = x * y * omc;
let xzomc = x * z * omc;
let yzomc = y * z * omc;
Self::from_cols(
Vec3A::new(x2 * omc + cos, xyomc + zsin, xzomc - ysin),
Vec3A::new(xyomc - zsin, y2 * omc + cos, yzomc + xsin),
Vec3A::new(xzomc + ysin, yzomc - xsin, z2 * omc + cos),
)
}
/// Creates a 3D rotation matrix from the given euler rotation sequence and the angles (in
/// radians).
#[inline]
#[must_use]
pub fn from_euler(order: EulerRot, a: f32, b: f32, c: f32) -> Self {
Self::from_euler_angles(order, a, b, c)
}
/// Extract Euler angles with the given Euler rotation order.
///
/// Note if the input matrix contains scales, shears, or other non-rotation transformations then
/// the resulting Euler angles will be ill-defined.
///
/// # Panics
///
/// Will panic if any input matrix column is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn to_euler(&self, order: EulerRot) -> (f32, f32, f32) {
glam_assert!(
self.x_axis.is_normalized()
&& self.y_axis.is_normalized()
&& self.z_axis.is_normalized()
);
self.to_euler_angles(order)
}
/// Creates a 3D rotation matrix from `angle` (in radians) around the x axis.
#[inline]
#[must_use]
pub fn from_rotation_x(angle: f32) -> Self {
let (sina, cosa) = math::sin_cos(angle);
Self::from_cols(
Vec3A::X,
Vec3A::new(0.0, cosa, sina),
Vec3A::new(0.0, -sina, cosa),
)
}
/// Creates a 3D rotation matrix from `angle` (in radians) around the y axis.
#[inline]
#[must_use]
pub fn from_rotation_y(angle: f32) -> Self {
let (sina, cosa) = math::sin_cos(angle);
Self::from_cols(
Vec3A::new(cosa, 0.0, -sina),
Vec3A::Y,
Vec3A::new(sina, 0.0, cosa),
)
}
/// Creates a 3D rotation matrix from `angle` (in radians) around the z axis.
#[inline]
#[must_use]
pub fn from_rotation_z(angle: f32) -> Self {
let (sina, cosa) = math::sin_cos(angle);
Self::from_cols(
Vec3A::new(cosa, sina, 0.0),
Vec3A::new(-sina, cosa, 0.0),
Vec3A::Z,
)
}
/// Creates an affine transformation matrix from the given 2D `translation`.
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
#[inline]
#[must_use]
pub fn from_translation(translation: Vec2) -> Self {
Self::from_cols(
Vec3A::X,
Vec3A::Y,
Vec3A::new(translation.x, translation.y, 1.0),
)
}
/// Creates an affine transformation matrix from the given 2D rotation `angle` (in
/// radians).
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
#[inline]
#[must_use]
pub fn from_angle(angle: f32) -> Self {
let (sin, cos) = math::sin_cos(angle);
Self::from_cols(
Vec3A::new(cos, sin, 0.0),
Vec3A::new(-sin, cos, 0.0),
Vec3A::Z,
)
}
/// Creates an affine transformation matrix from the given 2D `scale`, rotation `angle` (in
/// radians) and `translation`.
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
#[inline]
#[must_use]
pub fn from_scale_angle_translation(scale: Vec2, angle: f32, translation: Vec2) -> Self {
let (sin, cos) = math::sin_cos(angle);
Self::from_cols(
Vec3A::new(cos * scale.x, sin * scale.x, 0.0),
Vec3A::new(-sin * scale.y, cos * scale.y, 0.0),
Vec3A::new(translation.x, translation.y, 1.0),
)
}
/// Creates an affine transformation matrix from the given non-uniform 2D `scale`.
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
///
/// # Panics
///
/// Will panic if all elements of `scale` are zero when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn from_scale(scale: Vec2) -> Self {
// Do not panic as long as any component is non-zero
glam_assert!(scale.cmpne(Vec2::ZERO).any());
Self::from_cols(
Vec3A::new(scale.x, 0.0, 0.0),
Vec3A::new(0.0, scale.y, 0.0),
Vec3A::Z,
)
}
/// Creates an affine transformation matrix from the given 2x2 matrix.
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
#[inline]
pub fn from_mat2(m: Mat2) -> Self {
Self::from_cols((m.x_axis, 0.0).into(), (m.y_axis, 0.0).into(), Vec3A::Z)
}
/// Creates a 3x3 matrix from the first 9 values in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 9 elements long.
#[inline]
#[must_use]
pub const fn from_cols_slice(slice: &[f32]) -> Self {
Self::new(
slice[0], slice[1], slice[2], slice[3], slice[4], slice[5], slice[6], slice[7],
slice[8],
)
}
/// Writes the columns of `self` to the first 9 elements in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 9 elements long.
#[inline]
pub fn write_cols_to_slice(self, slice: &mut [f32]) {
slice[0] = self.x_axis.x;
slice[1] = self.x_axis.y;
slice[2] = self.x_axis.z;
slice[3] = self.y_axis.x;
slice[4] = self.y_axis.y;
slice[5] = self.y_axis.z;
slice[6] = self.z_axis.x;
slice[7] = self.z_axis.y;
slice[8] = self.z_axis.z;
}
/// Returns the matrix column for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 2.
#[inline]
#[must_use]
pub fn col(&self, index: usize) -> Vec3A {
match index {
0 => self.x_axis,
1 => self.y_axis,
2 => self.z_axis,
_ => panic!("index out of bounds"),
}
}
/// Returns a mutable reference to the matrix column for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 2.
#[inline]
pub fn col_mut(&mut self, index: usize) -> &mut Vec3A {
match index {
0 => &mut self.x_axis,
1 => &mut self.y_axis,
2 => &mut self.z_axis,
_ => panic!("index out of bounds"),
}
}
/// Returns the matrix row for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 2.
#[inline]
#[must_use]
pub fn row(&self, index: usize) -> Vec3A {
match index {
0 => Vec3A::new(self.x_axis.x, self.y_axis.x, self.z_axis.x),
1 => Vec3A::new(self.x_axis.y, self.y_axis.y, self.z_axis.y),
2 => Vec3A::new(self.x_axis.z, self.y_axis.z, self.z_axis.z),
_ => panic!("index out of bounds"),
}
}
/// Returns `true` if, and only if, all elements are finite.
/// If any element is either `NaN`, positive or negative infinity, this will return `false`.
#[inline]
#[must_use]
pub fn is_finite(&self) -> bool {
self.x_axis.is_finite() && self.y_axis.is_finite() && self.z_axis.is_finite()
}
/// Returns `true` if any elements are `NaN`.
#[inline]
#[must_use]
pub fn is_nan(&self) -> bool {
self.x_axis.is_nan() || self.y_axis.is_nan() || self.z_axis.is_nan()
}
/// Returns the transpose of `self`.
#[inline]
#[must_use]
pub fn transpose(&self) -> Self {
unsafe {
let tmp0 = _mm_shuffle_ps(self.x_axis.0, self.y_axis.0, 0b01_00_01_00);
let tmp1 = _mm_shuffle_ps(self.x_axis.0, self.y_axis.0, 0b11_10_11_10);
Self {
x_axis: Vec3A(_mm_shuffle_ps(tmp0, self.z_axis.0, 0b00_00_10_00)),
y_axis: Vec3A(_mm_shuffle_ps(tmp0, self.z_axis.0, 0b01_01_11_01)),
z_axis: Vec3A(_mm_shuffle_ps(tmp1, self.z_axis.0, 0b10_10_10_00)),
}
}
}
/// Returns the determinant of `self`.
#[inline]
#[must_use]
pub fn determinant(&self) -> f32 {
self.z_axis.dot(self.x_axis.cross(self.y_axis))
}
/// Returns the inverse of `self`.
///
/// If the matrix is not invertible the returned matrix will be invalid.
///
/// # Panics
///
/// Will panic if the determinant of `self` is zero when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn inverse(&self) -> Self {
let tmp0 = self.y_axis.cross(self.z_axis);
let tmp1 = self.z_axis.cross(self.x_axis);
let tmp2 = self.x_axis.cross(self.y_axis);
let det = self.z_axis.dot(tmp2);
glam_assert!(det != 0.0);
let inv_det = Vec3A::splat(det.recip());
Self::from_cols(tmp0.mul(inv_det), tmp1.mul(inv_det), tmp2.mul(inv_det)).transpose()
}
/// Transforms the given 2D vector as a point.
///
/// This is the equivalent of multiplying `rhs` as a 3D vector where `z` is `1`.
///
/// This method assumes that `self` contains a valid affine transform.
///
/// # Panics
///
/// Will panic if the 2nd row of `self` is not `(0, 0, 1)` when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn transform_point2(&self, rhs: Vec2) -> Vec2 {
glam_assert!(self.row(2).abs_diff_eq(Vec3A::Z, 1e-6));
Mat2::from_cols(self.x_axis.xy(), self.y_axis.xy()) * rhs + self.z_axis.xy()
}
/// Rotates the given 2D vector.
///
/// This is the equivalent of multiplying `rhs` as a 3D vector where `z` is `0`.
///
/// This method assumes that `self` contains a valid affine transform.
///
/// # Panics
///
/// Will panic if the 2nd row of `self` is not `(0, 0, 1)` when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn transform_vector2(&self, rhs: Vec2) -> Vec2 {
glam_assert!(self.row(2).abs_diff_eq(Vec3A::Z, 1e-6));
Mat2::from_cols(self.x_axis.xy(), self.y_axis.xy()) * rhs
}
/// Transforms a 3D vector.
#[inline]
#[must_use]
pub fn mul_vec3(&self, rhs: Vec3) -> Vec3 {
self.mul_vec3a(rhs.into()).into()
}
/// Transforms a [`Vec3A`].
#[inline]
#[must_use]
pub fn mul_vec3a(&self, rhs: Vec3A) -> Vec3A {
let mut res = self.x_axis.mul(rhs.xxx());
res = res.add(self.y_axis.mul(rhs.yyy()));
res = res.add(self.z_axis.mul(rhs.zzz()));
res
}
/// Multiplies two 3x3 matrices.
#[inline]
#[must_use]
pub fn mul_mat3(&self, rhs: &Self) -> Self {
Self::from_cols(
self.mul(rhs.x_axis),
self.mul(rhs.y_axis),
self.mul(rhs.z_axis),
)
}
/// Adds two 3x3 matrices.
#[inline]
#[must_use]
pub fn add_mat3(&self, rhs: &Self) -> Self {
Self::from_cols(
self.x_axis.add(rhs.x_axis),
self.y_axis.add(rhs.y_axis),
self.z_axis.add(rhs.z_axis),
)
}
/// Subtracts two 3x3 matrices.
#[inline]
#[must_use]
pub fn sub_mat3(&self, rhs: &Self) -> Self {
Self::from_cols(
self.x_axis.sub(rhs.x_axis),
self.y_axis.sub(rhs.y_axis),
self.z_axis.sub(rhs.z_axis),
)
}
/// Multiplies a 3x3 matrix by a scalar.
#[inline]
#[must_use]
pub fn mul_scalar(&self, rhs: f32) -> Self {
Self::from_cols(
self.x_axis.mul(rhs),
self.y_axis.mul(rhs),
self.z_axis.mul(rhs),
)
}
/// Divides a 3x3 matrix by a scalar.
#[inline]
#[must_use]
pub fn div_scalar(&self, rhs: f32) -> Self {
let rhs = Vec3A::splat(rhs);
Self::from_cols(
self.x_axis.div(rhs),
self.y_axis.div(rhs),
self.z_axis.div(rhs),
)
}
/// Returns true if the absolute difference of all elements between `self` and `rhs`
/// is less than or equal to `max_abs_diff`.
///
/// This can be used to compare if two matrices contain similar elements. It works best
/// when comparing with a known value. The `max_abs_diff` that should be used used
/// depends on the values being compared against.
///
/// For more see
/// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
#[inline]
#[must_use]
pub fn abs_diff_eq(&self, rhs: Self, max_abs_diff: f32) -> bool {
self.x_axis.abs_diff_eq(rhs.x_axis, max_abs_diff)
&& self.y_axis.abs_diff_eq(rhs.y_axis, max_abs_diff)
&& self.z_axis.abs_diff_eq(rhs.z_axis, max_abs_diff)
}
/// Takes the absolute value of each element in `self`
#[inline]
#[must_use]
pub fn abs(&self) -> Self {
Self::from_cols(self.x_axis.abs(), self.y_axis.abs(), self.z_axis.abs())
}
#[inline]
pub fn as_dmat3(&self) -> DMat3 {
DMat3::from_cols(
self.x_axis.as_dvec3(),
self.y_axis.as_dvec3(),
self.z_axis.as_dvec3(),
)
}
}
impl Default for Mat3A {
#[inline]
fn default() -> Self {
Self::IDENTITY
}
}
impl Add<Mat3A> for Mat3A {
type Output = Self;
#[inline]
fn add(self, rhs: Self) -> Self::Output {
self.add_mat3(&rhs)
}
}
impl AddAssign<Mat3A> for Mat3A {
#[inline]
fn add_assign(&mut self, rhs: Self) {
*self = self.add_mat3(&rhs);
}
}
impl Sub<Mat3A> for Mat3A {
type Output = Self;
#[inline]
fn sub(self, rhs: Self) -> Self::Output {
self.sub_mat3(&rhs)
}
}
impl SubAssign<Mat3A> for Mat3A {
#[inline]
fn sub_assign(&mut self, rhs: Self) {
*self = self.sub_mat3(&rhs);
}
}
impl Neg for Mat3A {
type Output = Self;
#[inline]
fn neg(self) -> Self::Output {
Self::from_cols(self.x_axis.neg(), self.y_axis.neg(), self.z_axis.neg())
}
}
impl Mul<Mat3A> for Mat3A {
type Output = Self;
#[inline]
fn mul(self, rhs: Self) -> Self::Output {
self.mul_mat3(&rhs)
}
}
impl MulAssign<Mat3A> for Mat3A {
#[inline]
fn mul_assign(&mut self, rhs: Self) {
*self = self.mul_mat3(&rhs);
}
}
impl Mul<Vec3A> for Mat3A {
type Output = Vec3A;
#[inline]
fn mul(self, rhs: Vec3A) -> Self::Output {
self.mul_vec3a(rhs)
}
}
impl Mul<Mat3A> for f32 {
type Output = Mat3A;
#[inline]
fn mul(self, rhs: Mat3A) -> Self::Output {
rhs.mul_scalar(self)
}
}
impl Mul<f32> for Mat3A {
type Output = Self;
#[inline]
fn mul(self, rhs: f32) -> Self::Output {
self.mul_scalar(rhs)
}
}
impl MulAssign<f32> for Mat3A {
#[inline]
fn mul_assign(&mut self, rhs: f32) {
*self = self.mul_scalar(rhs);
}
}
impl Div<Mat3A> for f32 {
type Output = Mat3A;
#[inline]
fn div(self, rhs: Mat3A) -> Self::Output {
rhs.div_scalar(self)
}
}
impl Div<f32> for Mat3A {
type Output = Self;
#[inline]
fn div(self, rhs: f32) -> Self::Output {
self.div_scalar(rhs)
}
}
impl DivAssign<f32> for Mat3A {
#[inline]
fn div_assign(&mut self, rhs: f32) {
*self = self.div_scalar(rhs);
}
}
impl Mul<Vec3> for Mat3A {
type Output = Vec3;
#[inline]
fn mul(self, rhs: Vec3) -> Vec3 {
self.mul_vec3a(rhs.into()).into()
}
}
impl From<Mat3> for Mat3A {
#[inline]
fn from(m: Mat3) -> Self {
Self {
x_axis: m.x_axis.into(),
y_axis: m.y_axis.into(),
z_axis: m.z_axis.into(),
}
}
}
impl Sum<Self> for Mat3A {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Self::ZERO, Self::add)
}
}
impl<'a> Sum<&'a Self> for Mat3A {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
}
}
impl Product for Mat3A {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Self::IDENTITY, Self::mul)
}
}
impl<'a> Product<&'a Self> for Mat3A {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::IDENTITY, |a, &b| Self::mul(a, b))
}
}
impl PartialEq for Mat3A {
#[inline]
fn eq(&self, rhs: &Self) -> bool {
self.x_axis.eq(&rhs.x_axis) && self.y_axis.eq(&rhs.y_axis) && self.z_axis.eq(&rhs.z_axis)
}
}
impl fmt::Debug for Mat3A {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct(stringify!(Mat3A))
.field("x_axis", &self.x_axis)
.field("y_axis", &self.y_axis)
.field("z_axis", &self.z_axis)
.finish()
}
}
impl fmt::Display for Mat3A {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(p) = f.precision() {
write!(
f,
"[{:.*}, {:.*}, {:.*}]",
p, self.x_axis, p, self.y_axis, p, self.z_axis
)
} else {
write!(f, "[{}, {}, {}]", self.x_axis, self.y_axis, self.z_axis)
}
}
}
+1545
View File
File diff suppressed because it is too large Load Diff
+1043
View File
File diff suppressed because it is too large Load Diff
+1925
View File
File diff suppressed because it is too large Load Diff
+1876
View File
File diff suppressed because it is too large Load Diff
+1835
View File
File diff suppressed because it is too large Load Diff
+1923
View File
File diff suppressed because it is too large Load Diff
+6
View File
@@ -0,0 +1,6 @@
pub mod mat2;
pub mod mat3a;
pub mod mat4;
pub mod quat;
pub mod vec3a;
pub mod vec4;
+588
View File
@@ -0,0 +1,588 @@
// Generated from mat.rs.tera template. Edit the template, not the generated file.
use crate::{f32::math, swizzles::*, DMat2, Mat3, Mat3A, Vec2};
use core::fmt;
use core::iter::{Product, Sum};
use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
use core::arch::wasm32::*;
/// Creates a 2x2 matrix from two column vectors.
#[inline(always)]
#[must_use]
pub const fn mat2(x_axis: Vec2, y_axis: Vec2) -> Mat2 {
Mat2::from_cols(x_axis, y_axis)
}
/// A 2x2 column major matrix.
///
/// SIMD vector types are used for storage on supported platforms.
///
/// This type is 16 byte aligned.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct Mat2(pub(crate) v128);
impl Mat2 {
/// A 2x2 matrix with all elements set to `0.0`.
pub const ZERO: Self = Self::from_cols(Vec2::ZERO, Vec2::ZERO);
/// A 2x2 identity matrix, where all diagonal elements are `1`, and all off-diagonal elements are `0`.
pub const IDENTITY: Self = Self::from_cols(Vec2::X, Vec2::Y);
/// All NAN:s.
pub const NAN: Self = Self::from_cols(Vec2::NAN, Vec2::NAN);
#[allow(clippy::too_many_arguments)]
#[inline(always)]
#[must_use]
const fn new(m00: f32, m01: f32, m10: f32, m11: f32) -> Self {
Self(f32x4(m00, m01, m10, m11))
}
/// Creates a 2x2 matrix from two column vectors.
#[inline(always)]
#[must_use]
pub const fn from_cols(x_axis: Vec2, y_axis: Vec2) -> Self {
Self(f32x4(x_axis.x, x_axis.y, y_axis.x, y_axis.y))
}
/// Creates a 2x2 matrix from a `[f32; 4]` array stored in column major order.
/// If your data is stored in row major you will need to `transpose` the returned
/// matrix.
#[inline]
#[must_use]
pub const fn from_cols_array(m: &[f32; 4]) -> Self {
Self::new(m[0], m[1], m[2], m[3])
}
/// Creates a `[f32; 4]` array storing data in column major order.
/// If you require data in row major order `transpose` the matrix first.
#[inline]
#[must_use]
pub const fn to_cols_array(&self) -> [f32; 4] {
unsafe { *(self as *const Self as *const [f32; 4]) }
}
/// Creates a 2x2 matrix from a `[[f32; 2]; 2]` 2D array stored in column major order.
/// If your data is in row major order you will need to `transpose` the returned
/// matrix.
#[inline]
#[must_use]
pub const fn from_cols_array_2d(m: &[[f32; 2]; 2]) -> Self {
Self::from_cols(Vec2::from_array(m[0]), Vec2::from_array(m[1]))
}
/// Creates a `[[f32; 2]; 2]` 2D array storing data in column major order.
/// If you require data in row major order `transpose` the matrix first.
#[inline]
#[must_use]
pub const fn to_cols_array_2d(&self) -> [[f32; 2]; 2] {
unsafe { *(self as *const Self as *const [[f32; 2]; 2]) }
}
/// Creates a 2x2 matrix with its diagonal set to `diagonal` and all other entries set to 0.
#[doc(alias = "scale")]
#[inline]
#[must_use]
pub const fn from_diagonal(diagonal: Vec2) -> Self {
Self::new(diagonal.x, 0.0, 0.0, diagonal.y)
}
/// Creates a 2x2 matrix containing the combining non-uniform `scale` and rotation of
/// `angle` (in radians).
#[inline]
#[must_use]
pub fn from_scale_angle(scale: Vec2, angle: f32) -> Self {
let (sin, cos) = math::sin_cos(angle);
Self::new(cos * scale.x, sin * scale.x, -sin * scale.y, cos * scale.y)
}
/// Creates a 2x2 matrix containing a rotation of `angle` (in radians).
#[inline]
#[must_use]
pub fn from_angle(angle: f32) -> Self {
let (sin, cos) = math::sin_cos(angle);
Self::new(cos, sin, -sin, cos)
}
/// Creates a 2x2 matrix from a 3x3 matrix, discarding the 2nd row and column.
#[inline]
#[must_use]
pub fn from_mat3(m: Mat3) -> Self {
Self::from_cols(m.x_axis.xy(), m.y_axis.xy())
}
/// Creates a 2x2 matrix from the minor of the given 3x3 matrix, discarding the `i`th column
/// and `j`th row.
///
/// # Panics
///
/// Panics if `i` or `j` is greater than 2.
#[inline]
#[must_use]
pub fn from_mat3_minor(m: Mat3, i: usize, j: usize) -> Self {
match (i, j) {
(0, 0) => Self::from_cols(m.y_axis.yz(), m.z_axis.yz()),
(0, 1) => Self::from_cols(m.y_axis.xz(), m.z_axis.xz()),
(0, 2) => Self::from_cols(m.y_axis.xy(), m.z_axis.xy()),
(1, 0) => Self::from_cols(m.x_axis.yz(), m.z_axis.yz()),
(1, 1) => Self::from_cols(m.x_axis.xz(), m.z_axis.xz()),
(1, 2) => Self::from_cols(m.x_axis.xy(), m.z_axis.xy()),
(2, 0) => Self::from_cols(m.x_axis.yz(), m.y_axis.yz()),
(2, 1) => Self::from_cols(m.x_axis.xz(), m.y_axis.xz()),
(2, 2) => Self::from_cols(m.x_axis.xy(), m.y_axis.xy()),
_ => panic!("index out of bounds"),
}
}
/// Creates a 2x2 matrix from a 3x3 matrix, discarding the 2nd row and column.
#[inline]
#[must_use]
pub fn from_mat3a(m: Mat3A) -> Self {
Self::from_cols(m.x_axis.xy(), m.y_axis.xy())
}
/// Creates a 2x2 matrix from the minor of the given 3x3 matrix, discarding the `i`th column
/// and `j`th row.
///
/// # Panics
///
/// Panics if `i` or `j` is greater than 2.
#[inline]
#[must_use]
pub fn from_mat3a_minor(m: Mat3A, i: usize, j: usize) -> Self {
match (i, j) {
(0, 0) => Self::from_cols(m.y_axis.yz(), m.z_axis.yz()),
(0, 1) => Self::from_cols(m.y_axis.xz(), m.z_axis.xz()),
(0, 2) => Self::from_cols(m.y_axis.xy(), m.z_axis.xy()),
(1, 0) => Self::from_cols(m.x_axis.yz(), m.z_axis.yz()),
(1, 1) => Self::from_cols(m.x_axis.xz(), m.z_axis.xz()),
(1, 2) => Self::from_cols(m.x_axis.xy(), m.z_axis.xy()),
(2, 0) => Self::from_cols(m.x_axis.yz(), m.y_axis.yz()),
(2, 1) => Self::from_cols(m.x_axis.xz(), m.y_axis.xz()),
(2, 2) => Self::from_cols(m.x_axis.xy(), m.y_axis.xy()),
_ => panic!("index out of bounds"),
}
}
/// Creates a 2x2 matrix from the first 4 values in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 4 elements long.
#[inline]
#[must_use]
pub const fn from_cols_slice(slice: &[f32]) -> Self {
Self::new(slice[0], slice[1], slice[2], slice[3])
}
/// Writes the columns of `self` to the first 4 elements in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 4 elements long.
#[inline]
pub fn write_cols_to_slice(self, slice: &mut [f32]) {
slice[0] = self.x_axis.x;
slice[1] = self.x_axis.y;
slice[2] = self.y_axis.x;
slice[3] = self.y_axis.y;
}
/// Returns the matrix column for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 1.
#[inline]
#[must_use]
pub fn col(&self, index: usize) -> Vec2 {
match index {
0 => self.x_axis,
1 => self.y_axis,
_ => panic!("index out of bounds"),
}
}
/// Returns a mutable reference to the matrix column for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 1.
#[inline]
pub fn col_mut(&mut self, index: usize) -> &mut Vec2 {
match index {
0 => &mut self.x_axis,
1 => &mut self.y_axis,
_ => panic!("index out of bounds"),
}
}
/// Returns the matrix row for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 1.
#[inline]
#[must_use]
pub fn row(&self, index: usize) -> Vec2 {
match index {
0 => Vec2::new(self.x_axis.x, self.y_axis.x),
1 => Vec2::new(self.x_axis.y, self.y_axis.y),
_ => panic!("index out of bounds"),
}
}
/// Returns `true` if, and only if, all elements are finite.
/// If any element is either `NaN`, positive or negative infinity, this will return `false`.
#[inline]
#[must_use]
pub fn is_finite(&self) -> bool {
self.x_axis.is_finite() && self.y_axis.is_finite()
}
/// Returns `true` if any elements are `NaN`.
#[inline]
#[must_use]
pub fn is_nan(&self) -> bool {
self.x_axis.is_nan() || self.y_axis.is_nan()
}
/// Returns the transpose of `self`.
#[inline]
#[must_use]
pub fn transpose(&self) -> Self {
Self(i32x4_shuffle::<0, 2, 5, 7>(self.0, self.0))
}
/// Returns the determinant of `self`.
#[inline]
#[must_use]
pub fn determinant(&self) -> f32 {
let abcd = self.0;
let dcba = i32x4_shuffle::<3, 2, 5, 4>(abcd, abcd);
let prod = f32x4_mul(abcd, dcba);
let det = f32x4_sub(prod, i32x4_shuffle::<1, 1, 5, 5>(prod, prod));
f32x4_extract_lane::<0>(det)
}
/// Returns the inverse of `self`.
///
/// If the matrix is not invertible the returned matrix will be invalid.
///
/// # Panics
///
/// Will panic if the determinant of `self` is zero when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn inverse(&self) -> Self {
const SIGN: v128 = crate::wasm32::v128_from_f32x4([1.0, -1.0, -1.0, 1.0]);
let abcd = self.0;
let dcba = i32x4_shuffle::<3, 2, 5, 4>(abcd, abcd);
let prod = f32x4_mul(abcd, dcba);
let sub = f32x4_sub(prod, i32x4_shuffle::<1, 1, 5, 5>(prod, prod));
let det = i32x4_shuffle::<0, 0, 4, 4>(sub, sub);
let tmp = f32x4_div(SIGN, det);
glam_assert!(Mat2(tmp).is_finite());
let dbca = i32x4_shuffle::<3, 1, 6, 4>(abcd, abcd);
Self(f32x4_mul(dbca, tmp))
}
/// Transforms a 2D vector.
#[inline]
#[must_use]
pub fn mul_vec2(&self, rhs: Vec2) -> Vec2 {
use core::mem::MaybeUninit;
let abcd = self.0;
let xxyy = f32x4(rhs.x, rhs.x, rhs.y, rhs.y);
let axbxcydy = f32x4_mul(abcd, xxyy);
let cydyaxbx = i32x4_shuffle::<2, 3, 4, 5>(axbxcydy, axbxcydy);
let result = f32x4_add(axbxcydy, cydyaxbx);
let mut out: MaybeUninit<v128> = MaybeUninit::uninit();
unsafe {
v128_store(out.as_mut_ptr(), result);
*(&out.assume_init() as *const v128 as *const Vec2)
}
}
/// Multiplies two 2x2 matrices.
#[inline]
#[must_use]
pub fn mul_mat2(&self, rhs: &Self) -> Self {
let abcd = self.0;
let rhs = rhs.0;
let xxyy0 = i32x4_shuffle::<0, 0, 5, 5>(rhs, rhs);
let xxyy1 = i32x4_shuffle::<2, 2, 7, 7>(rhs, rhs);
let axbxcydy0 = f32x4_mul(abcd, xxyy0);
let axbxcydy1 = f32x4_mul(abcd, xxyy1);
let cydyaxbx0 = i32x4_shuffle::<2, 3, 4, 5>(axbxcydy0, axbxcydy0);
let cydyaxbx1 = i32x4_shuffle::<2, 3, 4, 5>(axbxcydy1, axbxcydy1);
let result0 = f32x4_add(axbxcydy0, cydyaxbx0);
let result1 = f32x4_add(axbxcydy1, cydyaxbx1);
Self(i32x4_shuffle::<0, 1, 4, 5>(result0, result1))
}
/// Adds two 2x2 matrices.
#[inline]
#[must_use]
pub fn add_mat2(&self, rhs: &Self) -> Self {
Self(f32x4_add(self.0, rhs.0))
}
/// Subtracts two 2x2 matrices.
#[inline]
#[must_use]
pub fn sub_mat2(&self, rhs: &Self) -> Self {
Self(f32x4_sub(self.0, rhs.0))
}
/// Multiplies a 2x2 matrix by a scalar.
#[inline]
#[must_use]
pub fn mul_scalar(&self, rhs: f32) -> Self {
Self(f32x4_mul(self.0, f32x4_splat(rhs)))
}
/// Divides a 2x2 matrix by a scalar.
#[inline]
#[must_use]
pub fn div_scalar(&self, rhs: f32) -> Self {
Self(f32x4_div(self.0, f32x4_splat(rhs)))
}
/// Returns true if the absolute difference of all elements between `self` and `rhs`
/// is less than or equal to `max_abs_diff`.
///
/// This can be used to compare if two matrices contain similar elements. It works best
/// when comparing with a known value. The `max_abs_diff` that should be used used
/// depends on the values being compared against.
///
/// For more see
/// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
#[inline]
#[must_use]
pub fn abs_diff_eq(&self, rhs: Self, max_abs_diff: f32) -> bool {
self.x_axis.abs_diff_eq(rhs.x_axis, max_abs_diff)
&& self.y_axis.abs_diff_eq(rhs.y_axis, max_abs_diff)
}
/// Takes the absolute value of each element in `self`
#[inline]
#[must_use]
pub fn abs(&self) -> Self {
Self::from_cols(self.x_axis.abs(), self.y_axis.abs())
}
#[inline]
pub fn as_dmat2(&self) -> DMat2 {
DMat2::from_cols(self.x_axis.as_dvec2(), self.y_axis.as_dvec2())
}
}
impl Default for Mat2 {
#[inline]
fn default() -> Self {
Self::IDENTITY
}
}
impl Add<Mat2> for Mat2 {
type Output = Self;
#[inline]
fn add(self, rhs: Self) -> Self::Output {
self.add_mat2(&rhs)
}
}
impl AddAssign<Mat2> for Mat2 {
#[inline]
fn add_assign(&mut self, rhs: Self) {
*self = self.add_mat2(&rhs);
}
}
impl Sub<Mat2> for Mat2 {
type Output = Self;
#[inline]
fn sub(self, rhs: Self) -> Self::Output {
self.sub_mat2(&rhs)
}
}
impl SubAssign<Mat2> for Mat2 {
#[inline]
fn sub_assign(&mut self, rhs: Self) {
*self = self.sub_mat2(&rhs);
}
}
impl Neg for Mat2 {
type Output = Self;
#[inline]
fn neg(self) -> Self::Output {
Self(f32x4_neg(self.0))
}
}
impl Mul<Mat2> for Mat2 {
type Output = Self;
#[inline]
fn mul(self, rhs: Self) -> Self::Output {
self.mul_mat2(&rhs)
}
}
impl MulAssign<Mat2> for Mat2 {
#[inline]
fn mul_assign(&mut self, rhs: Self) {
*self = self.mul_mat2(&rhs);
}
}
impl Mul<Vec2> for Mat2 {
type Output = Vec2;
#[inline]
fn mul(self, rhs: Vec2) -> Self::Output {
self.mul_vec2(rhs)
}
}
impl Mul<Mat2> for f32 {
type Output = Mat2;
#[inline]
fn mul(self, rhs: Mat2) -> Self::Output {
rhs.mul_scalar(self)
}
}
impl Mul<f32> for Mat2 {
type Output = Self;
#[inline]
fn mul(self, rhs: f32) -> Self::Output {
self.mul_scalar(rhs)
}
}
impl MulAssign<f32> for Mat2 {
#[inline]
fn mul_assign(&mut self, rhs: f32) {
*self = self.mul_scalar(rhs);
}
}
impl Div<Mat2> for f32 {
type Output = Mat2;
#[inline]
fn div(self, rhs: Mat2) -> Self::Output {
rhs.div_scalar(self)
}
}
impl Div<f32> for Mat2 {
type Output = Self;
#[inline]
fn div(self, rhs: f32) -> Self::Output {
self.div_scalar(rhs)
}
}
impl DivAssign<f32> for Mat2 {
#[inline]
fn div_assign(&mut self, rhs: f32) {
*self = self.div_scalar(rhs);
}
}
impl Sum<Self> for Mat2 {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Self::ZERO, Self::add)
}
}
impl<'a> Sum<&'a Self> for Mat2 {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
}
}
impl Product for Mat2 {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Self::IDENTITY, Self::mul)
}
}
impl<'a> Product<&'a Self> for Mat2 {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::IDENTITY, |a, &b| Self::mul(a, b))
}
}
impl PartialEq for Mat2 {
#[inline]
fn eq(&self, rhs: &Self) -> bool {
self.x_axis.eq(&rhs.x_axis) && self.y_axis.eq(&rhs.y_axis)
}
}
#[cfg(not(target_arch = "spirv"))]
impl AsRef<[f32; 4]> for Mat2 {
#[inline]
fn as_ref(&self) -> &[f32; 4] {
unsafe { &*(self as *const Self as *const [f32; 4]) }
}
}
#[cfg(not(target_arch = "spirv"))]
impl AsMut<[f32; 4]> for Mat2 {
#[inline]
fn as_mut(&mut self) -> &mut [f32; 4] {
unsafe { &mut *(self as *mut Self as *mut [f32; 4]) }
}
}
impl core::ops::Deref for Mat2 {
type Target = crate::deref::Cols2<Vec2>;
#[inline]
fn deref(&self) -> &Self::Target {
unsafe { &*(self as *const Self as *const Self::Target) }
}
}
impl core::ops::DerefMut for Mat2 {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { &mut *(self as *mut Self as *mut Self::Target) }
}
}
impl fmt::Debug for Mat2 {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct(stringify!(Mat2))
.field("x_axis", &self.x_axis)
.field("y_axis", &self.y_axis)
.finish()
}
}
impl fmt::Display for Mat2 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(p) = f.precision() {
write!(f, "[{:.*}, {:.*}]", p, self.x_axis, p, self.y_axis)
} else {
write!(f, "[{}, {}]", self.x_axis, self.y_axis)
}
}
}
+926
View File
@@ -0,0 +1,926 @@
// Generated from mat.rs.tera template. Edit the template, not the generated file.
use crate::{
euler::{FromEuler, ToEuler},
f32::math,
swizzles::*,
DMat3, EulerRot, Mat2, Mat3, Mat4, Quat, Vec2, Vec3, Vec3A,
};
use core::fmt;
use core::iter::{Product, Sum};
use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
use core::arch::wasm32::*;
/// Creates a 3x3 matrix from three column vectors.
#[inline(always)]
#[must_use]
pub const fn mat3a(x_axis: Vec3A, y_axis: Vec3A, z_axis: Vec3A) -> Mat3A {
Mat3A::from_cols(x_axis, y_axis, z_axis)
}
/// A 3x3 column major matrix.
///
/// This 3x3 matrix type features convenience methods for creating and using linear and
/// affine transformations. If you are primarily dealing with 2D affine transformations the
/// [`Affine2`](crate::Affine2) type is much faster and more space efficient than
/// using a 3x3 matrix.
///
/// Linear transformations including 3D rotation and scale can be created using methods
/// such as [`Self::from_diagonal()`], [`Self::from_quat()`], [`Self::from_axis_angle()`],
/// [`Self::from_rotation_x()`], [`Self::from_rotation_y()`], or
/// [`Self::from_rotation_z()`].
///
/// The resulting matrices can be use to transform 3D vectors using regular vector
/// multiplication.
///
/// Affine transformations including 2D translation, rotation and scale can be created
/// using methods such as [`Self::from_translation()`], [`Self::from_angle()`],
/// [`Self::from_scale()`] and [`Self::from_scale_angle_translation()`].
///
/// The [`Self::transform_point2()`] and [`Self::transform_vector2()`] convenience methods
/// are provided for performing affine transforms on 2D vectors and points. These multiply
/// 2D inputs as 3D vectors with an implicit `z` value of `1` for points and `0` for
/// vectors respectively. These methods assume that `Self` contains a valid affine
/// transform.
#[derive(Clone, Copy)]
#[repr(C)]
pub struct Mat3A {
pub x_axis: Vec3A,
pub y_axis: Vec3A,
pub z_axis: Vec3A,
}
impl Mat3A {
/// A 3x3 matrix with all elements set to `0.0`.
pub const ZERO: Self = Self::from_cols(Vec3A::ZERO, Vec3A::ZERO, Vec3A::ZERO);
/// A 3x3 identity matrix, where all diagonal elements are `1`, and all off-diagonal elements are `0`.
pub const IDENTITY: Self = Self::from_cols(Vec3A::X, Vec3A::Y, Vec3A::Z);
/// All NAN:s.
pub const NAN: Self = Self::from_cols(Vec3A::NAN, Vec3A::NAN, Vec3A::NAN);
#[allow(clippy::too_many_arguments)]
#[inline(always)]
#[must_use]
const fn new(
m00: f32,
m01: f32,
m02: f32,
m10: f32,
m11: f32,
m12: f32,
m20: f32,
m21: f32,
m22: f32,
) -> Self {
Self {
x_axis: Vec3A::new(m00, m01, m02),
y_axis: Vec3A::new(m10, m11, m12),
z_axis: Vec3A::new(m20, m21, m22),
}
}
/// Creates a 3x3 matrix from three column vectors.
#[inline(always)]
#[must_use]
pub const fn from_cols(x_axis: Vec3A, y_axis: Vec3A, z_axis: Vec3A) -> Self {
Self {
x_axis,
y_axis,
z_axis,
}
}
/// Creates a 3x3 matrix from a `[f32; 9]` array stored in column major order.
/// If your data is stored in row major you will need to `transpose` the returned
/// matrix.
#[inline]
#[must_use]
pub const fn from_cols_array(m: &[f32; 9]) -> Self {
Self::new(m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8])
}
/// Creates a `[f32; 9]` array storing data in column major order.
/// If you require data in row major order `transpose` the matrix first.
#[inline]
#[must_use]
pub const fn to_cols_array(&self) -> [f32; 9] {
let [x_axis_x, x_axis_y, x_axis_z] = self.x_axis.to_array();
let [y_axis_x, y_axis_y, y_axis_z] = self.y_axis.to_array();
let [z_axis_x, z_axis_y, z_axis_z] = self.z_axis.to_array();
[
x_axis_x, x_axis_y, x_axis_z, y_axis_x, y_axis_y, y_axis_z, z_axis_x, z_axis_y,
z_axis_z,
]
}
/// Creates a 3x3 matrix from a `[[f32; 3]; 3]` 3D array stored in column major order.
/// If your data is in row major order you will need to `transpose` the returned
/// matrix.
#[inline]
#[must_use]
pub const fn from_cols_array_2d(m: &[[f32; 3]; 3]) -> Self {
Self::from_cols(
Vec3A::from_array(m[0]),
Vec3A::from_array(m[1]),
Vec3A::from_array(m[2]),
)
}
/// Creates a `[[f32; 3]; 3]` 3D array storing data in column major order.
/// If you require data in row major order `transpose` the matrix first.
#[inline]
#[must_use]
pub const fn to_cols_array_2d(&self) -> [[f32; 3]; 3] {
[
self.x_axis.to_array(),
self.y_axis.to_array(),
self.z_axis.to_array(),
]
}
/// Creates a 3x3 matrix with its diagonal set to `diagonal` and all other entries set to 0.
#[doc(alias = "scale")]
#[inline]
#[must_use]
pub const fn from_diagonal(diagonal: Vec3) -> Self {
Self::new(
diagonal.x, 0.0, 0.0, 0.0, diagonal.y, 0.0, 0.0, 0.0, diagonal.z,
)
}
/// Creates a 3x3 matrix from a 4x4 matrix, discarding the 4th row and column.
#[inline]
#[must_use]
pub fn from_mat4(m: Mat4) -> Self {
Self::from_cols(
Vec3A::from_vec4(m.x_axis),
Vec3A::from_vec4(m.y_axis),
Vec3A::from_vec4(m.z_axis),
)
}
/// Creates a 3x3 matrix from the minor of the given 4x4 matrix, discarding the `i`th column
/// and `j`th row.
///
/// # Panics
///
/// Panics if `i` or `j` is greater than 3.
#[inline]
#[must_use]
pub fn from_mat4_minor(m: Mat4, i: usize, j: usize) -> Self {
match (i, j) {
(0, 0) => Self::from_cols(
Vec3A::from_vec4(m.y_axis.yzww()),
Vec3A::from_vec4(m.z_axis.yzww()),
Vec3A::from_vec4(m.w_axis.yzww()),
),
(0, 1) => Self::from_cols(
Vec3A::from_vec4(m.y_axis.xzww()),
Vec3A::from_vec4(m.z_axis.xzww()),
Vec3A::from_vec4(m.w_axis.xzww()),
),
(0, 2) => Self::from_cols(
Vec3A::from_vec4(m.y_axis.xyww()),
Vec3A::from_vec4(m.z_axis.xyww()),
Vec3A::from_vec4(m.w_axis.xyww()),
),
(0, 3) => Self::from_cols(
Vec3A::from_vec4(m.y_axis.xyzw()),
Vec3A::from_vec4(m.z_axis.xyzw()),
Vec3A::from_vec4(m.w_axis.xyzw()),
),
(1, 0) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.yzww()),
Vec3A::from_vec4(m.z_axis.yzww()),
Vec3A::from_vec4(m.w_axis.yzww()),
),
(1, 1) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xzww()),
Vec3A::from_vec4(m.z_axis.xzww()),
Vec3A::from_vec4(m.w_axis.xzww()),
),
(1, 2) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xyww()),
Vec3A::from_vec4(m.z_axis.xyww()),
Vec3A::from_vec4(m.w_axis.xyww()),
),
(1, 3) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xyzw()),
Vec3A::from_vec4(m.z_axis.xyzw()),
Vec3A::from_vec4(m.w_axis.xyzw()),
),
(2, 0) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.yzww()),
Vec3A::from_vec4(m.y_axis.yzww()),
Vec3A::from_vec4(m.w_axis.yzww()),
),
(2, 1) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xzww()),
Vec3A::from_vec4(m.y_axis.xzww()),
Vec3A::from_vec4(m.w_axis.xzww()),
),
(2, 2) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xyww()),
Vec3A::from_vec4(m.y_axis.xyww()),
Vec3A::from_vec4(m.w_axis.xyww()),
),
(2, 3) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xyzw()),
Vec3A::from_vec4(m.y_axis.xyzw()),
Vec3A::from_vec4(m.w_axis.xyzw()),
),
(3, 0) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.yzww()),
Vec3A::from_vec4(m.y_axis.yzww()),
Vec3A::from_vec4(m.z_axis.yzww()),
),
(3, 1) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xzww()),
Vec3A::from_vec4(m.y_axis.xzww()),
Vec3A::from_vec4(m.z_axis.xzww()),
),
(3, 2) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xyww()),
Vec3A::from_vec4(m.y_axis.xyww()),
Vec3A::from_vec4(m.z_axis.xyww()),
),
(3, 3) => Self::from_cols(
Vec3A::from_vec4(m.x_axis.xyzw()),
Vec3A::from_vec4(m.y_axis.xyzw()),
Vec3A::from_vec4(m.z_axis.xyzw()),
),
_ => panic!("index out of bounds"),
}
}
/// Creates a 3D rotation matrix from the given quaternion.
///
/// # Panics
///
/// Will panic if `rotation` is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn from_quat(rotation: Quat) -> Self {
glam_assert!(rotation.is_normalized());
let x2 = rotation.x + rotation.x;
let y2 = rotation.y + rotation.y;
let z2 = rotation.z + rotation.z;
let xx = rotation.x * x2;
let xy = rotation.x * y2;
let xz = rotation.x * z2;
let yy = rotation.y * y2;
let yz = rotation.y * z2;
let zz = rotation.z * z2;
let wx = rotation.w * x2;
let wy = rotation.w * y2;
let wz = rotation.w * z2;
Self::from_cols(
Vec3A::new(1.0 - (yy + zz), xy + wz, xz - wy),
Vec3A::new(xy - wz, 1.0 - (xx + zz), yz + wx),
Vec3A::new(xz + wy, yz - wx, 1.0 - (xx + yy)),
)
}
/// Creates a 3D rotation matrix from a normalized rotation `axis` and `angle` (in
/// radians).
///
/// # Panics
///
/// Will panic if `axis` is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn from_axis_angle(axis: Vec3, angle: f32) -> Self {
glam_assert!(axis.is_normalized());
let (sin, cos) = math::sin_cos(angle);
let (xsin, ysin, zsin) = axis.mul(sin).into();
let (x, y, z) = axis.into();
let (x2, y2, z2) = axis.mul(axis).into();
let omc = 1.0 - cos;
let xyomc = x * y * omc;
let xzomc = x * z * omc;
let yzomc = y * z * omc;
Self::from_cols(
Vec3A::new(x2 * omc + cos, xyomc + zsin, xzomc - ysin),
Vec3A::new(xyomc - zsin, y2 * omc + cos, yzomc + xsin),
Vec3A::new(xzomc + ysin, yzomc - xsin, z2 * omc + cos),
)
}
/// Creates a 3D rotation matrix from the given euler rotation sequence and the angles (in
/// radians).
#[inline]
#[must_use]
pub fn from_euler(order: EulerRot, a: f32, b: f32, c: f32) -> Self {
Self::from_euler_angles(order, a, b, c)
}
/// Extract Euler angles with the given Euler rotation order.
///
/// Note if the input matrix contains scales, shears, or other non-rotation transformations then
/// the resulting Euler angles will be ill-defined.
///
/// # Panics
///
/// Will panic if any input matrix column is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn to_euler(&self, order: EulerRot) -> (f32, f32, f32) {
glam_assert!(
self.x_axis.is_normalized()
&& self.y_axis.is_normalized()
&& self.z_axis.is_normalized()
);
self.to_euler_angles(order)
}
/// Creates a 3D rotation matrix from `angle` (in radians) around the x axis.
#[inline]
#[must_use]
pub fn from_rotation_x(angle: f32) -> Self {
let (sina, cosa) = math::sin_cos(angle);
Self::from_cols(
Vec3A::X,
Vec3A::new(0.0, cosa, sina),
Vec3A::new(0.0, -sina, cosa),
)
}
/// Creates a 3D rotation matrix from `angle` (in radians) around the y axis.
#[inline]
#[must_use]
pub fn from_rotation_y(angle: f32) -> Self {
let (sina, cosa) = math::sin_cos(angle);
Self::from_cols(
Vec3A::new(cosa, 0.0, -sina),
Vec3A::Y,
Vec3A::new(sina, 0.0, cosa),
)
}
/// Creates a 3D rotation matrix from `angle` (in radians) around the z axis.
#[inline]
#[must_use]
pub fn from_rotation_z(angle: f32) -> Self {
let (sina, cosa) = math::sin_cos(angle);
Self::from_cols(
Vec3A::new(cosa, sina, 0.0),
Vec3A::new(-sina, cosa, 0.0),
Vec3A::Z,
)
}
/// Creates an affine transformation matrix from the given 2D `translation`.
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
#[inline]
#[must_use]
pub fn from_translation(translation: Vec2) -> Self {
Self::from_cols(
Vec3A::X,
Vec3A::Y,
Vec3A::new(translation.x, translation.y, 1.0),
)
}
/// Creates an affine transformation matrix from the given 2D rotation `angle` (in
/// radians).
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
#[inline]
#[must_use]
pub fn from_angle(angle: f32) -> Self {
let (sin, cos) = math::sin_cos(angle);
Self::from_cols(
Vec3A::new(cos, sin, 0.0),
Vec3A::new(-sin, cos, 0.0),
Vec3A::Z,
)
}
/// Creates an affine transformation matrix from the given 2D `scale`, rotation `angle` (in
/// radians) and `translation`.
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
#[inline]
#[must_use]
pub fn from_scale_angle_translation(scale: Vec2, angle: f32, translation: Vec2) -> Self {
let (sin, cos) = math::sin_cos(angle);
Self::from_cols(
Vec3A::new(cos * scale.x, sin * scale.x, 0.0),
Vec3A::new(-sin * scale.y, cos * scale.y, 0.0),
Vec3A::new(translation.x, translation.y, 1.0),
)
}
/// Creates an affine transformation matrix from the given non-uniform 2D `scale`.
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
///
/// # Panics
///
/// Will panic if all elements of `scale` are zero when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn from_scale(scale: Vec2) -> Self {
// Do not panic as long as any component is non-zero
glam_assert!(scale.cmpne(Vec2::ZERO).any());
Self::from_cols(
Vec3A::new(scale.x, 0.0, 0.0),
Vec3A::new(0.0, scale.y, 0.0),
Vec3A::Z,
)
}
/// Creates an affine transformation matrix from the given 2x2 matrix.
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
#[inline]
pub fn from_mat2(m: Mat2) -> Self {
Self::from_cols((m.x_axis, 0.0).into(), (m.y_axis, 0.0).into(), Vec3A::Z)
}
/// Creates a 3x3 matrix from the first 9 values in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 9 elements long.
#[inline]
#[must_use]
pub const fn from_cols_slice(slice: &[f32]) -> Self {
Self::new(
slice[0], slice[1], slice[2], slice[3], slice[4], slice[5], slice[6], slice[7],
slice[8],
)
}
/// Writes the columns of `self` to the first 9 elements in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 9 elements long.
#[inline]
pub fn write_cols_to_slice(self, slice: &mut [f32]) {
slice[0] = self.x_axis.x;
slice[1] = self.x_axis.y;
slice[2] = self.x_axis.z;
slice[3] = self.y_axis.x;
slice[4] = self.y_axis.y;
slice[5] = self.y_axis.z;
slice[6] = self.z_axis.x;
slice[7] = self.z_axis.y;
slice[8] = self.z_axis.z;
}
/// Returns the matrix column for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 2.
#[inline]
#[must_use]
pub fn col(&self, index: usize) -> Vec3A {
match index {
0 => self.x_axis,
1 => self.y_axis,
2 => self.z_axis,
_ => panic!("index out of bounds"),
}
}
/// Returns a mutable reference to the matrix column for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 2.
#[inline]
pub fn col_mut(&mut self, index: usize) -> &mut Vec3A {
match index {
0 => &mut self.x_axis,
1 => &mut self.y_axis,
2 => &mut self.z_axis,
_ => panic!("index out of bounds"),
}
}
/// Returns the matrix row for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 2.
#[inline]
#[must_use]
pub fn row(&self, index: usize) -> Vec3A {
match index {
0 => Vec3A::new(self.x_axis.x, self.y_axis.x, self.z_axis.x),
1 => Vec3A::new(self.x_axis.y, self.y_axis.y, self.z_axis.y),
2 => Vec3A::new(self.x_axis.z, self.y_axis.z, self.z_axis.z),
_ => panic!("index out of bounds"),
}
}
/// Returns `true` if, and only if, all elements are finite.
/// If any element is either `NaN`, positive or negative infinity, this will return `false`.
#[inline]
#[must_use]
pub fn is_finite(&self) -> bool {
self.x_axis.is_finite() && self.y_axis.is_finite() && self.z_axis.is_finite()
}
/// Returns `true` if any elements are `NaN`.
#[inline]
#[must_use]
pub fn is_nan(&self) -> bool {
self.x_axis.is_nan() || self.y_axis.is_nan() || self.z_axis.is_nan()
}
/// Returns the transpose of `self`.
#[inline]
#[must_use]
pub fn transpose(&self) -> Self {
let tmp0 = i32x4_shuffle::<0, 1, 4, 5>(self.x_axis.0, self.y_axis.0);
let tmp1 = i32x4_shuffle::<2, 3, 6, 7>(self.x_axis.0, self.y_axis.0);
Self {
x_axis: Vec3A(i32x4_shuffle::<0, 2, 4, 4>(tmp0, self.z_axis.0)),
y_axis: Vec3A(i32x4_shuffle::<1, 3, 5, 5>(tmp0, self.z_axis.0)),
z_axis: Vec3A(i32x4_shuffle::<0, 2, 6, 6>(tmp1, self.z_axis.0)),
}
}
/// Returns the determinant of `self`.
#[inline]
#[must_use]
pub fn determinant(&self) -> f32 {
self.z_axis.dot(self.x_axis.cross(self.y_axis))
}
/// Returns the inverse of `self`.
///
/// If the matrix is not invertible the returned matrix will be invalid.
///
/// # Panics
///
/// Will panic if the determinant of `self` is zero when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn inverse(&self) -> Self {
let tmp0 = self.y_axis.cross(self.z_axis);
let tmp1 = self.z_axis.cross(self.x_axis);
let tmp2 = self.x_axis.cross(self.y_axis);
let det = self.z_axis.dot(tmp2);
glam_assert!(det != 0.0);
let inv_det = Vec3A::splat(det.recip());
Self::from_cols(tmp0.mul(inv_det), tmp1.mul(inv_det), tmp2.mul(inv_det)).transpose()
}
/// Transforms the given 2D vector as a point.
///
/// This is the equivalent of multiplying `rhs` as a 3D vector where `z` is `1`.
///
/// This method assumes that `self` contains a valid affine transform.
///
/// # Panics
///
/// Will panic if the 2nd row of `self` is not `(0, 0, 1)` when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn transform_point2(&self, rhs: Vec2) -> Vec2 {
glam_assert!(self.row(2).abs_diff_eq(Vec3A::Z, 1e-6));
Mat2::from_cols(self.x_axis.xy(), self.y_axis.xy()) * rhs + self.z_axis.xy()
}
/// Rotates the given 2D vector.
///
/// This is the equivalent of multiplying `rhs` as a 3D vector where `z` is `0`.
///
/// This method assumes that `self` contains a valid affine transform.
///
/// # Panics
///
/// Will panic if the 2nd row of `self` is not `(0, 0, 1)` when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn transform_vector2(&self, rhs: Vec2) -> Vec2 {
glam_assert!(self.row(2).abs_diff_eq(Vec3A::Z, 1e-6));
Mat2::from_cols(self.x_axis.xy(), self.y_axis.xy()) * rhs
}
/// Transforms a 3D vector.
#[inline]
#[must_use]
pub fn mul_vec3(&self, rhs: Vec3) -> Vec3 {
self.mul_vec3a(rhs.into()).into()
}
/// Transforms a [`Vec3A`].
#[inline]
#[must_use]
pub fn mul_vec3a(&self, rhs: Vec3A) -> Vec3A {
let mut res = self.x_axis.mul(rhs.xxx());
res = res.add(self.y_axis.mul(rhs.yyy()));
res = res.add(self.z_axis.mul(rhs.zzz()));
res
}
/// Multiplies two 3x3 matrices.
#[inline]
#[must_use]
pub fn mul_mat3(&self, rhs: &Self) -> Self {
Self::from_cols(
self.mul(rhs.x_axis),
self.mul(rhs.y_axis),
self.mul(rhs.z_axis),
)
}
/// Adds two 3x3 matrices.
#[inline]
#[must_use]
pub fn add_mat3(&self, rhs: &Self) -> Self {
Self::from_cols(
self.x_axis.add(rhs.x_axis),
self.y_axis.add(rhs.y_axis),
self.z_axis.add(rhs.z_axis),
)
}
/// Subtracts two 3x3 matrices.
#[inline]
#[must_use]
pub fn sub_mat3(&self, rhs: &Self) -> Self {
Self::from_cols(
self.x_axis.sub(rhs.x_axis),
self.y_axis.sub(rhs.y_axis),
self.z_axis.sub(rhs.z_axis),
)
}
/// Multiplies a 3x3 matrix by a scalar.
#[inline]
#[must_use]
pub fn mul_scalar(&self, rhs: f32) -> Self {
Self::from_cols(
self.x_axis.mul(rhs),
self.y_axis.mul(rhs),
self.z_axis.mul(rhs),
)
}
/// Divides a 3x3 matrix by a scalar.
#[inline]
#[must_use]
pub fn div_scalar(&self, rhs: f32) -> Self {
let rhs = Vec3A::splat(rhs);
Self::from_cols(
self.x_axis.div(rhs),
self.y_axis.div(rhs),
self.z_axis.div(rhs),
)
}
/// Returns true if the absolute difference of all elements between `self` and `rhs`
/// is less than or equal to `max_abs_diff`.
///
/// This can be used to compare if two matrices contain similar elements. It works best
/// when comparing with a known value. The `max_abs_diff` that should be used used
/// depends on the values being compared against.
///
/// For more see
/// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
#[inline]
#[must_use]
pub fn abs_diff_eq(&self, rhs: Self, max_abs_diff: f32) -> bool {
self.x_axis.abs_diff_eq(rhs.x_axis, max_abs_diff)
&& self.y_axis.abs_diff_eq(rhs.y_axis, max_abs_diff)
&& self.z_axis.abs_diff_eq(rhs.z_axis, max_abs_diff)
}
/// Takes the absolute value of each element in `self`
#[inline]
#[must_use]
pub fn abs(&self) -> Self {
Self::from_cols(self.x_axis.abs(), self.y_axis.abs(), self.z_axis.abs())
}
#[inline]
pub fn as_dmat3(&self) -> DMat3 {
DMat3::from_cols(
self.x_axis.as_dvec3(),
self.y_axis.as_dvec3(),
self.z_axis.as_dvec3(),
)
}
}
impl Default for Mat3A {
#[inline]
fn default() -> Self {
Self::IDENTITY
}
}
impl Add<Mat3A> for Mat3A {
type Output = Self;
#[inline]
fn add(self, rhs: Self) -> Self::Output {
self.add_mat3(&rhs)
}
}
impl AddAssign<Mat3A> for Mat3A {
#[inline]
fn add_assign(&mut self, rhs: Self) {
*self = self.add_mat3(&rhs);
}
}
impl Sub<Mat3A> for Mat3A {
type Output = Self;
#[inline]
fn sub(self, rhs: Self) -> Self::Output {
self.sub_mat3(&rhs)
}
}
impl SubAssign<Mat3A> for Mat3A {
#[inline]
fn sub_assign(&mut self, rhs: Self) {
*self = self.sub_mat3(&rhs);
}
}
impl Neg for Mat3A {
type Output = Self;
#[inline]
fn neg(self) -> Self::Output {
Self::from_cols(self.x_axis.neg(), self.y_axis.neg(), self.z_axis.neg())
}
}
impl Mul<Mat3A> for Mat3A {
type Output = Self;
#[inline]
fn mul(self, rhs: Self) -> Self::Output {
self.mul_mat3(&rhs)
}
}
impl MulAssign<Mat3A> for Mat3A {
#[inline]
fn mul_assign(&mut self, rhs: Self) {
*self = self.mul_mat3(&rhs);
}
}
impl Mul<Vec3A> for Mat3A {
type Output = Vec3A;
#[inline]
fn mul(self, rhs: Vec3A) -> Self::Output {
self.mul_vec3a(rhs)
}
}
impl Mul<Mat3A> for f32 {
type Output = Mat3A;
#[inline]
fn mul(self, rhs: Mat3A) -> Self::Output {
rhs.mul_scalar(self)
}
}
impl Mul<f32> for Mat3A {
type Output = Self;
#[inline]
fn mul(self, rhs: f32) -> Self::Output {
self.mul_scalar(rhs)
}
}
impl MulAssign<f32> for Mat3A {
#[inline]
fn mul_assign(&mut self, rhs: f32) {
*self = self.mul_scalar(rhs);
}
}
impl Div<Mat3A> for f32 {
type Output = Mat3A;
#[inline]
fn div(self, rhs: Mat3A) -> Self::Output {
rhs.div_scalar(self)
}
}
impl Div<f32> for Mat3A {
type Output = Self;
#[inline]
fn div(self, rhs: f32) -> Self::Output {
self.div_scalar(rhs)
}
}
impl DivAssign<f32> for Mat3A {
#[inline]
fn div_assign(&mut self, rhs: f32) {
*self = self.div_scalar(rhs);
}
}
impl Mul<Vec3> for Mat3A {
type Output = Vec3;
#[inline]
fn mul(self, rhs: Vec3) -> Vec3 {
self.mul_vec3a(rhs.into()).into()
}
}
impl From<Mat3> for Mat3A {
#[inline]
fn from(m: Mat3) -> Self {
Self {
x_axis: m.x_axis.into(),
y_axis: m.y_axis.into(),
z_axis: m.z_axis.into(),
}
}
}
impl Sum<Self> for Mat3A {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Self::ZERO, Self::add)
}
}
impl<'a> Sum<&'a Self> for Mat3A {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
}
}
impl Product for Mat3A {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Self::IDENTITY, Self::mul)
}
}
impl<'a> Product<&'a Self> for Mat3A {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::IDENTITY, |a, &b| Self::mul(a, b))
}
}
impl PartialEq for Mat3A {
#[inline]
fn eq(&self, rhs: &Self) -> bool {
self.x_axis.eq(&rhs.x_axis) && self.y_axis.eq(&rhs.y_axis) && self.z_axis.eq(&rhs.z_axis)
}
}
impl fmt::Debug for Mat3A {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct(stringify!(Mat3A))
.field("x_axis", &self.x_axis)
.field("y_axis", &self.y_axis)
.field("z_axis", &self.z_axis)
.finish()
}
}
impl fmt::Display for Mat3A {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(p) = f.precision() {
write!(
f,
"[{:.*}, {:.*}, {:.*}]",
p, self.x_axis, p, self.y_axis, p, self.z_axis
)
} else {
write!(f, "[{}, {}, {}]", self.x_axis, self.y_axis, self.z_axis)
}
}
}
+1536
View File
File diff suppressed because it is too large Load Diff
+1015
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+1829
View File
File diff suppressed because it is too large Load Diff
+101
View File
@@ -0,0 +1,101 @@
mod daffine2;
mod daffine3;
mod dmat2;
mod dmat3;
mod dmat4;
mod dquat;
mod dvec2;
mod dvec3;
mod dvec4;
mod float;
pub(crate) mod math;
pub use daffine2::DAffine2;
pub use daffine3::DAffine3;
pub use dmat2::{dmat2, DMat2};
pub use dmat3::{dmat3, DMat3};
pub use dmat4::{dmat4, DMat4};
pub use dquat::{dquat, DQuat};
pub use dvec2::{dvec2, DVec2};
pub use dvec3::{dvec3, DVec3};
pub use dvec4::{dvec4, DVec4};
#[cfg(not(target_arch = "spirv"))]
mod test {
pub use super::*;
mod const_test_daffine2 {
const_assert_eq!(
core::mem::align_of::<super::DVec2>(),
core::mem::align_of::<super::DAffine2>()
);
const_assert_eq!(48, core::mem::size_of::<super::DAffine2>());
}
mod const_test_dmat2 {
const_assert_eq!(
core::mem::align_of::<super::DVec2>(),
core::mem::align_of::<super::DMat2>()
);
const_assert_eq!(32, core::mem::size_of::<super::DMat2>());
}
mod const_test_dmat3 {
const_assert_eq!(
core::mem::align_of::<f64>(),
core::mem::align_of::<super::DMat3>()
);
const_assert_eq!(72, core::mem::size_of::<super::DMat3>());
}
mod const_test_dmat4 {
const_assert_eq!(
core::mem::align_of::<super::DVec4>(),
core::mem::align_of::<super::DMat4>()
);
const_assert_eq!(128, core::mem::size_of::<super::DMat4>());
}
mod const_test_dquat {
#[cfg(not(target_arch = "spirv"))]
const_assert_eq!(
core::mem::align_of::<f64>(),
core::mem::align_of::<super::DQuat>()
);
#[cfg(target_arch = "spirv")]
const_assert_eq!(32, core::mem::align_of::<super::DQuat>());
const_assert_eq!(32, core::mem::size_of::<super::DQuat>());
}
mod const_test_dvec2 {
#[cfg(not(any(feature = "cuda", target_arch = "spirv")))]
const_assert_eq!(
core::mem::align_of::<f64>(),
core::mem::align_of::<super::DVec2>()
);
#[cfg(any(feature = "cuda", target_arch = "spirv"))]
const_assert_eq!(16, core::mem::align_of::<super::DVec2>());
const_assert_eq!(16, core::mem::size_of::<super::DVec2>());
}
mod const_test_dvec3 {
#[cfg(not(target_arch = "spirv"))]
const_assert_eq!(
core::mem::align_of::<f64>(),
core::mem::align_of::<super::DVec3>()
);
#[cfg(target_arch = "spirv")]
const_assert_eq!(16, core::mem::align_of::<super::DVec3>());
const_assert_eq!(24, core::mem::size_of::<super::DVec3>());
}
mod const_test_dvec4 {
#[cfg(not(any(feature = "cuda", target_arch = "spirv")))]
const_assert_eq!(
core::mem::align_of::<f64>(),
core::mem::align_of::<super::DVec4>()
);
#[cfg(any(feature = "cuda", target_arch = "spirv"))]
const_assert_eq!(16, core::mem::align_of::<super::DVec4>());
const_assert_eq!(32, core::mem::size_of::<super::DVec4>());
}
}
+418
View File
@@ -0,0 +1,418 @@
// Generated from affine.rs.tera template. Edit the template, not the generated file.
use crate::{DMat2, DMat3, DVec2};
use core::ops::{Deref, DerefMut, Mul, MulAssign};
/// A 2D affine transform, which can represent translation, rotation, scaling and shear.
#[derive(Copy, Clone)]
#[repr(C)]
pub struct DAffine2 {
pub matrix2: DMat2,
pub translation: DVec2,
}
impl DAffine2 {
/// The degenerate zero transform.
///
/// This transforms any finite vector and point to zero.
/// The zero transform is non-invertible.
pub const ZERO: Self = Self {
matrix2: DMat2::ZERO,
translation: DVec2::ZERO,
};
/// The identity transform.
///
/// Multiplying a vector with this returns the same vector.
pub const IDENTITY: Self = Self {
matrix2: DMat2::IDENTITY,
translation: DVec2::ZERO,
};
/// All NAN:s.
pub const NAN: Self = Self {
matrix2: DMat2::NAN,
translation: DVec2::NAN,
};
/// Creates an affine transform from three column vectors.
#[inline(always)]
#[must_use]
pub const fn from_cols(x_axis: DVec2, y_axis: DVec2, z_axis: DVec2) -> Self {
Self {
matrix2: DMat2::from_cols(x_axis, y_axis),
translation: z_axis,
}
}
/// Creates an affine transform from a `[f64; 6]` array stored in column major order.
#[inline]
#[must_use]
pub fn from_cols_array(m: &[f64; 6]) -> Self {
Self {
matrix2: DMat2::from_cols_array(&[m[0], m[1], m[2], m[3]]),
translation: DVec2::from_array([m[4], m[5]]),
}
}
/// Creates a `[f64; 6]` array storing data in column major order.
#[inline]
#[must_use]
pub fn to_cols_array(&self) -> [f64; 6] {
let x = &self.matrix2.x_axis;
let y = &self.matrix2.y_axis;
let z = &self.translation;
[x.x, x.y, y.x, y.y, z.x, z.y]
}
/// Creates an affine transform from a `[[f64; 2]; 3]`
/// 2D array stored in column major order.
/// If your data is in row major order you will need to `transpose` the returned
/// matrix.
#[inline]
#[must_use]
pub fn from_cols_array_2d(m: &[[f64; 2]; 3]) -> Self {
Self {
matrix2: DMat2::from_cols(m[0].into(), m[1].into()),
translation: m[2].into(),
}
}
/// Creates a `[[f64; 2]; 3]` 2D array storing data in
/// column major order.
/// If you require data in row major order `transpose` the matrix first.
#[inline]
#[must_use]
pub fn to_cols_array_2d(&self) -> [[f64; 2]; 3] {
[
self.matrix2.x_axis.into(),
self.matrix2.y_axis.into(),
self.translation.into(),
]
}
/// Creates an affine transform from the first 6 values in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 6 elements long.
#[inline]
#[must_use]
pub fn from_cols_slice(slice: &[f64]) -> Self {
Self {
matrix2: DMat2::from_cols_slice(&slice[0..4]),
translation: DVec2::from_slice(&slice[4..6]),
}
}
/// Writes the columns of `self` to the first 6 elements in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 6 elements long.
#[inline]
pub fn write_cols_to_slice(self, slice: &mut [f64]) {
self.matrix2.write_cols_to_slice(&mut slice[0..4]);
self.translation.write_to_slice(&mut slice[4..6]);
}
/// Creates an affine transform that changes scale.
/// Note that if any scale is zero the transform will be non-invertible.
#[inline]
#[must_use]
pub fn from_scale(scale: DVec2) -> Self {
Self {
matrix2: DMat2::from_diagonal(scale),
translation: DVec2::ZERO,
}
}
/// Creates an affine transform from the given rotation `angle`.
#[inline]
#[must_use]
pub fn from_angle(angle: f64) -> Self {
Self {
matrix2: DMat2::from_angle(angle),
translation: DVec2::ZERO,
}
}
/// Creates an affine transformation from the given 2D `translation`.
#[inline]
#[must_use]
pub fn from_translation(translation: DVec2) -> Self {
Self {
matrix2: DMat2::IDENTITY,
translation,
}
}
/// Creates an affine transform from a 2x2 matrix (expressing scale, shear and rotation)
#[inline]
#[must_use]
pub fn from_mat2(matrix2: DMat2) -> Self {
Self {
matrix2,
translation: DVec2::ZERO,
}
}
/// Creates an affine transform from a 2x2 matrix (expressing scale, shear and rotation) and a
/// translation vector.
///
/// Equivalent to
/// `DAffine2::from_translation(translation) * DAffine2::from_mat2(mat2)`
#[inline]
#[must_use]
pub fn from_mat2_translation(matrix2: DMat2, translation: DVec2) -> Self {
Self {
matrix2,
translation,
}
}
/// Creates an affine transform from the given 2D `scale`, rotation `angle` (in radians) and
/// `translation`.
///
/// Equivalent to `DAffine2::from_translation(translation) *
/// DAffine2::from_angle(angle) * DAffine2::from_scale(scale)`
#[inline]
#[must_use]
pub fn from_scale_angle_translation(scale: DVec2, angle: f64, translation: DVec2) -> Self {
let rotation = DMat2::from_angle(angle);
Self {
matrix2: DMat2::from_cols(rotation.x_axis * scale.x, rotation.y_axis * scale.y),
translation,
}
}
/// Creates an affine transform from the given 2D rotation `angle` (in radians) and
/// `translation`.
///
/// Equivalent to `DAffine2::from_translation(translation) * DAffine2::from_angle(angle)`
#[inline]
#[must_use]
pub fn from_angle_translation(angle: f64, translation: DVec2) -> Self {
Self {
matrix2: DMat2::from_angle(angle),
translation,
}
}
/// The given `DMat3` must be an affine transform,
#[inline]
#[must_use]
pub fn from_mat3(m: DMat3) -> Self {
use crate::swizzles::Vec3Swizzles;
Self {
matrix2: DMat2::from_cols(m.x_axis.xy(), m.y_axis.xy()),
translation: m.z_axis.xy(),
}
}
/// Extracts `scale`, `angle` and `translation` from `self`.
///
/// The transform is expected to be non-degenerate and without shearing, or the output
/// will be invalid.
///
/// # Panics
///
/// Will panic if the determinant `self.matrix2` is zero or if the resulting scale
/// vector contains any zero elements when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn to_scale_angle_translation(self) -> (DVec2, f64, DVec2) {
use crate::f64::math;
let det = self.matrix2.determinant();
glam_assert!(det != 0.0);
let scale = DVec2::new(
self.matrix2.x_axis.length() * math::signum(det),
self.matrix2.y_axis.length(),
);
glam_assert!(scale.cmpne(DVec2::ZERO).all());
let angle = math::atan2(-self.matrix2.y_axis.x, self.matrix2.y_axis.y);
(scale, angle, self.translation)
}
/// Transforms the given 2D point, applying shear, scale, rotation and translation.
#[inline]
#[must_use]
pub fn transform_point2(&self, rhs: DVec2) -> DVec2 {
self.matrix2 * rhs + self.translation
}
/// Transforms the given 2D vector, applying shear, scale and rotation (but NOT
/// translation).
///
/// To also apply translation, use [`Self::transform_point2()`] instead.
#[inline]
pub fn transform_vector2(&self, rhs: DVec2) -> DVec2 {
self.matrix2 * rhs
}
/// Returns `true` if, and only if, all elements are finite.
///
/// If any element is either `NaN`, positive or negative infinity, this will return
/// `false`.
#[inline]
#[must_use]
pub fn is_finite(&self) -> bool {
self.matrix2.is_finite() && self.translation.is_finite()
}
/// Returns `true` if any elements are `NaN`.
#[inline]
#[must_use]
pub fn is_nan(&self) -> bool {
self.matrix2.is_nan() || self.translation.is_nan()
}
/// Returns true if the absolute difference of all elements between `self` and `rhs`
/// is less than or equal to `max_abs_diff`.
///
/// This can be used to compare if two 3x4 matrices contain similar elements. It works
/// best when comparing with a known value. The `max_abs_diff` that should be used used
/// depends on the values being compared against.
///
/// For more see
/// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
#[inline]
#[must_use]
pub fn abs_diff_eq(&self, rhs: Self, max_abs_diff: f64) -> bool {
self.matrix2.abs_diff_eq(rhs.matrix2, max_abs_diff)
&& self.translation.abs_diff_eq(rhs.translation, max_abs_diff)
}
/// Return the inverse of this transform.
///
/// Note that if the transform is not invertible the result will be invalid.
#[inline]
#[must_use]
pub fn inverse(&self) -> Self {
let matrix2 = self.matrix2.inverse();
// transform negative translation by the matrix inverse:
let translation = -(matrix2 * self.translation);
Self {
matrix2,
translation,
}
}
}
impl Default for DAffine2 {
#[inline(always)]
fn default() -> Self {
Self::IDENTITY
}
}
impl Deref for DAffine2 {
type Target = crate::deref::Cols3<DVec2>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*(self as *const Self as *const Self::Target) }
}
}
impl DerefMut for DAffine2 {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { &mut *(self as *mut Self as *mut Self::Target) }
}
}
impl PartialEq for DAffine2 {
#[inline]
fn eq(&self, rhs: &Self) -> bool {
self.matrix2.eq(&rhs.matrix2) && self.translation.eq(&rhs.translation)
}
}
impl core::fmt::Debug for DAffine2 {
fn fmt(&self, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
fmt.debug_struct(stringify!(DAffine2))
.field("matrix2", &self.matrix2)
.field("translation", &self.translation)
.finish()
}
}
impl core::fmt::Display for DAffine2 {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
if let Some(p) = f.precision() {
write!(
f,
"[{:.*}, {:.*}, {:.*}]",
p, self.matrix2.x_axis, p, self.matrix2.y_axis, p, self.translation
)
} else {
write!(
f,
"[{}, {}, {}]",
self.matrix2.x_axis, self.matrix2.y_axis, self.translation
)
}
}
}
impl<'a> core::iter::Product<&'a Self> for DAffine2 {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::IDENTITY, |a, &b| a * b)
}
}
impl Mul for DAffine2 {
type Output = DAffine2;
#[inline]
fn mul(self, rhs: DAffine2) -> Self::Output {
Self {
matrix2: self.matrix2 * rhs.matrix2,
translation: self.matrix2 * rhs.translation + self.translation,
}
}
}
impl MulAssign for DAffine2 {
#[inline]
fn mul_assign(&mut self, rhs: DAffine2) {
*self = self.mul(rhs);
}
}
impl From<DAffine2> for DMat3 {
#[inline]
fn from(m: DAffine2) -> DMat3 {
Self::from_cols(
m.matrix2.x_axis.extend(0.0),
m.matrix2.y_axis.extend(0.0),
m.translation.extend(1.0),
)
}
}
impl Mul<DMat3> for DAffine2 {
type Output = DMat3;
#[inline]
fn mul(self, rhs: DMat3) -> Self::Output {
DMat3::from(self) * rhs
}
}
impl Mul<DAffine2> for DMat3 {
type Output = DMat3;
#[inline]
fn mul(self, rhs: DAffine2) -> Self::Output {
self * DMat3::from(rhs)
}
}
+566
View File
@@ -0,0 +1,566 @@
// Generated from affine.rs.tera template. Edit the template, not the generated file.
use crate::{DMat3, DMat4, DQuat, DVec3};
use core::ops::{Deref, DerefMut, Mul, MulAssign};
/// A 3D affine transform, which can represent translation, rotation, scaling and shear.
#[derive(Copy, Clone)]
#[repr(C)]
pub struct DAffine3 {
pub matrix3: DMat3,
pub translation: DVec3,
}
impl DAffine3 {
/// The degenerate zero transform.
///
/// This transforms any finite vector and point to zero.
/// The zero transform is non-invertible.
pub const ZERO: Self = Self {
matrix3: DMat3::ZERO,
translation: DVec3::ZERO,
};
/// The identity transform.
///
/// Multiplying a vector with this returns the same vector.
pub const IDENTITY: Self = Self {
matrix3: DMat3::IDENTITY,
translation: DVec3::ZERO,
};
/// All NAN:s.
pub const NAN: Self = Self {
matrix3: DMat3::NAN,
translation: DVec3::NAN,
};
/// Creates an affine transform from three column vectors.
#[inline(always)]
#[must_use]
pub const fn from_cols(x_axis: DVec3, y_axis: DVec3, z_axis: DVec3, w_axis: DVec3) -> Self {
Self {
matrix3: DMat3::from_cols(x_axis, y_axis, z_axis),
translation: w_axis,
}
}
/// Creates an affine transform from a `[f64; 12]` array stored in column major order.
#[inline]
#[must_use]
pub fn from_cols_array(m: &[f64; 12]) -> Self {
Self {
matrix3: DMat3::from_cols_array(&[
m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8],
]),
translation: DVec3::from_array([m[9], m[10], m[11]]),
}
}
/// Creates a `[f64; 12]` array storing data in column major order.
#[inline]
#[must_use]
pub fn to_cols_array(&self) -> [f64; 12] {
let x = &self.matrix3.x_axis;
let y = &self.matrix3.y_axis;
let z = &self.matrix3.z_axis;
let w = &self.translation;
[x.x, x.y, x.z, y.x, y.y, y.z, z.x, z.y, z.z, w.x, w.y, w.z]
}
/// Creates an affine transform from a `[[f64; 3]; 4]`
/// 3D array stored in column major order.
/// If your data is in row major order you will need to `transpose` the returned
/// matrix.
#[inline]
#[must_use]
pub fn from_cols_array_2d(m: &[[f64; 3]; 4]) -> Self {
Self {
matrix3: DMat3::from_cols(m[0].into(), m[1].into(), m[2].into()),
translation: m[3].into(),
}
}
/// Creates a `[[f64; 3]; 4]` 3D array storing data in
/// column major order.
/// If you require data in row major order `transpose` the matrix first.
#[inline]
#[must_use]
pub fn to_cols_array_2d(&self) -> [[f64; 3]; 4] {
[
self.matrix3.x_axis.into(),
self.matrix3.y_axis.into(),
self.matrix3.z_axis.into(),
self.translation.into(),
]
}
/// Creates an affine transform from the first 12 values in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 12 elements long.
#[inline]
#[must_use]
pub fn from_cols_slice(slice: &[f64]) -> Self {
Self {
matrix3: DMat3::from_cols_slice(&slice[0..9]),
translation: DVec3::from_slice(&slice[9..12]),
}
}
/// Writes the columns of `self` to the first 12 elements in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 12 elements long.
#[inline]
pub fn write_cols_to_slice(self, slice: &mut [f64]) {
self.matrix3.write_cols_to_slice(&mut slice[0..9]);
self.translation.write_to_slice(&mut slice[9..12]);
}
/// Creates an affine transform that changes scale.
/// Note that if any scale is zero the transform will be non-invertible.
#[inline]
#[must_use]
pub fn from_scale(scale: DVec3) -> Self {
Self {
matrix3: DMat3::from_diagonal(scale),
translation: DVec3::ZERO,
}
}
/// Creates an affine transform from the given `rotation` quaternion.
#[inline]
#[must_use]
pub fn from_quat(rotation: DQuat) -> Self {
Self {
matrix3: DMat3::from_quat(rotation),
translation: DVec3::ZERO,
}
}
/// Creates an affine transform containing a 3D rotation around a normalized
/// rotation `axis` of `angle` (in radians).
#[inline]
#[must_use]
pub fn from_axis_angle(axis: DVec3, angle: f64) -> Self {
Self {
matrix3: DMat3::from_axis_angle(axis, angle),
translation: DVec3::ZERO,
}
}
/// Creates an affine transform containing a 3D rotation around the x axis of
/// `angle` (in radians).
#[inline]
#[must_use]
pub fn from_rotation_x(angle: f64) -> Self {
Self {
matrix3: DMat3::from_rotation_x(angle),
translation: DVec3::ZERO,
}
}
/// Creates an affine transform containing a 3D rotation around the y axis of
/// `angle` (in radians).
#[inline]
#[must_use]
pub fn from_rotation_y(angle: f64) -> Self {
Self {
matrix3: DMat3::from_rotation_y(angle),
translation: DVec3::ZERO,
}
}
/// Creates an affine transform containing a 3D rotation around the z axis of
/// `angle` (in radians).
#[inline]
#[must_use]
pub fn from_rotation_z(angle: f64) -> Self {
Self {
matrix3: DMat3::from_rotation_z(angle),
translation: DVec3::ZERO,
}
}
/// Creates an affine transformation from the given 3D `translation`.
#[inline]
#[must_use]
pub fn from_translation(translation: DVec3) -> Self {
#[allow(clippy::useless_conversion)]
Self {
matrix3: DMat3::IDENTITY,
translation: translation.into(),
}
}
/// Creates an affine transform from a 3x3 matrix (expressing scale, shear and
/// rotation)
#[inline]
#[must_use]
pub fn from_mat3(mat3: DMat3) -> Self {
#[allow(clippy::useless_conversion)]
Self {
matrix3: mat3.into(),
translation: DVec3::ZERO,
}
}
/// Creates an affine transform from a 3x3 matrix (expressing scale, shear and rotation)
/// and a translation vector.
///
/// Equivalent to `DAffine3::from_translation(translation) * DAffine3::from_mat3(mat3)`
#[inline]
#[must_use]
pub fn from_mat3_translation(mat3: DMat3, translation: DVec3) -> Self {
#[allow(clippy::useless_conversion)]
Self {
matrix3: mat3.into(),
translation: translation.into(),
}
}
/// Creates an affine transform from the given 3D `scale`, `rotation` and
/// `translation`.
///
/// Equivalent to `DAffine3::from_translation(translation) *
/// DAffine3::from_quat(rotation) * DAffine3::from_scale(scale)`
#[inline]
#[must_use]
pub fn from_scale_rotation_translation(
scale: DVec3,
rotation: DQuat,
translation: DVec3,
) -> Self {
let rotation = DMat3::from_quat(rotation);
#[allow(clippy::useless_conversion)]
Self {
matrix3: DMat3::from_cols(
rotation.x_axis * scale.x,
rotation.y_axis * scale.y,
rotation.z_axis * scale.z,
),
translation: translation.into(),
}
}
/// Creates an affine transform from the given 3D `rotation` and `translation`.
///
/// Equivalent to `DAffine3::from_translation(translation) * DAffine3::from_quat(rotation)`
#[inline]
#[must_use]
pub fn from_rotation_translation(rotation: DQuat, translation: DVec3) -> Self {
#[allow(clippy::useless_conversion)]
Self {
matrix3: DMat3::from_quat(rotation),
translation: translation.into(),
}
}
/// The given `DMat4` must be an affine transform,
/// i.e. contain no perspective transform.
#[inline]
#[must_use]
pub fn from_mat4(m: DMat4) -> Self {
Self {
matrix3: DMat3::from_cols(
DVec3::from_vec4(m.x_axis),
DVec3::from_vec4(m.y_axis),
DVec3::from_vec4(m.z_axis),
),
translation: DVec3::from_vec4(m.w_axis),
}
}
/// Extracts `scale`, `rotation` and `translation` from `self`.
///
/// The transform is expected to be non-degenerate and without shearing, or the output
/// will be invalid.
///
/// # Panics
///
/// Will panic if the determinant `self.matrix3` is zero or if the resulting scale
/// vector contains any zero elements when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn to_scale_rotation_translation(&self) -> (DVec3, DQuat, DVec3) {
use crate::f64::math;
let det = self.matrix3.determinant();
glam_assert!(det != 0.0);
let scale = DVec3::new(
self.matrix3.x_axis.length() * math::signum(det),
self.matrix3.y_axis.length(),
self.matrix3.z_axis.length(),
);
glam_assert!(scale.cmpne(DVec3::ZERO).all());
let inv_scale = scale.recip();
#[allow(clippy::useless_conversion)]
let rotation = DQuat::from_mat3(&DMat3::from_cols(
(self.matrix3.x_axis * inv_scale.x).into(),
(self.matrix3.y_axis * inv_scale.y).into(),
(self.matrix3.z_axis * inv_scale.z).into(),
));
#[allow(clippy::useless_conversion)]
(scale, rotation, self.translation.into())
}
/// Creates a left-handed view transform using a camera position, an up direction, and a facing
/// direction.
///
/// For a view coordinate system with `+X=right`, `+Y=up` and `+Z=forward`.
#[inline]
#[must_use]
pub fn look_to_lh(eye: DVec3, dir: DVec3, up: DVec3) -> Self {
Self::look_to_rh(eye, -dir, up)
}
/// Creates a right-handed view transform using a camera position, an up direction, and a facing
/// direction.
///
/// For a view coordinate system with `+X=right`, `+Y=up` and `+Z=back`.
#[inline]
#[must_use]
pub fn look_to_rh(eye: DVec3, dir: DVec3, up: DVec3) -> Self {
let f = dir.normalize();
let s = f.cross(up).normalize();
let u = s.cross(f);
Self {
matrix3: DMat3::from_cols(
DVec3::new(s.x, u.x, -f.x),
DVec3::new(s.y, u.y, -f.y),
DVec3::new(s.z, u.z, -f.z),
),
translation: DVec3::new(-eye.dot(s), -eye.dot(u), eye.dot(f)),
}
}
/// Creates a left-handed view transform using a camera position, an up direction, and a focal
/// point.
/// For a view coordinate system with `+X=right`, `+Y=up` and `+Z=forward`.
///
/// # Panics
///
/// Will panic if `up` is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn look_at_lh(eye: DVec3, center: DVec3, up: DVec3) -> Self {
glam_assert!(up.is_normalized());
Self::look_to_lh(eye, center - eye, up)
}
/// Creates a right-handed view transform using a camera position, an up direction, and a focal
/// point.
/// For a view coordinate system with `+X=right`, `+Y=up` and `+Z=back`.
///
/// # Panics
///
/// Will panic if `up` is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn look_at_rh(eye: DVec3, center: DVec3, up: DVec3) -> Self {
glam_assert!(up.is_normalized());
Self::look_to_rh(eye, center - eye, up)
}
/// Transforms the given 3D points, applying shear, scale, rotation and translation.
#[inline]
pub fn transform_point3(&self, rhs: DVec3) -> DVec3 {
#[allow(clippy::useless_conversion)]
((self.matrix3.x_axis * rhs.x)
+ (self.matrix3.y_axis * rhs.y)
+ (self.matrix3.z_axis * rhs.z)
+ self.translation)
.into()
}
/// Transforms the given 3D vector, applying shear, scale and rotation (but NOT
/// translation).
///
/// To also apply translation, use [`Self::transform_point3()`] instead.
#[inline]
#[must_use]
pub fn transform_vector3(&self, rhs: DVec3) -> DVec3 {
#[allow(clippy::useless_conversion)]
((self.matrix3.x_axis * rhs.x)
+ (self.matrix3.y_axis * rhs.y)
+ (self.matrix3.z_axis * rhs.z))
.into()
}
/// Returns `true` if, and only if, all elements are finite.
///
/// If any element is either `NaN`, positive or negative infinity, this will return
/// `false`.
#[inline]
#[must_use]
pub fn is_finite(&self) -> bool {
self.matrix3.is_finite() && self.translation.is_finite()
}
/// Returns `true` if any elements are `NaN`.
#[inline]
#[must_use]
pub fn is_nan(&self) -> bool {
self.matrix3.is_nan() || self.translation.is_nan()
}
/// Returns true if the absolute difference of all elements between `self` and `rhs`
/// is less than or equal to `max_abs_diff`.
///
/// This can be used to compare if two 3x4 matrices contain similar elements. It works
/// best when comparing with a known value. The `max_abs_diff` that should be used used
/// depends on the values being compared against.
///
/// For more see
/// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
#[inline]
#[must_use]
pub fn abs_diff_eq(&self, rhs: Self, max_abs_diff: f64) -> bool {
self.matrix3.abs_diff_eq(rhs.matrix3, max_abs_diff)
&& self.translation.abs_diff_eq(rhs.translation, max_abs_diff)
}
/// Return the inverse of this transform.
///
/// Note that if the transform is not invertible the result will be invalid.
#[inline]
#[must_use]
pub fn inverse(&self) -> Self {
let matrix3 = self.matrix3.inverse();
// transform negative translation by the matrix inverse:
let translation = -(matrix3 * self.translation);
Self {
matrix3,
translation,
}
}
}
impl Default for DAffine3 {
#[inline(always)]
fn default() -> Self {
Self::IDENTITY
}
}
impl Deref for DAffine3 {
type Target = crate::deref::Cols4<DVec3>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
unsafe { &*(self as *const Self as *const Self::Target) }
}
}
impl DerefMut for DAffine3 {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { &mut *(self as *mut Self as *mut Self::Target) }
}
}
impl PartialEq for DAffine3 {
#[inline]
fn eq(&self, rhs: &Self) -> bool {
self.matrix3.eq(&rhs.matrix3) && self.translation.eq(&rhs.translation)
}
}
impl core::fmt::Debug for DAffine3 {
fn fmt(&self, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
fmt.debug_struct(stringify!(DAffine3))
.field("matrix3", &self.matrix3)
.field("translation", &self.translation)
.finish()
}
}
impl core::fmt::Display for DAffine3 {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
if let Some(p) = f.precision() {
write!(
f,
"[{:.*}, {:.*}, {:.*}, {:.*}]",
p,
self.matrix3.x_axis,
p,
self.matrix3.y_axis,
p,
self.matrix3.z_axis,
p,
self.translation
)
} else {
write!(
f,
"[{}, {}, {}, {}]",
self.matrix3.x_axis, self.matrix3.y_axis, self.matrix3.z_axis, self.translation
)
}
}
}
impl<'a> core::iter::Product<&'a Self> for DAffine3 {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::IDENTITY, |a, &b| a * b)
}
}
impl Mul for DAffine3 {
type Output = DAffine3;
#[inline]
fn mul(self, rhs: DAffine3) -> Self::Output {
Self {
matrix3: self.matrix3 * rhs.matrix3,
translation: self.matrix3 * rhs.translation + self.translation,
}
}
}
impl MulAssign for DAffine3 {
#[inline]
fn mul_assign(&mut self, rhs: DAffine3) {
*self = self.mul(rhs);
}
}
impl From<DAffine3> for DMat4 {
#[inline]
fn from(m: DAffine3) -> DMat4 {
DMat4::from_cols(
m.matrix3.x_axis.extend(0.0),
m.matrix3.y_axis.extend(0.0),
m.matrix3.z_axis.extend(0.0),
m.translation.extend(1.0),
)
}
}
impl Mul<DMat4> for DAffine3 {
type Output = DMat4;
#[inline]
fn mul(self, rhs: DMat4) -> Self::Output {
DMat4::from(self) * rhs
}
}
impl Mul<DAffine3> for DMat4 {
type Output = DMat4;
#[inline]
fn mul(self, rhs: DAffine3) -> Self::Output {
self * DMat4::from(rhs)
}
}
+529
View File
@@ -0,0 +1,529 @@
// Generated from mat.rs.tera template. Edit the template, not the generated file.
use crate::{f64::math, swizzles::*, DMat3, DVec2, Mat2};
use core::fmt;
use core::iter::{Product, Sum};
use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
/// Creates a 2x2 matrix from two column vectors.
#[inline(always)]
#[must_use]
pub const fn dmat2(x_axis: DVec2, y_axis: DVec2) -> DMat2 {
DMat2::from_cols(x_axis, y_axis)
}
/// A 2x2 column major matrix.
#[derive(Clone, Copy)]
#[cfg_attr(feature = "cuda", repr(align(16)))]
#[repr(C)]
pub struct DMat2 {
pub x_axis: DVec2,
pub y_axis: DVec2,
}
impl DMat2 {
/// A 2x2 matrix with all elements set to `0.0`.
pub const ZERO: Self = Self::from_cols(DVec2::ZERO, DVec2::ZERO);
/// A 2x2 identity matrix, where all diagonal elements are `1`, and all off-diagonal elements are `0`.
pub const IDENTITY: Self = Self::from_cols(DVec2::X, DVec2::Y);
/// All NAN:s.
pub const NAN: Self = Self::from_cols(DVec2::NAN, DVec2::NAN);
#[allow(clippy::too_many_arguments)]
#[inline(always)]
#[must_use]
const fn new(m00: f64, m01: f64, m10: f64, m11: f64) -> Self {
Self {
x_axis: DVec2::new(m00, m01),
y_axis: DVec2::new(m10, m11),
}
}
/// Creates a 2x2 matrix from two column vectors.
#[inline(always)]
#[must_use]
pub const fn from_cols(x_axis: DVec2, y_axis: DVec2) -> Self {
Self { x_axis, y_axis }
}
/// Creates a 2x2 matrix from a `[f64; 4]` array stored in column major order.
/// If your data is stored in row major you will need to `transpose` the returned
/// matrix.
#[inline]
#[must_use]
pub const fn from_cols_array(m: &[f64; 4]) -> Self {
Self::new(m[0], m[1], m[2], m[3])
}
/// Creates a `[f64; 4]` array storing data in column major order.
/// If you require data in row major order `transpose` the matrix first.
#[inline]
#[must_use]
pub const fn to_cols_array(&self) -> [f64; 4] {
[self.x_axis.x, self.x_axis.y, self.y_axis.x, self.y_axis.y]
}
/// Creates a 2x2 matrix from a `[[f64; 2]; 2]` 2D array stored in column major order.
/// If your data is in row major order you will need to `transpose` the returned
/// matrix.
#[inline]
#[must_use]
pub const fn from_cols_array_2d(m: &[[f64; 2]; 2]) -> Self {
Self::from_cols(DVec2::from_array(m[0]), DVec2::from_array(m[1]))
}
/// Creates a `[[f64; 2]; 2]` 2D array storing data in column major order.
/// If you require data in row major order `transpose` the matrix first.
#[inline]
#[must_use]
pub const fn to_cols_array_2d(&self) -> [[f64; 2]; 2] {
[self.x_axis.to_array(), self.y_axis.to_array()]
}
/// Creates a 2x2 matrix with its diagonal set to `diagonal` and all other entries set to 0.
#[doc(alias = "scale")]
#[inline]
#[must_use]
pub const fn from_diagonal(diagonal: DVec2) -> Self {
Self::new(diagonal.x, 0.0, 0.0, diagonal.y)
}
/// Creates a 2x2 matrix containing the combining non-uniform `scale` and rotation of
/// `angle` (in radians).
#[inline]
#[must_use]
pub fn from_scale_angle(scale: DVec2, angle: f64) -> Self {
let (sin, cos) = math::sin_cos(angle);
Self::new(cos * scale.x, sin * scale.x, -sin * scale.y, cos * scale.y)
}
/// Creates a 2x2 matrix containing a rotation of `angle` (in radians).
#[inline]
#[must_use]
pub fn from_angle(angle: f64) -> Self {
let (sin, cos) = math::sin_cos(angle);
Self::new(cos, sin, -sin, cos)
}
/// Creates a 2x2 matrix from a 3x3 matrix, discarding the 2nd row and column.
#[inline]
#[must_use]
pub fn from_mat3(m: DMat3) -> Self {
Self::from_cols(m.x_axis.xy(), m.y_axis.xy())
}
/// Creates a 2x2 matrix from the minor of the given 3x3 matrix, discarding the `i`th column
/// and `j`th row.
///
/// # Panics
///
/// Panics if `i` or `j` is greater than 2.
#[inline]
#[must_use]
pub fn from_mat3_minor(m: DMat3, i: usize, j: usize) -> Self {
match (i, j) {
(0, 0) => Self::from_cols(m.y_axis.yz(), m.z_axis.yz()),
(0, 1) => Self::from_cols(m.y_axis.xz(), m.z_axis.xz()),
(0, 2) => Self::from_cols(m.y_axis.xy(), m.z_axis.xy()),
(1, 0) => Self::from_cols(m.x_axis.yz(), m.z_axis.yz()),
(1, 1) => Self::from_cols(m.x_axis.xz(), m.z_axis.xz()),
(1, 2) => Self::from_cols(m.x_axis.xy(), m.z_axis.xy()),
(2, 0) => Self::from_cols(m.x_axis.yz(), m.y_axis.yz()),
(2, 1) => Self::from_cols(m.x_axis.xz(), m.y_axis.xz()),
(2, 2) => Self::from_cols(m.x_axis.xy(), m.y_axis.xy()),
_ => panic!("index out of bounds"),
}
}
/// Creates a 2x2 matrix from the first 4 values in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 4 elements long.
#[inline]
#[must_use]
pub const fn from_cols_slice(slice: &[f64]) -> Self {
Self::new(slice[0], slice[1], slice[2], slice[3])
}
/// Writes the columns of `self` to the first 4 elements in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 4 elements long.
#[inline]
pub fn write_cols_to_slice(self, slice: &mut [f64]) {
slice[0] = self.x_axis.x;
slice[1] = self.x_axis.y;
slice[2] = self.y_axis.x;
slice[3] = self.y_axis.y;
}
/// Returns the matrix column for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 1.
#[inline]
#[must_use]
pub fn col(&self, index: usize) -> DVec2 {
match index {
0 => self.x_axis,
1 => self.y_axis,
_ => panic!("index out of bounds"),
}
}
/// Returns a mutable reference to the matrix column for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 1.
#[inline]
pub fn col_mut(&mut self, index: usize) -> &mut DVec2 {
match index {
0 => &mut self.x_axis,
1 => &mut self.y_axis,
_ => panic!("index out of bounds"),
}
}
/// Returns the matrix row for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 1.
#[inline]
#[must_use]
pub fn row(&self, index: usize) -> DVec2 {
match index {
0 => DVec2::new(self.x_axis.x, self.y_axis.x),
1 => DVec2::new(self.x_axis.y, self.y_axis.y),
_ => panic!("index out of bounds"),
}
}
/// Returns `true` if, and only if, all elements are finite.
/// If any element is either `NaN`, positive or negative infinity, this will return `false`.
#[inline]
#[must_use]
pub fn is_finite(&self) -> bool {
self.x_axis.is_finite() && self.y_axis.is_finite()
}
/// Returns `true` if any elements are `NaN`.
#[inline]
#[must_use]
pub fn is_nan(&self) -> bool {
self.x_axis.is_nan() || self.y_axis.is_nan()
}
/// Returns the transpose of `self`.
#[inline]
#[must_use]
pub fn transpose(&self) -> Self {
Self {
x_axis: DVec2::new(self.x_axis.x, self.y_axis.x),
y_axis: DVec2::new(self.x_axis.y, self.y_axis.y),
}
}
/// Returns the determinant of `self`.
#[inline]
#[must_use]
pub fn determinant(&self) -> f64 {
self.x_axis.x * self.y_axis.y - self.x_axis.y * self.y_axis.x
}
/// Returns the inverse of `self`.
///
/// If the matrix is not invertible the returned matrix will be invalid.
///
/// # Panics
///
/// Will panic if the determinant of `self` is zero when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn inverse(&self) -> Self {
let inv_det = {
let det = self.determinant();
glam_assert!(det != 0.0);
det.recip()
};
Self::new(
self.y_axis.y * inv_det,
self.x_axis.y * -inv_det,
self.y_axis.x * -inv_det,
self.x_axis.x * inv_det,
)
}
/// Transforms a 2D vector.
#[inline]
#[must_use]
pub fn mul_vec2(&self, rhs: DVec2) -> DVec2 {
#[allow(clippy::suspicious_operation_groupings)]
DVec2::new(
(self.x_axis.x * rhs.x) + (self.y_axis.x * rhs.y),
(self.x_axis.y * rhs.x) + (self.y_axis.y * rhs.y),
)
}
/// Multiplies two 2x2 matrices.
#[inline]
#[must_use]
pub fn mul_mat2(&self, rhs: &Self) -> Self {
Self::from_cols(self.mul(rhs.x_axis), self.mul(rhs.y_axis))
}
/// Adds two 2x2 matrices.
#[inline]
#[must_use]
pub fn add_mat2(&self, rhs: &Self) -> Self {
Self::from_cols(self.x_axis.add(rhs.x_axis), self.y_axis.add(rhs.y_axis))
}
/// Subtracts two 2x2 matrices.
#[inline]
#[must_use]
pub fn sub_mat2(&self, rhs: &Self) -> Self {
Self::from_cols(self.x_axis.sub(rhs.x_axis), self.y_axis.sub(rhs.y_axis))
}
/// Multiplies a 2x2 matrix by a scalar.
#[inline]
#[must_use]
pub fn mul_scalar(&self, rhs: f64) -> Self {
Self::from_cols(self.x_axis.mul(rhs), self.y_axis.mul(rhs))
}
/// Divides a 2x2 matrix by a scalar.
#[inline]
#[must_use]
pub fn div_scalar(&self, rhs: f64) -> Self {
let rhs = DVec2::splat(rhs);
Self::from_cols(self.x_axis.div(rhs), self.y_axis.div(rhs))
}
/// Returns true if the absolute difference of all elements between `self` and `rhs`
/// is less than or equal to `max_abs_diff`.
///
/// This can be used to compare if two matrices contain similar elements. It works best
/// when comparing with a known value. The `max_abs_diff` that should be used used
/// depends on the values being compared against.
///
/// For more see
/// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
#[inline]
#[must_use]
pub fn abs_diff_eq(&self, rhs: Self, max_abs_diff: f64) -> bool {
self.x_axis.abs_diff_eq(rhs.x_axis, max_abs_diff)
&& self.y_axis.abs_diff_eq(rhs.y_axis, max_abs_diff)
}
/// Takes the absolute value of each element in `self`
#[inline]
#[must_use]
pub fn abs(&self) -> Self {
Self::from_cols(self.x_axis.abs(), self.y_axis.abs())
}
#[inline]
pub fn as_mat2(&self) -> Mat2 {
Mat2::from_cols(self.x_axis.as_vec2(), self.y_axis.as_vec2())
}
}
impl Default for DMat2 {
#[inline]
fn default() -> Self {
Self::IDENTITY
}
}
impl Add<DMat2> for DMat2 {
type Output = Self;
#[inline]
fn add(self, rhs: Self) -> Self::Output {
self.add_mat2(&rhs)
}
}
impl AddAssign<DMat2> for DMat2 {
#[inline]
fn add_assign(&mut self, rhs: Self) {
*self = self.add_mat2(&rhs);
}
}
impl Sub<DMat2> for DMat2 {
type Output = Self;
#[inline]
fn sub(self, rhs: Self) -> Self::Output {
self.sub_mat2(&rhs)
}
}
impl SubAssign<DMat2> for DMat2 {
#[inline]
fn sub_assign(&mut self, rhs: Self) {
*self = self.sub_mat2(&rhs);
}
}
impl Neg for DMat2 {
type Output = Self;
#[inline]
fn neg(self) -> Self::Output {
Self::from_cols(self.x_axis.neg(), self.y_axis.neg())
}
}
impl Mul<DMat2> for DMat2 {
type Output = Self;
#[inline]
fn mul(self, rhs: Self) -> Self::Output {
self.mul_mat2(&rhs)
}
}
impl MulAssign<DMat2> for DMat2 {
#[inline]
fn mul_assign(&mut self, rhs: Self) {
*self = self.mul_mat2(&rhs);
}
}
impl Mul<DVec2> for DMat2 {
type Output = DVec2;
#[inline]
fn mul(self, rhs: DVec2) -> Self::Output {
self.mul_vec2(rhs)
}
}
impl Mul<DMat2> for f64 {
type Output = DMat2;
#[inline]
fn mul(self, rhs: DMat2) -> Self::Output {
rhs.mul_scalar(self)
}
}
impl Mul<f64> for DMat2 {
type Output = Self;
#[inline]
fn mul(self, rhs: f64) -> Self::Output {
self.mul_scalar(rhs)
}
}
impl MulAssign<f64> for DMat2 {
#[inline]
fn mul_assign(&mut self, rhs: f64) {
*self = self.mul_scalar(rhs);
}
}
impl Div<DMat2> for f64 {
type Output = DMat2;
#[inline]
fn div(self, rhs: DMat2) -> Self::Output {
rhs.div_scalar(self)
}
}
impl Div<f64> for DMat2 {
type Output = Self;
#[inline]
fn div(self, rhs: f64) -> Self::Output {
self.div_scalar(rhs)
}
}
impl DivAssign<f64> for DMat2 {
#[inline]
fn div_assign(&mut self, rhs: f64) {
*self = self.div_scalar(rhs);
}
}
impl Sum<Self> for DMat2 {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Self::ZERO, Self::add)
}
}
impl<'a> Sum<&'a Self> for DMat2 {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
}
}
impl Product for DMat2 {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Self::IDENTITY, Self::mul)
}
}
impl<'a> Product<&'a Self> for DMat2 {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::IDENTITY, |a, &b| Self::mul(a, b))
}
}
impl PartialEq for DMat2 {
#[inline]
fn eq(&self, rhs: &Self) -> bool {
self.x_axis.eq(&rhs.x_axis) && self.y_axis.eq(&rhs.y_axis)
}
}
#[cfg(not(target_arch = "spirv"))]
impl AsRef<[f64; 4]> for DMat2 {
#[inline]
fn as_ref(&self) -> &[f64; 4] {
unsafe { &*(self as *const Self as *const [f64; 4]) }
}
}
#[cfg(not(target_arch = "spirv"))]
impl AsMut<[f64; 4]> for DMat2 {
#[inline]
fn as_mut(&mut self) -> &mut [f64; 4] {
unsafe { &mut *(self as *mut Self as *mut [f64; 4]) }
}
}
impl fmt::Debug for DMat2 {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct(stringify!(DMat2))
.field("x_axis", &self.x_axis)
.field("y_axis", &self.y_axis)
.finish()
}
}
impl fmt::Display for DMat2 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(p) = f.precision() {
write!(f, "[{:.*}, {:.*}]", p, self.x_axis, p, self.y_axis)
} else {
write!(f, "[{}, {}]", self.x_axis, self.y_axis)
}
}
}
+850
View File
@@ -0,0 +1,850 @@
// Generated from mat.rs.tera template. Edit the template, not the generated file.
use crate::{
euler::{FromEuler, ToEuler},
f64::math,
swizzles::*,
DMat2, DMat4, DQuat, DVec2, DVec3, EulerRot, Mat3,
};
use core::fmt;
use core::iter::{Product, Sum};
use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
/// Creates a 3x3 matrix from three column vectors.
#[inline(always)]
#[must_use]
pub const fn dmat3(x_axis: DVec3, y_axis: DVec3, z_axis: DVec3) -> DMat3 {
DMat3::from_cols(x_axis, y_axis, z_axis)
}
/// A 3x3 column major matrix.
///
/// This 3x3 matrix type features convenience methods for creating and using linear and
/// affine transformations. If you are primarily dealing with 2D affine transformations the
/// [`DAffine2`](crate::DAffine2) type is much faster and more space efficient than
/// using a 3x3 matrix.
///
/// Linear transformations including 3D rotation and scale can be created using methods
/// such as [`Self::from_diagonal()`], [`Self::from_quat()`], [`Self::from_axis_angle()`],
/// [`Self::from_rotation_x()`], [`Self::from_rotation_y()`], or
/// [`Self::from_rotation_z()`].
///
/// The resulting matrices can be use to transform 3D vectors using regular vector
/// multiplication.
///
/// Affine transformations including 2D translation, rotation and scale can be created
/// using methods such as [`Self::from_translation()`], [`Self::from_angle()`],
/// [`Self::from_scale()`] and [`Self::from_scale_angle_translation()`].
///
/// The [`Self::transform_point2()`] and [`Self::transform_vector2()`] convenience methods
/// are provided for performing affine transforms on 2D vectors and points. These multiply
/// 2D inputs as 3D vectors with an implicit `z` value of `1` for points and `0` for
/// vectors respectively. These methods assume that `Self` contains a valid affine
/// transform.
#[derive(Clone, Copy)]
#[repr(C)]
pub struct DMat3 {
pub x_axis: DVec3,
pub y_axis: DVec3,
pub z_axis: DVec3,
}
impl DMat3 {
/// A 3x3 matrix with all elements set to `0.0`.
pub const ZERO: Self = Self::from_cols(DVec3::ZERO, DVec3::ZERO, DVec3::ZERO);
/// A 3x3 identity matrix, where all diagonal elements are `1`, and all off-diagonal elements are `0`.
pub const IDENTITY: Self = Self::from_cols(DVec3::X, DVec3::Y, DVec3::Z);
/// All NAN:s.
pub const NAN: Self = Self::from_cols(DVec3::NAN, DVec3::NAN, DVec3::NAN);
#[allow(clippy::too_many_arguments)]
#[inline(always)]
#[must_use]
const fn new(
m00: f64,
m01: f64,
m02: f64,
m10: f64,
m11: f64,
m12: f64,
m20: f64,
m21: f64,
m22: f64,
) -> Self {
Self {
x_axis: DVec3::new(m00, m01, m02),
y_axis: DVec3::new(m10, m11, m12),
z_axis: DVec3::new(m20, m21, m22),
}
}
/// Creates a 3x3 matrix from three column vectors.
#[inline(always)]
#[must_use]
pub const fn from_cols(x_axis: DVec3, y_axis: DVec3, z_axis: DVec3) -> Self {
Self {
x_axis,
y_axis,
z_axis,
}
}
/// Creates a 3x3 matrix from a `[f64; 9]` array stored in column major order.
/// If your data is stored in row major you will need to `transpose` the returned
/// matrix.
#[inline]
#[must_use]
pub const fn from_cols_array(m: &[f64; 9]) -> Self {
Self::new(m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8])
}
/// Creates a `[f64; 9]` array storing data in column major order.
/// If you require data in row major order `transpose` the matrix first.
#[inline]
#[must_use]
pub const fn to_cols_array(&self) -> [f64; 9] {
[
self.x_axis.x,
self.x_axis.y,
self.x_axis.z,
self.y_axis.x,
self.y_axis.y,
self.y_axis.z,
self.z_axis.x,
self.z_axis.y,
self.z_axis.z,
]
}
/// Creates a 3x3 matrix from a `[[f64; 3]; 3]` 3D array stored in column major order.
/// If your data is in row major order you will need to `transpose` the returned
/// matrix.
#[inline]
#[must_use]
pub const fn from_cols_array_2d(m: &[[f64; 3]; 3]) -> Self {
Self::from_cols(
DVec3::from_array(m[0]),
DVec3::from_array(m[1]),
DVec3::from_array(m[2]),
)
}
/// Creates a `[[f64; 3]; 3]` 3D array storing data in column major order.
/// If you require data in row major order `transpose` the matrix first.
#[inline]
#[must_use]
pub const fn to_cols_array_2d(&self) -> [[f64; 3]; 3] {
[
self.x_axis.to_array(),
self.y_axis.to_array(),
self.z_axis.to_array(),
]
}
/// Creates a 3x3 matrix with its diagonal set to `diagonal` and all other entries set to 0.
#[doc(alias = "scale")]
#[inline]
#[must_use]
pub const fn from_diagonal(diagonal: DVec3) -> Self {
Self::new(
diagonal.x, 0.0, 0.0, 0.0, diagonal.y, 0.0, 0.0, 0.0, diagonal.z,
)
}
/// Creates a 3x3 matrix from a 4x4 matrix, discarding the 4th row and column.
#[inline]
#[must_use]
pub fn from_mat4(m: DMat4) -> Self {
Self::from_cols(
DVec3::from_vec4(m.x_axis),
DVec3::from_vec4(m.y_axis),
DVec3::from_vec4(m.z_axis),
)
}
/// Creates a 3x3 matrix from the minor of the given 4x4 matrix, discarding the `i`th column
/// and `j`th row.
///
/// # Panics
///
/// Panics if `i` or `j` is greater than 3.
#[inline]
#[must_use]
pub fn from_mat4_minor(m: DMat4, i: usize, j: usize) -> Self {
match (i, j) {
(0, 0) => Self::from_cols(m.y_axis.yzw(), m.z_axis.yzw(), m.w_axis.yzw()),
(0, 1) => Self::from_cols(m.y_axis.xzw(), m.z_axis.xzw(), m.w_axis.xzw()),
(0, 2) => Self::from_cols(m.y_axis.xyw(), m.z_axis.xyw(), m.w_axis.xyw()),
(0, 3) => Self::from_cols(m.y_axis.xyz(), m.z_axis.xyz(), m.w_axis.xyz()),
(1, 0) => Self::from_cols(m.x_axis.yzw(), m.z_axis.yzw(), m.w_axis.yzw()),
(1, 1) => Self::from_cols(m.x_axis.xzw(), m.z_axis.xzw(), m.w_axis.xzw()),
(1, 2) => Self::from_cols(m.x_axis.xyw(), m.z_axis.xyw(), m.w_axis.xyw()),
(1, 3) => Self::from_cols(m.x_axis.xyz(), m.z_axis.xyz(), m.w_axis.xyz()),
(2, 0) => Self::from_cols(m.x_axis.yzw(), m.y_axis.yzw(), m.w_axis.yzw()),
(2, 1) => Self::from_cols(m.x_axis.xzw(), m.y_axis.xzw(), m.w_axis.xzw()),
(2, 2) => Self::from_cols(m.x_axis.xyw(), m.y_axis.xyw(), m.w_axis.xyw()),
(2, 3) => Self::from_cols(m.x_axis.xyz(), m.y_axis.xyz(), m.w_axis.xyz()),
(3, 0) => Self::from_cols(m.x_axis.yzw(), m.y_axis.yzw(), m.z_axis.yzw()),
(3, 1) => Self::from_cols(m.x_axis.xzw(), m.y_axis.xzw(), m.z_axis.xzw()),
(3, 2) => Self::from_cols(m.x_axis.xyw(), m.y_axis.xyw(), m.z_axis.xyw()),
(3, 3) => Self::from_cols(m.x_axis.xyz(), m.y_axis.xyz(), m.z_axis.xyz()),
_ => panic!("index out of bounds"),
}
}
/// Creates a 3D rotation matrix from the given quaternion.
///
/// # Panics
///
/// Will panic if `rotation` is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn from_quat(rotation: DQuat) -> Self {
glam_assert!(rotation.is_normalized());
let x2 = rotation.x + rotation.x;
let y2 = rotation.y + rotation.y;
let z2 = rotation.z + rotation.z;
let xx = rotation.x * x2;
let xy = rotation.x * y2;
let xz = rotation.x * z2;
let yy = rotation.y * y2;
let yz = rotation.y * z2;
let zz = rotation.z * z2;
let wx = rotation.w * x2;
let wy = rotation.w * y2;
let wz = rotation.w * z2;
Self::from_cols(
DVec3::new(1.0 - (yy + zz), xy + wz, xz - wy),
DVec3::new(xy - wz, 1.0 - (xx + zz), yz + wx),
DVec3::new(xz + wy, yz - wx, 1.0 - (xx + yy)),
)
}
/// Creates a 3D rotation matrix from a normalized rotation `axis` and `angle` (in
/// radians).
///
/// # Panics
///
/// Will panic if `axis` is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn from_axis_angle(axis: DVec3, angle: f64) -> Self {
glam_assert!(axis.is_normalized());
let (sin, cos) = math::sin_cos(angle);
let (xsin, ysin, zsin) = axis.mul(sin).into();
let (x, y, z) = axis.into();
let (x2, y2, z2) = axis.mul(axis).into();
let omc = 1.0 - cos;
let xyomc = x * y * omc;
let xzomc = x * z * omc;
let yzomc = y * z * omc;
Self::from_cols(
DVec3::new(x2 * omc + cos, xyomc + zsin, xzomc - ysin),
DVec3::new(xyomc - zsin, y2 * omc + cos, yzomc + xsin),
DVec3::new(xzomc + ysin, yzomc - xsin, z2 * omc + cos),
)
}
/// Creates a 3D rotation matrix from the given euler rotation sequence and the angles (in
/// radians).
#[inline]
#[must_use]
pub fn from_euler(order: EulerRot, a: f64, b: f64, c: f64) -> Self {
Self::from_euler_angles(order, a, b, c)
}
/// Extract Euler angles with the given Euler rotation order.
///
/// Note if the input matrix contains scales, shears, or other non-rotation transformations then
/// the resulting Euler angles will be ill-defined.
///
/// # Panics
///
/// Will panic if any input matrix column is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn to_euler(&self, order: EulerRot) -> (f64, f64, f64) {
glam_assert!(
self.x_axis.is_normalized()
&& self.y_axis.is_normalized()
&& self.z_axis.is_normalized()
);
self.to_euler_angles(order)
}
/// Creates a 3D rotation matrix from `angle` (in radians) around the x axis.
#[inline]
#[must_use]
pub fn from_rotation_x(angle: f64) -> Self {
let (sina, cosa) = math::sin_cos(angle);
Self::from_cols(
DVec3::X,
DVec3::new(0.0, cosa, sina),
DVec3::new(0.0, -sina, cosa),
)
}
/// Creates a 3D rotation matrix from `angle` (in radians) around the y axis.
#[inline]
#[must_use]
pub fn from_rotation_y(angle: f64) -> Self {
let (sina, cosa) = math::sin_cos(angle);
Self::from_cols(
DVec3::new(cosa, 0.0, -sina),
DVec3::Y,
DVec3::new(sina, 0.0, cosa),
)
}
/// Creates a 3D rotation matrix from `angle` (in radians) around the z axis.
#[inline]
#[must_use]
pub fn from_rotation_z(angle: f64) -> Self {
let (sina, cosa) = math::sin_cos(angle);
Self::from_cols(
DVec3::new(cosa, sina, 0.0),
DVec3::new(-sina, cosa, 0.0),
DVec3::Z,
)
}
/// Creates an affine transformation matrix from the given 2D `translation`.
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
#[inline]
#[must_use]
pub fn from_translation(translation: DVec2) -> Self {
Self::from_cols(
DVec3::X,
DVec3::Y,
DVec3::new(translation.x, translation.y, 1.0),
)
}
/// Creates an affine transformation matrix from the given 2D rotation `angle` (in
/// radians).
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
#[inline]
#[must_use]
pub fn from_angle(angle: f64) -> Self {
let (sin, cos) = math::sin_cos(angle);
Self::from_cols(
DVec3::new(cos, sin, 0.0),
DVec3::new(-sin, cos, 0.0),
DVec3::Z,
)
}
/// Creates an affine transformation matrix from the given 2D `scale`, rotation `angle` (in
/// radians) and `translation`.
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
#[inline]
#[must_use]
pub fn from_scale_angle_translation(scale: DVec2, angle: f64, translation: DVec2) -> Self {
let (sin, cos) = math::sin_cos(angle);
Self::from_cols(
DVec3::new(cos * scale.x, sin * scale.x, 0.0),
DVec3::new(-sin * scale.y, cos * scale.y, 0.0),
DVec3::new(translation.x, translation.y, 1.0),
)
}
/// Creates an affine transformation matrix from the given non-uniform 2D `scale`.
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
///
/// # Panics
///
/// Will panic if all elements of `scale` are zero when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn from_scale(scale: DVec2) -> Self {
// Do not panic as long as any component is non-zero
glam_assert!(scale.cmpne(DVec2::ZERO).any());
Self::from_cols(
DVec3::new(scale.x, 0.0, 0.0),
DVec3::new(0.0, scale.y, 0.0),
DVec3::Z,
)
}
/// Creates an affine transformation matrix from the given 2x2 matrix.
///
/// The resulting matrix can be used to transform 2D points and vectors. See
/// [`Self::transform_point2()`] and [`Self::transform_vector2()`].
#[inline]
pub fn from_mat2(m: DMat2) -> Self {
Self::from_cols((m.x_axis, 0.0).into(), (m.y_axis, 0.0).into(), DVec3::Z)
}
/// Creates a 3x3 matrix from the first 9 values in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 9 elements long.
#[inline]
#[must_use]
pub const fn from_cols_slice(slice: &[f64]) -> Self {
Self::new(
slice[0], slice[1], slice[2], slice[3], slice[4], slice[5], slice[6], slice[7],
slice[8],
)
}
/// Writes the columns of `self` to the first 9 elements in `slice`.
///
/// # Panics
///
/// Panics if `slice` is less than 9 elements long.
#[inline]
pub fn write_cols_to_slice(self, slice: &mut [f64]) {
slice[0] = self.x_axis.x;
slice[1] = self.x_axis.y;
slice[2] = self.x_axis.z;
slice[3] = self.y_axis.x;
slice[4] = self.y_axis.y;
slice[5] = self.y_axis.z;
slice[6] = self.z_axis.x;
slice[7] = self.z_axis.y;
slice[8] = self.z_axis.z;
}
/// Returns the matrix column for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 2.
#[inline]
#[must_use]
pub fn col(&self, index: usize) -> DVec3 {
match index {
0 => self.x_axis,
1 => self.y_axis,
2 => self.z_axis,
_ => panic!("index out of bounds"),
}
}
/// Returns a mutable reference to the matrix column for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 2.
#[inline]
pub fn col_mut(&mut self, index: usize) -> &mut DVec3 {
match index {
0 => &mut self.x_axis,
1 => &mut self.y_axis,
2 => &mut self.z_axis,
_ => panic!("index out of bounds"),
}
}
/// Returns the matrix row for the given `index`.
///
/// # Panics
///
/// Panics if `index` is greater than 2.
#[inline]
#[must_use]
pub fn row(&self, index: usize) -> DVec3 {
match index {
0 => DVec3::new(self.x_axis.x, self.y_axis.x, self.z_axis.x),
1 => DVec3::new(self.x_axis.y, self.y_axis.y, self.z_axis.y),
2 => DVec3::new(self.x_axis.z, self.y_axis.z, self.z_axis.z),
_ => panic!("index out of bounds"),
}
}
/// Returns `true` if, and only if, all elements are finite.
/// If any element is either `NaN`, positive or negative infinity, this will return `false`.
#[inline]
#[must_use]
pub fn is_finite(&self) -> bool {
self.x_axis.is_finite() && self.y_axis.is_finite() && self.z_axis.is_finite()
}
/// Returns `true` if any elements are `NaN`.
#[inline]
#[must_use]
pub fn is_nan(&self) -> bool {
self.x_axis.is_nan() || self.y_axis.is_nan() || self.z_axis.is_nan()
}
/// Returns the transpose of `self`.
#[inline]
#[must_use]
pub fn transpose(&self) -> Self {
Self {
x_axis: DVec3::new(self.x_axis.x, self.y_axis.x, self.z_axis.x),
y_axis: DVec3::new(self.x_axis.y, self.y_axis.y, self.z_axis.y),
z_axis: DVec3::new(self.x_axis.z, self.y_axis.z, self.z_axis.z),
}
}
/// Returns the determinant of `self`.
#[inline]
#[must_use]
pub fn determinant(&self) -> f64 {
self.z_axis.dot(self.x_axis.cross(self.y_axis))
}
/// Returns the inverse of `self`.
///
/// If the matrix is not invertible the returned matrix will be invalid.
///
/// # Panics
///
/// Will panic if the determinant of `self` is zero when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn inverse(&self) -> Self {
let tmp0 = self.y_axis.cross(self.z_axis);
let tmp1 = self.z_axis.cross(self.x_axis);
let tmp2 = self.x_axis.cross(self.y_axis);
let det = self.z_axis.dot(tmp2);
glam_assert!(det != 0.0);
let inv_det = DVec3::splat(det.recip());
Self::from_cols(tmp0.mul(inv_det), tmp1.mul(inv_det), tmp2.mul(inv_det)).transpose()
}
/// Transforms the given 2D vector as a point.
///
/// This is the equivalent of multiplying `rhs` as a 3D vector where `z` is `1`.
///
/// This method assumes that `self` contains a valid affine transform.
///
/// # Panics
///
/// Will panic if the 2nd row of `self` is not `(0, 0, 1)` when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn transform_point2(&self, rhs: DVec2) -> DVec2 {
glam_assert!(self.row(2).abs_diff_eq(DVec3::Z, 1e-6));
DMat2::from_cols(self.x_axis.xy(), self.y_axis.xy()) * rhs + self.z_axis.xy()
}
/// Rotates the given 2D vector.
///
/// This is the equivalent of multiplying `rhs` as a 3D vector where `z` is `0`.
///
/// This method assumes that `self` contains a valid affine transform.
///
/// # Panics
///
/// Will panic if the 2nd row of `self` is not `(0, 0, 1)` when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn transform_vector2(&self, rhs: DVec2) -> DVec2 {
glam_assert!(self.row(2).abs_diff_eq(DVec3::Z, 1e-6));
DMat2::from_cols(self.x_axis.xy(), self.y_axis.xy()) * rhs
}
/// Transforms a 3D vector.
#[inline]
#[must_use]
pub fn mul_vec3(&self, rhs: DVec3) -> DVec3 {
let mut res = self.x_axis.mul(rhs.x);
res = res.add(self.y_axis.mul(rhs.y));
res = res.add(self.z_axis.mul(rhs.z));
res
}
/// Multiplies two 3x3 matrices.
#[inline]
#[must_use]
pub fn mul_mat3(&self, rhs: &Self) -> Self {
Self::from_cols(
self.mul(rhs.x_axis),
self.mul(rhs.y_axis),
self.mul(rhs.z_axis),
)
}
/// Adds two 3x3 matrices.
#[inline]
#[must_use]
pub fn add_mat3(&self, rhs: &Self) -> Self {
Self::from_cols(
self.x_axis.add(rhs.x_axis),
self.y_axis.add(rhs.y_axis),
self.z_axis.add(rhs.z_axis),
)
}
/// Subtracts two 3x3 matrices.
#[inline]
#[must_use]
pub fn sub_mat3(&self, rhs: &Self) -> Self {
Self::from_cols(
self.x_axis.sub(rhs.x_axis),
self.y_axis.sub(rhs.y_axis),
self.z_axis.sub(rhs.z_axis),
)
}
/// Multiplies a 3x3 matrix by a scalar.
#[inline]
#[must_use]
pub fn mul_scalar(&self, rhs: f64) -> Self {
Self::from_cols(
self.x_axis.mul(rhs),
self.y_axis.mul(rhs),
self.z_axis.mul(rhs),
)
}
/// Divides a 3x3 matrix by a scalar.
#[inline]
#[must_use]
pub fn div_scalar(&self, rhs: f64) -> Self {
let rhs = DVec3::splat(rhs);
Self::from_cols(
self.x_axis.div(rhs),
self.y_axis.div(rhs),
self.z_axis.div(rhs),
)
}
/// Returns true if the absolute difference of all elements between `self` and `rhs`
/// is less than or equal to `max_abs_diff`.
///
/// This can be used to compare if two matrices contain similar elements. It works best
/// when comparing with a known value. The `max_abs_diff` that should be used used
/// depends on the values being compared against.
///
/// For more see
/// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
#[inline]
#[must_use]
pub fn abs_diff_eq(&self, rhs: Self, max_abs_diff: f64) -> bool {
self.x_axis.abs_diff_eq(rhs.x_axis, max_abs_diff)
&& self.y_axis.abs_diff_eq(rhs.y_axis, max_abs_diff)
&& self.z_axis.abs_diff_eq(rhs.z_axis, max_abs_diff)
}
/// Takes the absolute value of each element in `self`
#[inline]
#[must_use]
pub fn abs(&self) -> Self {
Self::from_cols(self.x_axis.abs(), self.y_axis.abs(), self.z_axis.abs())
}
#[inline]
pub fn as_mat3(&self) -> Mat3 {
Mat3::from_cols(
self.x_axis.as_vec3(),
self.y_axis.as_vec3(),
self.z_axis.as_vec3(),
)
}
}
impl Default for DMat3 {
#[inline]
fn default() -> Self {
Self::IDENTITY
}
}
impl Add<DMat3> for DMat3 {
type Output = Self;
#[inline]
fn add(self, rhs: Self) -> Self::Output {
self.add_mat3(&rhs)
}
}
impl AddAssign<DMat3> for DMat3 {
#[inline]
fn add_assign(&mut self, rhs: Self) {
*self = self.add_mat3(&rhs);
}
}
impl Sub<DMat3> for DMat3 {
type Output = Self;
#[inline]
fn sub(self, rhs: Self) -> Self::Output {
self.sub_mat3(&rhs)
}
}
impl SubAssign<DMat3> for DMat3 {
#[inline]
fn sub_assign(&mut self, rhs: Self) {
*self = self.sub_mat3(&rhs);
}
}
impl Neg for DMat3 {
type Output = Self;
#[inline]
fn neg(self) -> Self::Output {
Self::from_cols(self.x_axis.neg(), self.y_axis.neg(), self.z_axis.neg())
}
}
impl Mul<DMat3> for DMat3 {
type Output = Self;
#[inline]
fn mul(self, rhs: Self) -> Self::Output {
self.mul_mat3(&rhs)
}
}
impl MulAssign<DMat3> for DMat3 {
#[inline]
fn mul_assign(&mut self, rhs: Self) {
*self = self.mul_mat3(&rhs);
}
}
impl Mul<DVec3> for DMat3 {
type Output = DVec3;
#[inline]
fn mul(self, rhs: DVec3) -> Self::Output {
self.mul_vec3(rhs)
}
}
impl Mul<DMat3> for f64 {
type Output = DMat3;
#[inline]
fn mul(self, rhs: DMat3) -> Self::Output {
rhs.mul_scalar(self)
}
}
impl Mul<f64> for DMat3 {
type Output = Self;
#[inline]
fn mul(self, rhs: f64) -> Self::Output {
self.mul_scalar(rhs)
}
}
impl MulAssign<f64> for DMat3 {
#[inline]
fn mul_assign(&mut self, rhs: f64) {
*self = self.mul_scalar(rhs);
}
}
impl Div<DMat3> for f64 {
type Output = DMat3;
#[inline]
fn div(self, rhs: DMat3) -> Self::Output {
rhs.div_scalar(self)
}
}
impl Div<f64> for DMat3 {
type Output = Self;
#[inline]
fn div(self, rhs: f64) -> Self::Output {
self.div_scalar(rhs)
}
}
impl DivAssign<f64> for DMat3 {
#[inline]
fn div_assign(&mut self, rhs: f64) {
*self = self.div_scalar(rhs);
}
}
impl Sum<Self> for DMat3 {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Self::ZERO, Self::add)
}
}
impl<'a> Sum<&'a Self> for DMat3 {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
}
}
impl Product for DMat3 {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Self::IDENTITY, Self::mul)
}
}
impl<'a> Product<&'a Self> for DMat3 {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::IDENTITY, |a, &b| Self::mul(a, b))
}
}
impl PartialEq for DMat3 {
#[inline]
fn eq(&self, rhs: &Self) -> bool {
self.x_axis.eq(&rhs.x_axis) && self.y_axis.eq(&rhs.y_axis) && self.z_axis.eq(&rhs.z_axis)
}
}
#[cfg(not(target_arch = "spirv"))]
impl AsRef<[f64; 9]> for DMat3 {
#[inline]
fn as_ref(&self) -> &[f64; 9] {
unsafe { &*(self as *const Self as *const [f64; 9]) }
}
}
#[cfg(not(target_arch = "spirv"))]
impl AsMut<[f64; 9]> for DMat3 {
#[inline]
fn as_mut(&mut self) -> &mut [f64; 9] {
unsafe { &mut *(self as *mut Self as *mut [f64; 9]) }
}
}
impl fmt::Debug for DMat3 {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_struct(stringify!(DMat3))
.field("x_axis", &self.x_axis)
.field("y_axis", &self.y_axis)
.field("z_axis", &self.z_axis)
.finish()
}
}
impl fmt::Display for DMat3 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(p) = f.precision() {
write!(
f,
"[{:.*}, {:.*}, {:.*}]",
p, self.x_axis, p, self.y_axis, p, self.z_axis
)
} else {
write!(f, "[{}, {}, {}]", self.x_axis, self.y_axis, self.z_axis)
}
}
}
+1396
View File
File diff suppressed because it is too large Load Diff
+940
View File
@@ -0,0 +1,940 @@
// Generated from quat.rs.tera template. Edit the template, not the generated file.
use crate::{
euler::{EulerRot, FromEuler, ToEuler},
f64::math,
DMat3, DMat4, DVec2, DVec3, DVec4, Quat,
};
use core::fmt;
use core::iter::{Product, Sum};
use core::ops::{Add, Div, Mul, MulAssign, Neg, Sub};
/// Creates a quaternion from `x`, `y`, `z` and `w` values.
///
/// This should generally not be called manually unless you know what you are doing. Use
/// one of the other constructors instead such as `identity` or `from_axis_angle`.
#[inline]
#[must_use]
pub const fn dquat(x: f64, y: f64, z: f64, w: f64) -> DQuat {
DQuat::from_xyzw(x, y, z, w)
}
/// A quaternion representing an orientation.
///
/// This quaternion is intended to be of unit length but may denormalize due to
/// floating point "error creep" which can occur when successive quaternion
/// operations are applied.
#[derive(Clone, Copy)]
#[cfg_attr(not(target_arch = "spirv"), repr(C))]
#[cfg_attr(target_arch = "spirv", repr(simd))]
pub struct DQuat {
pub x: f64,
pub y: f64,
pub z: f64,
pub w: f64,
}
impl DQuat {
/// All zeros.
const ZERO: Self = Self::from_array([0.0; 4]);
/// The identity quaternion. Corresponds to no rotation.
pub const IDENTITY: Self = Self::from_xyzw(0.0, 0.0, 0.0, 1.0);
/// All NANs.
pub const NAN: Self = Self::from_array([f64::NAN; 4]);
/// Creates a new rotation quaternion.
///
/// This should generally not be called manually unless you know what you are doing.
/// Use one of the other constructors instead such as `identity` or `from_axis_angle`.
///
/// `from_xyzw` is mostly used by unit tests and `serde` deserialization.
///
/// # Preconditions
///
/// This function does not check if the input is normalized, it is up to the user to
/// provide normalized input or to normalized the resulting quaternion.
#[inline(always)]
#[must_use]
pub const fn from_xyzw(x: f64, y: f64, z: f64, w: f64) -> Self {
Self { x, y, z, w }
}
/// Creates a rotation quaternion from an array.
///
/// # Preconditions
///
/// This function does not check if the input is normalized, it is up to the user to
/// provide normalized input or to normalized the resulting quaternion.
#[inline]
#[must_use]
pub const fn from_array(a: [f64; 4]) -> Self {
Self::from_xyzw(a[0], a[1], a[2], a[3])
}
/// Creates a new rotation quaternion from a 4D vector.
///
/// # Preconditions
///
/// This function does not check if the input is normalized, it is up to the user to
/// provide normalized input or to normalized the resulting quaternion.
#[inline]
#[must_use]
pub const fn from_vec4(v: DVec4) -> Self {
Self {
x: v.x,
y: v.y,
z: v.z,
w: v.w,
}
}
/// Creates a rotation quaternion from a slice.
///
/// # Preconditions
///
/// This function does not check if the input is normalized, it is up to the user to
/// provide normalized input or to normalized the resulting quaternion.
///
/// # Panics
///
/// Panics if `slice` length is less than 4.
#[inline]
#[must_use]
pub fn from_slice(slice: &[f64]) -> Self {
Self::from_xyzw(slice[0], slice[1], slice[2], slice[3])
}
/// Writes the quaternion to an unaligned slice.
///
/// # Panics
///
/// Panics if `slice` length is less than 4.
#[inline]
pub fn write_to_slice(self, slice: &mut [f64]) {
slice[0] = self.x;
slice[1] = self.y;
slice[2] = self.z;
slice[3] = self.w;
}
/// Create a quaternion for a normalized rotation `axis` and `angle` (in radians).
///
/// The axis must be a unit vector.
///
/// # Panics
///
/// Will panic if `axis` is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn from_axis_angle(axis: DVec3, angle: f64) -> Self {
glam_assert!(axis.is_normalized());
let (s, c) = math::sin_cos(angle * 0.5);
let v = axis * s;
Self::from_xyzw(v.x, v.y, v.z, c)
}
/// Create a quaternion that rotates `v.length()` radians around `v.normalize()`.
///
/// `from_scaled_axis(Vec3::ZERO)` results in the identity quaternion.
#[inline]
#[must_use]
pub fn from_scaled_axis(v: DVec3) -> Self {
let length = v.length();
if length == 0.0 {
Self::IDENTITY
} else {
Self::from_axis_angle(v / length, length)
}
}
/// Creates a quaternion from the `angle` (in radians) around the x axis.
#[inline]
#[must_use]
pub fn from_rotation_x(angle: f64) -> Self {
let (s, c) = math::sin_cos(angle * 0.5);
Self::from_xyzw(s, 0.0, 0.0, c)
}
/// Creates a quaternion from the `angle` (in radians) around the y axis.
#[inline]
#[must_use]
pub fn from_rotation_y(angle: f64) -> Self {
let (s, c) = math::sin_cos(angle * 0.5);
Self::from_xyzw(0.0, s, 0.0, c)
}
/// Creates a quaternion from the `angle` (in radians) around the z axis.
#[inline]
#[must_use]
pub fn from_rotation_z(angle: f64) -> Self {
let (s, c) = math::sin_cos(angle * 0.5);
Self::from_xyzw(0.0, 0.0, s, c)
}
/// Creates a quaternion from the given Euler rotation sequence and the angles (in radians).
#[inline]
#[must_use]
pub fn from_euler(euler: EulerRot, a: f64, b: f64, c: f64) -> Self {
Self::from_euler_angles(euler, a, b, c)
}
/// From the columns of a 3x3 rotation matrix.
///
/// Note if the input axes contain scales, shears, or other non-rotation transformations then
/// the output of this function is ill-defined.
///
/// # Panics
///
/// Will panic if any axis is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub(crate) fn from_rotation_axes(x_axis: DVec3, y_axis: DVec3, z_axis: DVec3) -> Self {
glam_assert!(x_axis.is_normalized() && y_axis.is_normalized() && z_axis.is_normalized());
// Based on https://github.com/microsoft/DirectXMath `XMQuaternionRotationMatrix`
let (m00, m01, m02) = x_axis.into();
let (m10, m11, m12) = y_axis.into();
let (m20, m21, m22) = z_axis.into();
if m22 <= 0.0 {
// x^2 + y^2 >= z^2 + w^2
let dif10 = m11 - m00;
let omm22 = 1.0 - m22;
if dif10 <= 0.0 {
// x^2 >= y^2
let four_xsq = omm22 - dif10;
let inv4x = 0.5 / math::sqrt(four_xsq);
Self::from_xyzw(
four_xsq * inv4x,
(m01 + m10) * inv4x,
(m02 + m20) * inv4x,
(m12 - m21) * inv4x,
)
} else {
// y^2 >= x^2
let four_ysq = omm22 + dif10;
let inv4y = 0.5 / math::sqrt(four_ysq);
Self::from_xyzw(
(m01 + m10) * inv4y,
four_ysq * inv4y,
(m12 + m21) * inv4y,
(m20 - m02) * inv4y,
)
}
} else {
// z^2 + w^2 >= x^2 + y^2
let sum10 = m11 + m00;
let opm22 = 1.0 + m22;
if sum10 <= 0.0 {
// z^2 >= w^2
let four_zsq = opm22 - sum10;
let inv4z = 0.5 / math::sqrt(four_zsq);
Self::from_xyzw(
(m02 + m20) * inv4z,
(m12 + m21) * inv4z,
four_zsq * inv4z,
(m01 - m10) * inv4z,
)
} else {
// w^2 >= z^2
let four_wsq = opm22 + sum10;
let inv4w = 0.5 / math::sqrt(four_wsq);
Self::from_xyzw(
(m12 - m21) * inv4w,
(m20 - m02) * inv4w,
(m01 - m10) * inv4w,
four_wsq * inv4w,
)
}
}
}
/// Creates a quaternion from a 3x3 rotation matrix.
///
/// Note if the input matrix contain scales, shears, or other non-rotation transformations then
/// the resulting quaternion will be ill-defined.
///
/// # Panics
///
/// Will panic if any input matrix column is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn from_mat3(mat: &DMat3) -> Self {
Self::from_rotation_axes(mat.x_axis, mat.y_axis, mat.z_axis)
}
/// Creates a quaternion from the upper 3x3 rotation matrix inside a homogeneous 4x4 matrix.
///
/// Note if the upper 3x3 matrix contain scales, shears, or other non-rotation transformations
/// then the resulting quaternion will be ill-defined.
///
/// # Panics
///
/// Will panic if any column of the upper 3x3 rotation matrix is not normalized when
/// `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn from_mat4(mat: &DMat4) -> Self {
Self::from_rotation_axes(
mat.x_axis.truncate(),
mat.y_axis.truncate(),
mat.z_axis.truncate(),
)
}
/// Gets the minimal rotation for transforming `from` to `to`. The rotation is in the
/// plane spanned by the two vectors. Will rotate at most 180 degrees.
///
/// The inputs must be unit vectors.
///
/// `from_rotation_arc(from, to) * from ≈ to`.
///
/// For near-singular cases (from≈to and from≈-to) the current implementation
/// is only accurate to about 0.001 (for `f32`).
///
/// # Panics
///
/// Will panic if `from` or `to` are not normalized when `glam_assert` is enabled.
#[must_use]
pub fn from_rotation_arc(from: DVec3, to: DVec3) -> Self {
glam_assert!(from.is_normalized());
glam_assert!(to.is_normalized());
const ONE_MINUS_EPS: f64 = 1.0 - 2.0 * f64::EPSILON;
let dot = from.dot(to);
if dot > ONE_MINUS_EPS {
// 0° singularity: from ≈ to
Self::IDENTITY
} else if dot < -ONE_MINUS_EPS {
// 180° singularity: from ≈ -to
use core::f64::consts::PI; // half a turn = 𝛕/2 = 180°
Self::from_axis_angle(from.any_orthonormal_vector(), PI)
} else {
let c = from.cross(to);
Self::from_xyzw(c.x, c.y, c.z, 1.0 + dot).normalize()
}
}
/// Gets the minimal rotation for transforming `from` to either `to` or `-to`. This means
/// that the resulting quaternion will rotate `from` so that it is colinear with `to`.
///
/// The rotation is in the plane spanned by the two vectors. Will rotate at most 90
/// degrees.
///
/// The inputs must be unit vectors.
///
/// `to.dot(from_rotation_arc_colinear(from, to) * from).abs() ≈ 1`.
///
/// # Panics
///
/// Will panic if `from` or `to` are not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn from_rotation_arc_colinear(from: DVec3, to: DVec3) -> Self {
if from.dot(to) < 0.0 {
Self::from_rotation_arc(from, -to)
} else {
Self::from_rotation_arc(from, to)
}
}
/// Gets the minimal rotation for transforming `from` to `to`. The resulting rotation is
/// around the z axis. Will rotate at most 180 degrees.
///
/// The inputs must be unit vectors.
///
/// `from_rotation_arc_2d(from, to) * from ≈ to`.
///
/// For near-singular cases (from≈to and from≈-to) the current implementation
/// is only accurate to about 0.001 (for `f32`).
///
/// # Panics
///
/// Will panic if `from` or `to` are not normalized when `glam_assert` is enabled.
#[must_use]
pub fn from_rotation_arc_2d(from: DVec2, to: DVec2) -> Self {
glam_assert!(from.is_normalized());
glam_assert!(to.is_normalized());
const ONE_MINUS_EPSILON: f64 = 1.0 - 2.0 * f64::EPSILON;
let dot = from.dot(to);
if dot > ONE_MINUS_EPSILON {
// 0° singularity: from ≈ to
Self::IDENTITY
} else if dot < -ONE_MINUS_EPSILON {
// 180° singularity: from ≈ -to
const COS_FRAC_PI_2: f64 = 0.0;
const SIN_FRAC_PI_2: f64 = 1.0;
// rotation around z by PI radians
Self::from_xyzw(0.0, 0.0, SIN_FRAC_PI_2, COS_FRAC_PI_2)
} else {
// vector3 cross where z=0
let z = from.x * to.y - to.x * from.y;
let w = 1.0 + dot;
// calculate length with x=0 and y=0 to normalize
let len_rcp = 1.0 / math::sqrt(z * z + w * w);
Self::from_xyzw(0.0, 0.0, z * len_rcp, w * len_rcp)
}
}
/// Returns the rotation axis (normalized) and angle (in radians) of `self`.
#[inline]
#[must_use]
pub fn to_axis_angle(self) -> (DVec3, f64) {
const EPSILON: f64 = 1.0e-8;
let v = DVec3::new(self.x, self.y, self.z);
let length = v.length();
if length >= EPSILON {
let angle = 2.0 * math::atan2(length, self.w);
let axis = v / length;
(axis, angle)
} else {
(DVec3::X, 0.0)
}
}
/// Returns the rotation axis scaled by the rotation in radians.
#[inline]
#[must_use]
pub fn to_scaled_axis(self) -> DVec3 {
let (axis, angle) = self.to_axis_angle();
axis * angle
}
/// Returns the rotation angles for the given euler rotation sequence.
#[inline]
#[must_use]
pub fn to_euler(self, order: EulerRot) -> (f64, f64, f64) {
self.to_euler_angles(order)
}
/// `[x, y, z, w]`
#[inline]
#[must_use]
pub fn to_array(&self) -> [f64; 4] {
[self.x, self.y, self.z, self.w]
}
/// Returns the vector part of the quaternion.
#[inline]
#[must_use]
pub fn xyz(self) -> DVec3 {
DVec3::new(self.x, self.y, self.z)
}
/// Returns the quaternion conjugate of `self`. For a unit quaternion the
/// conjugate is also the inverse.
#[inline]
#[must_use]
pub fn conjugate(self) -> Self {
Self {
x: -self.x,
y: -self.y,
z: -self.z,
w: self.w,
}
}
/// Returns the inverse of a normalized quaternion.
///
/// Typically quaternion inverse returns the conjugate of a normalized quaternion.
/// Because `self` is assumed to already be unit length this method *does not* normalize
/// before returning the conjugate.
///
/// # Panics
///
/// Will panic if `self` is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn inverse(self) -> Self {
glam_assert!(self.is_normalized());
self.conjugate()
}
/// Computes the dot product of `self` and `rhs`. The dot product is
/// equal to the cosine of the angle between two quaternion rotations.
#[inline]
#[must_use]
pub fn dot(self, rhs: Self) -> f64 {
DVec4::from(self).dot(DVec4::from(rhs))
}
/// Computes the length of `self`.
#[doc(alias = "magnitude")]
#[inline]
#[must_use]
pub fn length(self) -> f64 {
DVec4::from(self).length()
}
/// Computes the squared length of `self`.
///
/// This is generally faster than `length()` as it avoids a square
/// root operation.
#[doc(alias = "magnitude2")]
#[inline]
#[must_use]
pub fn length_squared(self) -> f64 {
DVec4::from(self).length_squared()
}
/// Computes `1.0 / length()`.
///
/// For valid results, `self` must _not_ be of length zero.
#[inline]
#[must_use]
pub fn length_recip(self) -> f64 {
DVec4::from(self).length_recip()
}
/// Returns `self` normalized to length 1.0.
///
/// For valid results, `self` must _not_ be of length zero.
///
/// Panics
///
/// Will panic if `self` is zero length when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn normalize(self) -> Self {
Self::from_vec4(DVec4::from(self).normalize())
}
/// Returns `true` if, and only if, all elements are finite.
/// If any element is either `NaN`, positive or negative infinity, this will return `false`.
#[inline]
#[must_use]
pub fn is_finite(self) -> bool {
DVec4::from(self).is_finite()
}
/// Returns `true` if any elements are `NAN`.
#[inline]
#[must_use]
pub fn is_nan(self) -> bool {
DVec4::from(self).is_nan()
}
/// Returns whether `self` of length `1.0` or not.
///
/// Uses a precision threshold of `1e-6`.
#[inline]
#[must_use]
pub fn is_normalized(self) -> bool {
DVec4::from(self).is_normalized()
}
#[inline]
#[must_use]
pub fn is_near_identity(self) -> bool {
// Based on https://github.com/nfrechette/rtm `rtm::quat_near_identity`
let threshold_angle = 0.002_847_144_6;
// Because of floating point precision, we cannot represent very small rotations.
// The closest f32 to 1.0 that is not 1.0 itself yields:
// 0.99999994.acos() * 2.0 = 0.000690533954 rad
//
// An error threshold of 1.e-6 is used by default.
// (1.0 - 1.e-6).acos() * 2.0 = 0.00284714461 rad
// (1.0 - 1.e-7).acos() * 2.0 = 0.00097656250 rad
//
// We don't really care about the angle value itself, only if it's close to 0.
// This will happen whenever quat.w is close to 1.0.
// If the quat.w is close to -1.0, the angle will be near 2*PI which is close to
// a negative 0 rotation. By forcing quat.w to be positive, we'll end up with
// the shortest path.
let positive_w_angle = math::acos_approx(math::abs(self.w)) * 2.0;
positive_w_angle < threshold_angle
}
/// Returns the angle (in radians) for the minimal rotation
/// for transforming this quaternion into another.
///
/// Both quaternions must be normalized.
///
/// # Panics
///
/// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn angle_between(self, rhs: Self) -> f64 {
glam_assert!(self.is_normalized() && rhs.is_normalized());
math::acos_approx(math::abs(self.dot(rhs))) * 2.0
}
/// Rotates towards `rhs` up to `max_angle` (in radians).
///
/// When `max_angle` is `0.0`, the result will be equal to `self`. When `max_angle` is equal to
/// `self.angle_between(rhs)`, the result will be equal to `rhs`. If `max_angle` is negative,
/// rotates towards the exact opposite of `rhs`. Will not go past the target.
///
/// Both quaternions must be normalized.
///
/// # Panics
///
/// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn rotate_towards(&self, rhs: Self, max_angle: f64) -> Self {
glam_assert!(self.is_normalized() && rhs.is_normalized());
let angle = self.angle_between(rhs);
if angle <= 1e-4 {
return *self;
}
let s = (max_angle / angle).clamp(-1.0, 1.0);
self.slerp(rhs, s)
}
/// Returns true if the absolute difference of all elements between `self` and `rhs`
/// is less than or equal to `max_abs_diff`.
///
/// This can be used to compare if two quaternions contain similar elements. It works
/// best when comparing with a known value. The `max_abs_diff` that should be used used
/// depends on the values being compared against.
///
/// For more see
/// [comparing floating point numbers](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/).
#[inline]
#[must_use]
pub fn abs_diff_eq(self, rhs: Self, max_abs_diff: f64) -> bool {
DVec4::from(self).abs_diff_eq(DVec4::from(rhs), max_abs_diff)
}
#[inline(always)]
#[must_use]
fn lerp_impl(self, end: Self, s: f64) -> Self {
(self * (1.0 - s) + end * s).normalize()
}
/// Performs a linear interpolation between `self` and `rhs` based on
/// the value `s`.
///
/// When `s` is `0.0`, the result will be equal to `self`. When `s`
/// is `1.0`, the result will be equal to `rhs`.
///
/// # Panics
///
/// Will panic if `self` or `end` are not normalized when `glam_assert` is enabled.
#[doc(alias = "mix")]
#[inline]
#[must_use]
pub fn lerp(self, end: Self, s: f64) -> Self {
glam_assert!(self.is_normalized());
glam_assert!(end.is_normalized());
let dot = self.dot(end);
let bias = if dot >= 0.0 { 1.0 } else { -1.0 };
self.lerp_impl(end * bias, s)
}
/// Performs a spherical linear interpolation between `self` and `end`
/// based on the value `s`.
///
/// When `s` is `0.0`, the result will be equal to `self`. When `s`
/// is `1.0`, the result will be equal to `end`.
///
/// # Panics
///
/// Will panic if `self` or `end` are not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn slerp(self, mut end: Self, s: f64) -> Self {
// http://number-none.com/product/Understanding%20Slerp,%20Then%20Not%20Using%20It/
glam_assert!(self.is_normalized());
glam_assert!(end.is_normalized());
// Note that a rotation can be represented by two quaternions: `q` and
// `-q`. The slerp path between `q` and `end` will be different from the
// path between `-q` and `end`. One path will take the long way around and
// one will take the short way. In order to correct for this, the `dot`
// product between `self` and `end` should be positive. If the `dot`
// product is negative, slerp between `self` and `-end`.
let mut dot = self.dot(end);
if dot < 0.0 {
end = -end;
dot = -dot;
}
const DOT_THRESHOLD: f64 = 1.0 - f64::EPSILON;
if dot > DOT_THRESHOLD {
// if above threshold perform linear interpolation to avoid divide by zero
self.lerp_impl(end, s)
} else {
let theta = math::acos_approx(dot);
let scale1 = math::sin(theta * (1.0 - s));
let scale2 = math::sin(theta * s);
let theta_sin = math::sin(theta);
((self * scale1) + (end * scale2)) * (1.0 / theta_sin)
}
}
/// Multiplies a quaternion and a 3D vector, returning the rotated vector.
///
/// # Panics
///
/// Will panic if `self` is not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn mul_vec3(self, rhs: DVec3) -> DVec3 {
glam_assert!(self.is_normalized());
let w = self.w;
let b = DVec3::new(self.x, self.y, self.z);
let b2 = b.dot(b);
rhs.mul(w * w - b2)
.add(b.mul(rhs.dot(b) * 2.0))
.add(b.cross(rhs).mul(w * 2.0))
}
/// Multiplies two quaternions. If they each represent a rotation, the result will
/// represent the combined rotation.
///
/// Note that due to floating point rounding the result may not be perfectly normalized.
///
/// # Panics
///
/// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
#[inline]
#[must_use]
pub fn mul_quat(self, rhs: Self) -> Self {
let (x0, y0, z0, w0) = self.into();
let (x1, y1, z1, w1) = rhs.into();
Self::from_xyzw(
w0 * x1 + x0 * w1 + y0 * z1 - z0 * y1,
w0 * y1 - x0 * z1 + y0 * w1 + z0 * x1,
w0 * z1 + x0 * y1 - y0 * x1 + z0 * w1,
w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1,
)
}
/// Creates a quaternion from a 3x3 rotation matrix inside a 3D affine transform.
///
/// Note if the input affine matrix contain scales, shears, or other non-rotation
/// transformations then the resulting quaternion will be ill-defined.
///
/// # Panics
///
/// Will panic if any input affine matrix column is not normalized when `glam_assert` is
/// enabled.
#[inline]
#[must_use]
pub fn from_affine3(a: &crate::DAffine3) -> Self {
#[allow(clippy::useless_conversion)]
Self::from_rotation_axes(
a.matrix3.x_axis.into(),
a.matrix3.y_axis.into(),
a.matrix3.z_axis.into(),
)
}
#[inline]
#[must_use]
pub fn as_quat(self) -> Quat {
Quat::from_xyzw(self.x as f32, self.y as f32, self.z as f32, self.w as f32)
}
}
impl fmt::Debug for DQuat {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.debug_tuple(stringify!(DQuat))
.field(&self.x)
.field(&self.y)
.field(&self.z)
.field(&self.w)
.finish()
}
}
impl fmt::Display for DQuat {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(p) = f.precision() {
write!(
f,
"[{:.*}, {:.*}, {:.*}, {:.*}]",
p, self.x, p, self.y, p, self.z, p, self.w
)
} else {
write!(f, "[{}, {}, {}, {}]", self.x, self.y, self.z, self.w)
}
}
}
impl Add<DQuat> for DQuat {
type Output = Self;
/// Adds two quaternions.
///
/// The sum is not guaranteed to be normalized.
///
/// Note that addition is not the same as combining the rotations represented by the
/// two quaternions! That corresponds to multiplication.
#[inline]
fn add(self, rhs: Self) -> Self {
Self::from_vec4(DVec4::from(self) + DVec4::from(rhs))
}
}
impl Sub<DQuat> for DQuat {
type Output = Self;
/// Subtracts the `rhs` quaternion from `self`.
///
/// The difference is not guaranteed to be normalized.
#[inline]
fn sub(self, rhs: Self) -> Self {
Self::from_vec4(DVec4::from(self) - DVec4::from(rhs))
}
}
impl Mul<f64> for DQuat {
type Output = Self;
/// Multiplies a quaternion by a scalar value.
///
/// The product is not guaranteed to be normalized.
#[inline]
fn mul(self, rhs: f64) -> Self {
Self::from_vec4(DVec4::from(self) * rhs)
}
}
impl Div<f64> for DQuat {
type Output = Self;
/// Divides a quaternion by a scalar value.
/// The quotient is not guaranteed to be normalized.
#[inline]
fn div(self, rhs: f64) -> Self {
Self::from_vec4(DVec4::from(self) / rhs)
}
}
impl Mul<DQuat> for DQuat {
type Output = Self;
/// Multiplies two quaternions. If they each represent a rotation, the result will
/// represent the combined rotation.
///
/// Note that due to floating point rounding the result may not be perfectly
/// normalized.
///
/// # Panics
///
/// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
#[inline]
fn mul(self, rhs: Self) -> Self {
self.mul_quat(rhs)
}
}
impl MulAssign<DQuat> for DQuat {
/// Multiplies two quaternions. If they each represent a rotation, the result will
/// represent the combined rotation.
///
/// Note that due to floating point rounding the result may not be perfectly
/// normalized.
///
/// # Panics
///
/// Will panic if `self` or `rhs` are not normalized when `glam_assert` is enabled.
#[inline]
fn mul_assign(&mut self, rhs: Self) {
*self = self.mul_quat(rhs);
}
}
impl Mul<DVec3> for DQuat {
type Output = DVec3;
/// Multiplies a quaternion and a 3D vector, returning the rotated vector.
///
/// # Panics
///
/// Will panic if `self` is not normalized when `glam_assert` is enabled.
#[inline]
fn mul(self, rhs: DVec3) -> Self::Output {
self.mul_vec3(rhs)
}
}
impl Neg for DQuat {
type Output = Self;
#[inline]
fn neg(self) -> Self {
self * -1.0
}
}
impl Default for DQuat {
#[inline]
fn default() -> Self {
Self::IDENTITY
}
}
impl PartialEq for DQuat {
#[inline]
fn eq(&self, rhs: &Self) -> bool {
DVec4::from(*self).eq(&DVec4::from(*rhs))
}
}
#[cfg(not(target_arch = "spirv"))]
impl AsRef<[f64; 4]> for DQuat {
#[inline]
fn as_ref(&self) -> &[f64; 4] {
unsafe { &*(self as *const Self as *const [f64; 4]) }
}
}
impl Sum<Self> for DQuat {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Self::ZERO, Self::add)
}
}
impl<'a> Sum<&'a Self> for DQuat {
fn sum<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::ZERO, |a, &b| Self::add(a, b))
}
}
impl Product for DQuat {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = Self>,
{
iter.fold(Self::IDENTITY, Self::mul)
}
}
impl<'a> Product<&'a Self> for DQuat {
fn product<I>(iter: I) -> Self
where
I: Iterator<Item = &'a Self>,
{
iter.fold(Self::IDENTITY, |a, &b| Self::mul(a, b))
}
}
impl From<DQuat> for DVec4 {
#[inline]
fn from(q: DQuat) -> Self {
Self::new(q.x, q.y, q.z, q.w)
}
}
impl From<DQuat> for (f64, f64, f64, f64) {
#[inline]
fn from(q: DQuat) -> Self {
(q.x, q.y, q.z, q.w)
}
}
impl From<DQuat> for [f64; 4] {
#[inline]
fn from(q: DQuat) -> Self {
[q.x, q.y, q.z, q.w]
}
}
+1856
View File
File diff suppressed because it is too large Load Diff
+1951
View File
File diff suppressed because it is too large Load Diff
+2010
View File
File diff suppressed because it is too large Load Diff
+21
View File
@@ -0,0 +1,21 @@
// Generated from float.rs.tera template. Edit the template, not the generated file.
use crate::float::FloatExt;
impl FloatExt for f64 {
#[inline]
fn lerp(self, rhs: f64, t: f64) -> f64 {
self + (rhs - self) * t
}
#[inline]
fn inverse_lerp(a: f64, b: f64, v: f64) -> f64 {
(v - a) / (b - a)
}
#[inline]
fn remap(self, in_start: f64, in_end: f64, out_start: f64, out_end: f64) -> f64 {
let t = f64::inverse_lerp(in_start, in_end, self);
f64::lerp(out_start, out_end, t)
}
}
+205
View File
@@ -0,0 +1,205 @@
#[cfg(any(feature = "libm", all(feature = "nostd-libm", not(feature = "std"))))]
mod libm_math {
#[inline(always)]
pub(crate) fn abs(f: f64) -> f64 {
libm::fabs(f)
}
#[inline(always)]
pub(crate) fn acos_approx(f: f64) -> f64 {
libm::acos(f.clamp(-1.0, 1.0))
}
#[inline(always)]
pub(crate) fn atan2(f: f64, other: f64) -> f64 {
libm::atan2(f, other)
}
#[inline(always)]
pub(crate) fn sin(f: f64) -> f64 {
libm::sin(f)
}
#[inline(always)]
pub(crate) fn sin_cos(f: f64) -> (f64, f64) {
libm::sincos(f)
}
#[inline(always)]
pub(crate) fn tan(f: f64) -> f64 {
libm::tan(f)
}
#[inline(always)]
pub(crate) fn sqrt(f: f64) -> f64 {
libm::sqrt(f)
}
#[inline(always)]
pub(crate) fn copysign(f: f64, sign: f64) -> f64 {
libm::copysign(f, sign)
}
#[inline(always)]
pub(crate) fn signum(f: f64) -> f64 {
if f.is_nan() {
f64::NAN
} else {
copysign(1.0, f)
}
}
#[inline(always)]
pub(crate) fn round(f: f64) -> f64 {
libm::round(f)
}
#[inline(always)]
pub(crate) fn trunc(f: f64) -> f64 {
libm::trunc(f)
}
#[inline(always)]
pub(crate) fn ceil(f: f64) -> f64 {
libm::ceil(f)
}
#[inline(always)]
pub(crate) fn floor(f: f64) -> f64 {
libm::floor(f)
}
#[inline(always)]
pub(crate) fn exp(f: f64) -> f64 {
libm::exp(f)
}
#[inline(always)]
pub(crate) fn powf(f: f64, n: f64) -> f64 {
libm::pow(f, n)
}
#[inline(always)]
pub(crate) fn mul_add(a: f64, b: f64, c: f64) -> f64 {
libm::fma(a, b, c)
}
#[inline]
pub fn div_euclid(a: f64, b: f64) -> f64 {
// Based on https://doc.rust-lang.org/src/std/f64.rs.html#293
let q = libm::trunc(a / b);
if a % b < 0.0 {
return if b > 0.0 { q - 1.0 } else { q + 1.0 };
}
q
}
#[inline]
pub fn rem_euclid(a: f64, b: f64) -> f64 {
let r = a % b;
if r < 0.0 {
r + abs(b)
} else {
r
}
}
}
#[cfg(all(not(feature = "libm"), feature = "std"))]
mod std_math {
#[inline(always)]
pub(crate) fn abs(f: f64) -> f64 {
f64::abs(f)
}
#[inline(always)]
pub(crate) fn acos_approx(f: f64) -> f64 {
f64::acos(f64::clamp(f, -1.0, 1.0))
}
#[inline(always)]
pub(crate) fn atan2(f: f64, other: f64) -> f64 {
f64::atan2(f, other)
}
#[inline(always)]
pub(crate) fn sin(f: f64) -> f64 {
f64::sin(f)
}
#[inline(always)]
pub(crate) fn sin_cos(f: f64) -> (f64, f64) {
f64::sin_cos(f)
}
#[inline(always)]
pub(crate) fn tan(f: f64) -> f64 {
f64::tan(f)
}
#[inline(always)]
pub(crate) fn sqrt(f: f64) -> f64 {
f64::sqrt(f)
}
#[inline(always)]
pub(crate) fn copysign(f: f64, sign: f64) -> f64 {
f64::copysign(f, sign)
}
#[inline(always)]
pub(crate) fn signum(f: f64) -> f64 {
f64::signum(f)
}
#[inline(always)]
pub(crate) fn round(f: f64) -> f64 {
f64::round(f)
}
#[inline(always)]
pub(crate) fn trunc(f: f64) -> f64 {
f64::trunc(f)
}
#[inline(always)]
pub(crate) fn ceil(f: f64) -> f64 {
f64::ceil(f)
}
#[inline(always)]
pub(crate) fn floor(f: f64) -> f64 {
f64::floor(f)
}
#[inline(always)]
pub(crate) fn exp(f: f64) -> f64 {
f64::exp(f)
}
#[inline(always)]
pub(crate) fn powf(f: f64, n: f64) -> f64 {
f64::powf(f, n)
}
#[inline(always)]
pub(crate) fn mul_add(a: f64, b: f64, c: f64) -> f64 {
f64::mul_add(a, b, c)
}
#[inline]
pub fn div_euclid(a: f64, b: f64) -> f64 {
f64::div_euclid(a, b)
}
#[inline]
pub fn rem_euclid(a: f64, b: f64) -> f64 {
f64::rem_euclid(a, b)
}
}
#[cfg(any(feature = "libm", all(feature = "nostd-libm", not(feature = "std"))))]
pub(crate) use libm_math::*;
#[cfg(all(not(feature = "libm"), feature = "std"))]
pub(crate) use std_math::*;
+17
View File
@@ -0,0 +1,17 @@
#[cfg(feature = "approx")]
pub mod impl_approx;
#[cfg(feature = "bytemuck")]
pub mod impl_bytemuck;
#[cfg(feature = "mint")]
pub mod impl_mint;
#[cfg(feature = "rand")]
pub mod impl_rand;
#[cfg(feature = "serde")]
pub mod impl_serde;
#[cfg(feature = "rkyv")]
pub mod impl_rkyv;
+212
View File
@@ -0,0 +1,212 @@
use crate::{
Affine2, Affine3A, DAffine2, DAffine3, DMat2, DMat3, DMat4, DQuat, DVec2, DVec3, DVec4, Mat2,
Mat3, Mat3A, Mat4, Quat, Vec2, Vec3, Vec3A, Vec4,
};
use approx::{AbsDiffEq, RelativeEq, UlpsEq};
macro_rules! impl_approx_as_ref {
($prim:ident, $type:ty) => {
impl AbsDiffEq for $type {
type Epsilon = <$prim as AbsDiffEq>::Epsilon;
fn default_epsilon() -> Self::Epsilon {
$prim::default_epsilon()
}
fn abs_diff_eq(&self, other: &Self, epsilon: Self::Epsilon) -> bool {
self.as_ref().abs_diff_eq(other.as_ref(), epsilon)
}
}
impl RelativeEq for $type {
fn default_max_relative() -> Self::Epsilon {
$prim::default_max_relative()
}
fn relative_eq(
&self,
other: &Self,
epsilon: Self::Epsilon,
max_relative: Self::Epsilon,
) -> bool {
self.as_ref()
.relative_eq(other.as_ref(), epsilon, max_relative)
}
}
impl UlpsEq for $type {
fn default_max_ulps() -> u32 {
$prim::default_max_ulps()
}
fn ulps_eq(&self, other: &Self, epsilon: Self::Epsilon, max_ulps: u32) -> bool {
self.as_ref().ulps_eq(other.as_ref(), epsilon, max_ulps)
}
}
};
}
macro_rules! impl_approx_xzy_axes {
($prim:ident, $type:ty) => {
impl AbsDiffEq for $type {
type Epsilon = <$prim as AbsDiffEq>::Epsilon;
fn default_epsilon() -> Self::Epsilon {
$prim::default_epsilon()
}
fn abs_diff_eq(&self, other: &Self, epsilon: Self::Epsilon) -> bool {
AbsDiffEq::abs_diff_eq(&self.x_axis, &other.x_axis, epsilon)
&& AbsDiffEq::abs_diff_eq(&self.y_axis, &other.y_axis, epsilon)
&& AbsDiffEq::abs_diff_eq(&self.z_axis, &other.z_axis, epsilon)
}
}
impl RelativeEq for $type {
fn default_max_relative() -> Self::Epsilon {
$prim::default_max_relative()
}
fn relative_eq(
&self,
other: &Self,
epsilon: Self::Epsilon,
max_relative: Self::Epsilon,
) -> bool {
RelativeEq::relative_eq(&self.x_axis, &other.x_axis, epsilon, max_relative)
&& RelativeEq::relative_eq(&self.y_axis, &other.y_axis, epsilon, max_relative)
&& RelativeEq::relative_eq(&self.z_axis, &other.z_axis, epsilon, max_relative)
}
}
impl UlpsEq for $type {
fn default_max_ulps() -> u32 {
$prim::default_max_ulps()
}
fn ulps_eq(&self, other: &Self, epsilon: Self::Epsilon, max_ulps: u32) -> bool {
UlpsEq::ulps_eq(&self.x_axis, &other.x_axis, epsilon, max_ulps)
&& UlpsEq::ulps_eq(&self.y_axis, &other.y_axis, epsilon, max_ulps)
&& UlpsEq::ulps_eq(&self.z_axis, &other.z_axis, epsilon, max_ulps)
}
}
};
}
macro_rules! impl_approx_xzyw_axes {
($prim:ident, $type:ty) => {
impl AbsDiffEq for $type {
type Epsilon = <$prim as AbsDiffEq>::Epsilon;
fn default_epsilon() -> Self::Epsilon {
$prim::default_epsilon()
}
fn abs_diff_eq(&self, other: &Self, epsilon: Self::Epsilon) -> bool {
AbsDiffEq::abs_diff_eq(&self.x_axis, &other.x_axis, epsilon)
&& AbsDiffEq::abs_diff_eq(&self.y_axis, &other.y_axis, epsilon)
&& AbsDiffEq::abs_diff_eq(&self.z_axis, &other.z_axis, epsilon)
&& AbsDiffEq::abs_diff_eq(&self.w_axis, &other.w_axis, epsilon)
}
}
impl RelativeEq for $type {
fn default_max_relative() -> Self::Epsilon {
$prim::default_max_relative()
}
fn relative_eq(
&self,
other: &Self,
epsilon: Self::Epsilon,
max_relative: Self::Epsilon,
) -> bool {
RelativeEq::relative_eq(&self.x_axis, &other.x_axis, epsilon, max_relative)
&& RelativeEq::relative_eq(&self.y_axis, &other.y_axis, epsilon, max_relative)
&& RelativeEq::relative_eq(&self.z_axis, &other.z_axis, epsilon, max_relative)
&& RelativeEq::relative_eq(&self.w_axis, &other.w_axis, epsilon, max_relative)
}
}
impl UlpsEq for $type {
fn default_max_ulps() -> u32 {
$prim::default_max_ulps()
}
fn ulps_eq(&self, other: &Self, epsilon: Self::Epsilon, max_ulps: u32) -> bool {
UlpsEq::ulps_eq(&self.x_axis, &other.x_axis, epsilon, max_ulps)
&& UlpsEq::ulps_eq(&self.y_axis, &other.y_axis, epsilon, max_ulps)
&& UlpsEq::ulps_eq(&self.z_axis, &other.z_axis, epsilon, max_ulps)
&& UlpsEq::ulps_eq(&self.w_axis, &other.w_axis, epsilon, max_ulps)
}
}
};
}
impl_approx_as_ref!(f32, Mat2);
impl_approx_as_ref!(f32, Mat3);
impl_approx_as_ref!(f32, Mat4);
impl_approx_as_ref!(f32, Quat);
impl_approx_as_ref!(f32, Vec2);
impl_approx_as_ref!(f32, Vec3);
impl_approx_as_ref!(f32, Vec4);
impl_approx_as_ref!(f32, Vec3A);
impl_approx_xzy_axes!(f32, Affine2);
impl_approx_xzyw_axes!(f32, Affine3A);
impl_approx_xzy_axes!(f32, Mat3A);
impl_approx_xzy_axes!(f64, DAffine2);
impl_approx_xzyw_axes!(f64, DAffine3);
impl_approx_as_ref!(f64, DMat2);
impl_approx_as_ref!(f64, DMat3);
impl_approx_as_ref!(f64, DMat4);
impl_approx_as_ref!(f64, DQuat);
impl_approx_as_ref!(f64, DVec2);
impl_approx_as_ref!(f64, DVec3);
impl_approx_as_ref!(f64, DVec4);
#[cfg(test)]
mod test {
use crate::*;
use approx::*;
macro_rules! impl_approx_test {
($prim:ident, $type:ident, $ones:expr) => {
let one_eps = $ones * $type::default_epsilon();
let two_eps = one_eps + one_eps;
let one_ulp = $ones * $prim::from_bits($prim::to_bits(1.0) + 1);
let four_ulp = $ones * $prim::from_bits($prim::to_bits(1.0) + 16);
approx::assert_abs_diff_eq!($ones, $ones);
approx::assert_abs_diff_eq!($ones, $ones + one_eps);
approx::assert_abs_diff_eq!($ones, $ones - one_eps);
approx::assert_abs_diff_ne!($ones, $ones + two_eps);
approx::assert_abs_diff_ne!($ones, $ones - two_eps);
approx::assert_relative_eq!($ones, $ones);
approx::assert_relative_ne!($ones, $ones - $ones);
// defaults to 4 ulps and I have no idea how to pass other parameters to this macro :)
approx::assert_ulps_eq!($ones, one_ulp);
approx::assert_ulps_ne!($ones, four_ulp);
};
($prim:ident, $type:ident) => {
impl_approx_test!($prim, $type, $type::ONE)
};
}
#[test]
fn test_approx() {
const ONESF32: [f32; 16] = [1.0; 16];
impl_approx_test!(f32, Vec2);
impl_approx_test!(f32, Vec3);
impl_approx_test!(f32, Vec3A);
impl_approx_test!(f32, Vec4);
impl_approx_test!(f32, Quat, Quat::from_slice(&ONESF32));
impl_approx_test!(f32, Mat2, Mat2::from_cols_slice(&ONESF32));
impl_approx_test!(f32, Mat3, Mat3::from_cols_slice(&ONESF32));
impl_approx_test!(f32, Mat3A, Mat3A::from_cols_slice(&ONESF32));
impl_approx_test!(f32, Mat4, Mat4::from_cols_slice(&ONESF32));
const ONESF64: [f64; 16] = [1.0; 16];
impl_approx_test!(f64, DVec2);
impl_approx_test!(f64, DVec3);
impl_approx_test!(f64, DVec4);
impl_approx_test!(f64, DQuat, DQuat::from_slice(&ONESF64));
impl_approx_test!(f64, DMat2, DMat2::from_cols_slice(&ONESF64));
impl_approx_test!(f64, DMat3, DMat3::from_cols_slice(&ONESF64));
impl_approx_test!(f64, DMat4, DMat4::from_cols_slice(&ONESF64));
}
}
+209
View File
@@ -0,0 +1,209 @@
use crate::{
Affine2, Affine3A, DAffine2, DAffine3, DMat2, DMat3, DMat4, DQuat, DVec2, DVec3, DVec4,
I16Vec2, I16Vec3, I16Vec4, I64Vec2, I64Vec3, I64Vec4, I8Vec2, I8Vec3, I8Vec4, IVec2, IVec3,
IVec4, Mat2, Mat3, Mat3A, Mat4, Quat, U16Vec2, U16Vec3, U16Vec4, U64Vec2, U64Vec3, U64Vec4,
U8Vec2, U8Vec3, U8Vec4, UVec2, UVec3, UVec4, Vec2, Vec3, Vec3A, Vec4,
};
use bytemuck::{AnyBitPattern, Pod, Zeroable};
// Affine2 contains internal padding due to Mat2 using SIMD
unsafe impl AnyBitPattern for Affine2 {}
unsafe impl Zeroable for Affine2 {}
unsafe impl AnyBitPattern for Affine3A {}
unsafe impl Zeroable for Affine3A {}
unsafe impl Pod for Mat2 {}
unsafe impl Zeroable for Mat2 {}
unsafe impl Pod for Mat3 {}
unsafe impl Zeroable for Mat3 {}
unsafe impl AnyBitPattern for Mat3A {}
unsafe impl Zeroable for Mat3A {}
unsafe impl Pod for Mat4 {}
unsafe impl Zeroable for Mat4 {}
unsafe impl Pod for Quat {}
unsafe impl Zeroable for Quat {}
unsafe impl Pod for Vec2 {}
unsafe impl Zeroable for Vec2 {}
unsafe impl Pod for Vec3 {}
unsafe impl Zeroable for Vec3 {}
unsafe impl AnyBitPattern for Vec3A {}
unsafe impl Zeroable for Vec3A {}
unsafe impl Pod for Vec4 {}
unsafe impl Zeroable for Vec4 {}
unsafe impl Pod for DAffine2 {}
unsafe impl Zeroable for DAffine2 {}
unsafe impl Pod for DAffine3 {}
unsafe impl Zeroable for DAffine3 {}
unsafe impl Pod for DMat2 {}
unsafe impl Zeroable for DMat2 {}
unsafe impl Pod for DMat3 {}
unsafe impl Zeroable for DMat3 {}
unsafe impl Pod for DMat4 {}
unsafe impl Zeroable for DMat4 {}
unsafe impl Pod for DQuat {}
unsafe impl Zeroable for DQuat {}
unsafe impl Pod for DVec2 {}
unsafe impl Zeroable for DVec2 {}
unsafe impl Pod for DVec3 {}
unsafe impl Zeroable for DVec3 {}
unsafe impl Pod for DVec4 {}
unsafe impl Zeroable for DVec4 {}
unsafe impl Pod for I8Vec2 {}
unsafe impl Zeroable for I8Vec2 {}
unsafe impl Pod for I8Vec3 {}
unsafe impl Zeroable for I8Vec3 {}
unsafe impl Pod for I8Vec4 {}
unsafe impl Zeroable for I8Vec4 {}
unsafe impl Pod for U8Vec2 {}
unsafe impl Zeroable for U8Vec2 {}
unsafe impl Pod for U8Vec3 {}
unsafe impl Zeroable for U8Vec3 {}
unsafe impl Pod for U8Vec4 {}
unsafe impl Zeroable for U8Vec4 {}
unsafe impl Pod for I16Vec2 {}
unsafe impl Zeroable for I16Vec2 {}
unsafe impl Pod for I16Vec3 {}
unsafe impl Zeroable for I16Vec3 {}
unsafe impl Pod for I16Vec4 {}
unsafe impl Zeroable for I16Vec4 {}
unsafe impl Pod for U16Vec2 {}
unsafe impl Zeroable for U16Vec2 {}
unsafe impl Pod for U16Vec3 {}
unsafe impl Zeroable for U16Vec3 {}
unsafe impl Pod for U16Vec4 {}
unsafe impl Zeroable for U16Vec4 {}
unsafe impl Pod for IVec2 {}
unsafe impl Zeroable for IVec2 {}
unsafe impl Pod for IVec3 {}
unsafe impl Zeroable for IVec3 {}
unsafe impl Pod for IVec4 {}
unsafe impl Zeroable for IVec4 {}
unsafe impl Pod for UVec2 {}
unsafe impl Zeroable for UVec2 {}
unsafe impl Pod for UVec3 {}
unsafe impl Zeroable for UVec3 {}
unsafe impl Pod for UVec4 {}
unsafe impl Zeroable for UVec4 {}
unsafe impl Pod for I64Vec2 {}
unsafe impl Zeroable for I64Vec2 {}
unsafe impl Pod for I64Vec3 {}
unsafe impl Zeroable for I64Vec3 {}
unsafe impl Pod for I64Vec4 {}
unsafe impl Zeroable for I64Vec4 {}
unsafe impl Pod for U64Vec2 {}
unsafe impl Zeroable for U64Vec2 {}
unsafe impl Pod for U64Vec3 {}
unsafe impl Zeroable for U64Vec3 {}
unsafe impl Pod for U64Vec4 {}
unsafe impl Zeroable for U64Vec4 {}
#[cfg(test)]
mod test {
use crate::{
Affine2, Affine3A, DAffine2, DAffine3, DMat2, DMat3, DMat4, DQuat, DVec2, DVec3, DVec4,
I16Vec2, I16Vec3, I16Vec4, I64Vec2, I64Vec3, I64Vec4, I8Vec2, I8Vec3, I8Vec4, IVec2, IVec3,
IVec4, Mat2, Mat3, Mat3A, Mat4, Quat, U16Vec2, U16Vec3, U16Vec4, U64Vec2, U64Vec3, U64Vec4,
U8Vec2, U8Vec3, U8Vec4, UVec2, UVec3, UVec4, Vec2, Vec3, Vec3A, Vec4,
};
use core::mem;
macro_rules! test_pod_t {
($name:ident, $t:ty) => {
#[test]
fn $name() {
let t = <$t>::default();
let b = bytemuck::bytes_of(&t);
// the below loop will fail in miri if we're doing something bad here.
for bi in b {
assert_eq!(bi, bi);
}
// should be the same address
assert_eq!(&t as *const $t as usize, b.as_ptr() as usize);
// should be the same size
assert_eq!(b.len(), mem::size_of_val(&t));
}
};
}
macro_rules! test_any_bit_pattern_t {
($name:ident, $t:ident) => {
#[test]
fn $name() {
let b = [0_u8; mem::size_of::<$t>()];
let t: $t = bytemuck::cast(b);
// should be the same size
assert_eq!(b.len(), mem::size_of_val(&t));
// should be zero
assert_eq!(t, $t::ZERO);
}
};
}
test_any_bit_pattern_t!(affine2, Affine2);
test_any_bit_pattern_t!(affine3a, Affine3A);
test_pod_t!(mat2, Mat2);
test_pod_t!(mat3, Mat3);
test_any_bit_pattern_t!(mat3a, Mat3A);
test_pod_t!(mat4, Mat4);
test_pod_t!(quat, Quat);
test_pod_t!(vec2, Vec2);
test_pod_t!(vec3, Vec3);
test_any_bit_pattern_t!(vec3a, Vec3A);
test_pod_t!(vec4, Vec4);
test_pod_t!(daffine2, DAffine2);
test_pod_t!(daffine3, DAffine3);
test_pod_t!(dmat2, DMat2);
test_pod_t!(dmat3, DMat3);
test_pod_t!(dmat4, DMat4);
test_pod_t!(dquat, DQuat);
test_pod_t!(dvec2, DVec2);
test_pod_t!(dvec3, DVec3);
test_pod_t!(dvec4, DVec4);
test_pod_t!(i8vec2, I8Vec2);
test_pod_t!(i8vec3, I8Vec3);
test_pod_t!(i8vec4, I8Vec4);
test_pod_t!(u8vec2, U8Vec2);
test_pod_t!(u8vec3, U8Vec3);
test_pod_t!(u8vec4, U8Vec4);
test_pod_t!(i16vec2, I16Vec2);
test_pod_t!(i16vec3, I16Vec3);
test_pod_t!(i16vec4, I16Vec4);
test_pod_t!(u16vec2, U16Vec2);
test_pod_t!(u16vec3, U16Vec3);
test_pod_t!(u16vec4, U16Vec4);
test_pod_t!(ivec2, IVec2);
test_pod_t!(ivec3, IVec3);
test_pod_t!(ivec4, IVec4);
test_pod_t!(uvec2, UVec2);
test_pod_t!(uvec3, UVec3);
test_pod_t!(uvec4, UVec4);
test_pod_t!(i64vec2, I64Vec2);
test_pod_t!(i64vec3, I64Vec3);
test_pod_t!(i64vec4, I64Vec4);
test_pod_t!(u64vec2, U64Vec2);
test_pod_t!(u64vec3, U64Vec3);
test_pod_t!(u64vec4, U64Vec4);
}
+536
View File
@@ -0,0 +1,536 @@
use mint::IntoMint;
use crate::{
DMat2, DMat3, DMat4, DQuat, DVec2, DVec3, DVec4, I16Vec2, I16Vec3, I16Vec4, I64Vec2, I64Vec3,
I64Vec4, I8Vec2, I8Vec3, I8Vec4, IVec2, IVec3, IVec4, Mat2, Mat3, Mat3A, Mat4, Quat, U16Vec2,
U16Vec3, U16Vec4, U64Vec2, U64Vec3, U64Vec4, U8Vec2, U8Vec3, U8Vec4, UVec2, UVec3, UVec4, Vec2,
Vec3, Vec3A, Vec4,
};
macro_rules! impl_vec_types {
($t:ty, $vec2:ty, $vec3:ty, $vec4:ty) => {
impl From<mint::Point2<$t>> for $vec2 {
fn from(v: mint::Point2<$t>) -> Self {
Self::new(v.x, v.y)
}
}
impl From<$vec2> for mint::Point2<$t> {
fn from(v: $vec2) -> Self {
Self { x: v.x, y: v.y }
}
}
impl From<mint::Vector2<$t>> for $vec2 {
fn from(v: mint::Vector2<$t>) -> Self {
Self::new(v.x, v.y)
}
}
impl From<$vec2> for mint::Vector2<$t> {
fn from(v: $vec2) -> Self {
Self { x: v.x, y: v.y }
}
}
impl IntoMint for $vec2 {
type MintType = mint::Vector2<$t>;
}
impl From<mint::Point3<$t>> for $vec3 {
fn from(v: mint::Point3<$t>) -> Self {
Self::new(v.x, v.y, v.z)
}
}
impl From<$vec3> for mint::Point3<$t> {
fn from(v: $vec3) -> Self {
Self {
x: v.x,
y: v.y,
z: v.z,
}
}
}
impl From<mint::Vector3<$t>> for $vec3 {
fn from(v: mint::Vector3<$t>) -> Self {
Self::new(v.x, v.y, v.z)
}
}
impl From<$vec3> for mint::Vector3<$t> {
fn from(v: $vec3) -> Self {
Self {
x: v.x,
y: v.y,
z: v.z,
}
}
}
impl IntoMint for $vec3 {
type MintType = mint::Vector3<$t>;
}
impl From<mint::Vector4<$t>> for $vec4 {
fn from(v: mint::Vector4<$t>) -> Self {
Self::new(v.x, v.y, v.z, v.w)
}
}
impl From<$vec4> for mint::Vector4<$t> {
fn from(v: $vec4) -> Self {
Self {
x: v.x,
y: v.y,
z: v.z,
w: v.w,
}
}
}
impl IntoMint for $vec4 {
type MintType = mint::Vector4<$t>;
}
};
}
macro_rules! impl_float_types {
($t:ty, $mat2:ty, $mat3:ty, $mat4:ty, $quat:ty, $vec2:ty, $vec3:ty, $vec4:ty) => {
impl_vec_types!($t, $vec2, $vec3, $vec4);
impl From<mint::Quaternion<$t>> for $quat {
fn from(q: mint::Quaternion<$t>) -> Self {
Self::from_xyzw(q.v.x, q.v.y, q.v.z, q.s)
}
}
impl From<$quat> for mint::Quaternion<$t> {
fn from(q: $quat) -> Self {
Self {
s: q.w,
v: mint::Vector3 {
x: q.x,
y: q.y,
z: q.z,
},
}
}
}
impl IntoMint for $quat {
type MintType = mint::Quaternion<$t>;
}
impl From<mint::RowMatrix2<$t>> for $mat2 {
fn from(m: mint::RowMatrix2<$t>) -> Self {
Self::from_cols(m.x.into(), m.y.into()).transpose()
}
}
impl From<$mat2> for mint::RowMatrix2<$t> {
fn from(m: $mat2) -> Self {
let mt = m.transpose();
Self {
x: mt.x_axis.into(),
y: mt.y_axis.into(),
}
}
}
impl From<mint::ColumnMatrix2<$t>> for $mat2 {
fn from(m: mint::ColumnMatrix2<$t>) -> Self {
Self::from_cols(m.x.into(), m.y.into())
}
}
impl From<$mat2> for mint::ColumnMatrix2<$t> {
fn from(m: $mat2) -> Self {
Self {
x: m.x_axis.into(),
y: m.y_axis.into(),
}
}
}
impl IntoMint for $mat2 {
type MintType = mint::ColumnMatrix2<$t>;
}
impl From<mint::RowMatrix3<$t>> for $mat3 {
fn from(m: mint::RowMatrix3<$t>) -> Self {
Self::from_cols(m.x.into(), m.y.into(), m.z.into()).transpose()
}
}
impl From<$mat3> for mint::RowMatrix3<$t> {
fn from(m: $mat3) -> Self {
let mt = m.transpose();
Self {
x: mt.x_axis.into(),
y: mt.y_axis.into(),
z: mt.z_axis.into(),
}
}
}
impl From<mint::ColumnMatrix3<$t>> for $mat3 {
fn from(m: mint::ColumnMatrix3<$t>) -> Self {
Self::from_cols(m.x.into(), m.y.into(), m.z.into())
}
}
impl From<$mat3> for mint::ColumnMatrix3<$t> {
fn from(m: $mat3) -> Self {
Self {
x: m.x_axis.into(),
y: m.y_axis.into(),
z: m.z_axis.into(),
}
}
}
impl IntoMint for $mat3 {
type MintType = mint::ColumnMatrix3<$t>;
}
impl From<mint::RowMatrix4<$t>> for $mat4 {
fn from(m: mint::RowMatrix4<$t>) -> Self {
Self::from_cols(m.x.into(), m.y.into(), m.z.into(), m.w.into()).transpose()
}
}
impl From<$mat4> for mint::RowMatrix4<$t> {
fn from(m: $mat4) -> Self {
let mt = m.transpose();
Self {
x: mt.x_axis.into(),
y: mt.y_axis.into(),
z: mt.z_axis.into(),
w: mt.w_axis.into(),
}
}
}
impl From<mint::ColumnMatrix4<$t>> for $mat4 {
fn from(m: mint::ColumnMatrix4<$t>) -> Self {
Self::from_cols(m.x.into(), m.y.into(), m.z.into(), m.w.into())
}
}
impl From<$mat4> for mint::ColumnMatrix4<$t> {
fn from(m: $mat4) -> Self {
Self {
x: m.x_axis.into(),
y: m.y_axis.into(),
z: m.z_axis.into(),
w: m.w_axis.into(),
}
}
}
impl IntoMint for $mat4 {
type MintType = mint::ColumnMatrix4<$t>;
}
};
}
impl From<mint::Point3<f32>> for Vec3A {
fn from(v: mint::Point3<f32>) -> Self {
Self::new(v.x, v.y, v.z)
}
}
impl From<Vec3A> for mint::Point3<f32> {
fn from(v: Vec3A) -> Self {
Self {
x: v.x,
y: v.y,
z: v.z,
}
}
}
impl From<mint::Vector3<f32>> for Vec3A {
fn from(v: mint::Vector3<f32>) -> Self {
Self::new(v.x, v.y, v.z)
}
}
impl From<Vec3A> for mint::Vector3<f32> {
fn from(v: Vec3A) -> Self {
Self {
x: v.x,
y: v.y,
z: v.z,
}
}
}
impl IntoMint for Vec3A {
type MintType = mint::Vector3<f32>;
}
impl From<mint::RowMatrix3<f32>> for Mat3A {
fn from(m: mint::RowMatrix3<f32>) -> Self {
Self::from_cols(m.x.into(), m.y.into(), m.z.into()).transpose()
}
}
impl From<Mat3A> for mint::RowMatrix3<f32> {
fn from(m: Mat3A) -> Self {
let mt = m.transpose();
Self {
x: mt.x_axis.into(),
y: mt.y_axis.into(),
z: mt.z_axis.into(),
}
}
}
impl From<mint::ColumnMatrix3<f32>> for Mat3A {
fn from(m: mint::ColumnMatrix3<f32>) -> Self {
Self::from_cols(m.x.into(), m.y.into(), m.z.into())
}
}
impl From<Mat3A> for mint::ColumnMatrix3<f32> {
fn from(m: Mat3A) -> Self {
Self {
x: m.x_axis.into(),
y: m.y_axis.into(),
z: m.z_axis.into(),
}
}
}
impl IntoMint for Mat3A {
type MintType = mint::ColumnMatrix3<f32>;
}
impl_float_types!(f32, Mat2, Mat3, Mat4, Quat, Vec2, Vec3, Vec4);
impl_float_types!(f64, DMat2, DMat3, DMat4, DQuat, DVec2, DVec3, DVec4);
impl_vec_types!(i8, I8Vec2, I8Vec3, I8Vec4);
impl_vec_types!(u8, U8Vec2, U8Vec3, U8Vec4);
impl_vec_types!(i16, I16Vec2, I16Vec3, I16Vec4);
impl_vec_types!(u16, U16Vec2, U16Vec3, U16Vec4);
impl_vec_types!(i32, IVec2, IVec3, IVec4);
impl_vec_types!(u32, UVec2, UVec3, UVec4);
impl_vec_types!(i64, I64Vec2, I64Vec3, I64Vec4);
impl_vec_types!(u64, U64Vec2, U64Vec3, U64Vec4);
#[cfg(test)]
mod test {
macro_rules! impl_vec_tests {
($t:ty, $vec2:ident, $vec3:ident, $vec4:ident) => {
use crate::{$vec2, $vec3, $vec4};
use mint;
#[test]
fn test_point2() {
let m = mint::Point2 {
x: 1 as $t,
y: 2 as $t,
};
let g = $vec2::from(m);
assert_eq!(g, $vec2::new(1 as $t, 2 as $t));
assert_eq!(m, g.into());
}
#[test]
fn test_point3() {
let m = mint::Point3 {
x: 1 as $t,
y: 2 as $t,
z: 3 as $t,
};
let g = $vec3::from(m);
assert_eq!(g, $vec3::new(1 as $t, 2 as $t, 3 as $t));
assert_eq!(m, g.into());
}
#[test]
fn test_vector2() {
let m = mint::Vector2 {
x: 1 as $t,
y: 2 as $t,
};
let g = $vec2::from(m);
assert_eq!(g, $vec2::new(1 as $t, 2 as $t));
assert_eq!(m, g.into());
}
#[test]
fn test_vector3() {
let m = mint::Vector3 {
x: 1 as $t,
y: 2 as $t,
z: 3 as $t,
};
let g = $vec3::from(m);
assert_eq!(g, $vec3::new(1 as $t, 2 as $t, 3 as $t));
assert_eq!(m, g.into());
}
#[test]
fn test_vector4() {
let m = mint::Vector4 {
x: 1 as $t,
y: 2 as $t,
z: 3 as $t,
w: 4 as $t,
};
let g = $vec4::from(m);
assert_eq!(g, $vec4::new(1 as $t, 2 as $t, 3 as $t, 4 as $t));
assert_eq!(m, g.into());
}
};
}
macro_rules! impl_float_tests {
($t:ty, $mat2:ident, $mat3:ident, $mat4:ident, $quat:ident, $vec2:ident, $vec3:ident, $vec4:ident) => {
impl_vec_tests!($t, $vec2, $vec3, $vec4);
use crate::{$mat2, $mat3, $mat4, $quat};
#[test]
fn test_quaternion() {
let m = mint::Quaternion {
v: mint::Vector3 {
x: 1.0,
y: 2.0,
z: 3.0,
},
s: 4.0,
};
let g = $quat::from(m);
assert_eq!(g, $quat::from_xyzw(1.0, 2.0, 3.0, 4.0));
assert_eq!(m, g.into());
}
#[test]
fn test_matrix2() {
let g = $mat2::from_cols_array_2d(&[[1.0, 2.0], [3.0, 4.0]]);
let m = mint::ColumnMatrix2::from(g);
assert_eq!(g, $mat2::from(m));
let mt = mint::RowMatrix2::from(g);
assert_eq!(mt, mint::RowMatrix2::from([[1.0, 3.0], [2.0, 4.0]]));
assert_eq!(g, $mat2::from(mt));
}
#[test]
fn test_matrix3() {
let g =
$mat3::from_cols_array_2d(&[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]);
let m = mint::ColumnMatrix3::from(g);
assert_eq!(g, $mat3::from(m));
let mt = mint::RowMatrix3::from(g);
assert_eq!(
mt,
mint::RowMatrix3::from([[1.0, 4.0, 7.0], [2.0, 5.0, 8.0], [3.0, 6.0, 9.0]])
);
assert_eq!(g, $mat3::from(mt));
}
#[test]
fn test_matrix4() {
let g = $mat4::from_cols_array_2d(&[
[1.0, 2.0, 3.0, 4.0],
[5.0, 6.0, 7.0, 8.0],
[9.0, 10.0, 11.0, 12.0],
[13.0, 14.0, 15.0, 16.0],
]);
let m = mint::ColumnMatrix4::from(g);
assert_eq!(g, $mat4::from(m));
let mt = mint::RowMatrix4::from(g);
assert_eq!(
mt,
mint::RowMatrix4::from([
[1.0, 5.0, 9.0, 13.0],
[2.0, 6.0, 10.0, 14.0],
[3.0, 7.0, 11.0, 15.0],
[4.0, 8.0, 12.0, 16.0]
])
);
assert_eq!(g, $mat4::from(mt));
}
};
}
mod f32 {
impl_float_tests!(f32, Mat2, Mat3, Mat4, Quat, Vec2, Vec3, Vec4);
#[test]
fn test_point3a() {
use crate::Vec3A;
let m = mint::Point3 {
x: 1.0,
y: 2.0,
z: 3.0,
};
let g = Vec3A::from(m);
assert_eq!(g, Vec3A::new(1.0, 2.0, 3.0));
assert_eq!(m, g.into());
}
#[test]
fn test_vector3a() {
use crate::Vec3A;
let m = mint::Vector3 {
x: 1.0,
y: 2.0,
z: 3.0,
};
let g = Vec3A::from(m);
assert_eq!(g, Vec3A::new(1.0, 2.0, 3.0));
assert_eq!(m, g.into());
}
#[test]
fn test_mat3a_col_major() {
use crate::Mat3A;
let m = mint::ColumnMatrix3 {
x: [0.0, 1.0, 2.0].into(),
y: [3.0, 4.0, 5.0].into(),
z: [6.0, 7.0, 8.0].into(),
};
let expected = Mat3A::from_cols(
[0.0, 1.0, 2.0].into(),
[3.0, 4.0, 5.0].into(),
[6.0, 7.0, 8.0].into(),
);
assert_eq!(expected, m.into());
assert_eq!(m, expected.into());
}
#[test]
fn test_mat3a_row_major() {
use crate::Mat3A;
let m = mint::RowMatrix3 {
x: [0.0, 1.0, 2.0].into(),
y: [3.0, 4.0, 5.0].into(),
z: [6.0, 7.0, 8.0].into(),
};
let expected = Mat3A::from_cols(
[0.0, 3.0, 6.0].into(),
[1.0, 4.0, 7.0].into(),
[2.0, 5.0, 8.0].into(),
);
assert_eq!(expected, m.into());
assert_eq!(m, expected.into());
}
}
mod f64 {
impl_float_tests!(f64, DMat2, DMat3, DMat4, DQuat, DVec2, DVec3, DVec4);
}
mod i32 {
impl_vec_tests!(i32, IVec2, IVec3, IVec4);
}
mod u32 {
impl_vec_tests!(u32, UVec2, UVec3, UVec4);
}
}
+263
View File
@@ -0,0 +1,263 @@
macro_rules! impl_vec_types {
($t:ty, $vec2:ident, $vec3:ident, $vec4:ident) => {
impl Distribution<$vec2> for Standard {
#[inline]
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> $vec2 {
rng.gen::<[$t; 2]>().into()
}
}
impl Distribution<$vec3> for Standard {
#[inline]
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> $vec3 {
rng.gen::<[$t; 3]>().into()
}
}
impl Distribution<$vec4> for Standard {
#[inline]
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> $vec4 {
rng.gen::<[$t; 4]>().into()
}
}
#[test]
fn test_vec2_rand() {
use rand::{Rng, SeedableRng};
use rand_xoshiro::Xoshiro256Plus;
let mut rng1 = Xoshiro256Plus::seed_from_u64(0);
let a: ($t, $t) = rng1.gen();
let mut rng2 = Xoshiro256Plus::seed_from_u64(0);
let b: $vec2 = rng2.gen();
assert_eq!(a, b.into());
}
#[test]
fn test_vec3_rand() {
use rand::{Rng, SeedableRng};
use rand_xoshiro::Xoshiro256Plus;
let mut rng1 = Xoshiro256Plus::seed_from_u64(0);
let a: ($t, $t, $t) = rng1.gen();
let mut rng2 = Xoshiro256Plus::seed_from_u64(0);
let b: $vec3 = rng2.gen();
assert_eq!(a, b.into());
}
#[test]
fn test_vec4_rand() {
use rand::{Rng, SeedableRng};
use rand_xoshiro::Xoshiro256Plus;
let mut rng1 = Xoshiro256Plus::seed_from_u64(0);
let a: ($t, $t, $t, $t) = rng1.gen();
let mut rng2 = Xoshiro256Plus::seed_from_u64(0);
let b: $vec4 = rng2.gen();
assert_eq!(a, b.into());
}
};
}
macro_rules! impl_float_types {
($t:ident, $mat2:ident, $mat3:ident, $mat4:ident, $quat:ident, $vec2:ident, $vec3:ident, $vec4:ident) => {
impl_vec_types!($t, $vec2, $vec3, $vec4);
impl Distribution<$mat2> for Standard {
#[inline]
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> $mat2 {
$mat2::from_cols_array(&rng.gen())
}
}
impl Distribution<$mat3> for Standard {
#[inline]
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> $mat3 {
$mat3::from_cols_array(&rng.gen())
}
}
impl Distribution<$mat4> for Standard {
#[inline]
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> $mat4 {
$mat4::from_cols_array(&rng.gen())
}
}
impl Distribution<$quat> for Standard {
#[inline]
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> $quat {
let z = rng.gen_range::<$t, _>(-1.0..=1.0);
let (y, x) = math::sin_cos(rng.gen_range::<$t, _>(0.0..TAU));
let r = math::sqrt(1.0 - z * z);
let axis = $vec3::new(r * x, r * y, z);
let angle = rng.gen_range::<$t, _>(0.0..TAU);
$quat::from_axis_angle(axis, angle)
}
}
#[test]
fn test_mat2_rand() {
use rand::{Rng, SeedableRng};
use rand_xoshiro::Xoshiro256Plus;
let mut rng1 = Xoshiro256Plus::seed_from_u64(0);
let a = $mat2::from_cols_array(&rng1.gen::<[$t; 4]>());
let mut rng2 = Xoshiro256Plus::seed_from_u64(0);
let b = rng2.gen::<$mat2>();
assert_eq!(a, b);
}
#[test]
fn test_mat3_rand() {
use rand::{Rng, SeedableRng};
use rand_xoshiro::Xoshiro256Plus;
let mut rng1 = Xoshiro256Plus::seed_from_u64(0);
let a = $mat3::from_cols_array(&rng1.gen::<[$t; 9]>());
let mut rng2 = Xoshiro256Plus::seed_from_u64(0);
let b = rng2.gen::<$mat3>();
assert_eq!(a, b);
}
#[test]
fn test_mat4_rand() {
use rand::{Rng, SeedableRng};
use rand_xoshiro::Xoshiro256Plus;
let mut rng1 = Xoshiro256Plus::seed_from_u64(0);
let a = $mat4::from_cols_array(&rng1.gen::<[$t; 16]>());
let mut rng2 = Xoshiro256Plus::seed_from_u64(0);
let b = rng2.gen::<$mat4>();
assert_eq!(a, b);
}
#[test]
fn test_quat_rand() {
use rand::{Rng, SeedableRng};
use rand_xoshiro::Xoshiro256Plus;
let mut rng1 = Xoshiro256Plus::seed_from_u64(0);
let a: $quat = rng1.gen();
assert!(a.is_normalized());
let mut rng2 = Xoshiro256Plus::seed_from_u64(0);
let b: $quat = rng2.gen();
assert_eq!(a, b);
}
};
}
mod f32 {
use crate::f32::math;
use crate::{Mat2, Mat3, Mat4, Quat, Vec2, Vec3, Vec3A, Vec4};
use core::f32::consts::TAU;
use rand::{
distributions::{Distribution, Standard},
Rng,
};
impl_float_types!(f32, Mat2, Mat3, Mat4, Quat, Vec2, Vec3, Vec4);
impl Distribution<Vec3A> for Standard {
#[inline]
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Vec3A {
rng.gen::<[f32; 3]>().into()
}
}
#[test]
fn test_vec3a_rand() {
use rand::{Rng, SeedableRng};
use rand_xoshiro::Xoshiro256Plus;
let mut rng1 = Xoshiro256Plus::seed_from_u64(0);
let a: (f32, f32, f32) = rng1.gen();
let mut rng2 = Xoshiro256Plus::seed_from_u64(0);
let b: Vec3A = rng2.gen();
assert_eq!(a, b.into());
}
}
mod f64 {
use crate::f64::math;
use crate::{DMat2, DMat3, DMat4, DQuat, DVec2, DVec3, DVec4};
use core::f64::consts::TAU;
use rand::{
distributions::{Distribution, Standard},
Rng,
};
impl_float_types!(f64, DMat2, DMat3, DMat4, DQuat, DVec2, DVec3, DVec4);
}
mod i8 {
use crate::{I8Vec2, I8Vec3, I8Vec4};
use rand::{
distributions::{Distribution, Standard},
Rng,
};
impl_vec_types!(i8, I8Vec2, I8Vec3, I8Vec4);
}
mod i16 {
use crate::{I16Vec2, I16Vec3, I16Vec4};
use rand::{
distributions::{Distribution, Standard},
Rng,
};
impl_vec_types!(i16, I16Vec2, I16Vec3, I16Vec4);
}
mod i32 {
use crate::{IVec2, IVec3, IVec4};
use rand::{
distributions::{Distribution, Standard},
Rng,
};
impl_vec_types!(i32, IVec2, IVec3, IVec4);
}
mod i64 {
use crate::{I64Vec2, I64Vec3, I64Vec4};
use rand::{
distributions::{Distribution, Standard},
Rng,
};
impl_vec_types!(i64, I64Vec2, I64Vec3, I64Vec4);
}
mod u8 {
use crate::{U8Vec2, U8Vec3, U8Vec4};
use rand::{
distributions::{Distribution, Standard},
Rng,
};
impl_vec_types!(u8, U8Vec2, U8Vec3, U8Vec4);
}
mod u16 {
use crate::{U16Vec2, U16Vec3, U16Vec4};
use rand::{
distributions::{Distribution, Standard},
Rng,
};
impl_vec_types!(u16, U16Vec2, U16Vec3, U16Vec4);
}
mod u32 {
use crate::{UVec2, UVec3, UVec4};
use rand::{
distributions::{Distribution, Standard},
Rng,
};
impl_vec_types!(u32, UVec2, UVec3, UVec4);
}
mod u64 {
use crate::{U64Vec2, U64Vec3, U64Vec4};
use rand::{
distributions::{Distribution, Standard},
Rng,
};
impl_vec_types!(u64, U64Vec2, U64Vec3, U64Vec4);
}
+274
View File
@@ -0,0 +1,274 @@
#[cfg(feature = "bytecheck")]
macro_rules! impl_rkyv {
(@bytecheck $type:ty) => {
impl<C: ?Sized> bytecheck::CheckBytes<C> for $type {
type Error = core::convert::Infallible;
#[inline]
unsafe fn check_bytes<'a>(
value: *const Self,
_: &mut C,
) -> Result<&'a Self, Self::Error> {
Ok(&*value)
}
}
};
($type:ty) => {
impl_rkyv_derive!(@serialize $type);
impl_rkyv_derive!(@archive_deserialize $type);
impl_rkyv!(@bytecheck $type);
};
}
#[cfg(not(feature = "bytecheck"))]
macro_rules! impl_rkyv {
($type:ty) => {
impl_rkyv_derive!(@serialize $type);
impl_rkyv_derive!(@archive_deserialize $type);
};
}
macro_rules! impl_rkyv_derive {
(@serialize $type:ty) => {
impl<S: Fallible + ?Sized> Serialize<S> for $type {
#[inline]
fn serialize(&self, _: &mut S) -> Result<Self::Resolver, S::Error> {
Ok(())
}
}
};
(@archive_deserialize $type:ty) => {
impl Archive for $type {
type Archived = $type;
type Resolver = ();
#[inline]
unsafe fn resolve(&self, _: usize, _: Self::Resolver, out: *mut Self::Archived) {
#[allow(unexpected_cfgs)]
out.write(to_archived!(*self as Self));
}
}
impl<D: Fallible + ?Sized> Deserialize<$type, D> for $type {
#[inline]
fn deserialize(&self, _: &mut D) -> Result<$type, D::Error> {
#[allow(unexpected_cfgs)]
Ok(from_archived!(*self))
}
}
};
}
mod f32 {
use crate::{Affine2, Affine3A, Mat2, Mat3, Mat3A, Mat4, Quat, Vec2, Vec3, Vec3A, Vec4};
use rkyv::{from_archived, to_archived, Archive, Deserialize, Fallible, Serialize};
impl_rkyv!(Affine2);
impl_rkyv!(Affine3A);
impl_rkyv!(Mat2);
impl_rkyv!(Mat3);
impl_rkyv!(Mat3A);
impl_rkyv!(Mat4);
impl_rkyv!(Quat);
impl_rkyv!(Vec2);
impl_rkyv!(Vec3);
impl_rkyv!(Vec3A);
impl_rkyv!(Vec4);
}
mod f64 {
use crate::{DAffine2, DAffine3, DMat2, DMat3, DMat4, DQuat, DVec2, DVec3, DVec4};
use rkyv::{from_archived, to_archived, Archive, Deserialize, Fallible, Serialize};
impl_rkyv!(DAffine2);
impl_rkyv!(DAffine3);
impl_rkyv!(DMat2);
impl_rkyv!(DMat3);
impl_rkyv!(DMat4);
impl_rkyv!(DQuat);
impl_rkyv!(DVec2);
impl_rkyv!(DVec3);
impl_rkyv!(DVec4);
}
mod i8 {
use crate::{I8Vec2, I8Vec3, I8Vec4};
use rkyv::{from_archived, to_archived, Archive, Deserialize, Fallible, Serialize};
impl_rkyv!(I8Vec2);
impl_rkyv!(I8Vec3);
impl_rkyv!(I8Vec4);
}
mod i16 {
use crate::{I16Vec2, I16Vec3, I16Vec4};
use rkyv::{from_archived, to_archived, Archive, Deserialize, Fallible, Serialize};
impl_rkyv!(I16Vec2);
impl_rkyv!(I16Vec3);
impl_rkyv!(I16Vec4);
}
mod i32 {
use crate::{IVec2, IVec3, IVec4};
use rkyv::{from_archived, to_archived, Archive, Deserialize, Fallible, Serialize};
impl_rkyv!(IVec2);
impl_rkyv!(IVec3);
impl_rkyv!(IVec4);
}
mod i64 {
use crate::{I64Vec2, I64Vec3, I64Vec4};
use rkyv::{from_archived, to_archived, Archive, Deserialize, Fallible, Serialize};
impl_rkyv!(I64Vec2);
impl_rkyv!(I64Vec3);
impl_rkyv!(I64Vec4);
}
mod u8 {
use crate::{U8Vec2, U8Vec3, U8Vec4};
use rkyv::{from_archived, to_archived, Archive, Deserialize, Fallible, Serialize};
impl_rkyv!(U8Vec2);
impl_rkyv!(U8Vec3);
impl_rkyv!(U8Vec4);
}
mod u16 {
use crate::{U16Vec2, U16Vec3, U16Vec4};
use rkyv::{from_archived, to_archived, Archive, Deserialize, Fallible, Serialize};
impl_rkyv!(U16Vec2);
impl_rkyv!(U16Vec3);
impl_rkyv!(U16Vec4);
}
mod u32 {
use crate::{UVec2, UVec3, UVec4};
use rkyv::{from_archived, to_archived, Archive, Deserialize, Fallible, Serialize};
impl_rkyv!(UVec2);
impl_rkyv!(UVec3);
impl_rkyv!(UVec4);
}
mod u64 {
use crate::{U64Vec2, U64Vec3, U64Vec4};
use rkyv::{from_archived, to_archived, Archive, Deserialize, Fallible, Serialize};
impl_rkyv!(U64Vec2);
impl_rkyv!(U64Vec3);
impl_rkyv!(U64Vec4);
}
#[cfg(test)]
mod test {
pub type DefaultSerializer = rkyv::ser::serializers::CoreSerializer<256, 256>;
pub type DefaultDeserializer = rkyv::Infallible;
use rkyv::ser::Serializer;
use rkyv::*;
pub fn test_archive<T>(value: &T)
where
T: core::fmt::Debug + PartialEq + rkyv::Serialize<DefaultSerializer>,
T::Archived: core::fmt::Debug + PartialEq<T> + rkyv::Deserialize<T, DefaultDeserializer>,
{
let mut serializer = DefaultSerializer::default();
serializer
.serialize_value(value)
.expect("failed to archive value");
let len = serializer.pos();
let buffer = serializer.into_serializer().into_inner();
let archived_value = unsafe { rkyv::archived_root::<T>(&buffer[0..len]) };
assert_eq!(archived_value, value);
let mut deserializer = DefaultDeserializer::default();
assert_eq!(
&archived_value.deserialize(&mut deserializer).unwrap(),
value
);
}
#[test]
fn test_rkyv() {
use crate::{Affine2, Affine3A, Mat2, Mat3, Mat3A, Mat4, Quat, Vec2, Vec3, Vec3A, Vec4};
test_archive(&Affine2::from_cols_array(&[1.0, 0.0, 2.0, 0.0, 3.0, 4.0]));
test_archive(&Affine3A::from_cols_array(&[
1.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 3.0, 4.0, 5.0, 6.0,
]));
test_archive(&Mat2::from_cols_array(&[1.0, 2.0, 3.0, 4.0]));
test_archive(&Mat3::from_cols_array(&[
1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0,
]));
test_archive(&Mat3A::from_cols_array(&[
1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0,
]));
test_archive(&Mat4::from_cols_array(&[
1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0,
]));
test_archive(&Quat::from_xyzw(1.0, 2.0, 3.0, 4.0));
test_archive(&Vec2::new(1.0, 2.0));
test_archive(&Vec3::new(1.0, 2.0, 3.0));
test_archive(&Vec3A::new(1.0, 2.0, 3.0));
test_archive(&Vec4::new(1.0, 2.0, 3.0, 4.0));
use crate::{DAffine2, DAffine3, DMat2, DMat3, DMat4, DQuat, DVec2, DVec3, DVec4};
test_archive(&DAffine2::from_cols_array(&[1.0, 0.0, 2.0, 0.0, 3.0, 4.0]));
test_archive(&DAffine3::from_cols_array(&[
1.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 3.0, 4.0, 5.0, 6.0,
]));
test_archive(&DMat2::from_cols_array(&[1.0, 2.0, 3.0, 4.0]));
test_archive(&DMat3::from_cols_array(&[
1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0,
]));
test_archive(&DMat4::from_cols_array(&[
1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0,
]));
test_archive(&DQuat::from_xyzw(1.0, 2.0, 3.0, 4.0));
test_archive(&DVec2::new(1.0, 2.0));
test_archive(&DVec3::new(1.0, 2.0, 3.0));
test_archive(&DVec4::new(1.0, 2.0, 3.0, 4.0));
use crate::{I8Vec2, I8Vec3, I8Vec4};
test_archive(&I8Vec2::new(-1, 2));
test_archive(&I8Vec3::new(-1, 2, 3));
test_archive(&I8Vec4::new(-1, 2, 3, 4));
use crate::{I16Vec2, I16Vec3, I16Vec4};
test_archive(&I16Vec2::new(-1, 2));
test_archive(&I16Vec3::new(-1, 2, 3));
test_archive(&I16Vec4::new(-1, 2, 3, 4));
use crate::{IVec2, IVec3, IVec4};
test_archive(&IVec2::new(-1, 2));
test_archive(&IVec3::new(-1, 2, 3));
test_archive(&IVec4::new(-1, 2, 3, 4));
use crate::{I64Vec2, I64Vec3, I64Vec4};
test_archive(&I64Vec2::new(-1, 2));
test_archive(&I64Vec3::new(-1, 2, 3));
test_archive(&I64Vec4::new(-1, 2, 3, 4));
use crate::{U8Vec2, U8Vec3, U8Vec4};
test_archive(&U8Vec2::new(1, 2));
test_archive(&U8Vec3::new(1, 2, 3));
test_archive(&U8Vec4::new(1, 2, 3, 4));
use crate::{U16Vec2, U16Vec3, U16Vec4};
test_archive(&U16Vec2::new(1, 2));
test_archive(&U16Vec3::new(1, 2, 3));
test_archive(&U16Vec4::new(1, 2, 3, 4));
use crate::{UVec2, UVec3, UVec4};
test_archive(&UVec2::new(1, 2));
test_archive(&UVec3::new(1, 2, 3));
test_archive(&UVec4::new(1, 2, 3, 4));
use crate::{U64Vec2, U64Vec3, U64Vec4};
test_archive(&U64Vec2::new(1, 2));
test_archive(&U64Vec3::new(1, 2, 3));
test_archive(&U64Vec4::new(1, 2, 3, 4));
}
}
File diff suppressed because it is too large Load Diff
+30
View File
@@ -0,0 +1,30 @@
/// A trait for extending [`prim@f32`] and [`prim@f64`] with extra methods.
pub trait FloatExt {
/// Performs a linear interpolation between `self` and `rhs` based on the value `s`.
///
/// When `s` is `0`, the result will be `self`. When `s` is `1`, the result
/// will be `rhs`. When `s` is outside of the range `[0, 1]`, the result is linearly
/// extrapolated.
#[must_use]
fn lerp(self, rhs: Self, s: Self) -> Self;
/// Returns `v` normalized to the range `[a, b]`.
///
/// When `v` is equal to `a` the result will be `0`. When `v` is equal to `b` will be `1`.
///
/// When `v` is outside of the range `[a, b]`, the result is linearly extrapolated.
///
/// `a` and `b` must not be equal, otherwise the result will be either infinite or `NAN`.
fn inverse_lerp(a: Self, b: Self, v: Self) -> Self;
/// Remap `self` from the input range to the output range.
///
/// When `self` is equal to `in_start` this returns `out_start`.
/// When `self` is equal to `in_end` this returns `out_end`.
///
/// When `self` is outside of the range `[in_start, in_end]`, the result is linearly extrapolated.
///
/// `in_start` and `in_end` must not be equal, otherwise the result will be either infinite or `NAN`.
#[must_use]
fn remap(self, in_start: Self, in_end: Self, out_start: Self, out_end: Self) -> Self;
}
+44
View File
@@ -0,0 +1,44 @@
mod i16vec2;
mod i16vec3;
mod i16vec4;
pub use i16vec2::{i16vec2, I16Vec2};
pub use i16vec3::{i16vec3, I16Vec3};
pub use i16vec4::{i16vec4, I16Vec4};
#[cfg(not(target_arch = "spirv"))]
mod test {
use super::*;
mod const_test_i16vec2 {
const_assert_eq!(4, core::mem::size_of::<super::I16Vec2>());
#[cfg(not(feature = "cuda"))]
const_assert_eq!(
core::mem::align_of::<i16>(),
core::mem::align_of::<super::I16Vec2>()
);
#[cfg(feature = "cuda")]
const_assert_eq!(4, core::mem::align_of::<super::I16Vec2>());
}
mod const_test_i16vec3 {
const_assert_eq!(
core::mem::align_of::<i16>(),
core::mem::align_of::<super::I16Vec3>()
);
const_assert_eq!(6, core::mem::size_of::<super::I16Vec3>());
}
mod const_test_i16vec4 {
const_assert_eq!(8, core::mem::size_of::<super::I16Vec4>());
#[cfg(not(feature = "cuda"))]
const_assert_eq!(
core::mem::align_of::<i16>(),
core::mem::align_of::<super::I16Vec4>()
);
#[cfg(feature = "cuda")]
const_assert_eq!(8, core::mem::align_of::<super::I16Vec4>());
}
}
+1805
View File
File diff suppressed because it is too large Load Diff
+1950
View File
File diff suppressed because it is too large Load Diff
+2086
View File
File diff suppressed because it is too large Load Diff
+44
View File
@@ -0,0 +1,44 @@
mod ivec2;
mod ivec3;
mod ivec4;
pub use ivec2::{ivec2, IVec2};
pub use ivec3::{ivec3, IVec3};
pub use ivec4::{ivec4, IVec4};
#[cfg(not(target_arch = "spirv"))]
mod test {
use super::*;
mod const_test_ivec2 {
const_assert_eq!(8, core::mem::size_of::<super::IVec2>());
#[cfg(not(feature = "cuda"))]
const_assert_eq!(
core::mem::align_of::<i32>(),
core::mem::align_of::<super::IVec2>()
);
#[cfg(feature = "cuda")]
const_assert_eq!(8, core::mem::align_of::<super::IVec2>());
}
mod const_test_ivec3 {
const_assert_eq!(
core::mem::align_of::<i32>(),
core::mem::align_of::<super::IVec3>()
);
const_assert_eq!(12, core::mem::size_of::<super::IVec3>());
}
mod const_test_ivec4 {
const_assert_eq!(16, core::mem::size_of::<super::IVec4>());
#[cfg(not(feature = "cuda"))]
const_assert_eq!(
core::mem::align_of::<i32>(),
core::mem::align_of::<super::IVec4>()
);
#[cfg(feature = "cuda")]
const_assert_eq!(16, core::mem::align_of::<super::IVec4>());
}
}
+1801
View File
File diff suppressed because it is too large Load Diff
+1938
View File
File diff suppressed because it is too large Load Diff
+2082
View File
File diff suppressed because it is too large Load Diff
+45
View File
@@ -0,0 +1,45 @@
mod i64vec2;
mod i64vec3;
mod i64vec4;
pub use i64vec2::{i64vec2, I64Vec2};
pub use i64vec3::{i64vec3, I64Vec3};
pub use i64vec4::{i64vec4, I64Vec4};
#[cfg(not(target_arch = "spirv"))]
mod test {
use super::*;
mod const_test_i64vec2 {
const_assert_eq!(16, core::mem::size_of::<super::I64Vec2>());
#[cfg(not(feature = "cuda"))]
const_assert_eq!(
core::mem::align_of::<i64>(),
core::mem::align_of::<super::I64Vec2>()
);
#[cfg(feature = "cuda")]
const_assert_eq!(16, core::mem::align_of::<super::I64Vec2>());
}
mod const_test_i64vec3 {
const_assert_eq!(24, core::mem::size_of::<super::I64Vec3>());
const_assert_eq!(
core::mem::align_of::<i64>(),
core::mem::align_of::<super::I64Vec3>()
);
}
mod const_test_i64vec4 {
const_assert_eq!(32, core::mem::size_of::<super::I64Vec4>());
#[cfg(not(feature = "cuda"))]
const_assert_eq!(
core::mem::align_of::<i64>(),
core::mem::align_of::<super::I64Vec4>()
);
#[cfg(feature = "cuda")]
const_assert_eq!(16, core::mem::align_of::<super::I64Vec4>());
}
}
+1797
View File
File diff suppressed because it is too large Load Diff
+1926
View File
File diff suppressed because it is too large Load Diff
+2078
View File
File diff suppressed because it is too large Load Diff
+44
View File
@@ -0,0 +1,44 @@
mod i8vec2;
mod i8vec3;
mod i8vec4;
pub use i8vec2::{i8vec2, I8Vec2};
pub use i8vec3::{i8vec3, I8Vec3};
pub use i8vec4::{i8vec4, I8Vec4};
#[cfg(not(target_arch = "spirv"))]
mod test {
use super::*;
mod const_test_i8vec2 {
const_assert_eq!(2, core::mem::size_of::<super::I8Vec2>());
#[cfg(not(feature = "cuda"))]
const_assert_eq!(
core::mem::align_of::<i8>(),
core::mem::align_of::<super::I8Vec2>()
);
#[cfg(feature = "cuda")]
const_assert_eq!(2, core::mem::align_of::<super::I8Vec2>());
}
mod const_test_i8vec3 {
const_assert_eq!(
core::mem::align_of::<i8>(),
core::mem::align_of::<super::I8Vec3>()
);
const_assert_eq!(3, core::mem::size_of::<super::I8Vec3>());
}
mod const_test_i8vec4 {
const_assert_eq!(4, core::mem::size_of::<super::I8Vec4>());
#[cfg(not(feature = "cuda"))]
const_assert_eq!(
core::mem::align_of::<i8>(),
core::mem::align_of::<super::I8Vec4>()
);
#[cfg(feature = "cuda")]
const_assert_eq!(4, core::mem::align_of::<super::I8Vec4>());
}
}
+1809
View File
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More