# Crowds: level of detail and sprites

Level of detail (LOD) is how the core draws thousands of different avatars in one frame: it does less for the
avatars that are small on screen. It is off until you call `sona_lod_set`.

![10,000 avatars of 55 costumes in one frame, the far ones drawn as sprites](../img/crowd-10000.webp)
![1,000 avatars of 55 costumes, each turned and timed differently](../img/crowd-1000.webp)

- Avatars near the camera are posed and drawn exactly as without it.
- Avatars further away are posed less often.
- Far avatars become **sprites**: a picture of the avatar, baked once per look and turn, drawn as one flat
  textured quad that faces the camera. A sprite is not posed at all.

Avatars cross between a mesh and a sprite over a short crossfade, so nothing pops.

The public API is five functions and two structs ([C reference: crowds](../reference.md#crowds-level-of-detail-and-sprites)).

## Quick start

```c
sona_ctx *ctx;
sona_config cfg;
sona_config_defaults(&cfg);
cfg.max_avatars = 10000;                 /* up to 16384 */
/* ... sources and licence as usual ... */
if (sona_open(&cfg, &ctx) != SONA_OK) return 1;
sona_lod_set(ctx, NULL);                 /* LOD and sprites on, with the defaults */

/* ... add avatars, create a renderer ... */

for (;;) {
  sona_lod_stats st;
  sona_update(ctx, dt, &view, NULL);     /* gives each avatar its step */
  sona_draw(renderer, &view, &target, NULL);   /* bakes new looks, draws meshes and sprites */
  sona_lod_stats_get(ctx, &st);          /* st.sprite avatars were sprites this frame */
}
```

```cpp
sona::Config cfg;
cfg.max_avatars(10000);                    // up to 16384; sources and licence as usual
sona::Context ctx(cfg);
ctx.set_lod(nullptr);                      // LOD and sprites on, with the defaults

// ... add avatars, create a renderer ...

for (;;) {
  ctx.update(dt, &view);                   // gives each avatar its step
  r.draw(view, target);                    // bakes new looks, draws meshes and sprites
  sona_lod_stats st = ctx.lod_stats();     // st.sprite avatars were sprites this frame
  (void)st;
}
```

```csharp
using var ctx = new SonaContext(new SonaOptions { MaxAvatars = 10000 });   // up to 16384; sources and licence as usual
ctx.SetLod();                                  // LOD and sprites on, with the defaults

// ... add avatars, create a renderer ...

for (;;)
{
    ctx.Update(dt, view);                      // gives each avatar its step
    r.Draw(view, target);                      // bakes new looks, draws meshes and sprites
    var st = ctx.LodStats();                   // st.sprite avatars were sprites this frame
}
```

```rust
let cfg = Config::new().max_avatars(10000);   // up to 16384; sources and licence as usual
let ctx = Context::open(cfg)?;
ctx.set_lod(None)?;                           // LOD and sprites on, with the defaults

// ... add avatars, create a renderer ...

loop {
    ctx.frame()?.update(dt, Some(view))?;     // gives each avatar its step
    unsafe { r.draw(view, target, None)? };   // bakes new looks, draws meshes and sprites
    let st = ctx.lod_stats();                 // st.sprite avatars were sprites this frame
}
```

```python
with sona.Context(max_avatars=10000) as ctx:   # up to 16384; sources and licence as usual
    ctx.set_lod()                                # LOD and sprites on, with the defaults
    # ... add avatars ...
    while True:
        ctx.update(dt)                           # gives each avatar its step
        st = ctx.lod_stats()                     # st["sprite"] avatars were sprites this frame
```

That is all a host needs. `sona_draw` and `sona_snapshot` bake sprites on their own; there is no extra call.

## On the web

The web SDK draws a crowd in one canvas and one context: every item is decoded and uploaded once and shared by every
avatar that wears it, and new avatars are built a few milliseconds at a time between frames. A staggered grid
of the manifests, each idling on its own clock:

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

const canvas = document.querySelector('canvas');
const sona = await SonaRenderer.create({ canvas });
manifests.forEach((m, i) => {
  const row = Math.floor(i / 4), col = (i % 4) - 1.5 + (row % 2) * 0.5;   // odd rows half a step over
  sona.add(m, { position: [col * 0.9, 0, -row * 0.9], clip: 'idle', startAt: 'random' });
});
sona.camera.preset('crowd');
```
The web SDK takes 256 avatars by default and 1,024 at most (`maxAvatars`); the native SDK's level of detail below is
for thousands.

## The steps

Each `sona_update` with a view gives every avatar in view a step from its height on screen in pixels
(`1.8 m * scale` projected at the avatar's depth):

| Step | When | Posed, and drawn as |
|---|---|---|
| `SONA_LOD_FULL` | height `>= full_px` | every frame; its meshes |
| `SONA_LOD_SAMPLED` | `quarter_px <=` height `< full_px` | when the clip reaches a new frame; its meshes |
| `SONA_LOD_QUARTER` | height `< quarter_px` | as SAMPLED, and at most every 4th frame; its meshes |
| `SONA_LOD_SPRITE` | height `< sprite_px` and its look is baked | never; one sprite |

FULL, SAMPLED and QUARTER apply with sprites on or off; `sona_lod_set` sets their two thresholds. An avatar becomes a sprite
below `sprite_px` and turns back into a mesh above `sprite_px * 1.15`, so one standing on the line does not
flicker. With no view (`sona_update(ctx, dt, NULL, NULL)`) every avatar is FULL.

## The options

```c
typedef struct sona_lod_options {
  float full_px;          /* default 120 */
  float quarter_px;       /* default 40 */
  float sprite_px;        /* default 48; 0: never a sprite */
  float fade_seconds;     /* default 0.25; 0: a cut */
  uint32_t sprite_angles; /* default 8 */
  uint32_t sprite_height; /* default 64 */
  uint32_t max_looks;     /* default 16384 */
  float bake_ms;          /* default 4 */
} sona_lod_options;
```

| Field | Unit and range | Meaning |
|---|---|---|
| `full_px` | pixels, `>= quarter_px` | At or above it an avatar is posed every frame |
| `quarter_px` | pixels, `0 .. full_px` | Below it an avatar is posed at most every 4th frame |
| `sprite_px` | pixels, `>= 0` | Below it an avatar becomes a sprite. 0 turns sprites off |
| `fade_seconds` | seconds, `0 .. 10` | How long a mesh-to-sprite crossfade takes, and a turn-to-turn one |
| `sprite_angles` | pictures, `4 .. 32` | Turns baked per look, evenly round the avatar |
| `sprite_height` | pixels, `32 .. 512` | Height of one baked picture, an even number; its width is half of it |
| `max_looks` | looks, `1 .. 65536` | Baked looks kept per renderer. Avatars past it stay meshes |
| `bake_ms` | milliseconds, `>= 0` | Baking time allowed per `sona_draw`. At least one batch of looks is baked each draw that needs one |

> **Note:** `sprite_angles * sprite_height / 2` must be 4096 or less (one sheet is that many pixels wide).

**A new ctx** has thresholds 120 and 40 and `sprite_px` 0: no sprites until `sona_lod_set`.

### `void sona_lod_defaults(sona_lod_options *o)`

Writes the defaults in the table above (sprites on at 48 px). `NULL` is ignored.

### `sona_result sona_lod_set(sona_ctx *ctx, const sona_lod_options *o)`

Sets the options. `NULL` sets the defaults. Takes effect at the next `sona_update`.

- `SONA_E_ARGUMENT`: `ctx` is NULL, or a value is out of range (also NaN). Nothing changes.
- `SONA_E_ARGUMENT` also when `sprite_px` is above 0 and a renderer already on the ctx cannot bake these options
  (see **The bake target** below). Nothing changes then either.
- `SONA_E_MEMORY`: the allocator failed (first call only).
- Changing `sprite_angles` or `sprite_height` drops every baked sheet; they are baked again as they are needed.

### `sona_result sona_lod_get(const sona_ctx *ctx, sona_lod_options *out)`

Copies the current options. `SONA_E_ARGUMENT` for a NULL argument.

### `uint32_t sona_avatar_lod(const sona_avatar *a, float *fade)`

The avatar's step at the last `sona_update`, and in `*fade` how far it is from its mesh (0) to its sprite (1).
`SONA_LOD_FULL` and 0 for NULL, an avatar that is not READY, or one that was not in view at that update (culled
by the view, or hidden). An avatar that comes back into view has its step again: a sprite that was culled is a
sprite again at once, with no new crossfade. `fade` may be NULL.

### `void sona_lod_stats_get(const sona_ctx *ctx, sona_lod_stats *out)`

```c
typedef struct sona_lod_stats {
  uint32_t full, sampled, quarter, sprite;   /* avatars in view per step at the last sona_update */
  uint32_t fading;                           /* of those, crossing between a mesh and a sprite */
  uint32_t looks;                            /* baked looks, over every renderer */
  uint32_t bakes;                            /* looks baked by the last sona_draw or sona_snapshot */
  float bake_ms;                             /* time those bakes took */
} sona_lod_stats;
```

All zero before the first `sona_lod_set`. NULL arguments are ignored.

**Threads**: all five functions belong to the ctx's owner thread, like every other ctx call.
`sona_lod_defaults` touches no ctx and is safe anywhere.

## Sprites

**A look** is the avatar's manifest: avatars with the same 1000 bytes share one sheet, whatever their scale,
place or clip. **A sheet** holds `sprite_angles` pictures side by side, each `sprite_height / 2` by
`sprite_height` pixels, of the avatar turned by `360 / sprite_angles` degrees each. Each picture sits in a gutter of
`sprite_height / 16` pixels on every side, which takes whatever spills out of the baked box (the sprite never shows
it). With the defaults a sheet is 320 x 72 pixels of four bytes, so its GPU memory is a fixed 92,160 bytes.

**Atlas pages.** Sheets live in atlas pages, sRGB textures of up to 2,048 x 2,048 (less on a device whose textures
are smaller), in columns: 168 sheets to a page with the defaults (a default page of 1,920 x 2,016 pixels). A page is made when the
last one is full and released when its last sheet goes. At the default page size 10,000 different looks take 60 pages (the default is 15.5 MB a page). `sona_stats.gpu_mb` counts the pages with the GPU caches.

**Baking.** The first `sona_draw` (or `sona_snapshot`) in which an avatar wants a sprite and its look has no
sheet bakes it: the core renders up to 32 looks, all turns, in one pass laid out exactly as their slots in the
page, without the shadow pass (every cell shares one light view, so a shadow map would mix them). `sona_draw`
records that pass into the host's frame ahead of the picture, presented straight into the page: no readback and
no wait (on GL a framebuffer blit, or a copy through the CPU where the context cannot turn sRGB writes off).
Such a draw uses two frame indices (the pass and the picture), so it counts twice against `frames_in_flight`. `sona_snapshot` bakes through the backend's readback and a region
upload, the same pixels byte for byte. A draw bakes one pass; a pass that is not full waits up to 6 draws for
more looks, so a crowd that becomes ready a few avatars a frame bakes in passes of many looks. Sheets nobody used
in the last few draws make room when `max_looks` is reached, and a pass then takes a run of the slots they gave
back in one column of a page. `sona_lod_stats.bakes` and `bake_ms` say which draws
baked and what it cost them on the CPU.

**The queue (Vulkan).** `sona_draw` on Vulkan only records into the host's command buffer, bakes included; it never
submits. `sona_snapshot` submits and waits on the `VkQueue` from `sona_device_desc`, as it always has: keep other
threads off that queue while it runs.

**The bake target.** One pass is one column of sheets: a sheet wide (`sprite_angles * (sprite_height / 2 + 2 *
(sprite_height / 16))` pixels) and a sheet tall (`sprite_height + 2 * (sprite_height / 16)`) per look, up to 32
looks. With the defaults that is 320 x 2,304 pixels at most. It must fit the device's largest texture:

- `sona_lod_set` refuses options whose one-look bake is wider or taller than the largest texture of a renderer
  already on the ctx (`SONA_E_ARGUMENT`). The widest bake the ranges allow is 5,120 pixels (32 angles at 256 px).
- A device that fits a sheet but not 32 bakes fewer looks per pass.
- A renderer made after `sona_lod_set` on a device too small for the options draws no sprites. It logs a warning
  once, and its avatars stay meshes (see the next point).

**More than one renderer.** Sheets belong to a renderer, but the crossfade belongs to the avatar. So an avatar turns
into a sprite only when every renderer that drew it since the last `sona_update` has its look baked. While a
renderer that cannot draw sprites draws the same ctx (a Metal or Xenos one next to a Vulkan one, or a device too small for
the bake), far avatars stay meshes, posed at the QUARTER rate, on every renderer. When it stops drawing, sprites
come back over `fade_seconds`. Each draw still shows a mesh wherever its own renderer has no sheet, so no renderer
loses an avatar.

The picture is the avatar as the baking avatar was posed at that moment, seen from the depth where sprites
start for that draw's view (the shading reads view-space depth: past about 18 m the shadow lookup leaves
avatars half lit, and a sheet baked there matches them).

**Drawing.** All sprites of one page go in instanced draws of up to 110 (one cb block each), after the opaque
meshes; each sprite names its slot in the page. Each sprite faces the camera, scaled with the avatar, centred
0.9 m up. It shows the turn nearest to the angle the camera sees the avatar from; when that changes by more than 0.65 of a step, the new picture crossfades in over
`fade_seconds` with an ordered dither.

**The crossfade.** Between mesh and sprite both are drawn for `fade_seconds`: the sprite, pulled toward the camera
along the view ray (so it covers the same pixels), takes over a growing share of a 4x4 dither pattern. In the
pixels it has taken, its transparent texels still write depth, so the mesh, drawn after it, gives those pixels up
too: the silhouette crosses over with the inside, and no frame of the crossfade is a visible cut.

### What a sprite does not show

- **Motion.** A sprite holds the baking avatar's pose. Its clip clock still runs (clip time, queue, crossfades,
  root motion `APPLY` all go on), so it is posed correctly the moment it turns back into a mesh.
- **Per-avatar changes on the same manifest.** Expressions set with `sona_avatar_expression` and pose
  overrides do not reach the sprite.
- **A held prop's own clip.** Props drawn only while performing are not in the picture.
- **Clip events from the pose.** Footfalls come from the evaluated pose, so a sprite has none (as a culled
  avatar has none). Started, looped, ended and mark events still arrive.
- **Joints.** `sona_joint_world`, `sona_avatar_capsule` and `sona_pose` give the last pose computed before the
  avatar became a sprite.
- Very wide items: the baked box is 1.1 m wide and 2.2 m tall (from 0.2 m below the feet). Anything outside it
  is cut off in the sprite: up to 0.27 m past a side, the top or the bottom it lands in the gutters between
  pictures; further out it can show at the edge of the neighbouring picture.

### Backends

| Backend | Sprites |
|---|---|
| Vulkan | Yes |
| GL 3.3, GLES 3.0 | Yes |
| D3D11, D3D12 | Yes, baked in the avatar's style. On D3D12 `sona_draw` records the bake on the backend's own list and submits it ahead of the host's |
| Metal, Xenos | No: their caps report no sprites, so far avatars stay meshes at the QUARTER rate |

## Example: a stadium

```c
/* 10,000 avatars in rows round a pitch, facing in */
sona_lod_set(ctx, NULL);
for (i = 0; i < 10000; i++) {
  sona_add_options o;
  sona_add_defaults(&o);
  seat(i, o.place.position, &o.place.turn_deg);   /* your layout */
  o.start_at = -1;                                 /* random start: a crowd out of step */
  sona_avatar_add_base64(ctx, looks[i % 12], &o, &av[i]);
}
```

```cpp
// 10,000 avatars in rows round a pitch, facing in
sona_lod_set(ctx.raw(), nullptr);   // sona.hpp has no wrapper: the C call on the handle
std::vector<sona::Avatar> crowd;
for (uint32_t k = 0; k < 10000; k++) {
  sona_add_options o = sona::add_defaults();
  o.place.position[0] = (float)(k % 100) - 50; o.place.position[2] = (float)(k / 100);   // your layout
  o.start_at = -1;                                   // random start: a crowd out of step
  crowd.push_back(ctx.add_base64(std::string(b64), o));
}
```

```csharp
// 10,000 avatars in rows round a pitch, facing in
ctx.SetLod();
var crowd = new List<SonaAvatar>();
for (var k = 0; k < 10000; k++)
    crowd.Add(ctx.Add(manifest, new SonaAddOptions {
        Placement = new SonaPlacement(k % 100 - 50, 0, k / 100),   // your layout
        StartAt = -1,                                                // random start: a crowd out of step
    }));
```

```rust
// 10,000 avatars in rows round a pitch, facing in
ctx.set_lod(None)?;
let mut crowd = Vec::new();
for k in 0..10000u32 {
    let mut o = AddOptions::default();
    o.place.position = [(k % 100) as f32 - 50.0, 0.0, (k / 100) as f32];   // your layout
    o.start_at = -1.0;                                                     // random start: a crowd out of step
    crowd.push(ctx.add(manifest, &o)?);
}
```

```python
# 10,000 avatars in rows round a pitch, facing in
ctx.set_lod()
crowd = [ctx.add(manifest, position=(k % 100 - 50, 0, k // 100),   # your layout
                 start_at=-1)                                      # random start: a crowd out of step
         for k in range(10000)]
```

`sona-bench --scene crowd --layout stadium --lod on` runs this layout (rows 0.62 m apart round a 72 x 48 m
pitch, the camera behind one end) and `--shot <prefix>` writes a full-size PNG per step.

## Measured

Every figure here is filled in from a `sona-bench` run's own output. The scene: every avatar in its own random
outfit and body from the full catalogue, 1920 x 1080, the median of three runs.

| 1,000 different avatars, grid | ms a frame (CPU, GPU) | Draws a frame; all ready after |
|---|---|---|
| RTX 4000 Ada machine, Vulkan | 1.79 (1.77, 1.59) | 9,470; 3,318 ms |
| Intel Arc iGPU (Core Ultra 9 185H), Vulkan | 14.05 (3.38, 13.98) | 9,470; 2,422 ms |
| RTX 4090 machine, Vulkan | 16.15 (3.48, 16.13) | 9,470; 2,380 ms |
| The same machine, GL | 33.53 (33.5, 33.52) | 9,470; 2,695 ms |

The RTX 4000 Ada and RTX 4090 rows are different machines, and the host as well as the card sets the figure. The GL
row is the same frame through the GL backend on the RTX 4090 machine.

The stadium, 10,000 different avatars with LOD (`--layout stadium --lod on --max-looks 10000`), the median of three runs:

| 10,000 different avatars, stadium | ms a frame (CPU, GPU) | Draws; ready after; memory |
|---|---|---|
| RTX 4000 Ada machine | 7.56 (7.5, 2.87) | 5,831 draws; 21,063 ms; CPU 6,973.9 MB, GPU 1,524.6 MB |
| Intel Arc iGPU (Core Ultra 9 185H) | 11.46 (7.84, 11.37) | 5,831 draws; 14,939 ms; CPU 6,876.7 MB, GPU 1,524.6 MB |

LOD is what makes the stadium possible: the far avatars are drawn as sprites from atlas pages, so the stadium's
10,000 take fewer draws than the grid's 1,000 (the Draws column). Every avatar still holds its own build, which is
the CPU MB column.

A new avatar from bytes already in memory and from a cold read, CPU only, twelve avatars, on the Core Ultra 9 185H:

| Cache | Median ready (ms) | Slowest ready (ms) |
|---|---|---|
| Warm | 25.77 | 28.42 |
| Cold | 26.11 | 31.78 |

To measure on your own machine, run `sona-bench` from your download: [performance](../performance.md#measure-it-yourself).

## Limits

- A sprite draw holds at most 110 sprites (one 3,584-byte cb block).
- `max_looks` is a set count (default 16,384), not read from the device's memory. On a small device an app with
  thousands of looks can ask for hundreds of MB of pages; a page that cannot be made leaves those avatars as meshes.
  Set `max_looks` lower on such devices.
- Avatars between `sprite_px` and `full_px` draw as meshes, simplified to about half their triangles below 120
  pixels ([hardening](hardening.md)); they are where most of the GPU time goes.
- Metal and Xenos have no sprites: their far avatars stay meshes, posed at the QUARTER rate.
- A sprite is a still picture: a far avatar does not animate.
- Every avatar holds its own build (the CPU MB column above), even when many share a look.
- The per-avatar work in `sona_update` (clock, culling, LOD) runs on the owner thread for every avatar.
