mod common;
use glam::{Quat, Vec3};
use serde_json::{Value, json};
use vrm_runtime::{
AvatarAssetBuilder, AvatarMeta, AvatarRuntime, HumanBone, LoadOptions, PlaybackMode,
PlaybackOptions, ValidationMode,
};
use vrm_runtime::{Interpolation, Keyframe, Track, VrmAnimation};
#[test]
fn typed_tracks_sample_step_linear_and_cubic_spline() {
let step = Track::new(
Interpolation::Step,
vec![Keyframe::new(0.0, 0.0), Keyframe::new(1.0, 1.0)],
);
assert_eq!(step.sample(0.75), Some(0.0));
let linear = Track::new(
Interpolation::Linear,
vec![
Keyframe::new(0.0, Vec3::ZERO),
Keyframe::new(1.0, Vec3::new(2.0, 0.0, 0.0)),
],
);
assert_eq!(linear.sample(0.25), Some(Vec3::new(0.5, 0.0, 0.0)));
let cubic = Track::new(
Interpolation::CubicSpline,
vec![
Keyframe::cubic(0.0, 0.0, 0.0, 0.0),
Keyframe::cubic(1.0, 1.0, 0.0, 0.0),
],
);
assert!((cubic.sample(0.5).unwrap() - 0.5).abs() < 1.0e-6);
assert_eq!(cubic.sample(f32::NAN), None);
}
#[test]
fn loads_first_vrma_animation_and_maps_vrm_channels() {
let fixture = VrmaFixture::complete();
let animation = VrmAnimation::from_bytes(&fixture.build()).unwrap();
assert_eq!(animation.duration(), 1.0);
assert_eq!(animation.bone_tracks().count(), 2);
assert!(animation.bone_track(HumanBone::Spine).is_none());
assert_eq!(
animation
.bone_track(HumanBone::Head)
.unwrap()
.rotation()
.unwrap()
.interpolation(),
Interpolation::CubicSpline
);
assert_eq!(
animation
.bone_track(HumanBone::Hips)
.unwrap()
.translation()
.unwrap()
.interpolation(),
Interpolation::Linear
);
assert_eq!(
animation.expression_track("happy").unwrap().interpolation(),
Interpolation::Linear
);
assert_eq!(
animation.look_at_rotation_track().unwrap().interpolation(),
Interpolation::Step
);
assert_eq!(
animation.look_at_offset_from_head_bone(),
Some(Vec3::new(0.0, 0.06, 0.06))
);
assert_eq!(animation.sample_expression_weight("happy", 1.0), 1.0);
assert_eq!(
animation.sample_bone_translation_delta(HumanBone::Hips, 1.0),
Some(Vec3::new(0.0, 1.0, 0.0))
);
let look_at = animation.sample_look_at_rotation(0.75).unwrap();
assert!(look_at.abs_diff_eq(Quat::IDENTITY, 1.0e-5));
}
#[test]
fn rejects_non_1_0_vrma_versions() {
let mut fixture = VrmaFixture::complete();
fixture.extension["specVersion"] = json!("1.0-beta");
let error = VrmAnimation::from_bytes(&fixture.build()).unwrap_err();
assert!(error.to_string().contains("specVersion"));
}
#[test]
fn rejects_required_extensions_not_declared_as_used() {
let mut fixture = VrmaFixture::complete();
fixture.root["extensionsUsed"] = json!([]);
let error = VrmAnimation::from_bytes(&fixture.build()).unwrap_err();
assert!(error.to_string().contains("extensionsRequired"));
assert!(error.to_string().contains("extensionsUsed"));
}
#[test]
fn rejects_an_extension_object_missing_from_extensions_used() {
let mut fixture = VrmaFixture::complete();
fixture.root["nodes"][0]["extensions"] = json!({
"VENDOR_undeclared_animation_data": {}
});
let error = VrmAnimation::from_bytes(&fixture.build()).unwrap_err();
assert!(
error
.to_string()
.contains("VENDOR_undeclared_animation_data")
);
assert!(error.to_string().contains("extensionsUsed"));
}
#[test]
fn rejects_an_undeclared_extension_in_a_vrma_expression_property() {
let mut fixture = VrmaFixture::complete();
fixture.extension["expressions"]["preset"]["happy"]["extensions"] =
json!({ "VENDOR_nested_animation_data": {} });
let error = VrmAnimation::from_bytes(&fixture.build()).unwrap_err();
assert!(error.to_string().contains("VENDOR_nested_animation_data"));
assert!(error.to_string().contains("extensionsUsed"));
}
#[test]
fn rejects_duplicate_extensions_used_entries() {
let mut fixture = VrmaFixture::complete();
fixture.root["extensionsUsed"] = json!(["VRMC_vrm_animation", "VRMC_vrm_animation"]);
let error = VrmAnimation::from_bytes(&fixture.build()).unwrap_err();
assert!(error.to_string().contains("duplicate"));
assert!(error.to_string().contains("extensionsUsed"));
}
#[test]
fn rejects_duplicate_extensions_required_entries() {
let mut fixture = VrmaFixture::complete();
fixture.root["extensionsRequired"] = json!(["VRMC_vrm_animation", "VRMC_vrm_animation"]);
let error = VrmAnimation::from_bytes(&fixture.build()).unwrap_err();
assert!(error.to_string().contains("duplicate"));
assert!(error.to_string().contains("extensionsRequired"));
}
#[test]
fn permissive_mode_reports_an_unknown_optional_extension() {
let mut fixture = VrmaFixture::complete();
fixture.root["extensionsUsed"] =
json!(["VRMC_vrm_animation", "VENDOR_optional_animation_data"]);
fixture.root["nodes"][0]["extensions"] = json!({
"VENDOR_optional_animation_data": {
"payload": {
"extensions": { "NOT_a_gltf_extension": {} }
}
}
});
fixture.extension["extras"] = json!({
"extensions": { "NOT_a_gltf_extension": {} }
});
let bytes = fixture.build();
VrmAnimation::from_bytes(&bytes).expect("strict mode may use optional-extension fallback data");
let outcome = VrmAnimation::from_bytes_with_options(
&bytes,
LoadOptions {
validation: ValidationMode::Permissive,
},
)
.unwrap();
assert!(outcome.diagnostics.iter().any(|diagnostic| {
diagnostic.code == "VRMA_UNSUPPORTED_OPTIONAL_EXTENSION"
&& diagnostic.path == "/extensionsUsed"
}));
}
#[test]
fn rejects_an_animation_output_accessor_before_the_reader_can_panic() {
let mut fixture = VrmaFixture::complete();
let output_accessor = fixture.root["animations"][0]["samplers"][0]["output"]
.as_u64()
.unwrap() as usize;
fixture.root["accessors"][output_accessor]["componentType"] = json!(5125);
let error = VrmAnimation::from_bytes(&fixture.build()).unwrap_err();
assert!(error.to_string().contains("output accessor"));
assert!(error.to_string().contains("rotation"));
}
#[test]
fn loads_only_the_first_gltf_animation_and_reports_the_rest() {
let mut fixture = VrmaFixture::complete();
let duplicate = fixture.root["animations"][0].clone();
fixture.root["animations"]
.as_array_mut()
.unwrap()
.push(duplicate);
let outcome =
VrmAnimation::from_bytes_with_options(&fixture.build(), LoadOptions::default()).unwrap();
assert_eq!(outcome.animation.duration(), 1.0);
assert!(
outcome
.diagnostics
.iter()
.any(|diagnostic| { diagnostic.code == "VRMA_ADDITIONAL_ANIMATIONS_IGNORED" })
);
}
#[test]
fn strict_rejects_and_permissive_ignores_forbidden_bone_translation() {
let mut fixture = VrmaFixture::complete();
fixture.add_vec3_channel(
1,
"translation",
"LINEAR",
[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]],
);
let bytes = fixture.build();
let error = VrmAnimation::from_bytes(&bytes).unwrap_err();
assert!(error.to_string().contains("translation"));
let outcome = VrmAnimation::from_bytes_with_options(
&bytes,
LoadOptions {
validation: ValidationMode::Permissive,
},
)
.unwrap();
assert!(!outcome.diagnostics.is_empty());
assert!(outcome.animation.bone_track(HumanBone::Spine).is_none());
}
#[test]
fn runtime_retargets_rotation_and_scales_hips_translation() {
let animation = VrmAnimation::from_bytes(&VrmaFixture::complete().build()).unwrap();
let mut nodes = common::minimal_nodes();
nodes[0].initial_translation = Vec3::new(0.0, 2.0, 0.0);
nodes[2].initial_rotation = Quat::from_rotation_z(std::f32::consts::FRAC_PI_2);
let asset = AvatarAssetBuilder::new()
.with_meta(AvatarMeta::new(
"Retarget Avatar",
["vrm-runtime"],
"https://vrm.dev/licenses/1.0/",
))
.with_humanoid(common::minimal_humanoid())
.with_nodes(nodes)
.build()
.unwrap();
let rest_world = asset.compute_world_matrices(&[]);
let target_head_world_rotation = rest_world[2].to_scale_rotation_translation().1;
let expected_head = animation
.sample_retargeted_source_bone_rotation(HumanBone::Head, 1.0, target_head_world_rotation)
.unwrap();
let mut runtime = AvatarRuntime::new(asset);
runtime
.play(
animation,
PlaybackOptions {
speed: 1.0,
mode: PlaybackMode::Once,
..PlaybackOptions::default()
},
)
.unwrap();
let frame = runtime.update(1.0).unwrap();
let hips = frame
.bone_updates()
.iter()
.find(|update| update.node_index() == 0)
.unwrap();
let head = frame
.bone_updates()
.iter()
.find(|update| update.node_index() == 2)
.unwrap();
assert_eq!(hips.translation(), Some(Vec3::new(0.0, 2.0, 0.0)));
assert!(head.rotation().abs_diff_eq(expected_head, 1.0e-5));
}
#[test]
fn runtime_composes_a_missing_optional_bone_into_next_mapped_descendants() {
let animation =
VrmAnimation::from_bytes(&VrmaFixture::complete().with_animated_upper_chest().build())
.unwrap();
let upper_chest = animation
.sample_normalized_source_bone_rotation(HumanBone::UpperChest, 1.0)
.unwrap();
let source_head = animation
.sample_normalized_source_bone_rotation(HumanBone::Head, 1.0)
.unwrap();
let mut runtime = AvatarRuntime::new(common::minimal_asset());
runtime
.play(
animation,
PlaybackOptions {
speed: 1.0,
mode: PlaybackMode::Once,
..PlaybackOptions::default()
},
)
.unwrap();
let frame = runtime.update(1.0).unwrap();
let rotation = |node_index| {
frame
.bone_updates()
.iter()
.find(|update| update.node_index() == node_index)
.unwrap()
.rotation()
};
assert!(rotation(2).abs_diff_eq(upper_chest * source_head, 1.0e-5));
assert!(rotation(9).abs_diff_eq(upper_chest, 1.0e-5));
assert!(rotation(12).abs_diff_eq(upper_chest, 1.0e-5));
}
#[test]
fn playback_can_disable_hips_translation_scaling() {
let animation = VrmAnimation::from_bytes(&VrmaFixture::complete().build()).unwrap();
let mut nodes = common::minimal_nodes();
nodes[0].initial_translation = Vec3::new(0.0, 2.0, 0.0);
let asset = AvatarAssetBuilder::new()
.with_meta(AvatarMeta::new(
"Unscaled Retarget Avatar",
["vrm-runtime"],
"https://vrm.dev/licenses/1.0/",
))
.with_humanoid(common::minimal_humanoid())
.with_nodes(nodes)
.build()
.unwrap();
let mut runtime = AvatarRuntime::new(asset);
runtime
.play(
animation,
PlaybackOptions {
speed: 1.0,
mode: PlaybackMode::Once,
scale_hips_translation: false,
},
)
.unwrap();
let frame = runtime.update(1.0).unwrap();
let hips = frame
.bone_updates()
.iter()
.find(|update| update.node_index() == 0)
.unwrap();
assert_eq!(hips.translation(), Some(Vec3::new(0.0, 1.0, 0.0)));
}
#[test]
fn strict_rejects_and_permissive_reports_invalid_humanoid_hierarchy() {
let mut fixture = VrmaFixture::complete();
fixture.root["nodes"][0]["children"] = json!([]);
let bytes = fixture.build();
let error = VrmAnimation::from_bytes(&bytes).unwrap_err();
assert!(error.to_string().contains("descendant"));
let outcome = VrmAnimation::from_bytes_with_options(
&bytes,
LoadOptions {
validation: ValidationMode::Permissive,
},
)
.unwrap();
assert!(
outcome
.diagnostics
.iter()
.any(|diagnostic| { diagnostic.code == "VRMA_HUMANOID_HIERARCHY_INVALID" })
);
}
#[test]
fn validates_scale_on_every_node_in_the_vrma_t_pose() {
let mut fixture = VrmaFixture::complete();
let unmapped_node = fixture.root["nodes"].as_array().unwrap().len();
fixture.root["nodes"]
.as_array_mut()
.unwrap()
.push(json!({ "scale": [1.0, 2.0, 1.0] }));
let bytes = fixture.build();
let error = VrmAnimation::from_bytes(&bytes).unwrap_err();
assert!(error.to_string().contains("positive and uniform"));
let outcome = VrmAnimation::from_bytes_with_options(
&bytes,
LoadOptions {
validation: ValidationMode::Permissive,
},
)
.unwrap();
assert!(outcome.diagnostics.iter().any(|diagnostic| {
diagnostic.code == "VRMA_HUMANOID_SCALE_INVALID"
&& diagnostic.path == format!("/nodes/{unmapped_node}/scale")
}));
}
#[test]
fn strict_rejects_an_optional_bone_without_its_required_parent_bone() {
let mut fixture = VrmaFixture::complete();
let intermediate = fixture.root["nodes"].as_array().unwrap().len();
fixture.root["nodes"]
.as_array_mut()
.unwrap()
.push(json!({}));
fixture.root["nodes"][11]["children"] = json!([intermediate]);
fixture.extension["humanoid"]["humanBones"]["leftIndexIntermediate"] =
json!({ "node": intermediate });
let error = VrmAnimation::from_bytes(&fixture.build()).unwrap_err();
assert!(error.to_string().contains("leftIndexIntermediate"));
assert!(error.to_string().contains("leftIndexProximal"));
}
#[test]
fn rejects_an_optional_bone_object_without_a_node() {
let mut fixture = VrmaFixture::complete();
fixture.extension["humanoid"]["humanBones"]["chest"] = json!({});
let error = VrmAnimation::from_bytes(&fixture.build()).unwrap_err();
assert!(error.to_string().contains("Chest") || error.to_string().contains("chest"));
assert!(error.to_string().contains("node"));
}
#[test]
fn strict_rejects_an_optional_bone_outside_its_humanoid_parent_branch() {
let mut fixture = VrmaFixture::complete();
let toes = fixture.root["nodes"].as_array().unwrap().len();
fixture.root["nodes"]
.as_array_mut()
.unwrap()
.push(json!({}));
fixture.root["nodes"][0]["children"]
.as_array_mut()
.unwrap()
.push(json!(toes));
fixture.extension["humanoid"]["humanBones"]["leftToes"] = json!({ "node": toes });
let error = VrmAnimation::from_bytes(&fixture.build()).unwrap_err();
assert!(error.to_string().contains("leftToes"));
assert!(error.to_string().contains("leftFoot"));
}
struct VrmaFixture {
root: Value,
extension: Value,
binary: Vec<u8>,
}
impl VrmaFixture {
fn complete() -> Self {
let bone_names = [
"hips",
"spine",
"head",
"leftUpperLeg",
"leftLowerLeg",
"leftFoot",
"rightUpperLeg",
"rightLowerLeg",
"rightFoot",
"leftUpperArm",
"leftLowerArm",
"leftHand",
"rightUpperArm",
"rightLowerArm",
"rightHand",
];
let human_bones = bone_names
.iter()
.enumerate()
.map(|(index, name)| ((*name).to_string(), json!({ "node": index })))
.collect::<serde_json::Map<_, _>>();
let expression_node = bone_names.len();
let look_at_node = expression_node + 1;
let mut nodes = (0..look_at_node + 1)
.map(|index| {
if index == 0 {
json!({ "translation": [0.0, 1.0, 0.0] })
} else {
json!({})
}
})
.collect::<Vec<_>>();
nodes[0]["children"] = json!([1, 3, 6]);
nodes[1]["children"] = json!([2, 9, 12]);
nodes[3]["children"] = json!([4]);
nodes[4]["children"] = json!([5]);
nodes[6]["children"] = json!([7]);
nodes[7]["children"] = json!([8]);
nodes[9]["children"] = json!([10]);
nodes[10]["children"] = json!([11]);
nodes[12]["children"] = json!([13]);
nodes[13]["children"] = json!([14]);
let extension = json!({
"specVersion": "1.0",
"humanoid": { "humanBones": human_bones },
"expressions": {
"preset": { "happy": { "node": expression_node } }
},
"lookAt": {
"node": look_at_node,
"offsetFromHeadBone": [0.0, 0.06, 0.06]
}
});
let root = json!({
"asset": { "version": "2.0" },
"extensionsUsed": ["VRMC_vrm_animation"],
"extensionsRequired": ["VRMC_vrm_animation"],
"nodes": nodes,
"animations": [{ "channels": [], "samplers": [] }],
"bufferViews": [],
"accessors": []
});
let mut fixture = Self {
root,
extension,
binary: Vec::new(),
};
fixture.add_quat_channel(
2,
"rotation",
"CUBICSPLINE",
[
[0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
[0.0, 0.0, 0.0, 0.0],
[0.0, 0.0, 0.0, 0.0],
[0.0, 0.70710677, 0.0, 0.70710677],
[0.0, 0.0, 0.0, 0.0],
],
);
fixture.add_vec3_channel(
0,
"translation",
"LINEAR",
[[0.0, 1.0, 0.0], [0.0, 2.0, 0.0]],
);
fixture.add_vec3_channel(
expression_node,
"translation",
"LINEAR",
[[0.0, 0.0, 0.0], [1.5, 0.0, 0.0]],
);
fixture.add_quat_channel(
look_at_node,
"rotation",
"STEP",
[[0.0, 0.0, 0.0, 1.0], [0.0, 0.70710677, 0.0, 0.70710677]],
);
fixture
}
fn with_animated_upper_chest(mut self) -> Self {
let chest_node = self.root["nodes"].as_array().unwrap().len();
let upper_chest_node = chest_node + 1;
self.root["nodes"]
.as_array_mut()
.unwrap()
.push(json!({ "children": [upper_chest_node] }));
self.root["nodes"]
.as_array_mut()
.unwrap()
.push(json!({ "children": [2, 9, 12] }));
self.root["nodes"][1]["children"] = json!([chest_node]);
self.extension["humanoid"]["humanBones"]["chest"] = json!({ "node": chest_node });
self.extension["humanoid"]["humanBones"]["upperChest"] =
json!({ "node": upper_chest_node });
self.add_quat_channel(
upper_chest_node,
"rotation",
"LINEAR",
[[0.0, 0.0, 0.0, 1.0], [0.70710677, 0.0, 0.0, 0.70710677]],
);
self
}
fn add_vec3_channel<const N: usize>(
&mut self,
node: usize,
path: &str,
interpolation: &str,
values: [[f32; 3]; N],
) {
let flattened = values.into_iter().flatten().collect::<Vec<_>>();
self.add_channel(node, path, interpolation, &flattened, "VEC3", N);
}
fn add_quat_channel<const N: usize>(
&mut self,
node: usize,
path: &str,
interpolation: &str,
values: [[f32; 4]; N],
) {
let flattened = values.into_iter().flatten().collect::<Vec<_>>();
self.add_channel(node, path, interpolation, &flattened, "VEC4", N);
}
fn add_channel(
&mut self,
node: usize,
path: &str,
interpolation: &str,
output: &[f32],
output_type: &str,
output_count: usize,
) {
let input_accessor = self.add_accessor(&[0.0, 1.0], "SCALAR", 2, true);
let output_accessor = self.add_accessor(output, output_type, output_count, false);
let sampler = self.root["animations"][0]["samplers"]
.as_array()
.unwrap()
.len();
self.root["animations"][0]["samplers"]
.as_array_mut()
.unwrap()
.push(json!({
"input": input_accessor,
"output": output_accessor,
"interpolation": interpolation
}));
self.root["animations"][0]["channels"]
.as_array_mut()
.unwrap()
.push(json!({
"sampler": sampler,
"target": { "node": node, "path": path }
}));
}
fn add_accessor(
&mut self,
values: &[f32],
accessor_type: &str,
count: usize,
is_input: bool,
) -> usize {
let offset = self.binary.len();
for value in values {
self.binary.extend_from_slice(&value.to_le_bytes());
}
let byte_length = self.binary.len() - offset;
let view = self.root["bufferViews"].as_array().unwrap().len();
self.root["bufferViews"]
.as_array_mut()
.unwrap()
.push(json!({
"buffer": 0,
"byteOffset": offset,
"byteLength": byte_length
}));
let accessor = self.root["accessors"].as_array().unwrap().len();
let mut value = json!({
"bufferView": view,
"componentType": 5126,
"count": count,
"type": accessor_type
});
if is_input {
value["min"] = json!([0.0]);
value["max"] = json!([1.0]);
}
self.root["accessors"].as_array_mut().unwrap().push(value);
accessor
}
fn build(mut self) -> Vec<u8> {
self.root["extensions"] = json!({ "VRMC_vrm_animation": self.extension });
self.root["buffers"] = json!([{ "byteLength": self.binary.len() }]);
make_glb(&self.root, &self.binary)
}
}
fn make_glb(root: &Value, binary: &[u8]) -> Vec<u8> {
let mut json_bytes = serde_json::to_vec(root).unwrap();
while !json_bytes.len().is_multiple_of(4) {
json_bytes.push(b' ');
}
let mut bin_bytes = binary.to_vec();
while !bin_bytes.len().is_multiple_of(4) {
bin_bytes.push(0);
}
let total_length = 12 + 8 + json_bytes.len() + 8 + bin_bytes.len();
let mut glb = Vec::with_capacity(total_length);
glb.extend_from_slice(&0x4654_6C67_u32.to_le_bytes());
glb.extend_from_slice(&2_u32.to_le_bytes());
glb.extend_from_slice(&(total_length as u32).to_le_bytes());
glb.extend_from_slice(&(json_bytes.len() as u32).to_le_bytes());
glb.extend_from_slice(&0x4E4F_534A_u32.to_le_bytes());
glb.extend_from_slice(&json_bytes);
glb.extend_from_slice(&(bin_bytes.len() as u32).to_le_bytes());
glb.extend_from_slice(&0x004E_4942_u32.to_le_bytes());
glb.extend_from_slice(&bin_bytes);
glb
}