use glam::Mat4;
#[derive(Debug, Clone)]
pub struct Skin {
joints: Vec<u32>,
inverse_bind_matrices: Vec<Mat4>,
}
impl Skin {
pub fn new(joints: Vec<u32>, inverse_bind_matrices: Vec<Mat4>) -> Self {
Self {
joints,
inverse_bind_matrices,
}
}
pub fn joints(&self) -> &[u32] {
&self.joints
}
pub fn inverse_bind_matrices(&self) -> &[Mat4] {
&self.inverse_bind_matrices
}
}
pub(crate) fn load_skins(
doc: &gltf::Document,
buffers: &[gltf::buffer::Data],
) -> Result<Vec<Skin>, crate::LoadError> {
doc.skins()
.map(|skin| {
let joints: Vec<u32> = skin.joints().map(|n| n.index() as u32).collect();
let reader = skin.reader(|buffer| Some(buffers[buffer.index()].0.as_slice()));
let mut inverse_bind_matrices = match reader.read_inverse_bind_matrices() {
Some(matrices) => matrices.map(|m| Mat4::from_cols_array_2d(&m)).collect(),
None => vec![Mat4::IDENTITY; joints.len()],
};
if inverse_bind_matrices.len() < joints.len() {
return Err(crate::LoadError::InvalidVrm(format!(
"skin {} has {} joints but only {} inverse bind matrices",
skin.index(),
joints.len(),
inverse_bind_matrices.len()
)));
}
if inverse_bind_matrices
.iter()
.flat_map(|matrix| matrix.to_cols_array())
.any(|value| !value.is_finite())
{
return Err(crate::LoadError::InvalidVrm(format!(
"skin {} contains a non-finite inverse bind matrix",
skin.index()
)));
}
inverse_bind_matrices.truncate(joints.len());
Ok(Skin::new(joints, inverse_bind_matrices))
})
.collect()
}