Skip to main content

vrm_runtime/
spring_bone.rs

1use crate::Avatar;
2use crate::instance::BoneUpdate;
3use crate::node::AvatarNode;
4use glam::{Mat3, Mat4, Quat, Vec3};
5use serde::Deserialize;
6use vrm_spec::vrmc_spring_bone_1_0 as spec;
7
8pub(crate) const VRMC_SPRING_BONE_EXTENDED_COLLIDER: &str = "VRMC_springBone_extended_collider";
9
10const PLANE_NORMAL_TOLERANCE: f32 = 1.0e-4;
11
12/// The geometric shape of a spring collider.
13#[derive(Debug, Clone)]
14pub enum ColliderShape {
15    /// A spherical boundary centered at a node-local offset.
16    Sphere {
17        /// Center of the sphere in the collider node's local space.
18        offset: Vec3,
19        /// Radius of the sphere in meters.
20        radius: f32,
21        /// When `false`, joints stay outside the sphere. When `true`, joints
22        /// are confined inside it.
23        inside: bool,
24    },
25    /// A capsule boundary between two node-local points.
26    Capsule {
27        /// Head of the capsule in the collider node's local space.
28        offset: Vec3,
29        /// Radius of the capsule in meters.
30        radius: f32,
31        /// Tail of the capsule in the collider node's local space.
32        tail: Vec3,
33        /// When `false`, joints stay outside the capsule. When `true`, joints
34        /// are confined inside it.
35        inside: bool,
36    },
37    /// A one-sided infinite plane boundary.
38    Plane {
39        /// A point on the plane in the collider node's local space.
40        offset: Vec3,
41        /// Unit normal pointing toward the allowed positive half-space. The
42        /// complete joint sphere is kept on this side of the plane.
43        normal: Vec3,
44    },
45}
46
47/// A collider attached to a node; its position is derived from the node's
48/// world matrix plus `shape`'s offset.
49#[derive(Debug, Clone)]
50pub struct SpringCollider {
51    /// Raw glTF index of the node that positions this collider.
52    pub node_index: u32,
53    /// Collider geometry expressed in the node's local space.
54    pub shape: ColliderShape,
55}
56
57/// A named group of colliders that spring chains can reference.
58#[derive(Debug, Clone)]
59pub struct SpringColliderGroup {
60    /// Optional author-facing group name.
61    pub name: Option<String>,
62    /// Colliders referenced by springs through this group.
63    pub colliders: Vec<SpringCollider>,
64}
65
66/// Physics parameters attached to one node in a spring chain.
67///
68/// Each node except the final tail marker is simulated against the next node
69/// in the chain.
70#[derive(Debug, Clone)]
71pub struct SpringJoint {
72    /// Raw glTF index of the simulated joint node.
73    pub node_index: u32,
74    /// Radius of the collision sphere around the joint, in meters.
75    pub hit_radius: f32,
76    /// Rest-direction restoring force.
77    pub stiffness: f32,
78    /// Magnitude of acceleration along [`Self::gravity_dir`].
79    pub gravity_power: f32,
80    /// Normalized gravity direction applied in world space.
81    pub gravity_dir: Vec3,
82    /// Fraction of previous-frame motion removed by drag.
83    pub drag_force: f32,
84}
85
86/// A single spring: a kinematic chain of joints plus the colliders it reacts
87/// to and an optional center node whose space inertia is evaluated in.
88#[derive(Debug, Clone)]
89pub struct SpringChain {
90    /// Optional author-facing spring name.
91    pub name: Option<String>,
92    /// Optional node whose moving space defines inertia cancellation.
93    pub center_node: Option<u32>,
94    /// Indices into [`SpringBone::collider_groups`].
95    pub collider_groups: Vec<usize>,
96    /// Consecutive joints from the root toward the chain tip.
97    pub joints: Vec<SpringJoint>,
98}
99
100/// The parsed spring-bone setup of the avatar: collider groups and chains.
101#[derive(Debug, Clone, Default)]
102pub struct SpringBone {
103    /// Collider groups available to spring chains.
104    pub collider_groups: Vec<SpringColliderGroup>,
105    /// Independently simulated spring chains.
106    pub springs: Vec<SpringChain>,
107}
108
109#[derive(Debug, Deserialize)]
110#[serde(rename_all = "camelCase")]
111struct ExtendedColliderSchema {
112    spec_version: String,
113    #[serde(default)]
114    shape: Option<ExtendedColliderShape>,
115}
116
117#[derive(Debug, Deserialize)]
118struct ExtendedColliderShape {
119    #[serde(default)]
120    sphere: Option<ExtendedColliderSphere>,
121    #[serde(default)]
122    capsule: Option<ExtendedColliderCapsule>,
123    #[serde(default)]
124    plane: Option<ExtendedColliderPlane>,
125}
126
127#[derive(Debug, Deserialize)]
128struct ExtendedColliderSphere {
129    #[serde(default)]
130    offset: Option<[f64; 3]>,
131    #[serde(default)]
132    radius: Option<f64>,
133    #[serde(default)]
134    inside: bool,
135}
136
137#[derive(Debug, Deserialize)]
138struct ExtendedColliderCapsule {
139    #[serde(default)]
140    offset: Option<[f64; 3]>,
141    #[serde(default)]
142    radius: Option<f64>,
143    #[serde(default)]
144    tail: Option<[f64; 3]>,
145    #[serde(default)]
146    inside: bool,
147}
148
149#[derive(Debug, Deserialize)]
150struct ExtendedColliderPlane {
151    #[serde(default)]
152    offset: Option<[f64; 3]>,
153    #[serde(default)]
154    normal: Option<[f64; 3]>,
155}
156
157fn deserialize_extended_collider(
158    collider: &spec::Collider,
159) -> Result<Option<ExtendedColliderSchema>, String> {
160    let Some(properties) = collider
161        .extensions
162        .as_ref()
163        .and_then(|extensions| extensions.get(VRMC_SPRING_BONE_EXTENDED_COLLIDER))
164    else {
165        return Ok(None);
166    };
167
168    let object = properties
169        .iter()
170        .map(|(name, value)| {
171            (
172                name.clone(),
173                value.clone().unwrap_or(serde_json::Value::Null),
174            )
175        })
176        .collect::<serde_json::Map<_, _>>();
177    serde_json::from_value(serde_json::Value::Object(object))
178        .map(Some)
179        .map_err(|error| format!("is malformed: {error}"))
180}
181
182fn finite_vec3(value: [f64; 3], field: &str) -> Result<Vec3, String> {
183    let result = Vec3::new(value[0] as f32, value[1] as f32, value[2] as f32);
184    if finite_vec3_after_narrowing(value) {
185        Ok(result)
186    } else {
187        Err(format!("{field} must contain finite values"))
188    }
189}
190
191fn finite_radius(value: Option<f64>) -> Result<f32, String> {
192    let value = value.unwrap_or(0.0);
193    let radius = value as f32;
194    if value >= 0.0 && finite_f32(value).is_some_and(|value| value >= 0.0) {
195        Ok(radius)
196    } else {
197        Err("radius must be a finite non-negative number".to_string())
198    }
199}
200
201fn finite_f32(value: f64) -> Option<f32> {
202    let narrowed = value as f32;
203    (value.is_finite() && narrowed.is_finite()).then_some(narrowed)
204}
205
206fn finite_vec3_after_narrowing(value: [f64; 3]) -> bool {
207    value
208        .into_iter()
209        .all(|component| finite_f32(component).is_some())
210}
211
212#[derive(Debug)]
213struct SpringTopologyChain {
214    center: Option<usize>,
215    joints: Vec<usize>,
216}
217
218/// Validates the semantic node ownership shared by loaded and constructed
219/// SpringBone data.
220///
221/// Every node on a path between two explicit joints is an implicit joint for
222/// duplicate and center checks, even though it has no independent parameters.
223fn validate_spring_topology(
224    parents: &[Option<usize>],
225    chains: &[SpringTopologyChain],
226) -> Result<(), String> {
227    fn ancestor_or_same(parents: &[Option<usize>], ancestor: usize, node: usize) -> bool {
228        if ancestor == node {
229            return true;
230        }
231
232        let mut cursor = parents.get(node).copied().flatten();
233        let mut steps = 0;
234        while let Some(current) = cursor {
235            if current == ancestor {
236                return true;
237            }
238            steps += 1;
239            if steps > parents.len() {
240                return false;
241            }
242            cursor = parents.get(current).copied().flatten();
243        }
244        false
245    }
246
247    let node_count = parents.len();
248    let mut memberships = Vec::with_capacity(chains.len());
249    for (chain_index, chain) in chains.iter().enumerate() {
250        let Some(&first_joint) = chain.joints.first() else {
251            return Err(format!("spring {chain_index} has no joints"));
252        };
253        if first_joint >= node_count {
254            return Err(format!(
255                "spring {chain_index} joint 0 references missing node {first_joint}"
256            ));
257        }
258
259        let mut membership = vec![first_joint];
260        for (joint_index, pair) in chain.joints.windows(2).enumerate() {
261            let previous = pair[0];
262            let child = pair[1];
263            if child >= node_count {
264                return Err(format!(
265                    "spring {chain_index} joint {} references missing node {child}",
266                    joint_index + 1
267                ));
268            }
269            if previous == child {
270                return Err(format!(
271                    "spring {chain_index} joint {} must descend from the previous joint",
272                    joint_index + 1
273                ));
274            }
275
276            let mut cursor = child;
277            let mut steps = 0;
278            while cursor != previous {
279                membership.push(cursor);
280                let Some(parent) = parents.get(cursor).copied().flatten() else {
281                    return Err(format!(
282                        "spring {chain_index} joint {} must descend from the previous joint",
283                        joint_index + 1
284                    ));
285                };
286                cursor = parent;
287                steps += 1;
288                if steps > node_count {
289                    return Err(format!(
290                        "spring {chain_index} joint {} must descend from the previous joint",
291                        joint_index + 1
292                    ));
293                }
294            }
295        }
296        memberships.push(membership);
297    }
298
299    let mut owners = vec![None; node_count];
300    for (chain_index, membership) in memberships.iter().enumerate() {
301        for &node in membership {
302            if let Some(previous_chain) = owners[node] {
303                return Err(format!(
304                    "spring {chain_index} overlaps spring {previous_chain} at explicit or implicit joint node {node}"
305                ));
306            }
307            owners[node] = Some(chain_index);
308        }
309    }
310
311    for (chain_index, chain) in chains.iter().enumerate() {
312        let Some(center) = chain.center else {
313            continue;
314        };
315        if center >= node_count {
316            return Err(format!(
317                "spring {chain_index} references missing center node {center}"
318            ));
319        }
320        let first_joint = chain.joints[0];
321        if !ancestor_or_same(parents, center, first_joint) {
322            return Err(format!(
323                "spring {chain_index} center node {center} must be its first joint {first_joint} or an ancestor"
324            ));
325        }
326
327        for (other_index, membership) in memberships.iter().enumerate() {
328            if chain_index == other_index {
329                continue;
330            }
331            if let Some(other_joint) = membership
332                .iter()
333                .copied()
334                .find(|&node| ancestor_or_same(parents, node, center))
335            {
336                return Err(format!(
337                    "spring {chain_index} center node {center} must not be another spring's joint node {other_joint} or its descendant"
338                ));
339            }
340        }
341    }
342
343    Ok(())
344}
345
346fn parse_extended_collider_shape(
347    collider: &spec::Collider,
348) -> Result<Option<ColliderShape>, String> {
349    let Some(extension) = deserialize_extended_collider(collider)? else {
350        return Ok(None);
351    };
352    if extension.spec_version != "1.0" {
353        return Err("specVersion must be `1.0`".to_string());
354    }
355    let Some(shape) = extension.shape else {
356        return Ok(None);
357    };
358    let shape_count = usize::from(shape.sphere.is_some())
359        + usize::from(shape.capsule.is_some())
360        + usize::from(shape.plane.is_some());
361    if shape_count != 1 {
362        return Err("shape must contain exactly one shape".to_string());
363    }
364
365    if let Some(sphere) = shape.sphere {
366        return Ok(Some(ColliderShape::Sphere {
367            offset: finite_vec3(sphere.offset.unwrap_or([0.0; 3]), "sphere.offset")?,
368            radius: finite_radius(sphere.radius)?,
369            inside: sphere.inside,
370        }));
371    }
372    if let Some(capsule) = shape.capsule {
373        return Ok(Some(ColliderShape::Capsule {
374            offset: finite_vec3(capsule.offset.unwrap_or([0.0; 3]), "capsule.offset")?,
375            radius: finite_radius(capsule.radius)?,
376            tail: finite_vec3(capsule.tail.unwrap_or([0.0; 3]), "capsule.tail")?,
377            inside: capsule.inside,
378        }));
379    }
380    let Some(plane) = shape.plane else {
381        return Err("shape must contain exactly one shape".to_string());
382    };
383    let normal = finite_vec3(plane.normal.unwrap_or([0.0, 0.0, 1.0]), "plane.normal")?;
384    if normal.length_squared() <= f32::EPSILON {
385        return Err("plane.normal must not be zero".to_string());
386    }
387    Ok(Some(ColliderShape::Plane {
388        offset: finite_vec3(plane.offset.unwrap_or([0.0; 3]), "plane.offset")?,
389        // Normalizing here also provides the permissive-mode recovery value.
390        normal: normal.normalize(),
391    }))
392}
393
394fn extended_plane_normal_is_normalized(collider: &spec::Collider) -> Result<bool, String> {
395    let Some(extension) = deserialize_extended_collider(collider)? else {
396        return Ok(true);
397    };
398    let Some(plane) = extension.shape.and_then(|shape| shape.plane) else {
399        return Ok(true);
400    };
401    let normal = finite_vec3(plane.normal.unwrap_or([0.0, 0.0, 1.0]), "plane.normal")?;
402    Ok((normal.length() - 1.0).abs() <= PLANE_NORMAL_TOLERANCE)
403}
404
405impl SpringBone {
406    pub(crate) fn load_spring_bone(schema: &spec::VrmcSpringBoneSchema) -> Self {
407        let colliders: Vec<SpringCollider> = schema
408            .colliders
409            .as_deref()
410            .unwrap_or_default()
411            .iter()
412            .map(|c| {
413                let node_index = c.node.value() as u32;
414                let extended_shape = parse_extended_collider_shape(c).ok().flatten();
415                let shape = extended_shape.unwrap_or_else(|| {
416                    if let Some(sphere) = &c.shape.sphere {
417                        let offset = sphere
418                            .offset
419                            .map(|o| Vec3::new(o[0] as f32, o[1] as f32, o[2] as f32))
420                            .unwrap_or(Vec3::ZERO);
421                        ColliderShape::Sphere {
422                            offset,
423                            radius: sphere.radius.unwrap_or(0.0) as f32,
424                            inside: false,
425                        }
426                    } else if let Some(capsule) = &c.shape.capsule {
427                        let offset = capsule
428                            .offset
429                            .map(|o| Vec3::new(o[0] as f32, o[1] as f32, o[2] as f32))
430                            .unwrap_or(Vec3::ZERO);
431                        let tail = capsule
432                            .tail
433                            .map(|t| Vec3::new(t[0] as f32, t[1] as f32, t[2] as f32))
434                            .unwrap_or(Vec3::ZERO);
435                        ColliderShape::Capsule {
436                            offset,
437                            radius: capsule.radius.unwrap_or(0.0) as f32,
438                            tail,
439                            inside: false,
440                        }
441                    } else {
442                        ColliderShape::Sphere {
443                            offset: Vec3::ZERO,
444                            radius: 0.0,
445                            inside: false,
446                        }
447                    }
448                });
449                SpringCollider { node_index, shape }
450            })
451            .collect();
452
453        let collider_groups = schema
454            .collider_groups
455            .as_deref()
456            .unwrap_or_default()
457            .iter()
458            .map(|group| {
459                let group_colliders = group
460                    .colliders
461                    .iter()
462                    .filter_map(|&idx| colliders.get(idx).cloned())
463                    .collect();
464                SpringColliderGroup {
465                    name: group.name.clone(),
466                    colliders: group_colliders,
467                }
468            })
469            .collect();
470
471        let springs = schema
472            .springs
473            .as_deref()
474            .unwrap_or_default()
475            .iter()
476            .map(|spring| {
477                let joints = spring
478                    .joints
479                    .iter()
480                    .map(|j| {
481                        let g_dir = j
482                            .gravity_dir
483                            .map(|d| Vec3::new(d[0] as f32, d[1] as f32, d[2] as f32))
484                            .unwrap_or(Vec3::new(0.0, -1.0, 0.0));
485                        SpringJoint {
486                            node_index: j.node.value() as u32,
487                            hit_radius: j.hit_radius.unwrap_or(0.0) as f32,
488                            stiffness: j.stiffness.unwrap_or(1.0) as f32,
489                            gravity_power: j.gravity_power.unwrap_or(0.0) as f32,
490                            gravity_dir: g_dir,
491                            drag_force: j.drag_force.unwrap_or(0.5) as f32,
492                        }
493                    })
494                    .collect();
495
496                SpringChain {
497                    name: spring.name.clone(),
498                    center_node: spring.center.as_ref().map(|c| c.value() as u32),
499                    collider_groups: spring
500                        .collider_groups
501                        .as_deref()
502                        .unwrap_or_default()
503                        .iter()
504                        .map(|&idx| idx as usize)
505                        .collect(),
506                    joints,
507                }
508            })
509            .collect();
510
511        Self {
512            collider_groups,
513            springs,
514        }
515    }
516}
517
518#[cfg(test)]
519pub(crate) fn validate_schema(
520    doc: &gltf::Document,
521    schema: &spec::VrmcSpringBoneSchema,
522) -> Result<(), crate::LoadError> {
523    validate_schema_with_plane_normalization(doc, schema, false).map(|_| ())
524}
525
526/// Validates SpringBone and reports whether a recoverable plane normal was
527/// normalized while loading.
528///
529/// A permissive loader can set `allow_plane_normalization` and emit a warning
530/// when the returned value is `true`. Zero and non-finite normals remain fatal.
531pub(crate) fn validate_schema_with_plane_normalization(
532    doc: &gltf::Document,
533    schema: &spec::VrmcSpringBoneSchema,
534    allow_plane_normalization: bool,
535) -> Result<bool, crate::LoadError> {
536    if schema.spec_version != "1.0" {
537        return Err(crate::LoadError::InvalidVrm(
538            "/extensions/VRMC_springBone/specVersion must be `1.0`".to_string(),
539        ));
540    }
541    if schema
542        .colliders
543        .as_ref()
544        .is_some_and(|items| items.is_empty())
545    {
546        return Err(crate::LoadError::InvalidVrm(
547            "/extensions/VRMC_springBone/colliders must not be empty when present".to_string(),
548        ));
549    }
550    if schema
551        .collider_groups
552        .as_ref()
553        .is_some_and(|items| items.is_empty())
554    {
555        return Err(crate::LoadError::InvalidVrm(
556            "/extensions/VRMC_springBone/colliderGroups must not be empty when present".to_string(),
557        ));
558    }
559    if schema
560        .springs
561        .as_ref()
562        .is_some_and(|items| items.is_empty())
563    {
564        return Err(crate::LoadError::InvalidVrm(
565            "/extensions/VRMC_springBone/springs must not be empty when present".to_string(),
566        ));
567    }
568    let node_count = doc.nodes().count();
569    let colliders = schema.colliders.as_deref().unwrap_or_default();
570    let mut normalized_plane_normal = false;
571    for (index, collider) in colliders.iter().enumerate() {
572        if collider.node.value() >= node_count {
573            return Err(crate::LoadError::InvalidVrm(format!(
574                "/extensions/VRMC_springBone/colliders/{index}/node is out of range"
575            )));
576        }
577        let shape_count = usize::from(collider.shape.sphere.is_some())
578            + usize::from(collider.shape.capsule.is_some());
579        if shape_count != 1 {
580            return Err(crate::LoadError::InvalidVrm(format!(
581                "/extensions/VRMC_springBone/colliders/{index}/shape must contain exactly one shape"
582            )));
583        }
584        let valid_vec = finite_vec3_after_narrowing;
585        let valid_radius = |radius: f64| {
586            radius >= 0.0 && finite_f32(radius).is_some_and(|narrowed| narrowed >= 0.0)
587        };
588        let valid = if let Some(sphere) = collider.shape.sphere {
589            sphere.radius.is_none_or(valid_radius) && sphere.offset.is_none_or(valid_vec)
590        } else if let Some(capsule) = collider.shape.capsule {
591            capsule.radius.is_none_or(valid_radius)
592                && capsule.offset.is_none_or(valid_vec)
593                && capsule.tail.is_none_or(valid_vec)
594        } else {
595            false
596        };
597        if !valid {
598            return Err(crate::LoadError::InvalidVrm(format!(
599                "/extensions/VRMC_springBone/colliders/{index}/shape contains invalid values"
600            )));
601        }
602        parse_extended_collider_shape(collider).map_err(|message| {
603            crate::LoadError::InvalidVrm(format!(
604                "/extensions/VRMC_springBone/colliders/{index}/extensions/{VRMC_SPRING_BONE_EXTENDED_COLLIDER} {message}"
605            ))
606        })?;
607        let plane_normal_is_normalized =
608            extended_plane_normal_is_normalized(collider).map_err(|message| {
609            crate::LoadError::InvalidVrm(format!(
610                "/extensions/VRMC_springBone/colliders/{index}/extensions/{VRMC_SPRING_BONE_EXTENDED_COLLIDER} {message}"
611            ))
612        })?;
613        if !plane_normal_is_normalized && !allow_plane_normalization {
614            return Err(crate::LoadError::InvalidVrm(format!(
615                "/extensions/VRMC_springBone/colliders/{index}/extensions/{VRMC_SPRING_BONE_EXTENDED_COLLIDER}/shape/plane/normal must be normalized"
616            )));
617        }
618        normalized_plane_normal |= !plane_normal_is_normalized;
619    }
620
621    let groups = schema.collider_groups.as_deref().unwrap_or_default();
622    for (group_index, group) in groups.iter().enumerate() {
623        if group.colliders.is_empty() {
624            return Err(crate::LoadError::InvalidVrm(format!(
625                "/extensions/VRMC_springBone/colliderGroups/{group_index}/colliders must not be empty"
626            )));
627        }
628        if group
629            .colliders
630            .iter()
631            .any(|&index| index >= colliders.len())
632        {
633            return Err(crate::LoadError::InvalidVrm(format!(
634                "/extensions/VRMC_springBone/colliderGroups/{group_index}/colliders contains an invalid index"
635            )));
636        }
637    }
638
639    let mut parents = vec![None; node_count];
640    for node in doc.nodes() {
641        for child in node.children() {
642            parents[child.index()] = Some(node.index());
643        }
644    }
645    let springs = schema.springs.as_deref().unwrap_or_default();
646    let topology = springs
647        .iter()
648        .map(|spring| SpringTopologyChain {
649            center: spring.center.as_ref().map(|center| center.value()),
650            joints: spring
651                .joints
652                .iter()
653                .map(|joint| joint.node.value())
654                .collect(),
655        })
656        .collect::<Vec<_>>();
657    validate_spring_topology(&parents, &topology).map_err(|message| {
658        crate::LoadError::InvalidVrm(format!("/extensions/VRMC_springBone/springs {message}"))
659    })?;
660
661    for (spring_index, spring) in springs.iter().enumerate() {
662        if spring
663            .collider_groups
664            .as_ref()
665            .is_some_and(|items| items.is_empty())
666        {
667            return Err(crate::LoadError::InvalidVrm(format!(
668                "/extensions/VRMC_springBone/springs/{spring_index}/colliderGroups must not be empty when present"
669            )));
670        }
671        if spring
672            .collider_groups
673            .as_deref()
674            .unwrap_or_default()
675            .iter()
676            .any(|&index| index < 0 || index as usize >= groups.len())
677        {
678            return Err(crate::LoadError::InvalidVrm(format!(
679                "/extensions/VRMC_springBone/springs/{spring_index}/colliderGroups contains an invalid index"
680            )));
681        }
682        for (joint_index, joint) in spring.joints.iter().enumerate() {
683            let non_negative = |value: Option<f64>| {
684                value.is_none_or(|value| {
685                    value >= 0.0 && finite_f32(value).is_some_and(|narrowed| narrowed >= 0.0)
686                })
687            };
688            if !non_negative(joint.hit_radius)
689                || !non_negative(joint.stiffness)
690                || !non_negative(joint.gravity_power)
691                || joint.drag_force.is_some_and(|value| {
692                    !(0.0..=1.0).contains(&value)
693                        || finite_f32(value).is_none_or(|narrowed| !(0.0..=1.0).contains(&narrowed))
694                })
695                || joint
696                    .gravity_dir
697                    .is_some_and(|value| !finite_vec3_after_narrowing(value))
698            {
699                return Err(crate::LoadError::InvalidVrm(format!(
700                    "/extensions/VRMC_springBone/springs/{spring_index}/joints/{joint_index} contains invalid physics values"
701                )));
702            }
703        }
704    }
705    Ok(normalized_plane_normal)
706}
707
708pub(crate) fn sort_springs_by_ancestry(doc: &gltf::Document, spring_bone: &mut SpringBone) {
709    let mut parents = vec![None; doc.nodes().count()];
710    for node in doc.nodes() {
711        for child in node.children() {
712            parents[child.index()] = Some(node.index());
713        }
714    }
715    let depth = |node: usize| {
716        let mut depth = 0usize;
717        let mut cursor = parents.get(node).copied().flatten();
718        while let Some(parent) = cursor {
719            depth += 1;
720            cursor = parents.get(parent).copied().flatten();
721        }
722        depth
723    };
724    spring_bone.springs.sort_by_key(|spring| {
725        spring
726            .joints
727            .first()
728            .map(|joint| depth(joint.node_index as usize))
729            .unwrap_or(usize::MAX)
730    });
731}
732
733pub(crate) fn validate_programmatic(
734    nodes: &[AvatarNode],
735    spring_bone: &SpringBone,
736) -> Result<(), String> {
737    let node_count = nodes.len();
738    let valid_vec = |value: Vec3| value.is_finite();
739
740    for (group_index, group) in spring_bone.collider_groups.iter().enumerate() {
741        if group.colliders.is_empty() {
742            return Err(format!(
743                "spring collider group {group_index} must contain at least one collider"
744            ));
745        }
746        for (collider_index, collider) in group.colliders.iter().enumerate() {
747            if collider.node_index as usize >= node_count {
748                return Err(format!(
749                    "spring collider {group_index}:{collider_index} references missing node {}",
750                    collider.node_index
751                ));
752            }
753            let valid = match collider.shape {
754                ColliderShape::Sphere { offset, radius, .. } => {
755                    valid_vec(offset) && radius.is_finite() && radius >= 0.0
756                }
757                ColliderShape::Capsule {
758                    offset,
759                    radius,
760                    tail,
761                    ..
762                } => valid_vec(offset) && valid_vec(tail) && radius.is_finite() && radius >= 0.0,
763                ColliderShape::Plane { offset, normal } => {
764                    valid_vec(offset)
765                        && valid_vec(normal)
766                        && (normal.length() - 1.0).abs() <= PLANE_NORMAL_TOLERANCE
767                }
768            };
769            if !valid {
770                return Err(format!(
771                    "spring collider {group_index}:{collider_index} contains invalid values"
772                ));
773            }
774        }
775    }
776
777    let parents = nodes
778        .iter()
779        .map(|node| node.parent.map(|parent| parent as usize))
780        .collect::<Vec<_>>();
781    let topology = spring_bone
782        .springs
783        .iter()
784        .map(|spring| SpringTopologyChain {
785            center: spring.center_node.map(|center| center as usize),
786            joints: spring
787                .joints
788                .iter()
789                .map(|joint| joint.node_index as usize)
790                .collect(),
791        })
792        .collect::<Vec<_>>();
793    validate_spring_topology(&parents, &topology)?;
794
795    for (spring_index, spring) in spring_bone.springs.iter().enumerate() {
796        if spring
797            .collider_groups
798            .iter()
799            .any(|&group| group >= spring_bone.collider_groups.len())
800        {
801            return Err(format!(
802                "spring {spring_index} references a missing collider group"
803            ));
804        }
805        for (joint_index, joint) in spring.joints.iter().enumerate() {
806            if !joint.hit_radius.is_finite()
807                || joint.hit_radius < 0.0
808                || !joint.stiffness.is_finite()
809                || joint.stiffness < 0.0
810                || !joint.gravity_power.is_finite()
811                || joint.gravity_power < 0.0
812                || !valid_vec(joint.gravity_dir)
813                || !joint.drag_force.is_finite()
814                || !(0.0..=1.0).contains(&joint.drag_force)
815            {
816                return Err(format!(
817                    "spring {spring_index} joint {joint_index} contains invalid physics values"
818                ));
819            }
820        }
821    }
822
823    Ok(())
824}
825
826/// Stateful spring bone simulator (L3).
827///
828/// Owned by [`crate::AvatarRuntime`], which drives it once per frame.
829/// Advanced consumers can drive it directly via [`Self::initialize`] /
830/// [`Self::update`] for a custom pipeline.
831///
832/// Simulates each spring chain with verlet integration: inertia is applied
833/// in the center node's space, stiffness and gravity in world space, and
834/// the bone axis is derived from the avatar's rest pose. Each joint pair
835/// `(joints[n], joints[n+1])` becomes one simulated joint; the last entry
836/// in `joints` is only a tail marker and is never simulated itself.
837pub struct SpringBoneSimulator {
838    chains: Vec<SimulatedSpringChain>,
839    initialized: bool,
840}
841
842#[derive(Debug, Clone)]
843struct SimulatedSpringChain {
844    center_node: Option<u32>,
845    collider_group_indices: Vec<usize>,
846    joints: Vec<SimulatedJoint>,
847}
848
849#[derive(Debug, Clone)]
850struct SimulatedJoint {
851    node_index: u32,
852    parent_node_index: Option<u32>,
853    bone_axis: Vec3,
854    bone_length: f32,
855    initial_local_rotation: Quat,
856    rest_local_matrix: Mat4,
857    stiffness: f32,
858    gravity_power: f32,
859    gravity_dir: Vec3,
860    drag_force: f32,
861    hit_radius: f32,
862    current_tail: Vec3,
863    prev_tail: Vec3,
864}
865
866#[derive(Debug, Clone)]
867enum WorldCollider {
868    Sphere {
869        center: Vec3,
870        radius: f32,
871        inside: bool,
872    },
873    Capsule {
874        head: Vec3,
875        tail: Vec3,
876        radius: f32,
877        inside: bool,
878    },
879    Plane {
880        offset: Vec3,
881        normal: Vec3,
882    },
883}
884
885impl WorldCollider {
886    fn from_local(shape: &ColliderShape, transform: Mat4) -> Self {
887        // VRM requires positive uniform node scales, so one transformed basis
888        // length is the world-space radius multiplier.
889        let radius_scale = transform.x_axis.truncate().length();
890        match shape {
891            ColliderShape::Sphere {
892                offset,
893                radius,
894                inside,
895            } => Self::Sphere {
896                center: transform.transform_point3(*offset),
897                radius: radius * radius_scale,
898                inside: *inside,
899            },
900            ColliderShape::Capsule {
901                offset,
902                radius,
903                tail,
904                inside,
905            } => Self::Capsule {
906                head: transform.transform_point3(*offset),
907                tail: transform.transform_point3(*tail),
908                radius: radius * radius_scale,
909                inside: *inside,
910            },
911            ColliderShape::Plane { offset, normal } => {
912                let normal_matrix = Mat3::from_mat4(transform).inverse().transpose();
913                Self::Plane {
914                    offset: transform.transform_point3(*offset),
915                    normal: (normal_matrix * *normal).normalize_or_zero(),
916                }
917            }
918        }
919    }
920
921    fn collision(&self, next_tail: Vec3, joint_radius: f32) -> (Vec3, f32) {
922        match self {
923            Self::Sphere {
924                center,
925                radius,
926                inside,
927            } => collision_with_axis_point(next_tail - *center, *radius, joint_radius, *inside),
928            Self::Capsule {
929                head,
930                tail,
931                radius,
932                inside,
933            } => {
934                let segment = *tail - *head;
935                let segment_length_squared = segment.length_squared();
936                let offset_from_head = next_tail - *head;
937                let t = if segment_length_squared > 1.0e-6 {
938                    (offset_from_head.dot(segment) / segment_length_squared).clamp(0.0, 1.0)
939                } else {
940                    0.0
941                };
942                let delta = next_tail - (*head + segment * t);
943                collision_with_axis_point(delta, *radius, joint_radius, *inside)
944            }
945            Self::Plane { offset, normal } => {
946                let delta = next_tail - *offset;
947                (*normal, delta.dot(*normal) - joint_radius)
948            }
949        }
950    }
951}
952
953fn collision_with_axis_point(
954    delta: Vec3,
955    collider_radius: f32,
956    joint_radius: f32,
957    inside: bool,
958) -> (Vec3, f32) {
959    let magnitude = delta.length();
960    let direction = if magnitude > 1.0e-6 {
961        delta / magnitude
962    } else {
963        Vec3::ZERO
964    };
965    if inside {
966        (-direction, collider_radius - joint_radius - magnitude)
967    } else {
968        (direction, magnitude - (collider_radius + joint_radius))
969    }
970}
971
972impl Default for SpringBoneSimulator {
973    fn default() -> Self {
974        Self::new()
975    }
976}
977
978impl SpringBoneSimulator {
979    /// Creates an uninitialized simulator with no retained motion state.
980    pub fn new() -> Self {
981        Self {
982            chains: Vec::new(),
983            initialized: false,
984        }
985    }
986
987    /// Resets all simulated state; the next [`Self::update`] call re-initializes
988    /// from the avatar's rest pose.
989    pub fn reset(&mut self) {
990        self.chains.clear();
991        self.initialized = false;
992    }
993
994    /// Builds the simulated chains from the avatar's rest pose. The rest data
995    /// (bone axis, bone length, initial rotations) is derived from the static
996    /// node tree, so the passed world matrices are not required.
997    pub fn initialize(&mut self, avatar: &Avatar, _world_matrices: &[Mat4]) {
998        let nodes = avatar.nodes();
999        let rest_world = crate::node::compute_world_matrices(nodes, &[]);
1000        let spring_bone = avatar.spring_bone();
1001
1002        self.chains.clear();
1003
1004        let node_depth = |node_index: u32| {
1005            let mut depth = 0usize;
1006            let mut cursor = nodes.get(node_index as usize).and_then(|node| node.parent);
1007            while let Some(parent) = cursor {
1008                depth += 1;
1009                cursor = nodes.get(parent as usize).and_then(|node| node.parent);
1010            }
1011            depth
1012        };
1013        let mut springs: Vec<&SpringChain> = spring_bone.springs.iter().collect();
1014        springs.sort_by_key(|spring| {
1015            spring
1016                .joints
1017                .first()
1018                .map(|joint| node_depth(joint.node_index))
1019                .unwrap_or(usize::MAX)
1020        });
1021
1022        for spring in springs {
1023            let center_mat = spring
1024                .center_node
1025                .and_then(|c| rest_world.get(c as usize))
1026                .copied();
1027            let world_to_center = center_mat.map(|m| m.inverse()).unwrap_or(Mat4::IDENTITY);
1028
1029            let mut joints = Vec::new();
1030
1031            // Each consecutive pair (joints[n], joints[n+1]) is one simulated
1032            // joint: joints[n] is the head, joints[n+1] is the tail.
1033            for pair in spring.joints.windows(2) {
1034                let head = &pair[0];
1035                let child_node_index = pair[1].node_index;
1036
1037                let head_idx = head.node_index as usize;
1038                let child_idx = child_node_index as usize;
1039                if head_idx >= nodes.len() || child_idx >= nodes.len() {
1040                    continue;
1041                }
1042
1043                let head_world = rest_world[head_idx];
1044                let head_pos = head_world.transform_point3(Vec3::ZERO);
1045                let child_pos = rest_world[child_idx].transform_point3(Vec3::ZERO);
1046
1047                let world_dir = child_pos - head_pos;
1048                let bone_length = world_dir.length();
1049                if bone_length <= 1e-6 {
1050                    continue;
1051                }
1052
1053                // boneAxis: rest direction toward the child, in the head's own
1054                // local coordinate system.
1055                let local_dir = head_world.inverse().transform_vector3(world_dir);
1056                let bone_axis = local_dir.normalize_or_zero();
1057                if bone_axis == Vec3::ZERO {
1058                    continue;
1059                }
1060
1061                let node = &nodes[head_idx];
1062                let current_tail = world_to_center.transform_point3(child_pos);
1063
1064                joints.push(SimulatedJoint {
1065                    node_index: head.node_index,
1066                    parent_node_index: node.parent,
1067                    bone_axis,
1068                    bone_length,
1069                    initial_local_rotation: node.initial_rotation,
1070                    rest_local_matrix: node.initial_local_matrix(),
1071                    stiffness: head.stiffness,
1072                    gravity_power: head.gravity_power,
1073                    gravity_dir: head.gravity_dir,
1074                    drag_force: head.drag_force,
1075                    hit_radius: head.hit_radius,
1076                    current_tail,
1077                    prev_tail: current_tail,
1078                });
1079            }
1080
1081            if !joints.is_empty() {
1082                self.chains.push(SimulatedSpringChain {
1083                    center_node: spring.center_node,
1084                    collider_group_indices: spring.collider_groups.clone(),
1085                    joints,
1086                });
1087            }
1088        }
1089
1090        self.initialized = true;
1091    }
1092
1093    /// Advances every chain by `dt` seconds and returns the resulting head-node
1094    /// rotations as [`BoneUpdate`]s (deltas on top of the initial rotation).
1095    ///
1096    /// The simulation is stateful: pass the same `dt` and pose each frame and
1097    /// the chains keep their velocity. See [`Self::reset`] to return to rest.
1098    pub fn update(&mut self, avatar: &Avatar, world_matrices: &[Mat4], dt: f32) -> Vec<BoneUpdate> {
1099        if !self.initialized {
1100            self.initialize(avatar, world_matrices);
1101        }
1102        if dt <= 0.0 {
1103            return Vec::new();
1104        }
1105
1106        let nodes = avatar.nodes();
1107        let spring_bone = avatar.spring_bone();
1108        let mut updates = Vec::new();
1109
1110        // Running world matrices: updated as each joint rotates so that the
1111        // next joint in the chain sees its head position and parent rotation
1112        // including already-applied spring rotations.
1113        let mut current_world: Vec<Mat4> = world_matrices.to_vec();
1114
1115        for chain in &mut self.chains {
1116            let center_mat = chain
1117                .center_node
1118                .and_then(|c| current_world.get(c as usize))
1119                .copied();
1120            let center_to_world = center_mat.unwrap_or(Mat4::IDENTITY);
1121            let world_to_center = center_mat.map(|m| m.inverse()).unwrap_or(Mat4::IDENTITY);
1122
1123            // World-space colliders of the groups this chain collides with.
1124            let mut colliders = Vec::new();
1125            for &g_idx in &chain.collider_group_indices {
1126                let Some(group) = spring_bone.collider_groups.get(g_idx) else {
1127                    continue;
1128                };
1129                for col in &group.colliders {
1130                    let c_idx = col.node_index as usize;
1131                    if c_idx >= current_world.len() {
1132                        continue;
1133                    }
1134                    let mat = current_world[c_idx];
1135                    colliders.push(WorldCollider::from_local(&col.shape, mat));
1136                }
1137            }
1138
1139            // joints[j+1] is the tail of simulated joint j.
1140            let next_node_indices: Vec<u32> =
1141                chain.joints.iter().skip(1).map(|j| j.node_index).collect();
1142
1143            for (j, joint) in chain.joints.iter_mut().enumerate() {
1144                let idx = joint.node_index as usize;
1145                if idx >= current_world.len() {
1146                    continue;
1147                }
1148
1149                // Head position, already reflecting ancestor spring rotations.
1150                let head_world = current_world[idx];
1151                let head_pos = head_world.transform_point3(Vec3::ZERO);
1152
1153                let parent_world = match joint.parent_node_index {
1154                    Some(p) if (p as usize) < current_world.len() => current_world[p as usize],
1155                    _ => Mat4::IDENTITY,
1156                };
1157                let parent_rot = parent_world.to_scale_rotation_translation().1;
1158
1159                // Stiffness pulls the tail along the rest bone axis, rotated
1160                // into world space by the current parent orientation.
1161                let world_axis = (parent_rot * joint.initial_local_rotation * joint.bone_axis)
1162                    .normalize_or_zero();
1163
1164                // Verlet integration. Inertia is evaluated in center space;
1165                // stiffness and gravity are applied in world space.
1166                let inertia = (joint.current_tail - joint.prev_tail) * (1.0 - joint.drag_force);
1167                let mut next_tail_world =
1168                    center_to_world.transform_point3(joint.current_tail + inertia);
1169                next_tail_world += world_axis * (joint.stiffness * dt);
1170                next_tail_world += joint.gravity_dir * (joint.gravity_power * dt);
1171
1172                // Constrain the bone length.
1173                let dir = (next_tail_world - head_pos).normalize_or_zero();
1174                if dir != Vec3::ZERO {
1175                    next_tail_world = head_pos + dir * joint.bone_length;
1176                }
1177
1178                // Collision with the chain's colliders.
1179                for col in &colliders {
1180                    let (direction, distance) = col.collision(next_tail_world, joint.hit_radius);
1181                    if distance < 0.0 {
1182                        // Push the tail out of the collider, then re-normalize.
1183                        next_tail_world -= direction * distance;
1184                        let dir = (next_tail_world - head_pos).normalize_or_zero();
1185                        if dir != Vec3::ZERO {
1186                            next_tail_world = head_pos + dir * joint.bone_length;
1187                        }
1188                    }
1189                }
1190
1191                joint.prev_tail = joint.current_tail;
1192                joint.current_tail = world_to_center.transform_point3(next_tail_world);
1193
1194                // Rotate the head node so its boneAxis points at the tail.
1195                // to = tail direction in the head's rest local frame.
1196                let rest_world_inv = (parent_world * joint.rest_local_matrix).inverse();
1197                let to = rest_world_inv
1198                    .transform_point3(next_tail_world)
1199                    .normalize_or_zero();
1200                if to != Vec3::ZERO {
1201                    let delta = Quat::from_rotation_arc(joint.bone_axis, to);
1202                    updates.push(BoneUpdate::new(joint.node_index, delta));
1203
1204                    // Propagate the rotation into the running world matrices so
1205                    // the next joint (the child) sees the updated pose.
1206                    let node = &nodes[idx];
1207                    let local = Mat4::from_scale_rotation_translation(
1208                        node.initial_scale,
1209                        node.initial_rotation * delta,
1210                        node.initial_translation,
1211                    );
1212                    current_world[idx] = parent_world * local;
1213                    if let Some(&next_node) = next_node_indices.get(j) {
1214                        update_path(&mut current_world, nodes, joint.node_index, next_node);
1215                    }
1216                }
1217            }
1218        }
1219
1220        updates
1221    }
1222}
1223
1224/// Recomputes the world matrices of the nodes strictly between `from` and `to`
1225/// (walking from `to` upward), so descendants of a rotated joint reflect the
1226/// new pose.
1227fn update_path(current_world: &mut [Mat4], nodes: &[AvatarNode], from: u32, to: u32) {
1228    let mut cur = to;
1229    while cur != from {
1230        let idx = cur as usize;
1231        if idx >= nodes.len() {
1232            break;
1233        }
1234        let Some(parent) = nodes[idx].parent else {
1235            break;
1236        };
1237        let p_idx = parent as usize;
1238        if p_idx >= current_world.len() {
1239            break;
1240        }
1241        current_world[idx] = current_world[p_idx] * nodes[idx].initial_local_matrix();
1242        cur = parent;
1243    }
1244}
1245
1246#[cfg(test)]
1247mod tests {
1248    use super::*;
1249    use serde_json::json;
1250
1251    fn node(index: u32, translation: Vec3, parent: Option<u32>) -> AvatarNode {
1252        AvatarNode {
1253            index,
1254            name: None,
1255            parent,
1256            children: Vec::new(),
1257            initial_translation: translation,
1258            initial_rotation: Quat::IDENTITY,
1259            initial_scale: Vec3::ONE,
1260        }
1261    }
1262
1263    fn avatar_with_one_node() -> Avatar {
1264        Avatar::new().with_nodes(vec![AvatarNode {
1265            index: 0,
1266            name: None,
1267            parent: None,
1268            children: Vec::new(),
1269            initial_translation: Vec3::ZERO,
1270            initial_rotation: Quat::IDENTITY,
1271            initial_scale: Vec3::ONE,
1272        }])
1273    }
1274
1275    fn single_joint_chain(
1276        axis: Vec3,
1277        stiffness: f32,
1278        gravity_power: f32,
1279        gravity_dir: Vec3,
1280        drag: f32,
1281    ) -> SimulatedSpringChain {
1282        SimulatedSpringChain {
1283            center_node: None,
1284            collider_group_indices: Vec::new(),
1285            joints: vec![SimulatedJoint {
1286                node_index: 0,
1287                parent_node_index: None,
1288                bone_axis: axis,
1289                bone_length: 0.1,
1290                initial_local_rotation: Quat::IDENTITY,
1291                rest_local_matrix: Mat4::IDENTITY,
1292                stiffness,
1293                gravity_power,
1294                gravity_dir,
1295                drag_force: drag,
1296                hit_radius: 0.02,
1297                current_tail: axis * 0.1,
1298                prev_tail: axis * 0.1,
1299            }],
1300        }
1301    }
1302
1303    fn run(sim: &mut SpringBoneSimulator, avatar: &Avatar, steps: usize) -> Vec<Vec<BoneUpdate>> {
1304        let world = vec![Mat4::IDENTITY; 2];
1305        (0..steps)
1306            .map(|_| sim.update(avatar, &world, 0.016))
1307            .collect()
1308    }
1309
1310    #[test]
1311    fn no_springs_yields_no_updates() {
1312        let avatar = Avatar::new();
1313        let mut sim = SpringBoneSimulator::new();
1314        let world = vec![Mat4::IDENTITY; 2];
1315        let updates = sim.update(&avatar, &world, 0.016);
1316        assert!(updates.is_empty());
1317    }
1318
1319    #[test]
1320    fn perpendicular_gravity_swings_tail() {
1321        let avatar = avatar_with_one_node();
1322        let mut sim = SpringBoneSimulator {
1323            chains: vec![single_joint_chain(Vec3::Y, 0.0, 1.0, Vec3::NEG_X, 1.0)],
1324            initialized: true,
1325        };
1326
1327        run(&mut sim, &avatar, 10);
1328
1329        let tail = sim.chains[0].joints[0].current_tail;
1330        assert!(tail.x < -0.03, "tail should swing toward -X, got {tail:?}");
1331        assert!((tail.length() - 0.1).abs() < 1e-2, "bone length preserved");
1332    }
1333
1334    #[test]
1335    fn stiffness_holds_tail_on_axis() {
1336        let avatar = avatar_with_one_node();
1337        let mut sim = SpringBoneSimulator {
1338            chains: vec![single_joint_chain(Vec3::Y, 10.0, 0.0, Vec3::NEG_Y, 1.0)],
1339            initialized: true,
1340        };
1341
1342        run(&mut sim, &avatar, 30);
1343
1344        let tail = sim.chains[0].joints[0].current_tail;
1345        assert!(
1346            tail.distance(Vec3::Y * 0.1) < 1e-3,
1347            "tail should stay on axis"
1348        );
1349    }
1350
1351    #[test]
1352    fn collider_deflects_tail_away() {
1353        let node = avatar_with_one_node();
1354        let collider = SpringCollider {
1355            node_index: 1,
1356            shape: ColliderShape::Sphere {
1357                offset: Vec3::new(-0.06, 0.08, 0.0),
1358                radius: 0.06,
1359                inside: false,
1360            },
1361        };
1362        let mut chain = single_joint_chain(Vec3::Y, 0.0, 1.0, Vec3::NEG_X, 1.0);
1363        chain.collider_group_indices = vec![0];
1364
1365        let mut with_collider = SpringBoneSimulator {
1366            chains: vec![chain.clone()],
1367            initialized: true,
1368        };
1369        let mut without_collider = SpringBoneSimulator {
1370            chains: vec![single_joint_chain(Vec3::Y, 0.0, 1.0, Vec3::NEG_X, 1.0)],
1371            initialized: true,
1372        };
1373
1374        let avatar_with = node.clone().with_spring_bone(SpringBone {
1375            collider_groups: vec![SpringColliderGroup {
1376                name: None,
1377                colliders: vec![collider],
1378            }],
1379            springs: Vec::new(),
1380        });
1381
1382        run(&mut with_collider, &avatar_with, 60);
1383        run(&mut without_collider, &node, 60);
1384
1385        let blocked = with_collider.chains[0].joints[0].current_tail;
1386        let free = without_collider.chains[0].joints[0].current_tail;
1387        assert!(
1388            blocked.x > free.x,
1389            "collider should block the -X swing: blocked={blocked:?} free={free:?}"
1390        );
1391    }
1392
1393    #[test]
1394    fn update_is_deterministic() {
1395        let avatar = avatar_with_one_node();
1396        let mut a = SpringBoneSimulator {
1397            chains: vec![single_joint_chain(Vec3::Y, 0.0, 1.0, Vec3::NEG_X, 1.0)],
1398            initialized: true,
1399        };
1400        let mut b = SpringBoneSimulator {
1401            chains: vec![single_joint_chain(Vec3::Y, 0.0, 1.0, Vec3::NEG_X, 1.0)],
1402            initialized: true,
1403        };
1404
1405        let updates_a = run(&mut a, &avatar, 30);
1406        let updates_b = run(&mut b, &avatar, 30);
1407
1408        assert_eq!(updates_a.len(), updates_b.len());
1409        for (step_a, step_b) in updates_a.iter().zip(updates_b.iter()) {
1410            assert_eq!(step_a.len(), step_b.len());
1411            for (u1, u2) in step_a.iter().zip(step_b.iter()) {
1412                assert_eq!(u1, u2);
1413            }
1414        }
1415    }
1416
1417    #[test]
1418    fn initialize_orders_springs_by_joint_ancestry() {
1419        let nodes = vec![
1420            node(0, Vec3::ZERO, None),
1421            node(1, Vec3::Y, Some(0)),
1422            node(2, Vec3::Y, Some(1)),
1423            node(3, Vec3::Y, Some(2)),
1424        ];
1425        let joint = |node_index| SpringJoint {
1426            node_index,
1427            hit_radius: 0.0,
1428            stiffness: 1.0,
1429            gravity_power: 0.0,
1430            gravity_dir: Vec3::NEG_Y,
1431            drag_force: 0.5,
1432        };
1433        let descendant = SpringChain {
1434            name: Some("descendant".to_string()),
1435            center_node: None,
1436            collider_groups: vec![],
1437            joints: vec![joint(2), joint(3)],
1438        };
1439        let ancestor = SpringChain {
1440            name: Some("ancestor".to_string()),
1441            center_node: None,
1442            collider_groups: vec![],
1443            joints: vec![joint(0), joint(1)],
1444        };
1445        let avatar = Avatar::new()
1446            .with_nodes(nodes)
1447            .with_spring_bone(SpringBone {
1448                collider_groups: vec![],
1449                springs: vec![descendant, ancestor],
1450            });
1451        let mut simulator = SpringBoneSimulator::new();
1452
1453        simulator.initialize(&avatar, &[]);
1454
1455        assert_eq!(simulator.chains[0].joints[0].node_index, 0);
1456        assert_eq!(simulator.chains[1].joints[0].node_index, 2);
1457    }
1458
1459    fn spring_schema(collider: serde_json::Value) -> spec::VrmcSpringBoneSchema {
1460        serde_json::from_value(json!({
1461            "specVersion": "1.0",
1462            "colliders": [collider],
1463            "colliderGroups": [{ "colliders": [0] }]
1464        }))
1465        .expect("the test spring schema must deserialize")
1466    }
1467
1468    fn document_with_one_node() -> gltf::Document {
1469        gltf::Gltf::from_slice(br#"{"asset":{"version":"2.0"},"nodes":[{}]}"#)
1470            .expect("the test glTF must be valid")
1471            .document
1472    }
1473
1474    fn extended_collider(shape: serde_json::Value) -> serde_json::Value {
1475        json!({
1476            "node": 0,
1477            "shape": {
1478                "sphere": {
1479                    "offset": [0.0, -10000.0, 0.0],
1480                    "radius": 0.0
1481                }
1482            },
1483            "extensions": {
1484                "VRMC_springBone_extended_collider": {
1485                    "specVersion": "1.0",
1486                    "shape": shape
1487                }
1488            }
1489        })
1490    }
1491
1492    #[test]
1493    fn extended_inside_sphere_overrides_the_core_fallback() {
1494        let schema = spring_schema(extended_collider(json!({
1495            "sphere": {
1496                "offset": [1.0, 2.0, 3.0],
1497                "radius": 0.5,
1498                "inside": true
1499            }
1500        })));
1501
1502        let spring_bone = SpringBone::load_spring_bone(&schema);
1503        let parsed = &spring_bone.collider_groups[0].colliders[0].shape;
1504
1505        match parsed {
1506            ColliderShape::Sphere {
1507                offset,
1508                radius,
1509                inside,
1510            } => {
1511                assert_eq!(*offset, Vec3::new(1.0, 2.0, 3.0));
1512                assert_eq!(*radius, 0.5);
1513                assert!(*inside);
1514            }
1515            other => panic!("expected an inside sphere, got {other:?}"),
1516        }
1517    }
1518
1519    #[test]
1520    fn extended_inside_capsule_preserves_head_tail_and_radius() {
1521        let schema = spring_schema(extended_collider(json!({
1522            "capsule": {
1523                "offset": [1.0, 2.0, 3.0],
1524                "tail": [4.0, 5.0, 6.0],
1525                "radius": 0.75,
1526                "inside": true
1527            }
1528        })));
1529
1530        let spring_bone = SpringBone::load_spring_bone(&schema);
1531
1532        match &spring_bone.collider_groups[0].colliders[0].shape {
1533            ColliderShape::Capsule {
1534                offset,
1535                tail,
1536                radius,
1537                inside,
1538            } => {
1539                assert_eq!(*offset, Vec3::new(1.0, 2.0, 3.0));
1540                assert_eq!(*tail, Vec3::new(4.0, 5.0, 6.0));
1541                assert_eq!(*radius, 0.75);
1542                assert!(*inside);
1543            }
1544            other => panic!("expected an inside capsule, got {other:?}"),
1545        }
1546    }
1547
1548    #[test]
1549    fn core_collider_fallback_loads_as_an_outside_shape() {
1550        let schema = spring_schema(json!({
1551            "node": 0,
1552            "shape": {
1553                "sphere": {
1554                    "offset": [1.0, 2.0, 3.0],
1555                    "radius": 0.5
1556                }
1557            }
1558        }));
1559
1560        let spring_bone = SpringBone::load_spring_bone(&schema);
1561
1562        match &spring_bone.collider_groups[0].colliders[0].shape {
1563            ColliderShape::Sphere { inside, .. } => assert!(!inside),
1564            other => panic!("expected a sphere, got {other:?}"),
1565        }
1566    }
1567
1568    #[test]
1569    fn extended_plane_overrides_the_core_fallback_during_loading() {
1570        let schema = spring_schema(extended_collider(json!({
1571            "plane": {
1572                "offset": [0.0, 2.0, 0.0],
1573                "normal": [0.0, 1.0, 0.0]
1574            }
1575        })));
1576
1577        let spring_bone = SpringBone::load_spring_bone(&schema);
1578
1579        match &spring_bone.collider_groups[0].colliders[0].shape {
1580            ColliderShape::Plane { offset, normal } => {
1581                assert_eq!(*offset, Vec3::new(0.0, 2.0, 0.0));
1582                assert_eq!(*normal, Vec3::Y);
1583            }
1584            other => panic!("expected a plane, got {other:?}"),
1585        }
1586    }
1587
1588    #[test]
1589    fn validates_extended_collider_version_and_shape_cardinality() {
1590        let doc = document_with_one_node();
1591        let mut wrong_version = extended_collider(json!({
1592            "sphere": { "radius": 1.0 }
1593        }));
1594        wrong_version["extensions"]["VRMC_springBone_extended_collider"]["specVersion"] =
1595            json!("1.0-beta");
1596        assert!(validate_schema(&doc, &spring_schema(wrong_version)).is_err());
1597
1598        let multiple_shapes = extended_collider(json!({
1599            "sphere": { "radius": 1.0 },
1600            "plane": { "normal": [0.0, 1.0, 0.0] }
1601        }));
1602        assert!(validate_schema(&doc, &spring_schema(multiple_shapes)).is_err());
1603    }
1604
1605    #[test]
1606    fn validates_extended_collider_numbers_and_plane_normal() {
1607        let doc = document_with_one_node();
1608        let negative_radius = extended_collider(json!({
1609            "capsule": { "radius": -0.1 }
1610        }));
1611        assert!(validate_schema(&doc, &spring_schema(negative_radius)).is_err());
1612
1613        let zero_normal = extended_collider(json!({
1614            "plane": { "normal": [0.0, 0.0, 0.0] }
1615        }));
1616        assert!(validate_schema(&doc, &spring_schema(zero_normal)).is_err());
1617
1618        let non_normalized = extended_collider(json!({
1619            "plane": { "normal": [0.0, 2.0, 0.0] }
1620        }));
1621        assert!(validate_schema(&doc, &spring_schema(non_normalized)).is_err());
1622
1623        let recoverable_normal = extended_collider(json!({
1624            "plane": { "normal": [0.0, 2.0, 0.0] }
1625        }));
1626        assert!(
1627            validate_schema_with_plane_normalization(
1628                &doc,
1629                &spring_schema(recoverable_normal),
1630                true,
1631            )
1632            .expect("permissive validation must normalize a non-zero plane normal")
1633        );
1634
1635        let default_normal = extended_collider(json!({ "plane": {} }));
1636        assert!(validate_schema(&doc, &spring_schema(default_normal)).is_ok());
1637    }
1638
1639    #[test]
1640    fn programmatic_plane_requires_a_finite_normalized_normal() {
1641        let spring_bone = |normal| SpringBone {
1642            collider_groups: vec![SpringColliderGroup {
1643                name: None,
1644                colliders: vec![SpringCollider {
1645                    node_index: 0,
1646                    shape: ColliderShape::Plane {
1647                        offset: Vec3::ZERO,
1648                        normal,
1649                    },
1650                }],
1651            }],
1652            springs: Vec::new(),
1653        };
1654        let nodes = [node(0, Vec3::ZERO, None)];
1655
1656        assert!(validate_programmatic(&nodes, &spring_bone(Vec3::Y)).is_ok());
1657        assert!(validate_programmatic(&nodes, &spring_bone(Vec3::ZERO)).is_err());
1658        assert!(validate_programmatic(&nodes, &spring_bone(Vec3::Y * 2.0)).is_err());
1659    }
1660
1661    fn resolve_collision(collider: &WorldCollider, tail: Vec3, hit_radius: f32) -> Vec3 {
1662        let (direction, distance) = collider.collision(tail, hit_radius);
1663        if distance < 0.0 {
1664            tail - direction * distance
1665        } else {
1666            tail
1667        }
1668    }
1669
1670    #[test]
1671    fn outside_and_inside_spheres_restrict_opposite_domains() {
1672        let outside = WorldCollider::Sphere {
1673            center: Vec3::ZERO,
1674            radius: 1.0,
1675            inside: false,
1676        };
1677        let inside = WorldCollider::Sphere {
1678            center: Vec3::ZERO,
1679            radius: 1.0,
1680            inside: true,
1681        };
1682
1683        assert!(resolve_collision(&outside, Vec3::X * 0.5, 0.1).distance(Vec3::X * 1.1) < 1e-5);
1684        assert!(resolve_collision(&inside, Vec3::X * 1.5, 0.1).distance(Vec3::X * 0.9) < 1e-5);
1685    }
1686
1687    #[test]
1688    fn outside_and_inside_capsules_restrict_opposite_domains() {
1689        let outside = WorldCollider::Capsule {
1690            head: Vec3::ZERO,
1691            tail: Vec3::Y,
1692            radius: 1.0,
1693            inside: false,
1694        };
1695        let inside = WorldCollider::Capsule {
1696            head: Vec3::ZERO,
1697            tail: Vec3::Y,
1698            radius: 1.0,
1699            inside: true,
1700        };
1701        let point = Vec3::new(0.5, 0.5, 0.0);
1702
1703        assert!(resolve_collision(&outside, point, 0.1).distance(Vec3::new(1.1, 0.5, 0.0)) < 1e-5);
1704        assert!(
1705            resolve_collision(&inside, Vec3::new(1.5, 0.5, 0.0), 0.1)
1706                .distance(Vec3::new(0.9, 0.5, 0.0))
1707                < 1e-5
1708        );
1709    }
1710
1711    #[test]
1712    fn plane_keeps_the_joint_sphere_in_the_positive_half_space() {
1713        let plane = WorldCollider::Plane {
1714            offset: Vec3::ZERO,
1715            normal: Vec3::Y,
1716        };
1717
1718        assert!(
1719            resolve_collision(&plane, Vec3::new(0.0, -0.5, 0.0), 0.1)
1720                .distance(Vec3::new(0.0, 0.1, 0.0))
1721                < 1e-5
1722        );
1723    }
1724
1725    #[test]
1726    fn world_collider_transforms_radius_and_plane_normal() {
1727        let transform = Mat4::from_scale_rotation_translation(
1728            Vec3::splat(2.0),
1729            Quat::from_rotation_z(std::f32::consts::FRAC_PI_2),
1730            Vec3::new(3.0, 4.0, 5.0),
1731        );
1732        let sphere = WorldCollider::from_local(
1733            &ColliderShape::Sphere {
1734                offset: Vec3::X,
1735                radius: 0.5,
1736                inside: false,
1737            },
1738            transform,
1739        );
1740        let plane = WorldCollider::from_local(
1741            &ColliderShape::Plane {
1742                offset: Vec3::X,
1743                normal: Vec3::X,
1744            },
1745            transform,
1746        );
1747
1748        match sphere {
1749            WorldCollider::Sphere { center, radius, .. } => {
1750                assert!(center.distance(Vec3::new(3.0, 6.0, 5.0)) < 1e-5);
1751                assert!((radius - 1.0).abs() < 1e-5);
1752            }
1753            other => panic!("expected a sphere, got {other:?}"),
1754        }
1755        match plane {
1756            WorldCollider::Plane { offset, normal } => {
1757                assert!(offset.distance(Vec3::new(3.0, 6.0, 5.0)) < 1e-5);
1758                assert!(normal.distance(Vec3::Y) < 1e-5);
1759            }
1760            other => panic!("expected a plane, got {other:?}"),
1761        }
1762    }
1763}