# Hair and cloth sway

Soft secondary motion: long hair, ponytails and plaits, skirts, dresses, kilts, robes and coat tails, and dangling
earrings swing as the avatar moves, lag behind a turn, settle when it stops, hang with the host's gravity and blow
in its wind, and slide off the legs, neck and shoulders instead of going through them. It is off by default, per
avatar, and costs nothing until it is turned on. No item file changes: what can sway is read from each item's own
mesh when it is worn.

![Six costumes swaying in the wind](../img/sway.webp)

The public API is seven functions and three structs ([C reference: hair and cloth sway](../reference.md#hair-and-cloth-sway)). Each struct starts with
`size = sizeof(struct)`; the `_defaults` functions set it and every other field.

## Quick start

```c
sona_sway o;
sona_sway_defaults(&o);                  /* hair, cloth and earrings; medium quality */
sona_avatar_sway(avatar, &o);            /* before or after READY */

sona_sway_world w;
sona_sway_world_defaults(&w);            /* gravity 0 -9.81 0, no wind */
w.wind[0] = 4;                           /* a 4 m/s breeze along +X, gusting */
sona_sway_world_set(ctx, &w);

sona_update(ctx, dt, &view, NULL);       /* the chains step inside the poses of this update */
```

```cpp
sona_sway o;
sona_sway_defaults(&o);                  // hair, cloth and earrings; medium quality
sona_avatar_sway(avatar.raw(), &o);      // before or after READY

sona_sway_world w;
sona_sway_world_defaults(&w);            // gravity 0 -9.81 0, no wind
w.wind[0] = 4;                           // a 4 m/s breeze along +X, gusting
sona_sway_world_set(ctx.raw(), &w);

ctx.update(dt, &view);                   // the chains step inside the poses of this update
```

```csharp
avatar.SetSway(SonaAvatar.SwayDefaults());       // hair, cloth and earrings; medium quality; before or after READY

var w = SonaContext.SwayWorldDefaults();         // gravity 0 -9.81 0, no wind
w.wind[0] = 4;                                   // a 4 m/s breeze along +X, gusting
ctx.SetSwayWorld(w);

ctx.Update(dt, view);                            // the chains step inside the poses of this update
```

```rust
avatar.set_sway(Some(&sway_defaults()))?;        // hair, cloth and earrings; medium quality; before or after READY

let mut w = sway_world_defaults();               // gravity 0 -9.81 0, no wind
w.wind[0] = 4.0;                                 // a 4 m/s breeze along +X, gusting
ctx.set_sway_world(Some(&w))?;

ctx.frame()?.update(dt, Some(view))?;            // the chains step inside the poses of this update
```

```python
avatar.sway()                                    # hair, cloth and earrings; medium quality; before or after READY

ctx.sway_world(wind=(4, 0, 0))                   # gravity 0 -9.81 0, a 4 m/s breeze along +X, gusting

ctx.update(dt, view)                             # the chains step inside the poses of this update
```

`sona_avatar_sway(a, NULL)` turns it off; the avatar draws its items' own meshes again. `sona_avatar_sway_reset`
puts everything back in its modelled shape at the next pose (after a cut or a teleport; a jump of over a metre
between poses does this by itself).

## Options

| `sona_sway` field | Default | What |
|---|---|---|
| `parts` | `SONA_SWAY_DEFAULT` | `SONA_SWAY_HAIR`, `_CLOTH`, `_ACCESSORIES` (earrings), `_HEADWEAR` (costume and hat pieces below the head: wigs, plaits, hoods, helmet flaps; not in the default because many are rigid). Changing parts re-skins at once |
| `quality` | `SONA_SWAY_MEDIUM` | `LOW`: 30 fixed steps a second, one constraint pass. `MEDIUM`: 60, two. `HIGH`: 120, three |
| `stiffness` | 0.5 | 0..1, how hard each chain keeps its modelled shape (the springs run from half to one and a half times their strength) |
| `damping` | 0.5 | 0..1, how soon a swing dies down |
| `wind_scale` | 1 | how much of the ctx's wind reaches this avatar; 0 indoors |
| `min_pixels` | 48 | below this height on screen the avatar rests in its modelled shape and steps nothing; 0: always sway |

| `sona_sway_world` field | Default | What |
|---|---|---|
| `gravity` | 0 -9.81 0 | m/s^2, world. Items are modelled hanging under normal gravity, so only the difference moves them: an avatar upright under the default hangs exactly as modelled, one lying down or in zero gravity does not |
| `wind` | 0 0 0 | m/s, world; air drag pulls each node towards it |
| `gust` | 0.35 | 0..1, how much the wind's strength wanders (smooth noise, per avatar and per chain) |
| `gust_seconds` | 1.5 | how long a gust takes |

`sona_avatar_sway_info` reports what sways on an avatar (`parts`, `meshes`, `chains`, `nodes`, `vertices`) and what
the last pose did (`steps`, `resting`, `max_offset`: metres the furthest node is from its modelled place). With sway
off it still reports the parts its items have. `sona_avatar_sway_mesh_parts(a, i)` names the parts one of
`sona_pose`'s meshes sways with.

## What sways

Each worn mesh is read in bind space against the rig's bind joints, once per mesh and ctx (every avatar wearing the
same item shares the result):

- **Hung from the head.** Vertices skinned to the head and neck (a threshold of 90%) that lie below a hang line 2 cm under
  the head joint. Stock hair (the hair slot alone) is `HAIR`; earrings (the earring slot alone) hang from their own
  tops and are `ACCESSORIES`; any other item, a costume or a hat, is `HEADWEAR`. Something wrapped round the face
  (a helmet's rim, a mask, a balaclava: more than a threshold of 4% of what hangs lies in front) never sways. At least 5 cm must
  hang (3 for earrings).
- **Hung from the hips.** Cloth on shirts, trousers and costumes skinned (a threshold of 80%) to the hips, the spine and the
  legs, below a hang line 3 cm above the thighs' joints, when the mesh passes the skirt test: trousers have cloth
  between the legs at their crotch and nowhere below it, while a skirt, dress, kilt or robe has cloth on the middle
  line, clear of both legs, both in front of them and behind them, within some 5 cm band below the crotch. Coat
  tails pass with cloth behind the legs 20 cm below the crotch; a top alone passes when it reaches 8 cm below the
  crotch. At least 8 cm must hang.

What sways, over the whole catalogue: the long stock hair styles (ponytails, plaits, bobs, shoulder length,
dreadlocks), earrings, cloth that hangs clear of the legs (skirts, dresses, kilts, robes, gowns, long coats, armour
skirts, capes) and, when turned on, headwear. No jeans, shorts or trousers do (a trench coat worn over trousers does,
for its coat). Some skirts and dresses do not: minis whose hem stays close to the crotch, dresses too tight to
clear the legs, and costumes whose skirt shares a mesh with socks or leggings.

## How it is skinned

Each region gets up to eight chains, one per 45 degree sector round it (sector 0 in front), with one to three nodes
from the hang line down to the hem; a chain's anchor sits on the hang line and never moves. The vertices that hang
are re-skinned in a copy of the mesh, through palette joints the mesh never reads. Each such joint carries one
(node, joint) pair: the original joint's skin matrix followed by how that node moved, so a vertex keeps its own
skinning and only the nodes' moves are blended. A node's move is the shortest turn from its modelled segment to
where the chain put it, after a turn about the segment by the angle the node moved round the region's axis: a skirt
swung round the body turns its surface, and so its shading, with it.

Four influences hold four nodes (two chains by two levels) of one joint, which is what hair has; cloth uses two nodes
(the two levels round it on its own sector's chain) of up to two joints; a vertex skinned to three or four joints
follows the nearest node with every joint. No joint's weight moves to another joint, and a joint a node barely carries
keeps its share unswayed, so with nothing swaying every vertex lands where its item put it, to the rounding of the
weights to bytes. Cloth chains are coupled to their neighbours (below), so the sector boundaries do not open.

A swaying mesh draws with its own palette: `sona_pose` lists it after the props (`sona_mesh.palette` indexes
`sona_pose_data.props`, `playing` 1) with the re-skinned vertices and a new `key`, so a host drawing through the
data API needs no new code. `sona_pose_vertices` skins through it too. With sway on, `prop_count` can therefore pass
4 (up to 4 held props and 8 swaying meshes): size arrays by it. A `sona_pose_data` stays valid until the next
`sona_update` even when sway is turned off or its parts change in between; the meshes it points at are freed then.

Exports (glTF, VRM) keep the items' own meshes. Crowd sprites are baked from the swaying meshes with their rest
palettes (each (node, joint) palette joint holding its joint's own matrix): the items' own shape, the same picture
as with sway off, so avatars with sway on and off share a look (`sway_gpu_vk` compares the two sheets).

## The solver

Verlet on fixed steps (`quality`), in world space so the avatar's own motion and turns drag the chains:

1. each node accelerates by gravity (less what the modelled shape carries, from the anchor joint's turn), a spring
   to its modelled place, and air drag towards the wind; its velocity is damped;
2. constraint passes: each segment keeps its modelled length; each node is pushed out of the body's capsules (neck,
   upper back, shoulders and upper arms for the head; thighs, shins and pelvis for the cloth), never further out
   than its modelled place is, so cloth modelled hugging a leg is not blown off it; no node strays further than
   0.45 of its chain length from its modelled place;
3. cloth only: each node's offset is pulled a fifth of the way to its neighbours' (the sheet holds together).

Each step meets the body where it was when the step fell due: the modelled targets are interpolated in time between the
last pose and this one. Between steps (a display at a frame rate of 144 Hz over a step rate of 60 a second), each node
keeps its offset from its modelled place on the body as the last step left it, so hair and skirt follow the body on the
poses without a step instead of hanging back and jumping at the next. A pose that comes after more time than the
quality's steps cover (3, 6 or 12) drops the rest, so even at a frame rate of 10 fps a pose never takes bigger steps; a
pose after more than half a second, a jump of a metre, or `sona_avatar_sway_reset` starts again at rest. Nothing a host
passes can make it explode: the bound in step 2 holds after every step, and a non-finite value puts the node back.

A resting avatar is not posed for sway: an avatar is posed again while its chains move, when its placement changes,
when the wind blows, or after `sona_sway_world_set`. In a crowd, avatars smaller than the crowd's full-rate size
pose at their own rate and step what that rate gives them.

## Determinism and threads

The solver is float maths with no FMA contraction and no libm; gusts come from a hash of the avatar's id and its own
sway clock. The same updates give the same bits on any number of worker threads. State is per avatar and touched only by
the thread posing it; the shared re-skinned meshes change only on the owner thread (turning sway on or off, or a new
build).

## Cost

Per swaying avatar and step: up to 48 nodes (two regions of eight chains of three), each a verlet update and one
to three constraint passes against up to 11 capsules; then per pose a blend of skin matrices per node and one 4x4
product per (node, joint) pair, and at each draw one more palette folded and uploaded per swaying mesh. The
re-skinned meshes are shared by every avatar wearing the item, so a crowd uploads each one once. Draw calls do not
change: a swaying mesh replaces its item's mesh.

Measured with the bench on an RTX 4090 machine, the crowd scene (1,000 avatars, each its own random outfit and
body from the full corpus and catalogue), `SONA_BENCH_SWAY` turning sway on for every avatar, the median of three
runs each.
In that crowd 114 of the avatars wear something that sways (120
meshes, 1,241 nodes): random outfits rarely pick long hair or a skirt.

| `--scene crowd --backend vk --counts 1000` | ms a frame | CPU ms a frame | GPU ms a frame | Draws a frame |
|---|---|---|---|---|
| sway off | 16.15 | 3.48 | 16.13 | 9,470 |
| `medium` | 16.19 | 3.27 | 16.18 | 9,470 |
| `medium,nolod` (every avatar sways at any size) | 16.18 | 3.61 | 16.16 | 9,470 |
| `high,nolod` | 16.16 | 3.31 | 16.14 | 9,470 |

On this machine the GPU time is the whole frame, and the draws do not change. The CPU side alone, `--scene pose
--backend none --threads 0` (one thread, every avatar posed every update, no view), the same crowd, CPU ms per
`sona_update`:

| `--scene pose --backend none --threads 0` | CPU ms an update |
|---|---|
| sway off | 1.97 |
| `medium` | 2.12 |
| `high` | 2.23 |

## The sample

`samples/c/sway_vk.c` (target `sway_vk`, Vulkan, headless): two copies of one avatar in long hair and a skirt on
turntables, sway off on the left and on on the right, each seen by its own camera from the same angle, so the two
halves of a cell differ only by sway. The tables speed up to a turn a second, spin, and stop dead; six moments make
a 3 x 2 sheet (at rest, speeding up, spinning, still spinning, just stopped, settling). With `--sequence <prefix>`
every frame is also written as a PNG, for a video; `--control` leaves sway off on both, for the same sheet without
it. Without `--wear` it dresses the first woman of the cast in the stock ponytail and polka dot skirt, which it finds
by name in the offline catalogue (`--catalogue`, default `data/sona-catalogue.bin`); `--quality` and `--stiffness`
set the options. It fails when the right copy does not sway both its hair and its skirt, or the spin moves it less
than 1 cm.

Seen side on, the polka dot skirt's front shows a pale band: its own front panel at a grazing angle, which the copy
with sway off shows too from the same angle (`--control`). An earlier sheet put both copies in one view, where they
were seen from different angles and only the swaying one showed it.

```sh
sway_vk --cast devs-cast.json --out sway.png
```

## Limits

- Cloth is chains coupled to their neighbours, not a cloth simulation: it does not fold, wrinkle or collide with
  itself, and only nodes collide with the body (between nodes, a hem swung hard into a leg can pass into it).
- The hang lines are fixed heights on the rig: a ponytail tied high swings only below the head's hang line.
- Bodies are capsules of fixed radii; very heavy body shapes are covered only by the never-deeper-than-modelled rule.
- Costume and hat pieces (`HEADWEAR`) are off by default because the mesh alone does not tell a wig from a helmet's
  neck guard.
- Long coats open at the front sway only when their tails pass behind the legs well below the crotch.
- Vertices within 5 cm of a region's axis (inner faces between the legs) keep their own skinning and do not sway.
