# Two-avatar interactions and seats

Two avatars do one thing together: hold hands, high-five, shake hands or hug. One or two avatars sit on a host's
seat: a chair, a bench or the ground. The avatars can be any heights and builds (a tall adult and a child at 0.7
scale, a heavy costume and a slim one); the core measures each body from its own mesh, stands the pair where the
interaction needs them, plays matched clips, and solves the arms and legs with IK so the contacts stay together.

![A high five](../img/interact-five.webp)
![Two avatars holding hands](../img/interact-hold.webp)

The API is 9 functions, 4 sized structs and a fixed event record. Nothing changes for avatars not in an
interaction.

## Quick start

```c
sona_interaction_desc d;
sona_interaction *it = NULL;

sona_interaction_defaults(&d, SONA_INTERACT_HOLD_HANDS);
d.a = parent;                      /* on the left */
d.b = child;                       /* on the right: the parent's right hand holds the child's left */
d.position[0] = 2; d.position[2] = -1;   /* the ground point between them */
d.turn_deg = 0;                    /* both face -Z */
sona_interaction_start(ctx, &d, &it);

/* every frame */
sona_update(ctx, dt, &view, NULL);
sona_interaction_event ev[8];
uint32_t n = sona_interaction_events(it, ev, 8);   /* START, CONTACT, HOLD ... */

/* later */
sona_interaction_end(it);          /* let go; END arrives when they are free */
sona_interaction_remove(it);       /* frees it; until then the handle stays valid */
```

```cpp
sona_interaction_desc d;
sona_interaction *it = nullptr;

sona_interaction_defaults(&d, SONA_INTERACT_HOLD_HANDS);
d.a = parent.raw();                      // on the left
d.b = child.raw();                       // on the right: the parent's right hand holds the child's left
d.position[0] = 2; d.position[2] = -1;   // the ground point between them
d.turn_deg = 0;                          // both face -Z
sona_interaction_start(ctx.raw(), &d, &it);

// every frame
ctx.update(dt, &view);
sona_interaction_event ev[8];
uint32_t n = sona_interaction_events(it, ev, 8);   // START, CONTACT, HOLD ...

// later
sona_interaction_end(it);                // let go; END arrives when they are free
sona_interaction_remove(it);             // frees it; until then the handle stays valid
```

```csharp
var d = SonaContext.InteractionDefaults(Native.SONA_INTERACT_HOLD_HANDS);
d.a = parent.Handle;                 // on the left
d.b = child.Handle;                  // on the right: the parent's right hand holds the child's left
d.position[0] = 2; d.position[2] = -1;   // the ground point between them
d.turn_deg = 0;                      // both face -Z
var it = ctx.StartInteraction(d);

// every frame
ctx.Update(dt, view);
var events = it.Events();            // START, CONTACT, HOLD ...

// later
it.End();                            // let go; END arrives when they are free
it.Dispose();                        // frees it
```

```rust
let mut d = interaction_defaults(sona_sys::SONA_INTERACT_HOLD_HANDS);
d.a = parent.raw();                  // on the left
d.b = child.raw();                   // on the right: the parent's right hand holds the child's left
d.position = [2.0, 0.0, -1.0];       // the ground point between them
d.turn_deg = 0.0;                    // both face -Z
let mut it = ctx.start_interaction(&d)?;

// every frame
ctx.frame()?.update(dt, Some(view))?;
let events = it.events();            // START, CONTACT, HOLD ...

// later
it.end()?;                           // let go; END arrives when they are free
drop(it);                            // frees it
```

```python
it = ctx.interaction("hold_hands", parent, child,   # the parent's right hand holds the child's left
                     position=(2, 0, -1), turn_deg=0)   # the ground point between them; both face -Z

# every frame
ctx.update(dt, view)
events = it.events()                 # start, contact, hold ...

# later
it.end()                             # let go; "end" arrives when they are free
it.remove()                          # frees it
```

A seat:

```c
sona_interaction_defaults(&d, SONA_INTERACT_SIT);
d.a = adult; d.b = child;          /* b NULL: one sitter */
d.flags = SONA_INTERACT_HANDS;     /* two sitters: the near hands hold */
sona_seat_defaults(&d.seat, SONA_SEAT_BENCH);
d.seat.position[0] = 4; d.seat.position[1] = 0.45f; d.seat.position[2] = 0.3f;   /* the front edge's middle, on top */
d.seat.turn_deg = 0;               /* the way they face */
sona_interaction_start(ctx, &d, &it);
```

