# Blending and walking on the web

The web half of [layers](layers.md): crossfades, layers over the avatar's clip with joint masks, blend spaces, and a
walk that holds the ground. They are calls on the avatar `scene.add()` gives you, the same model as the native
`sona_avatar_crossfade`, `sona_avatar_layer_*` and `sona_blend_space`. An avatar that blends nothing poses exactly as
before: `play()` without a fade is still a cut, and the idle playlist is untouched.

## Crossfades

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

const sona = await SonaRenderer.create({ canvas: document.querySelector('canvas') });
const avatar = sona.add(manifestBase64, { clip: 'GenericStand5' });
await avatar.ready;
await avatar.crossfade('GenericWave', 0.25);         // from what shows now, over a quarter second
await avatar.play('GenericCelebration', { fade: 0.4, loop: false });
avatar.play('GenericStand5');                        // no fade: a cut, as sona_avatar_play
```

A crossfade starts from whatever the avatar shows at that moment, so starting a new one halfway through another never
pops. Between poses far apart the fade is stretched until no joint turns faster in a frame than the two clips do on
their own: a crossfade from a crouch to a jump takes a little longer instead of snapping. The face switches once, when
the fade is half done.

A negative `speed` plays a clip backwards, from its end unless `from` says otherwise:

```js
await avatar.play('GenericCelebration', { loop: false, speed: -1, fade: 0.25 });
```

## Layers

Seven layers sit over the avatar's clip. Each plays a clip through a mask, so a wave can ride on top of whatever the
avatar is doing:

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

const sona = await SonaRenderer.create({ canvas: document.querySelector('canvas') });
const avatar = sona.add(manifestBase64, { clip: 'IdleShiftsWeight' });
await avatar.ready;
await avatar.layer(1).play('GenericWave', { mask: 'upper', oneShot: true });   // the arms wave, the legs carry on
await avatar.layer(2).play('IdleLooksAround', { mask: 'head', weight: 0.5 });
avatar.layer(2).weight(0, 0.5);                      // fade it out over half a second
```

| Option | Default | Meaning |
|---|---|---|
| `mask` | every joint | `'full'`, `'upper'` (Spine and up), `'lower'`, `'head'` (Neck and up), `'leftArm'`, `'rightArm'`, `'arms'`, or 71 weights from 0 to 1 |
| `fade` | 0.2 | seconds to blend the layer in |
| `oneShot` | false | fade the layer out over its last `fadeOut` seconds and empty it when the clip ends |
| `fadeOut` | 0.3 | a one-shot's fade out |
| `weight` | 1 | the layer's weight, 0 to 1 |
| `mode` | `'override'` | `'additive'` adds the clip's change from its first frame instead of replacing the joints it masks |
| `loop`, `speed` | true, 1 | as `play()` |

Higher layers sit over lower ones, and `layer(i).stop()` fades one out and empties it. The masks are the native
presets (`SONA_MASK_*`), so a mask set up for one platform moves the same joints on the other.

## Blend spaces

A blend space plays several clips on one shared cycle and weights them by where its parameters put the point, so
footfalls stay in step however the weights move. Any clip id is a clip key, so the stock walk is named by its id:

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

const WALK = '00400000-0064-0003-c1c8-f109a19cb2e0';   // the stock walk on the spot
const sona = await SonaRenderer.create({ canvas: document.querySelector('canvas') });
const avatar = sona.add(manifestBase64);
await avatar.ready;
await avatar.blend({
  x: 'speed',
  samples: [{ clip: 'Stand0', x: 0 }, { clip: WALK, x: 0.75 }],
}, { fade: 0.3 });
avatar.setParam('speed', 0.4);                       // the point follows over smooth seconds (default 0.1)
```

One parameter gives a line of samples; `y` adds a second and the samples are joined into triangles, as
`sona_blend_space`. Each sample may have its own `speed`, and a `phase` (0 to 1) that moves where its cycle starts, to
line up its left foot with the others'. `synced: false` lets each clip keep its own time instead.

## Walking

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

const sona = await SonaRenderer.create({ canvas: document.querySelector('canvas') });
const avatar = sona.add(manifestBase64);
await avatar.ready;
await avatar.locomote({ speed: 0.8 });               // metres a second

function step(dt) {                                  // each frame: move it by the stride
  const s = avatar.stride;                           // { speed, rate, walk, dir }
  const [x, y, z] = avatar.position;
  avatar.move({ position: [x + s.dir[0] * s.speed * dt, y, z + s.dir[1] * s.speed * dt] });
}
```

Or let it walk itself along its own facing, and stop it again:

```js
await avatar.locomote({ speed: 0.8, move: true });
await avatar.locomote({ speed: 0 });                // eases to a stop and goes back to its clip
```

`locomote()` plays the stock walk at the rate that makes its planted foot stand still at the speed asked for. That rate
comes from the walk's own stride, measured for every body height and shipped with the SDK, so a short avatar takes
quicker steps than a tall one at the same speed. Starts and stops ease in and out of the idle. A foot lock (two-bone leg
IK, as `sona_avatar_ik_foot_lock`) then holds the planted foot where it touched down: in the world the feet do not
slide.

Move the avatar by `stride.speed`, not by the speed you asked for. It is the ground speed for this frame and swells and
eases a little with the planted foot through each step, as a person's pace does; moving by it is what keeps the feet
still. The foot lock follows the avatar's own placement, so turning it, or easing it with `move({ ... }, { over })`,
works as well.

| Option | Default | Meaning |
|---|---|---|
| `speed` | 0 | metres a second; 0 stops |
| `move` | false | move the avatar along its facing by itself |
| `footLock` | true | hold the planted foot still |
| `maxRate` | 1.35 | the fastest the walk plays, as a multiple of its own rate; up to 2 for hurrying |

## Looking

New after 1.2.0: `lookAt` and the idle spacing below come with the next SDK release ([changelog](../changelog.md)).

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

const sona = await SonaRenderer.create({ canvas: document.querySelector('canvas') });
const avatar = sona.add(manifestBase64);
await avatar.ready;
avatar.lookAt([1.2, 1.5, 2]);                        // a point in the world: another avatar's head, the camera
```

The head and neck turn toward the point over whatever the clip and its layers play, with the limits of
`sona_ik_look`: by default 70 degrees either side, 35 up and 45 down, eased with `smooth` (defaults to 0.15 s) and
no faster than `rate` (defaults to 360 degrees a second). The neck takes a third of the turn and the head the rest. A point behind the avatar lets the head go back to
the clip instead of craning round. Call it every frame to follow something that moves; `lookAt(null)` eases back.

```js
avatar.lookAt(null);
```

## Idling in a crowd

`play('idle')` plays the idle playlist: mostly quiet stands, now and then a restless or lively one. Each avatar starts
its clip somewhere in the middle and keeps clear of the others in the same scene, so a crowd told to idle at the same
moment never moves in step. Pass `from` to start a clip at a time of your own.

## Seeing what plays

`avatar.where(i)` says what layer `i` (0 is the clip) is playing: seconds `t`, `norm` from 0 to 1 through it, whether it
is fading, and its weight. `avatar.events` lists what happened last frame (`started`, `looped`, `ended`, `stopped`, by
layer). To end a gesture on its own last frame instead of on a timer, fade to the next clip once `norm` is close to 1.

`avatar.onPose(fn)` runs `fn(pose, avatar)` on every pose before it is drawn; return a pose to draw that instead
(look-at, tracking). `onPose(null)` takes it off.

## Where the web and native differ

State machines (`sona_state_machine_create`) and root motion extraction are native only. Per-sample phase offsets are
web only: the native blend space has no phase field.
