Module retarget

Source
Expand description

Checked local-pose remapping between two real Skeletons.

Joint names and rest locals are parallel, caller-owned authoring metadata; neither changes the skeleton, animation, skin, save or replay format. Names are inspected only during preparation and are not retained. Each skeleton has 1..=MAX_ANIMATION_JOINTS joints, globally unique nonempty names of at most 4096 bytes, and parent-before-child order. Siblings may be reordered. Matched joints must have matched immediate parents (or both be roots).

The convention is local right delta, not world-space motion or IK: target_local = target_rest * inverse(source_rest) * source_local. Thus the source rest maps to the target rest; translation deltas rotate into the target rest frame and scale by target/source rest scale. Rotation deltas act after the target rest orientation. Different bone lengths and orientations are supported, but no length fitting or end-effector constraint is inferred. Parent/world transforms are evaluated later by the target skeleton. Only finite translations, valid scene quaternions and strictly positive, exactly uniform scales are supported. Reflection, nonuniform scale, zero scale and unrepresentable checked inverses/results are explicit errors. Shear has no input representation: this API accepts TRS locals only and never decomposes arbitrary matrices. Uniform local scales cannot introduce shear during hierarchy composition. Existing inverse-bind matrices are left intact and are not assumed to be inverses of these caller-supplied rest locals. Checked success is subject to f32 rounding and inverse conditioning; it is not an accuracy certificate. Translation underflow may round to zero; scale underflow to zero is rejected. An offset or source full rest inverse that cannot be represented is rejected even if a particular final pose could fit.

§Two-skeleton animation-to-skin recipe

This headless recipe constructs real skeletons with different sibling order, bone lengths and rest orientations, samples a real animation, and uses the mapped locals with the existing world/skin APIs. No renderer is required.

use ferravex_math::{Mat4, Quat};
use ferravex_play::{animation::*, animation::retarget::*, scene::*};

fn skeleton(parents: &[Option<usize>], rest: &[Transform]) -> Skeleton {
    let provisional = Skeleton::new(parents.iter().map(|&parent| Joint {
        parent, inverse_bind: IDENTITY,
    }).collect()).unwrap();
    let world = provisional.world_pose(rest).unwrap();
    Skeleton::new(parents.iter().zip(world).map(|(&parent, world)| Joint {
        parent,
        inverse_bind: Mat4::from_cols_array(&world).checked_inverse().unwrap()
            .to_cols_array(),
    }).collect()).unwrap()
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let source_rest = [Transform::default(), Transform {
        translation: [1., 0., 0.], ..Transform::default()
    }, Transform { translation: [0., 0., 1.], ..Transform::default() }];
    let target_rest = [Transform::default(), source_rest[2], Transform {
        translation: [0., 2., 0.],
        rotation: Quat::from_rotation_z(std::f32::consts::FRAC_PI_2).to_array(),
        scale: [2.; 3],
    }];
    let source = skeleton(&[None, Some(0), Some(0)], &source_rest);
    let target = skeleton(&[None, Some(0), Some(0)], &target_rest);
    let map = PreparedRetarget::try_new(&source, &["root", "arm", "marker"],
        &source_rest, &target, &["root", "marker", "arm"], &target_rest,
        MissingJointPolicy::Strict)?;
    let clip = AnimationClip::new(3, 1., LoopMode::Clamp, vec![JointTrack {
        joint: 1,
        translation: Some(Track::new(vec![
            Keyframe { time: 0., value: [1., 0., 0.] },
            Keyframe { time: 1., value: [2., 0., 0.] },
        ], Interpolation::Linear).unwrap()),
        rotation: Some(Track::new(vec![Keyframe { time: 1.,
            value: Quat::from_rotation_x(0.5).to_array() }], Interpolation::Step).unwrap()),
        scale: None,
    }], vec![]).unwrap();
    let mut sampled = [Transform::default(); 3];
    clip.sample_into(1., &source_rest, &mut sampled).unwrap();
    let mut mapped = [Transform::default(); 3];
    map.map_pose_into(&sampled, &mut mapped)?;
    assert!((mapped[2].translation[1] - 4.).abs() < 1e-5);
    let expected = Quat::from_array(target_rest[2].rotation)
        * Quat::from_rotation_x(0.5);
    assert!(Quat::from_array(mapped[2].rotation).dot(expected).abs() > 0.99999);
    let mut world = [IDENTITY; 3];
    let mut palette = [IDENTITY; 3];
    map.target().world_pose_into(&mapped, &mut world)?;
    assert!((world[2][13] - 4.).abs() < 1e-5);
    map.target().skin_palette_into(&mapped, &mut world, &mut palette)?;
    assert!(palette.iter().flatten().all(|v| v.is_finite()));
    // Feeding the rest again resets the result without any hidden history.
    map.map_pose_into(&source_rest, &mut mapped)?;
    assert_eq!(mapped, target_rest);
    map.target().skin_palette_into(&mapped, &mut world, &mut palette)?;
    for matrix in palette {
        assert!(Mat4::from_cols_array(&matrix).abs_diff_eq(Mat4::IDENTITY, 1e-5));
    }
    assert!(matches!(PreparedRetarget::try_new(&source, &["root", "arm", "arm"],
        &source_rest, &target, &["root", "marker", "arm"], &target_rest,
        MissingJointPolicy::Strict), Err(RetargetError::DuplicateName { .. })));
    assert!(matches!(PreparedRetarget::try_new(&source, &["root", "arm", "marker"],
        &source_rest, &target, &["root", "unknown", "arm"], &target_rest,
        MissingJointPolicy::Strict), Err(RetargetError::MissingJoint { .. })));
    Ok(())
}

Structs§

PreparedRetarget
Immutable prepared map tied by shared borrows to the exact two skeletons. Names are discarded; normalized rest locals and indexed offsets are owned. Skeleton mutation/replacement while borrowed is prevented by Rust. Raw pose slices carry no identity: the caller must supply source-order locals and use the target-order output with Self::target, not an unrelated same-size rig.

Enums§

MissingJointPolicy
Explicit policy for names present on only one side.
RetargetError
Indexed authoring, compatibility, capacity or numeric diagnostic.
RetargetTransformError
Unsupported local TRS or failed checked arithmetic; no decomposition occurs.
SkeletonSide
Side of the mapping containing a diagnostic’s joint index.