Skip to main content

re_core/
anim.rs

1//! Runtime pose evaluation on top of the clip data (`animation` +
2//! `skeleton`): sampling a clip into a joint pose, blending poses,
3//! override layers with joint masks, and CCD inverse kinematics.
4//!
5//! Determinism contract (same doctrine as the other CPU cores): fixed-step
6//! time, pure `glam` arithmetic, no randomness. Keyframe interpolation keeps
7//! using `KeyValue::lerp` (slerp for rotations); pose *blends* use
8//! shortest-arc normalized lerp, and the IK builds its align rotations with
9//! `Quat::from_rotation_arc` (square roots and cross products only — no
10//! transcendental at runtime). Evaluation stays a pure function of
11//! (skeleton, clip library, animator state) — the precondition for a
12//! scrubbable editor timeline and for offline rendering.
13
14use std::collections::BTreeMap;
15
16use glam::{Mat4, Quat, Vec3};
17
18use crate::animation::{Animation, ChannelPath, KeyValue, Space, Target};
19use crate::id::AnimationId;
20use crate::skeleton::Skeleton;
21use crate::transform::Transform;
22
23/// A full local pose of a skeleton: one `Transform` per joint, index-aligned
24/// with `Skeleton::joints`.
25#[derive(Clone, Debug, PartialEq)]
26pub struct Pose {
27    pub local: Vec<Transform>,
28}
29
30impl Pose {
31    /// The bind pose straight from the skeleton.
32    pub fn bind(skel: &Skeleton) -> Self {
33        Self {
34            local: skel.joints.iter().map(|j| j.local).collect(),
35        }
36    }
37
38    pub fn len(&self) -> usize {
39        self.local.len()
40    }
41
42    pub fn is_empty(&self) -> bool {
43        self.local.is_empty()
44    }
45
46    pub fn joint(&self, i: usize) -> Option<Transform> {
47        self.local.get(i).copied()
48    }
49
50    /// Global transform per joint under this pose. Same composition as
51    /// `Skeleton::global_transform` (parent-before-child joint order is a
52    /// standing invariant of `add_joint`), but pose-driven and iterative.
53    pub fn globals(&self, skel: &Skeleton) -> Vec<Transform> {
54        let n = self.local.len().min(skel.joints.len());
55        let mut g: Vec<Transform> = Vec::with_capacity(n);
56        for i in 0..n {
57            g.push(match skel.joints[i].parent {
58                Some(p) if p < n => g[p].then(&self.local[i]),
59                _ => self.local[i],
60            });
61        }
62        g
63    }
64
65    /// Write every `Target::Joint` channel of `anim` (sampled at `t`, loop
66    /// wrapped) into the pose, honoring each channel's `Space`.
67    /// `Target::Node` channels belong to scene evaluation and are skipped.
68    pub fn apply_clip(&mut self, skel: &Skeleton, anim: &Animation, t: f32) {
69        let t = wrap_time(anim, t);
70        for ch in &anim.channels {
71            let Target::Joint(name) = &ch.target else {
72                continue;
73            };
74            let Some(i) = skel.joint_by_name(name) else {
75                continue;
76            };
77            let Some(slot) = self.local.get_mut(i) else {
78                continue;
79            };
80            let Some(v) = ch.sample(t) else {
81                continue;
82            };
83            let bind = skel.joints[i].local;
84            *slot = apply_component(*slot, bind, ch.space, ch.path, v);
85        }
86    }
87
88    /// Blend toward `other` in place: `w = 0` keeps everything, `w = 1`
89    /// takes `other` wholesale.
90    pub fn blend_toward(&mut self, other: &Pose, w: f32) {
91        let n = self.local.len().min(other.local.len());
92        for i in 0..n {
93            self.local[i] = blend_transform(self.local[i], other.local[i], w);
94        }
95    }
96}
97
98/// Blend two poses: `w = 0` keeps `a`, `w = 1` takes `b`.
99pub fn blend(a: &Pose, b: &Pose, w: f32) -> Pose {
100    let n = a.local.len().min(b.local.len());
101    Pose {
102        local: (0..n)
103            .map(|i| blend_transform(a.local[i], b.local[i], w))
104            .collect(),
105    }
106}
107
108/// Per-component linear blend with shortest-arc normalized quaternion lerp.
109fn blend_transform(a: Transform, b: Transform, w: f32) -> Transform {
110    let lerp3 = |x: [f32; 3], y: [f32; 3]| {
111        [
112            x[0] + (y[0] - x[0]) * w,
113            x[1] + (y[1] - x[1]) * w,
114            x[2] + (y[2] - x[2]) * w,
115        ]
116    };
117    let qa = a.rotation_quat();
118    let mut qb = b.rotation_quat();
119    if qa.dot(qb) < 0.0 {
120        // The double cover must not take the long way round.
121        qb = -qb;
122    }
123    let m = qa.lerp(qb, w);
124    let q = if m.length_squared() > 0.0 {
125        m.normalize()
126    } else {
127        qb
128    };
129    Transform {
130        translation: lerp3(a.translation, b.translation),
131        rotation: q.to_array(),
132        scale: lerp3(a.scale, b.scale),
133    }
134}
135
136/// Which joints a layer is allowed to drive.
137#[derive(Clone, Debug, Default, PartialEq)]
138pub enum LayerMask {
139    /// Every joint of the skeleton.
140    #[default]
141    All,
142    /// Only the listed joint indices (e.g. the upper body for an "aim").
143    Joints(Vec<usize>),
144}
145
146/// An override layer above the base animation. `weight = 0` is inert,
147/// `weight = 1` lets the layer's clip drive its masked joints wholesale.
148#[derive(Clone, Debug, PartialEq)]
149pub struct Layer {
150    pub clip: AnimationId,
151    /// Local playhead; `step` advances it by `speed * dt`.
152    pub t: f32,
153    pub speed: f32,
154    pub weight: f32,
155    pub mask: LayerMask,
156}
157
158impl Layer {
159    pub fn new(clip: AnimationId) -> Self {
160        Self {
161            clip,
162            t: 0.0,
163            speed: 1.0,
164            weight: 1.0,
165            mask: LayerMask::All,
166        }
167    }
168
169    pub fn step(&mut self, dt: f32) {
170        self.t += self.speed * dt;
171    }
172
173    fn drives(&self, joint: usize) -> bool {
174        match &self.mask {
175            LayerMask::All => true,
176            LayerMask::Joints(v) => v.contains(&joint),
177        }
178    }
179}
180
181impl Pose {
182    /// Blend every masked joint toward the layer's clip pose by `weight`.
183    /// A missing clip or zero weight leaves the pose untouched.
184    pub fn apply_layer(
185        &mut self,
186        skel: &Skeleton,
187        animations: &BTreeMap<AnimationId, Animation>,
188        layer: &Layer,
189    ) {
190        let w = layer.weight.clamp(0.0, 1.0);
191        if w <= 0.0 {
192            return;
193        }
194        let Some(anim) = animations.get(&layer.clip) else {
195            return;
196        };
197        let mut target = Pose::bind(skel);
198        target.apply_clip(skel, anim, layer.t);
199        for (i, slot) in self.local.iter_mut().enumerate() {
200            if w >= 1.0 && layer.drives(i) {
201                *slot = target.local[i];
202            } else if layer.drives(i) {
203                *slot = blend_transform(*slot, target.local[i], w);
204            }
205        }
206    }
207
208    /// Cyclic coordinate descent toward `target`, pulling the last joint of
209    /// `chain` (a consecutive parent→child run) along. Returns the final tip
210    /// distance. `iters` bounds the work; `tol` stops early once close
211    /// enough. Invalid chains do nothing and report `INFINITY`.
212    ///
213    /// Each joint move is one world-space align rotation (arc quat from the
214    /// pivot→tip and pivot→target directions, no `acos`); the push back into
215    /// the local slot goes through matrix composition, so joint scales and
216    /// parent chains stay exact.
217    pub fn ik_ccd(
218        &mut self,
219        skel: &Skeleton,
220        chain: &[usize],
221        target: Vec3,
222        iters: u32,
223        tol: f32,
224    ) -> f32 {
225        if chain.len() < 2 || chain.iter().any(|&j| j >= self.local.len()) {
226            return f32::INFINITY;
227        }
228        for pair in chain.windows(2) {
229            if skel.joints[pair[1]].parent != Some(pair[0]) {
230                return f32::INFINITY;
231            }
232        }
233        let tip = *chain.last().expect("chain checked non-empty");
234        let mut dist = self.tip_distance(skel, tip, target);
235        for _ in 0..iters {
236            if dist <= tol {
237                break;
238            }
239            // From the joint in front of the tip up to the chain root:
240            // rotating a joint moves the tip, rotating the tip itself does not.
241            for k in (0..chain.len() - 1).rev() {
242                let j = chain[k];
243                let g = self.globals(skel);
244                let pivot = Vec3::from_array(g[j].translation);
245                let to_tip = Vec3::from_array(g[tip].translation) - pivot;
246                let to_tgt = target - pivot;
247                let lt = to_tip.length();
248                let lq = to_tgt.length();
249                if lt < 1e-6 || lq < 1e-6 {
250                    continue;
251                }
252                let q = Quat::from_rotation_arc(to_tip / lt, to_tgt / lq);
253                // Rotate the joint's whole subtree around the joint itself:
254                // T(pivot) · R(q) · T(−pivot) · global — without the pivot
255                // sandwich the chain would spin about the world origin.
256                let new_global = Mat4::from_translation(pivot)
257                    * Mat4::from_quat(q)
258                    * Mat4::from_translation(-pivot)
259                    * g[j].to_mat4();
260                let new_local = match skel.joints[j].parent {
261                    Some(p) if p < g.len() => g[p].to_mat4().inverse() * new_global,
262                    None => new_global,
263                    Some(_) => continue,
264                };
265                // Singular parent or NaN garbage: `from_mat4` refuses and
266                // the joint simply keeps its current rotation.
267                if let Some(t) = Transform::from_mat4(&new_local) {
268                    self.local[j] = t;
269                }
270            }
271            dist = self.tip_distance(skel, tip, target);
272        }
273        dist
274    }
275
276    fn tip_distance(&self, skel: &Skeleton, tip: usize, target: Vec3) -> f32 {
277        let g = self.globals(skel);
278        match g.get(tip) {
279            Some(t) => (target - Vec3::from_array(t.translation)).length(),
280            None => f32::INFINITY,
281        }
282    }
283}
284
285/// Loop-wrap a playhead for a looping clip (negative times wrap forward).
286fn wrap_time(anim: &Animation, t: f32) -> f32 {
287    let d = anim.duration();
288    if anim.looping && d > 0.0 {
289        let m = t % d;
290        if m < 0.0 {
291            m + d
292        } else {
293            m
294        }
295    } else {
296        t
297    }
298}
299
300/// Patch one TRS component from a sampled key onto the joint's local
301/// transform. `RelativeToBind` mirrors the exporter's bake exactly: the
302/// delta rides on the bind transform (`bind * delta`), only the animated
303/// component is read back.
304fn apply_component(
305    mut local: Transform,
306    bind: Transform,
307    space: Space,
308    path: ChannelPath,
309    v: KeyValue,
310) -> Transform {
311    match (space, path, v) {
312        (Space::Absolute, ChannelPath::Translation, KeyValue::Vec3(x)) => {
313            local.translation = x;
314        }
315        (Space::Absolute, ChannelPath::Rotation, KeyValue::Quat(q)) => {
316            local.rotation = q;
317        }
318        (Space::Absolute, ChannelPath::Scale, KeyValue::Vec3(s)) => {
319            local.scale = s;
320        }
321        (Space::RelativeToBind, path, v) => {
322            let mut delta = Transform::default();
323            match (path, v) {
324                (ChannelPath::Translation, KeyValue::Vec3(x)) => delta.translation = x,
325                (ChannelPath::Rotation, KeyValue::Quat(q)) => delta.rotation = q,
326                (ChannelPath::Scale, KeyValue::Vec3(s)) => delta.scale = s,
327                _ => return local,
328            }
329            let abs = bind.then(&delta);
330            match path {
331                ChannelPath::Translation => local.translation = abs.translation,
332                ChannelPath::Rotation => local.rotation = abs.rotation,
333                ChannelPath::Scale => local.scale = abs.scale,
334            }
335        }
336        // Key type does not fit the path (broken import): leave the joint.
337        _ => {}
338    }
339    local
340}
341
342/// Single-track playback with crossfades plus a stack of override layers.
343/// `step` is the fixed-timestep door (the physics doctrine): drive it with a
344/// constant `dt` for replayable results. Switching to the *same* clip is a
345/// deliberate no-op — restarts belong to the caller (sequencer).
346#[derive(Clone, Debug, PartialEq)]
347pub struct Animator {
348    pub clip: AnimationId,
349    /// Base playhead; `step` advances it by `speed * dt`.
350    pub t: f32,
351    pub speed: f32,
352    /// Override layers, applied bottom to top.
353    pub layers: Vec<Layer>,
354    /// Running crossfade toward `clip`; `None` = plain playback.
355    fade: Option<Fade>,
356}
357
358#[derive(Clone, Copy, Debug, PartialEq)]
359struct Fade {
360    from: AnimationId,
361    /// The old clip keeps playing out its own run during the fade.
362    t_from: f32,
363    speed_from: f32,
364    left: f32,
365    total: f32,
366}
367
368impl Animator {
369    pub fn new(clip: AnimationId) -> Self {
370        Self {
371            clip,
372            t: 0.0,
373            speed: 1.0,
374            layers: Vec::new(),
375            fade: None,
376        }
377    }
378
379    pub fn fading(&self) -> bool {
380        self.fade.is_some()
381    }
382
383    /// Switch clips. `fade > 0` crossfades from the current pose over
384    /// `fade` seconds (the new clip starts at `t = 0`); `fade = 0` cuts.
385    /// If the old or new clip is missing from the library the fade is
386    /// skipped — a plain cut still lands on the new id.
387    pub fn play(&mut self, clip: AnimationId, fade: f32) {
388        if clip == self.clip {
389            return;
390        }
391        self.fade = if fade > 0.0 {
392            Some(Fade {
393                from: self.clip,
394                t_from: self.t,
395                speed_from: self.speed,
396                left: fade,
397                total: fade,
398            })
399        } else {
400            None
401        };
402        self.clip = clip;
403        self.t = 0.0;
404    }
405
406    /// Advance every playhead by one fixed step (`dt` seconds).
407    pub fn step(&mut self, dt: f32) {
408        self.t += self.speed * dt;
409        if let Some(f) = &mut self.fade {
410            f.t_from += f.speed_from * dt;
411            f.left = (f.left - dt).max(0.0);
412            if f.left == 0.0 {
413                self.fade = None;
414            }
415        }
416        for l in &mut self.layers {
417            l.step(dt);
418        }
419    }
420
421    /// Evaluate the full stack as a pure function: bind pose, base clip
422    /// (crossfade-aware), then every layer bottom to top. Missing clip ids
423    /// degrade quietly to the layers below them.
424    pub fn pose(&self, skel: &Skeleton, animations: &BTreeMap<AnimationId, Animation>) -> Pose {
425        let mut base = Pose::bind(skel);
426        if let Some(f) = &self.fade {
427            if let Some(old) = animations.get(&f.from) {
428                base.apply_clip(skel, old, f.t_from);
429            }
430        }
431        let mut next = Pose::bind(skel);
432        if let Some(cur) = animations.get(&self.clip) {
433            next.apply_clip(skel, cur, self.t);
434        }
435        let mut p = match &self.fade {
436            Some(f) => blend(&base, &next, 1.0 - f.left / f.total),
437            None => next,
438        };
439        for l in &self.layers {
440            p.apply_layer(skel, animations, l);
441        }
442        p
443    }
444}
445
446// ── Unit gates ─────────────────────────────────────────────────────────
447
448#[cfg(test)]
449mod tests {
450    use super::*;
451    use crate::animation::{Animation, ChannelPath, KeyValue, Space, Target};
452    use glam::Vec3;
453
454    fn tr(x: f32, y: f32, z: f32) -> Transform {
455        Transform::from_parts(Vec3::new(x, y, z), Default::default(), Vec3::ONE)
456    }
457
458    fn clip_keys(
459        joint: &str,
460        path: ChannelPath,
461        space: Space,
462        looping: bool,
463        keys: &[(f32, KeyValue)],
464    ) -> Animation {
465        let mut a = Animation::new("clip");
466        a.looping = looping;
467        {
468            let ch = a.get_or_create(Target::Joint(joint.to_string()), path);
469            ch.space = space;
470            for (t, v) in keys {
471                ch.set_key(*t, *v);
472            }
473        }
474        a
475    }
476
477    fn two_bone_arm() -> Skeleton {
478        let mut sk = Skeleton::new("arm");
479        let sh = sk.add_joint("Shoulder", None, tr(0.0, 0.0, 0.0));
480        let el = sk.add_joint("Elbow", Some(sh), tr(0.0, -1.0, 0.0));
481        sk.add_joint("Hand", Some(el), tr(0.0, -1.0, 0.0));
482        sk
483    }
484
485    #[test]
486    fn clip_writes_absolute_and_relative_channels() {
487        let mut sk = Skeleton::new("rig");
488        sk.add_joint("J", None, tr(1.0, 0.0, 0.0));
489        // Absolute: the value *is* the local component; linear in between.
490        let a = clip_keys(
491            "J",
492            ChannelPath::Translation,
493            Space::Absolute,
494            false,
495            &[
496                (0.0, KeyValue::Vec3([0.0, 1.0, 0.0])),
497                (1.0, KeyValue::Vec3([0.0, 2.0, 0.0])),
498            ],
499        );
500        let mut p = Pose::bind(&sk);
501        p.apply_clip(&sk, &a, 0.5);
502        assert_eq!(p.local[0].translation, [0.0, 1.5, 0.0]);
503        p.apply_clip(&sk, &a, 5.0); // clamps at the last key
504        assert_eq!(p.local[0].translation, [0.0, 2.0, 0.0]);
505        // RelativeToBind: `bind * delta`, mirroring the export bake.
506        let r = clip_keys(
507            "J",
508            ChannelPath::Translation,
509            Space::RelativeToBind,
510            false,
511            &[(0.0, KeyValue::Vec3([0.0, 1.0, 0.0]))],
512        );
513        let mut p = Pose::bind(&sk);
514        p.apply_clip(&sk, &r, 0.0);
515        assert_eq!(p.local[0].translation, [1.0, 1.0, 0.0]);
516        // Loop wrap: t = 1.25 reads the same as t = 0.25.
517        let l = clip_keys(
518            "J",
519            ChannelPath::Translation,
520            Space::Absolute,
521            true,
522            &[
523                (0.0, KeyValue::Vec3([0.0, 0.0, 0.0])),
524                (1.0, KeyValue::Vec3([0.0, 2.0, 0.0])),
525            ],
526        );
527        let mut p1 = Pose::bind(&sk);
528        let mut p2 = Pose::bind(&sk);
529        p1.apply_clip(&sk, &l, 1.25);
530        p2.apply_clip(&sk, &l, 0.25);
531        assert_eq!(p1, p2);
532        // A node-targeted channel belongs to scene evaluation: untouched.
533        let mut n = Animation::new("nodeclip");
534        n.get_or_create(Target::Node(crate::id::NodeId(7)), ChannelPath::Translation)
535            .set_key(0.0, KeyValue::Vec3([9.0, 9.0, 9.0]));
536        let mut p = Pose::bind(&sk);
537        p.apply_clip(&sk, &n, 0.0);
538        assert_eq!(p, Pose::bind(&sk));
539    }
540
541    #[test]
542    fn blend_hits_endpoints_and_midpoint() {
543        let mut sk = Skeleton::new("rig");
544        sk.add_joint("J", None, tr(0.0, 0.0, 0.0));
545        let a = Pose {
546            local: vec![Transform {
547                translation: [0.0, 0.0, 0.0],
548                rotation: Quat::IDENTITY.to_array(),
549                scale: [1.0, 1.0, 1.0],
550            }],
551        };
552        let rot = Quat::from_rotation_z(std::f32::consts::FRAC_PI_2);
553        let b = Pose {
554            local: vec![Transform {
555                translation: [2.0, 0.0, 0.0],
556                rotation: rot.to_array(),
557                scale: [1.0, 1.0, 1.0],
558            }],
559        };
560        // Endpoints: translation exact, rotation same arc (normalize may
561        // cost the last ulp, so compare by dot, not bits).
562        let e0 = blend(&a, &b, 0.0);
563        assert_eq!(e0.local[0].translation, a.local[0].translation);
564        assert!((e0.local[0].rotation_quat().dot(Quat::IDENTITY).abs() - 1.0).abs() < 1e-6);
565        let e1 = blend(&a, &b, 1.0);
566        assert_eq!(e1.local[0].translation, b.local[0].translation);
567        assert!((e1.local[0].rotation_quat().dot(rot).abs() - 1.0).abs() < 1e-6);
568        let m = blend(&a, &b, 0.5);
569        assert_eq!(m.local[0].translation, [1.0, 0.0, 0.0]);
570        let qm = m.local[0].rotation_quat();
571        let want = Quat::from_rotation_z(std::f32::consts::FRAC_PI_4);
572        assert!(
573            (qm.dot(want).abs() - 1.0).abs() < 1e-6,
574            "nlerp half: {qm:?} vs {want:?}"
575        );
576        assert!((qm.length() - 1.0).abs() < 1e-6);
577        // The double cover must not take the long way: negating b's quat
578        // represents the same rotation and must blend the same.
579        let b_neg = Pose {
580            local: vec![Transform {
581                rotation: (-rot).to_array(),
582                ..b.local[0]
583            }],
584        };
585        let m2 = blend(&a, &b_neg, 0.5);
586        let q2 = m2.local[0].rotation_quat();
587        assert!((q2.dot(want).abs() - 1.0).abs() < 1e-6, "sign flip: {q2:?}");
588        // blend_toward matches blend.
589        let mut p = a.clone();
590        p.blend_toward(&b, 0.5);
591        assert_eq!(p, m);
592    }
593
594    #[test]
595    fn layer_mask_only_drives_marked_joints() {
596        let mut sk = Skeleton::new("rig");
597        sk.add_joint("A", None, tr(0.0, 0.0, 0.0));
598        sk.add_joint("B", None, tr(0.0, 0.0, 0.0));
599        let base_clip = clip_keys(
600            "A",
601            ChannelPath::Translation,
602            Space::Absolute,
603            false,
604            &[(0.0, KeyValue::Vec3([1.0, 0.0, 0.0]))],
605        );
606        let layer_clip = clip_keys(
607            "A",
608            ChannelPath::Translation,
609            Space::Absolute,
610            false,
611            &[(0.0, KeyValue::Vec3([0.0, 1.0, 0.0]))],
612        );
613        let mut lib: BTreeMap<AnimationId, Animation> = BTreeMap::new();
614        lib.insert(AnimationId(1), base_clip);
615        lib.insert(AnimationId(2), layer_clip.clone());
616        lib.insert(
617            AnimationId(3),
618            clip_keys(
619                "B",
620                ChannelPath::Translation,
621                Space::Absolute,
622                false,
623                &[(0.0, KeyValue::Vec3([0.0, 0.0, 7.0]))],
624            ),
625        );
626        let mut p = Pose::bind(&sk);
627        p.apply_clip(&sk, lib.get(&AnimationId(1)).unwrap(), 0.0);
628        // Full weight, masked to joint 0: joint A jumps, joint B stays at bind.
629        let mut l = Layer::new(AnimationId(2));
630        l.mask = LayerMask::Joints(vec![0]);
631        p.apply_layer(&sk, &lib, &l);
632        assert_eq!(p.local[0].translation, [0.0, 1.0, 0.0]);
633        assert_eq!(p.local[1].translation, [0.0, 0.0, 0.0]);
634        // Half weight blends the masked joint only.
635        let mut p2 = Pose::bind(&sk);
636        p2.apply_clip(&sk, lib.get(&AnimationId(1)).unwrap(), 0.0);
637        l.weight = 0.5;
638        p2.apply_layer(&sk, &lib, &l);
639        assert_eq!(p2.local[0].translation, [0.5, 0.5, 0.0]);
640        assert_eq!(p2.local[1].translation, [0.0, 0.0, 0.0]);
641        // Inert and missing layers change nothing.
642        let mut p3 = p.clone();
643        let mut zero = Layer::new(AnimationId(3));
644        zero.weight = 0.0;
645        p3.apply_layer(&sk, &lib, &zero);
646        assert_eq!(p3, p);
647        let ghost = Layer::new(AnimationId(99));
648        p3.apply_layer(&sk, &lib, &ghost);
649        assert_eq!(p3, p);
650    }
651
652    #[test]
653    fn ccd_pulls_tip_to_target() {
654        let sk = two_bone_arm();
655        let bind = Pose::bind(&sk);
656        // Reachable target: front-right of the chain. CCD converges linearly
657        // and its fixed point keeps a small tip-radius residual (pure align
658        // rotations cannot change the tip's radius about the chain root) —
659        // 2e-3 on unit bones is the honest gate.
660        let mut p = bind.clone();
661        let d = p.ik_ccd(&sk, &[0, 1, 2], Vec3::new(0.9, -1.4, 0.0), 64, 1e-3);
662        assert!(d <= 2e-3, "tip distance {d}");
663        let g = p.globals(&sk);
664        // The elbow never leaves its radius around the shoulder.
665        let r = (Vec3::from_array(g[1].translation) - Vec3::from_array(g[0].translation)).length();
666        assert!((r - 1.0).abs() < 1e-3, "bone stretched: r = {r}");
667        // Unreachable target straight below: the chain is already fully
668        // extended toward it, so the honest outcome is "stay at reach" —
669        // tip parked at [0,-2,0], distance 8 to the target.
670        let mut p = bind.clone();
671        let d = p.ik_ccd(&sk, &[0, 1, 2], Vec3::new(0.0, -10.0, 0.0), 40, 1e-3);
672        assert!((d - 8.0).abs() < 0.05, "reach clamp: {d}");
673        let g = p.globals(&sk);
674        let tip = Vec3::from_array(g[2].translation);
675        assert!(
676            (tip - Vec3::new(0.0, -2.0, 0.0)).length() < 1e-3,
677            "chain bent off reach line: {tip:?}"
678        );
679        // Side-ways unreachable target: must straighten to full reach.
680        let mut p = bind.clone();
681        let d = p.ik_ccd(&sk, &[0, 1, 2], Vec3::new(-9.0, 0.0, 0.0), 64, 1e-3);
682        let g = p.globals(&sk);
683        let tip = Vec3::from_array(g[2].translation);
684        assert!((d - (9.0 - 2.0)).abs() < 0.05, "side straighten: {d}");
685        assert!((tip.length() - 2.0).abs() < 0.05, "side reach: {tip:?}");
686        // Degenerate: on-top-of-pivot target must not NaN the rig.
687        let mut p = bind.clone();
688        p.ik_ccd(&sk, &[0, 1, 2], Vec3::new(0.0, 0.0, 0.0), 4, 1e-3);
689        assert!(p
690            .local
691            .iter()
692            .all(|t| t.translation.iter().all(|v| v.is_finite())));
693        // Broken chain (not consecutive) reports and does nothing.
694        let mut p = bind.clone();
695        assert_eq!(p.ik_ccd(&sk, &[0, 2], Vec3::X, 4, 1e-3), f32::INFINITY);
696        assert_eq!(p, bind);
697    }
698
699    #[test]
700    fn crossfade_ends_on_new_clip_and_replays_bitwise() {
701        let mut sk = Skeleton::new("rig");
702        sk.add_joint("J", None, tr(0.0, 0.0, 0.0));
703        let clip_a = clip_keys(
704            "J",
705            ChannelPath::Translation,
706            Space::Absolute,
707            true,
708            &[
709                (0.0, KeyValue::Vec3([0.0, 0.0, 0.0])),
710                (1.0, KeyValue::Vec3([2.0, 0.0, 0.0])),
711            ],
712        );
713        let clip_b = clip_keys(
714            "J",
715            ChannelPath::Translation,
716            Space::Absolute,
717            true,
718            &[
719                (0.0, KeyValue::Vec3([0.0, 0.0, 0.0])),
720                (1.0, KeyValue::Vec3([0.0, 2.0, 0.0])),
721            ],
722        );
723        let mut lib: BTreeMap<AnimationId, Animation> = BTreeMap::new();
724        lib.insert(AnimationId(1), clip_a);
725        lib.insert(AnimationId(2), clip_b);
726
727        let run = || {
728            let mut an = Animator::new(AnimationId(1));
729            let mut seen = Vec::new();
730            let dt = 1.0 / 60.0;
731            for _ in 0..30 {
732                an.step(dt);
733                seen.push(an.pose(&sk, &lib).local[0].translation);
734            }
735            an.play(AnimationId(2), 0.5);
736            assert!(an.fading());
737            for i in 0..40 {
738                an.step(dt);
739                let p = an.pose(&sk, &lib).local[0].translation;
740                seen.push(p);
741                if i == 10 {
742                    // Mid fade: both rails contribute.
743                    assert!(p[0] > 0.0 && p[1] > 0.0, "mid-fade one-sided: {p:?}");
744                }
745            }
746            assert!(!an.fading());
747            (seen, an)
748        };
749        let (run1, an) = run();
750        let (run2, _) = run();
751        assert_eq!(run1, run2, "same script, different bits");
752        // After the fade the pose is the plain new-clip pose, bit for bit.
753        let mut solo = Pose::bind(&sk);
754        solo.apply_clip(&sk, lib.get(&AnimationId(2)).unwrap(), an.t);
755        assert_eq!(an.pose(&sk, &lib), solo);
756    }
757
758    #[test]
759    fn bind_pose_globals_match_skeleton() {
760        let sk = Skeleton::humanoid("hum");
761        let p = Pose::bind(&sk);
762        let g = p.globals(&sk);
763        assert_eq!(g.len(), sk.joints.len());
764        for (i, got) in g.iter().enumerate() {
765            assert_eq!(*got, sk.global_transform(i), "global {i} drifts");
766        }
767    }
768}