This class performs real-time bone retargeting between two humanoid skeletons. It pre-calculates a transformation plan and uses that plan to convert source poses to target poses frame by frame without allocations.
#nullable enable annotations
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using HumanoidRetargeter.Core.Cleanup;
using HumanoidRetargeter.Core.Mapping;
using HumanoidRetargeter.Core.Maths;
using HumanoidRetargeter.Core.Skeleton;
using HumanoidRetargeter.Core.Target;
using SkeletonModel = HumanoidRetargeter.Core.Skeleton.Skeleton;
namespace HumanoidRetargeter.Core.Solve;
using Vector3 = System.Numerics.Vector3; // s&box compat: shadow engine's global-namespace Vector3 (see Code/HumanoidRetargeter/Assembly.cs)
/// <summary>
/// Cached, in-memory humanoid pose retargeter for live pose streams. It reuses the same
/// mapping, rest normalization, canonical frames, proportion handling and root transform
/// math as <see cref="GeometricSolver"/>, without creating clips or writing files per frame.
/// </summary>
/// <remarks>
/// A runtime instance owns reusable scratch buffers and is intentionally not thread-safe.
/// Create one instance per independently evaluated character/pose stream. Construction is
/// the expensive mapping/rig-analysis boundary; <see cref="TryRetarget"/> performs no
/// hierarchy scan, mapping rebuild, file IO, or successful-path heap allocation.
/// </remarks>
[Alias( "HumanoidRetargeter.Solve.RuntimePoseRetargeter" )]
public sealed class RuntimePoseRetargeter
{
private readonly GeometricSolver.Plan _plan;
private readonly XForm[] _scratchDestination;
private readonly int[] _targetRoots;
// The target's unmapped twist and deform helper bones: left at rest while a mapped hand
// pronates, they candy-wrap the forearm skin (first-person arms gripping a rifle)
private readonly TwistBoneFollow.Follow? _limbHelpers;
/// <summary>The immutable source skeleton used to compile this retarget plan.</summary>
public SkeletonModel SourceSkeleton { get; }
/// <summary>The source role mapping used to compile this retarget plan.</summary>
public MappingResult SourceMapping { get; }
/// <summary>The target rig used to compile this retarget plan.</summary>
public TargetRig TargetRig { get; }
/// <summary>Number of local transforms required in every source pose.</summary>
public int SourceBoneCount => SourceSkeleton.Count;
/// <summary>Number of local transforms required in every destination pose.</summary>
public int TargetBoneCount => TargetRig.Skeleton.Count;
/// <summary>
/// Rotation applied to every destination pose about the target's root, turning the target from the way its own
/// bind faces to the way the source's bind faces. Identity unless the plan was compiled with
/// <c>alignFacingToSource</c>.
/// </summary>
public Quaternion FacingCorrection { get; }
/// <summary>
/// Compiles a reusable runtime solve plan.
/// </summary>
/// <param name="sourceSkeleton">Source hierarchy and rest pose, in centimeters.</param>
/// <param name="sourceMapping">Canonical humanoid roles on the source hierarchy.</param>
/// <param name="targetRig">Mapped target hierarchy.</param>
/// <param name="initialSourcePose">
/// Optional initial/reference pose for sources whose bind is non-anatomical (for example
/// the SOMA/G1 stick-style capture path). Null uses the source rest pose.
/// </param>
/// <param name="options">Existing geometric solve options; null uses compatible defaults.</param>
/// <param name="restPlacementAuthored">
/// Whether source root placement shares the source rest coordinate space. Set false for
/// absolute capture-volume streams that should be recentered like BVH input.
/// </param>
/// <param name="alignFacingToSource">
/// Turn every destination pose so the target faces the way the source does, for a target placed in the source's
/// space (a live character driven by another). Without it the target keeps the facing of its own bind, which is
/// what an animation authored for that rig wants, but a rig bound facing sideways then turns sideways.
/// </param>
public RuntimePoseRetargeter(
SkeletonModel sourceSkeleton,
MappingResult sourceMapping,
TargetRig targetRig,
IReadOnlyList<XForm>? initialSourcePose = null,
SolveOptions? options = null,
bool restPlacementAuthored = true,
bool alignFacingToSource = false)
{
SourceSkeleton = sourceSkeleton ?? throw new ArgumentNullException(nameof(sourceSkeleton));
SourceMapping = sourceMapping ?? throw new ArgumentNullException(nameof(sourceMapping));
TargetRig = targetRig ?? throw new ArgumentNullException(nameof(targetRig));
ValidateMapping(sourceSkeleton, sourceMapping);
var reference = new XForm[sourceSkeleton.Count];
if (initialSourcePose is null)
{
for (var i = 0; i < reference.Length; i++)
reference[i] = sourceSkeleton[i].RestLocal;
}
else
{
if (initialSourcePose.Count != sourceSkeleton.Count)
throw new ArgumentException(
$"Initial pose has {initialSourcePose.Count} bones but the source skeleton has {sourceSkeleton.Count}.",
nameof(initialSourcePose));
for (var i = 0; i < reference.Length; i++)
reference[i] = initialSourcePose[i];
}
var clip = new Clip("runtime_reference", 30f, false, new List<XForm[]> { reference });
var scene = new SourceScene(sourceSkeleton, new[] { clip }, unitScaleCm: 1f)
{
RestPlacementAuthored = restPlacementAuthored,
};
_plan = new GeometricSolver.Plan(scene, clip, sourceMapping, targetRig, options ?? new SolveOptions());
_scratchDestination = new XForm[targetRig.Skeleton.Count];
FacingCorrection = alignFacingToSource
? FacingBetween(sourceSkeleton, sourceMapping, targetRig)
: Quaternion.Identity;
_targetRoots = targetRig.Skeleton.Bones.Where(b => b.ParentIndex < 0).Select(b => b.Index).ToArray();
// A live pose is written bone by bone, so no constraint of the model's moves these
_limbHelpers = TwistBoneFollow.Prepare(targetRig, excluded: null);
}
/// <summary>
/// Retargets one parent-local source pose into a caller-owned parent-local destination.
/// Throws for invalid buffer sizes or non-finite/degenerate input.
/// </summary>
public void Retarget(ReadOnlySpan<XForm> sourceLocals, Span<XForm> destinationLocals)
{
if (destinationLocals.Length < TargetBoneCount)
throw new ArgumentException(
$"Destination has {destinationLocals.Length} bones but the target skeleton requires {TargetBoneCount}.",
nameof(destinationLocals));
_plan.SolveFrameInto(sourceLocals, _scratchDestination);
_limbHelpers?.Apply(_scratchDestination);
ApplyFacing(_scratchDestination);
_scratchDestination.AsSpan().CopyTo(destinationLocals);
}
/// <summary>
/// Safe runtime variant. On failure it returns false, reports an actionable diagnostic,
/// and leaves <paramref name="destinationLocals"/> unchanged.
/// </summary>
public bool TryRetarget(
ReadOnlySpan<XForm> sourceLocals,
Span<XForm> destinationLocals,
out string? error)
{
if (sourceLocals.Length != SourceBoneCount)
{
error = $"Source pose has {sourceLocals.Length} bones; expected {SourceBoneCount}.";
return false;
}
if (destinationLocals.Length < TargetBoneCount)
{
error = $"Destination pose has {destinationLocals.Length} bones; expected at least {TargetBoneCount}.";
return false;
}
try
{
_plan.SolveFrameInto(sourceLocals, _scratchDestination);
_limbHelpers?.Apply(_scratchDestination);
ApplyFacing(_scratchDestination);
_scratchDestination.AsSpan().CopyTo(destinationLocals);
error = null;
return true;
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException)
{
error = $"Runtime retarget failed: {ex.Message}";
return false;
}
}
/// <summary>
/// Builds a target rig from the library's existing automatic humanoid mapper and then
/// compiles a runtime plan. This is an additive convenience for mocap, VR and procedural
/// animation consumers; it has no dependency on any motion-generation package.
/// </summary>
public static bool TryCreateAutoMapped(
SkeletonModel sourceSkeleton,
MappingResult sourceMapping,
SkeletonModel targetSkeleton,
out RuntimePoseRetargeter? retargeter,
out string? error,
IReadOnlyList<XForm>? initialSourcePose = null,
SolveOptions? options = null,
bool alignFacingToSource = false)
{
retargeter = null;
error = null;
try
{
var targetMap = AutoMapper.Map(targetSkeleton);
if (!HasMinimumHumanoidRoles(targetMap))
{
error = "Target skeleton could not be mapped as a humanoid (hips, head, hands, and feet are required).";
return false;
}
var targetRig = TargetRig.FromSkeleton(targetSkeleton, targetMap);
retargeter = new RuntimePoseRetargeter(
sourceSkeleton, sourceMapping, targetRig, initialSourcePose, options,
alignFacingToSource: alignFacingToSource);
return true;
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException)
{
error = $"Could not create runtime retargeter: {ex.Message}";
return false;
}
}
// Turns the whole destination pose about the target's root (its children follow their parents).
private void ApplyFacing(XForm[] pose)
{
if (FacingCorrection.IsIdentity)
return;
foreach (var root in _targetRoots)
{
var bone = pose[root];
pose[root] = new XForm(
Vector3.Transform(bone.Pos, FacingCorrection),
MathQ.Normalize(FacingCorrection * bone.Rot));
}
}
// The turn about the source's up axis that brings the target's bind facing onto the source's. Only the heading
// is matched: a slight lean in either bind stays the solver's business.
private static Quaternion FacingBetween(SkeletonModel sourceSkeleton, MappingResult sourceMapping, TargetRig targetRig)
{
var source = CanonicalFrames.Build(sourceSkeleton, sourceMapping);
var target = CanonicalFrames.Build(targetRig.Skeleton, targetRig.ToMappingResult());
var up = Vector3.Normalize(source.CharacterUp);
var from = target.CharacterForward - up * Vector3.Dot(target.CharacterForward, up);
var to = source.CharacterForward - up * Vector3.Dot(source.CharacterForward, up);
if (from.LengthSquared() < 1e-8f || to.LengthSquared() < 1e-8f)
return Quaternion.Identity;
from = Vector3.Normalize(from);
to = Vector3.Normalize(to);
var angle = MathF.Atan2(Vector3.Dot(up, Vector3.Cross(from, to)), Vector3.Dot(from, to));
return MathF.Abs(angle) < 1e-5f ? Quaternion.Identity : Quaternion.CreateFromAxisAngle(up, angle);
}
private static void ValidateMapping(SkeletonModel skeleton, MappingResult mapping)
{
foreach (var (role, bone) in mapping.RoleToBone)
{
if ((uint)bone >= (uint)skeleton.Count)
throw new ArgumentException(
$"Source mapping assigns {role} to bone {bone}, outside the source skeleton (count {skeleton.Count}).",
nameof(mapping));
}
if (!mapping.RoleToBone.ContainsKey(BoneRole.Hips))
throw new ArgumentException("Source mapping must include the Hips role.", nameof(mapping));
}
private static bool HasMinimumHumanoidRoles(MappingResult mapping)
=> mapping.RoleToBone.ContainsKey(BoneRole.Hips)
&& mapping.RoleToBone.ContainsKey(BoneRole.Head)
&& mapping.RoleToBone.ContainsKey(BoneRole.HandL)
&& mapping.RoleToBone.ContainsKey(BoneRole.HandR)
&& mapping.RoleToBone.ContainsKey(BoneRole.FootL)
&& mapping.RoleToBone.ContainsKey(BoneRole.FootR);
}