# 2D outputs: sprite sheets, stickers and pixel art

Pictures of an avatar for 2D games, chat and pixel-art games, made by the SDK with no art tool in between:

![A walk cycle as a sprite sheet, a row per direction](../img/sprite-sheet.webp)
![A sticker of an avatar, sent in a chat](../img/sticker.webp)
![Pixel art, 32 pixels tall, enlarged, standing in a pixel world](../img/pixel-art.webp)

- **Sprite sheets**: a clip rendered at N frames in M directions, trimmed, padded and packed on pages, with an
  atlas in Aseprite's or TexturePacker's JSON form. Or a plain grid, a row per direction.
- **Stickers**: a transparent, outlined cut-out of the avatar in a pose or an emote's frame.
- **Pixel art**: any picture brought down to a small height with a small palette, every pixel opaque or clear.
  Sheets can be pixel art too, with one palette for every frame.

Everything draws through `sona_snapshot`, the headless path the core already has, so any backend with a readback can
make them. They are tested on Vulkan, GL 3.3 and GLES 3.0.

## Quick start

```c
sona_sheet_options o;
sona_sheet *sheet = NULL;
sona_result r;
sona_sheet_defaults(&o);
o.clip = "00400000-0064-0003-c1c8-f109a19cb2e0";   /* a clip key ("GenericWave") or a clip id */
o.name = "walk";
o.pitch_deg = 30;                                 /* a top-down RPG camera */
while ((r = sona_sheet_render(renderer, avatar, &o, &sheet)) == SONA_PENDING)
  sona_update(ctx, 0, NULL, NULL);                /* the clip's file is loading */
if (r == SONA_OK) {
  sona_picture page;
  char *json;
  size_t len;
  sona_sheet_page(sheet, 0, &page);               /* RGBA8: sona_png_encode it as walk-0.png */
  sona_sheet_atlas(sheet, SONA_ATLAS_ASEPRITE, 0, "walk-{n}.png", &json, &len);
  /* ... write json ... */
  sona_free(ctx, json);
  sona_sheet_free(sheet);
}
```

```cpp
sona_sheet_options o;
sona_sheet *sheet = nullptr;
sona_result res;
sona_sheet_defaults(&o);
o.clip = "00400000-0064-0003-c1c8-f109a19cb2e0";   // a clip key ("GenericWave") or a clip id
o.name = "walk";
o.pitch_deg = 30;                                 // a top-down RPG camera
while ((res = sona_sheet_render(r.raw(), avatar.raw(), &o, &sheet)) == SONA_PENDING)
  ctx.update(0);                                  // the clip's file is loading
if (res == SONA_OK) {
  sona_picture page;
  char *json = nullptr;
  size_t len = 0;
  sona_sheet_page(sheet, 0, &page);               // RGBA8: png_encode it as walk-0.png
  sona_sheet_atlas(sheet, SONA_ATLAS_ASEPRITE, 0, "walk-{n}.png", &json, &len);
  // ... write json ...
  sona_free(ctx.raw(), json);
  sona_sheet_free(sheet);
}
```

```csharp
var o = SonaRenderer.SheetDefaults();
o.pitch_deg = 30;                                // a top-down RPG camera
using var sheet = r.RenderSheet(avatar, o, "00400000-0064-0003-c1c8-f109a19cb2e0", "walk");   // a clip key ("GenericWave") or a clip id
var page = sheet.Page(0);                        // the first page's pixels
```

```rust
let mut o = sheet_defaults();
o.pitch_deg = 30.0;                              // a top-down RPG camera
let clip = "00400000-0064-0003-c1c8-f109a19cb2e0";   // a clip key ("GenericWave") or a clip id
let sheet = loop {
    if let Some(s) = r.sheet(avatar, &o, Some(clip), Some("walk"), None)? {
        break s;                                 // None while the avatar's files are still arriving
    }
};
let (rgba, width, height) = sheet.page(0)?;
```

```python
# The Python package has no renderer on a device of your own: it reads avatars as data (avatar.pose()) for an engine
# to draw, and draws pictures with sona.Headless.
o = sona.sheet_defaults()
```

`samples/c/sprites2d_vk.c` does all three outputs headless on Vulkan and writes the files.

