# 3D print export

A posed avatar, or several, as one watertight and manifold solid for a 3D printer, written as STL or as 3MF with a
colour per vertex. No GPU, no network: it runs on the CPU in the calling thread. The calls are C, and C++ makes them as
they are; the C#, Rust and Python bindings make them through their raw layers (`Native.sona_print_avatars`,
`sona_sys::sona_print_avatars`, `sona._native`).

![A 3D print of an avatar in orange plastic on its base](../img/print3d.webp)

## How it works

1. **Pose.** Every part the avatar draws (body, garments, hair, a held prop while its clip plays) is skinned on the CPU
   as the last `sona_update` posed it, with its placement (`SONA_SPACE_WORLD`). Triangles with no area (hidden parts
   scaled to a point) and cut-out triangles (texture alpha under the shaders' 0.5 at the middle and near every corner)
   are left out. To print a clip frame, play the clip from that time, stop it, and update once:

   ```c
   sona_play_options pl = { 0, 1.0f, 1.25f };          /* no loop, speed 1, from 1.25 s */
   sona_avatar_play(a, "GenericWave", &pl);
   sona_update(ctx, 0, NULL, NULL);
   sona_avatar_stop(a);
   sona_update(ctx, 0, NULL, NULL);
   sona_print_avatars(&a, 1, &opts, &print);
   ```

2. **Axes and scale.** Millimetres, Z up, right-handed; an avatar at turn 0 faces -Y (the front view of a slicer). The
   SDK's frame is left-handed, so the axes are swapped (x, z, y), not mirrored. `height_mm` sets the whole figure's
   height, base not counted; `mm_per_metre` sets a fixed scale instead (1:12 is 83.33), so a set of figures matches.

3. **One solid from a distance field.** On a grid of `voxel_mm` spacing, every point within half the minimum wall of a
   triangle is solid. That makes every surface a shell at least `min_wall_mm` thick, so open garments, hair cards and
   single-sided planes print, thin parts reach the minimum wall, and overlapping shells, inner faces and the body under
   the clothes become one solid. Then holes and gaps narrower than about twice `close_mm` are closed: the free space is
   eroded by `close_mm`, flooded from the grid's border, and grown back; whatever the outside never reaches is solid,
   so nothing hollow is sealed inside.

4. **The surface.** The zero set of the field is cut out of the grid's Kuhn tetrahedra (six per cell, sharing the
   cell's diagonal). A field on tetrahedra gives a closed, manifold, consistently wound surface with no crossing
   triangles by construction; `sona_print_check` confirms it for any file.

5. **Base.** With `SONA_PRINT_BASE`, a round (or, with `SONA_PRINT_BASE_SQUARE`, a rounded square) plate of
   `base_height_mm` joins the feet: it covers the footprint of the lowest eighth of the figure plus `base_margin_mm`,
   and is at least 0.4 of the figure's height across (0.34 for the square). It is part of the same field, so it
   unites with the soles, which sink into it by the wall's thickness.

6. **Colour.** Each vertex takes the colour of the nearest point of the triangle it came from, as the HQ shaders
   compute their albedo before lighting: the colour texture times the intensity alpha plus the intensity colour, then
   the decal (not for reflective materials, whose decal slot holds the matcap), times the vertex colour (the baked
   occlusion), in linear light, written back as sRGB. The base takes `base_colour`. A point on a closed hole takes a
   neighbour's colour.

7. **Placement.** The solid stands on z = 0, its bounding box (base included) centred on x = y = 0. An arm
   reaching past the base moves the base off the centre.

What it costs: every surface grows by half the minimum wall (0.6 mm at the default 1.2 mm), so a figure is a little
fatter than the avatar. A partly cut-out card (a jagged fringe) prints whole. Colour is sampled once per vertex, about
every `voxel_mm`: fine for a colour printer, softer than the texture.

## Options

`sona_print_options`, 64 bytes, every field 4 bytes. Start from `sona_print_defaults`, which sets `size`.

| Field | Meaning | Default |
|---|---|---|
| `size` | `sizeof(sona_print_options)` | set |
| `flags` | `SONA_PRINT_BASE`, `_BASE_SQUARE`, `_NO_COLOUR` (every vertex white), `_LARGEST_ONLY` (drop every shell but the largest), `_NO_PROPS` (leave held props out) | 0 |
| `height_mm` | the figure's height, base not counted | 120 |
| `mm_per_metre` | a fixed scale instead; 0: from `height_mm` | 0 |
| `min_wall_mm` | the thinnest wall or part | 1.2 |
| `voxel_mm` | grid spacing; 0: `min_wall_mm / 2.5` | 0 |
| `close_mm` | holes and gaps narrower than about twice this are closed; 0: none | 0.6 |
| `base_height_mm` | plate thickness | 3 |
| `base_margin_mm` | room around the feet | 4 |
| `base_colour` | 0xAARRGGBB | 0xff3c3c3c |
| `max_voxels` | the grid's cap (memory grows with it); past it the grid coarsens, and once a cell is wider than half the wall the wall grows with it (`sona_print_mesh` says what was used) | 24,000,000 |
| `reserved[5]` | zero | 0 |

`SONA_E_ARGUMENT` for a `size` under 64, an unknown flag, a NaN or a value out of range (height 1 to 10,000 mm, wall
0.01 to 100 mm), a base flag with a zero base height, or a non-zero reserved word.

## Functions

### sona_print_avatars

`sona_result sona_print_avatars(sona_avatar *const *avatars, uint32_t count, const sona_print_options *o, sona_print **out)`

One solid from `count` READY avatars of one ctx, in their placements: several avatars side by side are one print
(they become one piece where they touch, separate shells where they do not). NULL `o`: the defaults. Uses the ctx's
allocator; blocks for the field's work.
`SONA_E_NOT_READY` when one is not READY, `SONA_E_ARGUMENT` for NULL arguments, bad options or avatars of two ctxs,
`SONA_E_NOT_FOUND` when nothing drawn has any area, `SONA_E_LIMIT` when even the coarsest grid would not fit
`max_voxels`, `SONA_E_MEMORY`. `sona_last_error` says which.

### sona_print_triangles

`sona_result sona_print_triangles(sona_ctx *ctx, const float *positions, uint32_t vertex_count, const uint32_t *indices, uint32_t triangle_count, const uint32_t *colours, const sona_print_options *o, sona_print **out)`

The same pipeline over any triangles: positions in metres in the SDK's frame (Y up, left-handed), indices three per
triangle in any winding, `colours` 0xAARRGGBB per vertex (NULL: white). `ctx` may be NULL (malloc). For a scene of
your own (an avatar with your props, a diorama). `SONA_E_ARGUMENT` also for an index past `vertex_count` or a NaN.

### sona_print_get

`sona_result sona_print_get(const sona_print *p, sona_print_mesh *out)`

The solid. Set `out->size` first. Pointers live as long as the `sona_print`.

| Field | Meaning |
|---|---|
| `vertex_count`, `triangle_count` | the mesh's vertices and triangles |
| `shells` | separate pieces; 1 when everything touches |
| `volume_mm3`, `area_mm2` | the volume it encloses in cubic millimetres and its surface in square millimetres |
| `positions` | `vertex_count * 3` floats, millimetres |
| `colours` | `vertex_count`, sRGB 0xAARRGGBB |
| `indices` | `triangle_count * 3`, counter-clockwise seen from outside |
| `lo`, `hi` | bounds; `lo[2]` is 0 |
| `mm_per_metre`, `min_wall_mm`, `voxel_mm` | what was used |

96 bytes with 8-byte pointers, 84 with 4-byte ones.

### sona_print_encode

`sona_result sona_print_encode(sona_print *p, uint32_t format, const uint8_t **out, size_t *out_len)`

A file in memory. `SONA_PRINT_STL`: binary STL, little-endian, 84 + 50 bytes a triangle, facet normals out of the
solid. `SONA_PRINT_3MF`: a 3MF package (OPC zip, entries deflated) with the core model in millimetres and the
materials extension's colour group: one colour per vertex, each distinct colour once, referenced from every triangle
corner. The bytes live in `p` until the next `sona_print_encode` on it or `sona_print_free`. The same input gives the
same bytes. `SONA_E_ARGUMENT` for another format.

### sona_print_free

`void sona_print_free(sona_print *p)`. NULL does nothing.

### sona_print_check

`sona_result sona_print_check(const float *positions, uint32_t vertex_count, const uint32_t *indices, uint32_t triangle_count, sona_print_report *out)`

Checks any triangle mesh, in any unit. Pure: no ctx, malloc. Set `out->size` first.

| Field | Meaning |
|---|---|
| `vertices`, `triangles`, `edges` | edges counted once |
| `boundary_edges` | edges with one triangle (holes) |
| `nonmanifold_edges` | edges with more than two |
| `flipped_edges` | edges whose two triangles run the same way along them (inconsistent winding) |
| `nonmanifold_vertices` | vertices whose triangles make more than one fan (two solids touching at a point) |
| `degenerate` | triangles with no area or a repeated corner |
| `self_intersections` | pairs of triangles that cross: an edge of one through the inside of the other, or two coplanar neighbours folded onto each other; tolerances scale with each pair's own size |
| `shells` | connected pieces |
| `euler` | vertices - edges + triangles: 2 per sphere-like shell, 2 - 2g for a shell with g handles |
| `volume_mm3`, `area_mm2`, `lo`, `hi` | volume by the divergence theorem (positive when wound outwards) |
| `ok` | 1 when watertight, manifold, consistently wound, positive volume, no degenerate and no crossing triangles |

Crossings are found by binning the triangles' boxes into a grid and testing each pair once, in the cell that holds the
low corner of where their boxes meet.

## Numbers

The `print3d` sample on one avatar one second into `GenericWave`, with `height_mm` set to 100, on a round base,
defaults otherwise. It ran on one thread of an RTX 4090 machine's CPU; the median of three runs:

| | |
|---|---|
| Time in `sona_print_avatars` (ms of CPU) | 510 |
| Time in `sona_print_check` (ms of CPU) | 621 |
| Solid | 260,866 vertices, 521,756 triangles, one shell, 36,379 mm3 |
| STL (bytes) | 26,087,884 |
| 3MF (bytes) | 10,088,734 |

The same avatar 200 mm tall, defaults otherwise: 2,016,836 triangles in
2,541 ms of CPU. Every one of them passes `sona_print_check`.

The STL and the 3MF open as one watertight, manifold part in manifold3d, trimesh, pymeshlab and PrusaSlicer, and
PrusaSlicer slices them into layers with supports.

## Sample

`samples/c/print3d.c`: one cast avatar (or two with `--pair`) mid-clip, printed, checked, written as STL, 3MF
and a picture of the solid drawn on the CPU. `print3d --check file.stl` runs any STL through `sona_print_check`.

```sh
print3d --cast devs-cast.json --index 0 --clip GenericWave --time 1.0 --height 100 \
        --stl figure.stl --3mf figure.3mf --png figure.png
```

`print_words` checks that no built library holds a vendor name as one string: the 3MF namespace URIs are written from
two pieces at run time, because the package step refuses such a binary.
