microcad_lang/value/
matrix.rs

1// Copyright © 2025 The µcad authors <info@ucad.xyz>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4//! Matrix value type
5
6use microcad_core::Scalar;
7
8use crate::ty::*;
9
10/// Matrix type
11#[derive(Debug, Clone, PartialEq)]
12pub enum Matrix {
13    /// 2x2 matrix.
14    Matrix2(microcad_core::Mat2),
15    /// 3x3 matrix.
16    Matrix3(microcad_core::Mat3),
17    /// 4x4 matrix.
18    Matrix4(microcad_core::Mat4),
19}
20
21impl Ty for Matrix {
22    fn ty(&self) -> Type {
23        match self {
24            Matrix::Matrix2(_) => Type::Matrix(MatrixType::new(2, 2)),
25            Matrix::Matrix3(_) => Type::Matrix(MatrixType::new(3, 3)),
26            Matrix::Matrix4(_) => Type::Matrix(MatrixType::new(4, 4)),
27        }
28    }
29}
30
31impl std::fmt::Display for Matrix {
32    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33        match self {
34            Matrix::Matrix2(matrix2) => write!(f, "{matrix2:?}"),
35            Matrix::Matrix3(matrix3) => write!(f, "{matrix3:?}"),
36            Matrix::Matrix4(matrix4) => write!(f, "{matrix4:?}"),
37        }
38    }
39}
40
41impl std::hash::Hash for Matrix {
42    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
43        match self {
44            Matrix::Matrix2(matrix2) => {
45                let slice: &[Scalar; 4] = matrix2.as_ref();
46                bytemuck::bytes_of(slice).hash(state);
47            }
48            Matrix::Matrix3(matrix3) => {
49                let slice: &[Scalar; 9] = matrix3.as_ref();
50                bytemuck::bytes_of(slice).hash(state);
51            }
52            Matrix::Matrix4(matrix4) => {
53                let slice: &[Scalar; 16] = matrix4.as_ref();
54                bytemuck::bytes_of(slice).hash(state);
55            }
56        }
57    }
58}