# Picking: which avatar, which part, which prop

Point at the picture, or cast a ray through the world, and get back the avatar
there, the item or body part it hit (with the item's id and section), the held prop, the joint that moves that
point, the body region (head, torso, left hand ...), the hit point, the surface normal and the distance. Two ways:

- **On the CPU** (`sona_pick_ray`, `sona_pick_screen`, `sona_pick_ray_all`, `sona_avatar_pick`): needs no renderer,
  works on every platform, and gives the same bits on every run and every machine.
- **Through a GPU id buffer** (`sona_pick_gpu`, `sona_pick_gpu_ids`): Vulkan, GL and GLES. The point pick draws one
  pixel; the region call gives a whole id buffer for selection outlines and editors.

Both see what the draw shows: back faces are culled, texels the draw discards (alpha under one half) let the ray
through, hidden and culled avatars are skipped, held props count only while their own clip plays (when the draw
shows them), and a far avatar drawn as a crowd sprite is picked on its picture.

## In code

```c
sona_pick_hit hit;
/* the mouse at (mx, my) in a view of the scene */
if (sona_pick_screen(ctx, &view, mx + 0.5, my + 0.5, NULL, &hit) == SONA_OK) {
  printf("avatar %u: %s %s (%s), %s, joint %s, %.2f m\n", hit.avatar_id,
         hit.part == SONA_PICK_BODY ? "body" : hit.part == SONA_PICK_PROP ? "prop" : "item", hit.item,
         sona_catalogue_section_name(hit.section), sona_region_name(hit.region),
         hit.joint >= 0 ? sona_joint_name((uint32_t)hit.joint) : "-", hit.distance);
}

/* a shot from a gun: the first avatar along it, the player's own avatar passed through */
sona_pick_options o;
sona_pick_defaults(&o);
o.ignore = &player;
o.ignore_count = 1;
o.max_distance = 50;
if (sona_pick_ray(ctx, muzzle, aim, &o, &hit) == SONA_OK && hit.region == SONA_REGION_HEAD) { /* a headshot */ }
```

```cpp
sona_pick_hit hit;
// the mouse at (mx, my) in a view of the scene
if (sona_pick_screen(ctx.raw(), &view, mx + 0.5, my + 0.5, nullptr, &hit) == SONA_OK) {
  const char *part = hit.part == SONA_PICK_BODY ? "body" : hit.part == SONA_PICK_PROP ? "prop" : "item";
  const char *joint = hit.joint >= 0 ? sona::joint_name((uint32_t)hit.joint) : "-";
  std::printf("avatar %u: %s %s (%s), %s, joint %s, %.2f m\n", hit.avatar_id, part, hit.item,
              sona::section_name(hit.section), sona_region_name(hit.region), joint, hit.distance);
}

// a shot from a gun: the first avatar along it, the player's own avatar passed through
sona_pick_options o;
sona_pick_defaults(&o);
sona_avatar *mine = me.raw();
o.ignore = &mine;
o.ignore_count = 1;
o.max_distance = 50;
if (sona_pick_ray(ctx.raw(), muzzle, aim, &o, &hit) == SONA_OK && hit.region == SONA_REGION_HEAD) { /* a headshot */ }
```

```csharp
// the mouse at (mx, my) in a view of the scene
if (ctx.PickScreen(view, mx + 0.5, my + 0.5, out var hit))
{
    var joint = hit.Joint >= 0 ? SonaJoints.Name(hit.Joint) : "-";
    Console.WriteLine($"avatar {hit.AvatarId}: {hit.Item}, {hit.RegionName}, joint {joint}, {hit.Distance:F2} m");
}

// a shot from a gun: the first avatar along it, the player's own avatar passed through
var o = new SonaPickOptions { Ignore = new[] { me }, MaxDistance = 50 };
if (ctx.PickRay(muzzle, aim, out hit, o) && hit.Region == Native.SONA_REGION_HEAD) { /* a headshot */ }
```

```rust
// the mouse at (mx, my) in a view of the scene
if let Some(hit) = ctx.pick_screen(view, mx + 0.5, my + 0.5, &PickOptions::default())? {
    let h = &hit.raw;
    println!("avatar {}: {}, {:.2} m", h.avatar_id, region_name(h.region).unwrap_or("-"), h.distance);
}

// a shot from a gun: the first avatar along it, the player's own avatar passed through
let o = PickOptions { ignore: vec![me.raw()], max_distance: 50.0, ..Default::default() };
if let Some(hit) = ctx.pick_ray(muzzle, aim, &o)? {
    if hit.raw.region == sona_sys::SONA_REGION_HEAD { /* a headshot */ }
}
```

```python
# the mouse at (mx, my) in a view of the scene
hit = sona.pick_screen(ctx, view, mx + 0.5, my + 0.5)
if hit:
    print("avatar %d: %s %s, %s, joint %d, %.2f m" % (hit.avatar_id, hit.part, hit.item, hit.region, hit.joint, hit.distance))

# a shot from a gun: the first avatar along it, the player's own avatar passed through
hit = sona.pick_ray(ctx, muzzle, aim, max_distance=50, ignore=[me])
if hit and hit.region == "head":
    pass                                              # a headshot
```

> **Note:** Call between `sona_update` calls, one thread at a time per ctx. A pick reads the pose of the last
> `sona_update`, which is the pose the next `sona_draw` draws.

## What a hit says

| Field | Meaning |
|---|---|
| `avatar`, `avatar_id` | the avatar (as `sona_avatar_id`) |
| `source` | `SONA_PICK_SOURCE_MESH` (a triangle), `_SPRITE` (a crowd sprite's picture), `_BOUNDS` (the sphere, with `SONA_PICK_BOUNDS`) |
| `part` | `SONA_PICK_BODY` (the body or head figure), `SONA_PICK_ITEM` (anything worn), `SONA_PICK_PROP` (a held prop) |
| `item`, `mask`, `section` | the item's id, its AssetMask, and a `sona_section` from the mask (see below) |
| `mesh`, `triangle`, `bary`, `uv` | index into `sona_pose_data.meshes`, the triangle (`indices[3 * triangle ..]`), the point's weights for its second and third corners, the colour texture's coordinates there |
| `prop` | index into `sona_pose_data.props` for a held prop, else -1 |
| `joint`, `region` | the named joint (`sona_joint_name`) that moves the point most, and its `sona_body_region`; -1 and NONE for a prop, which rides its own skeleton |
| `flags` | `SONA_PICK_HIT_BACK` (a back face, with `SONA_PICK_BACK_FACES`), `_FACE` (the face sheet's material: eyes, brows, mouth), `_GPU` (found through the id buffer) |
| `lod` | the avatar's crowd step at the last update |
| `point`, `normal`, `distance` | world space; the normal is the triangle's, turned toward the ray (the quad's for a sprite); metres along the ray |

`section` comes from the item's mask by the editor's rules (carryable, then costume for an item over two or more
garment slots, gloves for the gloves-and-ring pair, then the slot's own name; head and body for the figure). The
offline catalogue (`sona_catalogue_find` on `item`) has the item's name and its listed section; note that the
catalogue lists some full costumes as "gloves" (the editor's rule tests the gloves-and-ring pair before the
costume count), where the pick says costume.

The joint is the heaviest skinning joint of the triangle corner nearest the point, walked up past the body-shape
joints to a named one; the regions are: head (Head), neck (Neck), torso (Spine, Chest), hips (Hips), each arm
(shoulder, upper and lower arm), each hand (hand, fingers, the prop and special joints), each leg (upper and lower
leg) and each foot (foot, toes).

## Options

`sona_pick_options`: `flags`, `max_distance` (metres; 0: no limit) and `ignore` / `ignore_count` (avatars the ray
passes through). Flags:

| Flag | Meaning |
|---|---|
| `SONA_PICK_HIDDEN` | also avatars hidden with `sona_avatar_set_visible` |
| `SONA_PICK_CULLED` | also avatars outside the last update's view |
| `SONA_PICK_BACK_FACES` | triangles facing away count too (from inside a body, say) |
| `SONA_PICK_NO_ALPHA` | texels the draw discards count too |
| `SONA_PICK_NO_PROPS` | held props let the ray through |
| `SONA_PICK_BOUNDS` | stop at the bounding spheres: the avatar and a distance, no triangles |
| `SONA_PICK_SPRITES_AS_MESH` | a sprite avatar is tested on its mesh where it stands, not on its picture |

`sona_pick_ray_all` returns every avatar along the ray, each at its nearest hit, nearest first (for penetrating
shots, or a menu of what is under the cursor). `sona_avatar_pick` tests one avatar whatever its visibility.

## How the CPU pick works

1. **Spheres.** Every avatar in play whose bounding sphere (the one culling uses) the ray meets is a candidate, sorted
   by where the ray enters it. Candidates are tested nearest first and the walk stops once a sphere starts past the
   nearest hit so far: a pick through a crowd of 1,000 tests a handful of avatars.
2. **Boxes from the joints.** For each mesh, and for each run of 64 of its triangles, the bind-pose box of the
   vertices each joint moves is kept per avatar build (made on the first pick that reaches the avatar). A skinned
   vertex is a weighted mean of its joints' transforms of it, so it lies inside the box around each joint's
   transform of that bind-pose box: the union of those boxes, taken through the current pose's palette, bounds the
   mesh, and the run, exactly. Meshes are visited by where the ray enters their box.
3. **Triangles.** Only the triangles of the runs whose box the ray meets are tested, their vertices skinned one at
   a time with the scalar skinning's maths (double sums, one float store), so a pick is the same bits
   on x86, ARM, PowerPC and WASM. Each triangle is met by Moller-Trumbore in double. Front faces are the draw's (GL's
   `frontFace(CW)`); the alpha test samples the colour texture's level 0 bilinearly at the hit's uv0 and multiplies by
   the vertex colour's alpha, as the avatar shader does.
4. **Sprites.** An avatar the crowd draws as a sprite only is met on its quad (a view-aligned rectangle, 1.1 m by
   2.2 m at its scale, centred at 0.9 m up, as `crowd.c` draws it). The point on the quad becomes an orthographic
   ray into the mesh at the turn of the picture shown, in the avatar's held pose, which is the pose the picture was
   baked from (or, when another avatar of the same look baked it, a pose of the same clip). The hit is on the quad,
   with the quad's normal; the item, mesh, triangle and joint come from the picture. An avatar still crossing
   between mesh and sprite is picked on its mesh first.

## The GPU id buffer

`sona_pick_gpu` draws the avatars whose sphere the ray meets once more into a one-pixel target of the pass's own,
under the view's projection narrowed to that pixel. Each draw writes its index; the backend reads the pixel back
(Vulkan: on the readback command buffer, submitted on the device's queue and waited for, as `sona_snapshot` does;
GL: `glReadPixels`), and the hit is finished on the CPU on the one mesh found. The id pass uses each backend's own
avatar vertex stage and a small fragment stage that runs the draw's alpha test and writes the id; nothing of the
main pass changes. Sprite avatars are tested on the CPU and the nearer of the two hits wins.

`sona_pick_gpu_ids` draws every drawable avatar in a region of the picture (up to 4096 x 4096) and returns, per
pixel, the avatar id and the mesh index + 1. Sprite avatars are drawn as their meshes in their held pose there. The
sample uses it to outline the picked avatar and tint the item hit.

Backends: Vulkan, GL/GLES, D3D11, D3D12, Xenos and Metal have the id pass.

## What it costs

Measured with the crowd scene on an RTX 4090 machine, three runs, medians; each run picks at 1,000 seeded points
after the measured window:

```text
sona-bench --scene crowd --backend vk --outfits random --source dir:"<asset folder>" --samples devs-cast.json \
  --catalogue sona-catalogue.bin --assets-mb 30000 --seconds 4 --counts 1000 --picks 1000
```

| 1,000 different avatars, a pick | median ms | p95 ms | mean ms | hits of the 1,000 |
|---|---|---|---|---|
| CPU pick anywhere in the view, the first on those avatars (their boxes made) | 0.0102 | 3.2772 | 0.459 | 154 |
| CPU pick anywhere in the view, warm | 0.01 | 0.2213 | 0.0411 | 154 |
| `sona_pick_gpu` anywhere in the view | 0.0214 | 0.5429 | 0.1105 | 156 |
| CPU pick on a random avatar's chest, through the crowd, the first | 0.1625 | 0.6439 | 0.2301 | 1,000 |
| CPU pick on a random avatar's chest, warm | 0.1472 | 0.2633 | 0.1477 | 1,000 |
| `sona_pick_gpu` on a random avatar's chest | 0.6095 | 0.7789 | 0.6091 | 1,000 |

These are one machine's figures, and a slower CPU or GPU gives slower picks; what carries over is the shape: a pick
through 1,000 avatars tests only the few whose spheres the ray meets, and the first pick on an avatar after a build
also makes its boxes. A miss that meets no sphere costs a walk over the avatars' spheres. The picks run outside the
measured window, so the frame is the crowd's own: 16.17 ms a frame with the picks
against 16.15 without (the `crowd` file's `vk` run, the same machine).

## Determinism and agreement

- A CPU pick finds the same avatar, mesh and triangle as a brute-force test of every triangle of every avatar
  (`sona_pose_vertices`), at the same distance to float precision.
- The same picks on a second context built the same way give the same bits.
- A texel with zero alpha is not hit: a ray through a cutout goes on to whatever is behind it.
- The id buffer and the CPU pick agree at every pixel of a view: the same avatar everywhere, and the same mesh but
  for single pixels on a seam between two meshes.
- On sprites, the pixels drawn and the pixels picked agree except at the picture's filtered edge and at the turn
  between two baked pictures.

## Bindings

C#: `SonaPicking` (extension methods `ctx.PickRay`, `ctx.PickScreen`, `ctx.PickRayAll`, `avatar.Pick`,
`renderer.PickGpu`, `renderer.PickGpuIds`, and `SonaPicking.ViewRay`, `RegionName`) returning `SonaPickHit`.
Python: `sona.pick_ray`, `pick_screen`, `pick_ray_all`, `avatar_pick`, `pick_gpu`, `pick_gpu_ids`, `view_ray`,
`region_name`, returning `sona.PickHit`. Rust: `Context::pick_ray`, `pick_screen`, `pick_ray_all`, `Avatar::pick`,
`Renderer::pick_gpu`, `pick_gpu_ids`, `sona::view_ray`, `sona::region_name`, with `PickOptions` and `PickHit`.

## The sample

`samples/c/picking_vk.c` stands seven cast avatars in a row and five far behind them as crowd sprites, gives the third a
basketball and plays its clip, and clicks at a head, a chest, a foot, the ball, a far sprite and the floor. Each click
is picked on the CPU and on the GPU, and each writes a picture: the picked avatar outlined from the id buffer, the item
hit tinted, the point marked and a label naming the avatar, the item (from the catalogue when `--catalogue` is given),
the body part, the joint and the distance. `--check` fails when a click misses its avatar, the CPU and GPU disagree, the
floor is picked, or the held prop is not drawn or its click lands on anything but the prop.

```sh
picking_vk --cast devs-cast.json --catalogue sona-catalogue.bin \
           --prop 00001000-27c1-72c3-c1e9-058c5858081c --out picking --check
```

## Limits

- The alpha test samples level 0; the draw may sample a smaller mip far away, so a texel at the edge of a cutout can
  differ between the picture and the pick.
- A sprite is picked on the avatar's own held pose; when another avatar of the same look baked the sheet in another
  pose, the picture and the pick can differ by that pose.
- In `sona_pick_gpu_ids`, sprite avatars are drawn as meshes, not as their pictures.
- The section from the mask is the editor's rule on the mask alone; the catalogue has the listed one.
