# Clips: the stock clip library and the procedural idle

Two parts of the core pick and vary what an avatar plays:

- **The stock clip library.** All 100 stock clips, each with a name, a family, tags, the body it was
  made for and one stable id in `include/sona.h`. Find clips by name or by tag; play one and the SDK picks the
  variant made for the avatar's body.
- **The procedural idle.** Blinks, eye glances, small weight shifts and breathing, laid over whatever clip plays,
  so a standing avatar never looks frozen. Seeded and deterministic, cheap enough for a crowd, off by default.

The public API is 14 functions and 3 structs ([C reference: stock clips and the idle](../reference.md#the-stock-clip-library-and-the-procedural-idle)). Bindings: Python
(`sona.stock_clips`, `Avatar.play_stock`, `Avatar.idle`), C# (`SonaClips`, `SonaAvatar.PlayStock`, `SetIdle`) and
Rust (`sona::stock_clips_tagged`, `Avatar::play_stock`, `Avatar::set_idle`).

## Quick start

```c
/* every idle this body can play, the procedural idle on top */
uint32_t ids[64], n = sona_stock_clips_tagged(SONA_CLIP_TAG_IDLE, SONA_CLIP_TAG_COPY, body, ids, 64);
sona_idle_options idle;
sona_idle_defaults(&idle);                  /* blinks, glances, weight shifts and breathing, seed from the ctx */
sona_avatar_idle(avatar, &idle);

sona_avatar_play_stock(avatar, SONA_STOCK_WAVE, NULL, 0.3f);           /* crossfade into a wave */
sona_avatar_play_stock(avatar, sona_stock_clip_find("laugh"), NULL, 0); /* NULL opts: loops when the clip loops */
```

```cpp
// every idle this body can play, the procedural idle on top
uint32_t ids[64], n = sona_stock_clips_tagged(SONA_CLIP_TAG_IDLE, SONA_CLIP_TAG_COPY, body, ids, 64);
sona_idle_options idle;
sona_idle_defaults(&idle);                 // blinks, glances, weight shifts and breathing, seed from the ctx
sona_avatar_idle(avatar.raw(), &idle);     // sona.hpp has no wrapper: the C call on the handle

sona_avatar_play_stock(avatar.raw(), SONA_STOCK_WAVE, nullptr, 0.3f);              // crossfade into a wave
sona_avatar_play_stock(avatar.raw(), sona_stock_clip_find("laugh"), nullptr, 0);   // no options: loops when the clip loops
```

```csharp
// every idle this body can play, the procedural idle on top
var idles = SonaClips.Tagged(SonaClipTags.Idle, SonaClipTags.Copy, body);
avatar.SetIdle(SonaClips.IdleDefaults());     // blinks, glances, weight shifts and breathing, seed from the ctx

avatar.PlayStock("wave", 0.3f);               // crossfade into a wave
avatar.PlayStock("laugh");                    // no loop given: loops when the clip loops
```

```rust
// every idle this body can play, the procedural idle on top
let idles = stock_clips_tagged(sona_sys::SONA_CLIP_TAG_IDLE, sona_sys::SONA_CLIP_TAG_COPY, body);
avatar.set_idle(Some(&idle_defaults()))?;     // blinks, glances, weight shifts and breathing, seed from the ctx

if let Some(wave) = stock_clip_find("wave") {
    avatar.play_stock(wave, None, 0.3)?;      // crossfade into a wave
}
if let Some(laugh) = stock_clip_find("laugh") {
    avatar.play_stock(laugh, None, 0.0)?;     // no options: loops when the clip loops
}
```

```python
# every idle this body can play, the procedural idle on top
idles = sona.stock_clips(tags=["idle"], without=["copy"], body=body)
avatar.idle()                       # blinks, glances, weight shifts and breathing, seed from the ctx

avatar.play_stock("wave", fade=0.3)   # crossfade into a wave
avatar.play_stock("laugh")            # loop None: loops when the clip loops
```

`body` is the manifest's gender (`sona_manifest.gender`: 1 male, 2 female). `sona_avatar_play_stock` with
`SONA_STOCK_LAUGH_MALE` on a female avatar plays `laugh_female`: the call takes any member of a family and plays
the one made for the avatar.

The sample `samples/c/clip_library_vk.c` does this headless with Vulkan and writes a grid of frames:

```text
clip_library_vk --tag idle                               # one avatar cycles through the idles, idle on
clip_library_vk --names stand_0 --close --every 0.25     # the face up close: blinks, glances
clip_library_vk --mode sheet --at 0.25,0.5,0.75          # every clip held at three times
```

## On the web

The web SDK plays the same clips by the same keys. `play()` resolves once the clip is loaded and playing:

```js
import { SonaRenderer } from './sona-renderer.js';

const canvas = document.querySelector('canvas');
const sona = await SonaRenderer.create({ canvas });
const avatar = sona.add(manifestBase64, { clip: 'GenericWave' });
await avatar.ready;
for (const clip of ['Laugh', 'GenericClap', 'GenericCelebration']) {
  await avatar.play(clip);
  await new Promise((done) => setTimeout(done, 3000));
}
```
`sona.clips()` lists every key the SDK can play, with its length and whether it needs a prop.

## Ids

A clip's id is bytes 4 to 7 of its asset id, read as one big-endian number: `00400000-0007-0003-c1c8-f109a19cb2e0`
is `0x00070003`. The high half is the clip's index, the low half the body it was made for (1 male, 2 female,
3 both). The id comes from the clip itself, never from where it sits in a list, so a clip found later takes a new
number and every existing one keeps its own. `sona_stock_clip_get(id)` gives its row; `asset_id` is what
`sona_avatar_play` takes, so a host can also play the clip directly.

`sona_stock_clip_find` takes a library name (`"wave"`), an asset id in either case, or a key of the older
`sona_clip_get` table (`"GenericWave"`, `"Stand0"`). For those keys it returns the clip that `sona_avatar_play`
plays for the key, so the two agree.

## Names, families and tags

Names are lower case and unique. A family is one action across its body variants and copies: `laugh` holds
`laugh_male` and `laugh_female`. Nine families have a clip for each body (checks_hand, looks_around,
shifts_weight, angry, confused, laugh, cry, shocked, yawn); a few exist for one body only (stretch_male,
fist_raise_male, fist_pump_male, fixes_shoe_female, dance_female, hop_and_clap_female).
`sona_stock_clip_for_body(id, body)` maps between them and leaves a clip alone when it already suits the body.

| Tag | Meaning |
|---|---|
| idle | standing idles, fine to loop while nothing happens |
| emote | something to show: a wave, a clap, a spin |
| reaction | a feeling: angry, laughing, crying, shocked |
| look | the gaze goes somewhere |
| examine | checks its own clothes |
| celebrate | cheers |
| dance | dances |
| sleep | dozes |
| sit | sits |
| action | does something: swings, kicks, pushes, drives |
| jump | leaves the ground |
| float | floats in the air |
| locomotion | runs, walks, swims or steps |
| stage | enters or leaves the scene (travels about 9 to 12 m) |
| loop* | the last frame runs back into the first |
| travel* | the hips move 0.25 m or more sideways |
| male*, female* | made for that body only |
| copy* | the same motion as another clip (`same_as`) |

Bit order is part of the ABI: new tags only go at the end.

Four containers are **copies** of another clip: `sleep_alt`, `fist_pump_male_alt` and two whose root is stored in
other units (`float_up_alt`, `fist_raise_male_alt`: the hips sit 70 to 117 units up, so the avatar leaves the
frame). They are in the library because they are stock clips; filter them out with `SONA_CLIP_TAG_COPY` in `none`.

## The procedural idle

```c
sona_idle_options o;
sona_idle_defaults(&o);        /* parts SONA_IDLE_ALL, seed 0, amount 1, face_px 240 */
o.seed = 42;                   /* 0: from the ctx seed and the avatar id */
sona_avatar_idle(avatar, &o);  /* NULL turns it off */
```

```cpp
sona_idle_options o;
sona_idle_defaults(&o);              // parts SONA_IDLE_ALL, seed 0, amount 1, face_px 240
o.seed = 42;                         // 0: from the ctx seed and the avatar id
sona_avatar_idle(avatar.raw(), &o);  // nullptr turns it off; sona.hpp has no wrapper: the C call on the handle
```

```csharp
var o = SonaClips.IdleDefaults();   // parts All, seed 0, amount 1, face 240 px
o.Seed = 42;                        // 0: from the ctx seed and the avatar id
avatar.SetIdle(o);                  // null turns it off
```

```rust
let mut o = idle_defaults();       // parts SONA_IDLE_ALL, seed 0, amount 1, face_px 240
o.seed = 42;                        // 0: from the ctx seed and the avatar id
avatar.set_idle(Some(&o))?;         // None turns it off
```

```python
# parts all, amount 1, face_px 240; seed 0: from the ctx seed and the avatar id
avatar.idle(seed=42)
avatar.idle(on=False)               # turns it off
```

Four parts, each one a bit of `parts`:

| Part | What it does | Timing (set) |
|---|---|---|
| `SONA_IDLE_BLINK` | both eyes shut for a fixed 0.1 s (the face's blink shape) | one blink at a random time in an interval of 4 s, a double blink one time in five: about 0.3 a second |
| `SONA_IDLE_GLANCE` | the eyes look 6 to 16 degrees to a side and up to 6 down or 4 up; the head turns half as far (the neck takes two fifths of the turn, the head the rest) | seven 5 s spans in ten hold a glance of 0.8 to 2.2 s, eased in over 0.25 s and out over 0.35 s |
| `SONA_IDLE_SHIFT` | the weight moves to one foot: the hips slide up to 15 mm over it and that side rises 0.7 degrees; the legs lean back so the feet stay where they were and the spine leans against the hips | a new side every 7 s, mostly the other foot, moved over 1.8 s |
| `SONA_IDLE_BREATHE` | the chest lifts 0.8 degrees and the spine 0.35 about the clip's own pose, the shoulders rise 0.9 degrees and the arms keep hanging | one breath every 3.6 to 4.6 s |

`amount` (0 to 2) scales every motion. Everything is layered on the finished pose: after the clip, the crossfade,
the game's overrides and root motion. A joint a game holds with `SONA_OVERRIDE_REPLACE` takes the idle only in the
share the override leaves, so a game's look-at wins. Root motion is not changed (the idle's hip slide is taken
after the root is locked).

**Deterministic.** Each channel is a pure function of the seed and the ctx's clock (the sum of the `dt` passed to
`sona_update`), computed with the core's fdlibm trig. The same seed and the same updates give the same bytes on every
platform, serial or on workers. `sona_idle_sample` is the same function on its own, for hosts with their own skeleton,
and `sona_avatar_idle_state` reports what the last pose used.

