Skip to main content

vrm_runtime/
skin.rs

1use glam::Mat4;
2
3/// A glTF skin: the joint nodes and their inverse bind matrices used to
4/// compute the joint matrices for GPU skinning.
5#[derive(Debug, Clone)]
6pub struct Skin {
7    joints: Vec<u32>,
8    inverse_bind_matrices: Vec<Mat4>,
9}
10
11impl Skin {
12    /// Creates a skin from joint node indices and matching inverse bind matrices.
13    ///
14    /// Cross-object validation occurs when the containing asset is built.
15    pub fn new(joints: Vec<u32>, inverse_bind_matrices: Vec<Mat4>) -> Self {
16        Self {
17            joints,
18            inverse_bind_matrices,
19        }
20    }
21
22    /// Returns the avatar node index for each joint palette entry.
23    pub fn joints(&self) -> &[u32] {
24        &self.joints
25    }
26
27    /// Returns the inverse bind matrix corresponding to each joint.
28    pub fn inverse_bind_matrices(&self) -> &[Mat4] {
29        &self.inverse_bind_matrices
30    }
31}
32
33pub(crate) fn load_skins(
34    doc: &gltf::Document,
35    buffers: &[gltf::buffer::Data],
36) -> Result<Vec<Skin>, crate::LoadError> {
37    doc.skins()
38        .map(|skin| {
39            let joints: Vec<u32> = skin.joints().map(|n| n.index() as u32).collect();
40
41            let reader = skin.reader(|buffer| Some(buffers[buffer.index()].0.as_slice()));
42            let mut inverse_bind_matrices = match reader.read_inverse_bind_matrices() {
43                Some(matrices) => matrices.map(|m| Mat4::from_cols_array_2d(&m)).collect(),
44                None => vec![Mat4::IDENTITY; joints.len()],
45            };
46            if inverse_bind_matrices.len() < joints.len() {
47                return Err(crate::LoadError::InvalidVrm(format!(
48                    "skin {} has {} joints but only {} inverse bind matrices",
49                    skin.index(),
50                    joints.len(),
51                    inverse_bind_matrices.len()
52                )));
53            }
54            if inverse_bind_matrices
55                .iter()
56                .flat_map(|matrix| matrix.to_cols_array())
57                .any(|value| !value.is_finite())
58            {
59                return Err(crate::LoadError::InvalidVrm(format!(
60                    "skin {} contains a non-finite inverse bind matrix",
61                    skin.index()
62                )));
63            }
64            // glTF permits extra accessor elements; renderer-facing data keeps
65            // exactly the matrices that correspond to declared joints.
66            inverse_bind_matrices.truncate(joints.len());
67
68            Ok(Skin::new(joints, inverse_bind_matrices))
69        })
70        .collect()
71}