Skip to content

Inverse kinematics

IK bends an avatar's clip pose to fit the world it stands in: feet planted on the host's ground, hands on a steering wheel or a guitar neck, a head that turns to look at something, and eyes that follow it. It runs inside every pose, after the clip, the crossfades, the overrides and any layers, and before skinning, so everything downstream sees the solved pose: sona_joint_world, sona_pose (palettes, CPU skinning), held props, the capsule, and every draw on every backend.

The public API is eleven functions and five structs (C reference: inverse kinematics). Each struct starts with size = sizeof(struct); the _defaults functions set it and every other field.

Quick start

/* feet on the host's ground: any physics engine, through one callback */
static int ground(void *user, const sona_avatar *a, const float from[3],
    float depth, float point[3], float normal[3]) {
  /* 1 on a hit */
  return my_physics_raycast_down(user, from, depth, point, normal);
}

sona_ik_feet feet;
sona_ik_feet_defaults(&feet);
feet.ground = SONA_IK_GROUND_CALLBACK;
feet.query = ground;
feet.user = my_world;
sona_avatar_ik_feet(avatar, &feet);

/* look at the player; the eyes follow when the head cannot */
sona_ik_look look;
sona_ik_look_defaults(&look);
look.target[0] = player.x; look.target[1] = player.y + 1.6f;
look.target[2] = player.z;
/* again each frame as the player moves */
sona_avatar_ik_look(avatar, &look);

/* both hands on a wheel */
sona_ik_target hand;
sona_ik_target_defaults(&hand);
memcpy(hand.position, wheel_left_grip, sizeof hand.position);
sona_avatar_ik_target(avatar, SONA_IK_LEFT_HAND, &hand);
memcpy(hand.position, wheel_right_grip, sizeof hand.position);
sona_avatar_ik_target(avatar, SONA_IK_RIGHT_HAND, &hand);

/* IK runs in the poses of this update */
sona_update(ctx, dt, &view, NULL);
// feet on the host's ground: any physics engine, through one callback
sona_ik_feet feet;
sona_ik_feet_defaults(&feet);
feet.ground = SONA_IK_GROUND_CALLBACK;
feet.query = [](void *user, const sona_avatar *, const float from[3],
    float depth, float point[3], float normal[3]) {
  // 1 on a hit
  return my_physics_raycast_down(user, from, depth, point, normal);
};
feet.user = my_world;
sona_avatar_ik_feet(avatar.raw(), &feet);

// look at the player; the eyes follow when the head cannot
sona_ik_look look;
sona_ik_look_defaults(&look);
look.target[0] = player[0]; look.target[1] = player[1] + 1.6f;
look.target[2] = player[2];
// again each frame as the player moves
sona_avatar_ik_look(avatar.raw(), &look);

// both hands on a wheel
sona_ik_target hand;
sona_ik_target_defaults(&hand);
std::memcpy(hand.position, wheel_left_grip, sizeof hand.position);
sona_avatar_ik_target(avatar.raw(), SONA_IK_LEFT_HAND, &hand);
std::memcpy(hand.position, wheel_right_grip, sizeof hand.position);
sona_avatar_ik_target(avatar.raw(), SONA_IK_RIGHT_HAND, &hand);

// IK runs in the poses of this update
ctx.update(dt, &view);
// feet on the host's ground: any physics engine, through one callback
var feet = SonaAvatar.IkFeetDefaults();
feet.ground = Native.SONA_IK_GROUND_CALLBACK;
avatar.SetIkFeet(feet, (user, a, from, depth, point,
    normal) => MyRaycastDown(from, depth, point, normal));

// look at the player; the eyes follow when the head cannot
var look = SonaAvatar.IkLookDefaults();
look.target[0] = player[0]; look.target[1] = player[1] + 1.6f;
look.target[2] = player[2];
// again each frame as the player moves
avatar.SetIkLook(look);

// both hands on a wheel
var hand = SonaAvatar.IkTargetDefaults();
for (int k = 0; k < 3; k++) hand.position[k] = wheelLeftGrip[k];
avatar.SetIkTarget(Native.SONA_IK_LEFT_HAND, hand);
for (int k = 0; k < 3; k++) hand.position[k] = wheelRightGrip[k];
avatar.SetIkTarget(Native.SONA_IK_RIGHT_HAND, hand);

