Skip to main content

oa/core/vlm/
matrix.rs

1use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
2
3use super::quaternion::Quat;
4use super::scalar::{Float, approx, valid_tolerance};
5use super::vector::{Vec3, Vec4};
6
7/// A packed 3×3 row-major matrix.
8#[repr(C)]
9#[derive(Clone, Copy, Debug, Default, PartialEq)]
10pub struct Mat3<T: Float = f32> {
11	pub m: [[T; 3]; 3],
12}
13
14/// A packed 4×4 row-major matrix.
15#[repr(C)]
16#[derive(Clone, Copy, Debug, Default, PartialEq)]
17pub struct Mat4<T: Float = f32> {
18	pub m: [[T; 4]; 4],
19}
20
21pub type DMat3 = Mat3<f64>;
22pub type DMat4 = Mat4<f64>;
23
24impl<T: Float> Mat3<T> {
25	pub fn identity() -> Self {
26		Self {
27			m: [
28				[T::ONE, T::ZERO, T::ZERO],
29				[T::ZERO, T::ONE, T::ZERO],
30				[T::ZERO, T::ZERO, T::ONE],
31			],
32		}
33	}
34
35	pub fn is_finite(self) -> bool {
36		self.m.iter().flatten().all(|value| value.is_finite())
37	}
38
39	pub fn transpose(self) -> Self {
40		let mut result = Self::default();
41		for (row, values) in result.m.iter_mut().enumerate() {
42			for (column, value) in values.iter_mut().enumerate() {
43				*value = self.m[column][row];
44			}
45		}
46		result
47	}
48
49	pub fn determinant(self) -> T {
50		self.m[0][0] * (self.m[1][1] * self.m[2][2] - self.m[1][2] * self.m[2][1])
51			- self.m[0][1] * (self.m[1][0] * self.m[2][2] - self.m[1][2] * self.m[2][0])
52			+ self.m[0][2] * (self.m[1][0] * self.m[2][1] - self.m[1][1] * self.m[2][0])
53	}
54
55	pub fn try_inverse(self, tolerance: T) -> Option<Self> {
56		if !valid_tolerance(tolerance) || !self.is_finite() {
57			return None;
58		}
59		let magnitude = self
60			.m
61			.iter()
62			.flatten()
63			.fold(T::ZERO, |largest, value| largest.max(value.abs()));
64		if magnitude <= T::ZERO {
65			return None;
66		}
67		let scaled = self / magnitude;
68		let determinant = scaled.determinant();
69		if !determinant.is_finite() || determinant.abs() <= tolerance {
70			return None;
71		}
72		let inverse_determinant = T::ONE / determinant;
73		let m = scaled.m;
74		let inverse = Self {
75			m: [
76				[
77					(m[1][1] * m[2][2] - m[1][2] * m[2][1]) * inverse_determinant / magnitude,
78					(m[0][2] * m[2][1] - m[0][1] * m[2][2]) * inverse_determinant / magnitude,
79					(m[0][1] * m[1][2] - m[0][2] * m[1][1]) * inverse_determinant / magnitude,
80				],
81				[
82					(m[1][2] * m[2][0] - m[1][0] * m[2][2]) * inverse_determinant / magnitude,
83					(m[0][0] * m[2][2] - m[0][2] * m[2][0]) * inverse_determinant / magnitude,
84					(m[0][2] * m[1][0] - m[0][0] * m[1][2]) * inverse_determinant / magnitude,
85				],
86				[
87					(m[1][0] * m[2][1] - m[1][1] * m[2][0]) * inverse_determinant / magnitude,
88					(m[0][1] * m[2][0] - m[0][0] * m[2][1]) * inverse_determinant / magnitude,
89					(m[0][0] * m[1][1] - m[0][1] * m[1][0]) * inverse_determinant / magnitude,
90				],
91			],
92		};
93		if !inverse.is_finite() {
94			return None;
95		}
96		let matrix_norm = row_norm3(self);
97		let inverse_norm = row_norm3(inverse);
98		let condition = matrix_norm * inverse_norm;
99		if !condition.is_finite() || condition <= T::ZERO || T::ONE / condition <= tolerance {
100			return None;
101		}
102		Some(inverse)
103	}
104
105	pub fn transform(self, value: Vec3<T>) -> Vec3<T> {
106		value * self
107	}
108
109	pub fn approximately_equal(self, other: Self, absolute: T, relative: T) -> bool {
110		valid_tolerance(absolute)
111			&& valid_tolerance(relative)
112			&& self.m.iter().enumerate().all(|(row, values)| {
113				values
114					.iter()
115					.enumerate()
116					.all(|(column, value)| approx(*value, other.m[row][column], absolute, relative))
117			})
118	}
119}
120
121fn row_norm3<T: Float>(matrix: Mat3<T>) -> T {
122	matrix.m.iter().fold(T::ZERO, |largest, row| {
123		largest.max(row.iter().fold(T::ZERO, |sum, value| sum + value.abs()))
124	})
125}
126
127impl<T: Float> Mat4<T> {
128	pub fn identity() -> Self {
129		Self {
130			m: [
131				[T::ONE, T::ZERO, T::ZERO, T::ZERO],
132				[T::ZERO, T::ONE, T::ZERO, T::ZERO],
133				[T::ZERO, T::ZERO, T::ONE, T::ZERO],
134				[T::ZERO, T::ZERO, T::ZERO, T::ONE],
135			],
136		}
137	}
138
139	pub fn is_finite(self) -> bool {
140		self.m.iter().flatten().all(|value| value.is_finite())
141	}
142
143	pub fn transpose(self) -> Self {
144		let mut result = Self::default();
145		for (row, values) in result.m.iter_mut().enumerate() {
146			for (column, value) in values.iter_mut().enumerate() {
147				*value = self.m[column][row];
148			}
149		}
150		result
151	}
152
153	pub fn determinant(self) -> T {
154		if !self.is_finite() {
155			return T::from_f64(f64::NAN);
156		}
157		let mut reduced = self.m;
158		let mut result = T::ONE;
159		let mut negative = false;
160		for pivot_column in 0..4 {
161			let mut pivot_row = pivot_column;
162			let mut pivot_magnitude = reduced[pivot_row][pivot_column].abs();
163			for (row, values) in reduced.iter().enumerate().skip(pivot_column + 1) {
164				let magnitude = values[pivot_column].abs();
165				if magnitude > pivot_magnitude {
166					pivot_magnitude = magnitude;
167					pivot_row = row;
168				}
169			}
170			if pivot_magnitude == T::ZERO {
171				return T::ZERO;
172			}
173			if pivot_row != pivot_column {
174				reduced.swap(pivot_row, pivot_column);
175				negative = !negative;
176			}
177			let pivot = reduced[pivot_column][pivot_column];
178			result = result * pivot;
179			let pivot_values = reduced[pivot_column];
180			for row_values in reduced.iter_mut().skip(pivot_column + 1) {
181				let factor = row_values[pivot_column] / pivot;
182				for (column, value) in row_values.iter_mut().enumerate().skip(pivot_column + 1) {
183					*value = *value - factor * pivot_values[column];
184				}
185			}
186		}
187		if negative { -result } else { result }
188	}
189
190	pub fn try_inverse(self, tolerance: T) -> Option<Self> {
191		if !valid_tolerance(tolerance) || !self.is_finite() {
192			return None;
193		}
194		if self.m[0][3] == T::ZERO
195			&& self.m[1][3] == T::ZERO
196			&& self.m[2][3] == T::ZERO
197			&& self.m[3][3] == T::ONE
198		{
199			return self.try_affine_inverse(tolerance);
200		}
201		let mut augmented = [[T::ZERO; 8]; 4];
202		let mut row_scale = [T::ZERO; 4];
203		for row in 0..4 {
204			for (column, value) in self.m[row].iter().copied().enumerate() {
205				augmented[row][column] = value;
206				row_scale[row] = row_scale[row].max(value.abs());
207			}
208			if row_scale[row] <= T::ZERO {
209				return None;
210			}
211			augmented[row][row + 4] = T::ONE;
212		}
213		for pivot_column in 0..4 {
214			let mut pivot_row = pivot_column;
215			let mut pivot_ratio = augmented[pivot_row][pivot_column].abs() / row_scale[pivot_row];
216			for row in (pivot_column + 1)..4 {
217				let ratio = augmented[row][pivot_column].abs() / row_scale[row];
218				if ratio > pivot_ratio {
219					pivot_ratio = ratio;
220					pivot_row = row;
221				}
222			}
223			if !pivot_ratio.is_finite() || pivot_ratio <= tolerance {
224				return None;
225			}
226			if pivot_row != pivot_column {
227				augmented.swap(pivot_row, pivot_column);
228				row_scale.swap(pivot_row, pivot_column);
229			}
230			let inverse_pivot = T::ONE / augmented[pivot_column][pivot_column];
231			for value in &mut augmented[pivot_column] {
232				*value = *value * inverse_pivot;
233			}
234			for row in 0..4 {
235				if row == pivot_column {
236					continue;
237				}
238				let factor = augmented[row][pivot_column];
239				let pivot_values = augmented[pivot_column];
240				for (column, value) in augmented[row].iter_mut().enumerate() {
241					*value = *value - factor * pivot_values[column];
242				}
243			}
244		}
245		let mut inverse = Self::default();
246		for (row, values) in inverse.m.iter_mut().enumerate() {
247			for (column, value) in values.iter_mut().enumerate() {
248				*value = augmented[row][column + 4];
249			}
250		}
251		if !inverse.is_finite() {
252			return None;
253		}
254		let residual = self * inverse;
255		let factor = if T::TOLERANCE == T::from_f64(1.0e-5) {
256			T::from_f64(256.0)
257		} else {
258			T::from_f64(65536.0)
259		};
260		let residual_tolerance = (T::TOLERANCE * factor).max(tolerance * factor);
261		for row in 0..4 {
262			for column in 0..4 {
263				let expected = if row == column { T::ONE } else { T::ZERO };
264				if (residual.m[row][column] - expected).abs() > residual_tolerance {
265					return None;
266				}
267			}
268		}
269		Some(inverse)
270	}
271
272	pub fn linear_part(self) -> Mat3<T> {
273		Mat3 {
274			m: [
275				[self.m[0][0], self.m[0][1], self.m[0][2]],
276				[self.m[1][0], self.m[1][1], self.m[1][2]],
277				[self.m[2][0], self.m[2][1], self.m[2][2]],
278			],
279		}
280	}
281
282	pub fn translation_part(self) -> Vec3<T> {
283		Vec3 {
284			x: self.m[3][0],
285			y: self.m[3][1],
286			z: self.m[3][2],
287		}
288	}
289
290	pub fn new_from_affine(linear: Mat3<T>, translation: Vec3<T>) -> Self {
291		Self {
292			m: [
293				[linear.m[0][0], linear.m[0][1], linear.m[0][2], T::ZERO],
294				[linear.m[1][0], linear.m[1][1], linear.m[1][2], T::ZERO],
295				[linear.m[2][0], linear.m[2][1], linear.m[2][2], T::ZERO],
296				[translation.x, translation.y, translation.z, T::ONE],
297			],
298		}
299	}
300
301	pub fn is_affine(self, tolerance: T) -> bool {
302		valid_tolerance(tolerance)
303			&& self.is_finite()
304			&& approx(self.m[0][3], T::ZERO, tolerance, T::ZERO)
305			&& approx(self.m[1][3], T::ZERO, tolerance, T::ZERO)
306			&& approx(self.m[2][3], T::ZERO, tolerance, T::ZERO)
307			&& approx(self.m[3][3], T::ONE, tolerance, T::ZERO)
308	}
309
310	pub fn try_affine_inverse(self, tolerance: T) -> Option<Self> {
311		if !self.is_affine(tolerance) {
312			return None;
313		}
314		let inverse_linear = self.linear_part().try_inverse(tolerance)?;
315		let inverse_translation = (-self.translation_part()) * inverse_linear;
316		inverse_translation
317			.is_finite()
318			.then(|| Self::new_from_affine(inverse_linear, inverse_translation))
319	}
320
321	pub fn try_normal_matrix(self, tolerance: T) -> Option<Mat3<T>> {
322		if !self.is_affine(tolerance) {
323			return None;
324		}
325		Some(self.linear_part().try_inverse(tolerance)?.transpose())
326	}
327
328	pub fn transform(self, value: Vec4<T>) -> Vec4<T> {
329		value * self
330	}
331
332	pub fn transform_point(self, point: Vec3<T>) -> Vec3<T> {
333		let value = Vec4 {
334			x: point.x,
335			y: point.y,
336			z: point.z,
337			w: T::ONE,
338		} * self;
339		Vec3 {
340			x: value.x,
341			y: value.y,
342			z: value.z,
343		}
344	}
345
346	pub fn transform_direction(self, direction: Vec3<T>) -> Vec3<T> {
347		let value = Vec4 {
348			x: direction.x,
349			y: direction.y,
350			z: direction.z,
351			w: T::ZERO,
352		} * self;
353		Vec3 {
354			x: value.x,
355			y: value.y,
356			z: value.z,
357		}
358	}
359
360	pub fn try_project_point(self, point: Vec3<T>, tolerance: T) -> Option<Vec3<T>> {
361		if !valid_tolerance(tolerance) {
362			return None;
363		}
364		let homogeneous = Vec4 {
365			x: point.x,
366			y: point.y,
367			z: point.z,
368			w: T::ONE,
369		} * self;
370		if !homogeneous.is_finite() || homogeneous.w.abs() <= tolerance {
371			return None;
372		}
373		let projected = Vec3 {
374			x: homogeneous.x / homogeneous.w,
375			y: homogeneous.y / homogeneous.w,
376			z: homogeneous.z / homogeneous.w,
377		};
378		projected.is_finite().then_some(projected)
379	}
380
381	pub fn try_transform_normal(self, normal: Vec3<T>, tolerance: T) -> Option<Vec3<T>> {
382		let transformed = self
383			.try_inverse(tolerance)?
384			.transpose()
385			.transform_direction(normal);
386		if transformed.length() <= tolerance {
387			return None;
388		}
389		transformed.try_normalized()
390	}
391
392	pub fn translation(value: Vec3<T>) -> Self {
393		let mut result = Self::identity();
394		result.m[3][0] = value.x;
395		result.m[3][1] = value.y;
396		result.m[3][2] = value.z;
397		result
398	}
399
400	pub fn scaling(value: Vec3<T>) -> Self {
401		let mut result = Self::identity();
402		result.m[0][0] = value.x;
403		result.m[1][1] = value.y;
404		result.m[2][2] = value.z;
405		result
406	}
407
408	pub fn try_from_quaternion(rotation: Quat<T>) -> Option<Self> {
409		let q = rotation.try_normalized()?;
410		let xx = q.x * q.x;
411		let yy = q.y * q.y;
412		let zz = q.z * q.z;
413		let xy = q.x * q.y;
414		let xz = q.x * q.z;
415		let yz = q.y * q.z;
416		let xw = q.x * q.w;
417		let yw = q.y * q.w;
418		let zw = q.z * q.w;
419		let mut result = Self::identity();
420		result.m[0][0] = T::ONE - T::TWO * (yy + zz);
421		result.m[0][1] = T::TWO * (xy + zw);
422		result.m[0][2] = T::TWO * (xz - yw);
423		result.m[1][0] = T::TWO * (xy - zw);
424		result.m[1][1] = T::ONE - T::TWO * (xx + zz);
425		result.m[1][2] = T::TWO * (yz + xw);
426		result.m[2][0] = T::TWO * (xz + yw);
427		result.m[2][1] = T::TWO * (yz - xw);
428		result.m[2][2] = T::ONE - T::TWO * (xx + yy);
429		Some(result)
430	}
431
432	pub fn try_compose_trs(translation: Vec3<T>, rotation: Quat<T>, scale: Vec3<T>) -> Option<Self> {
433		if !translation.is_finite() || !scale.is_finite() {
434			return None;
435		}
436		let mut result = Self::try_from_quaternion(rotation)?;
437		for column in 0..3 {
438			result.m[0][column] = result.m[0][column] * scale.x;
439			result.m[1][column] = result.m[1][column] * scale.y;
440			result.m[2][column] = result.m[2][column] * scale.z;
441		}
442		result.m[3][0] = translation.x;
443		result.m[3][1] = translation.y;
444		result.m[3][2] = translation.z;
445		Some(result)
446	}
447
448	pub fn approximately_equal(self, other: Self, absolute: T, relative: T) -> bool {
449		valid_tolerance(absolute)
450			&& valid_tolerance(relative)
451			&& self.m.iter().enumerate().all(|(row, values)| {
452				values
453					.iter()
454					.enumerate()
455					.all(|(column, value)| approx(*value, other.m[row][column], absolute, relative))
456			})
457	}
458}
459
460macro_rules! matrix_ops {
461	($matrix:ident, $size:expr $(, $product_inline:meta)?) => {
462		impl<T: Float> Add for $matrix<T> {
463			type Output = Self;
464
465			fn add(self, other: Self) -> Self {
466				let mut result = Self::default();
467				for row in 0..$size {
468					for column in 0..$size {
469						result.m[row][column] = self.m[row][column] + other.m[row][column];
470					}
471				}
472				result
473			}
474		}
475
476		impl<T: Float> Sub for $matrix<T> {
477			type Output = Self;
478
479			fn sub(self, other: Self) -> Self {
480				let mut result = Self::default();
481				for row in 0..$size {
482					for column in 0..$size {
483						result.m[row][column] = self.m[row][column] - other.m[row][column];
484					}
485				}
486				result
487			}
488		}
489
490		impl<T: Float> Mul<T> for $matrix<T> {
491			type Output = Self;
492
493			fn mul(self, scalar: T) -> Self {
494				let mut result = Self::default();
495				for row in 0..$size {
496					for column in 0..$size {
497						result.m[row][column] = self.m[row][column] * scalar;
498					}
499				}
500				result
501			}
502		}
503
504		impl<T: Float> Div<T> for $matrix<T> {
505			type Output = Self;
506
507			fn div(self, scalar: T) -> Self {
508				self * (T::ONE / scalar)
509			}
510		}
511
512		impl<T: Float> Neg for $matrix<T> {
513			type Output = Self;
514
515			fn neg(self) -> Self {
516				self * -T::ONE
517			}
518		}
519
520		impl<T: Float> Mul for $matrix<T> {
521			type Output = Self;
522
523			$(#[$product_inline])?
524			fn mul(self, other: Self) -> Self {
525				let mut result = Self::default();
526				for row in 0..$size {
527					for column in 0..$size {
528						for inner in 0..$size {
529							result.m[row][column] =
530								result.m[row][column] + self.m[row][inner] * other.m[inner][column];
531						}
532					}
533				}
534				result
535			}
536		}
537
538		impl<T: Float> AddAssign for $matrix<T> {
539			fn add_assign(&mut self, other: Self) {
540				*self = *self + other;
541			}
542		}
543
544		impl<T: Float> SubAssign for $matrix<T> {
545			fn sub_assign(&mut self, other: Self) {
546				*self = *self - other;
547			}
548		}
549
550		impl<T: Float> MulAssign<T> for $matrix<T> {
551			fn mul_assign(&mut self, scalar: T) {
552				*self = *self * scalar;
553			}
554		}
555
556		impl<T: Float> MulAssign for $matrix<T> {
557			fn mul_assign(&mut self, other: Self) {
558				*self = *self * other;
559			}
560		}
561
562		impl<T: Float> DivAssign<T> for $matrix<T> {
563			fn div_assign(&mut self, scalar: T) {
564				*self = *self / scalar;
565			}
566		}
567	};
568}
569
570matrix_ops!(Mat3, 3, inline);
571matrix_ops!(Mat4, 4);
572
573impl<T: Float> Mul<Mat3<T>> for Vec3<T> {
574	type Output = Self;
575
576	fn mul(self, matrix: Mat3<T>) -> Self {
577		Self {
578			x: self.x * matrix.m[0][0] + self.y * matrix.m[1][0] + self.z * matrix.m[2][0],
579			y: self.x * matrix.m[0][1] + self.y * matrix.m[1][1] + self.z * matrix.m[2][1],
580			z: self.x * matrix.m[0][2] + self.y * matrix.m[1][2] + self.z * matrix.m[2][2],
581		}
582	}
583}
584
585impl<T: Float> Mul<Mat4<T>> for Vec4<T> {
586	type Output = Self;
587
588	fn mul(self, matrix: Mat4<T>) -> Self {
589		Self {
590			x: self.x * matrix.m[0][0]
591				+ self.y * matrix.m[1][0]
592				+ self.z * matrix.m[2][0]
593				+ self.w * matrix.m[3][0],
594			y: self.x * matrix.m[0][1]
595				+ self.y * matrix.m[1][1]
596				+ self.z * matrix.m[2][1]
597				+ self.w * matrix.m[3][1],
598			z: self.x * matrix.m[0][2]
599				+ self.y * matrix.m[1][2]
600				+ self.z * matrix.m[2][2]
601				+ self.w * matrix.m[3][2],
602			w: self.x * matrix.m[0][3]
603				+ self.y * matrix.m[1][3]
604				+ self.z * matrix.m[2][3]
605				+ self.w * matrix.m[3][3],
606		}
607	}
608}
609
610macro_rules! scalar_left_matrix {
611	($scalar:ty, $matrix:ident) => {
612		impl Mul<$matrix<$scalar>> for $scalar {
613			type Output = $matrix<$scalar>;
614
615			fn mul(self, matrix: $matrix<$scalar>) -> Self::Output {
616				matrix * self
617			}
618		}
619	};
620}
621
622scalar_left_matrix!(f32, Mat3);
623scalar_left_matrix!(f32, Mat4);
624scalar_left_matrix!(f64, Mat3);
625scalar_left_matrix!(f64, Mat4);