**The face.** Blinks and glances are face shapes (eye 13 shut; 9 to 12 look up, down, in and out, which is how the stock
clips glance: the left eye looks out and the right in when the avatar looks to its left). A new face sheet costs a bake,
so they show only while the avatar is at least `face_px` tall on screen (240 by default); smaller, one more bake puts
the face back and nothing more happens. While they show, the face also follows the clip's own expressions (the stand
clips carry their own blinks), as with `sona_avatar_expression`. Each combination is baked once per look and cached; its
face texture is keyed by the shapes, so the GPU holds one texture per set and avatars that look the same share it.

**Off by default.** A ctx that never calls `sona_avatar_idle`, or turns it off again, poses byte for byte as before.

## Cost

The idle adds no draws and no passes. Per avatar it holds a small state and, per pose, works out four channels (a
few hashes and one cosine) and up to 18 small joint turns on the finished pose. An avatar whose clip moves is posed
exactly as often as without the idle (the clip's frame rate, or every frame when it is near); a still clip
(`"still"`, or one that has ended) is posed at the idle's rate of 20 a second instead of not at all, with the crowd
rules for small avatars. Blinks and glances cost face bakes only for avatars at least `face_px` tall.

The face sheet is the one texture that changes without a rebuild, so the GPU cache has to notice a re-bake. Each
re-bake bumps a counter on the avatar (`face_gen`, next to `build_version`), and the cache compares only that on the
hot path; it reads the avatar's face texture only after the counter moved. Without the idle or a live expression
the counter never moves, so the per-frame check costs what it did before the idle existed.

Measured with the crowd scene (1,000 avatars, each its own random outfit and body) on an RTX 4090 machine, the
idle on every avatar with `sona-bench --idle on`, the median of three runs each:

| 1,000 avatars | Idle off | Idle on |
|---|---|---|
| ms a frame | 16.15 | 16.16 |
| CPU ms a frame | 3.48 | 3.14 |
| GPU ms a frame | 16.13 | 16.15 |
| GPU MB | 956.1 | 964.8 |
| CPU MB | 1,249.8 | 1,310.7 |

The GPU MB with the idle on includes the face sheets of the front avatars that blink.

## The clip table


100 clips. A clip's constant is `SONA_STOCK_` and its key in capitals (`wave` is `SONA_STOCK_WAVE`); the code after the key is its id. Seconds are frames / fps. Tags marked * are worked out from the clip itself. A clip's family is its key without `_female`, `_male` or `_alt`, or the one named.

| Key and id | Body, seconds, tags | What it does |
|---|---|---|
| `stand_0` `0x00030003` | both, 5.38; idle, loop* | Stands relaxed, the default pose |
| `stand_1` `0x00040003` | both, 21.38; idle, loop* | Stands, long quiet idle |
| `stand_2` `0x00050003` | both, 16.05; idle, loop* | Stands, quiet idle |
| `clap` `0x00060003` | both, 3.38; emote, celebrate, loop* | Claps |
| `wave` `0x00070003` | both, 5.38; emote, loop* | Waves hello |
| `celebrate` `0x00080003` | both, 3.42; emote, celebrate, loop* | Cheers with both arms |
| `checks_hand_female` `0x00090002` | female, 12.05; idle, loop*, female* | Looks at her hand |
| `looks_around_female` `0x000a0002` | female, 5.05; idle, look, loop*, female* | Looks around |
| `shifts_weight_female` `0x000b0002` | female, 12.72; idle, loop*, female* | Shifts her weight |
| `fixes_shoe_female` `0x000c0002` | female, 5.05; idle, loop*, female* | Lifts a foot and fixes her shoe |
| `angry_female` `0x000d0002` | female, 5.72; reaction, loop*, female* | Angry |
| `confused_female` `0x000e0002` | female, 3.72; reaction, loop*, female* | Confused |
| `laugh_female` `0x000f0002` | female, 5.55; reaction, loop*, female* | Laughs |
| `cry_female` `0x00100002` | female, 6.05; reaction, loop*, female* | Cries |
| `shocked_female` `0x00110002` | female, 3.88; reaction, loop*, female* | Shocked |
| `yawn_female` `0x00120002` | female, 3.72; idle, reaction, loop*, female* | Yawns |
| `looks_around_male` `0x00130001` | male, 10.72; idle, look, loop*, male* | Looks around |
| `stretch_male` `0x00140001` | male, 9.52; idle, loop*, male* | Stretches |
| `shifts_weight_male` `0x00150001` | male, 12.12; idle, loop*, male* | Shifts his weight |
| `angry_male` `0x00160001` | male, 4.72; reaction, loop*, male* | Angry |
| `confused_male` `0x00170001` | male, 3.22; reaction, loop*, male* | Confused |
| `laugh_male` `0x00180001` | male, 4.55; reaction, loop*, male* | Laughs |
| `cry_male` `0x00190001` | male, 6.38; reaction, loop*, male* | Cries |
| `shocked_male` `0x001a0001` | male, 4.38; reaction, loop*, male* | Shocked |
| `yawn_male` `0x001b0001` | male, 5.52; idle, reaction, male* | Yawns |
| `look_down` `0x001c0003` | both, 5.38; look, loop* | Looks down |
| `look_left` `0x001d0003` | both, 5.38; look, loop* | Looks to its left |
| `look_center` `0x001e0003` | both, 5.38; look, loop* | Looks ahead |
| `look_right` `0x001f0003` | both, 5.38; look, loop* | Looks to its right |
| `look_up` `0x00200003` | both, 5.38; look, loop* | Looks up |
| `look_down_left` `0x00210003` | both, 5.38; look, loop* | Looks down and to its left |
| `look_down_right` `0x00220003` | both, 5.38; look, loop* | Looks down and to its right |
| `look_up_left` `0x00230003` | both, 5.38; look, loop* | Looks up and to its left |
| `look_up_right` `0x00240003` | both, 5.38; look, loop* | Looks up and to its right |
| `sleep` `0x00250003` | both, 3.38; sleep, loop* | Dozes standing up |
| `checks_hand_male` `0x00260001` | male, 7.02; idle, loop*, male* | Looks at his hand |
| `stand_3` `0x00270003` | both, 10.72; idle, loop* | Stands, quiet idle |
| `stand_4` `0x00280003` | both, 8.38; idle, loop* | Stands, quiet idle |
| `stand_5` `0x00290003` | both, 4.88; idle, loop* | Stands around |
| `stand_6` `0x002a0003` | both, 6.05; idle, loop* | Stands and looks at the ground |
| `stand_7` `0x002b0003` | both, 6.38; idle, loop* | Stands and sighs |
| `examine_headwear` `0x002c0003` | both, 6.72; examine, loop* | Checks what is on its head |
| `float_up_alt` `0x002d0003` | both, 1.40; float, travel*, copy* | A copy of float_up, root in other units: leaves the frame (same as `float_up`) |
| `examine_lower_body` `0x002e0003` | both, 4.72; examine, loop* | Checks its trousers |
| `fist_raise_male_alt` `0x002f0001` | male, 1.92; emote, celebrate, loop*, male*, copy* | A copy of fist_raise_male, root in other units: leaves the frame (same as `fist_raise_male`) |
| `examine_shoes` `0x002f0003` | both, 3.65; examine, loop* | Checks its shoes |
| `fist_pump_male_alt` `0x00300001` | male, 2.30; emote, celebrate, loop*, male*, copy* | A copy of fist_pump_male (same as `fist_pump_male`) |
| `examine_upper_body` `0x00300003` | both, 4.05; examine, loop* | Checks its top |
| `sleep_alt` `0x00310003` | both, 3.38; sleep, loop*, copy* | A copy of sleep (same as `sleep`) |
| `spin_left` `0x00320003` | both, 2.35; emote | Spins to its left |
| `spin_right` `0x00330003` | both, 2.38; emote, loop* | Spins to its right |
| `raise_arms` `0x00340003` | both, 3.38; emote, celebrate, loop* | Raises both arms |
| `fist_raise_male` `0x00350001` | male, 1.90; emote, celebrate, loop*, male* | Raises a fist |
| `fist_pump_male` `0x00360001` | male, 2.30; emote, celebrate, loop*, male* | Pumps a fist |
| `dance_female` `0x00370002` | female, 5.42; celebrate, dance, loop*, female* | Dances |
| `hop_and_clap_female` `0x00380002` | female, 3.98; celebrate, dance, loop*, female* | Hops and claps |
| `jump_turn_right` `0x00390003` | both, 2.18; jump | Jumps and turns to its right |
| `jump_turn_left` `0x003a0003` | both, 1.63; jump | Jumps and turns to its left |
| `run_forward` `0x003b0003` | both, 0.63; locomotion, loop* | Runs on the spot, one stride |
| `run_forward_2` `0x003c0003` | both, 0.63; locomotion, loop*; family `run_forward` | Runs on the spot, the other stride |
| `step_aside_left` `0x003d0003` | both, 2.88; emote, locomotion, travel*; family `step_aside` | Steps out to its left, arms wide, and settles |
| `step_aside_right` `0x003e0003` | both, 2.88; emote, locomotion, travel*; family `step_aside` | Steps out to its right, arms wide, and settles |
| `jump_squat` `0x003f0003` | both, 1.01; jump | Jumps and lands in a squat |
| `float_spin_celebrate` `0x00400003` | both, 6.72; celebrate, float | Floats up, spins and cheers |
| `pick_me` `0x00410003` | both, 5.88; emote, loop* | Waves both arms, pick me |
| `float_hover` `0x00420003` | both, 8.72; float, loop* | Hovers in the air |
| `float_up` `0x00430003` | both, 1.38; float | Rises off the ground |
| `float_drop` `0x00440003` | both, 1.38; float | Drops back to the ground |
| `run_off` `0x00450003` | both, 5.38; locomotion, stage, travel* | Runs off to its left |
| `run_on` `0x00460003` | both, 5.05; locomotion, stage, travel* | Runs in from its right |
| `run_on_2` `0x00470003` | both, 5.05; locomotion, stage, travel*; family `run_on` | Runs in from its left |
| `run_on_3` `0x00480003` | both, 5.05; locomotion, stage, travel*; family `run_on` | Sprints in from its right, leaning forward |
| `run_on_4` `0x00490003` | both, 5.05; locomotion, stage, travel*; family `run_on` | Sprints in from its left, leaning forward |
| `crouch_to_float` `0x004a0003` | both, 1.26; float | Crouches, then springs up and floats |
| `crouch_cheer` `0x004b0003` | both, 4.42; emote, celebrate, loop* | Cheers from a crouch |
| `struggle_to_balance` `0x004c0003` | both, 1.38; reaction, loop* | Wobbles and finds its balance |
| `stumble` `0x004d0003` | both, 0.65; reaction | Stumbles |
| `crouch_look_around` `0x004e0003` | both, 1.72; look | Crouches and looks around |
| `baseball_swing` `0x00500003` | both, 1.90; action, loop* | Swings a bat |
| `baseball_swing_2` `0x00510003` | both, 1.28; action, loop*; family `baseball_swing` | Swings a bat, a second take |
| `crawl` `0x00520003` | both, 0.86; locomotion, loop* | Crawls on all fours, one cycle |
| `drive` `0x00530003` | both, 1.98; action, loop* | Drives, hands on a wheel |
| `faint` `0x00540003` | both, 1.40; reaction, travel* | Faints |
| `jump` `0x00550003` | both, 1.77; jump, loop* | Jumps |
| `jump_climb` `0x00560003` | both, 1.07; jump, loop* | Jumps up to climb |
| `kick` `0x00570003` | both, 1.61; action, loop* | Kicks |
| `pick_up` `0x00580003` | both, 2.61; action, loop* | Picks something up |
| `pull` `0x00590003` | both, 2.36; action, loop* | Pulls |
| `punch` `0x005a0003` | both, 1.07; action, loop* | Punches |
| `push` `0x005b0003` | both, 1.48; action, loop* | Pushes |
| `run_forward_3` `0x005c0003` | both, 0.77; locomotion; family `run_forward` | Runs, a third stride |
| `side_step_left` `0x005d0003` | both, 1.03; locomotion, loop* | Side-steps to its left |
| `side_step_right` `0x005e0003` | both, 1.03; locomotion, loop* | Side-steps to its right |
| `sit` `0x005f0003` | both, 3.36; sit, loop* | Sits down |
| `slap` `0x00600003` | both, 1.11; action, loop* | Slaps |
| `slap_2` `0x00610003` | both, 1.28; action, loop*; family `slap` | Slaps, a second take |
| `swim_2` `0x00620003` | both, 0.78; locomotion, loop*; family `swim` | Swims, a second stroke |
| `swim` `0x00630003` | both, 0.98; locomotion, loop* | Swims |
| `walk_forward` `0x00640003` | both, 1.15; locomotion, loop* | Walks on the spot |
| `stand_gesture` `0x00650003` | both, 24.88; idle, loop* | Stands and talks with its hands, a long idle |