```cpp
sona_interaction_desc d;
sona_interaction *it = nullptr;
sona_interaction_defaults(&d, SONA_INTERACT_SIT);
d.a = avatar.raw(); d.b = other.raw();   // b nullptr: one sitter
d.flags = SONA_INTERACT_HANDS;           // two sitters: the near hands hold
sona_seat_defaults(&d.seat, SONA_SEAT_BENCH);
d.seat.position[0] = 4; d.seat.position[1] = 0.45f; d.seat.position[2] = 0.3f;   // the front edge's middle, on top
d.seat.turn_deg = 0;                     // the way they face
sona_interaction_start(ctx.raw(), &d, &it);   // sona.hpp has no wrapper: the C call on the handles
```

```csharp
var d = SonaContext.InteractionDefaults(Native.SONA_INTERACT_SIT);
d.a = avatar.Handle; d.b = other.Handle;   // b zero: one sitter
d.flags = Native.SONA_INTERACT_HANDS;      // two sitters: the near hands hold
d.seat = SonaContext.SeatDefaults(Native.SONA_SEAT_BENCH);
d.seat.position[0] = 4; d.seat.position[1] = 0.45f; d.seat.position[2] = 0.3f;   // the front edge's middle, on top
d.seat.turn_deg = 0;                       // the way they face
var sitting = ctx.StartInteraction(d);
```

```rust
let mut d = interaction_defaults(sona_sys::SONA_INTERACT_SIT);
d.a = avatar.raw(); d.b = other.raw();     // b null: one sitter
d.flags = sona_sys::SONA_INTERACT_HANDS;   // two sitters: the near hands hold
d.seat = seat_defaults(sona_sys::SONA_SEAT_BENCH);
d.seat.position = [4.0, 0.45, 0.3];        // the front edge's middle, on top
d.seat.turn_deg = 0.0;                     // the way they face
let sitting = ctx.start_interaction(&d)?;
```

```python
sitting = ctx.interaction("sit", avatar, other,          # other None: one sitter
                          hands=True,                       # two sitters: the near hands hold
                          seat={"kind": "bench", "position": (4, 0.45, 0.3), "turn_deg": 0})   # the front edge's middle
```

## The kinds

- `SONA_INTERACT_HOLD_HANDS`: start and end default to 0.8 and 0.6 s; the hold defaults to 0 (until ended).
  Placement: side by side, both facing `turn_deg`, `a` on the left. Contact: `a`'s right palm against `b`'s left (`SONA_INTERACT_MIRROR`: the other hands, `a` on the right), palms front to back, fingers down. Clips and IK: the standing idle on both, started together; hands by IK.
- `SONA_INTERACT_HIGH_FIVE`: start, hold and end default to 0.8, 0.15 and 0.7 s.
  Placement: face to face, `a` facing `turn_deg`. Contact: right palms (`MIRROR`: left) as high as the shorter one reaches, beside its head when the other's fingers would come at its face. Clips and IK: the hands rise and draw back, then swing in to meet at the start's end; a much taller one crouches, knees apart.
- `SONA_INTERACT_HANDSHAKE`: start, hold and end default to 0.9, 1.6 and 0.8 s.
  Placement: face to face. Contact: right hands about elbow height (nearer the shorter one's), palms sideways. Clips and IK: elbows down and out; the fingers close round the other's hand (a grip) as the palms meet; the hands pump together during the hold (SHAKE events).
- `SONA_INTERACT_HUG`: start, hold and end default to 1.1, 2.5 and 1.0 s.
  Placement: face to face, the fronts all but touching (clothes and any lean included), stepping in over the start. Contact: one's palms on the other's back or flanks round its chest and arms, the other's palms at its waist. Clips and IK: the taller one's arms go round (of a height `a`'s; `MIRROR`: `b`'s) with the elbows out; the other's hold the waist with the elbows down at their own sides, so the two pairs of arms never cross. A much taller one crouches with its knees either side of the other and leans over it. Heads turned aside (look-at).
- `SONA_INTERACT_SIT`: start and end default to 1.3 and 1.4 s; the hold defaults to 0 (until ended).
  Placement: the sitters over the seat, facing `seat.turn_deg`; two side by side by their seated widths. Contact: the body's underside on the seat, the feet flat on the floor. Clips and IK: the stock sit clip (sits down, held, stands up); feet and hands by IK.

A hold of 0 holds until `sona_interaction_end`. Every timing can be set in the desc.

## How it fits the bodies

- **Measured, not assumed.** Each avatar's mesh is skinned at the rest pose once per build and sampled over every
  triangle (a coarse mesh's vertices alone leave gaps): a profile of slabs from the floor up (half width, front and
  back from the spine, clothes, hair and hats included; at the height of the rest pose's outstretched arms only the
  torso counts), two radii for each limb bone (the vertices its own joint moves most, and every vertex moving with
  it, twist and shape joints and sleeves included), and each hand's reach from the palm to the fingertips.
  Shoulder heights, arm and leg lengths, the palm point and the hands' rest turn come from the rig. Scale
  (`sona_placement.scale`) and the manifest's height and weight are in all of it.
- **Hands.** The spacing is chosen so both palms are inside each arm's reach and clear of both heads and chests,
  and so the other's fingers, straight out from its palm (or, where the wrist cannot turn that far, on the arm's
  line), stay 3 cm off the head and chest they point at: a child's big head in a high five puts the palms beside it
  rather than in front of it. Held hands are kept wide enough that neither hand, all its width and fingers, comes
  near the other's side. Where thick cuffs at the two wrists would meet, the palms slide apart (held hands
  sideways, a high five along the fingers) while still overlapping. The palms' plane tilts with the difference in
  shoulder height; the two palms stand a centimetre apart; each hand's turn is set so the palm faces the other.
