1use crate::{Quat, Vec3, Vec4, vec3, vec4};
2use std::ops::{Add, Index, IndexMut, Mul, MulAssign, Sub};
3
4#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11#[non_exhaustive]
12pub enum MatrixError {
13 NonFiniteInput { input: &'static str },
15 Singular { column: usize },
17 ResultOutOfRange,
20 ZeroHomogeneousW,
22 InvalidPerspective { parameter: &'static str },
25 DegenerateOrthographic { axis: &'static str },
27 DegenerateDirection,
29 DegenerateUp,
31}
32
33impl std::fmt::Display for MatrixError {
34 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35 match self {
36 Self::NonFiniteInput { input } => write!(f, "{input} must contain only finite values"),
37 Self::Singular { column } => write!(f, "matrix has a zero pivot at column {column}; remove dependent or zero axes"),
38 Self::ResultOutOfRange => f.write_str("matrix operation exceeds usable f32 range; rescale inputs or reduce frustum extremes"),
39 Self::ZeroHomogeneousW => f.write_str("projected point has zero homogeneous w; choose a point away from the projection plane"),
40 Self::InvalidPerspective { parameter } => write!(f, "invalid perspective {parameter}; require 0 < fov_y < PI, aspect > 0, near > 0, and far > near when supplied"),
41 Self::DegenerateOrthographic { axis } => write!(f, "orthographic {axis} bounds must differ"),
42 Self::DegenerateDirection => f.write_str("camera direction must be nonzero; eye and target must differ"),
43 Self::DegenerateUp => f.write_str("camera up must be nonzero and nonparallel to its direction"),
44 }
45 }
46}
47
48impl std::error::Error for MatrixError {}
49
50#[repr(C)]
52#[derive(Clone, Copy, Debug, PartialEq)]
53pub struct Mat4 {
54 pub x_axis: Vec4,
55 pub y_axis: Vec4,
56 pub z_axis: Vec4,
57 pub w_axis: Vec4,
58}
59impl Default for Mat4 {
60 fn default() -> Self {
61 Self::IDENTITY
62 }
63}
64impl Mat4 {
65 pub const IDENTITY: Self = Self::from_cols(Vec4::X, Vec4::Y, Vec4::Z, Vec4::W);
66 pub const ZERO: Self = Self::from_cols(Vec4::ZERO, Vec4::ZERO, Vec4::ZERO, Vec4::ZERO);
67 pub const NAN: Self = Self::from_cols(Vec4::NAN, Vec4::NAN, Vec4::NAN, Vec4::NAN);
68 pub const fn from_cols(x_axis: Vec4, y_axis: Vec4, z_axis: Vec4, w_axis: Vec4) -> Self {
69 Self {
70 x_axis,
71 y_axis,
72 z_axis,
73 w_axis,
74 }
75 }
76 pub const fn from_cols_array(v: &[f32; 16]) -> Self {
77 Self::from_cols(
78 vec4(v[0], v[1], v[2], v[3]),
79 vec4(v[4], v[5], v[6], v[7]),
80 vec4(v[8], v[9], v[10], v[11]),
81 vec4(v[12], v[13], v[14], v[15]),
82 )
83 }
84 pub const fn from_cols_array_2d(v: &[[f32; 4]; 4]) -> Self {
85 Self::from_cols(
86 Vec4::from_array(v[0]),
87 Vec4::from_array(v[1]),
88 Vec4::from_array(v[2]),
89 Vec4::from_array(v[3]),
90 )
91 }
92 pub const fn to_cols_array(self) -> [f32; 16] {
93 let a = self.to_cols_array_2d();
94 [
95 a[0][0], a[0][1], a[0][2], a[0][3], a[1][0], a[1][1], a[1][2], a[1][3], a[2][0],
96 a[2][1], a[2][2], a[2][3], a[3][0], a[3][1], a[3][2], a[3][3],
97 ]
98 }
99 pub const fn to_cols_array_2d(self) -> [[f32; 4]; 4] {
100 [
101 self.x_axis.to_array(),
102 self.y_axis.to_array(),
103 self.z_axis.to_array(),
104 self.w_axis.to_array(),
105 ]
106 }
107 pub fn col(self, index: usize) -> Vec4 {
108 self[index]
109 }
110 pub fn row(self, index: usize) -> Vec4 {
111 vec4(
112 self.x_axis[index],
113 self.y_axis[index],
114 self.z_axis[index],
115 self.w_axis[index],
116 )
117 }
118 pub fn transpose(self) -> Self {
119 Self::from_cols(self.row(0), self.row(1), self.row(2), self.row(3))
120 }
121 pub const fn from_translation(v: Vec3) -> Self {
122 Self::from_cols(Vec4::X, Vec4::Y, Vec4::Z, v.extend(1.0))
123 }
124 pub const fn from_scale(v: Vec3) -> Self {
125 Self::from_diagonal(vec4(v.x, v.y, v.z, 1.0))
126 }
127 pub const fn from_diagonal(v: Vec4) -> Self {
128 Self::from_cols(
129 vec4(v.x, 0.0, 0.0, 0.0),
130 vec4(0.0, v.y, 0.0, 0.0),
131 vec4(0.0, 0.0, v.z, 0.0),
132 vec4(0.0, 0.0, 0.0, v.w),
133 )
134 }
135 pub fn from_quat(rotation: Quat) -> Self {
137 let q = rotation.normalize();
138 Self::from_cols(
139 (q * Vec3::X).extend(0.0),
140 (q * Vec3::Y).extend(0.0),
141 (q * Vec3::Z).extend(0.0),
142 Vec4::W,
143 )
144 }
145 pub fn from_axis_angle(axis: Vec3, angle: f32) -> Self {
146 Self::from_quat(Quat::from_axis_angle(axis, angle))
147 }
148 pub fn from_rotation_x(angle: f32) -> Self {
149 Self::from_quat(Quat::from_rotation_x(angle))
150 }
151 pub fn from_rotation_y(angle: f32) -> Self {
152 Self::from_quat(Quat::from_rotation_y(angle))
153 }
154 pub fn from_rotation_z(angle: f32) -> Self {
155 Self::from_quat(Quat::from_rotation_z(angle))
156 }
157 pub fn from_rotation_translation(rotation: Quat, translation: Vec3) -> Self {
158 Self::from_scale_rotation_translation(Vec3::ONE, rotation, translation)
159 }
160 pub fn from_scale_rotation_translation(scale: Vec3, rotation: Quat, translation: Vec3) -> Self {
161 let mut result = Self::from_quat(rotation);
162 result.x_axis *= scale.x;
163 result.y_axis *= scale.y;
164 result.z_axis *= scale.z;
165 result.w_axis = translation.extend(1.0);
166 result
167 }
168 pub fn transform_point3(self, v: Vec3) -> Vec3 {
169 (self * v.extend(1.0)).truncate()
170 }
171 pub fn transform_vector3(self, v: Vec3) -> Vec3 {
172 (self * v.extend(0.0)).truncate()
173 }
174 pub fn project_point3(self, v: Vec3) -> Vec3 {
175 let result = self * v.extend(1.0);
176 result.truncate() / result.w
177 }
178 pub fn try_project_point3(self, v: Vec3) -> Result<Vec3, MatrixError> {
200 finite_input("matrix", &self.to_cols_array())?;
201 finite_input("point", &v.to_array())?;
202 let point = v.extend(1.0).to_array().map(f64::from);
203 let projected: [f64; 4] = std::array::from_fn(|row| {
204 self.row(row)
205 .to_array()
206 .into_iter()
207 .zip(point)
208 .map(|(a, b)| f64::from(a) * b)
209 .sum()
210 });
211 if projected[3] == 0.0 {
212 return Err(MatrixError::ZeroHomogeneousW);
213 }
214 Ok(vec3(
215 finite_f32(projected[0] / projected[3])?,
216 finite_f32(projected[1] / projected[3])?,
217 finite_f32(projected[2] / projected[3])?,
218 ))
219 }
220 pub fn mul_vec4(self, v: Vec4) -> Vec4 {
221 self.x_axis * v.x + self.y_axis * v.y + self.z_axis * v.z + self.w_axis * v.w
222 }
223 pub fn mul_mat4(self, rhs: Self) -> Self {
224 self * rhs
225 }
226 pub fn is_finite(self) -> bool {
227 self.x_axis.is_finite()
228 && self.y_axis.is_finite()
229 && self.z_axis.is_finite()
230 && self.w_axis.is_finite()
231 }
232 pub fn is_nan(self) -> bool {
233 self.x_axis.is_nan() || self.y_axis.is_nan() || self.z_axis.is_nan() || self.w_axis.is_nan()
234 }
235 pub fn abs_diff_eq(self, rhs: Self, tolerance: f32) -> bool {
236 (0..4).all(|i| self[i].abs_diff_eq(rhs[i], tolerance))
237 }
238 pub fn determinant(self) -> f32 {
240 let mut rows = std::array::from_fn::<_, 4, _>(|r| self.row(r).to_array().map(f64::from));
241 let mut determinant = 1.0_f64;
242 for column in 0..4 {
243 let pivot = (column..4)
244 .max_by(|&a, &b| rows[a][column].abs().total_cmp(&rows[b][column].abs()))
245 .unwrap();
246 if rows[pivot][column] == 0.0 {
247 return 0.0;
248 }
249 if pivot != column {
250 rows.swap(pivot, column);
251 determinant = -determinant;
252 }
253 let divisor = rows[column][column];
254 determinant *= divisor;
255 let pivot_row = rows[column];
256 for row in rows.iter_mut().skip(column + 1) {
257 let ratio = row[column] / divisor;
258 for (value, pivot_value) in row.iter_mut().zip(pivot_row).skip(column + 1) {
259 *value -= ratio * pivot_value;
260 }
261 }
262 }
263 determinant as f32
264 }
265 pub fn try_inverse(self) -> Option<Self> {
268 self.checked_inverse().ok()
269 }
270 pub fn checked_inverse(self) -> Result<Self, MatrixError> {
292 finite_input("matrix", &self.to_cols_array())?;
293 let mut augmented = [[0.0_f64; 8]; 4];
294 for (row, values) in augmented.iter_mut().enumerate() {
295 for (column, value) in values.iter_mut().take(4).enumerate() {
296 *value = f64::from(self[column][row]);
297 }
298 values[row + 4] = 1.0;
299 }
300 for column in 0..4 {
301 let pivot = (column..4)
302 .max_by(|&a, &b| {
303 augmented[a][column]
304 .abs()
305 .total_cmp(&augmented[b][column].abs())
306 })
307 .unwrap();
308 let divisor = augmented[pivot][column];
309 if !divisor.is_finite() {
310 return Err(MatrixError::ResultOutOfRange);
311 }
312 if divisor == 0.0 {
313 return Err(MatrixError::Singular { column });
314 }
315 augmented.swap(column, pivot);
316 for value in &mut augmented[column] {
317 *value /= divisor;
318 }
319 let pivot_row = augmented[column];
320 for (row, values) in augmented.iter_mut().enumerate() {
321 if row == column {
322 continue;
323 }
324 let coefficient = values[column];
325 for (value, pivot_value) in values.iter_mut().zip(pivot_row) {
326 *value -= coefficient * pivot_value;
327 }
328 }
329 }
330 let mut result = Self::ZERO;
331 for row in 0..4 {
332 for column in 0..4 {
333 result[column][row] = finite_f32(augmented[row][column + 4])?;
334 }
335 }
336 Ok(result)
337 }
338 pub fn inverse(self) -> Self {
339 self.try_inverse().unwrap_or(Self::NAN)
340 }
341 pub fn look_at_rh(eye: Vec3, target: Vec3, up: Vec3) -> Self {
343 Self::look_to_rh(eye, target - eye, up)
344 }
345 pub fn look_to_rh(eye: Vec3, direction: Vec3, up: Vec3) -> Self {
346 let z = (-direction).normalize();
347 let x = up.cross(z).normalize();
348 let y = z.cross(x);
349 Self::from_cols(
350 vec4(x.x, y.x, z.x, 0.0),
351 vec4(x.y, y.y, z.y, 0.0),
352 vec4(x.z, y.z, z.z, 0.0),
353 vec4(-x.dot(eye), -y.dot(eye), -z.dot(eye), 1.0),
354 )
355 }
356 pub fn look_at_lh(eye: Vec3, target: Vec3, up: Vec3) -> Self {
357 Self::look_to_lh(eye, target - eye, up)
358 }
359 pub fn look_to_lh(eye: Vec3, direction: Vec3, up: Vec3) -> Self {
360 Self::look_to_rh(eye, -direction, up)
361 }
362 pub fn try_look_at_rh(eye: Vec3, target: Vec3, up: Vec3) -> Result<Self, MatrixError> {
380 finite_input("eye", &eye.to_array())?;
381 finite_input("target", &target.to_array())?;
382 view_from_f64(
383 eye,
384 std::array::from_fn(|i| f64::from(eye[i]) - f64::from(target[i])),
385 up,
386 )
387 }
388 pub fn try_look_to_rh(eye: Vec3, direction: Vec3, up: Vec3) -> Result<Self, MatrixError> {
396 finite_input("direction", &direction.to_array())?;
397 view_from_f64(eye, direction.to_array().map(|v| -f64::from(v)), up)
398 }
399 pub fn try_look_at_lh(eye: Vec3, target: Vec3, up: Vec3) -> Result<Self, MatrixError> {
407 finite_input("eye", &eye.to_array())?;
408 finite_input("target", &target.to_array())?;
409 view_from_f64(
410 eye,
411 std::array::from_fn(|i| f64::from(target[i]) - f64::from(eye[i])),
412 up,
413 )
414 }
415 pub fn try_look_to_lh(eye: Vec3, direction: Vec3, up: Vec3) -> Result<Self, MatrixError> {
423 finite_input("direction", &direction.to_array())?;
424 view_from_f64(eye, direction.to_array().map(f64::from), up)
425 }
426
427 pub fn perspective_rh_gl(fov_y: f32, aspect: f32, near: f32, far: f32) -> Self {
429 validate_perspective(fov_y, aspect, near, far);
430 let y = (0.5 * fov_y).tan().recip();
431 Self::from_cols(
432 vec4(y / aspect, 0.0, 0.0, 0.0),
433 vec4(0.0, y, 0.0, 0.0),
434 vec4(0.0, 0.0, (far + near) / (near - far), -1.0),
435 vec4(0.0, 0.0, 2.0 * far * near / (near - far), 0.0),
436 )
437 }
438 pub fn perspective_rh(fov_y: f32, aspect: f32, near: f32, far: f32) -> Self {
440 validate_perspective(fov_y, aspect, near, far);
441 let y = (0.5 * fov_y).tan().recip();
442 Self::from_cols(
443 vec4(y / aspect, 0.0, 0.0, 0.0),
444 vec4(0.0, y, 0.0, 0.0),
445 vec4(0.0, 0.0, far / (near - far), -1.0),
446 vec4(0.0, 0.0, far * near / (near - far), 0.0),
447 )
448 }
449 pub fn perspective_lh(fov_y: f32, aspect: f32, near: f32, far: f32) -> Self {
450 let mut result = Self::perspective_rh(fov_y, aspect, near, far);
451 result.z_axis = -result.z_axis;
452 result
453 }
454 pub fn perspective_infinite_rh(fov_y: f32, aspect: f32, near: f32) -> Self {
455 validate_perspective(fov_y, aspect, near, near * 2.0);
456 let y = (0.5 * fov_y).tan().recip();
457 Self::from_cols(
458 vec4(y / aspect, 0.0, 0.0, 0.0),
459 vec4(0.0, y, 0.0, 0.0),
460 vec4(0.0, 0.0, -1.0, -1.0),
461 vec4(0.0, 0.0, -near, 0.0),
462 )
463 }
464 pub fn perspective_infinite_reverse_rh(fov_y: f32, aspect: f32, near: f32) -> Self {
465 validate_perspective(fov_y, aspect, near, near * 2.0);
466 let y = (0.5 * fov_y).tan().recip();
467 Self::from_cols(
468 vec4(y / aspect, 0.0, 0.0, 0.0),
469 vec4(0.0, y, 0.0, 0.0),
470 vec4(0.0, 0.0, 0.0, -1.0),
471 vec4(0.0, 0.0, near, 0.0),
472 )
473 }
474 pub fn orthographic_rh_gl(
475 left: f32,
476 right: f32,
477 bottom: f32,
478 top: f32,
479 near: f32,
480 far: f32,
481 ) -> Self {
482 validate_orthographic(left, right, bottom, top, near, far);
483 Self::from_cols(
484 vec4(2.0 / (right - left), 0.0, 0.0, 0.0),
485 vec4(0.0, 2.0 / (top - bottom), 0.0, 0.0),
486 vec4(0.0, 0.0, -2.0 / (far - near), 0.0),
487 vec4(
488 -(right + left) / (right - left),
489 -(top + bottom) / (top - bottom),
490 -(far + near) / (far - near),
491 1.0,
492 ),
493 )
494 }
495 pub fn orthographic_rh(
496 left: f32,
497 right: f32,
498 bottom: f32,
499 top: f32,
500 near: f32,
501 far: f32,
502 ) -> Self {
503 validate_orthographic(left, right, bottom, top, near, far);
504 Self::from_cols(
505 vec4(2.0 / (right - left), 0.0, 0.0, 0.0),
506 vec4(0.0, 2.0 / (top - bottom), 0.0, 0.0),
507 vec4(0.0, 0.0, -1.0 / (far - near), 0.0),
508 vec4(
509 -(right + left) / (right - left),
510 -(top + bottom) / (top - bottom),
511 -near / (far - near),
512 1.0,
513 ),
514 )
515 }
516 pub fn orthographic_lh(
517 left: f32,
518 right: f32,
519 bottom: f32,
520 top: f32,
521 near: f32,
522 far: f32,
523 ) -> Self {
524 let mut result = Self::orthographic_rh(left, right, bottom, top, near, far);
525 result.z_axis = -result.z_axis;
526 result
527 }
528 pub fn try_perspective_rh_gl(
543 fov_y: f32,
544 aspect: f32,
545 near: f32,
546 far: f32,
547 ) -> Result<Self, MatrixError> {
548 checked_perspective(fov_y, aspect, near, far, true)
549 }
550 pub fn try_perspective_rh(
559 fov_y: f32,
560 aspect: f32,
561 near: f32,
562 far: f32,
563 ) -> Result<Self, MatrixError> {
564 checked_perspective(fov_y, aspect, near, far, false)
565 }
566 pub fn try_perspective_lh(
576 fov_y: f32,
577 aspect: f32,
578 near: f32,
579 far: f32,
580 ) -> Result<Self, MatrixError> {
581 let mut result = Self::try_perspective_rh(fov_y, aspect, near, far)?;
582 result.z_axis = -result.z_axis;
583 Ok(result)
584 }
585 pub fn try_perspective_infinite_rh(
594 fov_y: f32,
595 aspect: f32,
596 near: f32,
597 ) -> Result<Self, MatrixError> {
598 let (x, y) = perspective_scales(fov_y, aspect, near)?;
599 perspective_from_f64(x, y, -1.0, -f64::from(near))
600 }
601 pub fn try_perspective_infinite_reverse_rh(
611 fov_y: f32,
612 aspect: f32,
613 near: f32,
614 ) -> Result<Self, MatrixError> {
615 let (x, y) = perspective_scales(fov_y, aspect, near)?;
616 perspective_from_f64(x, y, 0.0, f64::from(near))
617 }
618 pub fn try_orthographic_rh_gl(
637 left: f32,
638 right: f32,
639 bottom: f32,
640 top: f32,
641 near: f32,
642 far: f32,
643 ) -> Result<Self, MatrixError> {
644 checked_orthographic([left, right, bottom, top, near, far], true)
645 }
646 pub fn try_orthographic_rh(
655 left: f32,
656 right: f32,
657 bottom: f32,
658 top: f32,
659 near: f32,
660 far: f32,
661 ) -> Result<Self, MatrixError> {
662 checked_orthographic([left, right, bottom, top, near, far], false)
663 }
664 pub fn try_orthographic_lh(
674 left: f32,
675 right: f32,
676 bottom: f32,
677 top: f32,
678 near: f32,
679 far: f32,
680 ) -> Result<Self, MatrixError> {
681 let mut result = Self::try_orthographic_rh(left, right, bottom, top, near, far)?;
682 result.z_axis = -result.z_axis;
683 Ok(result)
684 }
685 pub fn try_to_scale_rotation_translation(self) -> Option<(Vec3, Quat, Vec3)> {
688 if !self.is_finite() || !self.row(3).abs_diff_eq(Vec4::W, 1.0e-5) {
689 return None;
690 }
691 let mut scale = vec3(
692 self.x_axis.truncate().length(),
693 self.y_axis.truncate().length(),
694 self.z_axis.truncate().length(),
695 );
696 if scale.min_element() <= 0.0 {
697 return None;
698 }
699 if self.determinant() < 0.0 {
700 scale.x = -scale.x;
701 }
702 let x = self.x_axis.truncate() / scale.x;
703 let y = self.y_axis.truncate() / scale.y;
704 let z = self.z_axis.truncate() / scale.z;
705 if x.dot(y).abs() > 1.0e-4 || y.dot(z).abs() > 1.0e-4 || z.dot(x).abs() > 1.0e-4 {
706 return None;
707 }
708 let rotation = rotation_from_basis(x, y, z);
709 Some((scale, rotation, self.w_axis.truncate()))
710 }
711 pub fn to_scale_rotation_translation(self) -> (Vec3, Quat, Vec3) {
712 self.try_to_scale_rotation_translation()
713 .unwrap_or((Vec3::NAN, Quat::NAN, Vec3::NAN))
714 }
715}
716fn finite_input(input: &'static str, values: &[f32]) -> Result<(), MatrixError> {
717 if values.iter().all(|v| v.is_finite()) {
718 Ok(())
719 } else {
720 Err(MatrixError::NonFiniteInput { input })
721 }
722}
723
724fn finite_f32(value: f64) -> Result<f32, MatrixError> {
725 let value = value as f32;
726 if value.is_finite() {
727 Ok(value)
728 } else {
729 Err(MatrixError::ResultOutOfRange)
730 }
731}
732
733fn matrix_from_f64(columns: [[f64; 4]; 4]) -> Result<Mat4, MatrixError> {
734 let mut result = Mat4::ZERO;
735 for (column, values) in columns.into_iter().enumerate() {
736 for (row, value) in values.into_iter().enumerate() {
737 result[column][row] = finite_f32(value)?;
738 }
739 }
740 Ok(result)
741}
742
743fn dot3_f64(a: [f64; 3], b: [f64; 3]) -> f64 {
744 a.into_iter().zip(b).map(|(a, b)| a * b).sum()
745}
746
747fn cross3_f64(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
748 [
749 a[1] * b[2] - a[2] * b[1],
750 a[2] * b[0] - a[0] * b[2],
751 a[0] * b[1] - a[1] * b[0],
752 ]
753}
754
755fn unit3_f64(v: [f64; 3]) -> Option<[f64; 3]> {
756 let length = dot3_f64(v, v).sqrt();
757 (length > 0.0).then(|| v.map(|value| value / length))
758}
759
760fn view_from_f64(eye: Vec3, back: [f64; 3], up: Vec3) -> Result<Mat4, MatrixError> {
761 finite_input("eye", &eye.to_array())?;
762 finite_input("up", &up.to_array())?;
763 let z = unit3_f64(back).ok_or(MatrixError::DegenerateDirection)?;
764 let x = unit3_f64(cross3_f64(up.to_array().map(f64::from), back))
767 .ok_or(MatrixError::DegenerateUp)?;
768 let y = cross3_f64(z, x);
769 let eye = eye.to_array().map(f64::from);
770 matrix_from_f64([
771 [x[0], y[0], z[0], 0.0],
772 [x[1], y[1], z[1], 0.0],
773 [x[2], y[2], z[2], 0.0],
774 [-dot3_f64(x, eye), -dot3_f64(y, eye), -dot3_f64(z, eye), 1.0],
775 ])
776}
777
778fn perspective_scales(fov_y: f32, aspect: f32, near: f32) -> Result<(f64, f64), MatrixError> {
779 for (input, value) in [("fov_y", fov_y), ("aspect", aspect), ("near", near)] {
780 finite_input(input, &[value])?;
781 if value <= 0.0 || (input == "fov_y" && value >= std::f32::consts::PI) {
782 return Err(MatrixError::InvalidPerspective { parameter: input });
783 }
784 }
785 let y = (0.5 * f64::from(fov_y)).tan().recip();
786 Ok((y / f64::from(aspect), y))
787}
788
789fn perspective_from_f64(x: f64, y: f64, z: f64, depth: f64) -> Result<Mat4, MatrixError> {
790 let result = matrix_from_f64([
791 [x, 0.0, 0.0, 0.0],
792 [0.0, y, 0.0, 0.0],
793 [0.0, 0.0, z, -1.0],
794 [0.0, 0.0, depth, 0.0],
795 ])?;
796 if result.x_axis.x == 0.0 || result.y_axis.y == 0.0 || result.w_axis.z == 0.0 {
797 return Err(MatrixError::ResultOutOfRange);
798 }
799 Ok(result)
800}
801
802fn checked_perspective(
803 fov_y: f32,
804 aspect: f32,
805 near: f32,
806 far: f32,
807 gl: bool,
808) -> Result<Mat4, MatrixError> {
809 let (x, y) = perspective_scales(fov_y, aspect, near)?;
810 finite_input("far", &[far])?;
811 if far <= near {
812 return Err(MatrixError::InvalidPerspective { parameter: "far" });
813 }
814 let (near, far) = (f64::from(near), f64::from(far));
815 let span = near - far;
816 let z = if gl { (far + near) / span } else { far / span };
817 let depth = (if gl { 2.0 } else { 1.0 }) * far * near / span;
818 perspective_from_f64(x, y, z, depth)
819}
820
821fn checked_orthographic(bounds: [f32; 6], gl: bool) -> Result<Mat4, MatrixError> {
822 for (input, value) in ["left", "right", "bottom", "top", "near", "far"]
823 .into_iter()
824 .zip(bounds)
825 {
826 finite_input(input, &[value])?;
827 }
828 for (axis, pair) in ["x", "y", "z"].into_iter().zip(bounds.as_chunks::<2>().0) {
829 if pair[0] == pair[1] {
830 return Err(MatrixError::DegenerateOrthographic { axis });
831 }
832 }
833 let [left, right, bottom, top, near, far] = bounds.map(f64::from);
834 let (width, height, depth) = (right - left, top - bottom, far - near);
835 let result = matrix_from_f64([
836 [2.0 / width, 0.0, 0.0, 0.0],
837 [0.0, 2.0 / height, 0.0, 0.0],
838 [0.0, 0.0, -(if gl { 2.0 } else { 1.0 }) / depth, 0.0],
839 [
840 -(right + left) / width,
841 -(top + bottom) / height,
842 -(if gl { far + near } else { near }) / depth,
843 1.0,
844 ],
845 ])?;
846 if result.x_axis.x == 0.0 || result.y_axis.y == 0.0 || result.z_axis.z == 0.0 {
847 return Err(MatrixError::ResultOutOfRange);
848 }
849 Ok(result)
850}
851
852fn rotation_from_basis(x: Vec3, y: Vec3, z: Vec3) -> Quat {
853 let trace = x.x + y.y + z.z;
854 let q = if trace > 0.0 {
855 let s = (trace + 1.0).sqrt() * 2.0;
856 Quat::from_xyzw((y.z - z.y) / s, (z.x - x.z) / s, (x.y - y.x) / s, s * 0.25)
857 } else if x.x > y.y && x.x > z.z {
858 let s = (1.0 + x.x - y.y - z.z).sqrt() * 2.0;
859 Quat::from_xyzw(s * 0.25, (y.x + x.y) / s, (z.x + x.z) / s, (y.z - z.y) / s)
860 } else if y.y > z.z {
861 let s = (1.0 + y.y - x.x - z.z).sqrt() * 2.0;
862 Quat::from_xyzw((y.x + x.y) / s, s * 0.25, (z.y + y.z) / s, (z.x - x.z) / s)
863 } else {
864 let s = (1.0 + z.z - x.x - y.y).sqrt() * 2.0;
865 Quat::from_xyzw((z.x + x.z) / s, (z.y + y.z) / s, s * 0.25, (x.y - y.x) / s)
866 };
867 q.normalize()
868}
869fn validate_perspective(fov: f32, aspect: f32, near: f32, far: f32) {
870 assert!(
871 fov.is_finite()
872 && fov > 0.0
873 && fov < std::f32::consts::PI
874 && aspect.is_finite()
875 && aspect > 0.0
876 && near.is_finite()
877 && far.is_finite()
878 && near > 0.0
879 && far > near,
880 "invalid perspective frustum"
881 );
882}
883fn validate_orthographic(left: f32, right: f32, bottom: f32, top: f32, near: f32, far: f32) {
884 assert!(
885 [left, right, bottom, top, near, far]
886 .into_iter()
887 .all(f32::is_finite)
888 && left != right
889 && bottom != top
890 && near != far,
891 "invalid orthographic frustum"
892 );
893}
894impl Index<usize> for Mat4 {
895 type Output = Vec4;
896 fn index(&self, index: usize) -> &Vec4 {
897 match index {
898 0 => &self.x_axis,
899 1 => &self.y_axis,
900 2 => &self.z_axis,
901 3 => &self.w_axis,
902 _ => panic!("matrix column {index} is out of range"),
903 }
904 }
905}
906impl IndexMut<usize> for Mat4 {
907 fn index_mut(&mut self, index: usize) -> &mut Vec4 {
908 match index {
909 0 => &mut self.x_axis,
910 1 => &mut self.y_axis,
911 2 => &mut self.z_axis,
912 3 => &mut self.w_axis,
913 _ => panic!("matrix column {index} is out of range"),
914 }
915 }
916}
917impl Mul<Vec4> for Mat4 {
918 type Output = Vec4;
919 fn mul(self, rhs: Vec4) -> Vec4 {
920 self.mul_vec4(rhs)
921 }
922}
923impl Mul for Mat4 {
924 type Output = Self;
925 fn mul(self, rhs: Self) -> Self {
926 Self::from_cols(
927 self * rhs.x_axis,
928 self * rhs.y_axis,
929 self * rhs.z_axis,
930 self * rhs.w_axis,
931 )
932 }
933}
934impl Mul<f32> for Mat4 {
935 type Output = Self;
936 fn mul(self, rhs: f32) -> Self {
937 Self::from_cols(
938 self.x_axis * rhs,
939 self.y_axis * rhs,
940 self.z_axis * rhs,
941 self.w_axis * rhs,
942 )
943 }
944}
945impl Mul<Mat4> for f32 {
946 type Output = Mat4;
947 fn mul(self, rhs: Mat4) -> Mat4 {
948 rhs * self
949 }
950}
951impl MulAssign for Mat4 {
952 fn mul_assign(&mut self, rhs: Self) {
953 *self = *self * rhs;
954 }
955}
956impl Add for Mat4 {
957 type Output = Self;
958 fn add(self, rhs: Self) -> Self {
959 Self::from_cols(
960 self.x_axis + rhs.x_axis,
961 self.y_axis + rhs.y_axis,
962 self.z_axis + rhs.z_axis,
963 self.w_axis + rhs.w_axis,
964 )
965 }
966}
967impl Sub for Mat4 {
968 type Output = Self;
969 fn sub(self, rhs: Self) -> Self {
970 Self::from_cols(
971 self.x_axis - rhs.x_axis,
972 self.y_axis - rhs.y_axis,
973 self.z_axis - rhs.z_axis,
974 self.w_axis - rhs.w_axis,
975 )
976 }
977}