// IK runs in the poses of this update
ctx.Update(dt, view);
// look at the player; the eyes follow when the head cannot
let mut look = ik_look_defaults();
look.target = [player[0], player[1] + 1.6, player[2]];
// again each frame as the player moves
avatar.set_ik_look(Some(&look))?;

// both hands on a wheel
let mut hand = ik_target_defaults();
hand.position = wheel_left_grip;
avatar.set_ik_target(sona_sys::SONA_IK_LEFT_HAND, Some(&hand))?;
hand.position = wheel_right_grip;
avatar.set_ik_target(sona_sys::SONA_IK_RIGHT_HAND, Some(&hand))?;

// IK runs in the poses of this update
ctx.frame()?.update(dt, Some(view))?;
# feet on the host's ground: any physics engine, through one callback
avatar.ik_feet(ground="callback", query=my_raycast_down)

# look at the player; the eyes follow when the head cannot
# again each frame as the player moves
avatar.ik_look(target=(player[0], player[1] + 1.6, player[2]))

# both hands on a wheel
avatar.ik_target("left_hand", position=wheel_left_grip)
avatar.ik_target("right_hand", position=wheel_right_grip)

# IK runs in the poses of this update
ctx.update(dt, view)

Turn anything off with a NULL struct (sona_avatar_ik_feet(a, NULL)), or everything with sona_avatar_ik_clear. An avatar with IK off is posed exactly as without IK, bit for bit.

Hand and foot targets

sona_avatar_ik_target(a, limb, &t) gives one limb a goal: SONA_IK_LEFT_HAND, _RIGHT_HAND, _LEFT_FOOT, _RIGHT_FOOT. Each limb is a two-bone chain (upper arm and forearm, thigh and shin) solved in closed form.

  • Where. A hand puts its palm at position: the point halfway from the wrist to the middle knuckle, a little into the palm, measured from each avatar's own rig, so a target on a wheel's rim is where the hand closes. SONA_IK_WRIST targets the wrist joint instead. A foot puts its ankle joint there.
  • Which space. World metres by default. SONA_IK_AVATAR_SPACE: in the avatar's own space, before its placement (a seat or a vehicle the avatar is parented to). SONA_IK_RELATIVE: in the frame of one of the avatar's joints (joint, from sona_joint_find), as the clip and the steps before this limb left it. A left hand on a guitar neck is a point fixed in PropRight, the frame the right hand holds the guitar by; hands on a two-handed prop work the same way. World and avatar-space hands are solved first, then relative ones, so a target relative to the other hand follows that hand's own solve.
  • Turn. With SONA_IK_ROTATION, rotation is the hand's (or foot's) world orientation as a unit quaternion (x, y, z, w), measured from the rest pose: the T-pose, arms straight out to the sides, palms down, the avatar facing -Z at turn 0. Without it the hand keeps the turn the clip gives it relative to the forearm.
  • Bend. The elbow or knee bends the way the clip bends it; while the limb is nearly straight, the way its hinge points. With SONA_IK_POLE, it bends towards pole (a point in the same space as position).
  • Weight. weight 0..1 blends from the clip's pose; changes ease over fade_seconds (default 0.2 s, smoothstep). Setting a target with weight 0 fades it out; NULL drops it at once.

A foot target replaces planting for that foot (a pedal, a ladder rung, a ball under the sole).

Foot planting

sona_avatar_ik_feet(a, &o) stands the feet on the ground. Three ways to give the ground:

ground What the host gives When
SONA_IK_GROUND_PLANE plane = n.x n.y n.z d (the points with dot(n, p) = d), world a floor or one slope
SONA_IK_GROUND_POINTS sona_avatar_ik_ground(a, foot, point, normal) per foot, from the host's own raycasts or contacts engines that already trace feet
SONA_IK_GROUND_CALLBACK query: a ray straight down from from, at most depth metres; return 1 with the hit point and unit normal terrain, stairs, anything