- **Bending to a shorter one.** In a high five or a hug with a much shorter partner the taller one crouches (the
  placement goes down, the feet stay flat where they stand, the knees bend apart either side of the other) and in
  a hug also leans forward from the hips up to 15 degrees (an ADD override on the Hips, eased in and out with the
  phases). The planning measures the bent body: the shoulders, the profile (the legs left out, they straddle the
  other) and the reach.
- **Hugs.** The hands are planned on each other's outlines: round the chest and upper arms for the arms going
  round, round the waist for the others. Each hand's spot (how far round, how far down, how far out the elbow) is
  searched for in reach first, then for the arm's bones and hand clear of the other's body and of the other's arms
  as planned, then for the most wrap. While the hands arrive and for the hold's first moments (a fixed 0.6 s) the goals settle on
  the posed meshes: each hand rests on the other's surface under it as the hand is actually posed (its turn, its
  thumb, the clip's curled fingers), a forearm or hand pressing into the other's body moves its goal out, and an
  arm going round that comes near one of the other's arms at the waist moves up along the body. Then the goals hold
  still.
- **Seats.** The stock sit clip is sampled on each sitter's own rig: where its seated underside is (bin by bin
  front to back), where its calves hang. The front edge goes just ahead of the calves, the sitter's placement rises
  or falls by what the seat's height asks, and what rests on the seat is the lowest point of the underside between
  the seat's edges. On a seat higher than the clip's, the sitter sits forward (the edge under the hip joints) and
  the thighs tilt down, up to 25 degrees, until the shins reach the floor; past that the feet hang, as a child's do
  on an adult's bench. The knees keep the clip's place and the shins swing to the floor, the feet flat on it. The
  ground: knees up, the feet forward on the floor, the hands on the knees. While seated, the palms rest on the
  thighs (relative to the thigh joints, so they follow the legs) and the IK's own-body checks are off for those
  avatars; at the end their IK limits go back to the defaults. During the same first moments of the hold the posed mesh is
  checked once more and the placement settles the lowest point onto the seat.
- **Limits.** Everything is solved by the [IK](../reference.md#inverse-kinematics) with its default limits: elbows, knees, wrists,
  ankles, hips and shoulders stay inside a person's range, a target out of reach is reached short.

## While it runs

- It owns its avatars' placement, clip and IK hand and foot targets, and while it bends one or closes a hand the
  ADD overrides of the Hips (a lean) and of the four fingers' joints (a handshake's grip); a hug also turns the
  heads (look-at). Layers and expressions stay the host's. Avoid moving the avatars, playing clips or overriding
  those joints until END; at the end it clears what it set.
- Placements ease into the spots over the first part of the start (set to 40% of it, with a cap of 0.4 s) when the avatars are
  within a metre of them, else they jump. `SONA_INTERACT_NO_ALIGN` leaves the placement to the host: stand the
  avatars on `sona_interaction_layout`'s spots, or walk them there (for SIT the height is still driven); there is
  no crouch then.
- `sona_interaction_move` moves the place (or the seat) and the pair goes with it at once: a pair walking hand in hand
  keeps hold. A move replans; a hug's replan searches its hands again.
