1use num_traits::{cast, NumCast};
17#[cfg(feature = "rand")]
18use rand::{
19 distributions::{Distribution, Standard},
20 Rng,
21};
22use std::fmt;
23use std::iter;
24use std::mem;
25use std::ops::*;
26
27use structure::*;
28
29use angle::Rad;
30use approx;
31use euler::Euler;
32use num::BaseFloat;
33use point::{Point2, Point3};
34use quaternion::Quaternion;
35use transform::{Transform, Transform2, Transform3};
36use vector::{Vector2, Vector3, Vector4};
37
38#[cfg(feature = "mint")]
39use mint;
40
41#[repr(C)]
45#[derive(Copy, Clone, PartialEq)]
46#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
47pub struct Matrix2<S> {
48 pub x: Vector2<S>,
50 pub y: Vector2<S>,
52}
53
54#[repr(C)]
58#[derive(Copy, Clone, PartialEq)]
59#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
60pub struct Matrix3<S> {
61 pub x: Vector3<S>,
63 pub y: Vector3<S>,
65 pub z: Vector3<S>,
67}
68
69#[repr(C)]
73#[derive(Copy, Clone, PartialEq)]
74#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
75pub struct Matrix4<S> {
76 pub x: Vector4<S>,
78 pub y: Vector4<S>,
80 pub z: Vector4<S>,
82 pub w: Vector4<S>,
84}
85
86impl<S> Matrix2<S> {
87 #[inline]
89 pub const fn new(c0r0: S, c0r1: S, c1r0: S, c1r1: S) -> Matrix2<S> {
90 Matrix2::from_cols(Vector2::new(c0r0, c0r1), Vector2::new(c1r0, c1r1))
91 }
92
93 #[inline]
95 pub const fn from_cols(c0: Vector2<S>, c1: Vector2<S>) -> Matrix2<S> {
96 Matrix2 { x: c0, y: c1 }
97 }
98}
99
100impl<S: BaseFloat> Matrix2<S> {
101 pub fn look_at(dir: Vector2<S>, up: Vector2<S>) -> Matrix2<S> {
104 Matrix2::look_at_stable(dir, up.x * dir.y >= up.y * dir.x)
105 }
106
107 pub fn look_at_stable(dir: Vector2<S>, flip: bool) -> Matrix2<S> {
111 let basis1 = dir.normalize();
112 let basis2 = if flip {
113 Vector2::new(basis1.y, -basis1.x)
114 } else {
115 Vector2::new(-basis1.y, basis1.x)
116 };
117 Matrix2::from_cols(basis1, basis2)
118 }
119
120 #[inline]
121 pub fn from_angle<A: Into<Rad<S>>>(theta: A) -> Matrix2<S> {
122 let (s, c) = Rad::sin_cos(theta.into());
123
124 Matrix2::new(c, s, -s, c)
125 }
126
127 pub fn is_finite(&self) -> bool {
129 self.x.is_finite() && self.y.is_finite()
130 }
131}
132
133impl<S> Matrix3<S> {
134 #[inline]
136 #[cfg_attr(rustfmt, rustfmt_skip)]
137 pub const fn new(
138 c0r0:S, c0r1:S, c0r2:S,
139 c1r0:S, c1r1:S, c1r2:S,
140 c2r0:S, c2r1:S, c2r2:S,
141 ) -> Matrix3<S> {
142 Matrix3::from_cols(
143 Vector3::new(c0r0, c0r1, c0r2),
144 Vector3::new(c1r0, c1r1, c1r2),
145 Vector3::new(c2r0, c2r1, c2r2),
146 )
147 }
148
149 #[inline]
151 pub const fn from_cols(c0: Vector3<S>, c1: Vector3<S>, c2: Vector3<S>) -> Matrix3<S> {
152 Matrix3 {
153 x: c0,
154 y: c1,
155 z: c2,
156 }
157 }
158}
159
160impl<S: BaseFloat> Matrix3<S> {
161 #[inline]
163 pub fn from_translation(v: Vector2<S>) -> Matrix3<S> {
164 #[cfg_attr(rustfmt, rustfmt_skip)]
165 Matrix3::new(
166 S::one(), S::zero(), S::zero(),
167 S::zero(), S::one(), S::zero(),
168 v.x, v.y, S::one(),
169 )
170 }
171
172 #[inline]
174 pub fn from_scale(value: S) -> Matrix3<S> {
175 Matrix3::from_nonuniform_scale(value, value)
176 }
177
178 #[inline]
180 pub fn from_nonuniform_scale(x: S, y: S) -> Matrix3<S> {
181 #[cfg_attr(rustfmt, rustfmt_skip)]
182 Matrix3::new(
183 x, S::zero(), S::zero(),
184 S::zero(), y, S::zero(),
185 S::zero(), S::zero(), S::one(),
186 )
187 }
188
189 #[deprecated = "Use Matrix3::look_to_lh"]
192 pub fn look_at(dir: Vector3<S>, up: Vector3<S>) -> Matrix3<S> {
193 Matrix3::look_to_lh(dir, up)
194 }
195
196 pub fn look_to_lh(dir: Vector3<S>, up: Vector3<S>) -> Matrix3<S> {
199 let dir = dir.normalize();
200 let side = up.cross(dir).normalize();
201 let up = dir.cross(side).normalize();
202
203 Matrix3::from_cols(side, up, dir).transpose()
204 }
205
206 pub fn look_to_rh(dir: Vector3<S>, up: Vector3<S>) -> Matrix3<S> {
209 Matrix3::look_to_lh(-dir, up)
210 }
211
212 pub fn from_angle_x<A: Into<Rad<S>>>(theta: A) -> Matrix3<S> {
214 let (s, c) = Rad::sin_cos(theta.into());
216
217 #[cfg_attr(rustfmt, rustfmt_skip)]
218 Matrix3::new(
219 S::one(), S::zero(), S::zero(),
220 S::zero(), c, s,
221 S::zero(), -s, c,
222 )
223 }
224
225 pub fn from_angle_y<A: Into<Rad<S>>>(theta: A) -> Matrix3<S> {
227 let (s, c) = Rad::sin_cos(theta.into());
229
230 #[cfg_attr(rustfmt, rustfmt_skip)]
231 Matrix3::new(
232 c, S::zero(), -s,
233 S::zero(), S::one(), S::zero(),
234 s, S::zero(), c,
235 )
236 }
237
238 pub fn from_angle_z<A: Into<Rad<S>>>(theta: A) -> Matrix3<S> {
240 let (s, c) = Rad::sin_cos(theta.into());
242
243 #[cfg_attr(rustfmt, rustfmt_skip)]
244 Matrix3::new(
245 c, s, S::zero(),
246 -s, c, S::zero(),
247 S::zero(), S::zero(), S::one(),
248 )
249 }
250
251 pub fn from_axis_angle<A: Into<Rad<S>>>(axis: Vector3<S>, angle: A) -> Matrix3<S> {
255 let (s, c) = Rad::sin_cos(angle.into());
256 let _1subc = S::one() - c;
257
258 #[cfg_attr(rustfmt, rustfmt_skip)]
259 Matrix3::new(
260 _1subc * axis.x * axis.x + c,
261 _1subc * axis.x * axis.y + s * axis.z,
262 _1subc * axis.x * axis.z - s * axis.y,
263
264 _1subc * axis.x * axis.y - s * axis.z,
265 _1subc * axis.y * axis.y + c,
266 _1subc * axis.y * axis.z + s * axis.x,
267
268 _1subc * axis.x * axis.z + s * axis.y,
269 _1subc * axis.y * axis.z - s * axis.x,
270 _1subc * axis.z * axis.z + c,
271 )
272 }
273
274 pub fn is_finite(&self) -> bool {
276 self.x.is_finite() && self.y.is_finite() && self.z.is_finite()
277 }
278}
279
280impl<S> Matrix4<S> {
281 #[inline]
283 #[cfg_attr(rustfmt, rustfmt_skip)]
284 pub const fn new(
285 c0r0: S, c0r1: S, c0r2: S, c0r3: S,
286 c1r0: S, c1r1: S, c1r2: S, c1r3: S,
287 c2r0: S, c2r1: S, c2r2: S, c2r3: S,
288 c3r0: S, c3r1: S, c3r2: S, c3r3: S,
289 ) -> Matrix4<S> {
290 Matrix4::from_cols(
291 Vector4::new(c0r0, c0r1, c0r2, c0r3),
292 Vector4::new(c1r0, c1r1, c1r2, c1r3),
293 Vector4::new(c2r0, c2r1, c2r2, c2r3),
294 Vector4::new(c3r0, c3r1, c3r2, c3r3),
295 )
296 }
297
298 #[inline]
300 pub const fn from_cols(
301 c0: Vector4<S>,
302 c1: Vector4<S>,
303 c2: Vector4<S>,
304 c3: Vector4<S>,
305 ) -> Matrix4<S> {
306 Matrix4 {
307 x: c0,
308 y: c1,
309 z: c2,
310 w: c3,
311 }
312 }
313}
314
315impl<S: BaseFloat> Matrix4<S> {
316 #[inline]
318 pub fn from_translation(v: Vector3<S>) -> Matrix4<S> {
319 #[cfg_attr(rustfmt, rustfmt_skip)]
320 Matrix4::new(
321 S::one(), S::zero(), S::zero(), S::zero(),
322 S::zero(), S::one(), S::zero(), S::zero(),
323 S::zero(), S::zero(), S::one(), S::zero(),
324 v.x, v.y, v.z, S::one(),
325 )
326 }
327
328 #[inline]
330 pub fn from_scale(value: S) -> Matrix4<S> {
331 Matrix4::from_nonuniform_scale(value, value, value)
332 }
333
334 #[inline]
336 pub fn from_nonuniform_scale(x: S, y: S, z: S) -> Matrix4<S> {
337 #[cfg_attr(rustfmt, rustfmt_skip)]
338 Matrix4::new(
339 x, S::zero(), S::zero(), S::zero(),
340 S::zero(), y, S::zero(), S::zero(),
341 S::zero(), S::zero(), z, S::zero(),
342 S::zero(), S::zero(), S::zero(), S::one(),
343 )
344 }
345
346 #[deprecated = "Use Matrix4::look_to_rh"]
349 pub fn look_at_dir(eye: Point3<S>, dir: Vector3<S>, up: Vector3<S>) -> Matrix4<S> {
350 let f = dir.normalize();
351 let s = f.cross(up).normalize();
352 let u = s.cross(f);
353
354 #[cfg_attr(rustfmt, rustfmt_skip)]
355 Matrix4::new(
356 s.x.clone(), u.x.clone(), -f.x.clone(), S::zero(),
357 s.y.clone(), u.y.clone(), -f.y.clone(), S::zero(),
358 s.z.clone(), u.z.clone(), -f.z.clone(), S::zero(),
359 -eye.dot(s), -eye.dot(u), eye.dot(f), S::one(),
360 )
361 }
362
363 pub fn look_to_rh(eye: Point3<S>, dir: Vector3<S>, up: Vector3<S>) -> Matrix4<S> {
366 let f = dir.normalize();
367 let s = f.cross(up).normalize();
368 let u = s.cross(f);
369
370 #[cfg_attr(rustfmt, rustfmt_skip)]
371 Matrix4::new(
372 s.x.clone(), u.x.clone(), -f.x.clone(), S::zero(),
373 s.y.clone(), u.y.clone(), -f.y.clone(), S::zero(),
374 s.z.clone(), u.z.clone(), -f.z.clone(), S::zero(),
375 -eye.dot(s), -eye.dot(u), eye.dot(f), S::one(),
376 )
377 }
378
379 pub fn look_to_lh(eye: Point3<S>, dir: Vector3<S>, up: Vector3<S>) -> Matrix4<S> {
382 Matrix4::look_to_rh(eye, -dir, up)
383 }
384
385 #[deprecated = "Use Matrix4::look_at_rh"]
388 pub fn look_at(eye: Point3<S>, center: Point3<S>, up: Vector3<S>) -> Matrix4<S> {
389 Matrix4::look_at_rh(eye, center, up)
390 }
391
392 pub fn look_at_rh(eye: Point3<S>, center: Point3<S>, up: Vector3<S>) -> Matrix4<S> {
395 Matrix4::look_to_rh(eye, center - eye, up)
396 }
397
398 pub fn look_at_lh(eye: Point3<S>, center: Point3<S>, up: Vector3<S>) -> Matrix4<S> {
401 Matrix4::look_to_lh(eye, center - eye, up)
402 }
403
404 pub fn from_angle_x<A: Into<Rad<S>>>(theta: A) -> Matrix4<S> {
406 let (s, c) = Rad::sin_cos(theta.into());
408
409 #[cfg_attr(rustfmt, rustfmt_skip)]
410 Matrix4::new(
411 S::one(), S::zero(), S::zero(), S::zero(),
412 S::zero(), c, s, S::zero(),
413 S::zero(), -s, c, S::zero(),
414 S::zero(), S::zero(), S::zero(), S::one(),
415 )
416 }
417
418 pub fn from_angle_y<A: Into<Rad<S>>>(theta: A) -> Matrix4<S> {
420 let (s, c) = Rad::sin_cos(theta.into());
422
423 #[cfg_attr(rustfmt, rustfmt_skip)]
424 Matrix4::new(
425 c, S::zero(), -s, S::zero(),
426 S::zero(), S::one(), S::zero(), S::zero(),
427 s, S::zero(), c, S::zero(),
428 S::zero(), S::zero(), S::zero(), S::one(),
429 )
430 }
431
432 pub fn from_angle_z<A: Into<Rad<S>>>(theta: A) -> Matrix4<S> {
434 let (s, c) = Rad::sin_cos(theta.into());
436
437 #[cfg_attr(rustfmt, rustfmt_skip)]
438 Matrix4::new(
439 c, s, S::zero(), S::zero(),
440 -s, c, S::zero(), S::zero(),
441 S::zero(), S::zero(), S::one(), S::zero(),
442 S::zero(), S::zero(), S::zero(), S::one(),
443 )
444 }
445
446 pub fn from_axis_angle<A: Into<Rad<S>>>(axis: Vector3<S>, angle: A) -> Matrix4<S> {
450 let (s, c) = Rad::sin_cos(angle.into());
451 let _1subc = S::one() - c;
452
453 #[cfg_attr(rustfmt, rustfmt_skip)]
454 Matrix4::new(
455 _1subc * axis.x * axis.x + c,
456 _1subc * axis.x * axis.y + s * axis.z,
457 _1subc * axis.x * axis.z - s * axis.y,
458 S::zero(),
459
460 _1subc * axis.x * axis.y - s * axis.z,
461 _1subc * axis.y * axis.y + c,
462 _1subc * axis.y * axis.z + s * axis.x,
463 S::zero(),
464
465 _1subc * axis.x * axis.z + s * axis.y,
466 _1subc * axis.y * axis.z - s * axis.x,
467 _1subc * axis.z * axis.z + c,
468 S::zero(),
469
470 S::zero(), S::zero(), S::zero(), S::one(),
471 )
472 }
473
474 pub fn is_finite(&self) -> bool {
476 self.w.is_finite() && self.x.is_finite() && self.y.is_finite() && self.z.is_finite()
477 }
478}
479
480impl<S: BaseFloat> Zero for Matrix2<S> {
481 #[inline]
482 fn zero() -> Matrix2<S> {
483 #[cfg_attr(rustfmt, rustfmt_skip)]
484 Matrix2::new(
485 S::zero(), S::zero(),
486 S::zero(), S::zero(),
487 )
488 }
489
490 #[inline]
491 fn is_zero(&self) -> bool {
492 ulps_eq!(self, &Self::zero())
493 }
494}
495
496impl<S: BaseFloat> Zero for Matrix3<S> {
497 #[inline]
498 fn zero() -> Matrix3<S> {
499 #[cfg_attr(rustfmt, rustfmt_skip)]
500 Matrix3::new(
501 S::zero(), S::zero(), S::zero(),
502 S::zero(), S::zero(), S::zero(),
503 S::zero(), S::zero(), S::zero(),
504 )
505 }
506
507 #[inline]
508 fn is_zero(&self) -> bool {
509 ulps_eq!(self, &Self::zero())
510 }
511}
512
513impl<S: BaseFloat> Zero for Matrix4<S> {
514 #[inline]
515 fn zero() -> Matrix4<S> {
516 #[cfg_attr(rustfmt, rustfmt_skip)]
517 Matrix4::new(
518 S::zero(), S::zero(), S::zero(), S::zero(),
519 S::zero(), S::zero(), S::zero(), S::zero(),
520 S::zero(), S::zero(), S::zero(), S::zero(),
521 S::zero(), S::zero(), S::zero(), S::zero(),
522 )
523 }
524
525 #[inline]
526 fn is_zero(&self) -> bool {
527 ulps_eq!(self, &Self::zero())
528 }
529}
530
531impl<S: BaseFloat> One for Matrix2<S> {
532 #[inline]
533 fn one() -> Matrix2<S> {
534 Matrix2::from_value(S::one())
535 }
536}
537
538impl<S: BaseFloat> One for Matrix3<S> {
539 #[inline]
540 fn one() -> Matrix3<S> {
541 Matrix3::from_value(S::one())
542 }
543}
544
545impl<S: BaseFloat> One for Matrix4<S> {
546 #[inline]
547 fn one() -> Matrix4<S> {
548 Matrix4::from_value(S::one())
549 }
550}
551
552impl<S: BaseFloat> VectorSpace for Matrix2<S> {
553 type Scalar = S;
554}
555
556impl<S: BaseFloat> VectorSpace for Matrix3<S> {
557 type Scalar = S;
558}
559
560impl<S: BaseFloat> VectorSpace for Matrix4<S> {
561 type Scalar = S;
562}
563
564impl<S: BaseFloat> Matrix for Matrix2<S> {
565 type Column = Vector2<S>;
566 type Row = Vector2<S>;
567 type Transpose = Matrix2<S>;
568
569 #[inline]
570 fn row(&self, r: usize) -> Vector2<S> {
571 Vector2::new(self[0][r], self[1][r])
572 }
573
574 #[inline]
575 fn swap_rows(&mut self, a: usize, b: usize) {
576 self[0].swap_elements(a, b);
577 self[1].swap_elements(a, b);
578 }
579
580 #[inline]
581 fn swap_columns(&mut self, a: usize, b: usize) {
582 let tmp = self[a];
583 self[a] = self[b];
584 self[b] = tmp;
585 }
586
587 #[inline]
588 fn swap_elements(&mut self, a: (usize, usize), b: (usize, usize)) {
589 let (ac, ar) = a;
590 let (bc, br) = b;
591 let tmp = self[ac][ar];
592 self[ac][ar] = self[bc][br];
593 self[bc][br] = tmp;
594 }
595
596 fn transpose(&self) -> Matrix2<S> {
597 #[cfg_attr(rustfmt, rustfmt_skip)]
598 Matrix2::new(
599 self[0][0], self[1][0],
600 self[0][1], self[1][1],
601 )
602 }
603}
604
605impl<S: BaseFloat> SquareMatrix for Matrix2<S> {
606 type ColumnRow = Vector2<S>;
607
608 #[inline]
609 fn from_value(value: S) -> Matrix2<S> {
610 #[cfg_attr(rustfmt, rustfmt_skip)]
611 Matrix2::new(
612 value, S::zero(),
613 S::zero(), value,
614 )
615 }
616
617 #[inline]
618 fn from_diagonal(value: Vector2<S>) -> Matrix2<S> {
619 #[cfg_attr(rustfmt, rustfmt_skip)]
620 Matrix2::new(
621 value.x, S::zero(),
622 S::zero(), value.y,
623 )
624 }
625
626 #[inline]
627 fn transpose_self(&mut self) {
628 self.swap_elements((0, 1), (1, 0));
629 }
630
631 #[inline]
632 fn determinant(&self) -> S {
633 self[0][0] * self[1][1] - self[1][0] * self[0][1]
634 }
635
636 #[inline]
637 fn diagonal(&self) -> Vector2<S> {
638 Vector2::new(self[0][0], self[1][1])
639 }
640
641 #[inline]
642 fn invert(&self) -> Option<Matrix2<S>> {
643 let det = self.determinant();
644 if det == S::zero() {
645 None
646 } else {
647 #[cfg_attr(rustfmt, rustfmt_skip)]
648 Some(Matrix2::new(
649 self[1][1] / det, -self[0][1] / det,
650 -self[1][0] / det, self[0][0] / det,
651 ))
652 }
653 }
654
655 #[inline]
656 fn is_diagonal(&self) -> bool {
657 ulps_eq!(self[0][1], &S::zero()) && ulps_eq!(self[1][0], &S::zero())
658 }
659
660 #[inline]
661 fn is_symmetric(&self) -> bool {
662 ulps_eq!(self[0][1], &self[1][0]) && ulps_eq!(self[1][0], &self[0][1])
663 }
664}
665
666impl<S: BaseFloat> Matrix for Matrix3<S> {
667 type Column = Vector3<S>;
668 type Row = Vector3<S>;
669 type Transpose = Matrix3<S>;
670
671 #[inline]
672 fn row(&self, r: usize) -> Vector3<S> {
673 Vector3::new(self[0][r], self[1][r], self[2][r])
674 }
675
676 #[inline]
677 fn swap_rows(&mut self, a: usize, b: usize) {
678 self[0].swap_elements(a, b);
679 self[1].swap_elements(a, b);
680 self[2].swap_elements(a, b);
681 }
682
683 #[inline]
684 fn swap_columns(&mut self, a: usize, b: usize) {
685 let tmp = self[a];
686 self[a] = self[b];
687 self[b] = tmp;
688 }
689
690 #[inline]
691 fn swap_elements(&mut self, a: (usize, usize), b: (usize, usize)) {
692 let (ac, ar) = a;
693 let (bc, br) = b;
694 let tmp = self[ac][ar];
695 self[ac][ar] = self[bc][br];
696 self[bc][br] = tmp;
697 }
698
699 fn transpose(&self) -> Matrix3<S> {
700 #[cfg_attr(rustfmt, rustfmt_skip)]
701 Matrix3::new(
702 self[0][0], self[1][0], self[2][0],
703 self[0][1], self[1][1], self[2][1],
704 self[0][2], self[1][2], self[2][2],
705 )
706 }
707}
708
709impl<S: BaseFloat> SquareMatrix for Matrix3<S> {
710 type ColumnRow = Vector3<S>;
711
712 #[inline]
713 fn from_value(value: S) -> Matrix3<S> {
714 #[cfg_attr(rustfmt, rustfmt_skip)]
715 Matrix3::new(
716 value, S::zero(), S::zero(),
717 S::zero(), value, S::zero(),
718 S::zero(), S::zero(), value,
719 )
720 }
721
722 #[inline]
723 fn from_diagonal(value: Vector3<S>) -> Matrix3<S> {
724 #[cfg_attr(rustfmt, rustfmt_skip)]
725 Matrix3::new(
726 value.x, S::zero(), S::zero(),
727 S::zero(), value.y, S::zero(),
728 S::zero(), S::zero(), value.z,
729 )
730 }
731
732 #[inline]
733 fn transpose_self(&mut self) {
734 self.swap_elements((0, 1), (1, 0));
735 self.swap_elements((0, 2), (2, 0));
736 self.swap_elements((1, 2), (2, 1));
737 }
738
739 fn determinant(&self) -> S {
740 self[0][0] * (self[1][1] * self[2][2] - self[2][1] * self[1][2])
741 - self[1][0] * (self[0][1] * self[2][2] - self[2][1] * self[0][2])
742 + self[2][0] * (self[0][1] * self[1][2] - self[1][1] * self[0][2])
743 }
744
745 #[inline]
746 fn diagonal(&self) -> Vector3<S> {
747 Vector3::new(self[0][0], self[1][1], self[2][2])
748 }
749
750 fn invert(&self) -> Option<Matrix3<S>> {
751 let det = self.determinant();
752 if det == S::zero() {
753 None
754 } else {
755 Some(
756 Matrix3::from_cols(
757 self[1].cross(self[2]) / det,
758 self[2].cross(self[0]) / det,
759 self[0].cross(self[1]) / det,
760 )
761 .transpose(),
762 )
763 }
764 }
765
766 fn is_diagonal(&self) -> bool {
767 ulps_eq!(self[0][1], &S::zero())
768 && ulps_eq!(self[0][2], &S::zero())
769 && ulps_eq!(self[1][0], &S::zero())
770 && ulps_eq!(self[1][2], &S::zero())
771 && ulps_eq!(self[2][0], &S::zero())
772 && ulps_eq!(self[2][1], &S::zero())
773 }
774
775 fn is_symmetric(&self) -> bool {
776 ulps_eq!(self[0][1], &self[1][0])
777 && ulps_eq!(self[0][2], &self[2][0])
778 && ulps_eq!(self[1][0], &self[0][1])
779 && ulps_eq!(self[1][2], &self[2][1])
780 && ulps_eq!(self[2][0], &self[0][2])
781 && ulps_eq!(self[2][1], &self[1][2])
782 }
783}
784
785impl<S: BaseFloat> Matrix for Matrix4<S> {
786 type Column = Vector4<S>;
787 type Row = Vector4<S>;
788 type Transpose = Matrix4<S>;
789
790 #[inline]
791 fn row(&self, r: usize) -> Vector4<S> {
792 Vector4::new(self[0][r], self[1][r], self[2][r], self[3][r])
793 }
794
795 #[inline]
796 fn swap_rows(&mut self, a: usize, b: usize) {
797 self[0].swap_elements(a, b);
798 self[1].swap_elements(a, b);
799 self[2].swap_elements(a, b);
800 self[3].swap_elements(a, b);
801 }
802
803 #[inline]
804 fn swap_columns(&mut self, a: usize, b: usize) {
805 let tmp = self[a];
806 self[a] = self[b];
807 self[b] = tmp;
808 }
809
810 #[inline]
811 fn swap_elements(&mut self, a: (usize, usize), b: (usize, usize)) {
812 let (ac, ar) = a;
813 let (bc, br) = b;
814 let tmp = self[ac][ar];
815 self[ac][ar] = self[bc][br];
816 self[bc][br] = tmp;
817 }
818
819 fn transpose(&self) -> Matrix4<S> {
820 #[cfg_attr(rustfmt, rustfmt_skip)]
821 Matrix4::new(
822 self[0][0], self[1][0], self[2][0], self[3][0],
823 self[0][1], self[1][1], self[2][1], self[3][1],
824 self[0][2], self[1][2], self[2][2], self[3][2],
825 self[0][3], self[1][3], self[2][3], self[3][3],
826 )
827 }
828}
829
830impl<S: BaseFloat> SquareMatrix for Matrix4<S> {
831 type ColumnRow = Vector4<S>;
832
833 #[inline]
834 fn from_value(value: S) -> Matrix4<S> {
835 #[cfg_attr(rustfmt, rustfmt_skip)]
836 Matrix4::new(
837 value, S::zero(), S::zero(), S::zero(),
838 S::zero(), value, S::zero(), S::zero(),
839 S::zero(), S::zero(), value, S::zero(),
840 S::zero(), S::zero(), S::zero(), value,
841 )
842 }
843
844 #[inline]
845 fn from_diagonal(value: Vector4<S>) -> Matrix4<S> {
846 #[cfg_attr(rustfmt, rustfmt_skip)]
847 Matrix4::new(
848 value.x, S::zero(), S::zero(), S::zero(),
849 S::zero(), value.y, S::zero(), S::zero(),
850 S::zero(), S::zero(), value.z, S::zero(),
851 S::zero(), S::zero(), S::zero(), value.w,
852 )
853 }
854
855 fn transpose_self(&mut self) {
856 self.swap_elements((0, 1), (1, 0));
857 self.swap_elements((0, 2), (2, 0));
858 self.swap_elements((0, 3), (3, 0));
859 self.swap_elements((1, 2), (2, 1));
860 self.swap_elements((1, 3), (3, 1));
861 self.swap_elements((2, 3), (3, 2));
862 }
863
864 fn determinant(&self) -> S {
865 let tmp = det_sub_proc(self, 1, 2, 3);
866 tmp.dot(Vector4::new(self[0][0], self[1][0], self[2][0], self[3][0]))
867 }
868
869 #[inline]
870 fn diagonal(&self) -> Vector4<S> {
871 Vector4::new(self[0][0], self[1][1], self[2][2], self[3][3])
872 }
873
874 #[cfg(not(feature = "simd"))]
880 fn invert(&self) -> Option<Matrix4<S>> {
881 let det = self.determinant();
882 if det == S::zero() {
883 None
884 } else {
885 let inv_det = S::one() / det;
886 let t = self.transpose();
887 let cf = |i, j| {
888 let mat = match i {
889 0 => {
890 Matrix3::from_cols(t.y.truncate_n(j), t.z.truncate_n(j), t.w.truncate_n(j))
891 }
892 1 => {
893 Matrix3::from_cols(t.x.truncate_n(j), t.z.truncate_n(j), t.w.truncate_n(j))
894 }
895 2 => {
896 Matrix3::from_cols(t.x.truncate_n(j), t.y.truncate_n(j), t.w.truncate_n(j))
897 }
898 3 => {
899 Matrix3::from_cols(t.x.truncate_n(j), t.y.truncate_n(j), t.z.truncate_n(j))
900 }
901 _ => panic!("out of range"),
902 };
903 let sign = if (i + j) & 1 == 1 {
904 -S::one()
905 } else {
906 S::one()
907 };
908 mat.determinant() * sign * inv_det
909 };
910
911 #[cfg_attr(rustfmt, rustfmt_skip)]
912 Some(Matrix4::new(
913 cf(0, 0), cf(0, 1), cf(0, 2), cf(0, 3),
914 cf(1, 0), cf(1, 1), cf(1, 2), cf(1, 3),
915 cf(2, 0), cf(2, 1), cf(2, 2), cf(2, 3),
916 cf(3, 0), cf(3, 1), cf(3, 2), cf(3, 3),
917 ))
918 }
919 }
920 #[cfg(feature = "simd")]
921 fn invert(&self) -> Option<Matrix4<S>> {
922 let tmp0 = det_sub_proc(self, 1, 2, 3);
925 let det = tmp0.dot(Vector4::new(self[0][0], self[1][0], self[2][0], self[3][0]));
926
927 if det == S::zero() {
928 None
929 } else {
930 let inv_det = S::one() / det;
931 let tmp0 = tmp0 * inv_det;
932 let tmp1 = det_sub_proc(self, 0, 3, 2) * inv_det;
933 let tmp2 = det_sub_proc(self, 0, 1, 3) * inv_det;
934 let tmp3 = det_sub_proc(self, 0, 2, 1) * inv_det;
935 Some(Matrix4::from_cols(tmp0, tmp1, tmp2, tmp3))
936 }
937 }
938
939 fn is_diagonal(&self) -> bool {
940 ulps_eq!(self[0][1], &S::zero())
941 && ulps_eq!(self[0][2], &S::zero())
942 && ulps_eq!(self[0][3], &S::zero())
943 && ulps_eq!(self[1][0], &S::zero())
944 && ulps_eq!(self[1][2], &S::zero())
945 && ulps_eq!(self[1][3], &S::zero())
946 && ulps_eq!(self[2][0], &S::zero())
947 && ulps_eq!(self[2][1], &S::zero())
948 && ulps_eq!(self[2][3], &S::zero())
949 && ulps_eq!(self[3][0], &S::zero())
950 && ulps_eq!(self[3][1], &S::zero())
951 && ulps_eq!(self[3][2], &S::zero())
952 }
953
954 fn is_symmetric(&self) -> bool {
955 ulps_eq!(self[0][1], &self[1][0])
956 && ulps_eq!(self[0][2], &self[2][0])
957 && ulps_eq!(self[0][3], &self[3][0])
958 && ulps_eq!(self[1][0], &self[0][1])
959 && ulps_eq!(self[1][2], &self[2][1])
960 && ulps_eq!(self[1][3], &self[3][1])
961 && ulps_eq!(self[2][0], &self[0][2])
962 && ulps_eq!(self[2][1], &self[1][2])
963 && ulps_eq!(self[2][3], &self[3][2])
964 && ulps_eq!(self[3][0], &self[0][3])
965 && ulps_eq!(self[3][1], &self[1][3])
966 && ulps_eq!(self[3][2], &self[2][3])
967 }
968}
969
970impl<S: BaseFloat> approx::AbsDiffEq for Matrix2<S> {
971 type Epsilon = S::Epsilon;
972
973 #[inline]
974 fn default_epsilon() -> S::Epsilon {
975 cast(1.0e-6f64).unwrap()
976 }
977
978 #[inline]
979 fn abs_diff_eq(&self, other: &Self, epsilon: S::Epsilon) -> bool {
980 Vector2::abs_diff_eq(&self[0], &other[0], epsilon)
981 && Vector2::abs_diff_eq(&self[1], &other[1], epsilon)
982 }
983}
984
985impl<S: BaseFloat> approx::RelativeEq for Matrix2<S> {
986 #[inline]
987 fn default_max_relative() -> S::Epsilon {
988 S::default_max_relative()
989 }
990
991 #[inline]
992 fn relative_eq(&self, other: &Self, epsilon: S::Epsilon, max_relative: S::Epsilon) -> bool {
993 Vector2::relative_eq(&self[0], &other[0], epsilon, max_relative)
994 && Vector2::relative_eq(&self[1], &other[1], epsilon, max_relative)
995 }
996}
997
998impl<S: BaseFloat> approx::UlpsEq for Matrix2<S> {
999 #[inline]
1000 fn default_max_ulps() -> u32 {
1001 S::default_max_ulps()
1002 }
1003
1004 #[inline]
1005 fn ulps_eq(&self, other: &Self, epsilon: S::Epsilon, max_ulps: u32) -> bool {
1006 Vector2::ulps_eq(&self[0], &other[0], epsilon, max_ulps)
1007 && Vector2::ulps_eq(&self[1], &other[1], epsilon, max_ulps)
1008 }
1009}
1010
1011impl<S: BaseFloat> approx::AbsDiffEq for Matrix3<S> {
1012 type Epsilon = S::Epsilon;
1013
1014 #[inline]
1015 fn default_epsilon() -> S::Epsilon {
1016 cast(1.0e-6f64).unwrap()
1017 }
1018
1019 #[inline]
1020 fn abs_diff_eq(&self, other: &Self, epsilon: S::Epsilon) -> bool {
1021 Vector3::abs_diff_eq(&self[0], &other[0], epsilon)
1022 && Vector3::abs_diff_eq(&self[1], &other[1], epsilon)
1023 && Vector3::abs_diff_eq(&self[2], &other[2], epsilon)
1024 }
1025}
1026
1027impl<S: BaseFloat> approx::RelativeEq for Matrix3<S> {
1028 #[inline]
1029 fn default_max_relative() -> S::Epsilon {
1030 S::default_max_relative()
1031 }
1032
1033 #[inline]
1034 fn relative_eq(&self, other: &Self, epsilon: S::Epsilon, max_relative: S::Epsilon) -> bool {
1035 Vector3::relative_eq(&self[0], &other[0], epsilon, max_relative)
1036 && Vector3::relative_eq(&self[1], &other[1], epsilon, max_relative)
1037 && Vector3::relative_eq(&self[2], &other[2], epsilon, max_relative)
1038 }
1039}
1040
1041impl<S: BaseFloat> approx::UlpsEq for Matrix3<S> {
1042 #[inline]
1043 fn default_max_ulps() -> u32 {
1044 S::default_max_ulps()
1045 }
1046
1047 #[inline]
1048 fn ulps_eq(&self, other: &Self, epsilon: S::Epsilon, max_ulps: u32) -> bool {
1049 Vector3::ulps_eq(&self[0], &other[0], epsilon, max_ulps)
1050 && Vector3::ulps_eq(&self[1], &other[1], epsilon, max_ulps)
1051 && Vector3::ulps_eq(&self[2], &other[2], epsilon, max_ulps)
1052 }
1053}
1054
1055impl<S: BaseFloat> approx::AbsDiffEq for Matrix4<S> {
1056 type Epsilon = S::Epsilon;
1057
1058 #[inline]
1059 fn default_epsilon() -> S::Epsilon {
1060 cast(1.0e-6f64).unwrap()
1061 }
1062
1063 #[inline]
1064 fn abs_diff_eq(&self, other: &Self, epsilon: S::Epsilon) -> bool {
1065 Vector4::abs_diff_eq(&self[0], &other[0], epsilon)
1066 && Vector4::abs_diff_eq(&self[1], &other[1], epsilon)
1067 && Vector4::abs_diff_eq(&self[2], &other[2], epsilon)
1068 && Vector4::abs_diff_eq(&self[3], &other[3], epsilon)
1069 }
1070}
1071
1072impl<S: BaseFloat> approx::RelativeEq for Matrix4<S> {
1073 #[inline]
1074 fn default_max_relative() -> S::Epsilon {
1075 S::default_max_relative()
1076 }
1077
1078 #[inline]
1079 fn relative_eq(&self, other: &Self, epsilon: S::Epsilon, max_relative: S::Epsilon) -> bool {
1080 Vector4::relative_eq(&self[0], &other[0], epsilon, max_relative)
1081 && Vector4::relative_eq(&self[1], &other[1], epsilon, max_relative)
1082 && Vector4::relative_eq(&self[2], &other[2], epsilon, max_relative)
1083 && Vector4::relative_eq(&self[3], &other[3], epsilon, max_relative)
1084 }
1085}
1086
1087impl<S: BaseFloat> approx::UlpsEq for Matrix4<S> {
1088 #[inline]
1089 fn default_max_ulps() -> u32 {
1090 S::default_max_ulps()
1091 }
1092
1093 #[inline]
1094 fn ulps_eq(&self, other: &Self, epsilon: S::Epsilon, max_ulps: u32) -> bool {
1095 Vector4::ulps_eq(&self[0], &other[0], epsilon, max_ulps)
1096 && Vector4::ulps_eq(&self[1], &other[1], epsilon, max_ulps)
1097 && Vector4::ulps_eq(&self[2], &other[2], epsilon, max_ulps)
1098 && Vector4::ulps_eq(&self[3], &other[3], epsilon, max_ulps)
1099 }
1100}
1101
1102impl<S: BaseFloat> Transform<Point2<S>> for Matrix3<S> {
1103 fn look_at(eye: Point2<S>, center: Point2<S>, up: Vector2<S>) -> Matrix3<S> {
1104 let dir = center - eye;
1105 Matrix3::from(Matrix2::look_at(dir, up))
1106 }
1107
1108 fn look_at_lh(eye: Point2<S>, center: Point2<S>, up: Vector2<S>) -> Matrix3<S> {
1109 let dir = center - eye;
1110 Matrix3::from(Matrix2::look_at(dir, up))
1111 }
1112
1113 fn look_at_rh(eye: Point2<S>, center: Point2<S>, up: Vector2<S>) -> Matrix3<S> {
1114 let dir = eye - center;
1115 Matrix3::from(Matrix2::look_at(dir, up))
1116 }
1117
1118 fn transform_vector(&self, vec: Vector2<S>) -> Vector2<S> {
1119 (self * vec.extend(S::zero())).truncate()
1120 }
1121
1122 fn transform_point(&self, point: Point2<S>) -> Point2<S> {
1123 Point2::from_vec((self * Point3::new(point.x, point.y, S::one()).to_vec()).truncate())
1124 }
1125
1126 fn concat(&self, other: &Matrix3<S>) -> Matrix3<S> {
1127 self * other
1128 }
1129
1130 fn inverse_transform(&self) -> Option<Matrix3<S>> {
1131 SquareMatrix::invert(self)
1132 }
1133}
1134
1135impl<S: BaseFloat> Transform<Point3<S>> for Matrix3<S> {
1136 fn look_at(eye: Point3<S>, center: Point3<S>, up: Vector3<S>) -> Matrix3<S> {
1137 let dir = center - eye;
1138 Matrix3::look_to_lh(dir, up)
1139 }
1140
1141 fn look_at_lh(eye: Point3<S>, center: Point3<S>, up: Vector3<S>) -> Matrix3<S> {
1142 let dir = center - eye;
1143 Matrix3::look_to_lh(dir, up)
1144 }
1145
1146 fn look_at_rh(eye: Point3<S>, center: Point3<S>, up: Vector3<S>) -> Matrix3<S> {
1147 let dir = center - eye;
1148 Matrix3::look_to_rh(dir, up)
1149 }
1150
1151 fn transform_vector(&self, vec: Vector3<S>) -> Vector3<S> {
1152 self * vec
1153 }
1154
1155 fn transform_point(&self, point: Point3<S>) -> Point3<S> {
1156 Point3::from_vec(self * point.to_vec())
1157 }
1158
1159 fn concat(&self, other: &Matrix3<S>) -> Matrix3<S> {
1160 self * other
1161 }
1162
1163 fn inverse_transform(&self) -> Option<Matrix3<S>> {
1164 SquareMatrix::invert(self)
1165 }
1166}
1167
1168impl<S: BaseFloat> Transform<Point3<S>> for Matrix4<S> {
1169
1170 fn look_at(eye: Point3<S>, center: Point3<S>, up: Vector3<S>) -> Matrix4<S> {
1171 Matrix4::look_at_rh(eye, center, up)
1172 }
1173
1174 fn look_at_lh(eye: Point3<S>, center: Point3<S>, up: Vector3<S>) -> Matrix4<S> {
1175 Matrix4::look_at_lh(eye, center, up)
1176 }
1177
1178 fn look_at_rh(eye: Point3<S>, center: Point3<S>, up: Vector3<S>) -> Matrix4<S> {
1179 Matrix4::look_at_rh(eye, center, up)
1180 }
1181
1182 fn transform_vector(&self, vec: Vector3<S>) -> Vector3<S> {
1183 (self * vec.extend(S::zero())).truncate()
1184 }
1185
1186 fn transform_point(&self, point: Point3<S>) -> Point3<S> {
1187 Point3::from_homogeneous(self * point.to_homogeneous())
1188 }
1189
1190 fn concat(&self, other: &Matrix4<S>) -> Matrix4<S> {
1191 self * other
1192 }
1193
1194 fn inverse_transform(&self) -> Option<Matrix4<S>> {
1195 SquareMatrix::invert(self)
1196 }
1197}
1198
1199impl<S: BaseFloat> Transform2 for Matrix3<S> {
1200 type Scalar = S;
1201}
1202
1203impl<S: BaseFloat> Transform3 for Matrix3<S> {
1204 type Scalar = S;
1205}
1206
1207impl<S: BaseFloat> Transform3 for Matrix4<S> {
1208 type Scalar = S;
1209}
1210
1211macro_rules! impl_matrix {
1212 ($MatrixN:ident, $VectorN:ident { $($field:ident : $row_index:expr),+ }) => {
1213 impl_operator!(<S: BaseFloat> Neg for $MatrixN<S> {
1214 fn neg(matrix) -> $MatrixN<S> { $MatrixN { $($field: -matrix.$field),+ } }
1215 });
1216
1217 impl_operator!(<S: BaseFloat> Mul<S> for $MatrixN<S> {
1218 fn mul(matrix, scalar) -> $MatrixN<S> { $MatrixN { $($field: matrix.$field * scalar),+ } }
1219 });
1220 impl_operator!(<S: BaseFloat> Div<S> for $MatrixN<S> {
1221 fn div(matrix, scalar) -> $MatrixN<S> { $MatrixN { $($field: matrix.$field / scalar),+ } }
1222 });
1223 impl_operator!(<S: BaseFloat> Rem<S> for $MatrixN<S> {
1224 fn rem(matrix, scalar) -> $MatrixN<S> { $MatrixN { $($field: matrix.$field % scalar),+ } }
1225 });
1226 impl_assignment_operator!(<S: BaseFloat> MulAssign<S> for $MatrixN<S> {
1227 fn mul_assign(&mut self, scalar) { $(self.$field *= scalar);+ }
1228 });
1229 impl_assignment_operator!(<S: BaseFloat> DivAssign<S> for $MatrixN<S> {
1230 fn div_assign(&mut self, scalar) { $(self.$field /= scalar);+ }
1231 });
1232 impl_assignment_operator!(<S: BaseFloat> RemAssign<S> for $MatrixN<S> {
1233 fn rem_assign(&mut self, scalar) { $(self.$field %= scalar);+ }
1234 });
1235
1236 impl_operator!(<S: BaseFloat> Add<$MatrixN<S> > for $MatrixN<S> {
1237 fn add(lhs, rhs) -> $MatrixN<S> { $MatrixN { $($field: lhs.$field + rhs.$field),+ } }
1238 });
1239 impl_operator!(<S: BaseFloat> Sub<$MatrixN<S> > for $MatrixN<S> {
1240 fn sub(lhs, rhs) -> $MatrixN<S> { $MatrixN { $($field: lhs.$field - rhs.$field),+ } }
1241 });
1242 impl<S: BaseFloat + AddAssign<S>> AddAssign<$MatrixN<S>> for $MatrixN<S> {
1243 fn add_assign(&mut self, other: $MatrixN<S>) { $(self.$field += other.$field);+ }
1244 }
1245 impl<S: BaseFloat + SubAssign<S>> SubAssign<$MatrixN<S>> for $MatrixN<S> {
1246 fn sub_assign(&mut self, other: $MatrixN<S>) { $(self.$field -= other.$field);+ }
1247 }
1248
1249 impl<S: BaseFloat> iter::Sum<$MatrixN<S>> for $MatrixN<S> {
1250 #[inline]
1251 fn sum<I: Iterator<Item=$MatrixN<S>>>(iter: I) -> $MatrixN<S> {
1252 iter.fold($MatrixN::zero(), Add::add)
1253 }
1254 }
1255
1256 impl<'a, S: 'a + BaseFloat> iter::Sum<&'a $MatrixN<S>> for $MatrixN<S> {
1257 #[inline]
1258 fn sum<I: Iterator<Item=&'a $MatrixN<S>>>(iter: I) -> $MatrixN<S> {
1259 iter.fold($MatrixN::zero(), Add::add)
1260 }
1261 }
1262
1263 impl<S: BaseFloat> iter::Product for $MatrixN<S> {
1264 #[inline]
1265 fn product<I: Iterator<Item=$MatrixN<S>>>(iter: I) -> $MatrixN<S> {
1266 iter.fold($MatrixN::identity(), Mul::mul)
1267 }
1268 }
1269
1270 impl<'a, S: 'a + BaseFloat> iter::Product<&'a $MatrixN<S>> for $MatrixN<S> {
1271 #[inline]
1272 fn product<I: Iterator<Item=&'a $MatrixN<S>>>(iter: I) -> $MatrixN<S> {
1273 iter.fold($MatrixN::identity(), Mul::mul)
1274 }
1275 }
1276
1277 impl_scalar_ops!($MatrixN<usize> { $($field),+ });
1278 impl_scalar_ops!($MatrixN<u8> { $($field),+ });
1279 impl_scalar_ops!($MatrixN<u16> { $($field),+ });
1280 impl_scalar_ops!($MatrixN<u32> { $($field),+ });
1281 impl_scalar_ops!($MatrixN<u64> { $($field),+ });
1282 impl_scalar_ops!($MatrixN<isize> { $($field),+ });
1283 impl_scalar_ops!($MatrixN<i8> { $($field),+ });
1284 impl_scalar_ops!($MatrixN<i16> { $($field),+ });
1285 impl_scalar_ops!($MatrixN<i32> { $($field),+ });
1286 impl_scalar_ops!($MatrixN<i64> { $($field),+ });
1287 impl_scalar_ops!($MatrixN<f32> { $($field),+ });
1288 impl_scalar_ops!($MatrixN<f64> { $($field),+ });
1289
1290
1291 impl<S: NumCast + Copy> $MatrixN<S> {
1292 #[inline]
1294 pub fn cast<T: NumCast>(&self) -> Option<$MatrixN<T>> {
1295 $(
1296 let $field = match self.$field.cast() {
1297 Some(field) => field,
1298 None => return None
1299 };
1300 )+
1301 Some($MatrixN { $($field),+ })
1302 }
1303 }
1304 }
1305}
1306
1307macro_rules! impl_scalar_ops {
1308 ($MatrixN:ident<$S:ident> { $($field:ident),+ }) => {
1309 impl_operator!(Mul<$MatrixN<$S>> for $S {
1310 fn mul(scalar, matrix) -> $MatrixN<$S> { $MatrixN { $($field: scalar * matrix.$field),+ } }
1311 });
1312 impl_operator!(Div<$MatrixN<$S>> for $S {
1313 fn div(scalar, matrix) -> $MatrixN<$S> { $MatrixN { $($field: scalar / matrix.$field),+ } }
1314 });
1315 impl_operator!(Rem<$MatrixN<$S>> for $S {
1316 fn rem(scalar, matrix) -> $MatrixN<$S> { $MatrixN { $($field: scalar % matrix.$field),+ } }
1317 });
1318 };
1319}
1320
1321impl_matrix!(Matrix2, Vector2 { x: 0, y: 1 });
1322impl_matrix!(Matrix3, Vector3 { x: 0, y: 1, z: 2 });
1323#[cfg_attr(rustfmt, rustfmt_skip)]
1324impl_matrix!(Matrix4, Vector4 { x: 0, y: 1, z: 2, w: 3 });
1325
1326macro_rules! impl_mv_operator {
1327 ($MatrixN:ident, $VectorN:ident { $($field:ident : $row_index:expr),+ }) => {
1328 impl_operator!(<S: BaseFloat> Mul<$VectorN<S> > for $MatrixN<S> {
1329 fn mul(matrix, vector) -> $VectorN<S> {$VectorN::new($(matrix.row($row_index).dot(vector.clone())),+)}
1330 });
1331 }
1332}
1333
1334impl_mv_operator!(Matrix2, Vector2 { x: 0, y: 1 });
1335impl_mv_operator!(Matrix3, Vector3 { x: 0, y: 1, z: 2 });
1336#[cfg(not(feature = "simd"))]
1337#[cfg_attr(rustfmt, rustfmt_skip)]
1338impl_mv_operator!(Matrix4, Vector4 { x: 0, y: 1, z: 2, w: 3 });
1339
1340#[cfg(feature = "simd")]
1341impl_operator!(<S: BaseFloat> Mul<Vector4<S> > for Matrix4<S> {
1342 fn mul(matrix, vector) -> Vector4<S> {
1343 matrix[0] * vector[0] + matrix[1] * vector[1] + matrix[2] * vector[2] + matrix[3] * vector[3]
1344 }
1345});
1346
1347impl_operator!(<S: BaseFloat> Mul<Matrix2<S> > for Matrix2<S> {
1348 fn mul(lhs, rhs) -> Matrix2<S> {
1349 Matrix2::new(lhs.row(0).dot(rhs[0]), lhs.row(1).dot(rhs[0]),
1350 lhs.row(0).dot(rhs[1]), lhs.row(1).dot(rhs[1]))
1351 }
1352});
1353
1354impl_operator!(<S: BaseFloat> Mul<Matrix3<S> > for Matrix3<S> {
1355 fn mul(lhs, rhs) -> Matrix3<S> {
1356 Matrix3::new(lhs.row(0).dot(rhs[0]), lhs.row(1).dot(rhs[0]), lhs.row(2).dot(rhs[0]),
1357 lhs.row(0).dot(rhs[1]), lhs.row(1).dot(rhs[1]), lhs.row(2).dot(rhs[1]),
1358 lhs.row(0).dot(rhs[2]), lhs.row(1).dot(rhs[2]), lhs.row(2).dot(rhs[2]))
1359 }
1360});
1361
1362impl_operator!(<S: BaseFloat> Mul<Matrix4<S> > for Matrix4<S> {
1369 fn mul(lhs, rhs) -> Matrix4<S> {
1370 {
1371 let a = lhs[0];
1372 let b = lhs[1];
1373 let c = lhs[2];
1374 let d = lhs[3];
1375
1376 #[cfg_attr(rustfmt, rustfmt_skip)]
1377 Matrix4::from_cols(
1378 a*rhs[0][0] + b*rhs[0][1] + c*rhs[0][2] + d*rhs[0][3],
1379 a*rhs[1][0] + b*rhs[1][1] + c*rhs[1][2] + d*rhs[1][3],
1380 a*rhs[2][0] + b*rhs[2][1] + c*rhs[2][2] + d*rhs[2][3],
1381 a*rhs[3][0] + b*rhs[3][1] + c*rhs[3][2] + d*rhs[3][3],
1382 )
1383 }
1384 }
1385});
1386
1387macro_rules! index_operators {
1388 ($MatrixN:ident<$S:ident>, $n:expr, $Output:ty, $I:ty) => {
1389 impl<$S> Index<$I> for $MatrixN<$S> {
1390 type Output = $Output;
1391
1392 #[inline]
1393 fn index<'a>(&'a self, i: $I) -> &'a $Output {
1394 let v: &[[$S; $n]; $n] = self.as_ref();
1395 From::from(&v[i])
1396 }
1397 }
1398
1399 impl<$S> IndexMut<$I> for $MatrixN<$S> {
1400 #[inline]
1401 fn index_mut<'a>(&'a mut self, i: $I) -> &'a mut $Output {
1402 let v: &mut [[$S; $n]; $n] = self.as_mut();
1403 From::from(&mut v[i])
1404 }
1405 }
1406 };
1407}
1408
1409index_operators!(Matrix2<S>, 2, Vector2<S>, usize);
1410index_operators!(Matrix3<S>, 3, Vector3<S>, usize);
1411index_operators!(Matrix4<S>, 4, Vector4<S>, usize);
1412impl<A> From<Euler<A>> for Matrix3<A::Unitless>
1426where
1427 A: Angle + Into<Rad<<A as Angle>::Unitless>>,
1428{
1429 fn from(src: Euler<A>) -> Matrix3<A::Unitless> {
1430 let (sx, cx) = Rad::sin_cos(src.x.into());
1432 let (sy, cy) = Rad::sin_cos(src.y.into());
1433 let (sz, cz) = Rad::sin_cos(src.z.into());
1434
1435 #[cfg_attr(rustfmt, rustfmt_skip)]
1436 Matrix3::new(
1437 cy * cz, cx * sz + sx * sy * cz, sx * sz - cx * sy * cz,
1438 -cy * sz, cx * cz - sx * sy * sz, sx * cz + cx * sy * sz,
1439 sy, -sx * cy, cx * cy,
1440 )
1441 }
1442}
1443
1444impl<A> From<Euler<A>> for Matrix4<A::Unitless>
1445where
1446 A: Angle + Into<Rad<<A as Angle>::Unitless>>,
1447{
1448 fn from(src: Euler<A>) -> Matrix4<A::Unitless> {
1449 let (sx, cx) = Rad::sin_cos(src.x.into());
1451 let (sy, cy) = Rad::sin_cos(src.y.into());
1452 let (sz, cz) = Rad::sin_cos(src.z.into());
1453
1454 #[cfg_attr(rustfmt, rustfmt_skip)]
1455 Matrix4::new(
1456 cy * cz, cx * sz + sx * sy * cz, sx * sz - cx * sy * cz, A::Unitless::zero(),
1457 -cy * sz, cx * cz - sx * sy * sz, sx * cz + cx * sy * sz, A::Unitless::zero(),
1458 sy, -sx * cy, cx * cy, A::Unitless::zero(),
1459 A::Unitless::zero(), A::Unitless::zero(), A::Unitless::zero(), A::Unitless::one(),
1460 )
1461 }
1462}
1463
1464macro_rules! fixed_array_conversions {
1465 ($MatrixN:ident <$S:ident> { $($field:ident : $index:expr),+ }, $n:expr) => {
1466 impl<$S> Into<[[$S; $n]; $n]> for $MatrixN<$S> {
1467 #[inline]
1468 fn into(self) -> [[$S; $n]; $n] {
1469 match self { $MatrixN { $($field),+ } => [$($field.into()),+] }
1470 }
1471 }
1472
1473 impl<$S> AsRef<[[$S; $n]; $n]> for $MatrixN<$S> {
1474 #[inline]
1475 fn as_ref(&self) -> &[[$S; $n]; $n] {
1476 unsafe { mem::transmute(self) }
1482 }
1483 }
1484
1485 impl<$S> AsMut<[[$S; $n]; $n]> for $MatrixN<$S> {
1486 #[inline]
1487 fn as_mut(&mut self) -> &mut [[$S; $n]; $n] {
1488 unsafe { mem::transmute(self) }
1491 }
1492 }
1493
1494 impl<$S: Copy> From<[[$S; $n]; $n]> for $MatrixN<$S> {
1495 #[inline]
1496 fn from(m: [[$S; $n]; $n]) -> $MatrixN<$S> {
1497 $MatrixN { $($field: From::from(m[$index])),+ }
1499 }
1500 }
1501
1502 impl<'a, $S> From<&'a [[$S; $n]; $n]> for &'a $MatrixN<$S> {
1503 #[inline]
1504 fn from(m: &'a [[$S; $n]; $n]) -> &'a $MatrixN<$S> {
1505 unsafe { mem::transmute(m) }
1507 }
1508 }
1509
1510 impl<'a, $S> From<&'a mut [[$S; $n]; $n]> for &'a mut $MatrixN<$S> {
1511 #[inline]
1512 fn from(m: &'a mut [[$S; $n]; $n]) -> &'a mut $MatrixN<$S> {
1513 unsafe { mem::transmute(m) }
1515 }
1516 }
1517
1518 impl<$S> AsRef<[$S; ($n * $n)]> for $MatrixN<$S> {
1527 #[inline]
1528 fn as_ref(&self) -> &[$S; ($n * $n)] {
1529 unsafe { mem::transmute(self) }
1533 }
1534 }
1535
1536 impl<$S> AsMut<[$S; ($n * $n)]> for $MatrixN<$S> {
1537 #[inline]
1538 fn as_mut(&mut self) -> &mut [$S; ($n * $n)] {
1539 unsafe { mem::transmute(self) }
1542 }
1543 }
1544
1545 impl<'a, $S> From<&'a [$S; ($n * $n)]> for &'a $MatrixN<$S> {
1554 #[inline]
1555 fn from(m: &'a [$S; ($n * $n)]) -> &'a $MatrixN<$S> {
1556 unsafe { mem::transmute(m) }
1558 }
1559 }
1560
1561 impl<'a, $S> From<&'a mut [$S; ($n * $n)]> for &'a mut $MatrixN<$S> {
1562 #[inline]
1563 fn from(m: &'a mut [$S; ($n * $n)]) -> &'a mut $MatrixN<$S> {
1564 unsafe { mem::transmute(m) }
1566 }
1567 }
1568 }
1569}
1570
1571fixed_array_conversions!(Matrix2<S> { x:0, y:1 }, 2);
1572fixed_array_conversions!(Matrix3<S> { x:0, y:1, z:2 }, 3);
1573fixed_array_conversions!(Matrix4<S> { x:0, y:1, z:2, w:3 }, 4);
1574
1575#[cfg(feature = "mint")]
1576macro_rules! mint_conversions {
1577 ($MatrixN:ident { $($field:ident),+ }, $MintN:ident) => {
1578 impl<S: Clone> Into<mint::$MintN<S>> for $MatrixN<S> {
1579 #[inline]
1580 fn into(self) -> mint::$MintN<S> {
1581 mint::$MintN { $($field: self.$field.into()),+ }
1582 }
1583 }
1584
1585 impl<S> From<mint::$MintN<S>> for $MatrixN<S> {
1586 #[inline]
1587 fn from(m: mint::$MintN<S>) -> Self {
1588 $MatrixN { $($field: m.$field.into()),+ }
1589 }
1590 }
1591
1592 }
1593}
1594
1595#[cfg(feature = "mint")]
1596mint_conversions!(Matrix2 { x, y }, ColumnMatrix2);
1597#[cfg(feature = "mint")]
1598mint_conversions!(Matrix3 { x, y, z }, ColumnMatrix3);
1599#[cfg(feature = "mint")]
1600mint_conversions!(Matrix4 { x, y, z, w }, ColumnMatrix4);
1601
1602impl<S: BaseFloat> From<Matrix2<S>> for Matrix3<S> {
1603 fn from(m: Matrix2<S>) -> Matrix3<S> {
1606 #[cfg_attr(rustfmt, rustfmt_skip)]
1607 Matrix3::new(
1608 m[0][0], m[0][1], S::zero(),
1609 m[1][0], m[1][1], S::zero(),
1610 S::zero(), S::zero(), S::one(),
1611 )
1612 }
1613}
1614
1615impl<S: BaseFloat> From<Matrix2<S>> for Matrix4<S> {
1616 fn from(m: Matrix2<S>) -> Matrix4<S> {
1619 #[cfg_attr(rustfmt, rustfmt_skip)]
1620 Matrix4::new(
1621 m[0][0], m[0][1], S::zero(), S::zero(),
1622 m[1][0], m[1][1], S::zero(), S::zero(),
1623 S::zero(), S::zero(), S::one(), S::zero(),
1624 S::zero(), S::zero(), S::zero(), S::one(),
1625 )
1626 }
1627}
1628
1629impl<S: BaseFloat> From<Matrix3<S>> for Matrix4<S> {
1630 fn from(m: Matrix3<S>) -> Matrix4<S> {
1633 #[cfg_attr(rustfmt, rustfmt_skip)]
1634 Matrix4::new(
1635 m[0][0], m[0][1], m[0][2], S::zero(),
1636 m[1][0], m[1][1], m[1][2], S::zero(),
1637 m[2][0], m[2][1], m[2][2], S::zero(),
1638 S::zero(), S::zero(), S::zero(), S::one(),
1639 )
1640 }
1641}
1642
1643impl<S: BaseFloat> From<Matrix3<S>> for Quaternion<S> {
1644 fn from(mat: Matrix3<S>) -> Quaternion<S> {
1646 let trace = mat.trace();
1648 let half: S = cast(0.5f64).unwrap();
1649
1650 if trace >= S::zero() {
1651 let s = (S::one() + trace).sqrt();
1652 let w = half * s;
1653 let s = half / s;
1654 let x = (mat[1][2] - mat[2][1]) * s;
1655 let y = (mat[2][0] - mat[0][2]) * s;
1656 let z = (mat[0][1] - mat[1][0]) * s;
1657 Quaternion::new(w, x, y, z)
1658 } else if (mat[0][0] > mat[1][1]) && (mat[0][0] > mat[2][2]) {
1659 let s = ((mat[0][0] - mat[1][1] - mat[2][2]) + S::one()).sqrt();
1660 let x = half * s;
1661 let s = half / s;
1662 let y = (mat[1][0] + mat[0][1]) * s;
1663 let z = (mat[0][2] + mat[2][0]) * s;
1664 let w = (mat[1][2] - mat[2][1]) * s;
1665 Quaternion::new(w, x, y, z)
1666 } else if mat[1][1] > mat[2][2] {
1667 let s = ((mat[1][1] - mat[0][0] - mat[2][2]) + S::one()).sqrt();
1668 let y = half * s;
1669 let s = half / s;
1670 let z = (mat[2][1] + mat[1][2]) * s;
1671 let x = (mat[1][0] + mat[0][1]) * s;
1672 let w = (mat[2][0] - mat[0][2]) * s;
1673 Quaternion::new(w, x, y, z)
1674 } else {
1675 let s = ((mat[2][2] - mat[0][0] - mat[1][1]) + S::one()).sqrt();
1676 let z = half * s;
1677 let s = half / s;
1678 let x = (mat[0][2] + mat[2][0]) * s;
1679 let y = (mat[2][1] + mat[1][2]) * s;
1680 let w = (mat[0][1] - mat[1][0]) * s;
1681 Quaternion::new(w, x, y, z)
1682 }
1683 }
1684}
1685
1686impl<S: fmt::Debug> fmt::Debug for Matrix2<S> {
1687 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1688 write!(f, "Matrix2 ")?;
1689 <[[S; 2]; 2] as fmt::Debug>::fmt(self.as_ref(), f)
1690 }
1691}
1692
1693impl<S: fmt::Debug> fmt::Debug for Matrix3<S> {
1694 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1695 write!(f, "Matrix3 ")?;
1696 <[[S; 3]; 3] as fmt::Debug>::fmt(self.as_ref(), f)
1697 }
1698}
1699
1700impl<S: fmt::Debug> fmt::Debug for Matrix4<S> {
1701 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1702 write!(f, "Matrix4 ")?;
1703 <[[S; 4]; 4] as fmt::Debug>::fmt(self.as_ref(), f)
1704 }
1705}
1706
1707#[cfg(feature = "rand")]
1708impl<S> Distribution<Matrix2<S>> for Standard
1709where
1710 Standard: Distribution<Vector2<S>>,
1711 S: BaseFloat,
1712{
1713 #[inline]
1714 fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Matrix2<S> {
1715 Matrix2 {
1716 x: self.sample(rng),
1717 y: self.sample(rng),
1718 }
1719 }
1720}
1721
1722#[cfg(feature = "rand")]
1723impl<S> Distribution<Matrix3<S>> for Standard
1724where
1725 Standard: Distribution<Vector3<S>>,
1726 S: BaseFloat,
1727{
1728 #[inline]
1729 fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Matrix3<S> {
1730 Matrix3 {
1731 x: rng.gen(),
1732 y: rng.gen(),
1733 z: rng.gen(),
1734 }
1735 }
1736}
1737
1738#[cfg(feature = "rand")]
1739impl<S> Distribution<Matrix4<S>> for Standard
1740where
1741 Standard: Distribution<Vector4<S>>,
1742 S: BaseFloat,
1743{
1744 #[inline]
1745 fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Matrix4<S> {
1746 Matrix4 {
1747 x: rng.gen(),
1748 y: rng.gen(),
1749 z: rng.gen(),
1750 w: rng.gen(),
1751 }
1752 }
1753}
1754
1755#[inline]
1763fn det_sub_proc<S: BaseFloat>(m: &Matrix4<S>, x: usize, y: usize, z: usize) -> Vector4<S> {
1764 let s: &[S; 16] = m.as_ref();
1765 let a = Vector4::new(s[4 + x], s[12 + x], s[x], s[8 + x]);
1766 let b = Vector4::new(s[8 + y], s[8 + y], s[4 + y], s[4 + y]);
1767 let c = Vector4::new(s[12 + z], s[z], s[12 + z], s[z]);
1768
1769 let d = Vector4::new(s[8 + x], s[8 + x], s[4 + x], s[4 + x]);
1770 let e = Vector4::new(s[12 + y], s[y], s[12 + y], s[y]);
1771 let f = Vector4::new(s[4 + z], s[12 + z], s[z], s[8 + z]);
1772
1773 let g = Vector4::new(s[12 + x], s[x], s[12 + x], s[x]);
1774 let h = Vector4::new(s[4 + y], s[12 + y], s[y], s[8 + y]);
1775 let i = Vector4::new(s[8 + z], s[8 + z], s[4 + z], s[4 + z]);
1776 let mut tmp = a.mul_element_wise(b.mul_element_wise(c));
1777 tmp += d.mul_element_wise(e.mul_element_wise(f));
1778 tmp += g.mul_element_wise(h.mul_element_wise(i));
1779 tmp -= a.mul_element_wise(e.mul_element_wise(i));
1780 tmp -= d.mul_element_wise(h.mul_element_wise(c));
1781 tmp -= g.mul_element_wise(b.mul_element_wise(f));
1782 tmp
1783}