Each pose, per foot:

  1. The clip's sole points (heel and toe tips, from the rig) give how high the clip lifts the foot above its own floor. That lift is kept above the real ground under the foot, so a walk keeps its steps.
  2. The ground under the heel gives the normal. A planted foot tilts to it, up to max_tilt_deg (35); the tilt fades out as the clip lifts the foot (fully planted below 3 cm, free above 15 cm).
  3. The ground under the toes is asked too: a foot whose toes are over a higher tread (a step's riser) stands on that tread, never in it.
  4. The hips move by the lower foot's change, so the lower leg keeps its clip shape and the higher leg bends; then lower still if a planted leg could not reach. They move at most max_hips_offset (0.45 m).
  5. Each leg solves to its ankle point with the foot's tilted turn, inside the knee and ankle limits. If the ankle's range tips the sole into the ground, the foot steps up by what went in and solves again: standing on a step with the other foot a tread below can leave the raised foot on its ball, never through the tread.

Changes of ground (a new step under a swinging foot, a moving platform) ease over smoothing (0.1 s); a foot is never eased into the ground. The host places the avatar at the ground height under its root, as with no IK; IK takes it from there.

The callback runs on the posing threads, at the same time for different avatars. It must be safe to call from any thread, answer the same question the same way (for determinism), and never call back into sona. A pose asks it four times (heel and toes, per foot). Hosts that cannot answer from any thread use POINTS, filled on their own thread before sona_update.

A frozen or held pose is re-posed when the avatar's placement moves under world-space goals, or when a goal is set; a host that changes the ground under a still avatar calls sona_avatar_ik_feet again.

Look-at: an avatar that looks at the player

sona_avatar_ik_look(a, &o) turns the head towards target, such as the player's head or the camera:

  • The turn is shared: a fifth of the yaw in the chest, a third in the neck, the rest in the head; pitch mostly in the neck and head. No roll.
  • Limits are measured from the chest: max_yaw_deg (70) either side, max_up_deg (35), max_down_deg (45). A target past the yaw limit holds the head at it; past the limit by 25 degrees it turns less, and by 65 degrees (a target behind the avatar) the head is back with the clip. Nothing snaps across the back.
  • smoothing (0.15 s) eases the direction, and max_speed_deg (360 a second) caps how fast the head turns. Turning the look off eases back over the same time.
  • The eyes use the face's own look shapes when the face has them (counts[2] of sona_avatar_expression_counts 13 or more): 9 up, 10 down, 11 to its right, 12 to its left, the same shape on both eyes (that is how the face draws them). They turn once the target is more than eye_threshold_deg (10) from where the head points, stay until it is back within a threshold of 60% of that, and hold each change for a fixed 0.12 s at least. The clip's blinks, sleepy and mood eyes win over the look; a host's sona_avatar_expression wins over both.

Flags: SONA_IK_LOOK_HEAD, SONA_IK_LOOK_EYES (default both).

Limits and the body

sona_avatar_ik_limits(a, &o) (NULL: the defaults) keeps every solve inside a person's range:

Field Default What
elbow_max_deg, knee_max_deg 145, 150 the most an elbow or knee bends; a target too close is reached as far as that allows
wrist_swing_deg, wrist_twist_deg 75, 80 the hand's turn from the forearm (swing off its axis, twist about it)
ankle_swing_deg, ankle_twist_deg 45, 30 the foot's turn from the shin
soft_reach 0.97 past this fraction of a straight limb, reaching eases in, so a limb never snaps straight
body_margin 0.02 m the gap kept between the limbs and the body
hip_forward_deg, hip_back_deg 120, 25 the thigh from hanging straight down, forward and behind (together at most 180)
hip_out_deg, hip_in_deg 45, 25 the thigh out to the side, and across in front of or behind the other leg
shoulder_back_deg 45 the upper arm behind the chest, held out level; hanging down it goes some 15 degrees further
shoulder_across_deg 50 the upper arm across the chest's front

The hip and shoulder limits are measured in the hips' and the chest's own frames, so they turn with the body. Shoulders also never take the upper arm across behind the back or raised up behind the head. These are hard limits: when a target needs more, the upper bone stops at the limit, the elbow or knee bends towards the target as far as its own range allows, and the hand or foot ends short of the target (SONA_IK_HIT_SWING, with the distance in error). A clip that already holds a limb past a limit keeps it there; IK never takes it further.

Knees bend forward over the foot, never back. The body checks (off with SONA_IK_NO_BODY) keep hands out of the torso, the head and the thighs, the forearm and elbow clear of them, and each leg clear of the other: a hand target inside the chest rests on it, and a reach across the body swings the elbow round the outside. Each limb tries its preferred bend first, then bends rotated about the reach in steps up to a half turn (and finer steps round the best when it still trespasses), and takes the one with the least trespass, range violation, shortfall and change. When every bend would go into the body, the limb reaches short instead: it stops at the nearest point on the way from where the clip has the hand or foot to the target where it is clear (SONA_IK_HIT_BODY). It never goes into the body further than the clip already had it. Elbows are kept from pointing up into the body. Every solve stays a hinge: the elbow and the knee only ever bend about their own axis.

Foot locking

sona_avatar_ik_foot_lock(a, &o) holds a foot the clip plants where it landed, in the world, until the clip lifts it, so a walk does not slide when the host moves the avatar at a speed the clip's stride does not match. A foot locks when the clip has it down and no longer swinging: its ankle within 1 cm of the height it stands at with the foot flat (heel and toes down, measured from the clip as it plays; before the clip has shown a flat foot, the heel within about 2 cm of the ground), and moving forward at under half its swing's speed. Heights are in the avatar's own space, so this is the clip's intent, not the terrain's. It lets go when the clip lifts the heel past about 4.5 cm. Held from the moment the heel first touches, a foot would be held while the clip still carries it forward, and a host faster than the clip would run the leg out of reach for that later in the step. While the clip still moves a held foot forward, the hold moves with it. A held foot the leg can no longer reach is dragged after the body just enough for the leg to reach it, so it never lifts off the ground.

Pulled more than max_slide (default 0.25 m) from where the clip has it, the foot lets go. Standing (the clip not moving the foot), it eases back to the clip over release_seconds (default 0.15) and plants again there, so an avatar slid while standing shuffles after its feet. In a walk's step (the clip carrying the foot back) it keeps that distance and moves with the clip's foot until the clip lifts it, then eases back over the swing; catching up with the clip in the middle of a step would move the foot faster than not locking at all. weight blends between the clip's foot and the held one. It works with foot planting (the planted height and tilt stay; locking only fixes where along the ground) and without it. NULL turns it off. A foot target replaces locking for that foot.

The stock walk is in place: its planted feet travel back under the body at the clip's own pace, which is a little under a metre a second at speed 1 and slower for shorter legs. While the host moves the avatar no faster than that pace, a locked foot holds still for the whole contact. Faster, the body outruns the planted leg late in each contact and the foot is dragged after it, less far than an unlocked foot slides, and it stays on the ground. To keep feet still at a faster host speed, play the walk faster (sona_play_options.speed) so its pace is past the host's.

A foot lets go one frame after max_slide is passed. An avatar slid while standing drags its feet along the ground; they are not lifted.

Spine assist

sona_avatar_ik_spine(a, &o): a hand target past the arm's reach bends the spine towards it. The least turn that brings the shoulder within reach is found, held to max_bend_deg (forward and to the sides, default 35) and max_twist_deg (default 40) about the chest's up, and shared out: hips_share (default 0.2) bends at the waist, the rest half at the spine and half at the chest. The legs and feet do not move. Targets relative to a joint (a prop) do not bend the spine. A target a little past the arm's reach is met, or nearly, where without spine assist the hand stops short.

Finger curl

sona_avatar_ik_fingers(a, hand, &o) sets each finger's curl (curl[5]: thumb, index, middle, ring, little; 0 open, 1 a fist) and spread (-1 together to 1 apart) over the clip's hand, blended by weight and eased in and out over fade_seconds. A finger's three joints curl towards the palm by up to 80-90, 100 and 70 degrees (the thumb 25, 40, 55, across the palm); 0 is the rest pose's straight finger whatever the clip did. NULL eases back to the clip. A fist closes every fingertip towards the palm, one finger can stay open while the others close, and the release fades.

Eye turns

The eyes under sona_avatar_ik_look move on their own: sona_avatar_ik_eyes(a, &o) sets how. They turn towards the target at up to max_speed_deg (default 400 degrees a second) with smoothing (default 0.05 s), ahead of the head, aiming where a moving target will be lead_seconds (default 0.08) from now. SONA_IK_EYES_SACCADES makes them jump instead, as eyes do, at most every 50 ms. The face has look shapes (up, down, to either side), so what shows is the shape the eyes' turn has reached past the look's eye_threshold_deg: with a target 35 degrees to one side, the default turns in 1 frame at a frame rate of 60 Hz, a speed set to 30 degrees a second takes 23 frames, and saccades take 1. NULL puts the defaults back.

The four additions are saved in the avatar's state with their smoothing.

What the last pose did

sona_avatar_ik_status(a, &st) tells what the last pose did: which limbs ran (active), each limb's distance from its target (error, metres) and what held it back (hit: SONA_IK_HIT_REACH, _BEND, _POLE (the bend moved off the preferred one), _BODY, _ROTATION, _GROUND, _SWING (a hip or shoulder limit)), how far the hips moved, the head's yaw and pitch from the clip, and the eye shapes shown.

Determinism and threads

The solver is double maths with the core's own trig (fdlibm, as everywhere in the core), no FMA contraction and one float store per matrix element. IK state is per avatar and is touched only by the thread posing it.

Cost

Set SONA_BENCH_IK_SLOPE=<degrees> (or <degrees>,cb for the callback path) to stand sona-bench's crowd on a slope rising along +X, each avatar placed at the slope's height and planting its feet.

Measured on an RTX 4090 machine (its CPU), 1,000 avatars each in its own outfit and shape from the full corpus and catalogue, on a 10 degree slope, the median of three runs each. sona-bench --scene pose --backend none --outfits random poses every avatar every frame (no view), so this is the CPU cost of IK on every pose, CPU ms per sona_update:

Threads IK off Feet on the plane Feet through a callback
1 thread 1.98 5.26 5.22
workers (auto) 1.79 1.46 2.36

The crowd scene, which also draws, with the feet on the plane against the plain crowd:

--scene crowd --backend vk --counts 1000 ms a frame CPU ms a frame
IK off 16.15 3.48
Feet on the plane 16.21 3.45

In a real crowd most avatars are SAMPLED or QUARTER (Crowds) and pose far less than every frame; IK runs only when an avatar poses. The reach-short search runs only when every bend would take a limb into the body.

The sample

samples/c/ik_scene_vk.c (target ik_scene_vk, Vulkan, headless): eight avatars on a staircase and a 15 degree slope with planted feet, one looking at a ball that circles its head, one with both hands on a turning wheel. The SDK draws only avatars, so the sample ray-casts the stairs, the slope and the floor from the same shapes its ground callback answers from, CPU-skins the avatars (sona_pose_vertices) for a depth buffer, and composites with depth: a foot inside a tread is cut off by it. It writes four wide views, five foot close-ups with IK on and the same five with IK off, three moments of the look-at (each with a face close-up), the wheel, and two views (-limits, -limits-back) of one avatar given a foot target behind and above its hip and a wrist target straight behind its shoulder (red dots), which it reaches short inside the hip's and shoulder's range; it fails when a planted foot or a hand misses by more than 2 cm. --eye-sheet also writes the look avatar's eye shapes 0, 9, 10, 11, 12 and 13.

ik_scene_vk --cast devs-cast.json --size 1280x720 --out ik-scene

Limits

  • The shoulder (clavicle) does not lift for a reach; the spine does.
  • The eyes are the face's look shapes, so what shows moves in steps; their turn underneath is continuous.
  • The body checks are capsules round the torso, head and legs, not the avatar's clothes.

This page as Markdown · All the docs as one file (llms-full.txt)