identity matrix

This commit is contained in:
Jon Janzen
2021-03-29 19:18:21 -06:00
parent 5ca76b424a
commit f106344504

View File

@@ -46,6 +46,15 @@ impl Matrix {
pub fn new_empty_4() -> Matrix {
Matrix::new_empty(4, 4)
}
pub fn identity() -> Matrix {
Matrix::new(vec![
vec![1.0, 0.0, 0.0, 0.0],
vec![0.0, 1.0, 0.0, 0.0],
vec![0.0, 0.0, 1.0, 0.0],
vec![0.0, 0.0, 0.0, 1.0],
])
}
}
impl Index<usize> for Matrix {
@@ -277,4 +286,31 @@ mod tests {
assert_eq!(matrix * tuple, expected);
}
#[test]
fn matrix_by_identity() {
let matrix = Matrix::from_array([
[0.0, 1.0, 2.0, 4.0,],
[1.0, 2.0, 4.0, 8.0,],
[2.0, 4.0, 8.0, 16.0],
[4.0, 8.0, 16.0, 32.0,]
]);
let expected = Matrix::from_array([
[0.0, 1.0, 2.0, 4.0,],
[1.0, 2.0, 4.0, 8.0,],
[2.0, 4.0, 8.0, 16.0],
[4.0, 8.0, 16.0, 32.0,]
]);
assert_eq!(matrix * Matrix::identity(), expected);
}
#[test]
fn tuple_by_identity() {
let t = Tuple::new(1.0, 2.0, 3.0, 4.0);
let expected = Tuple::new(1.0, 2.0, 3.0, 4.0);
assert_eq!(Matrix::identity() * t, expected);
}
}