- An avatar removed or failed cancels the interaction (CANCEL, phase DONE); the other avatar is let go.
- It all runs in `sona_update` on the owner thread, before the avatars advance; the status reads the pose of the
  last update. The same updates give the same bits on any number of worker threads.
- Cost: a held hug does a little work every update once settled, and more while it settles (the start and the
  hold's first moments, when it skins the partner's mesh under each hand); a seat skins the sitter's mesh only while it
  settles. Nothing runs for avatars not in an interaction.

## Status and events

`sona_interaction_status_get` gives the phase, time in it and progress, and:

- `contact_error`: hands: how far the palms are from touching (palms slid apart for thick cuffs count as touching
  where they overlap); seats: the gap or overlap between the lowest point over the seat (from the posed mesh) and
  the seat's top, and any planted foot's miss; hugs: the palms' distance from their settled goals on the other's
  body. `touching` is 1 under 2 cm (a hug: 3 cm).
- `clearance`: an estimate from a capsule round each limb bone (the radius of the vertices its own joint moves
  most) and the torso's slabs, between the two bodies away from the hands; negative means into each other. It is an
  estimate from capsules, not from the meshes.
- `contact`: the contact points (palms meeting; seats: under each sitter's hips); `ik_hit`: each avatar's IK hits.

Events: START, CONTACT (the first pose touching), HOLD, SHAKE (each pump, value = the pump's number), RELEASE,
END, CANCEL. Up to 32 are held; past that the oldest go. `sona_interaction_event` is a fixed 16-byte record (like
`sona_layer_event`): it grows only by new kinds.

## Layout

`sona_interaction_layout(&desc, &plan)` answers where the avatars will stand (`place[0..1]`), the contact points,
the spacing between their origins and the planned clearance, without starting anything. Both avatars must be READY;
for SIT it is `SONA_PENDING` until the stock sit clip has been read through the sources (it asks for it: call
again). It is an owner-thread call like `sona_interaction_start`: it measures both bodies each time (a hug also plans the hands), so call it when the plan is needed, not every frame.

## Errors

`SONA_E_ARGUMENT`: a bad size, kind, flag or timing, `b` missing (not SIT) or the same as `a`, avatars of two
contexts, an avatar already in a running interaction, `SONA_INTERACT_HANDS` without two sitters, a seat narrower
than 0.2 m or shallower than 0.15 m (not the ground), or two sitters who do not fit its width. `SONA_E_NOT_READY`:
an avatar is not READY. `SONA_E_LIMIT`: the ctx holds 64 interactions, finished ones included. An interaction is
freed only by `sona_interaction_remove` (or `sona_close`), so a handle the host holds stays valid; remove finished
ones you no longer need. A SIT whose sources lack the stock sit clip cancels.

## Limits

- **A hug wraps as far as the arms reach.** The stylised bodies are deep and the arms short: between two broad
  adults the hands rest on the other's flanks and lower back rather than meeting behind it, and the arms stay
  fairly straight. A small partner is wrapped fully.
- **Fingers.** A handshake's fingers close (a 35 degree bend in each finger joint); held hands and high fives keep
  the clip's fingers, and fingers never interlace. A bend that hits the other's hand is left (the palms touch).
- **No cloth.** Long coats and skirts skinned to the hips are measured as they hang at the rest pose; seated, a
  coat flap can show where it would really fold.
- **Stock clips only where they exist.** Sitting uses the stock sit clip; the others use the standing idle and IK.
  There is no matched two-person clip in the stock set.
- **Seats are boxes.** The seat is a flat top with a front edge; a host with a curved or sloped seat gives the
  nearest flat one.

## Sample

`samples/c/interactions_vk.c` (target `interactions_vk`, Vulkan, headless): eight stations side by side: a tall
adult and a child at 0.72 scale holding hands; a heavy tall avatar and a small one high-fiving; two of different
builds shaking hands; two adults hugging; a tall adult hugging a child at 0.72 (crouched, knees apart); an adult and
a child at 0.7 on a bench holding hands; one on a chair; one on the ground. The sample ray-casts the bench, the
chair and the floor and puts the avatars over them with depth. It writes an overview and two views of each station
while they hold, ends them all, and fails on a missed contact or an interaction that does not run its phases.
`--only <station>` runs one station and adds views from behind and above; `--marks` draws the contact points;
`--verbose` prints each limb's IK.

```sh
interactions_vk --cast devs-cast.json --size 1280x720 --out duo
```