## How a picture is made

1. **The avatar is staged alone.** For the length of the call the avatar is the only visible one, stands at the
   origin, and is posed at each time asked for. Its state is copied first and put back after: placement, clip and
   clip time, pose, fades, clip events, root motion, visibility and its crowd step. The host's clip keeps playing
   from where it was, and the next `sona_update` and `sona_draw` give the same picture they would have given
   without the call (`sprites2d_vk` checks it byte for byte). Joint overrides stay applied. The clip's own face
   track is baked into the pictures (an emote's laugh, a yawn), part by part where the host has not set an
   expression with `sona_avatar_expression`; the face sheet is put back byte for byte after.
2. **The clip is read on its own.** A clip named in the options (a key such as `"GenericWave"`, a raw clip id, or
   `"prop"` for the held prop's clip) is fetched from the ctx's sources without touching the avatar's own clip.
   Until its file has arrived the call returns `SONA_PENDING`: run `sona_update` and call again. A NULL clip
   samples the clip the avatar plays now (sheets), or keeps the pose it has now (stickers).
3. **The camera is fixed for the whole sheet.** Direction 0 faces `first_deg` (0: towards the camera, south;
   90: screen left, west; 180: away; 270: screen right), and the others follow clockwise seen from above, evenly
   round. The avatar turns; the camera and the light do not, so every direction is lit from the same side of the
   screen, as hand-drawn sprites are. The camera looks down by `pitch_deg`: 0 side on, 30 for top-down RPGs,
   26.565 for 2:1 isometric. `fov_deg` 0 is orthographic (a 0.5 degree camera from far away: depth changes the
   scale by a negligible amount). So every frame has the same scale and a feet point that does not move.
4. **The frame box comes from the joints**, every frame at every turn, with room for hands, hair, hats and soles
   (0.25 m at the sides, 0.32 m on top, 0.14 m below). A picture that still touches the edge of its cell (a big
   hat, a held prop, a wide dress) grows that edge by 0.3 m and the sheet is drawn again, up to five times.
   `px_per_metre` sets the scale: at 64 a 1.8 m avatar is about 115 pixels tall, whatever the clip.
5. **Walk cycles stay in place.** The hips are held where the clip starts (root motion EXTRACT for the call), so a
   walk walks on the spot and the game moves the sprite. `SONA_SHEET_ROOT_MOTION` keeps the travel in the
   pictures instead.

Frames are sampled at `from + span * i / frames` (`span` = `to - from`, or the whole clip), which suits a loop: the
last frame is not the first again. `SONA_SHEET_ENDS` samples both ends (`span * i / (frames - 1)`) for clips that
play once. Each frame lasts `span / frames` (or `span / (frames - 1)`) in the atlas, in milliseconds.

## Sprite sheets

- **Trimmed.** Each frame keeps the box of its pixels (alpha above 0) plus `padding` clear pixels round it, inside
  its cell. The atlas records where that box sat in the cell (`spriteSourceSize`) and the cell's size
  (`sourceSize`), so engines draw it at the right place. `SONA_SHEET_NO_TRIM` keeps whole cells.
- **Made unique.** Frames with the same pixels at the same place share one rectangle (a held still pose, the two
  ends of a loop); `sona_sheet_frame.alias` names the first. `SONA_SHEET_NO_DEDUP` turns it off.
- **Packed.** A skyline packer (bottom left, tallest first) fills pages no bigger than `max_page` on a side, trying
  several page widths and keeping the one with the smallest largest side, then the least area: square-ish pages,
  not strips. More pages when one is not enough. `SONA_SHEET_POW2` makes both sides powers of two. Nothing is
  rotated.
- **Grid.** `SONA_SHEET_GRID` lays whole cells in a grid, a row per direction and a column per frame (rows wrap
  at `max_page`; whole directions per page). That is what Godot's `Sprite2D` (`hframes`, `vframes`) and Unity's
  Sprite Editor (Grid By Cell Size) slice without any importer.
- **The pivot** is the avatar's feet, its placement's origin, in the cell: `sona_sheet_frame.pivot_x` and
  `pivot_y`. TexturePacker JSON carries it per frame (`pivot`, as a fraction of the cell); Aseprite JSON as a
  slice named `pivot` with the cell as its bounds.
- **Names.** Frames are `<name>_<direction>_<nnn>` (`walk_west_003`); directions are compass names at multiples
  of 45 degrees (`south`, `southwest`, `west`, ... `southeast`), else `dir<k>`. Each direction is an Aseprite frame
  tag and a TexturePacker animation named `<name>_<direction>`.
- **Pixel-art sheets.** With `pixel` set, cells are drawn at up to eight times the size, brought down with the area filter,
  then cut to opaque or clear and mapped to one palette made from every frame (or `pixel->palette`), with the
  outline if asked. `px_per_metre` is then the pixel art's own scale (18 gives a figure about 32 pixels tall);
  `pixel->height` is not used.

### The atlas formats

`sona_sheet_atlas(sheet, format, page, image, &json, &len)` writes one page's atlas as NUL-terminated UTF-8 JSON,
freed with `sona_free`. `image` is the page's file name for `meta.image`; `{n}` in it becomes the page number.

- `SONA_ATLAS_ASEPRITE`: Aseprite's "array" export: `frames` (filename, frame, rotated, trimmed,
  spriteSourceSize, sourceSize, duration), `meta` with `frameTags` (one per direction, `forward`), one `layers`
  entry and the `pivot` slice: the form Phaser 3's `load.aseprite` and the engine plugins that import Aseprite
  exports are made for.
- `SONA_ATLAS_TEXTUREPACKER`: TexturePacker's "JSON (Hash)": `frames` keyed by name, each with a `pivot`,
  `animations` (name to frame names, the form PixiJS reads), and `meta`. Phaser 3's `load.atlas` and PixiJS's
  `Spritesheet` read it. `page` `SONA_ATLAS_ALL_PAGES` writes every page in one file, in the multi-atlas form
  (`textures`, Phaser 3's `load.multiatlas`).

Both put `"app": "https://360sona.com"` and `"credit": "Powered by 360sona"` in `meta`. Numbers are written without
exponents and without the locale, so a host in any language gets valid JSON.

What has been checked: the core's JSON reader parses every atlas, and the trimmed frames put back at their offsets
rebuild every grid cell byte for byte (`sprites2d_vk`, `sprites2d_gl`). Godot 4.7 reads the sample's atlases with
its own `JSON` and `Image` classes, rebuilds the cells exactly, turns the Aseprite tags into `SpriteFrames`
animations of `AtlasTexture`s whose margins keep the full cell (`sprites2d_godot`). Phaser, PixiJS, Unity and
Aseprite themselves have not been run against these files.

## Stickers

`sona_sticker(renderer, avatar, &options, &picture)` draws the avatar alone, turned `turn_deg` from facing the
camera, at `time` seconds into `clip` (negative: its middle), framed by `framing`:

- `SONA_PRESET_FULL`: the whole figure, from the joints' box, grown until nothing touches the frame.
- `SONA_PRESET_UPPER`, `_BUST`, `_FACE`: the console's own framings (`sona_camera_preset`), cut at the frame's
  edge, for reaction and emote stickers ("Laugh", "ShockedSurprised").

It is drawn at twice the size, cut to its pixels, brought down with the area filter so the longer side is `pixels`
less the outline, and then given an outline `outline_px` wide (a true distance from the figure's edge, smooth at
any width; default white, 10 pixels), an optional hard drop shadow `shadow_px` down and right, `padding` clear
pixels round it, and with `SONA_STICKER_SQUARE` a square canvas. The canvas is `pixels + 2 * padding + shadow`
on its longer side. The picture is the caller's: `sona_free(ctx, picture.rgba)`.

The credit badge is stamped bottom right at three quarters of its size, unless `draw_flags` has `SONA_DRAW_NO_CREDIT` (the app then shows
the credit itself, as the licence requires). A sticker too small for the badge gets none and a warning in the log.

## Pixel art

`sona_pixel_art(ctx, &in, &options, &out)` works on any picture: a sticker cut-out (use `outline_px` 0 and
`SONA_DRAW_NO_CREDIT`), a snapshot, an item preview.

1. The figure's box (pixels with alpha 8 and up; `SONA_PIXEL_KEEP_FRAME`: the whole picture) is scaled to
   `height` pixels, less two for the outline, with an area filter: each output pixel is the coverage-weighted
   mean of the input it covers. No blur beyond that.
2. Each pixel becomes opaque or clear at `alpha_cut` (0.5): no half-transparent pixels.
3. Colours are mapped to the palette: `palette` (0xRRGGBB) when given, else `colours` colours made from the picture
   by median cut on a 15-bit histogram and six rounds of k-means, all in integers, darkest first. Distances weigh
   red, green and blue 3 : 4 : 2. `SONA_PIXEL_DITHER` adds an ordered 4 x 4 pattern first.
4. `SONA_PIXEL_OUTLINE` (on by default) paints the clear pixels next to the figure in `outline`, or, when its alpha
   is 0, the palette's darkest colour a third darker. `SONA_PIXEL_OUTLINE_THIN` uses the four side neighbours
   only.

The result is exactly `height` pixels tall. `sona_pixel_palette(ctx, pictures, n, colours, palette, &count)` makes
one palette for several pictures, to pass as `palette` so a character's frames and poses share colours (a
pixel-art sheet does this by itself).

Palettes and mapping are integer maths; the area filter and the outline distance are IEEE doubles and floats with
contraction off, so the same picture comes out on x86-64, arm64 and big-endian PowerPC.

## Types

### sona_sheet_options

| Field | Meaning | Default |
|---|---|---|
| `size` | `sizeof(sona_sheet_options)`; calls refuse a struct without it | set |
| `frames` | frames per direction, 1..1024 | 8 |
| `clip` | a clip key, a raw clip id or `"prop"`; NULL: the clip the avatar plays now | NULL |
| `name` | the animation's name in the atlas (up to 63 bytes); NULL: the clip as named, `"pose"` without one | NULL |
| `from`, `to` | seconds into the clip; `to <= from`: all of it | 0, 0 |
| `directions` | 1..64 | 8 |
| `first_deg` | direction 0's facing | 0 |
| `pitch_deg` | camera elevation, -45..89 | 0 |
| `fov_deg` | 0: orthographic; else 1..90 | 0 |
| `px_per_metre` | 2..1024 | 64 |
| `padding` | clear pixels round each trimmed frame, 0..64 | 2 |
| `max_page` | the largest page side, 64..16384 | 4096 |
| `flags` | `SONA_SHEET_POW2`, `_NO_TRIM`, `_ROOT_MOTION`, `_NO_DEDUP`, `_ENDS`, `_GRID` | 0 |
| `draw_flags` | `SONA_DRAW_*` for the pictures; `NO_CREDIT` is always added | `SONA_DRAW_NO_BLOOM` |
| `reserved` | 0 | 0 |
| `pixel` | not NULL: pixel-art frames | NULL |

80 bytes with 8-byte pointers, 68 with 4-byte ones.

### sona_sheet_frame

`page`, `x`, `y`, `w`, `h` (the rectangle on the page), `trim_x`, `trim_y` (where it sits in the cell), `cell_w`,
`cell_h` (the same for every frame), `pivot_x`, `pivot_y` (pixels in the cell), `direction`, `frame`,
`facing_deg`, `time` (seconds into the clip), `duration_ms`, `alias`. 68 bytes. Frames are direction-major:
index = direction * frames + frame.

### sona_sticker_options

| Field | Meaning | Default |
|---|---|---|
| `size` | `sizeof(sona_sticker_options)` | set |
| `pixels` | the cut-out's longer side, outline included, 32..4096 | 512 |
| `clip`, `time` | the pose: a clip and seconds into it (negative: its middle); NULL clip: the pose it has now | NULL, -1 |
| `turn_deg` | the avatar's turn from facing the camera | 0 |
| `framing` | `SONA_PRESET_FULL`, `_UPPER`, `_BUST`, `_FACE` | FULL |
| `outline_px`, `outline` | outline width (0..128; 0: none) and 0xAARRGGBB | 10, `0xffffffff` |
| `shadow_px`, `shadow` | drop shadow offset (0..128; 0: none) and 0xAARRGGBB | 0, `0x59000000` |
| `padding` | clear pixels round it, 0..1024 | 8 |
| `flags` | `SONA_STICKER_SQUARE` | 0 |
| `draw_flags` | `SONA_DRAW_*`; `NO_CREDIT`: no badge | 0 |

56 bytes with 8-byte pointers, 52 with 4-byte ones.

### sona_pixel_options

| Field | Meaning | Default |
|---|---|---|
| `size` | `sizeof(sona_pixel_options)` | set |
| `height` | the output's height, outline included, 4..1024 | 32 |
| `colours` | palette size made from the picture, 2..256 | 16 |
| `flags` | `SONA_PIXEL_OUTLINE`, `_OUTLINE_THIN`, `_DITHER`, `_KEEP_FRAME` | OUTLINE |
| `outline` | 0xAARRGGBB; alpha 0: from the palette | 0 |
| `alpha_cut` | 0.01..1 | 0.5 |
| `palette`, `palette_count` | 0xRRGGBB colours to map onto (1..256), or NULL | NULL, 0 |
| `reserved` | 0 | 0 |

40 bytes with 8-byte pointers, 36 with 4-byte ones.

### sona_picture

`rgba` (straight RGBA8, row 0 at the top), `width`, `height`. Pictures from `sona_sticker` and `sona_pixel_art`
are the caller's (`sona_free(ctx, p.rgba)`); pages from `sona_sheet_page` belong to the sheet.

## Rules

- One owner thread, as every call on a ctx. A sheet or a sticker is many `sona_snapshot` frames: each blocks until
  the GPU is done, and on Vulkan submits on the device's queue (keep other threads off it during the call). When
  no frame of the host's was in flight when the call began, the call reports its own frames done before it
  returns; otherwise report them with `sona_renderer_frame_done` as for any snapshot.
- `SONA_E_NOT_READY` before the avatar is READY; `SONA_E_ARGUMENT` for an item preview (draw those with
  `sona_item_preview_snapshot`), a renderer of another ctx, options without their `size`, a value out of range or
  an unknown clip key; `SONA_E_NOT_FOUND` for a clip whose file cannot be read, a sticker of nothing, or pixel art
  with no pixel opaque enough; `SONA_E_LIMIT` when a frame cannot fit `max_page`, a cell would need a render over
  8192 pixels, or the cells would pass the 1 GB limit. A sheet frame that drew nothing gets a 1 x 1 clear rectangle.
- Free every sheet with `sona_sheet_free` before `sona_close`.
- The bench path is untouched: nothing here runs inside `sona_update` or `sona_draw`.

## Numbers

The sample, one avatar, WalkForward, 8 directions of 8 frames, `pitch_deg` 30. It ran on an RTX 4090 machine,
Vulkan; the median of three runs:

| `sprites2d_vk` | ms to draw |
|---|---|
| The packed sheet, 80 px per metre | 32 |
| The grid, a row per direction | 10 |
| The pixel-art sheet, 24 px per metre | 31 |

Not counted: the clip's first load.

## Tests and sample

| Name | What |
|---|---|
| `sprites2d` | no GPU: options and their checks, the area filter against block means, the outline's distances, palettes (exact colours, darkest first), posterising, pixel art from a made-up figure, the packer (no overlaps, pages within bounds, powers of two, several pages, a too-big frame refused) |
| `sprites2d_vk`, `sprites2d_gl` | on every Vulkan and GL test device: a sheet of a cast avatar's wave (32 frames, every one drawn, pivots inside the cell, both atlases parsed), the avatar afterwards (the same snapshot byte for byte, no new clip events, the same joint, still playing), the same bytes twice, the grid's layout, the packed frames rebuilding the grid's cells; stickers (size, outline, clear corners, a square face sticker); pixel art from a cut-out; a pixel-art sheet (opaque or clear, one palette, powers of two). PNGs as `sprites2d-<device>-*.png` |
| `sprites2d_sample_vk` | `samples/c/sprites2d_vk.c` over the full corpus: the 8-direction walk (packed and grid), the pixel-art walk, a sticker and a 32 px avatar; fails when a frame is empty |
| `sprites2d_godot` | Godot 4 reads the sample's atlases (`samples/sprites2d/godot_atlas_check.gd`) |

The first three also pass under ASan and UBSan, built and preloaded as the CI's `asan` step does.
