vrm-runtime 0.1.0

Renderer-agnostic VRM 1.0 loader, validator, animation system, and runtime
Documentation
use glam::{Mat4, Quat, Vec3};

/// A node transform stored as a 4x4 matrix (column-major order).
///
/// Wraps a `glam::Mat4` in a plain `[[f32; 4]; 4]` so it can cross FFI
/// boundaries; every operation goes through `glam` under the hood.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Transform {
    matrix: [[f32; 4]; 4],
}

impl Transform {
    /// Identity transform with no translation, rotation, or scale.
    pub const IDENTITY: Self = Self {
        matrix: [
            [1.0, 0.0, 0.0, 0.0],
            [0.0, 1.0, 0.0, 0.0],
            [0.0, 0.0, 1.0, 0.0],
            [0.0, 0.0, 0.0, 1.0],
        ],
    };

    /// Creates a transform from a column-major matrix array.
    pub fn from_matrix(matrix: [[f32; 4]; 4]) -> Self {
        Self { matrix }
    }

    /// Creates a transform from a `glam` matrix.
    pub fn from_mat4(mat: Mat4) -> Self {
        Self {
            matrix: mat.to_cols_array_2d(),
        }
    }

    /// Creates a transform containing only a translation.
    pub fn from_translation(translation: Vec3) -> Self {
        Self::from_mat4(Mat4::from_translation(translation))
    }

    /// Creates a transform from scale, rotation, and translation components.
    pub fn from_scale_rotation_translation(scale: Vec3, rotation: Quat, translation: Vec3) -> Self {
        Self::from_mat4(Mat4::from_scale_rotation_translation(
            scale,
            rotation,
            translation,
        ))
    }

    /// Returns the underlying column-major matrix array.
    pub fn matrix(&self) -> &[[f32; 4]; 4] {
        &self.matrix
    }

    /// Converts this value into a `glam` matrix.
    pub fn to_mat4(&self) -> Mat4 {
        Mat4::from_cols_array_2d(&self.matrix)
    }

    /// Extracts the translation component.
    pub fn translation(&self) -> Vec3 {
        let (_scale, _rotation, translation) = self.to_scale_rotation_translation();
        translation
    }

    /// Decomposes this transform into scale, rotation, and translation.
    pub fn to_scale_rotation_translation(&self) -> (Vec3, Quat, Vec3) {
        self.to_mat4().to_scale_rotation_translation()
    }

    /// Composes this transform with `rhs` using matrix multiplication.
    pub fn multiply(self, rhs: Self) -> Self {
        Self::from_mat4(self.to_mat4() * rhs.to_mat4())
    }
}

impl From<Mat4> for Transform {
    fn from(mat: Mat4) -> Self {
        Self::from_mat4(mat)
    }
}

impl From<Transform> for Mat4 {
    fn from(t: Transform) -> Self {
        t.to_mat4()
    }
}